...
1 package hctypes_test
2
3 import (
4 "fmt"
5 "testing"
6
7 "gitlab.hexacode.org/go-libs/hctypes"
8 )
9
10 type Contoh struct {
11 key string
12 val string
13 }
14
15 func (this *Contoh) String() string {
16 return fmt.Sprintf("Contoh(%s=%v)", this.key, this.val)
17 }
18
19 func TestDictToJson(t *testing.T) {
20 type StructDict struct {
21 Key1 string `json:"key1"`
22 Key2 []int `json:"key2"`
23 }
24
25 structDict := &StructDict{}
26
27 inputDict := hctypes.Dict{
28 "key1": "value1",
29 "key2": hctypes.List{
30 42,
31 },
32 }
33
34 expectedJSON := hctypes.String(`{"key1":"value1","key2":[42]}`)
35 actualJSON := inputDict.ToJson().ToString()
36
37 if expectedJSON != actualJSON {
38 t.Errorf("Expected: %s, Got: %s", expectedJSON, actualJSON)
39 }
40
41 err := inputDict.Unmarshal(&structDict)
42
43 if err != nil {
44 t.Error(err)
45 }
46
47 if structDict.Key1 != "value1" {
48 t.Errorf("Expected: value1, Got: %s", structDict.Key1)
49 }
50
51 if len(structDict.Key2) != 1 {
52 t.Errorf("Expected: 1, Got: %d", len(structDict.Key2))
53 }
54
55 if structDict.Key2[0] != 42 {
56 t.Errorf("Expected: 42, Got: %d", structDict.Key2[0])
57 }
58
59 arrayInt := []int{}
60
61 inputList := hctypes.List{
62 42,
63 }
64
65 expectedJSON = hctypes.String(`[42]`)
66 actualJSON = inputList.ToJson().ToString()
67
68 if expectedJSON != actualJSON {
69 t.Errorf("Expected: %s, Got: %s", expectedJSON, actualJSON)
70 }
71
72 err = inputList.Unmarshal(&arrayInt)
73
74 if err != nil {
75 t.Error(err)
76 }
77
78 if len(arrayInt) != 1 {
79 t.Errorf("Expected: 1, Got: %d", len(arrayInt))
80 }
81
82 if arrayInt[0] != 42 {
83 t.Errorf("Expected: 42, Got: %d", arrayInt[0])
84 }
85
86 inputDict2, err := hctypes.MarshalDict(&structDict)
87
88 if err != nil {
89 t.Error(err)
90 }
91
92 expectedJSON = hctypes.String(`{"key1":"value1","key2":[42]}`)
93 actualJSON = inputDict2.ToJson().ToString()
94
95 if expectedJSON != actualJSON {
96 t.Errorf("Expected: %s, Got: %s", expectedJSON, actualJSON)
97 }
98
99 inputList2, err := hctypes.MarshalList(&arrayInt)
100
101 if err != nil {
102 t.Error(err)
103 }
104
105 expectedJSON = hctypes.String(`[42]`)
106 actualJSON = inputList2.ToJson().ToString()
107
108 if expectedJSON != actualJSON {
109 t.Errorf("Expected: %s, Got: %s", expectedJSON, actualJSON)
110 }
111
112 if !inputDict.Equal(inputDict2) {
113 t.Error("inputDict and inputDict2 should not be equal")
114 }
115
116 if !inputList.Equal(inputList2) {
117 t.Error("inputList and inputList2 should not be equal")
118 }
119 }
120
View as plain text