oficina / docs Public

Browser tests: port to chromedp v0.21 (rastrillo v0.40.0's harness)

Mechanical port to the generic action API: selectors name their kind
(chromedp.CSS), Evaluate/Poll are typed, modifiers are chromedp.Modifier*,
cdproto commands run through a small command() step (chromedp.Func +
cdp.Call), and ListenTarget becomes harness.Listen. Evaluate results are
read through a pointer (evalInto) so a script returning null or undefined
keeps v0.14's zero-value meaning. No assertion changed.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev a33ebb39ea8eb4727fd6827e380d4135713fa7aa parent 7130f99
4 files changed, +125 −96
  • internal/docs/carry_browser_test.go +2 −3
  • internal/docs/colophon_browser_test.go +5 −5
  • internal/docs/fonts_browser_test.go +98 −66
  • internal/docs/zoom_browser_test.go +20 −22
diff --git a/internal/docs/carry_browser_test.go b/internal/docs/carry_browser_test.go
index 81a6260..22ab542 100644
--- a/internal/docs/carry_browser_test.go
+++ b/internal/docs/carry_browser_test.go
@@ -10,7 +10,6 @@ import (
"testing"
"time"
- "github.com/chromedp/cdproto/input"
"github.com/chromedp/chromedp"
)
@@ -228,9 +227,9 @@ func TestAnUndoWhileARefusalIsPendingStaysUndone(t *testing.T) {
fr.rig.Run(chromedp.Sleep(700 * time.Millisecond))
fr.eval(t, docCaretJS(0, -1), &ok)
fr.rig.Run(chromedp.Sleep(40*time.Millisecond), chromedp.KeyEvent("a"), chromedp.Sleep(120*time.Millisecond))
- fr.rig.Run(chromedp.KeyEvent("z", chromedp.KeyModifiers(input.ModifierMeta)), chromedp.Sleep(200*time.Millisecond))
+ fr.rig.Run(chromedp.KeyEvent("z", chromedp.KeyModifiers(chromedp.ModifierMeta)), chromedp.Sleep(200*time.Millisecond))
if c.redo {
- fr.rig.Run(chromedp.KeyEvent("z", chromedp.KeyModifiers(input.ModifierMeta|input.ModifierShift)), chromedp.Sleep(200*time.Millisecond))
+ fr.rig.Run(chromedp.KeyEvent("z", chromedp.KeyModifiers(chromedp.ModifierMeta|chromedp.ModifierShift)), chromedp.Sleep(200*time.Millisecond))
}
if c.then != "" {
fr.eval(t, docCaretJS(0, -1), &ok)
diff --git a/internal/docs/colophon_browser_test.go b/internal/docs/colophon_browser_test.go
index c349e89..8096437 100644
--- a/internal/docs/colophon_browser_test.go
+++ b/internal/docs/colophon_browser_test.go
@@ -43,11 +43,11 @@ func TestColophonPagesReflowAndNeedNoScriptOrFont(t *testing.T) {
}
return served
})
- run := func(what string, actions ...chromedp.Action) {
+ run := func(what string, actions ...chromedp.Action[chromedp.Void]) {
t.Helper()
ctx, cancel := context.WithTimeout(rig.Context(), 30*time.Second)
defer cancel()
- if err := chromedp.Run(ctx, actions...); err != nil {
+ if err := chromedp.Do(ctx, actions...); err != nil {
t.Fatalf("%s: %v", what, err)
}
}
@@ -93,12 +93,12 @@ func TestColophonPagesReflowAndNeedNoScriptOrFont(t *testing.T) {
})()`
c := docs.Colophon()
for _, scripts := range []bool{true, false} {
- run("scripts", emulation.SetScriptExecutionDisabled(!scripts))
+ run("scripts", command(emulation.SetScriptExecutionDisabled, emulation.SetScriptExecutionDisabledParams{Value: !scripts}))
for _, width := range []int64{320, 1200} {
- run("width", emulation.SetDeviceMetricsOverride(width, 900, 1, false))
+ run("width", command(emulation.SetDeviceMetricsOverride, emulation.SetDeviceMetricsOverrideParams{Width: width, Height: 900, DeviceScaleFactor: 1}))
for _, path := range []string{"/help/colophon", "/help/colophon/carlito", "/help/colophon/prosemirror", "/help/fonts"} {
var m measure
- run(path, chromedp.Navigate(rig.Origin+path), chromedp.WaitReady("[estilo-colophon]", chromedp.ByQuery), chromedp.Sleep(150*time.Millisecond), chromedp.Evaluate(script, &m))
+ run(path, chromedp.Navigate(rig.Origin+path), chromedp.WaitReady(chromedp.CSS("[estilo-colophon]")), chromedp.Sleep(150*time.Millisecond), evalInto(&m, script))
where := fmt.Sprintf("%s at %dpx, scripts %v", path, width, scripts)
if !m.HasMain || m.Headings != 1 {
t.Fatalf("%s: the page did not render (%+v)", where, m)
diff --git a/internal/docs/fonts_browser_test.go b/internal/docs/fonts_browser_test.go
index 040a63a..4f34801 100644
--- a/internal/docs/fonts_browser_test.go
+++ b/internal/docs/fonts_browser_test.go
@@ -34,11 +34,11 @@ import (
"amadan.net/rastrillo/rastrillo"
"amadan.net/rastrillo/rastrillo/harness"
+ "github.com/chromedp/cdproto/cdp"
"github.com/chromedp/cdproto/emulation"
"github.com/chromedp/cdproto/input"
"github.com/chromedp/cdproto/network"
"github.com/chromedp/cdproto/page"
- cdpruntime "github.com/chromedp/cdproto/runtime"
"github.com/chromedp/chromedp"
"github.com/chromedp/chromedp/kb"
@@ -112,21 +112,17 @@ func newFontRig(t *testing.T) *fontRig {
})
})
fr.cookies = signInCookies(t, fr.app, "fonts@example.com")
- var set []chromedp.Action
+ var set []chromedp.Action[chromedp.Void]
for _, c := range fr.cookies {
- set = append(set, network.SetCookie(c.Name, c.Value).WithURL(fr.rig.Origin+"/").
- WithHTTPOnly(c.HttpOnly).WithSecure(c.Secure).WithSameSite(network.CookieSameSiteLax))
+ set = append(set, setCookie(fr.rig.Origin, c))
}
// Wide enough for the whole sheet, so the line-break check measures
// the 6.5in column the PDF sets.
- set = append(set, emulation.SetDeviceMetricsOverride(1280, 1000, 1, false),
+ set = append(set, command(emulation.SetDeviceMetricsOverride, emulation.SetDeviceMetricsOverrideParams{Width: 1280, Height: 1000, DeviceScaleFactor: 1}),
// No HTTP cache between checks: each one is a first visit, which
// is when the fonts have to come over the network.
- network.SetCacheDisabled(true),
- chromedp.ActionFunc(func(ctx context.Context) error {
- _, err := page.AddScriptToEvaluateOnNewDocument(probeJS).Do(ctx)
- return err
- }))
+ command(network.SetCacheDisabled, network.SetCacheDisabledParams{CacheDisabled: true}),
+ command(page.AddScriptToEvaluateOnNewDocument, page.AddScriptToEvaluateOnNewDocumentParams{Source: probeJS}))
fr.rig.Run(set...)
return fr
}
@@ -220,7 +216,7 @@ type probe struct {
func (fr *fontRig) probe(t *testing.T) probe {
t.Helper()
var raw string
- fr.rig.Run(chromedp.Evaluate(`JSON.stringify(window.__fontProbe)`, &raw))
+ fr.rig.Run(evalInto(&raw, `JSON.stringify(window.__fontProbe)`))
var p probe
if err := json.Unmarshal([]byte(raw), &p); err != nil {
t.Fatalf("probe: %v (%s)", err, raw)
@@ -234,33 +230,70 @@ func (fr *fontRig) probe(t *testing.T) probe {
func (fr *fontRig) open(t *testing.T, sqid string) {
t.Helper()
fr.rig.Run(fr.navigate("/d/"+sqid),
- chromedp.WaitVisible(`html[data-docs-fonts="shown"] [docs-text]`, chromedp.ByQuery))
+ chromedp.WaitVisible(chromedp.CSS(`html[data-docs-fonts="shown"] [docs-text]`)))
}
// navigate goes to path without waiting for the load event, which waits
// for every font the page has started fetching: a check of what happens
// while a font is slow must be able to act while it is.
-func (fr *fontRig) navigate(path string) chromedp.Action {
- return chromedp.ActionFunc(func(ctx context.Context) error {
- _, _, _, _, err := page.Navigate(fr.rig.Origin + path).Do(ctx)
- return err
- })
+func (fr *fontRig) navigate(path string) chromedp.Action[chromedp.Void] {
+ return command(page.Navigate, page.NavigateParams{URL: fr.rig.Origin + path})
}
// editable waits until the editor accepts input, which is once every
// face of every family in use has settled.
func (fr *fontRig) editable(t *testing.T) {
t.Helper()
- fr.rig.Run(chromedp.WaitVisible(`[docs-text][contenteditable="true"]`, chromedp.ByQuery))
+ fr.rig.Run(chromedp.WaitVisible(chromedp.CSS(`[docs-text][contenteditable="true"]`)))
}
func (fr *fontRig) eval(t *testing.T, js string, out any, await ...bool) {
t.Helper()
+ var opts []chromedp.EvaluateOption
if len(await) > 0 && await[0] {
- fr.rig.Run(chromedp.Evaluate(js, out, func(p *cdpruntime.EvaluateParams) *cdpruntime.EvaluateParams { return p.WithAwaitPromise(true) }))
+ opts = append(opts, chromedp.EvalAwaitPromise)
+ }
+ var raw json.RawMessage
+ fr.rig.Run(evalInto(&raw, js, opts...))
+ if len(raw) == 0 || string(raw) == "null" {
return
}
- fr.rig.Run(chromedp.Evaluate(js, out))
+ if err := json.Unmarshal(raw, out); err != nil {
+ t.Fatalf("eval: decoding %s: %v", raw, err)
+ }
+}
+
+// evalInto is a step that evaluates js and decodes the result into out.
+// A script that returns null or undefined leaves out as it was, as
+// chromedp v0.14's Evaluate did; v0.21's fails on null for a type that
+// cannot be nil, so the result is read through a pointer.
+func evalInto[T any](out *T, js string, opts ...chromedp.EvaluateOption) chromedp.Action[chromedp.Void] {
+ return chromedp.Func(func(ctx context.Context, t *chromedp.Target) error {
+ v, err := chromedp.Evaluate[*T](js, opts...)(ctx, t)
+ if err != nil {
+ return err
+ }
+ if v != nil {
+ *out = *v
+ }
+ return nil
+ })
+}
+
+// command is a step that sends one protocol command and drops its result.
+func command[P, R any](c cdp.Command[P, R], params P) chromedp.Action[chromedp.Void] {
+ return chromedp.Func(func(ctx context.Context, t *chromedp.Target) error {
+ _, err := cdp.Call(ctx, t, c, params)
+ return err
+ })
+}
+
+// setCookie is a step that sets a sign-in cookie for the rig's origin.
+func setCookie(origin string, c *http.Cookie) chromedp.Action[chromedp.Void] {
+ return command(network.SetCookie, network.SetCookieParams{
+ Name: c.Name, Value: c.Value, URL: origin + "/",
+ HTTPOnly: &c.HttpOnly, Secure: &c.Secure, SameSite: network.CookieSameSiteLax,
+ })
}
// Text is not painted before its fonts are ready. Every font file is
@@ -352,9 +385,9 @@ func TestFontEachPickerEntryRendersInItsOwnFace(t *testing.T) {
sqid := fr.document(t, "Picker", "")
fr.open(t, sqid)
fr.rig.Run(
- chromedp.WaitEnabled(`#docs-select-font-combo`, chromedp.ByQuery),
- chromedp.Click(`#docs-select-font-combo`, chromedp.ByQuery),
- chromedp.WaitVisible(`#docs-select-font-listbox [rst-combo-option]`, chromedp.ByQuery),
+ chromedp.WaitEnabled(chromedp.CSS(`#docs-select-font-combo`)),
+ chromedp.Click(chromedp.CSS(`#docs-select-font-combo`)),
+ chromedp.WaitVisible(chromedp.CSS(`#docs-select-font-listbox [rst-combo-option]`)),
)
var rows []struct {
Text string `json:"text"`
@@ -422,7 +455,7 @@ func TestFontPickingAFontLoadsItBeforeApplyingIt(t *testing.T) {
if early {
t.Error("the mark was applied while Playfair Display was still loading")
}
- fr.rig.Run(chromedp.WaitVisible(`[docs-text] .docs-font-playfair`, chromedp.ByQuery))
+ fr.rig.Run(chromedp.WaitVisible(chromedp.CSS(`[docs-text] .docs-font-playfair`)))
p := fr.probe(t)
for _, v := range p.Violations {
t.Error(v)
@@ -458,7 +491,7 @@ func TestFontACollaboratorsFontChangeWaitsForTheFont(t *testing.T) {
t.Fatalf("the collaborator's POST: %d %s", rec.Code, rec.Body.String())
}
posted := time.Now()
- fr.rig.Run(chromedp.WaitVisible(`[docs-text] .docs-font-playfair`, chromedp.ByQuery))
+ fr.rig.Run(chromedp.WaitVisible(chromedp.CSS(`[docs-text] .docs-font-playfair`)))
if waited := time.Since(posted); waited < 1200*time.Millisecond {
t.Errorf("the change appeared %v after it was posted, sooner than its font could have loaded", waited)
}
@@ -586,7 +619,7 @@ func TestFontARemoteChangeWaitsForTheFacesItUses(t *testing.T) {
fr.open(t, sqid)
fr.rig.Run(chromedp.Sleep(300 * time.Millisecond))
fr.post(t, sqid, c.vector)
- fr.rig.Run(chromedp.WaitVisible(c.sel, chromedp.ByQuery), chromedp.Sleep(200*time.Millisecond))
+ fr.rig.Run(chromedp.WaitVisible(chromedp.CSS(c.sel)), chromedp.Sleep(200*time.Millisecond))
fr.noViolations(t)
})
}
@@ -607,7 +640,7 @@ func TestFontAPasteAndAnInputRuleWaitForTheirFaces(t *testing.T) {
fr.eval(t, `(() => { const el = document.querySelector('[docs-text]'); el.focus();
const d = new DataTransfer(); d.setData('text/html', '<p><code>Pasted code</code></p>');
return el.dispatchEvent(new ClipboardEvent('paste', { clipboardData: d, bubbles: true, cancelable: true })) })()`, &ok)
- fr.rig.Run(chromedp.WaitVisible(`[docs-text] code`, chromedp.ByQuery), chromedp.Sleep(200*time.Millisecond))
+ fr.rig.Run(chromedp.WaitVisible(chromedp.CSS(`[docs-text] code`)), chromedp.Sleep(200*time.Millisecond))
fr.noViolations(t)
})
t.Run("heading rule", func(t *testing.T) {
@@ -623,8 +656,8 @@ func TestFontAPasteAndAnInputRuleWaitForTheirFaces(t *testing.T) {
fr.eval(t, `(() => { const p = document.querySelector('[docs-text] p:last-child'); const r = document.createRange();
r.selectNodeContents(p); r.collapse(false); getSelection().removeAllRanges(); getSelection().addRange(r);
document.querySelector('[docs-text]').focus(); return true })()`, &ok)
- fr.rig.Run(chromedp.KeyEvent("\r"), chromedp.SendKeys(`[docs-text]`, "# A heading", chromedp.ByQuery),
- chromedp.WaitVisible(`[docs-text] h1`, chromedp.ByQuery), chromedp.Sleep(300*time.Millisecond))
+ fr.rig.Run(chromedp.KeyEvent("\r"), chromedp.SendKeys(chromedp.CSS(`[docs-text]`), "# A heading"),
+ chromedp.WaitVisible(chromedp.CSS(`[docs-text] h1`)), chromedp.Sleep(300*time.Millisecond))
fr.noViolations(t)
})
}
@@ -652,7 +685,7 @@ func TestFontABoldThatCannotLoadChangesNothing(t *testing.T) {
var ok bool
fr.eval(t, `(() => { const p = document.querySelector('[docs-text] p'); const r = document.createRange(); r.selectNodeContents(p);
getSelection().removeAllRanges(); getSelection().addRange(r); document.querySelector('[docs-text]').focus(); return true })()`, &ok)
- fr.rig.Run(chromedp.Sleep(100*time.Millisecond), chromedp.Click(`[docs-toolbar] [data-docs-command="strong"]`, chromedp.ByQuery),
+ fr.rig.Run(chromedp.Sleep(100*time.Millisecond), chromedp.Click(chromedp.CSS(`[docs-toolbar] [data-docs-command="strong"]`)),
chromedp.Sleep(8*time.Second))
fr.eval(t, face, &after)
if before != after || strings.Contains(after, "Docs Carlito") {
@@ -685,10 +718,10 @@ func TestFontTheFirstRevealIsTheFinalLayout(t *testing.T) {
t.Run(c.name, func(t *testing.T) {
fr := newFontRig(t)
sqid := fr.document(t, "Pages", "long.bin")
- fr.rig.Run(network.SetCookie("docs-view", "paged").WithURL(fr.rig.Origin + "/"))
+ fr.rig.Run(command(network.SetCookie, network.SetCookieParams{Name: "docs-view", Value: "paged", URL: fr.rig.Origin + "/"}))
fr.editorDelay.Store(int64(c.delay))
fr.rig.Run(fr.navigate("/d/"+sqid),
- chromedp.WaitVisible(`[docs-page]`, chromedp.ByQuery), chromedp.Sleep(c.delay+1500*time.Millisecond))
+ chromedp.WaitVisible(chromedp.CSS(`[docs-page]`)), chromedp.Sleep(c.delay+1500*time.Millisecond))
p := fr.noViolations(t)
var gaps, height int
fr.eval(t, `document.querySelectorAll('[docs-page-gap]').length`, &gaps)
@@ -821,9 +854,9 @@ func TestFontTheClosedPickerFollowsTheCaret(t *testing.T) {
func TestFontWithoutJavaScriptTheSystemFacesAreFinal(t *testing.T) {
fr := newFontRig(t)
sqid := fr.document(t, "No script", "faces.bin")
- fr.rig.Run(emulation.SetScriptExecutionDisabled(true))
+ fr.rig.Run(command(emulation.SetScriptExecutionDisabled, emulation.SetScriptExecutionDisabledParams{Value: true}))
fr.slow.Store(int64(1500 * time.Millisecond))
- fr.rig.Run(fr.navigate("/d/"+sqid), chromedp.WaitReady(`[docs-page]`, chromedp.ByQuery))
+ fr.rig.Run(fr.navigate("/d/"+sqid), chromedp.WaitReady(chromedp.CSS(`[docs-page]`)))
read := func() (vis, family string, loaded int) {
var out []any
fr.eval(t, `[getComputedStyle(document.querySelector('[docs-page]')).visibility,
@@ -862,7 +895,7 @@ func TestFontAPastedFontStackMapsLikeTheNativeApp(t *testing.T) {
'<span style="font-family: Calibri, Arial">Calibri</span> <span style="font-family: Wingdings">Unknown</span> ' +
'<span style="font-family: Menlo, &quot;Courier New&quot;, monospace">Menlo</span></p>');
return el.dispatchEvent(new ClipboardEvent('paste', { clipboardData: d, bubbles: true, cancelable: true })) })()`, &ok)
- fr.rig.Run(chromedp.WaitVisible(`[docs-text] .docs-font-caladea`, chromedp.ByQuery), chromedp.Sleep(300*time.Millisecond))
+ fr.rig.Run(chromedp.WaitVisible(chromedp.CSS(`[docs-text] .docs-font-caladea`)), chromedp.Sleep(300*time.Millisecond))
var got map[string]string
fr.eval(t, `Object.fromEntries(['Georgia', 'Calibri', 'Unknown', 'Menlo'].map((w) => {
const walker = document.createTreeWalker(document.querySelector('[docs-text]'), NodeFilter.SHOW_TEXT);
@@ -893,7 +926,7 @@ func TestFontANestedPastedFontWinsOverItsParent(t *testing.T) {
d.setData('text/html', '<p style="font-family: Inter">Outer <span style="font-family: Calibri">Inner1</span> ' +
'<span style="font-family: Wingdings">Inner2</span> <span style="font-family: Cambria">Inner3</span> <span>Inner4</span></p>');
return el.dispatchEvent(new ClipboardEvent('paste', { clipboardData: d, bubbles: true, cancelable: true })) })()`, &ok)
- fr.rig.Run(chromedp.WaitVisible(`[docs-text] .docs-font-caladea`, chromedp.ByQuery), chromedp.Sleep(300*time.Millisecond))
+ fr.rig.Run(chromedp.WaitVisible(chromedp.CSS(`[docs-text] .docs-font-caladea`)), chromedp.Sleep(300*time.Millisecond))
var got map[string]string
fr.eval(t, `Object.fromEntries(['Outer', 'Inner1', 'Inner2', 'Inner3', 'Inner4'].map((w) => {
const walker = document.createTreeWalker(document.querySelector('[docs-text]'), NodeFilter.SHOW_TEXT);
@@ -1050,7 +1083,7 @@ func (fr *fontRig) checkGateCoverage(t *testing.T, dir, name string, late bool)
if mounted {
fr.blocked.Store("")
fr.open(t, doc.Sqid)
- fr.rig.Run(chromedp.WaitVisible(`[docs-text].ProseMirror`, chromedp.ByQuery))
+ fr.rig.Run(chromedp.WaitVisible(chromedp.CSS(`[docs-text].ProseMirror`)))
} else {
fr.blocked.Store("/static/editor.")
fr.open(t, doc.Sqid)
@@ -1168,7 +1201,7 @@ func TestFontEveryInputPathWaitsForItsFamily(t *testing.T) {
document.querySelector('[docs-text]').focus(); return true })()`
rows := []struct {
name, slow string
- steps []chromedp.Action
+ steps []chromedp.Action[chromedp.Void]
wait string
post string // a collaborator's vector instead of browser steps
}{
@@ -1210,12 +1243,12 @@ func TestFontEveryInputPathWaitsForItsFamily(t *testing.T) {
fr.eval(t, caretAtEnd, &ok)
// The toggle waits for code's face with the editor inert;
// typing goes in once it is back.
- fr.rig.Run(chromedp.Click(`[docs-toolbar] [data-docs-command="code"]`, chromedp.ByQuery))
+ fr.rig.Run(chromedp.Click(chromedp.CSS(`[docs-toolbar] [data-docs-command="code"]`)))
fr.settled(t)
fr.rig.Run(chromedp.KeyEvent(" typed as code"))
case "type a list after toggling code":
fr.eval(t, caretAtEnd, &ok)
- fr.rig.Run(chromedp.KeyEvent("\r"), chromedp.Click(`[docs-toolbar] [data-docs-command="code"]`, chromedp.ByQuery))
+ fr.rig.Run(chromedp.KeyEvent("\r"), chromedp.Click(chromedp.CSS(`[docs-toolbar] [data-docs-command="code"]`)))
fr.settled(t)
fr.rig.Run(chromedp.KeyEvent("- a listed code item"))
}
@@ -1223,15 +1256,15 @@ func TestFontEveryInputPathWaitsForItsFamily(t *testing.T) {
fr.post(t, sqid, row.post)
}
if text, ok := strings.CutPrefix(row.wait, "text:"); ok {
- fr.rig.Run(chromedp.Poll(`document.querySelector('[docs-text]').textContent.includes(`+strconv.Quote(text)+`)`, nil))
+ fr.rig.Run(chromedp.Poll[chromedp.Void](`document.querySelector('[docs-text]').textContent.includes(` + strconv.Quote(text) + `)`))
} else {
- fr.rig.Run(chromedp.WaitVisible(row.wait, chromedp.ByQuery))
+ fr.rig.Run(chromedp.WaitVisible(chromedp.CSS(row.wait)))
}
// Long enough for the held family to arrive and be applied.
fr.rig.Run(chromedp.Sleep(2500 * time.Millisecond))
if row.name == "paste, undo, redo" {
- fr.rig.Run(chromedp.KeyEvent("z", chromedp.KeyModifiers(input.ModifierMeta)), chromedp.Sleep(300*time.Millisecond),
- chromedp.KeyEvent("z", chromedp.KeyModifiers(input.ModifierMeta|input.ModifierShift)), chromedp.Sleep(300*time.Millisecond))
+ fr.rig.Run(chromedp.KeyEvent("z", chromedp.KeyModifiers(chromedp.ModifierMeta)), chromedp.Sleep(300*time.Millisecond),
+ chromedp.KeyEvent("z", chromedp.KeyModifiers(chromedp.ModifierMeta|chromedp.ModifierShift)), chromedp.Sleep(300*time.Millisecond))
}
p := fr.noViolations(t)
for run, faces := range p.Seen {
@@ -1296,8 +1329,8 @@ func (fr *fontRig) waitLog(t *testing.T) []waitEntry {
// settled waits until no font wait is in progress.
func (fr *fontRig) settled(t *testing.T) {
t.Helper()
- fr.rig.Run(chromedp.Poll(`(() => { const s = document.querySelector('[docs-fonts-status]'); const d = document.querySelector('[docs-text]');
- return !d.inert && d.getAttribute('contenteditable') === 'true' && !['loading', 'refused'].includes((s && s.getAttribute('data-state')) || '') })()`, nil,
+ fr.rig.Run(chromedp.Poll[chromedp.Void](`(() => { const s = document.querySelector('[docs-fonts-status]'); const d = document.querySelector('[docs-text]');
+ return !d.inert && d.getAttribute('contenteditable') === 'true' && !['loading', 'refused'].includes((s && s.getAttribute('data-state')) || '') })()`,
chromedp.WithPollingTimeout(15*time.Second)))
}
@@ -1346,8 +1379,8 @@ const docTextJS = `document.querySelector('[docs-text]').innerText.replace(/\n+/
// the wait.
func TestFontAWaitIsAShortModal(t *testing.T) {
const plain = "First paragraph.|Second paragraph."
- meta := chromedp.KeyModifiers(input.ModifierMeta)
- keys := []chromedp.Action{chromedp.KeyEvent("ab"), chromedp.KeyEvent(kb.Backspace), chromedp.KeyEvent(kb.ArrowLeft), chromedp.KeyEvent("X")}
+ meta := chromedp.KeyModifiers(chromedp.ModifierMeta)
+ keys := []chromedp.Action[chromedp.Void]{chromedp.KeyEvent("ab"), chromedp.KeyEvent(kb.Backspace), chromedp.KeyEvent(kb.ArrowLeft), chromedp.KeyEvent("X")}
rows := []struct {
name string
slow time.Duration
@@ -1372,7 +1405,7 @@ func TestFontAWaitIsAShortModal(t *testing.T) {
}
}},
{name: "an IME commit during the wait goes nowhere", during: func(t *testing.T, fr *fontRig) {
- fr.rig.Run(input.ImeSetComposition("にほん", 3, 3), chromedp.Sleep(100*time.Millisecond), input.InsertText("日本"))
+ fr.rig.Run(command(input.ImeSetComposition, input.ImeSetCompositionParams{Text: "にほん", SelectionStart: 3, SelectionEnd: 3}), chromedp.Sleep(100*time.Millisecond), command(input.InsertText, input.InsertTextParams{Text: "日本"}))
}, want: "PASTE" + plain},
{name: "the title keeps what is typed into it", during: func(t *testing.T, fr *fontRig) {
var ok bool
@@ -1510,7 +1543,7 @@ func TestFontUndoAfterABlockedPasteUndoesThePaste(t *testing.T) {
fr.eval(t, `(() => { const el = document.querySelector('[docs-text]'); const d = new DataTransfer();
d.setData('text/html', '<span style="font-family: Caveat">PASTE</span>');
el.dispatchEvent(new ClipboardEvent('paste', { clipboardData: d, bubbles: true, cancelable: true })); return true })()`, &ok)
- fr.rig.Run(chromedp.WaitVisible(`[docs-text] .docs-font-caveat`, chromedp.ByQuery), chromedp.Sleep(800*time.Millisecond))
+ fr.rig.Run(chromedp.WaitVisible(chromedp.CSS(`[docs-text] .docs-font-caveat`)), chromedp.Sleep(800*time.Millisecond))
text := func() string {
var s string
fr.eval(t, `document.querySelector('[docs-text] p').textContent`, &s)
@@ -1519,11 +1552,11 @@ func TestFontUndoAfterABlockedPasteUndoesThePaste(t *testing.T) {
if got := text(); got != "abcPASTEFirst paragraph." {
t.Fatalf("after the paste the paragraph is %q", got)
}
- fr.rig.Run(chromedp.KeyEvent("z", chromedp.KeyModifiers(input.ModifierMeta)), chromedp.Sleep(400*time.Millisecond))
+ fr.rig.Run(chromedp.KeyEvent("z", chromedp.KeyModifiers(chromedp.ModifierMeta)), chromedp.Sleep(400*time.Millisecond))
if got := text(); got != "abcFirst paragraph." {
t.Errorf("undo left %q; it should take the paste back and only the paste", got)
}
- fr.rig.Run(chromedp.KeyEvent("z", chromedp.KeyModifiers(input.ModifierMeta|input.ModifierShift)), chromedp.Sleep(400*time.Millisecond))
+ fr.rig.Run(chromedp.KeyEvent("z", chromedp.KeyModifiers(chromedp.ModifierMeta|chromedp.ModifierShift)), chromedp.Sleep(400*time.Millisecond))
if got := text(); got != "abcPASTEFirst paragraph." {
t.Errorf("redo left %q", got)
}
@@ -1546,7 +1579,7 @@ func TestFontACompositionInALoadedFamilyNeverBlocks(t *testing.T) {
const el = document.querySelector('[docs-text]'); el.focus();
const n = document.createTreeWalker(el.querySelector('p'), NodeFilter.SHOW_TEXT).nextNode(); const r = document.createRange();
r.setStart(n, 0); r.collapse(true); getSelection().removeAllRanges(); getSelection().addRange(r); return true })()`, &ok)
- fr.rig.Run(input.ImeSetComposition("にほん", 3, 3), chromedp.Sleep(200*time.Millisecond), input.InsertText("日本"), chromedp.Sleep(500*time.Millisecond))
+ fr.rig.Run(command(input.ImeSetComposition, input.ImeSetCompositionParams{Text: "にほん", SelectionStart: 3, SelectionEnd: 3}), chromedp.Sleep(200*time.Millisecond), command(input.InsertText, input.InsertTextParams{Text: "日本"}), chromedp.Sleep(500*time.Millisecond))
var text string
var lost bool
fr.eval(t, `document.querySelector('[docs-text] p').textContent`, &text)
@@ -1640,7 +1673,7 @@ func TestFontTheStatusNeverCoversText(t *testing.T) {
for _, state := range []string{"loading", "refused", "unavailable", "substitute"} {
t.Run(fmt.Sprintf("%dx%d %s", size.w, size.h, state), func(t *testing.T) {
fr := newFontRig(t)
- fr.rig.Run(emulation.SetDeviceMetricsOverride(size.w, size.h, 1, false))
+ fr.rig.Run(command(emulation.SetDeviceMetricsOverride, emulation.SetDeviceMetricsOverrideParams{Width: int64(size.w), Height: int64(size.h), DeviceScaleFactor: 1}))
vector := "long.bin"
switch state {
case "loading", "refused":
@@ -1757,17 +1790,16 @@ func TestFontPrefetchFollowsTheReveal(t *testing.T) {
sqid := fr.document(t, "Prefetch", "simple.bin")
// A real visit's cache: the prefetch puts each file there, and
// the face is then loaded from it.
- fr.rig.Run(network.SetCacheDisabled(false), chromedp.ActionFunc(func(ctx context.Context) error {
- _, err := page.AddScriptToEvaluateOnNewDocument(shownAtJS).Do(ctx)
- return err
- }))
+ fr.rig.Run(command(network.SetCacheDisabled, network.SetCacheDisabledParams{CacheDisabled: false}),
+ command(page.AddScriptToEvaluateOnNewDocument, page.AddScriptToEvaluateOnNewDocumentParams{Source: shownAtJS}))
if saveData {
- fr.rig.Run(emulation.SetDataSaverOverride().WithDataSaverEnabled(true))
+ enabled := true
+ fr.rig.Run(command(emulation.SetDataSaverOverride, emulation.SetDataSaverOverrideParams{DataSaverEnabled: &enabled}))
}
var mu sync.Mutex
priority := map[string]network.ResourcePriority{}
- chromedp.ListenTarget(fr.rig.Context(), func(ev any) {
- if e, ok := ev.(*network.EventRequestWillBeSent); ok && e.Type == network.ResourceTypeFetch && strings.HasSuffix(e.Request.URL, ".woff2") {
+ harness.Listen(fr.rig, fr.rig.Context(), network.RequestWillBeSent, func(e *network.EventRequestWillBeSent) {
+ if e.Type == network.ResourceTypeFetch && strings.HasSuffix(e.Request.URL, ".woff2") {
mu.Lock()
priority[e.Request.URL] = e.Request.InitialPriority
mu.Unlock()
@@ -1778,7 +1810,7 @@ func TestFontPrefetchFollowsTheReveal(t *testing.T) {
if saveData {
fr.rig.Run(chromedp.Sleep(4 * time.Second))
} else {
- fr.rig.Run(chromedp.Poll(`document.documentElement.getAttribute('data-docs-fonts-prefetch') === 'done'`, nil, chromedp.WithPollingTimeout(60*time.Second)))
+ fr.rig.Run(chromedp.Poll[chromedp.Void](`document.documentElement.getAttribute('data-docs-fonts-prefetch') === 'done'`, chromedp.WithPollingTimeout(60*time.Second)))
}
var raw string
fr.eval(t, fontFacesJS, &raw)
@@ -1870,8 +1902,8 @@ func TestFontAWaitDuringThePrefetch(t *testing.T) {
fr.match.Store("Caladea-")
fr.slow.Store(int64(2 * time.Second))
fetching := make(chan struct{}, 1)
- chromedp.ListenTarget(fr.rig.Context(), func(ev any) {
- if e, ok := ev.(*network.EventRequestWillBeSent); ok && e.Type == network.ResourceTypeFetch && strings.Contains(e.Request.URL, "Caladea-") {
+ harness.Listen(fr.rig, fr.rig.Context(), network.RequestWillBeSent, func(e *network.EventRequestWillBeSent) {
+ if e.Type == network.ResourceTypeFetch && strings.Contains(e.Request.URL, "Caladea-") {
select {
case fetching <- struct{}{}:
default:
@@ -1920,14 +1952,14 @@ func TestFontACompositionNeverStartsAWait(t *testing.T) {
var ok bool
fr.eval(t, waitLogJS, &ok)
fr.eval(t, selectInJS("p:last-child", -1, -1), &ok)
- fr.rig.Run(input.ImeSetComposition("にほん", 3, 3), chromedp.Sleep(150*time.Millisecond))
+ fr.rig.Run(command(input.ImeSetComposition, input.ImeSetCompositionParams{Text: "にほん", SelectionStart: 3, SelectionEnd: 3}), chromedp.Sleep(150*time.Millisecond))
// ProseMirror ignores a paste during a composition; a drop it takes.
fr.eval(t, `(() => { const el = document.querySelector('[docs-text]');
const d = new DataTransfer(); d.setData('text/html', '<p style="font-family: Caveat">DROPPED</p>');
const r = el.querySelector('p').getBoundingClientRect();
el.dispatchEvent(new DragEvent('drop', { dataTransfer: d, bubbles: true, cancelable: true, clientX: r.left + 30, clientY: r.top + 8 }));
return true })()`, &ok)
- fr.rig.Run(chromedp.Sleep(150*time.Millisecond), input.InsertText("日本"), chromedp.Sleep(500*time.Millisecond))
+ fr.rig.Run(chromedp.Sleep(150*time.Millisecond), command(input.InsertText, input.InsertTextParams{Text: "日本"}), chromedp.Sleep(500*time.Millisecond))
for _, e := range fr.waitLog(t) {
if e.Inert {
t.Errorf("at %dms a wait began during the composition", e.Ms)
diff --git a/internal/docs/zoom_browser_test.go b/internal/docs/zoom_browser_test.go
index 094daf6..2671ac1 100644
--- a/internal/docs/zoom_browser_test.go
+++ b/internal/docs/zoom_browser_test.go
@@ -20,8 +20,8 @@ import (
"time"
"amadan.net/rastrillo/rastrillo/harness"
+ "github.com/chromedp/cdproto/cdp"
"github.com/chromedp/cdproto/emulation"
- "github.com/chromedp/cdproto/network"
"github.com/chromedp/chromedp"
"github.com/carlosframework/docs/internal/docs"
@@ -73,13 +73,12 @@ func TestNoZoomOnTap(t *testing.T) {
}
sqid := strings.TrimPrefix(created.Header().Get("Location"), "/d/")
- run := func(what string, actions ...chromedp.Action) {
+ run := func(what string, actions ...chromedp.Action[chromedp.Void]) {
t.Helper()
ctx, cancel := context.WithTimeout(rig.Context(), 20*time.Second)
defer cancel()
- if err := chromedp.Run(ctx, actions...); err != nil {
- var at string
- _ = chromedp.Run(rig.Context(), chromedp.Location(&at))
+ if err := chromedp.Do(ctx, actions...); err != nil {
+ at, _ := chromedp.Run(rig.Context(), chromedp.Location())
t.Fatalf("%s: %v (the browser is at %s)", what, err, at)
}
}
@@ -87,23 +86,23 @@ func TestNoZoomOnTap(t *testing.T) {
// its media queries. SetEmulatedMedia's "pointer" feature is not
// emulated by this Chromium; the coarse check below is what proves
// the emulation took.
- run("touch emulation", emulation.SetTouchEmulationEnabled(true).WithMaxTouchPoints(5))
+ run("touch emulation", command(emulation.SetTouchEmulationEnabled, emulation.SetTouchEmulationEnabledParams{Enabled: true, MaxTouchPoints: 5}))
once := false
- measure := func(path, ready string, open ...chromedp.Action) {
+ measure := func(path, ready string, open ...chromedp.Action[chromedp.Void]) {
t.Helper()
var coarse bool
var small []string
- actions := []chromedp.Action{chromedp.Navigate(rig.Origin + path)}
+ actions := []chromedp.Action[chromedp.Void]{chromedp.Navigate(rig.Origin + path)}
if !once {
actions = append(actions, chromedp.Reload())
}
actions = append(actions,
- chromedp.WaitVisible(ready, chromedp.ByQuery),
- chromedp.Evaluate(`matchMedia('(pointer: coarse)').matches`, &coarse),
+ chromedp.WaitVisible(chromedp.CSS(ready)),
+ evalInto(&coarse, `matchMedia('(pointer: coarse)').matches`),
)
actions = append(actions, open...)
- actions = append(actions, chromedp.Evaluate(smallControls(textControls), &small))
+ actions = append(actions, evalInto(&small, smallControls(textControls)))
run(path, actions...)
if !coarse {
t.Fatalf("%s: the touch-screen emulation did not apply; this would measure desktop styles", path)
@@ -116,10 +115,9 @@ func TestNoZoomOnTap(t *testing.T) {
// Signed out first: the door is the field every visit starts on.
measure("/signin", `input[name="address"]`)
- var set []chromedp.Action
+ var set []chromedp.Action[chromedp.Void]
for _, c := range cookies {
- set = append(set, network.SetCookie(c.Name, c.Value).WithURL(rig.Origin+"/").
- WithHTTPOnly(c.HttpOnly).WithSecure(c.Secure).WithSameSite(network.CookieSameSiteLax))
+ set = append(set, setCookie(rig.Origin, c))
}
run("sign in", set...)
@@ -127,7 +125,7 @@ func TestNoZoomOnTap(t *testing.T) {
// The toolbar's three selects, once select.js has enhanced them, and
// the title field in the bar.
measure("/d/"+sqid, `[contenteditable="true"]`,
- chromedp.WaitVisible(`[estilo-bar-title-input], [docs-toolbar] input, [docs-toolbar] select`, chromedp.ByQuery))
+ chromedp.WaitVisible(chromedp.CSS(`[estilo-bar-title-input], [docs-toolbar] input, [docs-toolbar] select`)))
// The share page, then published: the link field shows only in the
// one render that follows the publish.
// A wide touch screen (an iPad in landscape, 1280px): from 64rem the
@@ -137,18 +135,18 @@ func TestNoZoomOnTap(t *testing.T) {
// The header's undo/redo are 32px targets there too, in a 32px pill.
var inspector string
var lead []float64
- run("a wide touch screen", emulation.SetDeviceMetricsOverride(1280, 900, 1, false))
+ run("a wide touch screen", command(emulation.SetDeviceMetricsOverride, emulation.SetDeviceMetricsOverrideParams{Width: 1280, Height: 900, DeviceScaleFactor: 1}))
measure("/d/"+sqid, `[contenteditable="true"]`,
- chromedp.WaitVisible(`[docs-inspector] [docs-toolbar] input`, chromedp.ByQuery),
- chromedp.Evaluate(`getComputedStyle(document.querySelector('[docs-inspector]')).position`, &inspector),
- chromedp.Evaluate(`(() => { const b = document.querySelector('[estilo-bar-lead] [data-docs-command="undo"]').getBoundingClientRect(); const p = document.querySelector('[estilo-bar-lead] [docs-history]').getBoundingClientRect(); return [b.width, b.height, p.height] })()`, &lead))
+ chromedp.WaitVisible(chromedp.CSS(`[docs-inspector] [docs-toolbar] input`)),
+ evalInto(&inspector, `getComputedStyle(document.querySelector('[docs-inspector]')).position`),
+ evalInto(&lead, `(() => { const b = document.querySelector('[estilo-bar-lead] [data-docs-command="undo"]').getBoundingClientRect(); const p = document.querySelector('[estilo-bar-lead] [docs-history]').getBoundingClientRect(); return [b.width, b.height, p.height] })()`))
if inspector != "fixed" {
t.Errorf("at 1280px the toolbar is not the inspector (position %q); this measured the strip", inspector)
}
if len(lead) != 3 || lead[0] < 32 || lead[1] < 32 || lead[2] != 32 {
t.Errorf("on a touch screen the header's undo is %vx%v in a %vpx pill, want 32x32 in 32", lead[0], lead[1], lead[2])
}
- run("back to the default width", emulation.ClearDeviceMetricsOverride())
+ run("back to the default width", command(emulation.ClearDeviceMetricsOverride, cdp.Empty{}))
measure("/d/"+sqid+"/share", `input[name="address"]`)
if rec := sameOrigin("/d/"+sqid+"/share/link", "on=1"); rec.Code != http.StatusSeeOther {
t.Fatalf("publishing: %d", rec.Code)
@@ -158,8 +156,8 @@ func TestNoZoomOnTap(t *testing.T) {
measure("/d/"+sqid+"/share", `[docs-share-url-input]`)
once = false
measure("/", `input[name="q"]`,
- chromedp.Evaluate(`document.dispatchEvent(new KeyboardEvent('keydown', {key: 'k', ctrlKey: true, bubbles: true}))`, nil),
- chromedp.WaitVisible(`[docs-jumpto-input]`, chromedp.ByQuery))
+ chromedp.Evaluate[chromedp.Void](`document.dispatchEvent(new KeyboardEvent('keydown', {key: 'k', ctrlKey: true, bubbles: true}))`),
+ chromedp.WaitVisible(chromedp.CSS(`[docs-jumpto-input]`)))
}
// smallControls is a script listing each visible, tappable control matching sel