Skip to content

Commit

Permalink
test: http helpers (#18)
Browse files Browse the repository at this point in the history
* test: http helpers

* test: add test for respond with json through generic interface

* test: adding test for error response
  • Loading branch information
logan-bobo authored Aug 1, 2024
1 parent 1c6fdac commit 3a462b2
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 2 deletions.
2 changes: 0 additions & 2 deletions handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import (
"database/sql"
"encoding/hex"
"encoding/json"
"fmt"
"log"
"net/http"
"net/mail"
Expand Down Expand Up @@ -260,7 +259,6 @@ func (apiCfg *apiConfig) postAPIUsers(w http.ResponseWriter, r *http.Request) {
_, err = mail.ParseAddress(payload.Email)

if err != nil {
fmt.Println(err)
respondWithError(w, http.StatusBadRequest, "invalid email address")
return
}
Expand Down
56 changes: 56 additions & 0 deletions httphelper_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package main

import (
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
)

func TestRespondWithJSON(t *testing.T) {
t.Run("test respond with json with generic interface", func(t *testing.T) {
response := httptest.NewRecorder()

type FooStruct struct {
Foo string `json:"foo"`
}

testStruct := FooStruct{
Foo: "bar",
}

respondWithJSON(response, http.StatusOK, testStruct)

wantStruct := FooStruct{}

err := json.NewDecoder(response.Body).Decode(&wantStruct)

if err != nil {
t.Errorf("could not parse result as expected")
}

if testStruct != wantStruct {
t.Errorf("failed to respond with arbitrary interface got %q want %q", testStruct, wantStruct)
}
})
}

func TestRespondWithError(t *testing.T) {
t.Run("test respond with error with generic error", func(t *testing.T) {
response := httptest.NewRecorder()

respondWithError(response, http.StatusInternalServerError, "stuff is broken")

wantStruct := errorResponse{}

err := json.NewDecoder(response.Body).Decode(&wantStruct)

if err != nil {
t.Errorf("could not parse result as expected")
}

if wantStruct.Error != "stuff is broken" {
t.Errorf("failed to respond with a generic error")
}
})
}

0 comments on commit 3a462b2

Please sign in to comment.