sessions/internal/router/rest/rest_test.go

114 lines
2.8 KiB
Go

package rest_test
import (
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"testing"
"time"
"gitea.dwysokinski.me/twhelp/sessions/internal/router/rest"
"gitea.dwysokinski.me/twhelp/sessions/internal/router/rest/internal/model"
"github.com/go-chi/chi/v5"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
"github.com/google/uuid"
"github.com/stretchr/testify/assert"
)
func TestRouteNotFound(t *testing.T) {
t.Parallel()
expectedResp := &model.ErrorResp{
Error: model.APIError{
Code: "route-not-found",
Message: "route not found",
},
}
resp := doRequest(rest.NewRouter(rest.RouterConfig{}), http.MethodGet, "/v1/"+uuid.NewString(), "", nil)
defer resp.Body.Close()
assertJSONResponse(t, resp, http.StatusNotFound, expectedResp, &model.ErrorResp{})
}
func TestMethodNotAllowed(t *testing.T) {
t.Parallel()
expectedResp := &model.ErrorResp{
Error: model.APIError{
Code: "method-not-allowed",
Message: "method not allowed",
},
}
resp := doRequest(rest.NewRouter(rest.RouterConfig{
Swagger: rest.SwaggerConfig{
Enabled: true,
},
}), http.MethodPost, "/v1/swagger/index.html", "", nil)
defer resp.Body.Close()
assertJSONResponse(t, resp, http.StatusMethodNotAllowed, expectedResp, &model.ErrorResp{})
}
func TestSwagger(t *testing.T) {
t.Parallel()
tests := []struct {
name string
target string
expectedContentType string
}{
{
name: "/v1/swagger/index.html",
target: "/v1/swagger/index.html",
expectedContentType: "text/html; charset=utf-8",
},
{
name: "/v1/swagger/doc.json",
target: "/v1/swagger/doc.json",
expectedContentType: "application/json; charset=utf-8",
},
}
router := rest.NewRouter(rest.RouterConfig{
Swagger: rest.SwaggerConfig{
Enabled: true,
},
})
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
resp := doRequest(router, http.MethodGet, tt.target, "", nil)
defer resp.Body.Close()
assert.Equal(t, http.StatusOK, resp.StatusCode)
assert.Equal(t, tt.expectedContentType, resp.Header.Get("Content-Type"))
})
}
}
func doRequest(mux chi.Router, method, target, apiKey string, body io.Reader) *http.Response {
rr := httptest.NewRecorder()
req := httptest.NewRequest(method, target, body)
if apiKey != "" {
req.Header.Set("X-Api-Key", apiKey)
}
mux.ServeHTTP(rr, req)
return rr.Result()
}
func assertJSONResponse(tb testing.TB, resp *http.Response, expectedStatus int, expected any, target any) {
tb.Helper()
assert.Equal(tb, "application/json", resp.Header.Get("Content-Type"))
assert.Equal(tb, expectedStatus, resp.StatusCode)
assert.NoError(tb, json.NewDecoder(resp.Body).Decode(target))
opts := cmp.Options{
cmpopts.IgnoreUnexported(time.Time{}),
}
assert.Empty(tb, cmp.Diff(expected, target, opts...))
}