builtin_json_test.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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 BenchmarkJSONStringify(b *testing.B) {
  46. b.StopTimer()
  47. vm := New()
  48. var createObj func(level int) *Object
  49. createObj = func(level int) *Object {
  50. o := vm.NewObject()
  51. o.Set("field1", "test")
  52. o.Set("field2", 42)
  53. if level > 0 {
  54. level--
  55. o.Set("obj1", createObj(level))
  56. o.Set("obj2", createObj(level))
  57. }
  58. return o
  59. }
  60. o := createObj(3)
  61. json := vm.Get("JSON").(*Object)
  62. stringify, _ := AssertFunction(json.Get("stringify"))
  63. b.StartTimer()
  64. for i := 0; i < b.N; i++ {
  65. stringify(nil, o)
  66. }
  67. }