Skip to content

Commit 1adb274

Browse files
authored
chore: backfill missing JSON builder tests (#2721)
## What kind of change does this PR introduce? Chore. Backfill missing JSON builder tests as requested from #2658 (review) ## What is the current behavior? No tests. ## What is the new behavior? Unit tests added.
1 parent 289d2f2 commit 1adb274

1 file changed

Lines changed: 57 additions & 0 deletions

File tree

‎internal/api/shared/json_test.go‎

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
package shared
2+
3+
import (
4+
"net/http"
5+
"net/http/httptest"
6+
"testing"
7+
8+
"github.com/stretchr/testify/assert"
9+
"github.com/stretchr/testify/require"
10+
)
11+
12+
func TestJSON(t *testing.T) {
13+
t.Run("Defaults to JSON", func(t *testing.T) {
14+
w := httptest.NewRecorder()
15+
16+
json := JSON(w)
17+
require.NotNil(t, json)
18+
assert.Equal(t, http.StatusOK, w.Code)
19+
assert.Equal(t, "application/json", w.Header().Get("Content-Type"))
20+
})
21+
22+
t.Run("Adds a Header", func(t *testing.T) {
23+
w := httptest.NewRecorder()
24+
25+
json := JSON(w).Header("X-Request-ID", "1")
26+
require.NotNil(t, json)
27+
assert.Equal(t, "1", w.Header().Get("X-Request-ID"))
28+
})
29+
30+
t.Run("Uses a custom Content-Type", func(t *testing.T) {
31+
w := httptest.NewRecorder()
32+
33+
json := JSON(w).ContentType("application/scim+json")
34+
require.NotNil(t, json)
35+
assert.Equal(t, "application/scim+json", w.Header().Get("Content-Type"))
36+
})
37+
38+
t.Run("Writes data to the response body", func(t *testing.T) {
39+
w := httptest.NewRecorder()
40+
b := []byte("hello, world")
41+
42+
err := JSON(w).Write(b)
43+
require.NoError(t, err)
44+
assert.Equal(t, "hello, world", w.Body.String())
45+
})
46+
47+
t.Run("Serializes a type to JSON", func(t *testing.T) {
48+
w := httptest.NewRecorder()
49+
type person struct {
50+
Name string `json:"name"`
51+
}
52+
53+
err := JSON(w).Send(&person{Name: "gilfoyle"})
54+
require.NoError(t, err)
55+
assert.Equal(t, `{"name":"gilfoyle"}`, w.Body.String())
56+
})
57+
}

0 commit comments

Comments
 (0)