88 lines
2.0 KiB
Go
Raw Normal View History

2023-07-18 19:48:38 +00:00
package server_test
2023-07-18 16:02:57 +00:00
import (
"errors"
"io"
"net/http"
"net/http/httptest"
2023-07-19 11:01:51 +00:00
"strings"
2023-07-18 16:02:57 +00:00
"testing"
"git.akyoto.dev/go/assert"
2023-07-18 19:48:38 +00:00
"git.akyoto.dev/go/server"
2023-07-18 16:02:57 +00:00
)
2023-07-19 10:31:33 +00:00
func TestRouter(t *testing.T) {
2023-07-18 19:48:38 +00:00
s := server.New()
2023-07-18 16:02:57 +00:00
2023-07-18 19:48:38 +00:00
s.Get("/", func(ctx server.Context) error {
2023-07-18 16:02:57 +00:00
return ctx.Bytes([]byte("Hello"))
})
2023-07-18 19:48:38 +00:00
s.Get("/blog/:post", func(ctx server.Context) error {
2023-07-18 16:02:57 +00:00
return ctx.Bytes([]byte("Hello"))
})
2023-07-18 19:48:38 +00:00
s.Get("/error", func(ctx server.Context) error {
2023-07-18 16:02:57 +00:00
return ctx.Error(http.StatusUnauthorized, errors.New("Not logged in"))
})
2023-07-19 11:01:51 +00:00
s.Get("/reader", func(ctx server.Context) error {
return ctx.Reader(strings.NewReader("Hello"))
})
s.Get("/string", func(ctx server.Context) error {
return ctx.String("Hello")
})
2023-07-18 16:02:57 +00:00
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)},
2023-07-19 11:01:51 +00:00
{URL: "/reader", Status: http.StatusOK, Body: "Hello"},
{URL: "/string", Status: http.StatusOK, Body: "Hello"},
2023-07-18 16:02:57 +00:00
}
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()
2023-07-18 19:48:38 +00:00
s.ServeHTTP(response, request)
2023-07-18 16:02:57 +00:00
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)
})
}
}
2023-07-19 10:31:33 +00:00
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)
})
}