//go:build browser package browsertest import ( "amadan.net/rastrillo/rastrillo/harness" "context" "fmt" "github.com/chromedp/chromedp" "os" "path/filepath" "strings" "testing" "time" ) func Wait(expression string) chromedp.Action[chromedp.Void] { return WaitWithin(expression, 5*time.Second) } // WaitWithin is Wait with its own window, for a change that waits on // work the test asked to take time (a step told to sleep), not on the // page: 5 s is room for the page to react, not for the work and the // page together on a loaded machine. func WaitWithin(expression string, window time.Duration) chromedp.Action[chromedp.Void] { return chromedp.Func(func(ctx context.Context, target *chromedp.Target) error { ctx, cancel := context.WithTimeout(ctx, window) defer cancel() tick := time.NewTicker(20 * time.Millisecond) defer tick.Stop() for { ok, err := chromedp.Evaluate[bool]("document.readyState === 'complete' && ("+expression+")")(ctx, target) if err == nil && ok { return nil } select { case <-ctx.Done(): return fmt.Errorf("waiting for %s: %w (last evaluation: %v)", expression, ctx.Err(), err) case <-tick.C: } } }) } func Click(selector string) chromedp.Action[chromedp.Void] { return chromedp.Func(func(ctx context.Context, target *chromedp.Target) error { ctx, cancel := context.WithTimeout(ctx, 8*time.Second) defer cancel() _, err := chromedp.RunResponse(ctx, chromedp.Click(chromedp.CSS(selector))) return err }) } func Screenshot(t *testing.T, rig *harness.Rig, name string) { t.Helper() dir := os.Getenv("EQUIPO_BROWSER_ARTIFACTS") if dir == "" { return } if strings.HasPrefix(name, "mockup-") && strings.HasSuffix(name, "-390") { harness.Evaluate[bool](rig, `(()=>{const e=location.pathname.includes('native')?document.querySelectorAll('.ph')[2]:document.querySelector('.phone');e?.scrollIntoView({block:'start'});return true})()`) } if os.Getenv("EQUIPO_CHAT_HISTORY") == "1" { harness.Evaluate[bool](rig, `(()=>{const e=document.querySelector('[equipo-scroll]');if(e)e.scrollTop=0;return true})()`) } if err := os.MkdirAll(dir, 0700); err != nil { t.Fatal(err) } if err := os.WriteFile(filepath.Join(dir, name+".png"), harness.Read(rig, chromedp.CaptureScreenshot()), 0600); err != nil { t.Fatal(err) } }