This repository has been archived by the owner on Mar 3, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 18
/
main_test.go
129 lines (121 loc) · 2.53 KB
/
main_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
package main_test
import (
"encoding/json"
"reflect"
"testing"
"github.com/shiroyagicorp/prometheus-json-exporter"
)
type kvPair struct {
key string
value float64
}
type receiver struct {
received []kvPair
}
func (r *receiver) Receive(key string, value float64) {
r.received = append(r.received, kvPair{key, value})
}
func TestWalkJSON(t *testing.T) {
testData := []struct {
name string
bytes []byte
expected []kvPair
}{
{
name: "float value",
bytes: []byte(`{"x": 1.0}`),
expected: []kvPair{
kvPair{key: "x", value: 1.0},
},
},
{
name: "int value",
bytes: []byte(`{"x": 1}`),
expected: []kvPair{
kvPair{key: "x", value: 1.0},
},
},
{
name: "bool value",
bytes: []byte(`{"x": true}`),
expected: []kvPair{
kvPair{key: "x", value: 1.0},
},
},
{
name: "string value",
bytes: []byte(`{"x": "ok"}`),
expected: nil,
},
{
name: "null value",
bytes: []byte(`{"x": null}`),
expected: nil,
},
{
name: "array value",
bytes: []byte(`{"x": [1, 2, 3]}`),
expected: []kvPair{
kvPair{key: "x__0", value: 1},
kvPair{key: "x__1", value: 2},
kvPair{key: "x__2", value: 3},
},
},
{
name: "nested value",
bytes: []byte(`{"x": {"y": 1}}`),
expected: []kvPair{
kvPair{key: "x.y", value: 1.0},
},
},
{
name: "nested^2 value",
bytes: []byte(`{"x": {"y": {"z": 1}}}`),
expected: []kvPair{
kvPair{key: "x.y.z", value: 1.0},
},
},
{
name: "array in nested value",
bytes: []byte(`{"x": {"y": [1, 2, 3]}}`),
expected: []kvPair{
kvPair{key: "x.y__0", value: 1},
kvPair{key: "x.y__1", value: 2},
kvPair{key: "x.y__2", value: 3},
},
},
{
name: "array in array value",
bytes: []byte(`{"x": [[1, 2], [3, 4]]}`),
expected: []kvPair{
kvPair{key: "x__0__0", value: 1},
kvPair{key: "x__0__1", value: 2},
kvPair{key: "x__1__0", value: 3},
kvPair{key: "x__1__1", value: 4},
},
},
{
name: "array at root",
bytes: []byte(`[1, 2, 3]`),
expected: []kvPair{
kvPair{key: "__0", value: 1},
kvPair{key: "__1", value: 2},
kvPair{key: "__2", value: 3},
},
},
}
for _, tt := range testData {
t.Run(tt.name, func(t *testing.T) {
var jsonData interface{}
err := json.Unmarshal(tt.bytes, &jsonData)
if err != nil {
t.Errorf("Error: %v", err)
}
r := &receiver{}
main.WalkJSON("", jsonData, r)
if !reflect.DeepEqual(r.received, tt.expected) {
t.Errorf("Got: %#v, expected: %#v", r.received, tt.expected)
}
})
}
}