1package json
2
3import (
4	"encoding/json"
5	"testing"
6
7	"github.com/zclconf/go-cty/cty"
8)
9
10func TestSimpleJSONValue(t *testing.T) {
11	tests := []struct {
12		Input cty.Value
13		JSON  string
14		Want  cty.Value
15	}{
16		{
17			cty.NumberIntVal(5),
18			`5`,
19			cty.NumberIntVal(5),
20		},
21		{
22			cty.True,
23			`true`,
24			cty.True,
25		},
26		{
27			cty.StringVal("hello"),
28			`"hello"`,
29			cty.StringVal("hello"),
30		},
31		{
32			cty.TupleVal([]cty.Value{cty.StringVal("hello"), cty.True}),
33			`["hello",true]`,
34			cty.TupleVal([]cty.Value{cty.StringVal("hello"), cty.True}),
35		},
36		{
37			cty.ListVal([]cty.Value{cty.False, cty.True}),
38			`[false,true]`,
39			cty.TupleVal([]cty.Value{cty.False, cty.True}),
40		},
41		{
42			cty.SetVal([]cty.Value{cty.False, cty.True}),
43			`[false,true]`,
44			cty.TupleVal([]cty.Value{cty.False, cty.True}),
45		},
46		{
47			cty.ObjectVal(map[string]cty.Value{"true": cty.True, "greet": cty.StringVal("hello")}),
48			`{"greet":"hello","true":true}`,
49			cty.ObjectVal(map[string]cty.Value{"true": cty.True, "greet": cty.StringVal("hello")}),
50		},
51		{
52			cty.MapVal(map[string]cty.Value{"true": cty.True, "false": cty.False}),
53			`{"false":false,"true":true}`,
54			cty.ObjectVal(map[string]cty.Value{"true": cty.True, "false": cty.False}),
55		},
56		{
57			cty.NullVal(cty.Bool),
58			`null`,
59			cty.NullVal(cty.DynamicPseudoType), // type is lost in the round-trip
60		},
61	}
62
63	for _, test := range tests {
64		t.Run(test.Input.GoString(), func(t *testing.T) {
65			wrappedInput := SimpleJSONValue{test.Input}
66			buf, err := json.Marshal(wrappedInput)
67			if err != nil {
68				t.Fatalf("unexpected error from json.Marshal: %s", err)
69			}
70			if string(buf) != test.JSON {
71				t.Fatalf(
72					"incorrect JSON\ninput: %#v\ngot:   %s\nwant:  %s",
73					test.Input, buf, test.JSON,
74				)
75			}
76
77			var wrappedOutput SimpleJSONValue
78			err = json.Unmarshal(buf, &wrappedOutput)
79			if err != nil {
80				t.Fatalf("unexpected error from json.Unmarshal: %s", err)
81			}
82
83			if !wrappedOutput.Value.RawEquals(test.Want) {
84				t.Fatalf(
85					"incorrect result\nJSON:  %s\ngot:   %#v\nwant:  %#v",
86					buf, wrappedOutput.Value, test.Want,
87				)
88			}
89		})
90	}
91}
92