fork/gdu

git clone https://git.julia.blue/fork/gdu

Daniel Mildefeat: show bar for item count (#649)daaae96

master
19.5 KiB760 linesraw
1package webui
2
3import (
4	"bufio"
5	"bytes"
6	"encoding/json"
7	"io"
8	"net"
9	"net/http"
10	"net/http/httptest"
11	"net/url"
12	"os"
13	"path/filepath"
14	"strings"
15	"testing"
16	"time"
17
18	"github.com/dundee/gdu/v5/internal/common"
19	"github.com/dundee/gdu/v5/internal/testdev"
20	"github.com/dundee/gdu/v5/internal/testdir"
21	"github.com/dundee/gdu/v5/pkg/analyze"
22	"github.com/dundee/gdu/v5/pkg/device"
23	"github.com/dundee/gdu/v5/pkg/fs"
24)
25
26func newTestUI() *UI {
27	return CreateUI(io.Discard, "127.0.0.1:0", false, "", false, false, false, false)
28}
29
30// makeTree creates a temporary directory tree and returns its root path.
31func makeTree(t *testing.T) string {
32	t.Helper()
33	root := t.TempDir()
34
35	if err := os.WriteFile(filepath.Join(root, "big.bin"), make([]byte, 4096), 0o600); err != nil {
36		t.Fatal(err)
37	}
38	if err := os.WriteFile(filepath.Join(root, "small.txt"), make([]byte, 16), 0o600); err != nil {
39		t.Fatal(err)
40	}
41	sub := filepath.Join(root, "sub")
42	if err := os.Mkdir(sub, 0o700); err != nil {
43		t.Fatal(err)
44	}
45	if err := os.WriteFile(filepath.Join(sub, "nested.dat"), make([]byte, 1024), 0o600); err != nil {
46		t.Fatal(err)
47	}
48	return root
49}
50
51func scan(t *testing.T, ui *UI, path string) {
52	t.Helper()
53	if err := ui.AnalyzePath(path, nil); err != nil {
54		t.Fatalf("AnalyzePath: %v", err)
55	}
56	deadline := time.Now().Add(5 * time.Second)
57	for time.Now().Before(deadline) {
58		if ui.buildStatus().State == "done" {
59			return
60		}
61		time.Sleep(10 * time.Millisecond)
62	}
63	t.Fatal("scan did not complete in time")
64}
65
66func TestStatusEndpoint(t *testing.T) {
67	ui := newTestUI()
68	root := makeTree(t)
69	scan(t, ui, root)
70
71	srv := httptest.NewServer(ui.routes())
72	defer srv.Close()
73
74	resp, err := http.Get(srv.URL + "/api/v1/status")
75	if err != nil {
76		t.Fatal(err)
77	}
78	defer resp.Body.Close()
79
80	var status statusResponse
81	if err := json.NewDecoder(resp.Body).Decode(&status); err != nil {
82		t.Fatal(err)
83	}
84	if status.State != "done" {
85		t.Errorf("state = %q, want done", status.State)
86	}
87	if status.RootPath != root {
88		t.Errorf("rootPath = %q, want %q", status.RootPath, root)
89	}
90}
91
92func TestNodesEndpoint(t *testing.T) {
93	ui := newTestUI()
94	root := makeTree(t)
95	scan(t, ui, root)
96
97	srv := httptest.NewServer(ui.routes())
98	defer srv.Close()
99
100	resp, err := http.Get(srv.URL + "/api/v1/nodes?path=" + url.QueryEscape(root))
101	if err != nil {
102		t.Fatal(err)
103	}
104	defer resp.Body.Close()
105	if resp.StatusCode != http.StatusOK {
106		t.Fatalf("status = %d, want 200", resp.StatusCode)
107	}
108
109	var node nodeResponse
110	if err := json.NewDecoder(resp.Body).Decode(&node); err != nil {
111		t.Fatal(err)
112	}
113
114	if !node.Node.IsDir {
115		t.Error("root node should be a directory")
116	}
117	if len(node.Breadcrumbs) != 1 {
118		t.Errorf("breadcrumbs = %d, want 1", len(node.Breadcrumbs))
119	}
120	if len(node.Children) != 3 {
121		t.Fatalf("children = %d, want 3", len(node.Children))
122	}
123	// Default sort is by disk usage descending. Assert the returned order is
124	// monotonically non-increasing rather than depending on fixture specifics
125	// (sparse files can have near-zero disk usage regardless of apparent size).
126	for i := 1; i < len(node.Children); i++ {
127		if node.Children[i-1].Usage < node.Children[i].Usage {
128			t.Errorf("children not sorted by usage desc: %+v", node.Children)
129			break
130		}
131	}
132	for _, c := range node.Children {
133		if c.Size <= 0 {
134			t.Errorf("child %q has non-positive size", c.Name)
135		}
136	}
137}
138
139func TestNodesNested(t *testing.T) {
140	ui := newTestUI()
141	root := makeTree(t)
142	scan(t, ui, root)
143
144	srv := httptest.NewServer(ui.routes())
145	defer srv.Close()
146
147	sub := filepath.Join(root, "sub")
148	resp, err := http.Get(srv.URL + "/api/v1/nodes?path=" + url.QueryEscape(sub))
149	if err != nil {
150		t.Fatal(err)
151	}
152	defer resp.Body.Close()
153
154	var node nodeResponse
155	if err := json.NewDecoder(resp.Body).Decode(&node); err != nil {
156		t.Fatal(err)
157	}
158	if node.Node.Name != "sub" {
159		t.Errorf("node name = %q, want sub", node.Node.Name)
160	}
161	if len(node.Breadcrumbs) != 2 {
162		t.Errorf("breadcrumbs = %d, want 2 (root, sub)", len(node.Breadcrumbs))
163	}
164	if len(node.Children) != 1 || node.Children[0].Name != "nested.dat" {
165		t.Errorf("unexpected children: %+v", node.Children)
166	}
167}
168
169func TestNodesPathTraversalRejected(t *testing.T) {
170	ui := newTestUI()
171	root := makeTree(t)
172	scan(t, ui, root)
173
174	srv := httptest.NewServer(ui.routes())
175	defer srv.Close()
176
177	resp, err := http.Get(srv.URL + "/api/v1/nodes?path=" + url.QueryEscape("/etc"))
178	if err != nil {
179		t.Fatal(err)
180	}
181	defer resp.Body.Close()
182	if resp.StatusCode != http.StatusForbidden {
183		t.Errorf("status = %d, want 403", resp.StatusCode)
184	}
185}
186
187func TestNodesNotFound(t *testing.T) {
188	ui := newTestUI()
189	root := makeTree(t)
190	scan(t, ui, root)
191
192	srv := httptest.NewServer(ui.routes())
193	defer srv.Close()
194
195	missing := filepath.Join(root, "does-not-exist")
196	resp, err := http.Get(srv.URL + "/api/v1/nodes?path=" + url.QueryEscape(missing))
197	if err != nil {
198		t.Fatal(err)
199	}
200	defer resp.Body.Close()
201	if resp.StatusCode != http.StatusNotFound {
202		t.Errorf("status = %d, want 404", resp.StatusCode)
203	}
204}
205
206func TestParseSort(t *testing.T) {
207	cases := []struct {
208		sort, order string
209		wantBy      fs.SortBy
210		wantOrder   fs.SortOrder
211	}{
212		{"", "", fs.SortBySize, fs.SortDesc},
213		{"name", "asc", fs.SortByName, fs.SortAsc},
214		{"itemCount", "desc", fs.SortByItemCount, fs.SortDesc},
215		{"mtime", "asc", fs.SortByMtime, fs.SortAsc},
216		{"size", "asc", fs.SortBySize, fs.SortAsc},
217	}
218	for _, c := range cases {
219		gotBy, gotOrder := parseSort(c.sort, c.order)
220		if gotBy != c.wantBy || gotOrder != c.wantOrder {
221			t.Errorf("parseSort(%q,%q) = (%v,%v), want (%v,%v)",
222				c.sort, c.order, gotBy, gotOrder, c.wantBy, c.wantOrder)
223		}
224	}
225}
226
227func TestBrowserCommand(t *testing.T) {
228	cases := []struct {
229		goos, cmd string
230		wantName  string
231		wantArgs  []string
232	}{
233		{"darwin", "", "open", []string{"http://x"}},
234		{"windows", "", "rundll32", []string{"url.dll,FileProtocolHandler", "http://x"}},
235		{"linux", "", "xdg-open", []string{"http://x"}},
236		{"linux", "firefox", "firefox", []string{"http://x"}},
237		{"linux", "flatpak run org.mozilla.firefox", "flatpak", []string{"run", "org.mozilla.firefox", "http://x"}},
238	}
239	for _, c := range cases {
240		name, args, err := browserCommand(c.goos, "http://x", c.cmd)
241		if err != nil {
242			t.Fatalf("browserCommand error: %v", err)
243		}
244		if name != c.wantName {
245			t.Errorf("name = %q, want %q", name, c.wantName)
246		}
247		if len(args) != len(c.wantArgs) {
248			t.Fatalf("args = %v, want %v", args, c.wantArgs)
249		}
250		for i := range args {
251			if args[i] != c.wantArgs[i] {
252				t.Errorf("args[%d] = %q, want %q", i, args[i], c.wantArgs[i])
253			}
254		}
255	}
256}
257
258func TestSetCollapsePath(t *testing.T) {
259	ui := newTestUI()
260	if ui.collapsePath {
261		t.Fatal("collapsePath should default to false")
262	}
263	ui.SetCollapsePath(true)
264	if !ui.collapsePath {
265		t.Error("SetCollapsePath(true) did not set the field")
266	}
267}
268
269func TestCreateUIDefaultListenAddr(t *testing.T) {
270	ui := CreateUI(io.Discard, "", false, "", true, true, true, true)
271	if ui.listenAddr != "localhost:0" {
272		t.Errorf("listenAddr = %q, want localhost:0", ui.listenAddr)
273	}
274	if !ui.UseColors || !ui.ShowApparentSize || !ui.ShowRelativeSize || !ui.UseSIPrefix {
275		t.Error("display options not propagated to embedded common.UI")
276	}
277}
278
279func TestListDevicesAndHandleDevices(t *testing.T) {
280	ui := newTestUI()
281
282	devices := device.Devices{
283		&device.Device{
284			Name:       "/dev/sda1",
285			MountPoint: "/",
286			Fstype:     "ext4",
287			Size:       1000,
288			Free:       400,
289		},
290	}
291	getter := testdev.DevicesInfoGetterMock{Devices: devices}
292
293	if err := ui.ListDevices(getter); err != nil {
294		t.Fatalf("ListDevices: %v", err)
295	}
296
297	srv := httptest.NewServer(ui.routes())
298	defer srv.Close()
299
300	resp, err := http.Get(srv.URL + "/api/v1/devices")
301	if err != nil {
302		t.Fatal(err)
303	}
304	defer resp.Body.Close()
305	if resp.StatusCode != http.StatusOK {
306		t.Fatalf("status = %d, want 200", resp.StatusCode)
307	}
308
309	var out []deviceJSON
310	if err := json.NewDecoder(resp.Body).Decode(&out); err != nil {
311		t.Fatal(err)
312	}
313	if len(out) != 1 {
314		t.Fatalf("devices = %d, want 1", len(out))
315	}
316	d := out[0]
317	if d.Name != "/dev/sda1" || d.MountPoint != "/" || d.Fstype != "ext4" ||
318		d.Size != 1000 || d.Free != 400 {
319		t.Errorf("unexpected device payload: %+v", d)
320	}
321}
322
323func TestHandleDevicesEmpty(t *testing.T) {
324	ui := newTestUI()
325
326	srv := httptest.NewServer(ui.routes())
327	defer srv.Close()
328
329	resp, err := http.Get(srv.URL + "/api/v1/devices")
330	if err != nil {
331		t.Fatal(err)
332	}
333	defer resp.Body.Close()
334
335	var out []deviceJSON
336	if err := json.NewDecoder(resp.Body).Decode(&out); err != nil {
337		t.Fatal(err)
338	}
339	if len(out) != 0 {
340		t.Errorf("devices = %d, want 0", len(out))
341	}
342}
343
344const sampleReport = `
345	[1,2,{"progname":"gdu","progver":"development","timestamp":1626806293},
346	[{"name":"/home/xxx","mtime":1629333600},
347	{"name":"gdu.json","asize":33805233,"dsize":33808384},
348	[{"name":"app"},
349	{"name":"app.go","asize":4638,"dsize":8192},
350	{"name":"app_test.go","asize":4974,"dsize":8192}],
351	{"name":"main.go","asize":3205,"dsize":4096,"mtime":1629333600}]]
352`
353
354func TestReadAnalysis(t *testing.T) {
355	ui := newTestUI()
356
357	if err := ui.ReadAnalysis(strings.NewReader(sampleReport)); err != nil {
358		t.Fatalf("ReadAnalysis: %v", err)
359	}
360
361	status := ui.buildStatus()
362	if status.State != "done" {
363		t.Errorf("state = %q, want done", status.State)
364	}
365	if status.RootPath != "/home/xxx" {
366		t.Errorf("rootPath = %q, want /home/xxx", status.RootPath)
367	}
368
369	node, err := ui.findNode("/home/xxx")
370	if err != nil {
371		t.Fatalf("findNode: %v", err)
372	}
373	if node.GetName() != "xxx" {
374		t.Errorf("root name = %q, want xxx", node.GetName())
375	}
376	if !node.IsDir() {
377		t.Error("root should be a directory")
378	}
379}
380
381func TestReadAnalysisError(t *testing.T) {
382	ui := newTestUI()
383
384	err := ui.ReadAnalysis(strings.NewReader("not valid json"))
385	if err == nil {
386		t.Fatal("expected error for invalid input")
387	}
388
389	status := ui.buildStatus()
390	if status.State != "error" {
391		t.Errorf("state = %q, want error", status.State)
392	}
393	if status.Error == "" {
394		t.Error("expected non-empty error message in status")
395	}
396	if ui.scanning {
397		t.Error("scanning flag should be cleared after error")
398	}
399}
400
401func TestReadFromStorage(t *testing.T) {
402	fin := testdir.CreateTestDir()
403	defer fin()
404
405	storagePath := t.TempDir() + "/badger"
406
407	// Populate the storage with a stored analysis.
408	a := analyze.CreateStoredAnalyzer(storagePath)
409	dir := a.AnalyzeDir(
410		"test_dir",
411		func(_, _ string) bool { return false },
412		func(_ string) bool { return false },
413	)
414	a.GetDone().Wait()
415	dir.UpdateStats(make(fs.HardLinkedItems))
416
417	ui := newTestUI()
418	if err := ui.ReadFromStorage(storagePath, "test_dir"); err != nil {
419		t.Fatalf("ReadFromStorage: %v", err)
420	}
421
422	status := ui.buildStatus()
423	if status.State != "done" {
424		t.Errorf("state = %q, want done", status.State)
425	}
426
427	node, err := ui.findNode("test_dir")
428	if err != nil {
429		t.Fatalf("findNode: %v", err)
430	}
431	if node.GetName() != "test_dir" {
432		t.Errorf("root name = %q, want test_dir", node.GetName())
433	}
434	if node.GetItemCount() != 5 {
435		t.Errorf("itemCount = %d, want 5", node.GetItemCount())
436	}
437}
438
439func TestReadFromStorageError(t *testing.T) {
440	ui := newTestUI()
441	// A non-existent path yields a badger read error.
442	err := ui.ReadFromStorage(t.TempDir()+"/badger", "missing_dir")
443	if err == nil {
444		t.Fatal("expected error reading a missing dir from storage")
445	}
446}
447
448func TestBuildStatusStates(t *testing.T) {
449	// Fresh UI: no topDir yet, not scanning -> reported as scanning.
450	ui := newTestUI()
451	if got := ui.buildStatus().State; got != "scanning" {
452		t.Errorf("initial state = %q, want scanning", got)
453	}
454
455	// Explicit scanning flag.
456	ui.mu.Lock()
457	ui.scanning = true
458	ui.mu.Unlock()
459	if got := ui.buildStatus().State; got != "scanning" {
460		t.Errorf("scanning state = %q, want scanning", got)
461	}
462}
463
464func TestStatusJSON(t *testing.T) {
465	ui := newTestUI()
466	ui.mu.Lock()
467	ui.topDirPath = "/tmp/root"
468	ui.progress = common.CurrentProgress{
469		CurrentItemName: "current",
470		ItemCount:       3,
471		TotalUsage:      100,
472	}
473	ui.mu.Unlock()
474
475	raw := ui.statusJSON()
476
477	var status statusResponse
478	if err := json.Unmarshal([]byte(raw), &status); err != nil {
479		t.Fatalf("statusJSON produced invalid JSON: %v", err)
480	}
481	if status.RootPath != "/tmp/root" {
482		t.Errorf("rootPath = %q, want /tmp/root", status.RootPath)
483	}
484	if status.Progress.ItemCount != 3 || status.Progress.TotalUsage != 100 ||
485		status.Progress.CurrentItem != "current" {
486		t.Errorf("unexpected progress: %+v", status.Progress)
487	}
488}
489
490func TestHandleEventsSSE(t *testing.T) {
491	ui := newTestUI()
492	ui.mu.Lock()
493	ui.topDirPath = "/tmp/root"
494	ui.mu.Unlock()
495
496	srv := httptest.NewServer(ui.routes())
497	defer srv.Close()
498
499	req, err := http.NewRequest(http.MethodGet, srv.URL+"/api/v1/events", nil)
500	if err != nil {
501		t.Fatal(err)
502	}
503	resp, err := http.DefaultClient.Do(req)
504	if err != nil {
505		t.Fatal(err)
506	}
507	defer resp.Body.Close()
508
509	if ct := resp.Header.Get("Content-Type"); ct != "text/event-stream" {
510		t.Errorf("content-type = %q, want text/event-stream", ct)
511	}
512
513	// The initial state is pushed immediately on connect.
514	reader := bufio.NewReader(resp.Body)
515	line, err := readSSEData(t, reader)
516	if err != nil {
517		t.Fatalf("reading initial SSE frame: %v", err)
518	}
519	var status statusResponse
520	if err := json.Unmarshal([]byte(line), &status); err != nil {
521		t.Fatalf("initial SSE frame not valid JSON (%q): %v", line, err)
522	}
523	if status.RootPath != "/tmp/root" {
524		t.Errorf("initial SSE rootPath = %q, want /tmp/root", status.RootPath)
525	}
526
527	// A subsequent publish is delivered to the connected subscriber.
528	ui.hub.publish(`{"state":"custom"}`)
529	line, err = readSSEData(t, reader)
530	if err != nil {
531		t.Fatalf("reading published SSE frame: %v", err)
532	}
533	if line != `{"state":"custom"}` {
534		t.Errorf("published frame = %q", line)
535	}
536}
537
538// readSSEData reads lines until it finds a `data: ` frame and returns its payload.
539func readSSEData(t *testing.T, r *bufio.Reader) (string, error) {
540	t.Helper()
541	deadline := time.Now().Add(3 * time.Second)
542	for time.Now().Before(deadline) {
543		line, err := r.ReadString('\n')
544		if err != nil {
545			return "", err
546		}
547		line = strings.TrimRight(line, "\r\n")
548		if strings.HasPrefix(line, "data: ") {
549			return strings.TrimPrefix(line, "data: "), nil
550		}
551	}
552	return "", io.EOF
553}
554
555func TestHub(t *testing.T) {
556	h := newHub()
557
558	ch, last := h.subscribe()
559	if last != "" {
560		t.Errorf("last = %q, want empty before any publish", last)
561	}
562
563	h.publish("hello")
564	select {
565	case msg := <-ch:
566		if msg != "hello" {
567			t.Errorf("received %q, want hello", msg)
568		}
569	case <-time.After(time.Second):
570		t.Fatal("did not receive published message")
571	}
572
573	// A late subscriber gets the most recent message via `last`.
574	ch2, last2 := h.subscribe()
575	if last2 != "hello" {
576		t.Errorf("late subscriber last = %q, want hello", last2)
577	}
578
579	h.unsubscribe(ch)
580	// unsubscribe closes the channel.
581	if _, open := <-ch; open {
582		t.Error("channel should be closed after unsubscribe")
583	}
584
585	// Unsubscribing twice is a no-op and must not panic.
586	h.unsubscribe(ch)
587
588	h.unsubscribe(ch2)
589}
590
591func TestHubPublishDoesNotBlockOnFullSubscriber(t *testing.T) {
592	h := newHub()
593	ch, _ := h.subscribe()
594	defer h.unsubscribe(ch)
595
596	// The subscriber channel is buffered to 8; publishing more than the buffer
597	// must not block because publish drops on a full channel.
598	for i := 0; i < 100; i++ {
599		h.publish("msg")
600	}
601}
602
603func TestWarnIfRemote(t *testing.T) {
604	cases := []struct {
605		name     string
606		addr     net.Addr
607		wantWarn bool
608	}{
609		{
610			name:     "loopback ipv4",
611			addr:     &net.TCPAddr{IP: net.ParseIP("127.0.0.1"), Port: 8080},
612			wantWarn: false,
613		},
614		{
615			name:     "loopback ipv6",
616			addr:     &net.TCPAddr{IP: net.ParseIP("::1"), Port: 8080},
617			wantWarn: false,
618		},
619		{
620			name:     "remote",
621			addr:     &net.TCPAddr{IP: net.ParseIP("0.0.0.0"), Port: 8080},
622			wantWarn: true,
623		},
624		{
625			name:     "lan",
626			addr:     &net.TCPAddr{IP: net.ParseIP("192.168.1.10"), Port: 8080},
627			wantWarn: true,
628		},
629	}
630	for _, c := range cases {
631		t.Run(c.name, func(t *testing.T) {
632			var buf bytes.Buffer
633			warnIfRemote(&buf, c.addr)
634			warned := strings.Contains(buf.String(), "WARNING")
635			if warned != c.wantWarn {
636				t.Errorf("warned = %v, want %v (output: %q)", warned, c.wantWarn, buf.String())
637			}
638		})
639	}
640}
641
642func TestToNodeJSONFlag(t *testing.T) {
643	parent := &analyze.Dir{File: &analyze.File{Name: "root"}}
644
645	// A file with a meaningful flag exposes it in the JSON payload.
646	flagged := &analyze.File{Name: "denied", Flag: '!', Parent: parent}
647	if got := toNodeJSON(flagged).Flag; got != "!" {
648		t.Errorf("flag = %q, want !", got)
649	}
650
651	// A blank flag (space) is omitted.
652	blank := &analyze.File{Name: "ok", Flag: ' ', Parent: parent}
653	if got := toNodeJSON(blank).Flag; got != "" {
654		t.Errorf("space flag = %q, want empty", got)
655	}
656
657	// A zero flag is also omitted.
658	zero := &analyze.File{Name: "zero", Parent: parent}
659	if got := toNodeJSON(zero).Flag; got != "" {
660		t.Errorf("zero flag = %q, want empty", got)
661	}
662}
663
664// TestToNodeJSONItemCount pins the wire format to the displayed item count, so
665// the browser shows the same number the API sorts by.
666func TestToNodeJSONItemCount(t *testing.T) {
667	parent := &analyze.Dir{File: &analyze.File{Name: "root"}}
668
669	// A directory reports what it contains, not counting itself.
670	dir := &analyze.Dir{File: &analyze.File{Name: "sub", Parent: parent}, ItemCount: 4}
671	if got := toNodeJSON(dir).ItemCount; got != 3 {
672		t.Errorf("dir itemCount = %d, want 3", got)
673	}
674
675	// A file counts itself.
676	file := &analyze.File{Name: "leaf", Parent: parent}
677	if got := toNodeJSON(file).ItemCount; got != 1 {
678		t.Errorf("file itemCount = %d, want 1", got)
679	}
680}
681
682func TestAnalyzePathWithParent(t *testing.T) {
683	ui := newTestUI()
684	root := makeTree(t)
685
686	// First scan the root so we have a parent dir in the tree.
687	scan(t, ui, root)
688
689	parent, err := ui.findNode(root)
690	if err != nil {
691		t.Fatalf("findNode(root): %v", err)
692	}
693
694	// Re-scan the "sub" directory into the existing parent. This exercises the
695	// parentDir != nil branch: SetParent / RemoveFileByName / AddFile. The
696	// re-scanned dir replaces the old child in the parent and keeps the same
697	// top-level tree root.
698	sub := filepath.Join(root, "sub")
699	if err := ui.AnalyzePath(sub, parent); err != nil {
700		t.Fatalf("AnalyzePath(sub, parent): %v", err)
701	}
702	waitDone(t, ui)
703
704	// The refreshed "sub" child is present in the parent and points back to it.
705	child, found := childByName(parent, "sub")
706	if !found {
707		t.Fatal("re-scanned sub not found under parent")
708	}
709	if child.GetName() != "sub" {
710		t.Errorf("child name = %q, want sub", child.GetName())
711	}
712	if child.GetParent() != parent {
713		t.Error("re-scanned sub should have its parent set to the original root")
714	}
715	if child.GetItemCount() < 1 {
716		t.Error("re-scanned sub should have counted its files")
717	}
718}
719
720func waitDone(t *testing.T, ui *UI) {
721	t.Helper()
722	deadline := time.Now().Add(5 * time.Second)
723	for time.Now().Before(deadline) {
724		if ui.buildStatus().State == "done" {
725			return
726		}
727		time.Sleep(10 * time.Millisecond)
728	}
729	t.Fatal("scan did not complete in time")
730}
731
732func TestStaticHandlerServesIndex(t *testing.T) {
733	srv := httptest.NewServer(staticHandler())
734	defer srv.Close()
735
736	// Root path serves the SPA entry point.
737	resp, err := http.Get(srv.URL + "/")
738	if err != nil {
739		t.Fatal(err)
740	}
741	defer resp.Body.Close()
742	if resp.StatusCode != http.StatusOK {
743		t.Errorf("root status = %d, want 200", resp.StatusCode)
744	}
745
746	// An unknown non-asset path falls back to index.html (client-side routing).
747	resp2, err := http.Get(srv.URL + "/some/spa/route")
748	if err != nil {
749		t.Fatal(err)
750	}
751	defer resp2.Body.Close()
752	if resp2.StatusCode != http.StatusOK {
753		t.Errorf("fallback status = %d, want 200", resp2.StatusCode)
754	}
755	body, _ := io.ReadAll(resp2.Body)
756	if !strings.Contains(strings.ToLower(string(body)), "<!doctype html") &&
757		!strings.Contains(strings.ToLower(string(body)), "<html") {
758		t.Errorf("fallback body does not look like the SPA index: %q", string(body[:min(80, len(body))]))
759	}
760}