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