Skip to content

Commit

Permalink
test: add more tests
Browse files Browse the repository at this point in the history
  • Loading branch information
joshiste committed Feb 12, 2024
1 parent 4a50b31 commit 245e13c
Show file tree
Hide file tree
Showing 2 changed files with 81 additions and 4 deletions.
9 changes: 5 additions & 4 deletions exthttp/exthttp.go
Original file line number Diff line number Diff line change
Expand Up @@ -126,11 +126,12 @@ func WriteError(w http.ResponseWriter, err extension_kit.ExtensionError) {
// WriteBody writes the given value as the HTTP response body as JSON with status code 200.
func WriteBody(w http.ResponseWriter, response any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(200)
encodeErr := json.NewEncoder(w).Encode(response)
if encodeErr != nil {
log.Err(encodeErr).Msgf("Failed to response body")
if err := json.NewEncoder(w).Encode(response); err != nil {
log.Err(err).Msgf("Failed to response body")
w.WriteHeader(500)
return
}
w.WriteHeader(200)
}

func IfNoneMatchHandler(etagFn func() string, delegate Handler) Handler {
Expand Down
76 changes: 76 additions & 0 deletions exthttp/exthttp_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
package exthttp

import (
"github.com/stretchr/testify/assert"
"net/http"
"net/http/httptest"
"testing"
Expand Down Expand Up @@ -131,3 +132,78 @@ func TestIfNoneMatchHandler(t *testing.T) {
})
}
}

func TestPanicRecovery(t *testing.T) {
tests := []struct {
name string
panic bool
wantedStatusCode int
}{
{
name: "should return 200",
panic: false,
wantedStatusCode: 200,
},
{
name: "should return 500",
panic: true,
wantedStatusCode: 500,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
req, err := http.NewRequest("GET", "/", nil)
if err != nil {
t.Fatal(err)
}
rr := httptest.NewRecorder()

PanicRecovery(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if tt.panic {
panic("test")
}
w.WriteHeader(200)
})).ServeHTTP(rr, req)

if status := rr.Code; status != tt.wantedStatusCode {
t.Errorf("handler returned wrong status code: got %v want %v", status, tt.wantedStatusCode)
}

})
}
}

func TestWriteBody(t *testing.T) {
tests := []struct {
name string
responseBody any
wantedStatus int
wantedBody string
}{
{
name: "should write body",
responseBody: map[string]string{
"key": "value",
},
wantedStatus: 200,
wantedBody: "{\"key\":\"value\"}\n",
},
{
name: "should fail writing body",
responseBody: make(chan int),
wantedStatus: 500,
wantedBody: "",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
rr := httptest.NewRecorder()

WriteBody(rr, tt.responseBody)

assert.Equal(t, tt.wantedBody, rr.Body.String())
assert.Equal(t, tt.wantedStatus, rr.Code)
assert.Equal(t, "application/json", rr.Header().Get("Content-Type"))
})
}
}

0 comments on commit 245e13c

Please sign in to comment.