Add asserts test util
For comparing the body of a request with an instance.
This commit is contained in:
parent
42c5cc15d8
commit
d452b8b8ae
|
|
@ -0,0 +1,27 @@
|
||||||
|
package test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"io/ioutil"
|
||||||
|
"net/http/httptest"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
)
|
||||||
|
|
||||||
|
// BodyEquals asserts the content from the response recorder with the encoded json of the provided instance.
|
||||||
|
func BodyEquals(t assert.TestingT, obj interface{}, recorder *httptest.ResponseRecorder) {
|
||||||
|
bytes, err := ioutil.ReadAll(recorder.Body)
|
||||||
|
assert.Nil(t, err)
|
||||||
|
actual := string(bytes)
|
||||||
|
|
||||||
|
JSONEquals(t, obj, actual)
|
||||||
|
}
|
||||||
|
|
||||||
|
// JSONEquals asserts the content of the string with the encoded json of the provided instance.
|
||||||
|
func JSONEquals(t assert.TestingT, obj interface{}, expected string) {
|
||||||
|
bytes, err := json.Marshal(obj)
|
||||||
|
assert.Nil(t, err)
|
||||||
|
objJSON := string(bytes)
|
||||||
|
|
||||||
|
assert.JSONEq(t, expected, objJSON)
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,42 @@
|
||||||
|
package test_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http/httptest"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/gotify/server/test"
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
)
|
||||||
|
|
||||||
|
type obj struct {
|
||||||
|
Test string
|
||||||
|
ID int
|
||||||
|
}
|
||||||
|
|
||||||
|
type fakeTesting struct {
|
||||||
|
hasErrors bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *fakeTesting) Errorf(format string, args ...interface{}) {
|
||||||
|
t.hasErrors = true
|
||||||
|
}
|
||||||
|
|
||||||
|
func Test_BodyEquals(t *testing.T) {
|
||||||
|
recorder := httptest.NewRecorder()
|
||||||
|
recorder.WriteString(`{"ID": 2, "Test": "asd"}`)
|
||||||
|
|
||||||
|
fakeTesting := &fakeTesting{}
|
||||||
|
|
||||||
|
test.BodyEquals(fakeTesting, &obj{ID: 2, Test: "asd"}, recorder)
|
||||||
|
assert.False(t, fakeTesting.hasErrors)
|
||||||
|
}
|
||||||
|
|
||||||
|
func Test_BodyEquals_failing(t *testing.T) {
|
||||||
|
recorder := httptest.NewRecorder()
|
||||||
|
recorder.WriteString(`{"ID": 3, "Test": "asd"}`)
|
||||||
|
|
||||||
|
fakeTesting := &fakeTesting{}
|
||||||
|
|
||||||
|
test.BodyEquals(fakeTesting, &obj{ID: 2, Test: "asd"}, recorder)
|
||||||
|
assert.True(t, fakeTesting.hasErrors)
|
||||||
|
}
|
||||||
Loading…
Reference in New Issue