1 package hcl
2
3 import (
4 "testing"
5
6 "github.com/stretchr/testify/assert"
7 "github.com/stretchr/testify/require"
8 )
9
10
11 const original = `# key-value pair
12 "key" = "value"
13
14 // list
15 "list" = ["item1", "item2", "item3"]
16
17 /* map */
18 "map" = {
19 "key" = "value"
20 }
21
22 /*
23 nested map
24 */
25 "nested_map" "map" {
26 "key" = "value"
27
28 "list" = ["item1", "item2", "item3"]
29 }`
30
31
32 const encoded = `"key" = "value"
33
34 "list" = ["item1", "item2", "item3"]
35
36 "map" = {
37 "key" = "value"
38 }
39
40 "nested_map" "map" {
41 "key" = "value"
42
43 "list" = ["item1", "item2", "item3"]
44 }`
45
46
47
48
49
50 var decoded = map[string]any{
51 "key": "value",
52 "list": []any{
53 "item1",
54 "item2",
55 "item3",
56 },
57 "map": []map[string]any{
58 {
59 "key": "value",
60 },
61 },
62 "nested_map": []map[string]any{
63 {
64 "map": []map[string]any{
65 {
66 "key": "value",
67 "list": []any{
68 "item1",
69 "item2",
70 "item3",
71 },
72 },
73 },
74 },
75 },
76 }
77
78
79 var data = map[string]any{
80 "key": "value",
81 "list": []any{
82 "item1",
83 "item2",
84 "item3",
85 },
86 "map": map[string]any{
87 "key": "value",
88 },
89 "nested_map": map[string]any{
90 "map": map[string]any{
91 "key": "value",
92 "list": []any{
93 "item1",
94 "item2",
95 "item3",
96 },
97 },
98 },
99 }
100
101 func TestCodec_Encode(t *testing.T) {
102 codec := Codec{}
103
104 b, err := codec.Encode(data)
105 require.NoError(t, err)
106
107 assert.Equal(t, encoded, string(b))
108 }
109
110 func TestCodec_Decode(t *testing.T) {
111 t.Run("OK", func(t *testing.T) {
112 codec := Codec{}
113
114 v := map[string]any{}
115
116 err := codec.Decode([]byte(original), v)
117 require.NoError(t, err)
118
119 assert.Equal(t, decoded, v)
120 })
121
122 t.Run("InvalidData", func(t *testing.T) {
123 codec := Codec{}
124
125 v := map[string]any{}
126
127 err := codec.Decode([]byte(`invalid data`), v)
128 require.Error(t, err)
129
130 t.Logf("decoding failed as expected: %s", err)
131 })
132 }
133
View as plain text