81 lines
2.4 KiB
Go
Raw Permalink Normal View History

2024-03-20 20:17:23 +00:00
package content_test
import (
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"git.akyoto.dev/go/assert"
2024-03-22 14:08:24 +00:00
"git.akyoto.dev/go/web"
"git.akyoto.dev/go/web/content"
)
func TestContentTypes(t *testing.T) {
2024-03-22 14:08:24 +00:00
s := web.NewServer()
2024-03-22 14:08:24 +00:00
s.Get("/css", func(ctx web.Context) error {
2024-03-20 20:17:23 +00:00
return content.CSS(ctx, "body{}")
})
2024-03-22 14:08:24 +00:00
s.Get("/csv", func(ctx web.Context) error {
2024-03-20 20:17:23 +00:00
return content.CSV(ctx, "ID;Name\n")
})
2024-03-22 14:08:24 +00:00
s.Get("/html", func(ctx web.Context) error {
2024-03-20 20:17:23 +00:00
return content.HTML(ctx, "<html></html>")
})
2024-03-22 14:08:24 +00:00
s.Get("/js", func(ctx web.Context) error {
2024-03-20 20:17:23 +00:00
return content.JS(ctx, "console.log(42)")
})
2024-03-22 14:08:24 +00:00
s.Get("/json", func(ctx web.Context) error {
2024-03-20 20:17:23 +00:00
return content.JSON(ctx, struct{ Name string }{Name: "User 1"})
})
2024-03-22 14:08:24 +00:00
s.Get("/text", func(ctx web.Context) error {
2024-03-20 20:17:23 +00:00
return content.Text(ctx, "Hello")
})
2024-03-22 14:08:24 +00:00
s.Get("/xml", func(ctx web.Context) error {
2024-03-20 20:17:23 +00:00
return content.XML(ctx, "<xml></xml>")
})
tests := []struct {
Method string
URL string
Body string
Status int
Response string
ContentType string
}{
{Method: "GET", URL: "/css", Body: "", Status: http.StatusOK, Response: "body{}", ContentType: "text/css"},
{Method: "GET", URL: "/csv", Body: "", Status: http.StatusOK, Response: "ID;Name\n", ContentType: "text/csv"},
{Method: "GET", URL: "/html", Body: "", Status: http.StatusOK, Response: "<html></html>", ContentType: "text/html"},
{Method: "GET", URL: "/js", Body: "", Status: http.StatusOK, Response: "console.log(42)", ContentType: "text/javascript"},
{Method: "GET", URL: "/json", Body: "", Status: http.StatusOK, Response: "{\"Name\":\"User 1\"}\n", ContentType: "application/json"},
{Method: "GET", URL: "/text", Body: "", Status: http.StatusOK, Response: "Hello", ContentType: "text/plain"},
{Method: "GET", URL: "/xml", Body: "", Status: http.StatusOK, Response: "<xml></xml>", ContentType: "text/xml"},
}
for _, test := range tests {
t.Run("example.com"+test.URL, func(t *testing.T) {
request := httptest.NewRequest(test.Method, "http://example.com"+test.URL, strings.NewReader(test.Body))
response := httptest.NewRecorder()
s.ServeHTTP(response, request)
result := response.Result()
assert.Equal(t, result.StatusCode, test.Status)
contentType := result.Header.Get("Content-Type")
assert.Equal(t, contentType, test.ContentType)
body, err := io.ReadAll(result.Body)
assert.Nil(t, err)
assert.Equal(t, string(body), test.Response)
})
}
}