Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 10 additions & 5 deletions .context/TECHSTACK.md
Original file line number Diff line number Diff line change
Expand Up @@ -745,11 +745,16 @@ data-doop-webfonts>` for the roster families the frame names and does not load i

- Vitest 5 - unit/integration tests across `server/` and `src/`; run via `bun run test`
(`vitest run`). Tests live in `tests/`.
- Browser tests drive one shared Chromium and one Vite fixture server (`tests/browser.ts`), which
`tests/globalSetup.ts` starts and warms (every `tests/fixtures/*.html` loaded once) before any
worker runs; a file calls `openBrowser()` for its own context (focus emulated, 30s navigation
bound) and `fixtureUrl()` for its page. A test that needs its own Vite server (a proxy) builds it
from `fixtureServerConfig()`, so every server shares one dependency hash and cache directory.
- Browser tests drive one shared Chromium and one fixture server (`tests/browser.ts`), which
`tests/globalSetup.ts` starts before any worker runs. The server hands out a production build:
`tests/fixtures.vite.config.ts` is the app's own build with every `tests/fixtures/*.html` as an
entry beside `index.html`, built once per run (about a second, as its own `vite build` process
with `NODE_ENV=production`) into a temp directory and served by `vite preview`; there is no dev
server and no live-reload client. A file calls `pagePerTest()` for a page per test in its own
context (focus emulated, 30s navigation bound) and `fixtureUrl()` for its page. A fixture
exposes what a test needs on `window`; a test cannot import `/src/...` from the page. A test that
puts the app in front of a real backend starts its own server over the same build with
`serveBuilt(proxy)`.
- CI runs the browser tests on the Chrome for Testing build named in `.chrome-version`, installed
by the `test` job and passed as `CHROME_PATH`, so a runner image update cannot change the
browser without a commit. `bun run test:linux [vitest args]` (`scripts/test-linux.sh`,
Expand Down
151 changes: 94 additions & 57 deletions tests/browser.ts
Original file line number Diff line number Diff line change
@@ -1,29 +1,36 @@
import { readdirSync } from 'node:fs'
import { execFile } from 'node:child_process'
import { cpSync, mkdtempSync, rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
import path from 'node:path'
import { promisify } from 'node:util'
import puppeteer, { type Browser, type Page, type Permission } from 'puppeteer-core'
import { createServer, type InlineConfig, type ServerOptions } from 'vite'
import { preview, type ProxyOptions } from 'vite'
import { afterAll, afterEach, beforeAll, expect, inject } from 'vitest'
import { findBrowserPath, launchBrowser } from '../server/screenshot.ts'

/**
* Shared rig for the tests that drive a real Chromium: ONE browser and ONE
* Vite server for the fixtures, started and warmed by tests/globalSetup.ts
* before any worker runs.
* server for the fixtures, started by tests/globalSetup.ts before any worker
* runs.
*
* Every file used to launch its own Chromium and its own Vite server. On the
* 2-vCPU CI runner that meant a cold Chrome start (30s+ on a fresh VM, past
* puppeteer's launch timeout) and a cold transform of the whole app (past the
* 5-10s navigation timeouts) inside the first files' hooks, and files whose
* servers asked for different `optimizeDeps` rewrote the shared dependency
* cache under each other. Now the cold costs are paid once, outside any test
* timeout, and each file gets a fresh browser context (its own cookies and
* storage, and its own window, so its pages stay visible and focused) on the
* warm browser.
* The server hands out a production build of the fixtures (and of the app's
* own index.html), made once per run by tests/fixtures.vite.config.ts. A page
* is a few bundled files, so a load costs much the same on a 2-vCPU CI runner
* as it does here, and it is the code that ships. A dev server would serve
* the app as hundreds of unbundled modules, a second or two per load on CI,
* and its live-reload client gives a stalled load up for a lost server and
* never recovers the page.
*
* Chrome's cold start (30s+ on a fresh VM, past puppeteer's launch timeout)
* and the build are paid once, outside any test timeout, and each file gets a
* fresh browser context (its own cookies and storage, and its own window, so
* its pages stay visible and focused) on the warm browser.
*/

declare module 'vitest' {
interface ProvidedContext {
/** null when no Chromium is installed; every browser test skips then */
browserRig: { wsEndpoint: string; fixtureOrigin: string } | null
browserRig: { wsEndpoint: string; fixtureOrigin: string; builtDir: string } | null
}
}

Expand All @@ -33,10 +40,10 @@ const FIXTURES = 'tests/fixtures'
* caches from a cold disk; that has taken well over puppeteer's 30s. */
const COLD_START_MS = 180_000

/** A fixture load fetches and runs the app as hundreds of unbundled modules:
* well under a second here, several on a busy 2-vCPU runner. Files set a
* tight default timeout for their UI waits (5s), which puppeteer would also
* apply to navigation; loads get their own, roomier bound. */
/** A fixture load is a handful of bundled files, well under a second. Files
* set a tight default timeout for their UI waits (5s), which puppeteer would
* also apply to navigation; loads get their own, roomier bound for a runner
* that stalls. */
const NAVIGATION_TIMEOUT_MS = 30_000

/** The bound on one UI wait (waitForSelector, waitForFunction, a locator
Expand All @@ -47,71 +54,101 @@ const NAVIGATION_TIMEOUT_MS = 30_000
const STEP_TIMEOUT_MS = 15_000

/**
* The Vite config every fixture server uses. One `optimizeDeps` for all of
* them: the dependency hash covers `include`, and a server whose hash differs
* re-bundles the cache directory out from under the others. The fixtures are
* scan entries so their dependencies are bundled up front instead of being
* discovered mid-test, which reloads every open page. The cache directory is
* separate from `bun run dev`'s, so a dev server in the same checkout never
* fights a test run over it, and nothing is watched: a file written while the
* suite runs must not reload the pages under test.
* Build every fixture and the app into a fresh directory outside the tree.
* Vite runs as its own process because a production build is decided by
* NODE_ENV, which vitest has already set to `test` in this one. What the
* fixtures fetch by path at run time (a stylesheet, an image) is not part of
* the bundle, so those files are copied next to the built pages.
*/
export function fixtureServerConfig(server: ServerOptions = {}): InlineConfig {
return {
async function buildFixtures(): Promise<string> {
const dir = mkdtempSync(path.join(tmpdir(), 'doop-test-fixtures-'))
try {
await promisify(execFile)(
process.execPath,
['node_modules/vite/bin/vite.js', 'build', '--config', 'tests/fixtures.vite.config.ts', '--outDir', dir],
{ env: { ...process.env, NODE_ENV: 'production' } },
)
cpSync(FIXTURES, path.join(dir, FIXTURES), {
recursive: true,
filter: (source) => !/\.(html|ts)$/.test(source),
})
return dir
} catch (error) {
rmSync(dir, { recursive: true, force: true })
throw error
}
}

export interface BuiltServer {
/** without a trailing slash */
origin: string
close(): Promise<void>
}

/**
* Serve the built pages. The shared fixture server answers only the files
* that exist. A test that puts the app in front of a real backend starts its
* own with `proxy`, and that one also answers every app route with
* index.html, as the production server does.
*/
export async function serveBuilt(
proxy?: Record<string, ProxyOptions>,
builtDir = rig().builtDir,
): Promise<BuiltServer> {
const server = await preview({
configFile: false,
logLevel: 'error',
cacheDir: 'node_modules/.vite-test',
optimizeDeps: {
entries: ['index.html', `${FIXTURES}/*.html`],
include: ['posthog-js/dist/posthog-recorder', 'posthog-js/dist/rrweb'],
},
server: { port: 0, watch: null, ...server },
appType: proxy ? 'spa' : 'mpa',
build: { outDir: builtDir },
preview: { port: 0, proxy },
})
return {
origin: server.resolvedUrls!.local[0]!.replace(/\/$/, ''),
close: () => server.close(),
}
}

export interface BrowserRig {
wsEndpoint: string
fixtureOrigin: string
builtDir: string
close(): Promise<void>
}

/** Launch the browser and the fixture server, then load every fixture once so
* dependency bundling and the app's transforms are done before tests start. */
/** Launch the browser and build and serve the fixtures, then load one page so
* the browser's first render is behind it before tests start. */
export async function startBrowserRig(): Promise<BrowserRig | null> {
if (!findBrowserPath()) return null
const [launched, created] = await Promise.allSettled([
launchBrowser(COLD_START_MS),
createServer(fixtureServerConfig()),
])
const [launched, built] = await Promise.allSettled([launchBrowser(COLD_START_MS), buildFixtures()])
const browser = launched.status === 'fulfilled' ? launched.value : null
const vite = created.status === 'fulfilled' ? created.value : null
const builtDir = built.status === 'fulfilled' ? built.value : null
let server: BuiltServer | null = null
const close = async () => {
await browser?.close()
await vite?.close()
await server?.close()
if (builtDir) rmSync(builtDir, { recursive: true, force: true })
}
try {
if (!browser || !vite)
throw launched.status === 'rejected' ? launched.reason : (created as PromiseRejectedResult).reason
await vite.listen()
const fixtureOrigin = vite.resolvedUrls!.local[0]!
await warmFixtures(browser, fixtureOrigin)
return { wsEndpoint: browser.wsEndpoint(), fixtureOrigin, close }
if (!browser || !builtDir)
throw launched.status === 'rejected' ? launched.reason : (built as PromiseRejectedResult).reason
server = await serveBuilt(undefined, builtDir)
const fixtureOrigin = `${server.origin}/`
await warmBrowser(browser, fixtureOrigin)
return { wsEndpoint: browser.wsEndpoint(), fixtureOrigin, builtDir, close }
} catch (error) {
/* a half-started rig must not leave a Chromium or a server holding the run open */
await close()
throw error
}
}

async function warmFixtures(browser: Browser, origin: string): Promise<void> {
/** A fresh Chrome's first page starts a renderer and fills its font and code
* caches; one load here keeps that out of the first test's timeout. */
async function warmBrowser(browser: Browser, origin: string): Promise<void> {
const context = await browser.createBrowserContext()
try {
/* one at a time: the first pays for the dependency bundle, the rest only
for the modules that are theirs */
for (const file of readdirSync(FIXTURES).filter((name) => name.endsWith('.html'))) {
const page = await context.newPage()
await page.goto(`${origin}${FIXTURES}/${file}`, { waitUntil: 'load', timeout: COLD_START_MS })
await page.close()
}
const page = await context.newPage()
await page.goto(`${origin}${FIXTURES}/drawing.html`, { waitUntil: 'load', timeout: COLD_START_MS })
} finally {
await context.close()
}
Expand All @@ -126,7 +163,7 @@ export interface TestBrowser {
close(): Promise<void>
}

function rig(): { wsEndpoint: string; fixtureOrigin: string } {
function rig(): { wsEndpoint: string; fixtureOrigin: string; builtDir: string } {
const provided = inject('browserRig')
if (!provided) throw new Error('no browser rig: tests/globalSetup.ts found no Chromium')
return provided
Expand Down
4 changes: 0 additions & 4 deletions tests/elementCommentPositionBrowser.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,10 +48,6 @@ describe.skipIf(!findBrowserPath())('element comment pin placement', () => {
page = await pages.open()
page.on('pageerror', (error) => errors.push(String(error)))
await page.goto(fixtureUrl('elementPanel.html'))
await page.addScriptTag({
type: 'module',
content: "import { useStore } from '/src/lib/store.ts'; window.commentPositionStore = useStore",
})
await page.waitForFunction(() => !!window.commentPositionStore)
await page.evaluate(
({ frame, comment }) => {
Expand Down
22 changes: 8 additions & 14 deletions tests/fitSelectionBrowser.test.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'
import { createServer, type ViteDevServer } from 'vite'
import type { Page } from 'puppeteer-core'
import { findBrowserPath } from '../server/screenshot'
import { fixtureServerConfig, pagePerTest } from './browser'
import { pagePerTest, serveBuilt, type BuiltServer } from './browser'
import { freePort, startServer, type Server } from './harness'

/* ⇧2 fits the selection into the part of the stage the panels leave open,
not the whole window under them */
describe.skipIf(!findBrowserPath())('zoom to selection with the panels open', () => {
let vite: ViteDevServer
let web: BuiltServer
let server: Server
const pages = pagePerTest()
let page: Page
Expand All @@ -20,16 +19,11 @@ describe.skipIf(!findBrowserPath())('zoom to selection with the panels open', ()
let frameId: string
beforeAll(async () => {
const port = await freePort()
vite = await createServer(
fixtureServerConfig({
proxy: {
'/api': { target: `http://localhost:${port}` },
'/ws': { target: `ws://localhost:${port}`, ws: true },
},
}),
)
await vite.listen()
origin = vite.resolvedUrls!.local[0]!.replace(/\/$/, '')
web = await serveBuilt({
'/api': { target: `http://localhost:${port}` },
'/ws': { target: `ws://localhost:${port}`, ws: true },
})
origin = web.origin
server = await startServer({ PORT: String(port), BETTER_AUTH_URL: origin })
}, 60_000)
beforeEach(async () => {
Expand Down Expand Up @@ -67,7 +61,7 @@ describe.skipIf(!findBrowserPath())('zoom to selection with the panels open', ()
await page.waitForSelector('[data-frame-title]')
})
afterAll(async () => {
await vite?.close()
await web?.close()
server?.stop()
})

Expand Down
28 changes: 28 additions & 0 deletions tests/fixtures.vite.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { readdirSync } from 'node:fs'
import { mergeConfig, type UserConfig } from 'vite'
import app from '../vite.config.ts'

/* The production build the browser tests load (tests/browser.ts runs it once
per test run): the app's own build with every fixture page as an entry
beside index.html, minified as it ships. No .env file is read, so the pages
are the same on every machine, and no source maps are written: nothing
reads them, and the build stays about a second. */
const pages: UserConfig = {
logLevel: 'error',
envDir: false,
build: {
emptyOutDir: true,
sourcemap: false,
reportCompressedSize: false,
rollupOptions: {
input: [
'index.html',
...readdirSync('tests/fixtures')
.filter((name) => name.endsWith('.html'))
.map((name) => `tests/fixtures/${name}`),
],
},
},
}

export default mergeConfig(app as UserConfig, pages)
2 changes: 2 additions & 0 deletions tests/fixtures/elementPanel.html
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@
import { editElementGeometry } from '/src/lib/frameBridge.ts'
import { nudgeSelection } from '/src/lib/layerEdits.ts'
import '/src/styles.css'
/* the app's own store, for a test that seeds state the harness has no call for */
window.commentPositionStore = useStore
window.elementPanelHarness = {
/* one frame, or several stacked in order (later ones on top) */
seed: (frame) => {
Expand Down
3 changes: 1 addition & 2 deletions tests/frameRasterBrowser.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -144,8 +144,7 @@ describe.skipIf(!findBrowserPath())('rasterizing a frame in the browser', () =>
})

it('rejects a frame with an image the browser cannot fetch, for the server to render', async () => {
/* a host nothing answers on; the fixture server itself answers any
path with the app page */
/* a host nothing answers on */
const failed = await page.evaluate(() =>
(window as unknown as { render: (o: unknown) => Promise<Rendered> })
.render({ html: '<html><body><img src="http://127.0.0.1:9/no-cors.png"></body></html>' })
Expand Down
10 changes: 7 additions & 3 deletions tests/frameReplay.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,10 @@ describe.skipIf(!findBrowserPath())('sandboxed frame replay', () => {
})
}, 60_000)

/** The recorder the frame downloads: its own file in the build, named
* recorder-<hash>.js (the page's posthog-recorder chunk is another file). */
const isRecorder = (request: HTTPRequest) => /\/recorder-[\w-]+\.js$/.test(new URL(request.url()).pathname)

async function render(html: string, index = 0) {
await page.evaluate(
(html, index) => {
Expand Down Expand Up @@ -59,7 +63,7 @@ describe.skipIf(!findBrowserPath())('sandboxed frame replay', () => {
})
let attempts = 0
const onRequest = (request: HTTPRequest) => {
if (new URL(request.url()).pathname.endsWith('/dist/recorder.js')) {
if (isRecorder(request)) {
attempts++
if (attempts === 1) void request.abort('failed')
else release(request)
Expand Down Expand Up @@ -92,7 +96,7 @@ describe.skipIf(!findBrowserPath())('sandboxed frame replay', () => {
const saved = await page.evaluate(() => window.messages.find((m) => m.type === 'doop:edited')!.html)
expect(saved).toContain('<div data-doop-replay="">Preserve design content</div>')
expect(saved).toContain('<script data-doop-replay="">window.designScriptRan = true</script>')
expect(saved).not.toContain('/dist/recorder.js')
expect(saved).not.toContain(new URL(request.url()).pathname)
await page.evaluate(() => {
window.messages = window.messages.filter((m) => m.type !== 'doop:edited')
})
Expand Down Expand Up @@ -179,7 +183,7 @@ describe.skipIf(!findBrowserPath())('sandboxed frame replay', () => {
await page.setRequestInterception(true)
let attempts = 0
const onRequest = (request: HTTPRequest) => {
if (new URL(request.url()).pathname.endsWith('/dist/recorder.js')) {
if (isRecorder(request)) {
attempts++
void request.abort('failed')
} else void request.continue()
Expand Down
Loading
Loading