Skip to content

Commit 1787bdd

Browse files
committed
test(util/helpers_test.go): add tests for WriteJSON and WriteError
1 parent c6ad5e1 commit 1787bdd

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

internal/util/helpers_test.go

+60
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,12 @@
1717
package util_test
1818

1919
import (
20+
"encoding/json"
21+
"errors"
2022
"html/template"
23+
"io"
24+
"net/http"
25+
"net/http/httptest"
2126
"testing"
2227

2328
"github.com/orca-group/spirit/internal/util"
@@ -45,3 +50,58 @@ func TestCountLines(t *testing.T) {
4550

4651
require.Equal(t, lines, template.HTML("<div>1</div><div>2</div>"))
4752
}
53+
54+
func TestHandleBodyDetection(t *testing.T) {}
55+
func TestHandleBodyJSON(t *testing.T) {}
56+
func TestHandleBodyMultipart(t *testing.T) {}
57+
58+
func TestWriteJSON(t *testing.T) {
59+
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
60+
err := util.WriteJSON[map[string]interface{}](w, 200, map[string]interface{}{
61+
"test": "test",
62+
})
63+
64+
require.NoError(t, err)
65+
}))
66+
defer server.Close()
67+
68+
res, err := http.Get(server.URL)
69+
require.NoError(t, err)
70+
71+
require.Equal(t, http.StatusOK, res.StatusCode)
72+
73+
x, _ := io.ReadAll(res.Body)
74+
var body map[string]interface{}
75+
json.Unmarshal(x, &body)
76+
77+
require.Equal(t, body, map[string]interface{}{
78+
"payload": map[string]interface{}{
79+
"test": "test",
80+
},
81+
"error": "",
82+
})
83+
}
84+
85+
func TestWriteError(t *testing.T) {
86+
e := errors.New("some error")
87+
88+
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
89+
err := util.WriteError(w, http.StatusInternalServerError, e)
90+
require.NoError(t, err)
91+
}))
92+
defer server.Close()
93+
94+
res, err := http.Get(server.URL)
95+
require.NoError(t, err)
96+
97+
require.Equal(t, http.StatusInternalServerError, res.StatusCode)
98+
99+
x, _ := io.ReadAll(res.Body)
100+
var body map[string]interface{}
101+
json.Unmarshal(x, &body)
102+
103+
require.Equal(t, body, map[string]interface{}{
104+
"payload": map[string]interface{}{},
105+
"error": e.Error(),
106+
})
107+
}

0 commit comments

Comments
 (0)