builtin_json_test.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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 TestQuoteMalformedSurrogatePair(t *testing.T) {
  58. testScript1(`JSON.stringify("\uD800")`, asciiString(`"\ud800"`), t)
  59. }
  60. func BenchmarkJSONStringify(b *testing.B) {
  61. b.StopTimer()
  62. vm := New()
  63. var createObj func(level int) *Object
  64. createObj = func(level int) *Object {
  65. o := vm.NewObject()
  66. o.Set("field1", "test")
  67. o.Set("field2", 42)
  68. if level > 0 {
  69. level--
  70. o.Set("obj1", createObj(level))
  71. o.Set("obj2", createObj(level))
  72. }
  73. return o
  74. }
  75. o := createObj(3)
  76. json := vm.Get("JSON").(*Object)
  77. stringify, _ := AssertFunction(json.Get("stringify"))
  78. b.StartTimer()
  79. for i := 0; i < b.N; i++ {
  80. stringify(nil, o)
  81. }
  82. }