Debian Codegraph @

pkg/http/marshal_test.go

raw
1 package http
2
3 import (
4 "bytes"
5 "net/http/httptest"
6 "testing"
7
8 "github.com/stretchr/testify/assert"
9 )
10
11 func TestConcatenateJSON(t *testing.T) {
12 type args struct {
13 first []byte
14 second []byte
15 }
16 tests := []struct {
17 name string
18 args args
19 want []byte
20 wantErr bool
21 }{
22 {
23 "invalid first part, error",
24 args{
25 []byte(`invalid`),
26 []byte(`{"some": "thing"}`),
27 },
28 nil,
29 true,
30 },
31 {
32 "invalid second part, error",
33 args{
34 []byte(`{"some": "thing"}`),
35 []byte(`invalid`),
36 },
37 nil,
38 true,
39 },
40 {
41 "both valid, merged",
42 args{
43 []byte(`{"some": "thing"}`),
44 []byte(`{"another": "thing"}`),
45 },
46
47 []byte(`{"some": "thing","another": "thing"}`),
48 false,
49 },
50 {
51 "first empty",
52 args{
53 []byte(`{}`),
54 []byte(`{"some": "thing"}`),
55 },
56
57 []byte(`{"some": "thing"}`),
58 false,
59 },
60 {
61 "second empty",
62 args{
63 []byte(`{"some": "thing"}`),
64 []byte(`{}`),
65 },
66
67 []byte(`{"some": "thing"}`),
68 false,
69 },
70 {
71 "both empty",
72 args{
73 []byte(`{}`),
74 []byte(`{}`),
75 },
76
77 []byte(`{}`),
78 false,
79 },
80 }
81 for _, tt := range tests {
82 t.Run(tt.name, func(t *testing.T) {
83 got, err := ConcatenateJSON(tt.args.first, tt.args.second)
84 if (err != nil) != tt.wantErr {
85 t.Errorf("ConcatenateJSON() error = %v, wantErr %v", err, tt.wantErr)
86 return
87 }
88 if !bytes.Equal(got, tt.want) {
89 t.Errorf("ConcatenateJSON() got = %v, want %v", string(got), tt.want)
90 }
91 })
92 }
93 }
94
95 func TestMarshalJSONWithStatus(t *testing.T) {
96 type args struct {
97 i any
98 status int
99 }
100 type res struct {
101 statusCode int
102 body string
103 }
104 tests := []struct {
105 name string
106 args args
107 res res
108 }{
109 {
110 "empty ok",
111 args{
112 nil,
113 200,
114 },
115 res{
116 200,
117 "",
118 },
119 },
120 {
121 "string ok",
122 args{
123 "ok",
124 200,
125 },
126 res{
127 200,
128 `"ok"
129 `,
130 },
131 },
132 {
133 "struct ok",
134 args{
135 struct {
136 Test string `json:"test"`
137 }{"ok"},
138 200,
139 },
140 res{
141 200,
142 `{"test":"ok"}
143 `,
144 },
145 },
146 }
147 for _, tt := range tests {
148 t.Run(tt.name, func(t *testing.T) {
149 w := httptest.NewRecorder()
150 MarshalJSONWithStatus(w, tt.args.i, tt.args.status)
151 assert.Equal(t, tt.res.statusCode, w.Result().StatusCode)
152 assert.Equal(t, "application/json", w.Header().Get("content-type"))
153 assert.Equal(t, tt.res.body, w.Body.String())
154 })
155 }
156 }