| 1 | package render |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "image" |
| 9 | "image/png" |
| 10 | "os" |
| 11 | "path/filepath" |
| 12 | "strings" |
| 13 | "testing" |
| 14 | "time" |
| 15 | ) |
| 16 | |
| 17 | const fakeSite = "http://127.0.0.1:4000/" |
| 18 | |
| 19 | func pngOf(t *testing.T, w, h int) []byte { |
| 20 | t.Helper() |
| 21 | var b bytes.Buffer |
| 22 | if err := png.Encode(&b, image.NewGray(image.Rect(0, 0, w, h))); err != nil { |
| 23 | t.Fatal(err) |
| 24 | } |
| 25 | return b.Bytes() |
| 26 | } |
| 27 | |
| 28 | // fakeBrowser answers the driver's calls as Chromium does, with hooks a |
| 29 | // test sets: what a page's navigation sends, what its capture is. When |
| 30 | // only is set the hooks apply only to the page whose URL ends with it. |
| 31 | type fakeBrowser struct { |
| 32 | t *testing.T |
| 33 | only string |
| 34 | // afterNavigate sends the page's events; nil is a page that loads. |
| 35 | afterNavigate func(p *peer) |
| 36 | // shot is the capture for a clip (0 by 0 for the viewport); nil is |
| 37 | // a PNG of the size asked for. |
| 38 | shot func(clipW, clipH float64) []byte |
| 39 | // links is Runtime.evaluate's value. |
| 40 | links any |
| 41 | // contentHeight is Page.getLayoutMetrics's. |
| 42 | contentHeight float64 |
| 43 | clips []map[string]any |
| 44 | url string |
| 45 | } |
| 46 | |
| 47 | func (f *fakeBrowser) hooked() bool { return f.only == "" || strings.HasSuffix(f.url, f.only) } |
| 48 | |
| 49 | func (f *fakeBrowser) handle(p *peer, c peerCall) { |
| 50 | var params map[string]any |
| 51 | json.Unmarshal(c.Params, ¶ms) |
| 52 | switch c.Method { |
| 53 | case "Target.createTarget": |
| 54 | p.reply(c, map[string]any{"targetId": "T1"}) |
| 55 | case "Target.attachToTarget": |
| 56 | p.reply(c, map[string]any{"sessionId": "S1"}) |
| 57 | case "Page.getFrameTree": |
| 58 | p.reply(c, map[string]any{"frameTree": map[string]any{"frame": map[string]any{"id": "F1", "loaderId": "L0"}}}) |
| 59 | case "Page.navigate": |
| 60 | f.url, _ = params["url"].(string) |
| 61 | p.reply(c, map[string]any{"frameId": "F1", "loaderId": "L1"}) |
| 62 | if f.afterNavigate != nil && f.hooked() { |
| 63 | f.afterNavigate(p) |
| 64 | return |
| 65 | } |
| 66 | loads(p, "L1") |
| 67 | case "Page.getLayoutMetrics": |
| 68 | p.reply(c, map[string]any{"cssContentSize": map[string]any{"width": 1440, "height": f.contentHeight}}) |
| 69 | case "Page.captureScreenshot": |
| 70 | var w, h float64 = 1440, 900 |
| 71 | if clip, ok := params["clip"].(map[string]any); ok { |
| 72 | f.clips = append(f.clips, clip) |
| 73 | w, h = clip["width"].(float64), clip["height"].(float64) |
| 74 | } |
| 75 | data := pngOf(f.t, int(w), int(h)) |
| 76 | if f.shot != nil && f.hooked() { |
| 77 | data = f.shot(w, h) |
| 78 | } |
| 79 | p.reply(c, map[string]any{"data": data}) |
| 80 | case "Page.createIsolatedWorld": |
| 81 | p.reply(c, map[string]any{"executionContextId": 7}) |
| 82 | case "Runtime.evaluate": |
| 83 | links := f.links |
| 84 | if links == nil { |
| 85 | links = map[string]any{"title": "Shop", "checked": 2, "broken": []string{}} |
| 86 | } |
| 87 | p.reply(c, map[string]any{"result": map[string]any{"type": "object", "value": links}}) |
| 88 | case "Accessibility.getFullAXTree": |
| 89 | p.reply(c, map[string]any{"nodes": []any{ |
| 90 | map[string]any{"nodeId": "1", "role": map[string]any{"value": "RootWebArea"}, "name": map[string]any{"value": "Shop"}, "childIds": []string{"2"}}, |
| 91 | map[string]any{"nodeId": "2", "parentId": "1", "role": map[string]any{"value": "heading"}, "name": map[string]any{"value": "Hello"}}, |
| 92 | }}) |
| 93 | default: |
| 94 | p.reply(c, map[string]any{}) |
| 95 | } |
| 96 | } |
| 97 | |
| 98 | // loads sends a document's commit, load and network idle. |
| 99 | func loads(p *peer, loader string) { |
| 100 | p.event("S1", "Page.frameNavigated", map[string]any{"frame": map[string]any{"id": "F1", "loaderId": loader, "url": fakeSite}}) |
| 101 | p.event("S1", "Page.lifecycleEvent", map[string]any{"frameId": "F1", "loaderId": loader, "name": "load"}) |
| 102 | p.event("S1", "Page.lifecycleEvent", map[string]any{"frameId": "F1", "loaderId": loader, "name": "networkIdle"}) |
| 103 | } |
| 104 | |
| 105 | func runDrive(t *testing.T, f *fakeBrowser, timeout time.Duration, pages ...Page) (*Report, string, *peer, error) { |
| 106 | t.Helper() |
| 107 | p := newPeer(t, f.handle) |
| 108 | dir := t.TempDir() |
| 109 | out, err := os.OpenRoot(dir) |
| 110 | if err != nil { |
| 111 | t.Fatal(err) |
| 112 | } |
| 113 | defer out.Close() |
| 114 | ctx, cancel := context.WithTimeoutCause(context.Background(), timeout, errCallTimeout) |
| 115 | defer cancel() |
| 116 | r, err := drive(ctx, p.fromPeer, p.toBrowser, fakeSite, out, pages) |
| 117 | return r, dir, p, err |
| 118 | } |
| 119 | |
| 120 | // One page, end to end over the pipe: the viewport set, the page opened |
| 121 | // and navigated, its events collected, the capture written, the title, |
| 122 | // links and outline read, and the target closed. |
| 123 | func TestDrivePage(t *testing.T) { |
| 124 | f := &fakeBrowser{t: t, contentHeight: 50000} |
| 125 | f.afterNavigate = func(p *peer) { |
| 126 | p.event("S1", "Network.requestWillBeSent", map[string]any{"requestId": "r1", "type": "Script", "request": map[string]any{"url": "https://cdn.example.com/lib.js"}}) |
| 127 | p.event("S1", "Network.loadingFailed", map[string]any{"requestId": "r1", "type": "Script", "errorText": "net::ERR_NAME_NOT_RESOLVED"}) |
| 128 | p.event("S1", "Runtime.consoleAPICalled", map[string]any{"type": "error", "args": []any{map[string]any{"type": "string", "value": "boom"}}}) |
| 129 | // Another session's events are not this page's. |
| 130 | p.event("S2", "Runtime.consoleAPICalled", map[string]any{"type": "error", "args": []any{map[string]any{"type": "string", "value": "other"}}}) |
| 131 | loads(p, "L1") |
| 132 | } |
| 133 | f.links = map[string]any{"title": "Shop\n", "checked": 9999, "broken": []string{fakeSite + "missing/", "https://elsewhere.example/"}} |
| 134 | r, dir, p, err := runDrive(t, f, 10*time.Second, Page{Path: "/shop/", Viewport: Desktop, FullPage: true}) |
| 135 | if err != nil { |
| 136 | t.Fatal(err) |
| 137 | } |
| 138 | if len(r.Pages) != 1 { |
| 139 | t.Fatalf("report %+v", r) |
| 140 | } |
| 141 | pr := r.Pages[0] |
| 142 | if pr.Title != "Shop" || pr.Capture != "page-1.png" || pr.CaptureWidth != 1440 || pr.CaptureHeight != MaxCaptureHeight { |
| 143 | t.Fatalf("page %+v", pr) |
| 144 | } |
| 145 | if len(pr.ConsoleErrors) != 1 || pr.ConsoleErrors[0] != "boom" || len(pr.FailedLoads) != 1 || pr.FailedLoads[0].Kind != LoadExternalBlocked { |
| 146 | t.Fatalf("collected %+v", pr) |
| 147 | } |
| 148 | // The browser's word is bounded and checked: only same-site links. |
| 149 | if len(pr.BrokenLinks) != 1 || pr.BrokenLinks[0] != fakeSite+"missing/" || pr.LinksChecked != maxLinks { |
| 150 | t.Fatalf("links %q %d", pr.BrokenLinks, pr.LinksChecked) |
| 151 | } |
| 152 | if pr.Outline != "RootWebArea \"Shop\"\n heading \"Hello\"\n" { |
| 153 | t.Fatalf("outline %q", pr.Outline) |
| 154 | } |
| 155 | if w, h := diskPNG(t, filepath.Join(dir, "page-1.png")); w != 1440 || h != MaxCaptureHeight { |
| 156 | t.Fatalf("capture on disk %dx%d", w, h) |
| 157 | } |
| 158 | if len(f.clips) != 1 || f.clips[0]["height"] != float64(MaxCaptureHeight) || f.clips[0]["width"] != float64(1440) { |
| 159 | t.Fatalf("clips %v", f.clips) |
| 160 | } |
| 161 | got := strings.Join(p.methods(), " ") |
| 162 | for _, want := range []string{"Browser.setDownloadBehavior", "Emulation.setDeviceMetricsOverride", "Page.setLifecycleEventsEnabled", "Inspector.enable", "Network.enable", "Page.navigate", "Page.captureScreenshot", "Target.closeTarget"} { |
| 163 | if !strings.Contains(got, want) { |
| 164 | t.Errorf("no %s in %s", want, got) |
| 165 | } |
| 166 | } |
| 167 | p.mu.Lock() |
| 168 | for _, c := range p.calls { |
| 169 | if c.Method == "Page.navigate" && !bytes.Contains(c.Params, []byte(`"url":"http://127.0.0.1:4000/shop/"`)) { |
| 170 | t.Errorf("navigate %s", c.Params) |
| 171 | } |
| 172 | if c.Method == "Emulation.setDeviceMetricsOverride" && !bytes.Contains(c.Params, []byte(`"height":900`)) { |
| 173 | t.Errorf("viewport %s", c.Params) |
| 174 | } |
| 175 | if c.Method == "Runtime.evaluate" && !bytes.Contains(c.Params, []byte(`"contextId":7`)) { |
| 176 | t.Errorf("the link check is not in the isolated world: %s", c.Params) |
| 177 | } |
| 178 | } |
| 179 | p.mu.Unlock() |
| 180 | // A content shorter than the viewport is captured at the viewport. |
| 181 | f2 := &fakeBrowser{t: t, contentHeight: 300} |
| 182 | if _, _, _, err := runDrive(t, f2, 10*time.Second, Page{Path: "/", Viewport: Phone, FullPage: true}); err != nil { |
| 183 | t.Fatal(err) |
| 184 | } |
| 185 | if len(f2.clips) != 1 || f2.clips[0]["height"] != float64(844) || f2.clips[0]["width"] != float64(390) { |
| 186 | t.Fatalf("short page clips %v", f2.clips) |
| 187 | } |
| 188 | } |
| 189 | |
| 190 | func diskPNG(t *testing.T, path string) (int, int) { |
| 191 | t.Helper() |
| 192 | raw, err := os.ReadFile(path) |
| 193 | if err != nil { |
| 194 | t.Fatal(err) |
| 195 | } |
| 196 | cfg, err := png.DecodeConfig(bytes.NewReader(raw)) |
| 197 | if err != nil { |
| 198 | t.Fatal(err) |
| 199 | } |
| 200 | return cfg.Width, cfg.Height |
| 201 | } |
| 202 | |
| 203 | // How a call ends early: a page that never loads runs into the call's |
| 204 | // deadline; a renderer that crashes, a page session that detaches, a |
| 205 | // browser that ends or breaks the protocol, and a capture that is not |
| 206 | // the PNG asked for are crashed. The pages before are kept. |
| 207 | func TestDriveEndsEarly(t *testing.T) { |
| 208 | never := func(p *peer) {} |
| 209 | for _, c := range []struct { |
| 210 | name string |
| 211 | set func(f *fakeBrowser) |
| 212 | code string |
| 213 | cause error |
| 214 | }{ |
| 215 | {"never loads", func(f *fakeBrowser) { f.afterNavigate = never }, "", errCallTimeout}, |
| 216 | {"renderer crashed", func(f *fakeBrowser) { |
| 217 | f.afterNavigate = func(p *peer) { p.event("S1", "Inspector.targetCrashed", map[string]any{}) } |
| 218 | }, CodeCrashed, nil}, |
| 219 | {"session detached", func(f *fakeBrowser) { |
| 220 | f.afterNavigate = func(p *peer) { |
| 221 | p.event("", "Target.detachedFromTarget", map[string]any{"sessionId": "S1", "targetId": "T1"}) |
| 222 | } |
| 223 | }, CodeCrashed, nil}, |
| 224 | {"browser ended", func(f *fakeBrowser) { f.afterNavigate = func(p *peer) { p.out.Close() } }, CodeCrashed, nil}, |
| 225 | {"not a message", func(f *fakeBrowser) { f.afterNavigate = func(p *peer) { p.send("{]") } }, CodeCrashed, nil}, |
| 226 | {"capture not a PNG", func(f *fakeBrowser) { f.shot = func(float64, float64) []byte { return []byte("GIF89a") } }, CodeCrashed, nil}, |
| 227 | {"capture too big", func(f *fakeBrowser) { f.shot = func(float64, float64) []byte { return pngOf(t, 2000, 900) } }, CodeCrashed, nil}, |
| 228 | } { |
| 229 | t.Run(c.name, func(t *testing.T) { |
| 230 | // The first page is normal; the second fails. |
| 231 | f := &fakeBrowser{t: t, contentHeight: 900, only: "/second"} |
| 232 | c.set(f) |
| 233 | r, _, _, err := runDrive(t, f, 2*time.Second, Page{Path: "/", Viewport: Desktop}, Page{Path: "/second", Viewport: Desktop}) |
| 234 | if c.cause != nil { |
| 235 | if !errors.Is(err, c.cause) { |
| 236 | t.Fatalf("err %v, want %v", err, c.cause) |
| 237 | } |
| 238 | } else if ErrorCode(err) != c.code { |
| 239 | t.Fatalf("err %v, want %s", err, c.code) |
| 240 | } |
| 241 | if r == nil || len(r.Pages) != 1 || r.Pages[0].Path != "/" { |
| 242 | t.Fatalf("report %+v", r) |
| 243 | } |
| 244 | }) |
| 245 | } |
| 246 | } |
| 247 | |