package render import ( "context" "encoding/json" "errors" "fmt" "net/url" "strings" "testing" "time" ) var testSiteURL, _ = url.Parse("http://127.0.0.1:4000/") // Every failed load is one of three kinds, or not reported. func TestClassifyLoad(t *testing.T) { for _, c := range []struct { url, kind string status int netErr bool want string }{ {"https://cdn.example.com/lib.js", "Script", 0, true, LoadExternalBlocked}, {"http://1.1.1.1/x.css", "Stylesheet", 0, true, LoadExternalBlocked}, {"http://[2606:4700::1111]/x", "Fetch", 0, true, LoadExternalBlocked}, // Another port of the sandbox's own loopback is not the site. {"http://127.0.0.1:4001/x", "XHR", 0, true, LoadExternalBlocked}, {"https://127.0.0.1:4000/x", "Image", 0, true, LoadExternalBlocked}, {"http://cdn.example.com/landing", "Document", 0, true, LoadExternalBlocked}, {"http://127.0.0.1:4000/missing.png", "Image", 404, false, LoadNotFound}, {"http://127.0.0.1:4000/missing/", "Document", 404, false, LoadNotFound}, {"http://127.0.0.1:4000/broken", "Fetch", 500, false, LoadNotFound}, {"https://fonts.gstatic.com/a.woff2", "Font", 0, true, LoadFont}, {"http://127.0.0.1:4000/f.woff2", "Font", 404, false, LoadFont}, // Not failures, or not the page's: nothing reported. {"http://127.0.0.1:4000/ok.png", "Image", 200, false, ""}, {"http://127.0.0.1:4000/moved", "Document", 301, false, ""}, {"http://127.0.0.1:4000/csp-blocked.js", "Script", 0, true, ""}, {"data:text/plain,x", "Image", 0, true, ""}, {"chrome-error://chromewebdata/", "Document", 0, true, ""}, {"blob:http://127.0.0.1:4000/1", "Fetch", 0, true, ""}, {"::not a url", "Script", 0, true, ""}, } { got, ok := classifyLoad(testSiteURL, c.url, c.kind, c.status, c.netErr) if got != c.want || ok != (c.want != "") { t.Errorf("%s %s %d %v: %q %v, want %q", c.url, c.kind, c.status, c.netErr, got, ok, c.want) } } } func raw(v any) json.RawMessage { b, _ := json.Marshal(v) return b } func testPage() (*pageState, context.Context) { ctx, cancel := context.WithCancelCause(context.Background()) p := newPageState(testSiteURL, "S1", cancel) p.setMain("F1") return p, ctx } // Console errors and failed loads are bounded and counted past the // bound; a failed load already listed is not listed or counted again; only errors count; a page's later events are not // collected once it is captured. func TestPageStateBounds(t *testing.T) { p, _ := testPage() for i := 0; i < 50; i++ { p.event("Runtime.consoleAPICalled", raw(map[string]any{"type": "error", "args": []any{ map[string]any{"type": "string", "value": fmt.Sprintf("bad\n\x1b[31m %d\u202e", i)}, map[string]any{"type": "number", "value": 7, "description": "7"}, map[string]any{"type": "object", "description": "Object"}, }})) } p.event("Runtime.consoleAPICalled", raw(map[string]any{"type": "log", "args": []any{map[string]any{"type": "string", "value": "fine"}}})) for i := 0; i < 40; i++ { id := fmt.Sprint("r", i) p.event("Network.requestWillBeSent", raw(map[string]any{"requestId": id, "type": "Script", "request": map[string]any{"url": fmt.Sprintf("https://cdn%d.example.com/x.js", i)}})) p.event("Network.loadingFailed", raw(map[string]any{"requestId": id, "type": "Script", "errorText": "net::ERR_NAME_NOT_RESOLVED"})) // The same failure again is not another entry. p.event("Network.requestWillBeSent", raw(map[string]any{"requestId": id + "b", "type": "Script", "request": map[string]any{"url": fmt.Sprintf("https://cdn%d.example.com/x.js", i)}})) p.event("Network.loadingFailed", raw(map[string]any{"requestId": id + "b", "type": "Script"})) } var r PageReport p.finish(&r) if len(r.ConsoleErrors) != maxConsoleErrors || r.ConsoleErrorsOmitted != 30 || r.ConsoleErrors[0] != "bad [31m 0 7 Object" { t.Fatalf("console %q, %d omitted", r.ConsoleErrors, r.ConsoleErrorsOmitted) } if len(r.FailedLoads) != maxFailedLoads || r.FailedLoadsOmitted != 20 || r.FailedLoads[0] != (FailedLoad{Kind: LoadExternalBlocked, URL: "https://cdn0.example.com/x.js"}) { t.Fatalf("failed %+v, %d omitted", r.FailedLoads, r.FailedLoadsOmitted) } p.event("Runtime.exceptionThrown", raw(map[string]any{"exceptionDetails": map[string]any{"text": "Uncaught"}})) p.event("Network.responseReceived", raw(map[string]any{"requestId": "late", "type": "Fetch", "response": map[string]any{"url": "http://127.0.0.1:4000/late", "status": 404}})) var after PageReport p.finish(&after) if after.ConsoleErrorsOmitted != 30 || after.FailedLoadsOmitted != 20 { t.Fatalf("collected after the capture: %+v", after) } } // An exception is its text and the first line of its description; a // cancelled request, one never seen, and one whose id is oversize are // not reported; requests in flight are bounded. func TestPageStateEvents(t *testing.T) { p, _ := testPage() p.event("Runtime.exceptionThrown", raw(map[string]any{"exceptionDetails": map[string]any{"text": "Uncaught", "exception": map[string]any{"type": "object", "description": "Error: boom\n at x.html:3"}}})) p.event("Network.requestWillBeSent", raw(map[string]any{"requestId": "c", "type": "Image", "request": map[string]any{"url": "https://x.example/a.png"}})) p.event("Network.loadingFailed", raw(map[string]any{"requestId": "c", "canceled": true})) p.event("Network.loadingFailed", raw(map[string]any{"requestId": "never-sent"})) long := strings.Repeat("i", maxRequestID+1) p.event("Network.requestWillBeSent", raw(map[string]any{"requestId": long, "type": "Image", "request": map[string]any{"url": "https://x.example/b.png"}})) p.event("Network.loadingFailed", raw(map[string]any{"requestId": long})) // A same-site redirect to another host keeps the id: the failure is // the new URL's. p.event("Network.requestWillBeSent", raw(map[string]any{"requestId": "rd", "type": "Script", "request": map[string]any{"url": "http://127.0.0.1:4000/go"}})) p.event("Network.requestWillBeSent", raw(map[string]any{"requestId": "rd", "type": "Script", "request": map[string]any{"url": "https://cdn.example.com/went.js"}, "redirectResponse": map[string]any{"status": 302}})) p.event("Network.loadingFailed", raw(map[string]any{"requestId": "rd", "type": "Script"})) p.event("Network.responseReceived", raw(map[string]any{"requestId": "f", "type": "Font", "response": map[string]any{"url": "http://127.0.0.1:4000/f.woff2", "status": 404}})) for i := 0; i < 3*maxTracked; i++ { p.event("Network.requestWillBeSent", raw(map[string]any{"requestId": fmt.Sprint("q", i), "request": map[string]any{"url": "http://127.0.0.1:4000/q"}})) } if len(p.requests) > maxTracked { t.Fatalf("%d requests tracked", len(p.requests)) } var r PageReport p.finish(&r) if len(r.ConsoleErrors) != 1 || r.ConsoleErrors[0] != "Uncaught Error: boom" { t.Fatalf("console %q", r.ConsoleErrors) } want := []FailedLoad{{Kind: LoadExternalBlocked, URL: "https://cdn.example.com/went.js"}, {Kind: LoadFont, URL: "http://127.0.0.1:4000/f.woff2", Status: 404}} if fmt.Sprint(r.FailedLoads) != fmt.Sprint(want) { t.Fatalf("failed %+v", r.FailedLoads) } } // Load is the main frame's current document's: an earlier document's, // another frame's or a load before the navigation does not count; a // new document starts the wait again; idle ends it early, and without // idle it ends IdleWait after the load. A crash ends it at once. func TestPageStateWaitsForLoad(t *testing.T) { waits := func(p *pageState, ctx context.Context, d time.Duration) error { ctx, cancel := context.WithTimeout(ctx, d) defer cancel() return p.waitLoaded(ctx) } p, ctx := testPage() nav := func(loader string) { p.event("Page.frameNavigated", raw(map[string]any{"frame": map[string]any{"id": "F1", "loaderId": loader}})) } life := func(frame, loader, name string) { p.event("Page.lifecycleEvent", raw(map[string]any{"frameId": frame, "loaderId": loader, "name": name})) } life("F1", "L0", "load") life("F1", "L0", "networkIdle") nav("L1") life("F1", "L0", "load") life("F1", "L0", "networkIdle") life("F2", "L1", "load") life("F2", "L1", "networkIdle") if err := waits(p, ctx, 100*time.Millisecond); !errors.Is(err, context.DeadlineExceeded) { t.Fatalf("loaded early: %v", err) } life("F1", "L1", "load") nav("L2") if err := waits(p, ctx, 100*time.Millisecond); !errors.Is(err, context.DeadlineExceeded) { t.Fatalf("an earlier document's load counted: %v", err) } // A subframe's navigation is not a new main document. p.event("Page.frameNavigated", raw(map[string]any{"frame": map[string]any{"id": "F2", "parentId": "F1", "loaderId": "L9"}})) life("F1", "L2", "load") life("F1", "L2", "networkIdle") if err := waits(p, ctx, 100*time.Millisecond); err != nil { t.Fatalf("idle: %v", err) } // Without idle the wait ends IdleWait after load. p2, ctx2 := testPage() p2.event("Page.frameNavigated", raw(map[string]any{"frame": map[string]any{"id": "F1", "loaderId": "L1"}})) p2.event("Page.lifecycleEvent", raw(map[string]any{"frameId": "F1", "loaderId": "L1", "name": "load"})) p2.mu.Lock() p2.loadedAt = time.Now().Add(-IdleWait + 200*time.Millisecond) p2.mu.Unlock() began := time.Now() if err := waits(p2, ctx2, 3*time.Second); err != nil || time.Since(began) > time.Second { t.Fatalf("no idle: %v after %v", err, time.Since(began)) } p3, ctx3 := testPage() go func() { time.Sleep(50 * time.Millisecond) p3.event("Inspector.targetCrashed", nil) }() if err := waits(p3, ctx3, 3*time.Second); !errors.Is(err, errRendererCrashed) { t.Fatalf("crash: %v", err) } } func axn(id, parent, role, name string, ignored bool, children ...string) axNode { n := axNode{NodeID: id, ParentID: parent, Ignored: ignored, ChildIDs: children} if role != "" { n.Role = &axValue{Value: raw(role)} } if name != "" { n.Name = &axValue{Value: raw(name)} } return n } // The outline is the tree's meaningful nodes, indented, bounded, and // safe from cycles and lies in the ids. func TestOutline(t *testing.T) { nodes := []axNode{ axn("1", "", "RootWebArea", "Shop", false, "2", "9"), axn("2", "1", "generic", "", false, "3", "5"), axn("3", "2", "heading", "Welcome\n\u202ehome", false, "4"), axn("4", "3", "StaticText", "Welcome home", false), axn("5", "2", "paragraph", "", false, "6", "6", "1", "5", "missing"), axn("6", "5", "StaticText", "Some words", false, "7"), axn("7", "6", "InlineTextBox", "Some words", false), axn("9", "1", "button", "Hidden", true), } text, cut := outline(nodes, maxOutline) want := "RootWebArea \"Shop\"\n heading \"Welcome home\"\n paragraph\n StaticText \"Some words\"\n" if text != want || cut { t.Fatalf("outline %q %v, want %q", text, cut, want) } // A long tree is cut at whole lines. big := []axNode{axn("r", "", "list", "", false)} for i := 0; i < 1000; i++ { id := fmt.Sprint("i", i) big[0].ChildIDs = append(big[0].ChildIDs, id) big = append(big, axn(id, "r", "listitem", strings.Repeat("x", 300), false)) } text, cut = outline(big, maxOutline) if !cut || len(text) > maxOutline || !strings.HasSuffix(text, "\n") { t.Fatalf("cut %v, %d bytes", cut, len(text)) } for _, line := range strings.Split(strings.TrimSuffix(text, "\n"), "\n") { if len(line) > 2+len("listitem")+maxName+3 { t.Fatalf("line of %d bytes", len(line)) } } if text, _ := outline(nil, maxOutline); text != "" { t.Fatalf("empty tree %q", text) } // Every node claims a parent: no root, no outline, no loop. loop := []axNode{axn("a", "b", "list", "", false, "b"), axn("b", "a", "list", "", false, "a")} if text, _ := outline(loop, maxOutline); text != "" { t.Fatalf("loop %q", text) } } // Page text is valid UTF-8 with no control or format characters, one // space for any run of space, within its bound, cut at a rune. func TestClean(t *testing.T) { for _, c := range []struct { in string max int want string }{ {"plain", 10, "plain"}, {" a \n\t b ", 10, "a b"}, {"a\x00b\x1bc\u202ed\u200be", 10, "a b c d e"}, {"bad \xff utf8", 20, "bad utf8"}, {"héllo", 2, "h"}, {"héllo", 3, "hé"}, {"ab cd", 3, "ab"}, {"", 5, ""}, } { if got := clean(c.in, c.max); got != c.want { t.Errorf("clean(%q, %d) = %q, want %q", c.in, c.max, got, c.want) } } } // The report's JSON is a fixed schema: these names, empty lists as []. func TestReportSchema(t *testing.T) { r := Report{Schema: ReportSchema, ElapsedMS: 1200, Pages: []PageReport{{ Path: "/", Viewport: Phone, Width: 390, Height: 844, Capture: "page-1.png", CaptureWidth: 390, CaptureHeight: 844, Title: "Shop", ConsoleErrors: []string{"boom"}, FailedLoads: []FailedLoad{{Kind: LoadNotFound, URL: "http://127.0.0.1:1/x", Status: 404}, {Kind: LoadFont, URL: "https://f.example/a.woff2"}}, BrokenLinks: []string{}, LinksChecked: 2, Outline: "RootWebArea \"Shop\"\n", }}} got, err := json.Marshal(r) if err != nil { t.Fatal(err) } want := `{"schema":1,"elapsed_ms":1200,"pages":[{"path":"/","viewport":"phone","width":390,"height":844,"full_page":false,"capture":"page-1.png","capture_width":390,"capture_height":844,"title":"Shop","console_errors":["boom"],"console_errors_omitted":0,"failed_loads":[{"kind":"not found","url":"http://127.0.0.1:1/x","status":404},{"kind":"font","url":"https://f.example/a.woff2"}],"failed_loads_omitted":0,"broken_links":[],"broken_links_omitted":0,"links_checked":2,"outline":"RootWebArea \"Shop\"\n","outline_cut":false}]}` if string(got) != want { t.Fatalf("report\n%s\nwant\n%s", got, want) } r.Error = CodeTimeout if got, _ := json.Marshal(r); !strings.HasPrefix(string(got), `{"schema":1,"error":"timeout",`) { t.Fatalf("with error %s", got) } } // Only the fixed viewports and plain site paths are rendered, at most // MaxPages a call. func TestCheckPages(t *testing.T) { good := Page{Path: "/a/b.html?x=1", Viewport: Tablet} if err := checkPages([]Page{good}); err != nil { t.Fatal(err) } for _, v := range []Viewport{Phone, Tablet, Desktop} { if w, h, ok := v.Size(); !ok || w == 0 || h == 0 { t.Errorf("%s: %d %d %v", v, w, h, ok) } } if w, h, _ := Phone.Size(); w != 390 || h != 844 { t.Errorf("phone %dx%d", w, h) } if w, h, _ := Tablet.Size(); w != 834 || h != 1194 { t.Errorf("tablet %dx%d", w, h) } if w, h, _ := Desktop.Size(); w != 1440 || h != 900 { t.Errorf("desktop %dx%d", w, h) } seven := make([]Page, MaxPages+1) for i := range seven { seven[i] = good } for name, pages := range map[string][]Page{ "none": nil, "seven": seven, "viewport": {{Path: "/", Viewport: "watch"}}, "relative": {{Path: "a.html", Viewport: Phone}}, "host": {{Path: "//evil.example/", Viewport: Phone}}, "scheme": {{Path: "http://evil.example/", Viewport: Phone}}, "fragment": {{Path: "/#x", Viewport: Phone}}, "space": {{Path: "/a b", Viewport: Phone}}, "control": {{Path: "/a\nb", Viewport: Phone}}, "backslash": {{Path: "/\\evil.example", Viewport: Phone}}, "non-ascii": {{Path: "/é", Viewport: Phone}}, "long": {{Path: "/" + strings.Repeat("a", 1024), Viewport: Phone}}, "empty": {{Path: "", Viewport: Phone}}, } { if checkPages(pages) == nil { t.Errorf("%s: accepted", name) } } }