oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1//go:build linux
2
3package render
4
5import (
6 "context"
7 "crypto/sha256"
8 "encoding/hex"
9 "encoding/json"
10 "errors"
11 "image/png"
12 "io/fs"
13 "os"
14 "path/filepath"
15 "slices"
16 "strconv"
17 "strings"
18 "testing"
19 "time"
20)
21
22// realConfig is a launch of the real browser, from the tree
23// EQUIPO_RENDERER_TREE names, over a copy of testdata/site, and an
24// empty out directory for Render.
25func realConfig(t *testing.T) (LaunchConfig, string) {
26 t.Helper()
27 tree := os.Getenv("EQUIPO_RENDERER_TREE")
28 if tree == "" {
29 t.Skip("set EQUIPO_RENDERER_TREE to a tree built by scripts/build-renderer-tree.py --tree to render the fixture sites")
30 }
31 bwrap, self := usableBwrap(t)
32 manifest, err := os.ReadFile(filepath.Join(tree, "MANIFEST"))
33 if err != nil {
34 t.Fatal(err)
35 }
36 sum := sha256.Sum256(manifest)
37 var stderr bounded
38 stderr.max = 64 << 10
39 t.Cleanup(func() {
40 if t.Failed() {
41 t.Logf("sandbox stderr:\n%s", stderr.Bytes())
42 }
43 })
44 return LaunchConfig{Bwrap: bwrap, Binary: self, Tree: tree, Pin: hex.EncodeToString(sum[:]), Site: fixtureSite(t), Stderr: &stderr}, testOut(t)
45}
46
47// fixtureSite copies testdata/site to a directory only this user can
48// write, as Launch requires.
49func fixtureSite(t *testing.T) string {
50 t.Helper()
51 dir := filepath.Join(tempDir(t), "site")
52 must(t, os.CopyFS(dir, os.DirFS("testdata/site")))
53 must(t, filepath.WalkDir(dir, func(p string, d fs.DirEntry, err error) error {
54 if err != nil {
55 return err
56 }
57 if d.IsDir() {
58 return os.Chmod(p, 0o755)
59 }
60 return os.Chmod(p, 0o644)
61 }))
62 return dir
63}
64
65func readReport(t *testing.T, out string) Report {
66 t.Helper()
67 raw, err := os.ReadFile(filepath.Join(out, ReportName))
68 if err != nil {
69 t.Fatal(err)
70 }
71 var r Report
72 if err = json.Unmarshal(raw, &r); err != nil {
73 t.Fatal(err)
74 }
75 return r
76}
77
78func captureSize(t *testing.T, out, name string) (int, int) {
79 t.Helper()
80 f, err := os.Open(filepath.Join(out, name))
81 if err != nil {
82 t.Fatal(err)
83 }
84 defer f.Close()
85 cfg, err := png.DecodeConfig(f)
86 if err != nil {
87 t.Fatalf("%s: %v", name, err)
88 }
89 return cfg.Width, cfg.Height
90}
91
92func hasLoad(loads []FailedLoad, kind, url string) bool {
93 return slices.ContainsFunc(loads, func(f FailedLoad) bool { return f.Kind == kind && f.URL == url })
94}
95
96// The fixture site, six pages in one call: a console error, a CDN
97// script, web fonts, broken links and a very tall page, full and not.
98func TestRenderFixtureSite(t *testing.T) {
99 cfg, out := realConfig(t)
100 pages := []Page{
101 {Path: "/", Viewport: Desktop},
102 {Path: "/console.html", Viewport: Phone},
103 {Path: "/cdn.html", Viewport: Tablet},
104 {Path: "/font.html", Viewport: Desktop},
105 {Path: "/tall.html", Viewport: Desktop, FullPage: true},
106 {Path: "/tall.html", Viewport: Phone},
107 }
108 began := time.Now()
109 report, err := Render(context.Background(), cfg, out, pages)
110 if err != nil {
111 t.Fatal(err)
112 }
113 t.Logf("rendered %d pages in %v", len(report.Pages), time.Since(began))
114 if onDisk := readReport(t, out); onDisk.Schema != ReportSchema || len(onDisk.Pages) != len(pages) || onDisk.Error != "" {
115 t.Fatalf("report.json %+v", onDisk)
116 }
117 for i, p := range report.Pages {
118 w, h := captureSize(t, out, p.Capture)
119 if p.Capture != "page-"+strconv.Itoa(i+1)+".png" || w != p.CaptureWidth || h != p.CaptureHeight {
120 t.Errorf("page %d capture %q %dx%d, report %dx%d", i, p.Capture, w, h, p.CaptureWidth, p.CaptureHeight)
121 }
122 vw, vh, _ := pages[i].Viewport.Size()
123 if !pages[i].FullPage && (w != vw || h != vh) {
124 t.Errorf("page %d (%s) captured %dx%d, viewport %dx%d", i, pages[i].Viewport, w, h, vw, vh)
125 }
126 js, _ := json.Marshal(p)
127 t.Logf("page %d: %s", i+1, js)
128 }
129 home := report.Pages[0]
130 site := strings.TrimSuffix(siteOf(t, home), "/")
131 if home.Title != "Shop home" {
132 t.Errorf("title %q", home.Title)
133 }
134 if !slices.Equal(home.BrokenLinks, []string{site + "/missing/"}) || home.LinksChecked != 2 {
135 t.Errorf("broken links %q of %d", home.BrokenLinks, home.LinksChecked)
136 }
137 if !hasLoad(home.FailedLoads, LoadNotFound, site+"/no-such-image.png") {
138 t.Errorf("failed loads %+v", home.FailedLoads)
139 }
140 for _, want := range []string{`heading "Welcome to the shop"`, `link "About"`, `button "Buy"`, `image "A product"`, `navigation`} {
141 if !strings.Contains(home.Outline, want) {
142 t.Errorf("outline lacks %s:\n%s", want, home.Outline)
143 }
144 }
145 console := report.Pages[1]
146 if len(console.ConsoleErrors) != maxConsoleErrors || console.ConsoleErrors[0] != "boom 42" || console.ConsoleErrors[1] != "Uncaught Error: uncaught on purpose" || console.ConsoleErrors[2] != "again 0" || console.ConsoleErrorsOmitted != 22 {
147 t.Errorf("console errors %q, %d omitted", console.ConsoleErrors, console.ConsoleErrorsOmitted)
148 }
149 cdn := report.Pages[2]
150 if !hasLoad(cdn.FailedLoads, LoadExternalBlocked, "https://cdn.example.com/lib.js") || !hasLoad(cdn.FailedLoads, LoadExternalBlocked, "http://1.1.1.1/style.css") {
151 t.Errorf("cdn failed loads %+v", cdn.FailedLoads)
152 }
153 font := report.Pages[3]
154 if !hasLoad(font.FailedLoads, LoadFont, "https://fonts.gstatic.com/s/remote/v1/remote.woff2") || !hasLoad(font.FailedLoads, LoadFont, site+"/fonts/missing.woff2") {
155 t.Errorf("font failed loads %+v", font.FailedLoads)
156 }
157 if tall := report.Pages[4]; tall.CaptureWidth != 1440 || tall.CaptureHeight != MaxCaptureHeight {
158 t.Errorf("full tall page %dx%d", tall.CaptureWidth, tall.CaptureHeight)
159 }
160}
161
162// siteOf is the site's origin, read back from a page's failed load.
163func siteOf(t *testing.T, p PageReport) string {
164 t.Helper()
165 for _, f := range p.FailedLoads {
166 if f.Kind == LoadNotFound {
167 if i := strings.Index(f.URL[len("http://"):], "/"); i > 0 {
168 return f.URL[:len("http://")+i+1]
169 }
170 }
171 }
172 t.Fatalf("no same-site failed load in %+v", p.FailedLoads)
173 return ""
174}
175
176// A page that redirects itself to another host is not followed: the
177// load shows as external blocked.
178func TestRenderRedirectIsBlocked(t *testing.T) {
179 cfg, out := realConfig(t)
180 report, err := Render(context.Background(), cfg, out, []Page{{Path: "/redirect.html", Viewport: Desktop}})
181 if err != nil {
182 t.Fatal(err)
183 }
184 p := report.Pages[0]
185 js, _ := json.Marshal(p)
186 t.Logf("%s", js)
187 if !hasLoad(p.FailedLoads, LoadExternalBlocked, "http://cdn.example.com/landing") {
188 t.Fatalf("failed loads %+v", p.FailedLoads)
189 }
190}
191
192// A script that never ends is the call's timeout, and the sandbox is
193// killed.
194func TestRenderNeverEndingScriptTimesOut(t *testing.T) {
195 cfg, out := realConfig(t)
196 defer func(d time.Duration) { callTimeout = d }(callTimeout)
197 callTimeout = 15 * time.Second
198 began := time.Now()
199 report, err := Render(context.Background(), cfg, out, []Page{{Path: "/", Viewport: Desktop}, {Path: "/forever.html", Viewport: Desktop}})
200 took := time.Since(began)
201 if ErrorCode(err) != CodeTimeout {
202 t.Fatalf("err %v", err)
203 }
204 if took > callTimeout+15*time.Second {
205 t.Fatalf("took %v", took)
206 }
207 if report == nil || report.Error != CodeTimeout || len(report.Pages) != 1 || readReport(t, out).Error != CodeTimeout {
208 t.Fatalf("report %+v", report)
209 }
210 t.Logf("%v after %v", err, took)
211}
212
213// A page that exhausts the renderer's memory is crashed.
214func TestRenderCrashedRenderer(t *testing.T) {
215 cfg, out := realConfig(t)
216 began := time.Now()
217 report, err := Render(context.Background(), cfg, out, []Page{{Path: "/crash.html", Viewport: Desktop}})
218 if ErrorCode(err) != CodeCrashed {
219 t.Fatalf("err %v", err)
220 }
221 if report == nil || report.Error != CodeCrashed {
222 t.Fatalf("report %+v", report)
223 }
224 t.Logf("%v after %v", err, time.Since(began))
225}
226
227// A sandbox over its memory is killed, and the call is crashed.
228func TestRenderOverMemoryIsCrashed(t *testing.T) {
229 cfg, out := realConfig(t)
230 defer func(n int64) { memoryLimit = n }(memoryLimit)
231 // Less than the browser itself takes.
232 memoryLimit = 32 << 20
233 report, err := Render(context.Background(), cfg, out, []Page{{Path: "/", Viewport: Desktop}})
234 var e *Error
235 if !errors.As(err, &e) || e.Code != CodeCrashed || e.Detail != errOverMemory.Error() {
236 t.Fatalf("err %v", err)
237 }
238 if report == nil || report.Error != CodeCrashed {
239 t.Fatalf("report %+v", report)
240 }
241 t.Logf("%v", err)
242}
243
244// The fixture render that install and verify-installed run: the real
245// browser paints the embedded page, and CheckFixture leaves nothing in
246// its scratch directory.
247func TestCheckFixtureRealBrowser(t *testing.T) {
248 cfg, _ := realConfig(t)
249 scratch := tempDir(t)
250 began := time.Now()
251 if err := CheckFixture(context.Background(), cfg, scratch); err != nil {
252 t.Fatal(err)
253 }
254 t.Logf("fixture render in %v", time.Since(began))
255 if left, _ := os.ReadDir(scratch); len(left) != 0 {
256 t.Fatalf("left in scratch: %v", left)
257 }
258}
259