go.ketch.com/lib/goja@v0.0.1/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 BenchmarkJSONStringify(b *testing.B) {
    69  	b.StopTimer()
    70  	vm := New()
    71  	var createObj func(level int) *Object
    72  	createObj = func(level int) *Object {
    73  		o := vm.NewObject()
    74  		o.Set("field1", "test")
    75  		o.Set("field2", 42)
    76  		if level > 0 {
    77  			level--
    78  			o.Set("obj1", createObj(level))
    79  			o.Set("obj2", createObj(level))
    80  		}
    81  		return o
    82  	}
    83  
    84  	o := createObj(3)
    85  	json := vm.Get("JSON").(*Object)
    86  	stringify, _ := AssertFunction(json.Get("stringify"))
    87  	b.StartTimer()
    88  	for i := 0; i < b.N; i++ {
    89  		stringify(nil, o)
    90  	}
    91  }