2023-07-19 12:31:33 +02:00

77 lines
1.7 KiB
Go

package server_test
import (
"errors"
"io"
"net/http"
"net/http/httptest"
"testing"
"git.akyoto.dev/go/assert"
"git.akyoto.dev/go/server"
)
func TestRouter(t *testing.T) {
s := server.New()
s.Get("/", func(ctx server.Context) error {
return ctx.Bytes([]byte("Hello"))
})
s.Get("/blog/:post", func(ctx server.Context) error {
return ctx.Bytes([]byte("Hello"))
})
s.Get("/error", func(ctx server.Context) error {
return ctx.Error(http.StatusUnauthorized, errors.New("Not logged in"))
})
tests := []struct {
URL string
Status int
Body string
}{
{URL: "/", Status: http.StatusOK, Body: "Hello"},
{URL: "/blog/post", Status: http.StatusOK, Body: "Hello"},
{URL: "/error", Status: http.StatusUnauthorized, Body: "Not logged in"},
{URL: "/not-found", Status: http.StatusNotFound, Body: http.StatusText(http.StatusNotFound)},
}
for _, test := range tests {
t.Run("example.com"+test.URL, func(t *testing.T) {
request := httptest.NewRequest(http.MethodGet, test.URL, nil)
response := httptest.NewRecorder()
s.ServeHTTP(response, request)
result := response.Result()
assert.Equal(t, result.StatusCode, test.Status)
body, err := io.ReadAll(result.Body)
assert.Nil(t, err)
assert.DeepEqual(t, string(body), test.Body)
})
}
}
func TestPanic(t *testing.T) {
s := server.New()
s.Get("/panic", func(ctx server.Context) error {
panic("Something unbelievable happened")
})
t.Run("example.com/panic", func(t *testing.T) {
defer func() {
r := recover()
if r == nil {
t.Error("Didn't panic")
}
}()
request := httptest.NewRequest(http.MethodGet, "/panic", nil)
response := httptest.NewRecorder()
s.ServeHTTP(response, request)
})
}