package handler_test
import (
"io"
"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 /test.html",
method: http.MethodGet,
path: "/test.html",
wantContentType: "text/html; charset=utf-8",
wantStatusCode: http.StatusOK,
wantBody: "\n
\n Test\n \n\n",
},
{
name: "GET /",
method: http.MethodGet,
path: "/",
wantContentType: "text/html",
wantStatusCode: http.StatusOK,
wantBody: "Welcome to netflux.io",
},
{
name: "HEAD /",
method: http.MethodHead,
path: "/",
wantContentType: "text/html",
wantStatusCode: http.StatusOK,
wantBody: "",
},
{
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: "Method Not Allowed\n",
},
}
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(
handler.Params{
MatrixHostname: matrixHostname,
MatrixBaseURL: matrixBaseURL,
RootPath: "testdata/static/",
},
)
h.ServeHTTP(rec, req)
resp := rec.Result()
defer resp.Body.Close()
assert.Equal(t, tc.wantStatusCode, resp.StatusCode)
if tc.wantContentType != "" {
assert.Equal(t, tc.wantContentType, resp.Header.Get("content-type"))
}
respBody, err := io.ReadAll(resp.Body)
require.NoError(t, err)
assert.Contains(t, string(respBody), tc.wantBody)
})
}
}