//go:build linux package render import ( "context" "crypto/sha256" "encoding/hex" "encoding/json" "errors" "image/png" "io/fs" "os" "path/filepath" "slices" "strconv" "strings" "testing" "time" ) // realConfig is a launch of the real browser, from the tree // EQUIPO_RENDERER_TREE names, over a copy of testdata/site, and an // empty out directory for Render. func realConfig(t *testing.T) (LaunchConfig, string) { t.Helper() tree := os.Getenv("EQUIPO_RENDERER_TREE") if tree == "" { t.Skip("set EQUIPO_RENDERER_TREE to a tree built by scripts/build-renderer-tree.py --tree to render the fixture sites") } bwrap, self := usableBwrap(t) manifest, err := os.ReadFile(filepath.Join(tree, "MANIFEST")) if err != nil { t.Fatal(err) } sum := sha256.Sum256(manifest) var stderr bounded stderr.max = 64 << 10 t.Cleanup(func() { if t.Failed() { t.Logf("sandbox stderr:\n%s", stderr.Bytes()) } }) return LaunchConfig{Bwrap: bwrap, Binary: self, Tree: tree, Pin: hex.EncodeToString(sum[:]), Site: fixtureSite(t), Stderr: &stderr}, testOut(t) } // fixtureSite copies testdata/site to a directory only this user can // write, as Launch requires. func fixtureSite(t *testing.T) string { t.Helper() dir := filepath.Join(tempDir(t), "site") must(t, os.CopyFS(dir, os.DirFS("testdata/site"))) must(t, filepath.WalkDir(dir, func(p string, d fs.DirEntry, err error) error { if err != nil { return err } if d.IsDir() { return os.Chmod(p, 0o755) } return os.Chmod(p, 0o644) })) return dir } func readReport(t *testing.T, out string) Report { t.Helper() raw, err := os.ReadFile(filepath.Join(out, ReportName)) if err != nil { t.Fatal(err) } var r Report if err = json.Unmarshal(raw, &r); err != nil { t.Fatal(err) } return r } func captureSize(t *testing.T, out, name string) (int, int) { t.Helper() f, err := os.Open(filepath.Join(out, name)) if err != nil { t.Fatal(err) } defer f.Close() cfg, err := png.DecodeConfig(f) if err != nil { t.Fatalf("%s: %v", name, err) } return cfg.Width, cfg.Height } func hasLoad(loads []FailedLoad, kind, url string) bool { return slices.ContainsFunc(loads, func(f FailedLoad) bool { return f.Kind == kind && f.URL == url }) } // The fixture site, six pages in one call: a console error, a CDN // script, web fonts, broken links and a very tall page, full and not. func TestRenderFixtureSite(t *testing.T) { cfg, out := realConfig(t) pages := []Page{ {Path: "/", Viewport: Desktop}, {Path: "/console.html", Viewport: Phone}, {Path: "/cdn.html", Viewport: Tablet}, {Path: "/font.html", Viewport: Desktop}, {Path: "/tall.html", Viewport: Desktop, FullPage: true}, {Path: "/tall.html", Viewport: Phone}, } began := time.Now() report, err := Render(context.Background(), cfg, out, pages) if err != nil { t.Fatal(err) } t.Logf("rendered %d pages in %v", len(report.Pages), time.Since(began)) if onDisk := readReport(t, out); onDisk.Schema != ReportSchema || len(onDisk.Pages) != len(pages) || onDisk.Error != "" { t.Fatalf("report.json %+v", onDisk) } for i, p := range report.Pages { w, h := captureSize(t, out, p.Capture) if p.Capture != "page-"+strconv.Itoa(i+1)+".png" || w != p.CaptureWidth || h != p.CaptureHeight { t.Errorf("page %d capture %q %dx%d, report %dx%d", i, p.Capture, w, h, p.CaptureWidth, p.CaptureHeight) } vw, vh, _ := pages[i].Viewport.Size() if !pages[i].FullPage && (w != vw || h != vh) { t.Errorf("page %d (%s) captured %dx%d, viewport %dx%d", i, pages[i].Viewport, w, h, vw, vh) } js, _ := json.Marshal(p) t.Logf("page %d: %s", i+1, js) } home := report.Pages[0] site := strings.TrimSuffix(siteOf(t, home), "/") if home.Title != "Shop home" { t.Errorf("title %q", home.Title) } if !slices.Equal(home.BrokenLinks, []string{site + "/missing/"}) || home.LinksChecked != 2 { t.Errorf("broken links %q of %d", home.BrokenLinks, home.LinksChecked) } if !hasLoad(home.FailedLoads, LoadNotFound, site+"/no-such-image.png") { t.Errorf("failed loads %+v", home.FailedLoads) } for _, want := range []string{`heading "Welcome to the shop"`, `link "About"`, `button "Buy"`, `image "A product"`, `navigation`} { if !strings.Contains(home.Outline, want) { t.Errorf("outline lacks %s:\n%s", want, home.Outline) } } console := report.Pages[1] 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 { t.Errorf("console errors %q, %d omitted", console.ConsoleErrors, console.ConsoleErrorsOmitted) } cdn := report.Pages[2] if !hasLoad(cdn.FailedLoads, LoadExternalBlocked, "https://cdn.example.com/lib.js") || !hasLoad(cdn.FailedLoads, LoadExternalBlocked, "http://1.1.1.1/style.css") { t.Errorf("cdn failed loads %+v", cdn.FailedLoads) } font := report.Pages[3] if !hasLoad(font.FailedLoads, LoadFont, "https://fonts.gstatic.com/s/remote/v1/remote.woff2") || !hasLoad(font.FailedLoads, LoadFont, site+"/fonts/missing.woff2") { t.Errorf("font failed loads %+v", font.FailedLoads) } if tall := report.Pages[4]; tall.CaptureWidth != 1440 || tall.CaptureHeight != MaxCaptureHeight { t.Errorf("full tall page %dx%d", tall.CaptureWidth, tall.CaptureHeight) } } // siteOf is the site's origin, read back from a page's failed load. func siteOf(t *testing.T, p PageReport) string { t.Helper() for _, f := range p.FailedLoads { if f.Kind == LoadNotFound { if i := strings.Index(f.URL[len("http://"):], "/"); i > 0 { return f.URL[:len("http://")+i+1] } } } t.Fatalf("no same-site failed load in %+v", p.FailedLoads) return "" } // A page that redirects itself to another host is not followed: the // load shows as external blocked. func TestRenderRedirectIsBlocked(t *testing.T) { cfg, out := realConfig(t) report, err := Render(context.Background(), cfg, out, []Page{{Path: "/redirect.html", Viewport: Desktop}}) if err != nil { t.Fatal(err) } p := report.Pages[0] js, _ := json.Marshal(p) t.Logf("%s", js) if !hasLoad(p.FailedLoads, LoadExternalBlocked, "http://cdn.example.com/landing") { t.Fatalf("failed loads %+v", p.FailedLoads) } } // A script that never ends is the call's timeout, and the sandbox is // killed. func TestRenderNeverEndingScriptTimesOut(t *testing.T) { cfg, out := realConfig(t) defer func(d time.Duration) { callTimeout = d }(callTimeout) callTimeout = 15 * time.Second began := time.Now() report, err := Render(context.Background(), cfg, out, []Page{{Path: "/", Viewport: Desktop}, {Path: "/forever.html", Viewport: Desktop}}) took := time.Since(began) if ErrorCode(err) != CodeTimeout { t.Fatalf("err %v", err) } if took > callTimeout+15*time.Second { t.Fatalf("took %v", took) } if report == nil || report.Error != CodeTimeout || len(report.Pages) != 1 || readReport(t, out).Error != CodeTimeout { t.Fatalf("report %+v", report) } t.Logf("%v after %v", err, took) } // A page that exhausts the renderer's memory is crashed. func TestRenderCrashedRenderer(t *testing.T) { cfg, out := realConfig(t) began := time.Now() report, err := Render(context.Background(), cfg, out, []Page{{Path: "/crash.html", Viewport: Desktop}}) if ErrorCode(err) != CodeCrashed { t.Fatalf("err %v", err) } if report == nil || report.Error != CodeCrashed { t.Fatalf("report %+v", report) } t.Logf("%v after %v", err, time.Since(began)) } // A sandbox over its memory is killed, and the call is crashed. func TestRenderOverMemoryIsCrashed(t *testing.T) { cfg, out := realConfig(t) defer func(n int64) { memoryLimit = n }(memoryLimit) // Less than the browser itself takes. memoryLimit = 32 << 20 report, err := Render(context.Background(), cfg, out, []Page{{Path: "/", Viewport: Desktop}}) var e *Error if !errors.As(err, &e) || e.Code != CodeCrashed || e.Detail != errOverMemory.Error() { t.Fatalf("err %v", err) } if report == nil || report.Error != CodeCrashed { t.Fatalf("report %+v", report) } t.Logf("%v", err) } // The fixture render that install and verify-installed run: the real // browser paints the embedded page, and CheckFixture leaves nothing in // its scratch directory. func TestCheckFixtureRealBrowser(t *testing.T) { cfg, _ := realConfig(t) scratch := tempDir(t) began := time.Now() if err := CheckFixture(context.Background(), cfg, scratch); err != nil { t.Fatal(err) } t.Logf("fixture render in %v", time.Since(began)) if left, _ := os.ReadDir(scratch); len(left) != 0 { t.Fatalf("left in scratch: %v", left) } }