server_test.go
⎇
Raw
1package server
2
3import (
4 "database/sql"
5 "html"
6 "io"
7 "net/http"
8 "net/http/httptest"
9 "net/url"
10 "os"
11 "os/exec"
12 "path/filepath"
13 "regexp"
14 "strings"
15 "testing"
16
17 "vidarchive/internal/config"
18 "vidarchive/internal/database"
19 "vidarchive/internal/handler"
20 "vidarchive/internal/repository"
21 "vidarchive/internal/service"
22 "vidarchive/internal/worker"
23)
24
25// Authentication is mandatory, so the test server is configured with real
26// credentials. The hash is bcrypt over testPassword at the minimum cost,
27// because every test server logs in once.
28const (
29 testUsername = "tester"
30 testPassword = "test-password"
31 testPasswordHash = "$2a$04$6h5pthPxQs2muU4eCZjhReZlMvwf7XP9HUKCEubLMQZsR/84fHs0i"
32)
33
34// testServer is a Server whose Router() signs every request in, so the tests
35// that are not about authentication don't each have to log in. Tests that do
36// exercise the login flow reach past it with srv.Server.Router().
37type testServer struct {
38 *Server
39 session *http.Cookie
40}
41
42func (s testServer) Router() http.Handler {
43 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
44 if _, err := r.Cookie("session"); err != nil {
45 r.AddCookie(s.session)
46 }
47 s.Server.Router().ServeHTTP(w, r)
48 })
49}
50
51func setupTestServer(t *testing.T) (testServer, *config.Config, func()) {
52 srv, cfg, _, cleanup := setupTestServerDB(t)
53 return srv, cfg, cleanup
54}
55
56// setupTestServerDB is setupTestServer with the database handle exposed, for
57// tests that need to break the database on purpose.
58func setupTestServerDB(t *testing.T) (testServer, *config.Config, *sql.DB, func()) {
59 t.Helper()
60 dataDir := t.TempDir()
61 t.Setenv("VIDARCHIVE_DATA_DIR", dataDir)
62 t.Setenv("VIDARCHIVE_USERNAME", testUsername)
63 t.Setenv("VIDARCHIVE_PASSWORD_HASH", testPasswordHash)
64
65 cfg := config.New()
66 if err := os.MkdirAll(cfg.LibraryDir, 0o755); err != nil {
67 t.Fatalf("create library dir: %v", err)
68 }
69 if err := os.MkdirAll(cfg.TempDir, 0o755); err != nil {
70 t.Fatalf("create temp dir: %v", err)
71 }
72
73 db, err := database.New(cfg)
74 if err != nil {
75 t.Fatalf("init db: %v", err)
76 }
77
78 presetRepo := repository.NewPresetRepository(db)
79 downloadRepo := repository.NewDownloadRepository(db)
80 settingsRepo := repository.NewSettingsRepository(db)
81 subscriptionRepo := repository.NewSubscriptionRepository(db)
82
83 presetSvc := service.NewPresetService(presetRepo)
84 librarySvc := service.NewLibraryService(cfg.LibraryDir, cfg.FFmpegPath, cfg.FFprobePath)
85 settingsSvc := service.NewSettingsService(settingsRepo)
86 subscriptionSvc := service.NewSubscriptionService(subscriptionRepo, cfg)
87 downloadSvc := service.NewDownloadService(downloadRepo, librarySvc, presetSvc, settingsSvc, subscriptionSvc, cfg)
88 workerPool := worker.New(downloadSvc, cfg.Workers)
89
90 h, err := handler.New(cfg, presetSvc, downloadSvc, librarySvc, settingsSvc, subscriptionSvc, workerPool)
91 if err != nil {
92 t.Fatalf("init handler: %v", err)
93 }
94
95 srv := New(cfg, h)
96
97 login := postForm(srv.Router(), "/login", url.Values{
98 "username": {testUsername},
99 "password": {testPassword},
100 })
101 session := sessionCookie(login.Result().Cookies())
102 if session == nil {
103 t.Fatal("test login issued no session; check testPasswordHash")
104 }
105
106 cleanup := func() {
107 workerPool.Stop()
108 db.Close()
109 }
110 return testServer{Server: srv, session: session}, cfg, db, cleanup
111}
112
113func createItem(t *testing.T, libraryDir, relPath, name string, files map[string]string) {
114 t.Helper()
115 itemDir := filepath.Join(libraryDir, relPath)
116 if err := os.MkdirAll(itemDir, 0o755); err != nil {
117 t.Fatalf("create item dir: %v", err)
118 }
119 marker := filepath.Join(itemDir, ".vidarchive-item.toml")
120 if err := os.WriteFile(marker, []byte("name = \""+name+"\"\nduration = -1\n"), 0o644); err != nil {
121 t.Fatalf("write marker: %v", err)
122 }
123 for filename, content := range files {
124 path := filepath.Join(itemDir, filename)
125 if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
126 t.Fatalf("write file %s: %v", filename, err)
127 }
128 }
129}
130
131func TestLibraryEngagementViews(t *testing.T) {
132 srv, cfg, cleanup := setupTestServer(t)
133 defer cleanup()
134
135 createItem(t, cfg.LibraryDir, "engagement", "Engagement", map[string]string{
136 "video.mp4": "dummy video",
137 "info.json": `{"comments":[{"id":"parent","author":"<parent>","text":"safe <comment>","time_text":"today"},{"id":"reply","parent":"parent","author":"<child>","text":"reply","time_text":"today"}],"heatmap":[{"start_time":0,"end_time":10,"value":1}]}`,
138 })
139
140 detail := getWith(srv.Router(), "/library/item/engagement", nil)
141 if detail.Code != http.StatusOK {
142 t.Fatalf("detail status = %d", detail.Code)
143 }
144 body := detail.Body.String()
145 for _, want := range []string{"Playback heatmap", "&lt;parent&gt;", "&lt;child&gt;", "safe &lt;comment&gt;", "replying to <strong>&lt;parent&gt;</strong>", "View all comments"} {
146 if !strings.Contains(body, want) {
147 t.Errorf("detail missing %q", want)
148 }
149 }
150
151 all := getWith(srv.Router(), "/library/comments/engagement", nil)
152 if all.Code != http.StatusOK || !strings.Contains(all.Body.String(), "Engagement comments") {
153 t.Fatalf("comments view status/body unexpected: %d %s", all.Code, all.Body.String())
154 }
155
156 // A real item whose path ends in "comments" must remain reachable through
157 // the item route now that the full comments view has its own namespace.
158 createItem(t, cfg.LibraryDir, "playlist/comments", "Nested Comments Item", map[string]string{
159 "video.mp4": "dummy video",
160 })
161 item := getWith(srv.Router(), "/library/item/playlist/comments", nil)
162 if item.Code != http.StatusOK || !strings.Contains(item.Body.String(), "Nested Comments Item") {
163 t.Fatalf("item path ending in comments was shadowed: %d %s", item.Code, item.Body.String())
164 }
165}
166
167func TestCommentsViewMalformedSidecarIsError(t *testing.T) {
168 srv, cfg, cleanup := setupTestServer(t)
169 defer cleanup()
170
171 createItem(t, cfg.LibraryDir, "bad-comments", "Bad comments", map[string]string{
172 "video.mp4": "dummy video",
173 "info.json": `{"comments":[`,
174 })
175 w := getWith(srv.Router(), "/library/comments/bad-comments", nil)
176 if w.Code != http.StatusInternalServerError {
177 t.Fatalf("malformed comments status = %d, want 500", w.Code)
178 }
179 if !strings.Contains(w.Body.String(), "Something went wrong") {
180 t.Fatalf("malformed comments response = %q", w.Body.String())
181 }
182}
183
184func TestCommentsViewEncodedPath(t *testing.T) {
185 srv, cfg, cleanup := setupTestServer(t)
186 defer cleanup()
187
188 const item = "nested/An Item +"
189 createItem(t, cfg.LibraryDir, item, "Encoded comments", map[string]string{
190 "video.mp4": "dummy video",
191 "info.json": `{"comments":[{"author":"author","text":"hello"}]}`,
192 })
193
194 reqURL := "/library/comments/" + (&url.URL{Path: item}).EscapedPath()
195 w := getWith(srv.Router(), reqURL, nil)
196 if w.Code != http.StatusOK || !strings.Contains(w.Body.String(), "Encoded comments") {
197 t.Fatalf("encoded comments route %s: status=%d body=%s", reqURL, w.Code, w.Body.String())
198 }
199}
200
201func TestNestedLibraryItem(t *testing.T) {
202 srv, cfg, cleanup := setupTestServer(t)
203 defer cleanup()
204
205 createItem(t, cfg.LibraryDir, "test/My Item [id]", "My Item", map[string]string{
206 "My Item [id].mp4": "dummy video",
207 })
208
209 router := srv.Router()
210
211 req := httptest.NewRequest("GET", "/library/item/test/My%20Item%20%5Bid%5D", nil)
212 w := httptest.NewRecorder()
213 router.ServeHTTP(w, req)
214 if w.Code != http.StatusOK {
215 body, _ := io.ReadAll(w.Body)
216 t.Errorf("expected 200, got %d: %s", w.Code, string(body))
217 }
218}
219
220// A directory whose name contains a literal '+' must round-trip: in a URL path
221// '+' is a literal plus (not a space), reachable raw or percent-encoded.
222func TestLiteralPlusInPathSegment(t *testing.T) {
223 srv, cfg, cleanup := setupTestServer(t)
224 defer cleanup()
225
226 createItem(t, cfg.LibraryDir, "C++ Tutorial", "C++ Tutorial", map[string]string{
227 "C++ Tutorial.mp4": "dummy video",
228 })
229
230 router := srv.Router()
231 for _, path := range []string{
232 "/library/item/C++%20Tutorial",
233 "/library/item/C%2B%2B%20Tutorial",
234 } {
235 req := httptest.NewRequest("GET", path, nil)
236 w := httptest.NewRecorder()
237 router.ServeHTTP(w, req)
238 if w.Code != http.StatusOK {
239 body, _ := io.ReadAll(w.Body)
240 t.Errorf("%s: expected 200, got %d: %s", path, w.Code, string(body))
241 }
242 }
243}
244
245func TestMediaFileQueryDecoding(t *testing.T) {
246 srv, cfg, cleanup := setupTestServer(t)
247 defer cleanup()
248
249 createItem(t, cfg.LibraryDir, "My Item [id]", "My Item", map[string]string{
250 "My Item [id].mp4": "dummy video",
251 "My+Other.mp4": "dummy video plus",
252 })
253
254 router := srv.Router()
255
256 tests := []struct {
257 path string
258 expected int
259 }{
260 {"/media/item/My%20Item%20%5Bid%5D?file=My+Item+%5Bid%5D.mp4", http.StatusOK},
261 {"/media/item/My%20Item%20%5Bid%5D?file=My%20Item%20%5Bid%5D.mp4", http.StatusOK},
262 {"/media/item/My%20Item%20%5Bid%5D?file=My%2BOther.mp4", http.StatusOK},
263 {"/media/item/My%20Item%20%5Bid%5D?file=missing.mp4", http.StatusNotFound},
264 }
265 for _, tc := range tests {
266 req := httptest.NewRequest("GET", tc.path, nil)
267 w := httptest.NewRecorder()
268 router.ServeHTTP(w, req)
269 if w.Code != tc.expected {
270 body, _ := io.ReadAll(w.Body)
271 t.Errorf("%s: expected %d, got %d: %s", tc.path, tc.expected, w.Code, string(body))
272 }
273 }
274}
275
276// TestSubtitleServedByPathSegment guards the regression where subtitle tracks
277// are linked as <item>/subtitles/<lang> (language as a trailing path segment),
278// but the handler only recognized the "/subtitles" suffix with a ?lang= query.
279// The path form fell through to media serving and returned 400 "Missing file".
280func TestSubtitleServedByPathSegment(t *testing.T) {
281 srv, cfg, cleanup := setupTestServer(t)
282 defer cleanup()
283
284 // An item whose name contains non-ASCII + spaces, like the reported URL.
285 const item = "ずんだパーリナイ ⧸ なみぐる [ywXQ9SqsaBQ]"
286 createItem(t, cfg.LibraryDir, item, "Vid", map[string]string{
287 "video.mp4": "dummy video",
288 })
289 vtt := "WEBVTT\n\n00:00:00.000 --> 00:00:01.000\nhi\n"
290 subDir := filepath.Join(cfg.LibraryDir, item, "subtitles")
291 if err := os.MkdirAll(subDir, 0o755); err != nil {
292 t.Fatal(err)
293 }
294 if err := os.WriteFile(filepath.Join(subDir, "eng.vtt"), []byte(vtt), 0o644); err != nil {
295 t.Fatal(err)
296 }
297
298 router := srv.Router()
299 reqURL := "/media/item/" + (&url.URL{Path: item}).EscapedPath() + "/subtitles/eng"
300 req := httptest.NewRequest("GET", reqURL, nil)
301 w := httptest.NewRecorder()
302 router.ServeHTTP(w, req)
303 if w.Code != http.StatusOK {
304 body, _ := io.ReadAll(w.Body)
305 t.Fatalf("expected 200 for %s, got %d: %s", reqURL, w.Code, string(body))
306 }
307 if ct := w.Header().Get("Content-Type"); !strings.HasPrefix(ct, "text/vtt") {
308 t.Errorf("expected text/vtt content-type, got %q", ct)
309 }
310 if body, _ := io.ReadAll(w.Body); !strings.Contains(string(body), "WEBVTT") {
311 t.Errorf("expected the .vtt contents, got %q", string(body))
312 }
313
314 // A traversal attempt in the language segment must be rejected, not served.
315 bad := httptest.NewRequest("GET", "/media/item/"+(&url.URL{Path: item}).EscapedPath()+"/subtitles/..%2f..%2fsecret", nil)
316 bw := httptest.NewRecorder()
317 router.ServeHTTP(bw, bad)
318 if bw.Code == http.StatusOK {
319 t.Errorf("traversal in language segment was served (status %d)", bw.Code)
320 }
321}
322
323func TestPathTraversalBlocked(t *testing.T) {
324 srv, cfg, cleanup := setupTestServer(t)
325 defer cleanup()
326
327 outside := filepath.Join(cfg.DataDir, "secret")
328 if err := os.MkdirAll(outside, 0o755); err != nil {
329 t.Fatalf("create outside dir: %v", err)
330 }
331 marker := filepath.Join(outside, ".vidarchive-item.toml")
332 if err := os.WriteFile(marker, []byte("name = \"secret\"\nduration = -1\n"), 0o644); err != nil {
333 t.Fatalf("write marker: %v", err)
334 }
335
336 router := srv.Router()
337
338 req := httptest.NewRequest("GET", "/library/item/../secret", nil)
339 w := httptest.NewRecorder()
340 router.ServeHTTP(w, req)
341 if w.Code != http.StatusNotFound {
342 t.Errorf("expected 404 for path traversal, got %d", w.Code)
343 }
344}
345
346func TestPerFileExistingThumbnailServed(t *testing.T) {
347 srv, cfg, cleanup := setupTestServer(t)
348 defer cleanup()
349
350 // A pre-existing per-file thumbnail (<stem>.thumbnail.webp) is served for the
351 // matching ?file= request without re-extraction.
352 createItem(t, cfg.LibraryDir, "thumb-item", "Thumb Item", map[string]string{
353 "video.mp4": "dummy video",
354 "video.thumbnail.webp": "GENERATED-THUMB",
355 })
356
357 router := srv.Router()
358 req := httptest.NewRequest("GET", "/media/item/thumb-item/thumbnail?file=video.mp4", nil)
359 w := httptest.NewRecorder()
360 router.ServeHTTP(w, req)
361 if w.Code != http.StatusOK {
362 body, _ := io.ReadAll(w.Body)
363 t.Fatalf("expected 200, got %d: %s", w.Code, string(body))
364 }
365 if body, _ := io.ReadAll(w.Body); string(body) != "GENERATED-THUMB" {
366 t.Errorf("expected the existing per-file thumbnail, got %q", string(body))
367 }
368}
369
370func TestAudioThumbnailPlaceholder(t *testing.T) {
371 srv, cfg, cleanup := setupTestServer(t)
372 defer cleanup()
373
374 createItem(t, cfg.LibraryDir, "audio-item", "Audio Item", map[string]string{
375 "song.mp3": "dummy audio",
376 })
377
378 router := srv.Router()
379 req := httptest.NewRequest("GET", "/media/item/audio-item/thumbnail", nil)
380 w := httptest.NewRecorder()
381 router.ServeHTTP(w, req)
382 if w.Code != http.StatusOK {
383 body, _ := io.ReadAll(w.Body)
384 t.Fatalf("expected 200, got %d: %s", w.Code, string(body))
385 }
386 body, _ := io.ReadAll(w.Body)
387 if len(body) == 0 {
388 t.Errorf("placeholder thumbnail body was empty")
389 }
390}
391
392func TestMultiFileCardThumbnailURLsDecodeToFilenames(t *testing.T) {
393 srv, cfg, cleanup := setupTestServer(t)
394 defer cleanup()
395
396 // Filenames with spaces are the case that broke: the template must emit a
397 // query value that the handler decodes back to the exact filename (the bug
398 // was double-escaping spaces to %2b, which decodes to '+').
399 files := map[string]string{
400 "01 - Color Bars.mp4": "v",
401 "02 - Test Pattern.mp4": "v",
402 }
403 createItem(t, cfg.LibraryDir, "multi", "Multi", files)
404
405 req := httptest.NewRequest("GET", "/library", nil)
406 w := httptest.NewRecorder()
407 srv.Router().ServeHTTP(w, req)
408 body, _ := io.ReadAll(w.Body)
409
410 re := regexp.MustCompile(`thumbnail\?file=([^"]+)`)
411 matches := re.FindAllStringSubmatch(string(body), -1)
412 if len(matches) != len(files) {
413 t.Fatalf("expected %d per-file thumbnail URLs in the card, got %d", len(files), len(matches))
414 }
415 for _, m := range matches {
416 vals, err := url.ParseQuery("file=" + m[1])
417 if err != nil {
418 t.Fatalf("bad query %q: %v", m[1], err)
419 }
420 got := vals.Get("file")
421 if _, ok := files[got]; !ok {
422 t.Errorf("thumbnail file=%q decodes to %q, which is not a real filename (double-encoding regression)", m[1], got)
423 }
424 }
425}
426
427// TestNestedFolderLinkRoundTrip guards the double-encoding regression: a folder
428// whose name contains a space was linked with urlEncodePath *inside* a ?path=
429// query, which html/template then re-escaped (%20 -> %2520). Clicking the link
430// landed on a path the server decoded to "playlist%20test%202" — a directory
431// that doesn't exist — so the folder rendered empty and the breadcrumb showed
432// the literal "%20". The link must round-trip: its decoded ?path must be the
433// real directory, the item inside must render, and the breadcrumb must show the
434// human-readable name.
435func TestNestedFolderLinkRoundTrip(t *testing.T) {
436 srv, cfg, cleanup := setupTestServer(t)
437 defer cleanup()
438
439 createItem(t, cfg.LibraryDir, "subs/playlist test 2/Vid One", "Vid One", map[string]string{
440 "video.mp4": "dummy video",
441 })
442 router := srv.Router()
443
444 // List the parent and pull out the generated folder link.
445 req := httptest.NewRequest("GET", "/library?path=subs", nil)
446 w := httptest.NewRecorder()
447 router.ServeHTTP(w, req)
448 if w.Code != http.StatusOK {
449 t.Fatalf("list /library?path=subs: got %d", w.Code)
450 }
451 body := w.Body.String()
452
453 folderHref := regexp.MustCompile(`href="(/library\?path=[^"]+)" class="folder-item"`).FindStringSubmatch(body)
454 if folderHref == nil {
455 t.Fatalf("no folder link rendered for nested folder; body:\n%s", body)
456 }
457 href := html.UnescapeString(folderHref[1])
458
459 // The link's decoded ?path must be the real directory, not a still-encoded one.
460 u, err := url.Parse(href)
461 if err != nil {
462 t.Fatalf("parse folder href %q: %v", href, err)
463 }
464 if got := u.Query().Get("path"); got != "subs/playlist test 2" {
465 t.Fatalf("folder link path decodes to %q, want %q (double-encoding regression)", got, "subs/playlist test 2")
466 }
467
468 // Follow the link exactly as a browser would. The folder must not be empty,
469 // and the breadcrumb must show the readable name (never the encoded form).
470 req = httptest.NewRequest("GET", href, nil)
471 w = httptest.NewRecorder()
472 router.ServeHTTP(w, req)
473 if w.Code != http.StatusOK {
474 t.Fatalf("follow folder link %q: got %d", href, w.Code)
475 }
476 nested := w.Body.String()
477 if !strings.Contains(nested, "Vid One") {
478 t.Errorf("nested folder rendered empty — item 'Vid One' missing; body:\n%s", nested)
479 }
480 // The breadcrumb must display the readable name, not the percent-encoded form.
481 if !strings.Contains(nested, ">playlist test 2<") {
482 t.Errorf("breadcrumb missing readable folder name 'playlist test 2'")
483 }
484 if strings.Contains(nested, ">playlist%20test%202<") {
485 t.Errorf("breadcrumb displays the encoded name instead of a space (regression)")
486 }
487 // No link may carry a double-encoded path (%2520 == %25 + 20 == re-escaped %20).
488 if strings.Contains(nested, "%2520") {
489 t.Errorf("a link is double-encoded (%%2520) — urlEncodePath inside a ?path= query (regression)")
490 }
491}
492
493func TestListingDoesNotExtractThumbnails(t *testing.T) {
494 srv, cfg, cleanup := setupTestServer(t)
495 defer cleanup()
496
497 createItem(t, cfg.LibraryDir, "novid", "No Thumb", map[string]string{
498 "video.mp4": "dummy video",
499 })
500
501 router := srv.Router()
502 req := httptest.NewRequest("GET", "/library", nil)
503 w := httptest.NewRecorder()
504 router.ServeHTTP(w, req)
505 if w.Code != http.StatusOK {
506 t.Fatalf("expected 200, got %d", w.Code)
507 }
508
509 // Rendering the listing must not have created any thumbnail file.
510 entries, err := os.ReadDir(filepath.Join(cfg.LibraryDir, "novid"))
511 if err != nil {
512 t.Fatal(err)
513 }
514 for _, e := range entries {
515 if strings.Contains(e.Name(), ".thumbnail.") {
516 t.Errorf("listing extracted a thumbnail (%q) — should happen on request only", e.Name())
517 }
518 }
519}
520
521func TestGeneratedThumbnailServedOverIcon(t *testing.T) {
522 srv, cfg, cleanup := setupTestServer(t)
523 defer cleanup()
524
525 createItem(t, cfg.LibraryDir, "gen", "Gen", map[string]string{
526 "video.mp4": "dummy video",
527 "video.thumbnail.webp": "WEBPDATA",
528 })
529
530 router := srv.Router()
531 req := httptest.NewRequest("GET", "/media/item/gen/thumbnail?file=video.mp4", nil)
532 w := httptest.NewRecorder()
533 router.ServeHTTP(w, req)
534 if w.Code != http.StatusOK {
535 t.Fatalf("expected 200, got %d", w.Code)
536 }
537 if body, _ := io.ReadAll(w.Body); string(body) != "WEBPDATA" {
538 t.Errorf("expected generated thumbnail contents, got %q", string(body))
539 }
540}
541
542func TestThumbnailExtractedOnRequest(t *testing.T) {
543 if _, err := exec.LookPath("ffmpeg"); err != nil {
544 t.Skip("ffmpeg not on PATH")
545 }
546 srv, cfg, cleanup := setupTestServer(t)
547 defer cleanup()
548
549 itemDir := filepath.Join(cfg.LibraryDir, "realvid")
550 createItem(t, cfg.LibraryDir, "realvid", "Real", nil)
551 cmd := exec.Command("ffmpeg", "-hide_banner", "-loglevel", "error",
552 "-f", "lavfi", "-i", "testsrc=duration=3:size=64x64:rate=5",
553 "-pix_fmt", "yuv420p", filepath.Join(itemDir, "realvid.mp4"), "-y")
554 if out, err := cmd.CombinedOutput(); err != nil {
555 t.Fatalf("make test video: %v\n%s", err, out)
556 }
557
558 router := srv.Router()
559 req := httptest.NewRequest("GET", "/media/item/realvid/thumbnail?file=realvid.mp4", nil)
560 w := httptest.NewRecorder()
561 router.ServeHTTP(w, req)
562 if w.Code != http.StatusOK {
563 t.Fatalf("expected 200, got %d", w.Code)
564 }
565 if ct := w.Header().Get("Content-Type"); !strings.HasPrefix(ct, "image/") {
566 t.Errorf("expected image content-type, got %q", ct)
567 }
568 body, _ := io.ReadAll(w.Body)
569 if len(body) == 0 {
570 t.Error("served thumbnail body was empty")
571 }
572
573 // A real thumbnail file should now exist on disk, with no temp leftovers.
574 entries, _ := os.ReadDir(itemDir)
575 var found bool
576 for _, e := range entries {
577 if strings.Contains(e.Name(), ".thumbnail.") {
578 found = true
579 }
580 if strings.Contains(e.Name(), ".tmp") {
581 t.Errorf("leftover temp file %q", e.Name())
582 }
583 }
584 if !found {
585 t.Error("no thumbnail file written to disk after request")
586 }
587}
588
589func TestLibraryPageIsFast(t *testing.T) {
590 srv, cfg, cleanup := setupTestServer(t)
591 defer cleanup()
592
593 for i := 0; i < 50; i++ {
594 createItem(t, cfg.LibraryDir, "item-"+string(rune('a'+i)), "Item", map[string]string{
595 "video.mp4": "dummy",
596 })
597 }
598
599 router := srv.Router()
600 req := httptest.NewRequest("GET", "/library", nil)
601 w := httptest.NewRecorder()
602 router.ServeHTTP(w, req)
603 if w.Code != http.StatusOK {
604 body, _ := io.ReadAll(w.Body)
605 t.Fatalf("expected 200, got %d: %s", w.Code, string(body))
606 }
607}
608