github.com/mailru/activerecord@v1.12.2/pkg/serializer/json_w_test.go (about) 1 package serializer 2 3 import ( 4 "errors" 5 "reflect" 6 "testing" 7 8 "github.com/mailru/activerecord/pkg/serializer/errs" 9 ) 10 11 func TestJSONUnmarshal(t *testing.T) { 12 type args struct { 13 val string 14 } 15 tests := []struct { 16 name string 17 args args 18 exec func(string) (any, error) 19 want any 20 wantErr error 21 }{ 22 { 23 name: "simple map", 24 args: args{val: `{"key": "value"}`}, 25 exec: func(val string) (any, error) { 26 var got map[string]interface{} 27 err := JSONUnmarshal(val, &got) 28 return got, err 29 }, 30 want: map[string]interface{}{"key": "value"}, 31 wantErr: nil, 32 }, 33 { 34 name: "nested map", 35 args: args{val: `{"key": {"nestedkey": "value"}}`}, 36 exec: func(val string) (any, error) { 37 var got map[string]interface{} 38 err := JSONUnmarshal(val, &got) 39 return got, err 40 }, 41 want: map[string]interface{}{"key": map[string]interface{}{"nestedkey": "value"}}, 42 wantErr: nil, 43 }, 44 { 45 name: "err map unmarshal", 46 args: args{val: `{"key": {"nestedkey": "value}}`}, 47 exec: func(val string) (any, error) { 48 var got map[string]interface{} 49 err := JSONUnmarshal(val, &got) 50 return got, err 51 }, 52 want: nil, 53 wantErr: errs.ErrUnmarshalJSON, 54 }, 55 { 56 name: "simple custom type ", 57 args: args{val: `{"quota": 2373874}`}, 58 exec: func(val string) (any, error) { 59 var got Services 60 err := JSONUnmarshal(val, &got) 61 return got, err 62 }, 63 want: Services{Quota: 2373874}, 64 wantErr: nil, 65 }, 66 { 67 name: "nested custom type", 68 args: args{val: `{"quota": 234321523, "gift": {"giftible_id": "year2020_333_1", "gift_quota": 2343432784}}`}, 69 exec: func(val string) (any, error) { 70 var got Services 71 err := JSONUnmarshal(val, &got) 72 return got, err 73 }, 74 want: Services{Quota: 234321523, Gift: &Gift{GiftibleID: "year2020_333_1", GiftQuota: 2343432784}}, 75 wantErr: nil, 76 }, 77 { 78 name: "err custom type", 79 args: args{val: `{"quota": 234321523, "gift": }}}}}}}}}}`}, 80 exec: func(val string) (any, error) { 81 var got Services 82 err := JSONUnmarshal(val, &got) 83 return got, err 84 }, 85 want: nil, 86 wantErr: errs.ErrUnmarshalJSON, 87 }, 88 } 89 for _, tt := range tests { 90 t.Run(tt.name, func(t *testing.T) { 91 got, err := tt.exec(tt.args.val) 92 if tt.wantErr != err && !errors.Is(err, tt.wantErr) { 93 t.Errorf("JSONUnmarshal() error = %v, wantErr %v", err, tt.wantErr) 94 } 95 if tt.wantErr == nil && !reflect.DeepEqual(got, tt.want) { 96 t.Errorf("JSONUnmarshal() = %v, want %v", got, tt.want) 97 } 98 }) 99 } 100 }