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