1+ package tests
2+
3+ import (
4+ "testing"
5+
6+ "github.com/codeshelldev/secured-signal-api/utils"
7+ "github.com/codeshelldev/secured-signal-api/utils/templating"
8+ )
9+
10+ func TestJsonTemplating (t * testing.T ) {
11+ variables := map [string ]interface {}{
12+ "array" : []string {
13+ "item0" ,
14+ "item1" ,
15+ },
16+ "key" : "val" ,
17+ "int" : 4 ,
18+ }
19+
20+ json := `
21+ {
22+ "dict": { "key": "{{.key}}" },
23+ "dictArray": [
24+ { "key": "{{.key}}" },
25+ { "key": "{{.array}}" }
26+ ],
27+ "key1": "{{.array}}",
28+ "key2": "{{.int}}"
29+ }`
30+
31+ data := utils.GetJson [map [string ]interface {}](json )
32+
33+ expected := map [string ]interface {}{
34+ "dict" : map [string ]interface {}{
35+ "key" : "val" ,
36+ },
37+ "dictArray" : []interface {}{
38+ map [string ]interface {}{"key" : "val" },
39+ map [string ]interface {}{"key" : []interface {}{ "item0" , "item1" }},
40+ },
41+ "key1" : []interface {}{ "item0" , "item1" },
42+ "key2" : 4 ,
43+ }
44+
45+ got , err := templating .RenderJSONTemplate ("json" , data , variables )
46+
47+ if err != nil {
48+ t .Error ("Error Templating JSON: " , err .Error ())
49+ }
50+
51+ expectedStr := utils .ToJson (expected )
52+ gotStr := utils .ToJson (got )
53+
54+ if expectedStr != gotStr {
55+ t .Error ("\n Expected: " , expectedStr , "\n Got: " , gotStr )
56+ }
57+ }
58+
59+ func TestJsonPath (t * testing.T ) {
60+ json := `
61+ {
62+ "dict": { "key": "value" },
63+ "dictArray": [
64+ { "key": "value0" },
65+ { "key": "value1" }
66+ ],
67+ "array": [
68+ "item0",
69+ "item1"
70+ ],
71+ "key": "val"
72+ }`
73+
74+ data := utils.GetJson [map [string ]interface {}](json )
75+
76+ cases := []struct {
77+ key string
78+ expected string
79+ }{
80+ {
81+ key : "key" ,
82+ expected : "val" ,
83+ },
84+ {
85+ key : "dict.key" ,
86+ expected : "value" ,
87+ },
88+ {
89+ key : "dictArray[0].key" ,
90+ expected : "value0" ,
91+ },
92+ {
93+ key : "dictArray[1].key" ,
94+ expected : "value1" ,
95+ },
96+ {
97+ key : "array[0]" ,
98+ expected : "item0" ,
99+ },
100+ {
101+ key : "array[1]" ,
102+ expected : "item1" ,
103+ },
104+ }
105+
106+ for _ , c := range cases {
107+ key := c .key
108+ expected := c .expected
109+
110+ got , ok := utils .GetJsonByPath (key , data )
111+
112+ if ! ok || got .(string ) != expected {
113+ t .Error ("Expected: " , key , " == " , expected , "; Got: " , got )
114+ }
115+ }
116+ }
0 commit comments