-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathdecode_test.go
More file actions
106 lines (95 loc) · 2.19 KB
/
decode_test.go
File metadata and controls
106 lines (95 loc) · 2.19 KB
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
package plunk
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
)
type TestStruct struct {
Name string `json:"name"`
Value int `json:"value"`
}
func TestDecodeResponse(t *testing.T) {
testCases := []struct {
responseBody string
expected TestStruct
}{
{
responseBody: `{"name": "Test", "value": 42}`,
expected: TestStruct{Name: "Test", Value: 42},
},
}
for _, tc := range testCases {
// Create a test server that returns the mocked response
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write([]byte(tc.responseBody))
}))
defer ts.Close()
// Send a request to the test server
resp, err := http.Get(ts.URL)
assert.Nil(t, err)
defer resp.Body.Close()
// Call decodeResponse with the test server's response
var result TestStruct
err = decodeResponse(resp, &result)
assert.Nil(t, err)
assert.NotNil(t, result)
assert.Equal(t, tc.expected, result)
}
}
func TestDecodeStringToMap(t *testing.T) {
testCases := []struct {
input *string
expected map[string]interface{}
}{
{
input: nil,
expected: nil,
},
{
input: func() *string {
s := `{"key": "value"}`
return &s
}(),
expected: map[string]interface{}{"key": "value"},
},
{
input: func() *string {
s := `{"key1": 1, "key2": 2}`
return &s
}(),
expected: map[string]interface{}{"key1": 1.0, "key2": 2.0},
},
}
for _, tc := range testCases {
result, err := decodeStringToMap(tc.input)
assert.Nil(t, err)
assert.Equal(t, tc.expected, result)
}
}
func TestConvertMapToJSONString(t *testing.T) {
testCases := []struct {
input map[string]interface{}
expected string
}{
{
input: nil,
expected: "",
},
{
input: map[string]interface{}{"key": "value"},
expected: `{"key":"value"}`,
},
{
input: map[string]interface{}{"key1": 1, "key2": 2},
expected: `{"key1":1,"key2":2}`,
},
}
for i, tc := range testCases {
result, err := convertMapToJSONString(tc.input)
assert.Nil(t, err)
assert.Equal(t, tc.expected, result, "test case %d", i)
}
}