github.com/philpearl/plenc@v0.0.15/plenccodec/json_test.go (about) 1 package plenccodec_test 2 3 import ( 4 "encoding/json" 5 "reflect" 6 "testing" 7 8 "github.com/google/go-cmp/cmp" 9 "github.com/philpearl/plenc" 10 "github.com/philpearl/plenc/plenccodec" 11 ) 12 13 func TestJSONMap(t *testing.T) { 14 type customMap map[string]interface{} 15 plenc.RegisterCodec(reflect.TypeOf(customMap{}), plenccodec.JSONMapCodec{}) 16 17 tests := []customMap{ 18 { 19 "a": 1, 20 "b": -1, 21 "c": 1.1, 22 "d": "hat", 23 "e": map[string]interface{}{ 24 "f": 1, 25 "a": []interface{}{1, 2, 3}, 26 "b": []interface{}{1, 1.3, "haddock"}, 27 }, 28 "f": nil, 29 "g": true, 30 "h": json.Number("3.1415"), 31 }, 32 {}, 33 nil, 34 } 35 36 for _, test := range tests { 37 t.Run("", func(t *testing.T) { 38 var ( 39 d []byte 40 err error 41 ) 42 d, err = plenc.Marshal(d, &test) 43 if err != nil { 44 t.Fatal(err) 45 } 46 47 var out customMap 48 if err := plenc.Unmarshal(d, &out); err != nil { 49 t.Fatal(err) 50 } 51 52 if diff := cmp.Diff(test, out); diff != "" { 53 t.Fatalf("maps differ. %s", diff) 54 } 55 }) 56 } 57 } 58 59 func TestJSONMapStruct(t *testing.T) { 60 type customMap map[string]interface{} 61 plenc.RegisterCodec(reflect.TypeOf(customMap{}), plenccodec.JSONMapCodec{}) 62 63 type my struct { 64 A customMap `plenc:"1"` 65 B customMap `plenc:"2"` 66 } 67 68 in := my{ 69 A: make(customMap), 70 B: nil, 71 } 72 73 d, err := plenc.Marshal(nil, &in) 74 if err != nil { 75 t.Fatal(err) 76 } 77 78 var out my 79 if err := plenc.Unmarshal(d, &out); err != nil { 80 t.Fatal(err) 81 } 82 83 if diff := cmp.Diff(in, out); diff != "" { 84 t.Fatalf("maps differ. %s", diff) 85 } 86 } 87 88 func TestJSONMapSkip(t *testing.T) { 89 type customMap map[string]interface{} 90 plenc.RegisterCodec(reflect.TypeOf(customMap{}), plenccodec.JSONMapCodec{}) 91 92 type my struct { 93 A int `plenc:"1"` 94 B customMap `plenc:"2"` 95 C string `plenc:"3"` 96 } 97 98 in := my{ 99 A: 37, 100 B: customMap{ 101 "a": 1, 102 "b": -1, 103 "c": 1.1, 104 "d": "hat", 105 "e": map[string]interface{}{ 106 "f": 1, 107 "a": []interface{}{1, 2, 3}, 108 }, 109 "f": nil, 110 "g": true, 111 "h": json.Number("3.1415"), 112 }, 113 C: "hello", 114 } 115 116 var ( 117 d []byte 118 err error 119 ) 120 d, err = plenc.Marshal(d, &in) 121 if err != nil { 122 t.Fatal(err) 123 } 124 125 var out struct { 126 A int `plenc:"1"` 127 C string `plenc:"3"` 128 } 129 if err := plenc.Unmarshal(d, &out); err != nil { 130 t.Fatal(err) 131 } 132 133 if out.A != 37 && out.C != "hello" { 134 t.Fatalf("output not as expected. %#v", out) 135 } 136 }