50 lines
1.7 KiB
Go
50 lines
1.7 KiB
Go
package api
|
|
|
|
import (
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"os"
|
|
"path/filepath"
|
|
"testing"
|
|
)
|
|
|
|
func TestMediaHandlerWebP(t *testing.T) {
|
|
dir := t.TempDir()
|
|
must := func(err error) {
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
must(os.MkdirAll(filepath.Join(dir, "iblock"), 0o755))
|
|
must(os.WriteFile(filepath.Join(dir, "iblock", "a.jpg"), []byte("JPEG"), 0o644))
|
|
must(os.WriteFile(filepath.Join(dir, "iblock", "a.jpg.webp"), []byte("WEBP"), 0o644))
|
|
must(os.WriteFile(filepath.Join(dir, "iblock", "b.png"), []byte("PNG"), 0o644))
|
|
h := mediaHandler(dir)
|
|
get := func(p, accept string) *httptest.ResponseRecorder {
|
|
r := httptest.NewRequest(http.MethodGet, p, nil)
|
|
if accept != "" {
|
|
r.Header.Set("Accept", accept)
|
|
}
|
|
w := httptest.NewRecorder()
|
|
h.ServeHTTP(w, r)
|
|
return w
|
|
}
|
|
cases := []struct{ path, accept, body, ctype string }{
|
|
{"/media/iblock/a.jpg", "image/avif,image/webp,*/*", "WEBP", "image/webp"}, // есть копия, браузер умеет WebP
|
|
{"/media/iblock/a.jpg", "image/png,*/*", "JPEG", "image/jpeg"}, // браузер без WebP — оригинал
|
|
{"/media/iblock/b.png", "image/webp", "PNG", "image/png"}, // копии нет — оригинал
|
|
}
|
|
for _, c := range cases {
|
|
w := get(c.path, c.accept)
|
|
if w.Code != 200 || w.Body.String() != c.body || w.Header().Get("Content-Type") != c.ctype {
|
|
t.Errorf("%s (%s): %d %q %q", c.path, c.accept, w.Code, w.Body.String(), w.Header().Get("Content-Type"))
|
|
}
|
|
if w.Header().Get("Vary") != "Accept" {
|
|
t.Errorf("%s: нет Vary: Accept", c.path)
|
|
}
|
|
}
|
|
if w := get("/media/../media_webp.go", "image/webp"); w.Code == 200 {
|
|
t.Errorf("выход за пределы папки: %d", w.Code)
|
|
}
|
|
}
|