netflux-homepage/handler/handler_test.go

98 lines
2.4 KiB
Go
Raw Normal View History

2022-06-06 16:48:53 +00:00
package handler_test
import (
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
"git.netflux.io/rob/netflux-homepage/handler"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestHandler(t *testing.T) {
const (
matrixHostname = "foo.example.com:443"
matrixBaseURL = "https://foo.example.com"
)
testCases := []struct {
name string
method string
path string
wantContentType string
wantStatusCode int
wantBody string
}{
{
name: "GET /.well-known/matrix/server",
method: http.MethodGet,
path: "/.well-known/matrix/server",
wantContentType: "application/json",
wantStatusCode: http.StatusOK,
wantBody: `{"m.server": "foo.example.com:443"}`,
},
{
name: "GET /.well-known/matrix/client",
method: http.MethodGet,
path: "/.well-known/matrix/client",
wantContentType: "application/json",
wantStatusCode: http.StatusOK,
wantBody: `{"m.homeserver": {"base_url": "https://foo.example.com"}}`,
},
{
name: "GET /",
method: http.MethodGet,
path: "/",
wantContentType: "text/html",
wantStatusCode: http.StatusOK,
wantBody: "Welcome to netflux.io",
},
2022-06-07 03:04:33 +00:00
{
name: "HEAD /",
method: http.MethodHead,
path: "/",
wantContentType: "text/html",
wantStatusCode: http.StatusOK,
wantBody: "",
},
2022-06-06 18:23:49 +00:00
{
name: "page not found",
method: http.MethodGet,
path: "/foo",
wantStatusCode: http.StatusNotFound,
wantBody: "404 page not found",
},
{
name: "wrong method",
method: http.MethodPost,
path: "/",
wantStatusCode: http.StatusMethodNotAllowed,
wantBody: "405 method not allowed",
},
2022-06-06 16:48:53 +00:00
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
req := httptest.NewRequest(tc.method, tc.path, nil)
rec := httptest.NewRecorder()
h := handler.New(matrixHostname, matrixBaseURL)
h.ServeHTTP(rec, req)
resp := rec.Result()
defer resp.Body.Close()
assert.Equal(t, tc.wantStatusCode, resp.StatusCode)
2022-06-06 18:23:49 +00:00
if tc.wantContentType != "" {
assert.Equal(t, tc.wantContentType, resp.Header.Get("content-type"))
}
2022-06-07 03:04:33 +00:00
respBody, err := ioutil.ReadAll(resp.Body)
require.NoError(t, err)
assert.Contains(t, string(respBody), tc.wantBody)
2022-06-06 16:48:53 +00:00
})
}
}