1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
|
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)
}
}
}
|