70 lines
1.9 KiB
Go
70 lines
1.9 KiB
Go
package testutil
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"io"
|
|
"net/http/httptest"
|
|
"testing"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/stretchr/testify/assert"
|
|
"github.com/stretchr/testify/require"
|
|
"tss-rocks-be/ent"
|
|
"tss-rocks-be/ent/enttest"
|
|
)
|
|
|
|
// SetupTestRouter returns a new Gin engine for testing
|
|
func SetupTestRouter() *gin.Engine {
|
|
gin.SetMode(gin.TestMode)
|
|
return gin.New()
|
|
}
|
|
|
|
// NewTestClient creates a new ent client for testing
|
|
func NewTestClient() *ent.Client {
|
|
client := enttest.Open(testing.TB(nil), "sqlite3", "file:ent?mode=memory&cache=shared&_fk=1")
|
|
return client
|
|
}
|
|
|
|
// MakeTestRequest performs a test HTTP request and returns the response
|
|
func MakeTestRequest(t *testing.T, router *gin.Engine, method, path string, body interface{}) *httptest.ResponseRecorder {
|
|
var reqBody io.Reader
|
|
if body != nil {
|
|
jsonBytes, err := json.Marshal(body)
|
|
require.NoError(t, err)
|
|
reqBody = bytes.NewBuffer(jsonBytes)
|
|
}
|
|
|
|
req := httptest.NewRequest(method, path, reqBody)
|
|
if body != nil {
|
|
req.Header.Set("Content-Type", "application/json")
|
|
}
|
|
|
|
w := httptest.NewRecorder()
|
|
router.ServeHTTP(w, req)
|
|
return w
|
|
}
|
|
|
|
// AssertResponse asserts the HTTP response status code and body
|
|
func AssertResponse(t *testing.T, w *httptest.ResponseRecorder, expectedStatus int, expectedBody interface{}) {
|
|
assert.Equal(t, expectedStatus, w.Code)
|
|
|
|
if expectedBody != nil {
|
|
var actualBody interface{}
|
|
err := json.Unmarshal(w.Body.Bytes(), &actualBody)
|
|
require.NoError(t, err)
|
|
assert.Equal(t, expectedBody, actualBody)
|
|
}
|
|
}
|
|
|
|
// AssertErrorResponse asserts an error response with a specific message
|
|
func AssertErrorResponse(t *testing.T, w *httptest.ResponseRecorder, expectedStatus int, expectedMessage string) {
|
|
assert.Equal(t, expectedStatus, w.Code)
|
|
|
|
var response struct {
|
|
Error string `json:"error"`
|
|
}
|
|
err := json.Unmarshal(w.Body.Bytes(), &response)
|
|
require.NoError(t, err)
|
|
assert.Equal(t, expectedMessage, response.Error)
|
|
}
|