package content_test import ( "io" "net/http" "net/http/httptest" "strings" "testing" "git.akyoto.dev/go/assert" "git.akyoto.dev/go/server" "git.akyoto.dev/go/server/content" ) func TestContentTypes(t *testing.T) { s := server.New() s.Get("/css", func(ctx server.Context) error { return content.CSS(ctx, "body{}") }) s.Get("/csv", func(ctx server.Context) error { return content.CSV(ctx, "ID;Name\n") }) s.Get("/html", func(ctx server.Context) error { return content.HTML(ctx, "") }) s.Get("/js", func(ctx server.Context) error { return content.JS(ctx, "console.log(42)") }) s.Get("/json", func(ctx server.Context) error { return content.JSON(ctx, struct{ Name string }{Name: "User 1"}) }) s.Get("/text", func(ctx server.Context) error { return content.Text(ctx, "Hello") }) s.Get("/xml", func(ctx server.Context) error { return content.XML(ctx, "") }) 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: "", 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: "", 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) }) } }