package route import ( "net/http" "net/http/httptest" "strconv" "strings" "testing" "github.com/tamakyi/TamaBox/internal/route/assets" ) // TestWriteBanned 守住「被封禁后的响应是一张图」。 func TestWriteBanned(t *testing.T) { rec := httptest.NewRecorder() writeBanned(rec, http.MethodGet) if rec.Code != http.StatusForbidden { t.Fatalf("status = %d, want 403(换成图片不改变状态码语义)", rec.Code) } if ct := rec.Header().Get("Content-Type"); ct != "image/webp" { t.Errorf("Content-Type = %q, want image/webp", ct) } if cl := rec.Header().Get("Content-Length"); cl != strconv.Itoa(len(assets.BannedImage)) { t.Errorf("Content-Length = %q, want %d", cl, len(assets.BannedImage)) } if cc := rec.Header().Get("Cache-Control"); !strings.Contains(cc, "no-store") { t.Errorf("Cache-Control = %q, want 含 no-store(中间层缓存 403 无意义)", cc) } body := rec.Body.Bytes() // webp 的容器头:RIFF....WEBP。写成字节判断,避免「图片被换成 HTML」这类回归。 if len(body) < 12 || string(body[0:4]) != "RIFF" || string(body[8:12]) != "WEBP" { t.Errorf("body 不是 webp(前 12 字节 %q)", body[:min(12, len(body))]) } if strings.Contains(string(body), "403 Forbidden") && len(body) < 512 { t.Error("body 仍是明文文案,没换成图片") } } // TestWriteBannedHead 覆盖 HEAD:头照给(含 Content-Length),body 不发。 func TestWriteBannedHead(t *testing.T) { rec := httptest.NewRecorder() writeBanned(rec, http.MethodHead) if rec.Code != http.StatusForbidden { t.Fatalf("status = %d, want 403", rec.Code) } if rec.Body.Len() != 0 { t.Errorf("HEAD 不应有 body,实际 %d 字节", rec.Body.Len()) } if cl := rec.Header().Get("Content-Length"); cl != strconv.Itoa(len(assets.BannedImage)) { t.Errorf("Content-Length = %q, want %d", cl, len(assets.BannedImage)) } }