...
1 package test
2
3 import (
4 "encoding/json"
5 "fmt"
6 "github.com/json-iterator/go"
7 "github.com/modern-go/reflect2"
8 "github.com/stretchr/testify/require"
9 "testing"
10 )
11
12 type unmarshalCase struct {
13 obj func() interface{}
14 ptr interface{}
15 input string
16 selected bool
17 }
18
19 var unmarshalCases []unmarshalCase
20
21 var marshalCases = []interface{}{
22 nil,
23 }
24
25 type selectedMarshalCase struct {
26 marshalCase interface{}
27 }
28
29 func Test_unmarshal(t *testing.T) {
30 for _, testCase := range unmarshalCases {
31 if testCase.selected {
32 unmarshalCases = []unmarshalCase{testCase}
33 break
34 }
35 }
36 for i, testCase := range unmarshalCases {
37 t.Run(fmt.Sprintf("[%v]%s", i, testCase.input), func(t *testing.T) {
38 should := require.New(t)
39 var obj1 interface{}
40 var obj2 interface{}
41 if testCase.obj != nil {
42 obj1 = testCase.obj()
43 obj2 = testCase.obj()
44 } else {
45 valType := reflect2.TypeOfPtr(testCase.ptr).Elem()
46 obj1 = valType.New()
47 obj2 = valType.New()
48 }
49 err1 := json.Unmarshal([]byte(testCase.input), obj1)
50 should.NoError(err1, "json")
51 err2 := jsoniter.ConfigCompatibleWithStandardLibrary.Unmarshal([]byte(testCase.input), obj2)
52 should.NoError(err2, "jsoniter")
53 should.Equal(obj1, obj2)
54 })
55 }
56 }
57
58 func Test_marshal(t *testing.T) {
59 for _, testCase := range marshalCases {
60 selectedMarshalCase, found := testCase.(selectedMarshalCase)
61 if found {
62 marshalCases = []interface{}{selectedMarshalCase.marshalCase}
63 break
64 }
65 }
66 for i, testCase := range marshalCases {
67 var name string
68 if testCase != nil {
69 name = fmt.Sprintf("[%v]%v/%s", i, testCase, reflect2.TypeOf(testCase).String())
70 }
71 t.Run(name, func(t *testing.T) {
72 should := require.New(t)
73 output1, err1 := json.Marshal(testCase)
74 should.NoError(err1, "json")
75 output2, err2 := jsoniter.ConfigCompatibleWithStandardLibrary.Marshal(testCase)
76 should.NoError(err2, "jsoniter")
77 should.Equal(string(output1), string(output2))
78 })
79 }
80 }
81
View as plain text