83 lines
1.9 KiB
Go
83 lines
1.9 KiB
Go
package images
|
|
|
|
import (
|
|
"io"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"testing"
|
|
|
|
"github.com/gofiber/fiber/v3"
|
|
)
|
|
|
|
func TestImagePathHelpers(t *testing.T) {
|
|
filename := "/example.png"
|
|
|
|
if got := imagePublicPath(filename); got != "/uploads/example.png" {
|
|
t.Fatalf("expected public path %q, got %q", "/uploads/example.png", got)
|
|
}
|
|
|
|
if got := imageDiskPath(filename); got != "uploads/example.png" {
|
|
t.Fatalf("expected disk path %q, got %q", "uploads/example.png", got)
|
|
}
|
|
}
|
|
|
|
func TestBuildImageURLUsesForwardedHeaders(t *testing.T) {
|
|
app := fiber.New()
|
|
app.Get("/image-url", func(c fiber.Ctx) error {
|
|
return c.SendString(buildImageURL(c, "/uploads/example.png"))
|
|
})
|
|
|
|
req := httptest.NewRequest(http.MethodGet, "/image-url", nil)
|
|
req.Header.Set("X-Forwarded-Proto", "https")
|
|
req.Header.Set("X-Forwarded-Host", "cdn.example.com")
|
|
|
|
resp, err := app.Test(req)
|
|
if err != nil {
|
|
t.Fatalf("request failed: %v", err)
|
|
}
|
|
t.Cleanup(func() {
|
|
_ = resp.Body.Close()
|
|
})
|
|
|
|
body, err := io.ReadAll(resp.Body)
|
|
if err != nil {
|
|
t.Fatalf("failed to read response body: %v", err)
|
|
}
|
|
|
|
if got := string(body); got != "https://cdn.example.com/uploads/example.png" {
|
|
t.Fatalf("expected forwarded image url, got %q", got)
|
|
}
|
|
}
|
|
|
|
func TestParsePagination(t *testing.T) {
|
|
cases := []struct {
|
|
query string
|
|
wantPage int
|
|
wantLimit int
|
|
}{
|
|
{"", 1, 20},
|
|
{"page=0&limit=0", 1, 20},
|
|
{"page=3&limit=50", 3, 50},
|
|
{"page=-1&limit=200", 1, 20},
|
|
}
|
|
|
|
for _, tc := range cases {
|
|
app := fiber.New()
|
|
app.Get("/test", func(c fiber.Ctx) error {
|
|
page, limit := parsePagination(c)
|
|
return c.JSON(fiber.Map{"page": page, "limit": limit})
|
|
})
|
|
|
|
req := httptest.NewRequest(http.MethodGet, "/test?"+tc.query, nil)
|
|
resp, err := app.Test(req)
|
|
if err != nil {
|
|
t.Fatalf("request failed for query %q: %v", tc.query, err)
|
|
}
|
|
t.Cleanup(func() { _ = resp.Body.Close() })
|
|
|
|
if resp.StatusCode != http.StatusOK {
|
|
t.Fatalf("query %q: expected 200 got %d", tc.query, resp.StatusCode)
|
|
}
|
|
}
|
|
}
|