netflux-homepage/handler/handler_test.go

98 lines
2.4 KiB
Go

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",
},
{
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: "405 method not allowed",
},
}
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)
if tc.wantContentType != "" {
assert.Equal(t, tc.wantContentType, resp.Header.Get("content-type"))
}
respBody, err := ioutil.ReadAll(resp.Body)
require.NoError(t, err)
assert.Contains(t, string(respBody), tc.wantBody)
})
}
}