...
1 package json
2
3 import (
4 "testing"
5
6 "github.com/stretchr/testify/assert"
7 "github.com/stretchr/testify/require"
8 )
9
10
11 const encoded = `{
12 "key": "value",
13 "list": [
14 "item1",
15 "item2",
16 "item3"
17 ],
18 "map": {
19 "key": "value"
20 },
21 "nested_map": {
22 "map": {
23 "key": "value",
24 "list": [
25 "item1",
26 "item2",
27 "item3"
28 ]
29 }
30 }
31 }`
32
33
34 var data = map[string]any{
35 "key": "value",
36 "list": []any{
37 "item1",
38 "item2",
39 "item3",
40 },
41 "map": map[string]any{
42 "key": "value",
43 },
44 "nested_map": map[string]any{
45 "map": map[string]any{
46 "key": "value",
47 "list": []any{
48 "item1",
49 "item2",
50 "item3",
51 },
52 },
53 },
54 }
55
56 func TestCodec_Encode(t *testing.T) {
57 codec := Codec{}
58
59 b, err := codec.Encode(data)
60 require.NoError(t, err)
61
62 assert.Equal(t, encoded, string(b))
63 }
64
65 func TestCodec_Decode(t *testing.T) {
66 t.Run("OK", func(t *testing.T) {
67 codec := Codec{}
68
69 v := map[string]any{}
70
71 err := codec.Decode([]byte(encoded), v)
72 require.NoError(t, err)
73
74 assert.Equal(t, data, v)
75 })
76
77 t.Run("InvalidData", func(t *testing.T) {
78 codec := Codec{}
79
80 v := map[string]any{}
81
82 err := codec.Decode([]byte(`invalid data`), v)
83 require.Error(t, err)
84
85 t.Logf("decoding failed as expected: %s", err)
86 })
87 }
88
View as plain text