package render import ( "bytes" "context" "encoding/json" "errors" "image" "image/png" "os" "path/filepath" "strings" "testing" "time" ) const fakeSite = "http://127.0.0.1:4000/" func pngOf(t *testing.T, w, h int) []byte { t.Helper() var b bytes.Buffer if err := png.Encode(&b, image.NewGray(image.Rect(0, 0, w, h))); err != nil { t.Fatal(err) } return b.Bytes() } // fakeBrowser answers the driver's calls as Chromium does, with hooks a // test sets: what a page's navigation sends, what its capture is. When // only is set the hooks apply only to the page whose URL ends with it. type fakeBrowser struct { t *testing.T only string // afterNavigate sends the page's events; nil is a page that loads. afterNavigate func(p *peer) // shot is the capture for a clip (0 by 0 for the viewport); nil is // a PNG of the size asked for. shot func(clipW, clipH float64) []byte // links is Runtime.evaluate's value. links any // contentHeight is Page.getLayoutMetrics's. contentHeight float64 clips []map[string]any url string } func (f *fakeBrowser) hooked() bool { return f.only == "" || strings.HasSuffix(f.url, f.only) } func (f *fakeBrowser) handle(p *peer, c peerCall) { var params map[string]any json.Unmarshal(c.Params, ¶ms) switch c.Method { case "Target.createTarget": p.reply(c, map[string]any{"targetId": "T1"}) case "Target.attachToTarget": p.reply(c, map[string]any{"sessionId": "S1"}) case "Page.getFrameTree": p.reply(c, map[string]any{"frameTree": map[string]any{"frame": map[string]any{"id": "F1", "loaderId": "L0"}}}) case "Page.navigate": f.url, _ = params["url"].(string) p.reply(c, map[string]any{"frameId": "F1", "loaderId": "L1"}) if f.afterNavigate != nil && f.hooked() { f.afterNavigate(p) return } loads(p, "L1") case "Page.getLayoutMetrics": p.reply(c, map[string]any{"cssContentSize": map[string]any{"width": 1440, "height": f.contentHeight}}) case "Page.captureScreenshot": var w, h float64 = 1440, 900 if clip, ok := params["clip"].(map[string]any); ok { f.clips = append(f.clips, clip) w, h = clip["width"].(float64), clip["height"].(float64) } data := pngOf(f.t, int(w), int(h)) if f.shot != nil && f.hooked() { data = f.shot(w, h) } p.reply(c, map[string]any{"data": data}) case "Page.createIsolatedWorld": p.reply(c, map[string]any{"executionContextId": 7}) case "Runtime.evaluate": links := f.links if links == nil { links = map[string]any{"title": "Shop", "checked": 2, "broken": []string{}} } p.reply(c, map[string]any{"result": map[string]any{"type": "object", "value": links}}) case "Accessibility.getFullAXTree": p.reply(c, map[string]any{"nodes": []any{ map[string]any{"nodeId": "1", "role": map[string]any{"value": "RootWebArea"}, "name": map[string]any{"value": "Shop"}, "childIds": []string{"2"}}, map[string]any{"nodeId": "2", "parentId": "1", "role": map[string]any{"value": "heading"}, "name": map[string]any{"value": "Hello"}}, }}) default: p.reply(c, map[string]any{}) } } // loads sends a document's commit, load and network idle. func loads(p *peer, loader string) { p.event("S1", "Page.frameNavigated", map[string]any{"frame": map[string]any{"id": "F1", "loaderId": loader, "url": fakeSite}}) p.event("S1", "Page.lifecycleEvent", map[string]any{"frameId": "F1", "loaderId": loader, "name": "load"}) p.event("S1", "Page.lifecycleEvent", map[string]any{"frameId": "F1", "loaderId": loader, "name": "networkIdle"}) } func runDrive(t *testing.T, f *fakeBrowser, timeout time.Duration, pages ...Page) (*Report, string, *peer, error) { t.Helper() p := newPeer(t, f.handle) dir := t.TempDir() out, err := os.OpenRoot(dir) if err != nil { t.Fatal(err) } defer out.Close() ctx, cancel := context.WithTimeoutCause(context.Background(), timeout, errCallTimeout) defer cancel() r, err := drive(ctx, p.fromPeer, p.toBrowser, fakeSite, out, pages) return r, dir, p, err } // One page, end to end over the pipe: the viewport set, the page opened // and navigated, its events collected, the capture written, the title, // links and outline read, and the target closed. func TestDrivePage(t *testing.T) { f := &fakeBrowser{t: t, contentHeight: 50000} f.afterNavigate = func(p *peer) { p.event("S1", "Network.requestWillBeSent", map[string]any{"requestId": "r1", "type": "Script", "request": map[string]any{"url": "https://cdn.example.com/lib.js"}}) p.event("S1", "Network.loadingFailed", map[string]any{"requestId": "r1", "type": "Script", "errorText": "net::ERR_NAME_NOT_RESOLVED"}) p.event("S1", "Runtime.consoleAPICalled", map[string]any{"type": "error", "args": []any{map[string]any{"type": "string", "value": "boom"}}}) // Another session's events are not this page's. p.event("S2", "Runtime.consoleAPICalled", map[string]any{"type": "error", "args": []any{map[string]any{"type": "string", "value": "other"}}}) loads(p, "L1") } f.links = map[string]any{"title": "Shop\n", "checked": 9999, "broken": []string{fakeSite + "missing/", "https://elsewhere.example/"}} r, dir, p, err := runDrive(t, f, 10*time.Second, Page{Path: "/shop/", Viewport: Desktop, FullPage: true}) if err != nil { t.Fatal(err) } if len(r.Pages) != 1 { t.Fatalf("report %+v", r) } pr := r.Pages[0] if pr.Title != "Shop" || pr.Capture != "page-1.png" || pr.CaptureWidth != 1440 || pr.CaptureHeight != MaxCaptureHeight { t.Fatalf("page %+v", pr) } if len(pr.ConsoleErrors) != 1 || pr.ConsoleErrors[0] != "boom" || len(pr.FailedLoads) != 1 || pr.FailedLoads[0].Kind != LoadExternalBlocked { t.Fatalf("collected %+v", pr) } // The browser's word is bounded and checked: only same-site links. if len(pr.BrokenLinks) != 1 || pr.BrokenLinks[0] != fakeSite+"missing/" || pr.LinksChecked != maxLinks { t.Fatalf("links %q %d", pr.BrokenLinks, pr.LinksChecked) } if pr.Outline != "RootWebArea \"Shop\"\n heading \"Hello\"\n" { t.Fatalf("outline %q", pr.Outline) } if w, h := diskPNG(t, filepath.Join(dir, "page-1.png")); w != 1440 || h != MaxCaptureHeight { t.Fatalf("capture on disk %dx%d", w, h) } if len(f.clips) != 1 || f.clips[0]["height"] != float64(MaxCaptureHeight) || f.clips[0]["width"] != float64(1440) { t.Fatalf("clips %v", f.clips) } got := strings.Join(p.methods(), " ") for _, want := range []string{"Browser.setDownloadBehavior", "Emulation.setDeviceMetricsOverride", "Page.setLifecycleEventsEnabled", "Inspector.enable", "Network.enable", "Page.navigate", "Page.captureScreenshot", "Target.closeTarget"} { if !strings.Contains(got, want) { t.Errorf("no %s in %s", want, got) } } p.mu.Lock() for _, c := range p.calls { if c.Method == "Page.navigate" && !bytes.Contains(c.Params, []byte(`"url":"http://127.0.0.1:4000/shop/"`)) { t.Errorf("navigate %s", c.Params) } if c.Method == "Emulation.setDeviceMetricsOverride" && !bytes.Contains(c.Params, []byte(`"height":900`)) { t.Errorf("viewport %s", c.Params) } if c.Method == "Runtime.evaluate" && !bytes.Contains(c.Params, []byte(`"contextId":7`)) { t.Errorf("the link check is not in the isolated world: %s", c.Params) } } p.mu.Unlock() // A content shorter than the viewport is captured at the viewport. f2 := &fakeBrowser{t: t, contentHeight: 300} if _, _, _, err := runDrive(t, f2, 10*time.Second, Page{Path: "/", Viewport: Phone, FullPage: true}); err != nil { t.Fatal(err) } if len(f2.clips) != 1 || f2.clips[0]["height"] != float64(844) || f2.clips[0]["width"] != float64(390) { t.Fatalf("short page clips %v", f2.clips) } } func diskPNG(t *testing.T, path string) (int, int) { t.Helper() raw, err := os.ReadFile(path) if err != nil { t.Fatal(err) } cfg, err := png.DecodeConfig(bytes.NewReader(raw)) if err != nil { t.Fatal(err) } return cfg.Width, cfg.Height } // How a call ends early: a page that never loads runs into the call's // deadline; a renderer that crashes, a page session that detaches, a // browser that ends or breaks the protocol, and a capture that is not // the PNG asked for are crashed. The pages before are kept. func TestDriveEndsEarly(t *testing.T) { never := func(p *peer) {} for _, c := range []struct { name string set func(f *fakeBrowser) code string cause error }{ {"never loads", func(f *fakeBrowser) { f.afterNavigate = never }, "", errCallTimeout}, {"renderer crashed", func(f *fakeBrowser) { f.afterNavigate = func(p *peer) { p.event("S1", "Inspector.targetCrashed", map[string]any{}) } }, CodeCrashed, nil}, {"session detached", func(f *fakeBrowser) { f.afterNavigate = func(p *peer) { p.event("", "Target.detachedFromTarget", map[string]any{"sessionId": "S1", "targetId": "T1"}) } }, CodeCrashed, nil}, {"browser ended", func(f *fakeBrowser) { f.afterNavigate = func(p *peer) { p.out.Close() } }, CodeCrashed, nil}, {"not a message", func(f *fakeBrowser) { f.afterNavigate = func(p *peer) { p.send("{]") } }, CodeCrashed, nil}, {"capture not a PNG", func(f *fakeBrowser) { f.shot = func(float64, float64) []byte { return []byte("GIF89a") } }, CodeCrashed, nil}, {"capture too big", func(f *fakeBrowser) { f.shot = func(float64, float64) []byte { return pngOf(t, 2000, 900) } }, CodeCrashed, nil}, } { t.Run(c.name, func(t *testing.T) { // The first page is normal; the second fails. f := &fakeBrowser{t: t, contentHeight: 900, only: "/second"} c.set(f) r, _, _, err := runDrive(t, f, 2*time.Second, Page{Path: "/", Viewport: Desktop}, Page{Path: "/second", Viewport: Desktop}) if c.cause != nil { if !errors.Is(err, c.cause) { t.Fatalf("err %v, want %v", err, c.cause) } } else if ErrorCode(err) != c.code { t.Fatalf("err %v, want %s", err, c.code) } if r == nil || len(r.Pages) != 1 || r.Pages[0].Path != "/" { t.Fatalf("report %+v", r) } }) } }