builtin_json_test.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package goja
  2. import (
  3. "encoding/json"
  4. "strings"
  5. "testing"
  6. "time"
  7. )
  8. func TestJSONMarshalObject(t *testing.T) {
  9. vm := New()
  10. o := vm.NewObject()
  11. o.Set("test", 42)
  12. o.Set("testfunc", vm.Get("Error"))
  13. b, err := json.Marshal(o)
  14. if err != nil {
  15. t.Fatal(err)
  16. }
  17. if string(b) != `{"test":42}` {
  18. t.Fatalf("Unexpected value: %s", b)
  19. }
  20. }
  21. func TestJSONMarshalGoDate(t *testing.T) {
  22. vm := New()
  23. o := vm.NewObject()
  24. o.Set("test", time.Unix(86400, 0).UTC())
  25. b, err := json.Marshal(o)
  26. if err != nil {
  27. t.Fatal(err)
  28. }
  29. if string(b) != `{"test":"1970-01-02T00:00:00Z"}` {
  30. t.Fatalf("Unexpected value: %s", b)
  31. }
  32. }
  33. func TestJSONMarshalObjectCircular(t *testing.T) {
  34. vm := New()
  35. o := vm.NewObject()
  36. o.Set("o", o)
  37. _, err := json.Marshal(o)
  38. if err == nil {
  39. t.Fatal("Expected error")
  40. }
  41. if !strings.HasSuffix(err.Error(), "Converting circular structure to JSON") {
  42. t.Fatalf("Unexpected error: %v", err)
  43. }
  44. }
  45. func TestJSONParseReviver(t *testing.T) {
  46. // example from
  47. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
  48. const SCRIPT = `
  49. JSON.parse('{"p": 5}', function(key, value) {
  50. return typeof value === 'number'
  51. ? value * 2 // return value * 2 for numbers
  52. : value // return everything else unchanged
  53. })["p"]
  54. `
  55. testScript1(SCRIPT, intToValue(10), t)
  56. }
  57. func BenchmarkJSONStringify(b *testing.B) {
  58. b.StopTimer()
  59. vm := New()
  60. var createObj func(level int) *Object
  61. createObj = func(level int) *Object {
  62. o := vm.NewObject()
  63. o.Set("field1", "test")
  64. o.Set("field2", 42)
  65. if level > 0 {
  66. level--
  67. o.Set("obj1", createObj(level))
  68. o.Set("obj2", createObj(level))
  69. }
  70. return o
  71. }
  72. o := createObj(3)
  73. json := vm.Get("JSON").(*Object)
  74. stringify, _ := AssertFunction(json.Get("stringify"))
  75. b.StartTimer()
  76. for i := 0; i < b.N; i++ {
  77. stringify(nil, o)
  78. }
  79. }