github.com/nuvolaris/goja@v0.0.0-20230825100449-967811910c6d/builtin_json_test.go (about) 1 package goja 2 3 import ( 4 "encoding/json" 5 "strings" 6 "testing" 7 "time" 8 ) 9 10 func TestJSONMarshalObject(t *testing.T) { 11 vm := New() 12 o := vm.NewObject() 13 o.Set("test", 42) 14 o.Set("testfunc", vm.Get("Error")) 15 b, err := json.Marshal(o) 16 if err != nil { 17 t.Fatal(err) 18 } 19 if string(b) != `{"test":42}` { 20 t.Fatalf("Unexpected value: %s", b) 21 } 22 } 23 24 func TestJSONMarshalGoDate(t *testing.T) { 25 vm := New() 26 o := vm.NewObject() 27 o.Set("test", time.Unix(86400, 0).UTC()) 28 b, err := json.Marshal(o) 29 if err != nil { 30 t.Fatal(err) 31 } 32 if string(b) != `{"test":"1970-01-02T00:00:00Z"}` { 33 t.Fatalf("Unexpected value: %s", b) 34 } 35 } 36 37 func TestJSONMarshalObjectCircular(t *testing.T) { 38 vm := New() 39 o := vm.NewObject() 40 o.Set("o", o) 41 _, err := json.Marshal(o) 42 if err == nil { 43 t.Fatal("Expected error") 44 } 45 if !strings.HasSuffix(err.Error(), "Converting circular structure to JSON") { 46 t.Fatalf("Unexpected error: %v", err) 47 } 48 } 49 50 func TestJSONParseReviver(t *testing.T) { 51 // example from 52 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse 53 const SCRIPT = ` 54 JSON.parse('{"p": 5}', function(key, value) { 55 return typeof value === 'number' 56 ? value * 2 // return value * 2 for numbers 57 : value // return everything else unchanged 58 })["p"] 59 ` 60 61 testScript(SCRIPT, intToValue(10), t) 62 } 63 64 func TestQuoteMalformedSurrogatePair(t *testing.T) { 65 testScript(`JSON.stringify("\uD800")`, asciiString(`"\ud800"`), t) 66 } 67 68 func TestEOFWrapping(t *testing.T) { 69 vm := New() 70 71 _, err := vm.RunString("JSON.parse('{')") 72 if err == nil { 73 t.Fatal("Expected error") 74 } 75 76 if !strings.Contains(err.Error(), "Unexpected end of JSON input") { 77 t.Fatalf("Error doesn't contain human-friendly wrapper: %v", err) 78 } 79 } 80 81 func BenchmarkJSONStringify(b *testing.B) { 82 b.StopTimer() 83 vm := New() 84 var createObj func(level int) *Object 85 createObj = func(level int) *Object { 86 o := vm.NewObject() 87 o.Set("field1", "test") 88 o.Set("field2", 42) 89 if level > 0 { 90 level-- 91 o.Set("obj1", createObj(level)) 92 o.Set("obj2", createObj(level)) 93 } 94 return o 95 } 96 97 o := createObj(3) 98 json := vm.Get("JSON").(*Object) 99 stringify, _ := AssertFunction(json.Get("stringify")) 100 b.StartTimer() 101 for i := 0; i < b.N; i++ { 102 stringify(nil, o) 103 } 104 }