oficina / slides Public

Slides: the saving browser test waits on conditions and explains its failures

TestSavingContinuesWhileALinkIsLoading decided pass or fail after fixed
pauses, and closed its pages with Playwright's page.close(), which skips
the unload handlers. One WebKit run failed that way under load and could
not be read (Claude Fable on Docs #94, round 3).

Each scenario in saving.mjs and saving-webkit.swift now watches the page
at least as long as the old pause, then waits until the test server's
view of the deck (/test/saving-state/<sqid>) holds what the scenario
needs, for at most 20 s. A scenario that never gets there fails. A trace
script records the page's fetches, keepalive POSTs, probe HEADs and
beacons. When a scenario fails, the test prints that trace next to every
POST the server got (size, encoding, status, timing) and the text it
holds. A new held-link variant closes the page as a person would, with
runBeforeUnload. Test harness only: no app code or bundle changes.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev ad9bcb282c3422f142c95f120414867d014ee3c6 parent f1141cd
3 files changed, +608 −121
  • fixtures/engines/saving-webkit.swift +96 −11
  • fixtures/engines/saving.mjs +145 −62
  • internal/slidestest/saving_browser_test.go +367 −48

CI passed — run details

diff --git a/fixtures/engines/saving-webkit.swift b/fixtures/engines/saving-webkit.swift
index 26ab077..eda7efa 100644
--- a/fixtures/engines/saving-webkit.swift
+++ b/fixtures/engines/saving-webkit.swift
@@ -22,6 +22,13 @@
// throttled, as an occluded Safari tab's are; occlusion detection is
// turned off so the page is visible, as a document someone is typing in
// is. Built by the test with swiftc; macOS only.
+//
+// As in saving.mjs, nothing waits a fixed time to decide anything: each
+// scenario watches the page at least as long as it used to, then until the
+// server's view of the document (config.state) holds config.want, for at
+// most twenty seconds, and reports whether it did. The page's requests are
+// recorded by the config's trace script and printed on a "SAVING TRACE"
+// line, which the test shows if the scenario fails.
import Cocoa
import WebKit
@@ -38,6 +45,12 @@ struct Config: Decodable {
let typing: [String: String]
let type: String
let cookies: [Cookie]
+ // trace records the page's requests; state, followed by the sqid, is
+ // the server's view of the document; want is what the server must
+ // hold for the scenario to be done.
+ let trace: String
+ let state: String
+ let want: String
let page: String
let ready: String
// back: what is typed before leaving, and how long the page is away.
@@ -75,10 +88,67 @@ struct Config: Decodable {
return false
}
+ // The fixed pause each scenario's watch replaces, and how long it
+ // waits for the server at most.
+ let watch = 3.0
+ let ceiling = 20.0
+
+ // View is the test server's side of the document: its text, how many
+ // saves it answered while the held link loaded, and every save that
+ // reached it. Asked from here, not from the page.
+ struct View: Decodable {
+ struct Post: Decodable { let status: Int }
+ let text: String
+ let held: Int
+ let posts: [Post]
+ }
+
+ func view() async -> View? {
+ guard let (data, _) = try? await URLSession.shared.data(from: URL(string: config.origin + config.state + config.doc)!) else { return nil }
+ return try? JSONDecoder().decode(View.self, from: data)
+ }
+
+ func holds(_ text: String, _ want: String) -> Bool {
+ want.split(separator: " ").allSatisfy { text.contains($0) }
+ }
+
+ // settle waits for done(view) from since, at least watchFor seconds
+ // and at most the ceiling; it says whether it came, and after how
+ // many milliseconds.
+ func settle(since: Date, watchFor: Double, _ done: (View) -> Bool) async -> (Bool, Int) {
+ while true {
+ let s = Date().timeIntervalSince(since)
+ if s >= watchFor, let v = await view(), done(v) {
+ try? await Task.sleep(for: .milliseconds(250))
+ return (true, Int(s * 1000))
+ }
+ if s >= ceiling { return (false, Int(s * 1000)) }
+ try? await Task.sleep(for: .milliseconds(100))
+ }
+ }
+
+ // report prints the scenario's "SAVING RESULT" and "SAVING TRACE"
+ // lines: the save states the page showed, whether what it waited for
+ // came, and the page's requests.
+ func report(_ engine: String, persisted: Bool? = nil, settled: Bool, ms: Int, waiting: String) async {
+ func read(_ script: String) async -> Any {
+ let s = (try? await js(script)) as? String ?? "[]"
+ return (try? JSONSerialization.jsonObject(with: Data(s.utf8))) ?? []
+ }
+ var result: [String: Any] = ["engine": engine, "states": await read("JSON.stringify(window.__saveStates || [])"), "settled": settled, "ms": ms, "waiting": waiting]
+ if let persisted { result["persisted"] = persisted }
+ let trace: [String: Any] = ["engine": engine, "trace": await read("JSON.stringify(window.__saveTrace || [])")]
+ for (prefix, line) in [("SAVING RESULT ", result), ("SAVING TRACE ", trace)] {
+ let data = try! JSONSerialization.data(withJSONObject: line, options: [.sortedKeys])
+ print(prefix + String(decoding: data, as: UTF8.self))
+ }
+ }
+
func run() async throws {
setbuf(stdout, nil)
let cfg = WKWebViewConfiguration()
cfg.websiteDataStore = .nonPersistent()
+ cfg.userContentController.addUserScript(WKUserScript(source: config.trace, injectionTime: .atDocumentStart, forMainFrameOnly: true))
let host = URL(string: config.origin)!.host!
for c in config.cookies {
let cookie = HTTPCookie(properties: [.name: c.Name, .value: c.Value, .domain: host, .path: "/"])!
@@ -104,10 +174,10 @@ struct Config: Decodable {
}
try await Task.sleep(for: .milliseconds(500))
let typing = String(data: try JSONEncoder().encode(config.typing), encoding: .utf8)!
+ let since = Date()
_ = try await js("(\(config.script))(\(typing)); true")
- try await Task.sleep(for: .seconds(3))
- let states = (try? await js("JSON.stringify(window.__saveStates || [])")) as? String ?? "[]"
- print("SAVING RESULT {\"engine\":\"wkwebview\",\"states\":\(states)}")
+ let (settled, ms) = await settle(since: since, watchFor: watch) { holds($0.text, config.want) && $0.held > 0 }
+ await report("wkwebview", settled: settled, ms: ms, waiting: "the server to hold \"\(config.want)\", saved while the link loaded")
}
// back is the "back" scenario (see the header).
@@ -123,25 +193,40 @@ struct Config: Decodable {
guard await until(editor, seconds: 30) else { throw NSError(domain: "the editor never opened", code: 1) }
try await Task.sleep(for: .milliseconds(500))
_ = try await js("window.__saveStates = []; new MutationObserver(() => window.__saveStates.push(document.querySelector('[estilo-save-status]').getAttribute('data-state'))).observe(document.querySelector('[estilo-save-status]'), { attributes: true, attributeFilter: ['data-state'] }); addEventListener('pageshow', (e) => { window.__persisted = e.persisted }); true")
- let before = String(data: try JSONEncoder().encode([config.before ?? "Before leaving"]), encoding: .utf8)!
+ let beforeText = config.before ?? "Before leaving"
+ let before = String(data: try JSONEncoder().encode([beforeText]), encoding: .utf8)!
+ var since = Date()
_ = try await js("(\(config.type))(\(before)[0]); true")
// Past the debounce: the save is on the wire, and the server holds it.
- try await Task.sleep(for: .milliseconds(600))
+ var (settled, ms) = await settle(since: since, watchFor: 0) { !$0.posts.isEmpty }
+ guard settled else {
+ await report("wkwebview-back", settled: false, ms: ms, waiting: "the save typed before leaving to reach the server")
+ return
+ }
web.load(URLRequest(url: URL(string: config.origin + "/healthz")!))
guard await until(list, seconds: 30) else { throw NSError(domain: "the document was never left", code: 1) }
// The held save is answered while the page is away, or, back
- // sooner, it is still on the wire.
- try await Task.sleep(for: .milliseconds(config.awayMs ?? 2000))
+ // sooner (awayMs), it is still on the wire.
+ if let away = config.awayMs {
+ try await Task.sleep(for: .milliseconds(away))
+ } else {
+ since = Date()
+ (settled, ms) = await settle(since: since, watchFor: 0) { v in holds(v.text, beforeText) && v.posts.allSatisfy { $0.status != 0 } }
+ guard settled else {
+ await report("wkwebview-back", settled: false, ms: ms, waiting: "the save typed before leaving to be answered while the page was away")
+ return
+ }
+ }
web.goBack()
guard await until("window.__persisted === true && " + editor, seconds: 15) else {
- print("SAVING RESULT {\"engine\":\"wkwebview-back\",\"persisted\":false,\"states\":[]}")
+ await report("wkwebview-back", persisted: false, settled: false, ms: 0, waiting: "the page to come back from the back/forward cache")
return
}
try await Task.sleep(for: .milliseconds(300))
+ since = Date()
_ = try await js("(\(config.type))('After coming back'); true")
- try await Task.sleep(for: .seconds(3))
- let states = (try? await js("JSON.stringify(window.__saveStates || [])")) as? String ?? "[]"
- print("SAVING RESULT {\"engine\":\"wkwebview-back\",\"persisted\":true,\"states\":\(states)}")
+ (settled, ms) = await settle(since: since, watchFor: watch) { holds($0.text, config.want) }
+ await report("wkwebview-back", persisted: true, settled: settled, ms: ms, waiting: "the server to hold \"\(config.want)\"")
}
}
diff --git a/fixtures/engines/saving.mjs b/fixtures/engines/saving.mjs
index 57dd842..f491092 100644
--- a/fixtures/engines/saving.mjs
+++ b/fixtures/engines/saving.mjs
@@ -15,9 +15,16 @@
// Run by internal/slidestest/saving_browser_test.go, which serves the link's
// target and holds it unanswered, counts the saves that reach it while it
// does, and reads the document back from the server afterwards. This
-// prints one "SAVING RESULT" line per engine with the save states the page
-// showed, and, given config.closing, one "SAVING CLOSED" line once a page
-// that closed with a large save on the wire has had time to beacon.
+// prints, per scenario, one "SAVING RESULT" line with the save states the
+// page showed and whether what the scenario waited for came, and one
+// "SAVING TRACE" line with the page's requests (the config's trace
+// script), which the test prints if the scenario fails.
+//
+// Nothing here waits a fixed time to decide anything. Each scenario
+// watches the page at least as long as it used to (WATCH_MS), then until
+// the server's view of the document (config.state) holds what it waits
+// for, for at most CEILING_MS. A fixed three seconds could not tell a slow
+// pass from a stall (Claude Fable on Docs #94, round 3).
const { chromium, webkit } = await import('playwright')
@@ -28,70 +35,147 @@ const pause = (ms) => new Promise((r) => setTimeout(r, ms))
// evaluates a string with eval, which Slides' CSP refuses.
const ready = (page) => page.waitForFunction(() => document.documentElement.getAttribute('data-slides-fonts') === 'shown' && !!document.querySelector('[slides-stage] [data-block="text"] [contenteditable="true"], [slides-stage] [data-block="text"][contenteditable="true"]'), null, { timeout: 30000 })
+// WATCH_MS is how long a scenario watches the save line at least: the
+// fixed pause it replaces, so no state it could see is missed now.
+// CEILING_MS is how long it waits for the server at most.
+const WATCH_MS = 3000
+const CEILING_MS = 20000
+
+// view is the test server's side of a document: its text, and every save
+// that reached it. Asked from here, not from the page, which is the one
+// whose requests are being refused.
+const view = async (sqid) => {
+ const r = await fetch(config.origin + config.state + sqid)
+ if (!r.ok) throw new Error(`${config.state}${sqid}: ${r.status}`)
+ return r.json()
+}
+
+const holds = (text, want) => want.split(/\s+/).every((w) => text.includes(w))
+
+// retried is whether the page tried a save again after one was refused:
+// the moment it decides whether to say "Trouble saving".
+const retried = (trace) => {
+ const refused = new Set(trace.filter((e) => e.ev === 'refused').map((e) => e.id))
+ const posts = trace.filter((e) => e.ev === 'start' && e.m === 'POST' && e.u.endsWith('/updates'))
+ return posts.some((p, i) => refused.has(p.id) && i < posts.length - 1)
+}
+
+// settle waits for done(view) from since, at least watchMs and at most
+// CEILING_MS, and says whether it came and when.
+async function settle (sqid, since, watchMs, done) {
+ for (;;) {
+ const ms = Date.now() - since
+ if (ms >= watchMs && done(await view(sqid))) {
+ // The page's console lines from just before are still on their way.
+ await pause(250)
+ return { settled: true, ms }
+ }
+ if (ms >= CEILING_MS) return { settled: false, ms }
+ await pause(100)
+ }
+}
+
+// open is a document's page, ready to type in, with its save states and
+// requests read from its console from the start: Playwright's own
+// evaluate waits for a pending navigation to finish, and the held link
+// never does.
+async function open (context, sqid) {
+ const page = await context.newPage()
+ const seen = { states: [], trace: [], typed: false }
+ page.on('console', (m) => {
+ const t = m.text()
+ if (t.startsWith('SAVE-STATE ')) seen.states.push(t.slice('SAVE-STATE '.length))
+ else if (t.startsWith('SAVE-TRACE ')) seen.trace.push(JSON.parse(t.slice('SAVE-TRACE '.length)))
+ else if (t === 'SAVE-TYPED') seen.typed = true
+ })
+ // A real close asks first only while a resync holds the page; yes.
+ page.on('dialog', (d) => d.accept().catch(() => {}))
+ await page.goto(config.origin + '/d/' + sqid + config.page)
+ await ready(page)
+ await pause(500)
+ return { page, seen }
+}
+
+const report = (engine, seen, got, waiting) => {
+ console.log('SAVING RESULT ' + JSON.stringify({ engine, states: seen.states, settled: got.settled, ms: got.ms, waiting }))
+ console.log('SAVING TRACE ' + JSON.stringify({ engine, trace: seen.trace }))
+}
+
+// heldScenario types into a document with the held link loading, and
+// waits for the server to hold want: saved while the link loads, given
+// link, or, given orRetried, a refused save tried again will do.
+async function heldScenario (context, engine, sqid, typing, { want, link, orRetried }) {
+ const { page, seen } = await open(context, sqid)
+ const since = Date.now()
+ await page.evaluate(`(${config.script})(${JSON.stringify(typing)})`)
+ const waiting = `the server to hold ${JSON.stringify(want.slice(0, 40))}` + (link ? ', saved while the link loaded' : '') + (orRetried ? ', or a refused save tried again' : '')
+ const got = await settle(sqid, since, WATCH_MS, (v) => (holds(v.text, want) && (!link || v.held > 0)) || (orRetried && retried(seen.trace)))
+ report(engine, seen, got, waiting)
+ // Each page done with is closed, and its held link and stream with it:
+ // left open they take the host's connections (six, on HTTP/1.1), and a
+ // later page's unload beacon queues behind them. Playwright's close
+ // skips the unload handlers, so this is harsher than a tab closing:
+ // what the scenario waited for has to have been saved already.
+ await page.close()
+}
+
for (const [engineName, engine] of Object.entries({ chromium, webkit }).filter(([n]) => !process.env.DOCS_ENGINES_ENGINE || n === process.env.DOCS_ENGINES_ENGINE)) {
const browser = await engine.launch({ headless: true })
try {
const context = await browser.newContext()
await context.addCookies(config.cookies.map((c) => ({ name: c.Name, value: c.Value, url: config.origin, httpOnly: c.HttpOnly, sameSite: 'Lax' })))
- const page = await context.newPage()
- const states = []
- // The page is read through its console from here on: Playwright's own
- // evaluate waits for a pending navigation to finish, and this one never
- // does.
- page.on('console', (m) => {
- if (m.text().startsWith('SAVE-STATE ')) states.push(m.text().slice('SAVE-STATE '.length))
- })
- await page.goto(config.origin + '/d/' + config.docs[engineName] + config.page)
- await ready(page)
- await pause(500)
- await page.evaluate(`(${config.script})(${JSON.stringify(config.typing)})`)
- // Well past the debounce and a local round trip, and the link is still
- // loading: the test's server holds it until the browser goes away.
- await pause(3000)
- console.log('SAVING RESULT ' + JSON.stringify({ engine: engineName, states }))
- // Each page done with is closed, and its held link and stream with it:
- // left open they take the host's connections (six, on HTTP/1.1), and a
- // later page's unload beacon queues behind them.
- await page.close()
-
- // The same with other edits (config.held: [{ name, docs, typing }]):
- // a large paste of prose, which goes keepalive once gzipped, and one
- // too large for a keepalive save even compressed, which WebKit refuses
- // until the link is answered. Nothing is lost, and the page must not
- // say a save failed, because none did.
+ await context.addInitScript(config.trace)
+
+ // Three words typed while the link loads: saved while it does.
+ await heldScenario(context, engineName, config.docs[engineName], config.typing, { want: config.want, link: true })
+
+ // The same, closed the way a person closes a tab, as soon as the last
+ // word is in: the unload handlers run, and the beacon carries what the
+ // queue has not yet sent.
+ if (config.closed) {
+ const sqid = config.closed[engineName]
+ const { page, seen } = await open(context, sqid)
+ const since = Date.now()
+ await page.evaluate(`(${config.script})(${JSON.stringify(config.typing)})`)
+ const until = Date.now() + CEILING_MS
+ while (!seen.typed && Date.now() < until) await pause(25)
+ const gone = new Promise((resolve) => page.once('close', resolve))
+ await page.close({ runBeforeUnload: true })
+ await Promise.race([gone, pause(CEILING_MS)])
+ const got = await settle(sqid, since, 0, (v) => holds(v.text, config.want))
+ report(engineName + '-closed', seen, got, `the server to hold ${JSON.stringify(config.want)} after the tab closed`)
+ }
+
+ // The same with other edits (config.held: [{ name, docs, typing, want,
+ // link, retried }]): a large paste of prose, which goes keepalive once
+ // gzipped, and one too large for a keepalive save even compressed,
+ // which WebKit refuses until the link is answered. Nothing is lost, and
+ // the page must not say a save failed, because none did.
for (const held of config.held || []) {
- const page = await context.newPage()
- const heldStates = []
- page.on('console', (m) => {
- if (m.text().startsWith('SAVE-STATE ')) heldStates.push(m.text().slice('SAVE-STATE '.length))
- })
- await page.goto(config.origin + '/d/' + held.docs[engineName] + config.page)
- await ready(page)
- await pause(500)
- await page.evaluate(`(${config.script})(${JSON.stringify(held.typing)})`)
- await pause(3000)
- console.log('SAVING RESULT ' + JSON.stringify({ engine: engineName + '-' + held.name, states: heldStates }))
- await page.close()
+ await heldScenario(context, engineName + '-' + held.name, held.docs[engineName], held.typing, { want: held.want, link: !!held.link, orRetried: !!held.retried })
}
// Typed with no link loading (config.typed: [{ name, docs, text }]):
// the server's side is the case, such as a hop that strips a gzipped
- // save's Content-Encoding.
+ // save's Content-Encoding. Each text is saved before the next is typed.
for (const typed of config.typed || []) {
- const page = await context.newPage()
- const typedStates = []
- page.on('console', (m) => {
- if (m.text().startsWith('SAVE-STATE ')) typedStates.push(m.text().slice('SAVE-STATE '.length))
- })
- await page.goto(config.origin + '/d/' + typed.docs[engineName] + config.page)
- await ready(page)
- await pause(500)
+ const sqid = typed.docs[engineName]
+ const { page, seen } = await open(context, sqid)
await page.evaluate(`(() => { const line = document.querySelector('[estilo-save-status]'); new MutationObserver(() => console.log('SAVE-STATE ' + line.getAttribute('data-state'))).observe(line, { attributes: true, attributeFilter: ['data-state'] }) })()`)
+ const got = { settled: true, ms: 0 }
+ let waiting = ''
for (const text of typed.text) {
+ const since = Date.now()
await page.evaluate(`(${config.type})(${JSON.stringify(text)})`)
- await pause(1500)
+ const one = await settle(sqid, since, 1500, (v) => holds(v.text, text))
+ got.ms += one.ms
+ if (!one.settled) {
+ got.settled = false
+ waiting = `the server to hold ${JSON.stringify(text.slice(0, 40))}`
+ break
+ }
}
- console.log('SAVING RESULT ' + JSON.stringify({ engine: engineName + '-' + typed.name, states: typedStates }))
+ report(engineName + '-' + typed.name, seen, got, waiting || 'the server to hold each text')
await page.close()
}
@@ -99,17 +183,16 @@ for (const [engineName, engine] of Object.entries({ chromium, webkit }).filter((
// types more behind it and leaves before that is sent, and the unload
// beacon must carry what was typed. Keepalive requests and beacons
// share one 64KiB quota, so a beacon that repeats the save already on
- // the wire is refused (Claude Fable on #94).
+ // the wire is refused (Claude Fable on Docs #94). Done once the large save
+ // has been answered and the server holds both.
if (config.closing) {
- const closing = await context.newPage()
- await closing.goto(config.origin + '/d/' + config.closing[engineName] + config.page)
- await ready(closing)
- await pause(500)
- await closing.evaluate(`(${config.closingScript})(${JSON.stringify(config.closingTyping)})`)
- await closing.waitForURL(config.origin + '/healthz', { timeout: 30000 })
- // The held save is answered, and the beacon has long arrived.
- await pause(4500)
- console.log('SAVING CLOSED ' + JSON.stringify({ engine: engineName }))
+ const sqid = config.closing[engineName]
+ const { page, seen } = await open(context, sqid)
+ const since = Date.now()
+ await page.evaluate(`(${config.closingScript})(${JSON.stringify(config.closingTyping)})`)
+ await page.waitForURL(config.origin + '/healthz', { timeout: 30000 })
+ const got = await settle(sqid, since, 0, (v) => !v.largeHeld && holds(v.text, 'Bigpaste Queuedbehind'))
+ report(engineName + '-closing', seen, got, 'the large save to be answered and the server to hold "Bigpaste Queuedbehind"')
}
} finally {
await browser.close()
diff --git a/internal/slidestest/saving_browser_test.go b/internal/slidestest/saving_browser_test.go
index 137e67d..d7148d2 100644
--- a/internal/slidestest/saving_browser_test.go
+++ b/internal/slidestest/saving_browser_test.go
@@ -4,6 +4,7 @@ package slidestest
import (
"encoding/json"
+ "fmt"
"io"
"log/slog"
"math/rand/v2"
@@ -56,10 +57,52 @@ const savingScript = `({ text, held }) => {
getSelection().collapseToEnd()
document.execCommand('insertText', false, ' ' + words[i])
if (++i < words.length) setTimeout(type, 300)
+ else {
+ window.__typed = true
+ console.log('SAVE-TYPED')
+ }
}
setTimeout(type, 300)
}`
+// traceScript runs in every page before its own scripts: it records the
+// requests a save can make (POSTs, the probe's HEADs, beacons, the log's
+// GETs; not the static files) with their timing and how each was answered
+// or refused, in window.__saveTrace and as "SAVE-TRACE" console lines. The
+// test prints them when a scenario fails, beside the server's side of the
+// same saves, so a failure says which requests left the page and what
+// became of them (Claude Fable on Docs #94, round 3). It hands each call to the
+// browser's own fetch and sendBeacon unchanged and returns their results.
+const traceScript = `(() => {
+ const trace = window.__saveTrace = []
+ const log = (e) => {
+ e.at = Math.round(performance.timeOrigin + performance.now())
+ trace.push(e)
+ console.log('SAVE-TRACE ' + JSON.stringify(e))
+ }
+ const path = (u) => { try { const x = new URL(u, location.href); return x.pathname + x.search } catch { return String(u) } }
+ const size = (b) => b == null ? 0 : (b.byteLength ?? b.size ?? String(b).length)
+ let n = 0
+ const fetch = window.fetch
+ window.fetch = function (input, init) {
+ const u = path(typeof input === 'string' || input instanceof URL ? input : input.url)
+ const m = ((init && init.method) || (input && input.method) || 'GET').toUpperCase()
+ if (m === 'GET' && u.startsWith('/static/')) return fetch.apply(window, arguments)
+ const h = new Headers((init && init.headers) || undefined)
+ const id = ++n
+ log({ id, ev: 'start', m, u, ka: !!(init && init.keepalive), enc: h.get('Content-Encoding') || '', size: size(init && init.body) })
+ const p = fetch.apply(window, arguments)
+ p.then((r) => log({ id, ev: 'answer', status: r.status }), (err) => log({ id, ev: 'refused', err: String(err) }))
+ return p
+ }
+ const beacon = navigator.sendBeacon
+ navigator.sendBeacon = function (u, data) {
+ const ok = beacon.apply(navigator, arguments)
+ log({ id: ++n, ev: 'beacon', m: 'POST', u: path(u), size: size(data), ok })
+ return ok
+ }
+})()`
+
// typeScript types text at the end of the document's first paragraph.
const typeScript = `(text) => {
const p = document.querySelector('[slides-stage] [data-block="text"] p')
@@ -154,6 +197,15 @@ const savingReady = `document.documentElement.getAttribute('data-slides-fonts')
//
// The scenario is blind unless the link really was loading while the
// saves were made, so that is checked too.
+//
+// The harnesses wait on conditions, not fixed pauses. Each scenario
+// watches the page at least as long as the fixed pause used to, then until
+// the server's view of the document (savingStatePath) holds what the
+// scenario waits for, for at most twenty seconds; a scenario that never
+// gets there fails. Any failure prints the page's requests beside the
+// server's side of them (explain). A fixed three seconds, and a page
+// closed without its unload handlers, made a one-off WebKit failure
+// impossible to read (Claude Fable on Docs #94, round 3).
func TestSavingContinuesWhileALinkIsLoading(t *testing.T) {
if _, err := os.Stat("../../fixtures/engines/node_modules/playwright"); err != nil {
if os.Getenv("RASTRILLO_BROWSER_OPTIONAL") != "" {
@@ -164,11 +216,12 @@ func TestSavingContinuesWhileALinkIsLoading(t *testing.T) {
s := newSavingServer(t)
t.Run("playwright", func(t *testing.T) {
engines := []string{"chromium", "webkit"}
- docs, closing, large, prose, stripped := map[string]string{}, map[string]string{}, map[string]string{}, map[string]string{}, map[string]string{}
+ docs, closed, closing, large, prose, stripped := map[string]string{}, map[string]string{}, map[string]string{}, map[string]string{}, map[string]string{}, map[string]string{}
for _, e := range engines {
stripped[e] = s.document(t, e+" stripped")
s.strip(stripped[e])
docs[e] = s.document(t, e)
+ closed[e] = s.document(t, e+" closed")
large[e] = s.document(t, e+" large")
prose[e] = s.document(t, e+" prose")
closing[e] = s.document(t, e+" closing")
@@ -178,47 +231,58 @@ func TestSavingContinuesWhileALinkIsLoading(t *testing.T) {
cmd.Dir = "../../fixtures/engines"
cmd.Env = append(os.Environ(), "DOCS_SAVING_CONFIG="+s.config(t, map[string]any{
"docs": docs,
+ "closed": closed,
"closing": closing,
"closingScript": closingScript,
"closingTyping": closingTyping(),
"typed": []map[string]any{
{"name": "stripped", "docs": stripped, "text": []string{"Strippedpaste" + strings.Repeat("-gzipped-and-then-stripped", 120), "Smallafter"}},
},
+ // want is what the scenario waits for the server to hold; with
+ // link, saved while the link loads; with retried, a refused
+ // save tried again will do instead.
"held": []map[string]any{
- {"name": "large", "docs": large, "typing": map[string]string{"text": largeText(), "held": heldNavigation}},
- {"name": "prose", "docs": prose, "typing": map[string]string{"text": proseText(), "held": heldNavigation}},
+ {"name": "large", "docs": large, "typing": map[string]string{"text": largeText(), "held": heldNavigation}, "want": largeText()[:64], "retried": true},
+ {"name": "prose", "docs": prose, "typing": map[string]string{"text": proseText(), "held": heldNavigation}, "want": "Prosepaste", "link": true},
},
}))
out, err := cmd.CombinedOutput()
- t.Logf("%s", out)
+ logHarness(t, string(out))
if err != nil {
t.Fatalf("saving.mjs: %v", err)
}
results := savingResults(t, string(out))
for _, e := range engines {
t.Run(e, func(t *testing.T) { s.check(t, docs[e], results[e]) })
- // Closed with a large save on the wire and more typed behind
- // it: the more must arrive by the unload beacon. Keepalive
- // saves and beacons share the browser's 64KiB, so a beacon
- // repeating the save on the wire was refused, and so was its
- // keepalive fallback (Claude Fable on Docs #94).
+ // The same, closed as a person closes a tab, at once after the
+ // last word: the unload handlers run, so the beacon carries
+ // what the queue has not sent yet. Playwright's page.close()
+ // skips them, which the held-link case above keeps as the
+ // harsher close (Claude Fable on Docs #94, round 3).
+ t.Run(e+"/closed", func(t *testing.T) {
+ r := s.result(t, closed[e], results[e+"-closed"])
+ s.contains(t, closed[e], savingText)
+ s.calm(t, r)
+ })
// An edit too large for a keepalive save, even compressed, is
// refused by WebKit until the link is answered: the page waits
// quietly and retries, because no request has failed. "Trouble
// saving" said otherwise (Claude Fable on Docs #94).
- t.Run(e+"/large", func(t *testing.T) { s.calm(t, results[e+"-large"]) })
+ t.Run(e+"/large", func(t *testing.T) { s.calm(t, s.result(t, large[e], results[e+"-large"])) })
// A gzipped save meets a server that does not gunzip it: here a
// hop strips Content-Encoding, and updatesPost reads the
// compressed bytes as the update and refuses them (422), as main
// does, and as a rollback would. The save is sent again as it
// is, and nothing is dropped (Claude Fable on Docs #94, round 2).
t.Run(e+"/stripped", func(t *testing.T) {
+ r := s.result(t, stripped[e], results[e+"-stripped"])
s.contains(t, stripped[e], "Strippedpaste Smallafter")
- s.calm(t, results[e+"-stripped"])
+ s.calm(t, r)
})
// A paste of 64KB of prose, twice what a keepalive save may
// carry, goes gzipped and fits: saved while the link loads.
t.Run(e+"/prose", func(t *testing.T) {
+ r := s.result(t, prose[e], results[e+"-prose"])
s.mu.Lock()
held := s.held[prose[e]]
s.mu.Unlock()
@@ -226,12 +290,19 @@ func TestSavingContinuesWhileALinkIsLoading(t *testing.T) {
t.Error("the paste did not reach the server while the link was loading")
}
s.contains(t, prose[e], "Prosepaste")
- s.calm(t, results[e+"-prose"])
+ s.calm(t, r)
})
+ // Closed with a large save on the wire and more typed behind
+ // it: the more must arrive by the unload beacon. Keepalive
+ // saves and beacons share the browser's 64KiB, so a beacon
+ // repeating the save on the wire was refused, and so was its
+ // keepalive fallback (Claude Fable on Docs #94).
t.Run(e+"/closing", func(t *testing.T) {
- if !strings.Contains(string(out), `SAVING CLOSED {"engine":"`+e+`"}`) {
+ if results[e+"-closing"] == nil {
+ s.explain(t, closing[e], nil)
t.Fatal("the harness never closed the page")
}
+ s.result(t, closing[e], results[e+"-closing"])
// The beacon, while the large save is still held: the
// queued text arrives by itself. Without it the old page,
// which outlives the hold, sends the text once the large
@@ -261,7 +332,7 @@ func TestSavingContinuesWhileALinkIsLoading(t *testing.T) {
}
t.Run("held-link", func(t *testing.T) {
doc := s.document(t, "wkwebview")
- out := runSavingHarness(t, bin, s.config(t, map[string]any{"doc": doc, "scenario": "held-link"}))
+ out := runSavingHarness(t, bin, s.config(t, map[string]any{"doc": doc, "scenario": "held-link", "want": savingText}))
s.check(t, doc, savingResults(t, out)["wkwebview"])
})
// The page leaves with a save on the wire, the server answers it
@@ -273,12 +344,13 @@ func TestSavingContinuesWhileALinkIsLoading(t *testing.T) {
t.Run("back", func(t *testing.T) {
doc := s.document(t, "wkwebview back")
s.slow(doc)
- out := runSavingHarness(t, bin, s.config(t, map[string]any{"doc": doc, "scenario": "back"}))
+ out := runSavingHarness(t, bin, s.config(t, map[string]any{"doc": doc, "scenario": "back", "want": "Before leaving After coming back"}))
+ r := s.result(t, doc, savingResults(t, out)["wkwebview-back"])
if !strings.Contains(out, `"persisted":true`) {
t.Fatal("the page was not shown again from the back/forward cache, so this check saw nothing")
}
s.contains(t, doc, "After coming back")
- s.calm(t, savingResults(t, out)["wkwebview-back"])
+ s.calm(t, r)
})
// Back at once, with a large paste still on the wire: the resend
// may be refused while that save and the unload beacon hold
@@ -288,12 +360,13 @@ func TestSavingContinuesWhileALinkIsLoading(t *testing.T) {
doc := s.document(t, "wkwebview back quick")
s.holdLarge(doc)
big := closingTyping()["big"]
- out := runSavingHarness(t, bin, s.config(t, map[string]any{"doc": doc, "scenario": "back", "before": big, "awayMs": 300}))
+ out := runSavingHarness(t, bin, s.config(t, map[string]any{"doc": doc, "scenario": "back", "before": big, "awayMs": 300, "want": "Bigpaste After coming back"}))
+ r := s.result(t, doc, savingResults(t, out)["wkwebview-back"])
if !strings.Contains(out, `"persisted":true`) {
t.Fatal("the page was not shown again from the back/forward cache, so this check saw nothing")
}
s.contains(t, doc, "Bigpaste After coming back")
- s.calm(t, savingResults(t, out)["wkwebview-back"])
+ s.calm(t, r)
})
})
}
@@ -303,7 +376,7 @@ func runSavingHarness(t *testing.T, bin, config string) string {
cmd := exec.Command(bin)
cmd.Env = append(os.Environ(), "DOCS_SAVING_CONFIG="+config)
out, err := cmd.CombinedOutput()
- t.Logf("%s", out)
+ logHarness(t, string(out))
if err != nil {
t.Fatalf("saving-webkit: %v", err)
}
@@ -312,6 +385,10 @@ func runSavingHarness(t *testing.T, bin, config string) string {
const savingText = "Typed while loading"
+// savingStatePath, followed by a document's sqid, is the server's view of
+// it as JSON (savingView): what the harnesses wait on.
+const savingStatePath = "/test/saving-state/"
+
type savingServer struct {
rig *fontRig
served http.Handler
@@ -335,6 +412,31 @@ type savingServer struct {
// duringLarge counts the saves answered 2xx meanwhile.
holdingLarge map[string]bool
duringLarge map[string]int
+ // posts are, per document, the saves that reached the server, in the
+ // order they did.
+ posts map[string][]*savingPost
+}
+
+// savingPost is one save as the server saw it.
+type savingPost struct {
+ At int64 `json:"at"` // arrived, Unix ms
+ Bytes int64 `json:"bytes"`
+ Encoding string `json:"encoding,omitempty"` // as sent, before any stripping
+ Type string `json:"type,omitempty"`
+ Status int `json:"status"` // 0 until answered
+ Took int64 `json:"took"` // ms from arrival to answer
+ Link bool `json:"link,omitempty"` // answered while the held link was loading
+ Large bool `json:"large,omitempty"` // the large save the server held
+}
+
+// savingView is what the server holds for a document, and how its saves
+// went.
+type savingView struct {
+ Text string `json:"text"`
+ Held int `json:"held"`
+ DuringLarge int `json:"duringLarge"`
+ LargeHeld bool `json:"largeHeld"` // a large save awaited, or held now
+ Posts []savingPost `json:"posts"`
}
// strip makes sqid's saves lose their Content-Encoding on the way in, as
@@ -363,7 +465,7 @@ func (s *savingServer) slow(sqid string) {
func newSavingServer(t *testing.T) *savingServer {
t.Helper()
server := httptest.NewUnstartedServer(nil)
- s := &savingServer{origin: "http://" + server.Listener.Addr().String(), held: map[string]int{}, slowed: map[string]bool{}, heldLarge: map[string]bool{}, holdingLarge: map[string]bool{}, duringLarge: map[string]int{}, stripped: map[string]bool{}}
+ s := &savingServer{origin: "http://" + server.Listener.Addr().String(), held: map[string]int{}, slowed: map[string]bool{}, heldLarge: map[string]bool{}, holdingLarge: map[string]bool{}, duringLarge: map[string]int{}, stripped: map[string]bool{}, posts: map[string][]*savingPost{}}
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
d, err := db.Open(filepath.Join(t.TempDir(), "app.db"), logger)
if err != nil {
@@ -390,9 +492,16 @@ func newSavingServer(t *testing.T) *savingServer {
<-r.Context().Done()
return
}
+ if sqid, ok := strings.CutPrefix(r.URL.Path, savingStatePath); ok && r.Method == http.MethodGet {
+ w.Header().Set("Content-Type", "application/json")
+ _ = json.NewEncoder(w).Encode(s.view(sqid))
+ return
+ }
if r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/updates") {
s.mu.Lock()
sqid := strings.Split(r.URL.Path, "/")[2]
+ post := &savingPost{At: time.Now().UnixMilli(), Bytes: r.ContentLength, Encoding: r.Header.Get("Content-Encoding"), Type: r.Header.Get("Content-Type")}
+ s.posts[sqid] = append(s.posts[sqid], post)
slow, large := s.slowed[sqid], s.heldLarge[sqid] && r.ContentLength > 16*1024
if s.stripped[sqid] {
r.Header.Del("Content-Encoding")
@@ -421,6 +530,7 @@ func newSavingServer(t *testing.T) *savingServer {
if rec.code/100 == 2 && !large && s.holdingLarge[sqid] {
s.duringLarge[sqid]++
}
+ post.Status, post.Took, post.Link, post.Large = rec.code, time.Now().UnixMilli()-post.At, during, large
s.mu.Unlock()
return
}
@@ -446,7 +556,10 @@ func (s *savingServer) config(t *testing.T, extra map[string]any) string {
"cookies": s.cookies,
"script": savingScript,
"typing": map[string]string{"text": savingText, "held": heldNavigation},
+ "want": savingText,
"type": typeScript,
+ "trace": traceScript,
+ "state": savingStatePath,
"page": "/edit",
"ready": savingReady,
}
@@ -460,14 +573,56 @@ func (s *savingServer) config(t *testing.T, extra map[string]any) string {
return string(b)
}
+// text is the server's first slide, as HTML.
+func (s *savingServer) text(sqid string) (string, error) {
+ req := httptest.NewRequest(http.MethodGet, "/d/"+sqid+"/slides/slideone0001.html", nil)
+ for _, c := range s.cookies {
+ req.AddCookie(c)
+ }
+ rec := httptest.NewRecorder()
+ s.served.ServeHTTP(rec, req)
+ if rec.Code != http.StatusOK {
+ return "", fmt.Errorf("the slide: %d %s", rec.Code, rec.Body.String())
+ }
+ return rec.Body.String(), nil
+}
+
+// view is the server's side of sqid: its text, and every save that
+// reached it.
+func (s *savingServer) view(sqid string) savingView {
+ text, err := s.text(sqid)
+ if err != nil {
+ text = err.Error()
+ }
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ v := savingView{Text: text, Held: s.held[sqid], DuringLarge: s.duringLarge[sqid], LargeHeld: s.heldLarge[sqid] || s.holdingLarge[sqid], Posts: []savingPost{}}
+ for _, p := range s.posts[sqid] {
+ v.Posts = append(v.Posts, *p)
+ }
+ return v
+}
+
+// result is a scenario's harness report, which must exist and must have
+// got what it waited for; should the scenario fail, its story is printed.
+func (s *savingServer) result(t *testing.T, sqid string, r *savingResult) *savingResult {
+ t.Helper()
+ s.explain(t, sqid, r)
+ if r == nil {
+ t.Fatal("the harness reported nothing for this scenario")
+ }
+ if !r.Settled {
+ t.Errorf("the harness gave up after %d ms waiting for %s", r.Ms, r.Waiting)
+ }
+ return r
+}
+
// check is the held-link scenario's verdict: saves reached the server
// while the link was loading, the words are in the server's document, and
// the page never said a save had failed.
-func (s *savingServer) check(t *testing.T, sqid string, states []string) {
+func (s *savingServer) check(t *testing.T, sqid string, r *savingResult) {
t.Helper()
- if states == nil {
- t.Fatal("the harness reported nothing for this engine")
- }
+ s.result(t, sqid, r)
s.mu.Lock()
held := s.held[sqid]
s.mu.Unlock()
@@ -475,68 +630,232 @@ func (s *savingServer) check(t *testing.T, sqid string, states []string) {
t.Error("no save reached the server while the link was loading: the editor stopped saving")
}
s.contains(t, sqid, savingText)
- s.calm(t, states)
+ s.calm(t, r)
}
// contains reads the first slide back from the server and checks every
// word of text is in it.
func (s *savingServer) contains(t *testing.T, sqid, text string) {
t.Helper()
- req := httptest.NewRequest(http.MethodGet, "/d/"+sqid+"/slides/slideone0001.html", nil)
- for _, c := range s.cookies {
- req.AddCookie(c)
- }
- rec := httptest.NewRecorder()
- s.served.ServeHTTP(rec, req)
- if rec.Code != http.StatusOK {
- t.Fatalf("the slide: %d %s", rec.Code, rec.Body.String())
+ body, err := s.text(sqid)
+ if err != nil {
+ t.Fatal(err)
}
for _, word := range strings.Fields(text) {
- if !strings.Contains(rec.Body.String(), word) {
- t.Errorf("the server's document is missing %q:\n%s", word, rec.Body.String())
+ if !strings.Contains(body, word) {
+ t.Errorf("the server's document is missing %q:\n%s", word, body)
}
}
}
// calm fails if the page ever said a save failed: in these scenarios no
// request does.
-func (s *savingServer) calm(t *testing.T, states []string) {
+func (s *savingServer) calm(t *testing.T, r *savingResult) {
t.Helper()
- if states == nil {
+ if r == nil {
t.Fatal("the harness reported no save states")
}
- for _, st := range states {
+ for _, st := range r.States {
if st == "retrying" || st == "failed" {
- t.Errorf("the page said %q while no request had failed (states %v)", st, states)
+ t.Errorf("the page said %q while no request had failed (states %v)", st, r.States)
break
}
}
}
-// savingResults reads each "SAVING RESULT {engine, states}" line.
-func savingResults(t *testing.T, out string) map[string][]string {
+// explain prints, should t fail, what the page sent and what the server
+// made of it, on one clock: the page's requests (traceScript) and every
+// save that reached the server, how each was answered, and the text the
+// server holds. So a failure says whether the saves never left the page,
+// left and were refused, or are still waiting for an answer.
+func (s *savingServer) explain(t *testing.T, sqid string, r *savingResult) {
+ t.Cleanup(func() {
+ if !t.Failed() {
+ return
+ }
+ v := s.view(sqid)
+ var base int64
+ for _, at := range []int64{firstAt(r), firstPost(v)} {
+ if at != 0 && (base == 0 || at < base) {
+ base = at
+ }
+ }
+ var b strings.Builder
+ if r != nil {
+ fmt.Fprintf(&b, "The harness waited %d ms for %s (got it: %v); the save line showed %v.\n", r.Ms, r.Waiting, r.Settled, r.States)
+ }
+ b.WriteString("What the page sent (ms from the first request either side saw):\n")
+ if r == nil || len(r.Trace) == 0 {
+ b.WriteString(" nothing recorded\n")
+ } else {
+ // A page refused four times a second makes hundreds: the start
+ // and the end say what happened.
+ for i, e := range r.Trace {
+ if n := len(r.Trace); n > 60 && i >= 40 && i < n-20 {
+ if i == 40 {
+ fmt.Fprintf(&b, " … %d more\n", n-60)
+ }
+ continue
+ }
+ fmt.Fprintf(&b, " %s\n", e.line(base))
+ }
+ }
+ b.WriteString("What reached the server:\n")
+ if len(v.Posts) == 0 {
+ b.WriteString(" no save\n")
+ }
+ for _, p := range v.Posts {
+ fmt.Fprintf(&b, " %s\n", p.line(base))
+ }
+ fmt.Fprintf(&b, "Saves answered 2xx while the link loaded: %d; while the large save was held: %d.\n", v.Held, v.DuringLarge)
+ text := v.Text
+ if len(text) > 800 {
+ text = text[:800] + fmt.Sprintf("… (%d bytes in all)", len(v.Text))
+ }
+ fmt.Fprintf(&b, "What the server holds:\n%s", text)
+ t.Logf("%s", b.String())
+ })
+}
+
+func firstAt(r *savingResult) int64 {
+ if r == nil || len(r.Trace) == 0 {
+ return 0
+ }
+ return r.Trace[0].At
+}
+
+func firstPost(v savingView) int64 {
+ if len(v.Posts) == 0 {
+ return 0
+ }
+ return v.Posts[0].At
+}
+
+func (p savingPost) line(base int64) string {
+ enc := p.Encoding
+ if enc == "" {
+ enc = "identity"
+ }
+ what := fmt.Sprintf("+%d ms POST %d B %s %s", p.At-base, p.Bytes, enc, p.Type)
+ if p.Large {
+ what += ", the large save, held 3 s"
+ }
+ if p.Status == 0 {
+ return what + ": not answered yet"
+ }
+ what += fmt.Sprintf(": answered %d after %d ms", p.Status, p.Took)
+ if p.Link {
+ what += ", with the link loading"
+ }
+ return what
+}
+
+// savingTrace is one entry of traceScript's record.
+type savingTrace struct {
+ ID int `json:"id"`
+ At int64 `json:"at"`
+ Event string `json:"ev"`
+ Method string `json:"m"`
+ URL string `json:"u"`
+ Keep bool `json:"ka"`
+ Encoding string `json:"enc"`
+ Size int `json:"size"`
+ Status int `json:"status"`
+ Err string `json:"err"`
+ OK bool `json:"ok"`
+}
+
+func (e savingTrace) line(base int64) string {
+ at := fmt.Sprintf("+%d ms #%d", e.At-base, e.ID)
+ switch e.Event {
+ case "start":
+ how := "fetch"
+ if e.Keep {
+ how = "keepalive fetch"
+ }
+ if e.Encoding != "" {
+ how += " " + e.Encoding
+ }
+ return fmt.Sprintf("%s %s %s %s, %d B", at, how, e.Method, e.URL, e.Size)
+ case "answer":
+ return fmt.Sprintf("%s answered %d", at, e.Status)
+ case "refused":
+ return fmt.Sprintf("%s refused: %s", at, e.Err)
+ case "beacon":
+ ok := "queued"
+ if !e.OK {
+ ok = "refused"
+ }
+ return fmt.Sprintf("%s beacon %s %s, %d B: %s", at, e.Method, e.URL, e.Size, ok)
+ }
+ return fmt.Sprintf("%s %s", at, e.Event)
+}
+
+// savingResult is one "SAVING RESULT" line: the save states the page
+// showed, and whether what the scenario waited for came, and when; with
+// the page's requests from its "SAVING TRACE" line.
+type savingResult struct {
+ Engine string `json:"engine"`
+ States []string `json:"states"`
+ Settled bool `json:"settled"`
+ Ms int `json:"ms"`
+ Waiting string `json:"waiting"`
+ Trace []savingTrace
+}
+
+// savingResults reads each "SAVING RESULT {engine, states, ...}" line, and
+// the "SAVING TRACE {engine, trace}" line beside it.
+func savingResults(t *testing.T, out string) map[string]*savingResult {
t.Helper()
- results := map[string][]string{}
+ results := map[string]*savingResult{}
+ traces := map[string][]savingTrace{}
for _, line := range strings.Split(out, "\n") {
- rest, ok := strings.CutPrefix(strings.TrimSpace(line), "SAVING RESULT ")
- if !ok {
+ line = strings.TrimSpace(line)
+ if rest, ok := strings.CutPrefix(line, "SAVING TRACE "); ok {
+ var tr struct {
+ Engine string `json:"engine"`
+ Trace []savingTrace `json:"trace"`
+ }
+ if err := json.Unmarshal([]byte(rest), &tr); err != nil {
+ t.Fatalf("%q: %v", line, err)
+ }
+ traces[tr.Engine] = tr.Trace
continue
}
- var r struct {
- Engine string `json:"engine"`
- States []string `json:"states"`
+ rest, ok := strings.CutPrefix(line, "SAVING RESULT ")
+ if !ok {
+ continue
}
+ var r savingResult
if err := json.Unmarshal([]byte(rest), &r); err != nil {
t.Fatalf("%q: %v", line, err)
}
if r.States == nil {
r.States = []string{}
}
- results[r.Engine] = r.States
+ results[r.Engine] = &r
+ }
+ for engine, tr := range traces {
+ if r := results[engine]; r != nil {
+ r.Trace = tr
+ }
}
return results
}
+// logHarness logs a harness's output, less the request traces: those are
+// printed only for a scenario that fails (explain).
+func logHarness(t *testing.T, out string) {
+ t.Helper()
+ var keep []string
+ for _, line := range strings.Split(out, "\n") {
+ if !strings.HasPrefix(strings.TrimSpace(line), "SAVING TRACE ") {
+ keep = append(keep, line)
+ }
+ }
+ t.Logf("%s", strings.Join(keep, "\n"))
+}
+
type statusRecorder struct {
http.ResponseWriter
code int