package files_test import ( "net/http" "os" "path/filepath" "testing" "rickub.com/bots-garden/ori/internal/files" ) var pngHeader = []byte{0x89, 'P', 'N', 'G', 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 0} func TestRawStreamsBytesWithImageContentType(t *testing.T) { root, h := workspace(t) if err := os.WriteFile(filepath.Join(root, "logo.png"), pngHeader, 0o644); err != nil { t.Fatal(err) } rec := do(t, h, http.MethodGet, "/api/raw?path=logo.png", "") if rec.Code != http.StatusOK { t.Fatalf("GET raw = %d (%s)", rec.Code, rec.Body.String()) } if got := rec.Header().Get("Content-Type"); got != "image/png" { t.Errorf("Content-Type = %q, want image/png", got) } if got := rec.Body.Bytes(); string(got) != string(pngHeader) { t.Errorf("body = %v, want the exact file bytes", got) } if rec.Header().Get("Content-Length") != "12" { t.Errorf("Content-Length = %q, want 12", rec.Header().Get("Content-Length")) } } func TestRawAcceptsAbsolutePathsLikeTheOtherEndpoints(t *testing.T) { root, h := workspace(t) rec := do(t, h, http.MethodGet, "/api/raw?path="+filepath.Join(root, "README.md"), "") if rec.Code != http.StatusOK || rec.Body.String() != "# hello" { t.Errorf("absolute raw read = %d %q", rec.Code, rec.Body.String()) } if got := rec.Header().Get("Content-Type"); got != "text/markdown; charset=utf-8" { t.Errorf("Content-Type = %q, want the mime table's markdown type", got) } } func TestRawErrors(t *testing.T) { _, h := workspace(t) cases := []struct { target string want int }{ {"/api/raw", http.StatusBadRequest}, {"/api/raw?path=src", http.StatusBadRequest}, {"/api/raw?path=ghost.png", http.StatusNotFound}, } for _, tc := range cases { if rec := do(t, h, http.MethodGet, tc.target, ""); rec.Code != tc.want { t.Errorf("GET %s = %d, want %d", tc.target, rec.Code, tc.want) } } } func TestContentTypeFor(t *testing.T) { cases := []struct { path string head []byte want string }{ {"a.png", nil, "image/png"}, {"a.JPG", nil, "image/jpeg"}, {"a.jpeg", nil, "image/jpeg"}, {"a.gif", nil, "image/gif"}, {"a.webp", nil, "image/webp"}, {"a.svg", nil, "image/svg+xml"}, {"diagram.drawio.svg", nil, "image/svg+xml"}, {"a.bmp", nil, "image/bmp"}, {"a.ico", nil, "image/x-icon"}, {"a.avif", nil, "image/avif"}, {"a.json", nil, "application/json"}, {"README.md", nil, "text/markdown; charset=utf-8"}, {"NOTES.MARKDOWN", nil, "text/markdown; charset=utf-8"}, {"noext", []byte("plain words"), "text/plain; charset=utf-8"}, } for _, tc := range cases { if got := files.ContentTypeFor(tc.path, tc.head); got != tc.want { t.Errorf("ContentTypeFor(%q) = %q, want %q", tc.path, got, tc.want) } } }