builtin_json_test.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package goja
  2. import (
  3. "encoding/json"
  4. "strings"
  5. "testing"
  6. )
  7. func TestJSONMarshalObject(t *testing.T) {
  8. vm := New()
  9. o := vm.NewObject()
  10. o.Set("test", 42)
  11. o.Set("testfunc", vm.Get("Error"))
  12. b, err := json.Marshal(o)
  13. if err != nil {
  14. t.Fatal(err)
  15. }
  16. if string(b) != `{"test":42}` {
  17. t.Fatalf("Unexpected value: %s", b)
  18. }
  19. }
  20. func TestJSONMarshalObjectCircular(t *testing.T) {
  21. vm := New()
  22. o := vm.NewObject()
  23. o.Set("o", o)
  24. _, err := json.Marshal(o)
  25. if err == nil {
  26. t.Fatal("Expected error")
  27. }
  28. if !strings.HasSuffix(err.Error(), "Converting circular structure to JSON") {
  29. t.Fatalf("Unexpected error: %v", err)
  30. }
  31. }
  32. func BenchmarkJSONStringify(b *testing.B) {
  33. b.StopTimer()
  34. vm := New()
  35. var createObj func(level int) *Object
  36. createObj = func(level int) *Object {
  37. o := vm.NewObject()
  38. o.Set("field1", "test")
  39. o.Set("field2", 42)
  40. if level > 0 {
  41. level--
  42. o.Set("obj1", createObj(level))
  43. o.Set("obj2", createObj(level))
  44. }
  45. return o
  46. }
  47. o := createObj(3)
  48. json := vm.Get("JSON").(*Object)
  49. stringify, _ := AssertFunction(json.Get("stringify"))
  50. b.StartTimer()
  51. for i := 0; i < b.N; i++ {
  52. stringify(nil, o)
  53. }
  54. }