package server_test import ( "errors" "io" "net/http" "net/http/httptest" "strings" "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("/string", func(ctx server.Context) error { return ctx.String("Hello") }) s.Get("/error", func(ctx server.Context) error { return ctx.Error(http.StatusUnauthorized, "Not logged in") }) s.Get("/error2", func(ctx server.Context) error { return ctx.Error(http.StatusUnauthorized, "Not logged in", errors.New("Missing auth token")) }) s.Get("/reader", func(ctx server.Context) error { return ctx.Reader(strings.NewReader("Hello")) }) s.Get("/blog/:article", func(ctx server.Context) error { article := ctx.Get("article") return ctx.String(article) }) s.Get("/missing-parameter", func(ctx server.Context) error { missing := ctx.Get("missing") return ctx.String(missing) }) s.Post("/", func(ctx server.Context) error { return ctx.String("Post") }) s.Delete("/", func(ctx server.Context) error { return ctx.String("Delete") }) s.Put("/", func(ctx server.Context) error { return ctx.String("Put") }) tests := []struct { Method string URL string Status int Body string }{ {Method: "GET", URL: "/", Status: http.StatusOK, Body: "Hello"}, {Method: "GET", URL: "/error", Status: http.StatusUnauthorized, Body: "Not logged in"}, {Method: "GET", URL: "/error2", Status: http.StatusUnauthorized, Body: "Not logged in\nMissing auth token"}, {Method: "GET", URL: "/not-found", Status: http.StatusNotFound, Body: http.StatusText(http.StatusNotFound)}, {Method: "GET", URL: "/reader", Status: http.StatusOK, Body: "Hello"}, {Method: "GET", URL: "/string", Status: http.StatusOK, Body: "Hello"}, {Method: "GET", URL: "/blog/testing-my-router", Status: http.StatusOK, Body: "testing-my-router"}, {Method: "GET", URL: "/missing-parameter", Status: http.StatusOK, Body: ""}, {Method: "POST", URL: "/", Status: http.StatusOK, Body: "Post"}, {Method: "DELETE", URL: "/", Status: http.StatusOK, Body: "Delete"}, {Method: "PUT", URL: "/", Status: http.StatusOK, Body: "Put"}, } for _, test := range tests { t.Run("example.com"+test.URL, func(t *testing.T) { request := httptest.NewRequest(test.Method, 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) }) }