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 browser
2
3package browsertest
4
5import (
6 "amadan.net/rastrillo/rastrillo/harness"
7 "context"
8 "fmt"
9 "github.com/chromedp/chromedp"
10 "os"
11 "path/filepath"
12 "strings"
13 "testing"
14 "time"
15)
16
17func Wait(expression string) chromedp.Action[chromedp.Void] {
18 return WaitWithin(expression, 5*time.Second)
19}
20
21// WaitWithin is Wait with its own window, for a change that waits on
22// work the test asked to take time (a step told to sleep), not on the
23// page: 5 s is room for the page to react, not for the work and the
24// page together on a loaded machine.
25func WaitWithin(expression string, window time.Duration) chromedp.Action[chromedp.Void] {
26 return chromedp.Func(func(ctx context.Context, target *chromedp.Target) error {
27 ctx, cancel := context.WithTimeout(ctx, window)
28 defer cancel()
29 tick := time.NewTicker(20 * time.Millisecond)
30 defer tick.Stop()
31 for {
32 ok, err := chromedp.Evaluate[bool]("document.readyState === 'complete' && ("+expression+")")(ctx, target)
33 if err == nil && ok {
34 return nil
35 }
36 select {
37 case <-ctx.Done():
38 return fmt.Errorf("waiting for %s: %w (last evaluation: %v)", expression, ctx.Err(), err)
39 case <-tick.C:
40 }
41 }
42 })
43}
44
45func Click(selector string) chromedp.Action[chromedp.Void] {
46 return chromedp.Func(func(ctx context.Context, target *chromedp.Target) error {
47 ctx, cancel := context.WithTimeout(ctx, 8*time.Second)
48 defer cancel()
49 _, err := chromedp.RunResponse(ctx, chromedp.Click(chromedp.CSS(selector)))
50 return err
51 })
52}
53
54func Screenshot(t *testing.T, rig *harness.Rig, name string) {
55 t.Helper()
56 dir := os.Getenv("EQUIPO_BROWSER_ARTIFACTS")
57 if dir == "" {
58 return
59 }
60 if strings.HasPrefix(name, "mockup-") && strings.HasSuffix(name, "-390") {
61 harness.Evaluate[bool](rig, `(()=>{const e=location.pathname.includes('native')?document.querySelectorAll('.ph')[2]:document.querySelector('.phone');e?.scrollIntoView({block:'start'});return true})()`)
62 }
63 if os.Getenv("EQUIPO_CHAT_HISTORY") == "1" {
64 harness.Evaluate[bool](rig, `(()=>{const e=document.querySelector('[equipo-scroll]');if(e)e.scrollTop=0;return true})()`)
65 }
66 if err := os.MkdirAll(dir, 0700); err != nil {
67 t.Fatal(err)
68 }
69 if err := os.WriteFile(filepath.Join(dir, name+".png"), harness.Read(rig, chromedp.CaptureScreenshot()), 0600); err != nil {
70 t.Fatal(err)
71 }
72}
73