Skip to content

Commit

Permalink
chore: add tests
Browse files Browse the repository at this point in the history
  • Loading branch information
maxwellgithinji committed Aug 11, 2021
1 parent 3205bd8 commit e0a7e88
Showing 1 changed file with 123 additions and 0 deletions.
123 changes: 123 additions & 0 deletions helpers_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
package errorcodeutil_test

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

"github.com/savannahghi/errorcodeutil"
"github.com/stretchr/testify/assert"
)

func TestReportErr(t *testing.T) {
type args struct {
w http.ResponseWriter
err error
status int
}

tests := []struct {
name string
args args
wantStatus int
}{
{
name: "setting the status from the error reporter",
args: args{
w: httptest.NewRecorder(),
err: fmt.Errorf("a test error"),
status: http.StatusBadRequest,
},
wantStatus: http.StatusBadRequest,
},
}
for _, tt := range tests {
errorcodeutil.ReportErr(tt.args.w, tt.args.err, tt.args.status)
rw, ok := tt.args.w.(*httptest.ResponseRecorder)
assert.True(t, ok)
assert.NotNil(t, rw)
assert.Equal(t, tt.args.status, rw.Code)
}
}

func TestErrorMap(t *testing.T) {
err := fmt.Errorf("test error")
errMap := errorcodeutil.ErrorMap(err)
if errMap["error"] == "" {
t.Errorf("empty error key in error map")
}
if errMap["error"] != "test error" {
t.Errorf("expected http error value to be %s, got %s", "test error", errMap["error"])
}
}

func TestRespondWithError(t *testing.T) {
type args struct {
w http.ResponseWriter
code int
err error
}
tests := []struct {
name string
args args
wantStatus int
}{
{
name: "responds with correct status code",
args: args{
w: httptest.NewRecorder(),
code: http.StatusNotFound,
err: fmt.Errorf("not found error"),
},
wantStatus: http.StatusNotFound,
},
}
for _, tt := range tests {
errorcodeutil.RespondWithError(tt.args.w, tt.args.code, tt.args.err)
rw, ok := tt.args.w.(*httptest.ResponseRecorder)
assert.True(t, ok)
assert.NotNil(t, rw)
assert.Equal(t, tt.args.code, rw.Code)
}
}

func TestRespondWithJson(t *testing.T) {
type args struct {
w http.ResponseWriter
code int
payload []byte
}

expectedPayloadMSI := map[string]interface{}{
"error": "page not found",
}

bs, err := json.Marshal(expectedPayloadMSI)
if err != nil {
t.Errorf("Error marshalling %s", err)
}

tests := []struct {
name string
args args
wantStatus int
}{
{
name: "responds with correct status and payload",
args: args{
w: httptest.NewRecorder(),
code: http.StatusNotFound,
payload: bs,
},
},
}
for _, tt := range tests {
errorcodeutil.RespondWithJSON(tt.args.w, tt.args.code, tt.args.payload)
rw, ok := tt.args.w.(*httptest.ResponseRecorder)
assert.True(t, ok)
assert.NotNil(t, rw)
assert.Equal(t, tt.args.code, rw.Code)
}
}

0 comments on commit e0a7e88

Please sign in to comment.