Skip to content

Commit

Permalink
Add test helpers for inspecting response/error interfaces
Browse files Browse the repository at this point in the history
  • Loading branch information
dnsge committed May 3, 2023
1 parent fb71a31 commit fdddb33
Show file tree
Hide file tree
Showing 2 changed files with 90 additions and 0 deletions.
27 changes: 27 additions & 0 deletions helpers_test.go
@@ -0,0 +1,27 @@
package sapi

import (
"github.com/stretchr/testify/assert"
"net/http"
"testing"
)

func TestGetResStatus(t *testing.T) {
res := Status(http.StatusCreated)
assert.Equal(t, http.StatusCreated, GetResStatus(res))
}

func TestGetResBody(t *testing.T) {
res := Status(http.StatusCreated)
assert.JSONEq(t, `{"status": 201}`, GetResBody(res))
}

func TestGetErrStatus(t *testing.T) {
err := ErrorStatus(http.StatusInternalServerError)
assert.Equal(t, http.StatusInternalServerError, GetErrStatus(err))
}

func TestGetErrBody(t *testing.T) {
err := Error(http.StatusInternalServerError, "Oh no")
assert.JSONEq(t, `{"status": 500, "error": "Oh no"}`, GetErrBody(err))
}
63 changes: 63 additions & 0 deletions test_helpers.go
@@ -0,0 +1,63 @@
package sapi

import (
"github.com/gin-gonic/gin"
"net/http"
"net/http/httptest"
)

func execRes(res Res) *httptest.ResponseRecorder {
recorder := httptest.NewRecorder()
c, _ := gin.CreateTestContext(recorder)
res.WriteResponse(c)
return recorder
}

func execErr(err Err) *httptest.ResponseRecorder {
recorder := httptest.NewRecorder()
c, _ := gin.CreateTestContext(recorder)
err.WriteError(c)
return recorder
}

// GetResStatus returns the status code contained within the given response.
// This method should be exclusively used for testing.
func GetResStatus(res Res) int {
recorder := execRes(res)
return recorder.Code
}

// GetResHeaders returns the headers written for the given response.
// This method should be exclusively used for testing.
func GetResHeaders(res Res) http.Header {
recorder := execRes(res)
return recorder.Header()
}

// GetResBody returns the body written for the given response.
// This method should be exclusively used for testing.
func GetResBody(res Res) string {
recorder := execRes(res)
return recorder.Body.String()
}

// GetErrStatus returns the status code contained within the given error response.
// This method should be exclusively used for testing.
func GetErrStatus(err Err) int {
recorder := execErr(err)
return recorder.Code
}

// GetErrHeaders returns the headers written for the given error response.
// This method should be exclusively used for testing.
func GetErrHeaders(err Err) http.Header {
recorder := execErr(err)
return recorder.Header()
}

// GetErrBody returns the body written for the given error response.
// This method should be exclusively used for testing.
func GetErrBody(err Err) string {
recorder := execErr(err)
return recorder.Body.String()
}

0 comments on commit fdddb33

Please sign in to comment.