value_test.go 1.9 KB

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