Skip to content

Commit

Permalink
test(util/helpers_test.go): add tests for WriteJSON and WriteError
Browse files Browse the repository at this point in the history
  • Loading branch information
lukewhrit committed Aug 8, 2023
1 parent c6ad5e1 commit 1787bdd
Showing 1 changed file with 60 additions and 0 deletions.
60 changes: 60 additions & 0 deletions internal/util/helpers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,12 @@
package util_test

import (
"encoding/json"
"errors"
"html/template"
"io"
"net/http"
"net/http/httptest"
"testing"

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

require.Equal(t, lines, template.HTML("<div>1</div><div>2</div>"))
}

func TestHandleBodyDetection(t *testing.T) {}
func TestHandleBodyJSON(t *testing.T) {}
func TestHandleBodyMultipart(t *testing.T) {}

func TestWriteJSON(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
err := util.WriteJSON[map[string]interface{}](w, 200, map[string]interface{}{
"test": "test",
})

require.NoError(t, err)
}))
defer server.Close()

res, err := http.Get(server.URL)
require.NoError(t, err)

require.Equal(t, http.StatusOK, res.StatusCode)

x, _ := io.ReadAll(res.Body)
var body map[string]interface{}
json.Unmarshal(x, &body)

require.Equal(t, body, map[string]interface{}{
"payload": map[string]interface{}{
"test": "test",
},
"error": "",
})
}

func TestWriteError(t *testing.T) {
e := errors.New("some error")

server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
err := util.WriteError(w, http.StatusInternalServerError, e)
require.NoError(t, err)
}))
defer server.Close()

res, err := http.Get(server.URL)
require.NoError(t, err)

require.Equal(t, http.StatusInternalServerError, res.StatusCode)

x, _ := io.ReadAll(res.Body)
var body map[string]interface{}
json.Unmarshal(x, &body)

require.Equal(t, body, map[string]interface{}{
"payload": map[string]interface{}{},
"error": e.Error(),
})
}

0 comments on commit 1787bdd

Please sign in to comment.