mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-12-01 13:34:33 +00:00
test(webui): add playwright e2e framework with video player play/pause test
Add a Playwright UI integration test framework for the frame-accurate video player. Tests run against a backend-free harness served by Bun's native HTML bundler (matching the project's Bun-based dev/prod serving), so no database, auth or transcode pipeline is required. - Add @playwright/test with chromium/firefox/webkit projects; the browser is selectable via the Playwright --project flag (webkit = Safari engine). - Serve the harness with Bun.serve + bun-plugin-tailwind (no separate Vite toolchain); commit a deterministic 16x16/5s/30fps fixture video and matching AssetInfo. - Add a play/pause spec covering both the play control and clicking the video area, asserting the native video clock, seekbar fill and frame readout stay frame-locked after pause (settle-aware, tolerance-based assertions). - Mock all backend API calls (anchored /api/ and /files/ routes) for isolation. - Exclude e2e specs from Vitest; add a separate CI job (webkit on macOS).
This commit is contained in:
@@ -262,6 +262,7 @@ const ProgressBar: React.FC<ProgressBarProps> = ({
|
||||
onMouseLeave={handleMouseLeave}
|
||||
onMouseDown={handleMouseDown}
|
||||
onTouchStart={handleTouchStart}
|
||||
data-testid="seekbar"
|
||||
>
|
||||
{/* Hidden Preview Video Element */}
|
||||
<video
|
||||
@@ -316,6 +317,7 @@ const ProgressBar: React.FC<ProgressBarProps> = ({
|
||||
<div
|
||||
className="relative absolute top-0 left-0 h-full rounded-full bg-primary"
|
||||
style={{ width: `${progressPercent}%` }}
|
||||
data-testid="seekbar-fill"
|
||||
>
|
||||
{/* Thumb (Playhead) - visible on group hover or active */}
|
||||
<div
|
||||
|
||||
@@ -165,7 +165,13 @@ const ControlBar: React.FC<ControlBarProps> = ({
|
||||
>
|
||||
{/* Left Side: Play, Vol, Time */}
|
||||
<div className="flex items-center gap-4">
|
||||
<button onClick={togglePlay} className="hover:text-primary transition-colors">
|
||||
<button
|
||||
onClick={togglePlay}
|
||||
className="hover:text-primary transition-colors"
|
||||
data-testid="play-toggle"
|
||||
data-playing={state.isPlaying}
|
||||
aria-label={state.isPlaying ? 'Pause' : 'Play'}
|
||||
>
|
||||
{state.isPlaying ? (
|
||||
<Pause className="w-6 h-6 fill-current" />
|
||||
) : (
|
||||
@@ -206,7 +212,9 @@ const ControlBar: React.FC<ControlBarProps> = ({
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-1 text-sm font-medium tabular-nums select-none min-w-[100px]">
|
||||
<span className="text-muted-foreground font-mono">{displayString}</span>
|
||||
<span className="text-muted-foreground font-mono" data-testid="time-readout">
|
||||
{displayString}
|
||||
</span>
|
||||
<DropdownMenu modal={false}>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<button className="h-6 w-6 inline-flex items-center justify-center rounded-md hover:bg-muted text-muted-foreground hover:text-foreground transition-colors cursor-pointer focus:outline-none">
|
||||
@@ -911,6 +919,7 @@ const VideoPlayer: React.FC<VideoPlayerProps> = ({
|
||||
)}
|
||||
onClick={togglePlay}
|
||||
data-vjs-player
|
||||
data-testid="video-area"
|
||||
>
|
||||
{/* Hidden VideoJS container */}
|
||||
<div ref={videoContainerRef} className="absolute inset-0 z-[-1]" />
|
||||
|
||||
Binary file not shown.
@@ -0,0 +1,50 @@
|
||||
import type { AssetInfo } from '@shumai/dtos'
|
||||
|
||||
/**
|
||||
* Deterministic metadata for the committed fixture video
|
||||
* (packages/webui/e2e/fixtures/sample.mp4).
|
||||
*
|
||||
* Generated with:
|
||||
* ffmpeg -f lavfi -i testsrc=size=16x16:rate=30 -t 5 -pix_fmt yuv420p sample.mp4
|
||||
*
|
||||
* Verified via ffprobe: 16x16, 30/1 fps, duration 5.0s, 150 frames.
|
||||
* These constants are shared by the harness and the Playwright specs so the
|
||||
* frame-accurate assertions have known-good expected values.
|
||||
*/
|
||||
export const SAMPLE_FRAME_RATE = 30
|
||||
export const SAMPLE_TOTAL_FRAMES = 150
|
||||
export const SAMPLE_DURATION = 5
|
||||
export const SAMPLE_WIDTH = 16
|
||||
export const SAMPLE_HEIGHT = 16
|
||||
|
||||
/**
|
||||
* The fixture video is served statically by the harness Vite server
|
||||
* (publicDir points at packages/webui/e2e/fixtures), so it is reachable at
|
||||
* the site root. No backend is involved.
|
||||
*/
|
||||
export const SAMPLE_VIDEO_URL = '/sample.mp4'
|
||||
|
||||
export const sampleVideoAsset: AssetInfo = {
|
||||
id: 'e2e-sample-asset',
|
||||
name: 'sample.mp4',
|
||||
sizeByte: 6170,
|
||||
fileCount: 1,
|
||||
type: 'file',
|
||||
status: 'ready',
|
||||
mediaType: 'video',
|
||||
createdAt: '2024-01-01T00:00:00.000Z',
|
||||
updatedAt: '2024-01-01T00:00:00.000Z',
|
||||
media: {
|
||||
original: {
|
||||
downloadUrl: SAMPLE_VIDEO_URL,
|
||||
key: 'sample.mp4',
|
||||
},
|
||||
metadata: {
|
||||
duration: SAMPLE_DURATION,
|
||||
originalWidth: SAMPLE_WIDTH,
|
||||
originalHeight: SAMPLE_HEIGHT,
|
||||
frameRate: SAMPLE_FRAME_RATE,
|
||||
totalFrames: SAMPLE_TOTAL_FRAMES,
|
||||
},
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<link rel="stylesheet" href="../../globals.css" />
|
||||
<title>Video Player E2E Harness</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="./main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,37 @@
|
||||
import ReactDOM from 'react-dom/client'
|
||||
import VideoPlayer from '@/ui/components/viewers/video-player'
|
||||
import { useUiStore } from '@/ui/stores/ui'
|
||||
import { sampleVideoAsset } from './fixture'
|
||||
|
||||
/**
|
||||
* Backend-free harness page that mounts the *real* VideoPlayer component with a
|
||||
* fixture AssetInfo pointing at a locally served sample video. No API/router/
|
||||
* query providers are required for playback, so this isolates the frame-accurate
|
||||
* player logic (useFramePlayer + ProgressBar + video.js) for UI integration tests.
|
||||
*
|
||||
* We force the time readout into "frames" mode so specs can parse the exact
|
||||
* integer frame index the UI is displaying and assert it against the native
|
||||
* <video> clock and the seekbar fill.
|
||||
*/
|
||||
useUiStore.setState({ videoTimeDisplayMode: 'frames' })
|
||||
|
||||
const rootElement = document.getElementById('root')
|
||||
if (!rootElement) {
|
||||
throw new Error('Harness root element not found')
|
||||
}
|
||||
|
||||
// Replicate the exact constrained container the real app (file-viewer) mounts
|
||||
// the player inside: a `flex flex-col flex-1 h-full overflow-hidden` wrapper that
|
||||
// itself sits in a bounded flex parent. This gives the player root a definite
|
||||
// 800x600 box and prevents the video area's canvas from feeding its width back
|
||||
// through the ResizeObserver (which otherwise grows unbounded in a bare stage).
|
||||
ReactDOM.createRoot(rootElement).render(
|
||||
<div
|
||||
data-testid="harness-stage"
|
||||
style={{ width: '800px', height: '600px', display: 'flex', overflow: 'hidden' }}
|
||||
>
|
||||
<div className="flex flex-col flex-1 h-full overflow-hidden relative">
|
||||
<VideoPlayer data={sampleVideoAsset} />
|
||||
</div>
|
||||
</div>,
|
||||
)
|
||||
@@ -0,0 +1,34 @@
|
||||
import { dirname, join } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import index from './index.html'
|
||||
|
||||
/**
|
||||
* Backend-free harness server for the Playwright e2e suite.
|
||||
*
|
||||
* Uses Bun's native HTML bundler (the same path the real app uses via
|
||||
* `Bun.serve({ routes })` in apps/web) so the test toolchain matches the
|
||||
* project's Bun-based dev/prod serving. Tailwind is applied through the
|
||||
* `bun-plugin-tailwind` entry configured in the repo's bunfig.toml
|
||||
* ([serve.static]). It serves:
|
||||
* - the harness page (index.html -> main.tsx, bundled on the fly), and
|
||||
* - the committed fixture video from ../fixtures at the site root.
|
||||
*/
|
||||
const here = dirname(fileURLToPath(import.meta.url))
|
||||
const fixturesDir = join(here, '..', 'fixtures')
|
||||
|
||||
const port = process.env.HARNESS_PORT ? Number(process.env.HARNESS_PORT) : 5199
|
||||
|
||||
const server = Bun.serve({
|
||||
port,
|
||||
development: true,
|
||||
routes: {
|
||||
'/sample.mp4': () =>
|
||||
new Response(Bun.file(join(fixturesDir, 'sample.mp4')), {
|
||||
headers: { 'Content-Type': 'video/mp4' },
|
||||
}),
|
||||
'/': index,
|
||||
'/*': index,
|
||||
},
|
||||
})
|
||||
|
||||
console.log(`🎬 Video player harness running at ${server.url}`)
|
||||
@@ -0,0 +1,139 @@
|
||||
import type { Locator, Page } from '@playwright/test'
|
||||
import { SAMPLE_FRAME_RATE, SAMPLE_TOTAL_FRAMES } from '../harness/fixture'
|
||||
|
||||
const VIDEO_SELECTOR = '[data-testid="video-area"] video'
|
||||
|
||||
/**
|
||||
* Snapshot of the player's synchronized state, read from the three independent
|
||||
* surfaces that must stay frame-locked:
|
||||
* - the native <video> element (video.js engine / media clock),
|
||||
* - the seekbar fill (derived from useFramePlayer's currentFrame),
|
||||
* - the numeric frame readout (also derived from currentFrame).
|
||||
*/
|
||||
export interface PlayerSnapshot {
|
||||
paused: boolean
|
||||
ended: boolean
|
||||
currentTime: number
|
||||
/** Frame index implied by the native media clock: floor(t * fps + 0.45). */
|
||||
nativeFrame: number
|
||||
/** Frame index shown in the "N / M fr" readout. */
|
||||
readoutFrame: number
|
||||
/** Seekbar fill width as a fraction (0..1) of the track width. */
|
||||
seekbarFraction: number
|
||||
}
|
||||
|
||||
export class VideoPlayerPage {
|
||||
readonly page: Page
|
||||
readonly stage: Locator
|
||||
readonly videoArea: Locator
|
||||
readonly playToggle: Locator
|
||||
readonly video: Locator
|
||||
readonly seekbar: Locator
|
||||
readonly seekbarFill: Locator
|
||||
readonly timeReadout: Locator
|
||||
|
||||
constructor(page: Page) {
|
||||
this.page = page
|
||||
this.stage = page.getByTestId('harness-stage')
|
||||
this.videoArea = page.getByTestId('video-area')
|
||||
this.playToggle = page.getByTestId('play-toggle')
|
||||
this.video = page.locator(VIDEO_SELECTOR).first()
|
||||
this.seekbar = page.getByTestId('seekbar')
|
||||
this.seekbarFill = page.getByTestId('seekbar-fill')
|
||||
this.timeReadout = page.getByTestId('time-readout')
|
||||
}
|
||||
|
||||
async goto(): Promise<void> {
|
||||
await this.page.goto('/')
|
||||
await this.waitUntilReady()
|
||||
}
|
||||
|
||||
/** Wait until the video.js engine has metadata and a usable frame readout. */
|
||||
async waitUntilReady(): Promise<void> {
|
||||
await this.video.waitFor({ state: 'attached' })
|
||||
await this.page.waitForFunction(
|
||||
(selector) => {
|
||||
const el = document.querySelector(selector) as HTMLVideoElement | null
|
||||
return !!el && el.readyState >= 1 /* HAVE_METADATA */ && Number.isFinite(el.duration)
|
||||
},
|
||||
VIDEO_SELECTOR,
|
||||
{ timeout: 15_000 },
|
||||
)
|
||||
// The readout renders "N / M fr" once currentFrame state is wired up.
|
||||
await this.page.waitForFunction(
|
||||
(selector) => /\d+\s*\/\s*\d+\s*fr/.test(document.querySelector(selector)?.textContent ?? ''),
|
||||
'[data-testid="time-readout"]',
|
||||
{ timeout: 15_000 },
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Some engines (notably WebKit headless) refuse to start playback for a clip
|
||||
* that could produce sound without an explicit muted flag. The fixture has no
|
||||
* audio track, but we mute defensively so play() resolves consistently.
|
||||
*/
|
||||
async muteNativeVideo(): Promise<void> {
|
||||
await this.video.evaluate((el: HTMLVideoElement) => {
|
||||
el.muted = true
|
||||
})
|
||||
}
|
||||
|
||||
async isPaused(): Promise<boolean> {
|
||||
return this.video.evaluate((el: HTMLVideoElement) => el.paused)
|
||||
}
|
||||
|
||||
async currentTime(): Promise<number> {
|
||||
return this.video.evaluate((el: HTMLVideoElement) => el.currentTime)
|
||||
}
|
||||
|
||||
private async readoutFrame(): Promise<number> {
|
||||
const text = (await this.timeReadout.textContent()) ?? ''
|
||||
const match = text.match(/(\d+)\s*\/\s*\d+\s*fr/)
|
||||
return match ? Number.parseInt(match[1], 10) : Number.NaN
|
||||
}
|
||||
|
||||
private async seekbarFraction(): Promise<number> {
|
||||
const track = await this.seekbar.boundingBox()
|
||||
const fill = await this.seekbarFill.boundingBox()
|
||||
if (!track || !fill || track.width === 0) return 0
|
||||
return fill.width / track.width
|
||||
}
|
||||
|
||||
/** Read a coherent snapshot of all three synchronized surfaces. */
|
||||
async snapshot(): Promise<PlayerSnapshot> {
|
||||
const [native, readoutFrame, seekbarFraction] = await Promise.all([
|
||||
this.video.evaluate((el: HTMLVideoElement, fps: number) => {
|
||||
return {
|
||||
paused: el.paused,
|
||||
ended: el.ended,
|
||||
currentTime: el.currentTime,
|
||||
nativeFrame: Math.floor(el.currentTime * fps + 0.45),
|
||||
}
|
||||
}, SAMPLE_FRAME_RATE),
|
||||
this.readoutFrame(),
|
||||
this.seekbarFraction(),
|
||||
])
|
||||
|
||||
return {
|
||||
paused: native.paused,
|
||||
ended: native.ended,
|
||||
currentTime: native.currentTime,
|
||||
nativeFrame: native.nativeFrame,
|
||||
readoutFrame,
|
||||
seekbarFraction,
|
||||
}
|
||||
}
|
||||
|
||||
clickPlayToggle(): Promise<void> {
|
||||
return this.playToggle.click()
|
||||
}
|
||||
|
||||
clickVideoArea(): Promise<void> {
|
||||
// The drawing-canvas overlay is pointer-events:none when not drawing, so the
|
||||
// click lands on the video-area div and triggers togglePlay.
|
||||
return this.videoArea.click({ position: { x: 20, y: 20 } })
|
||||
}
|
||||
}
|
||||
|
||||
export const FRAME_RATE = SAMPLE_FRAME_RATE
|
||||
export const TOTAL_FRAMES = SAMPLE_TOTAL_FRAMES
|
||||
@@ -0,0 +1,141 @@
|
||||
import { expect, test } from '@playwright/test'
|
||||
import { FRAME_RATE, TOTAL_FRAMES, VideoPlayerPage } from '../pages/video-player.page'
|
||||
|
||||
/**
|
||||
* Pure UI integration test for the frame-accurate video player.
|
||||
*
|
||||
* The player keeps three surfaces in lockstep off a single `currentFrame` state:
|
||||
* 1. the native <video> element (video.js media clock),
|
||||
* 2. the seekbar fill, and
|
||||
* 3. the numeric frame readout.
|
||||
*
|
||||
* On pause, useFramePlayer snaps the native clock to the paused frame's center
|
||||
* time, so after a short settle the native frame, the readout frame and the
|
||||
* seekbar fill must all agree. We assert that invariant here rather than trusting
|
||||
* any single surface.
|
||||
*/
|
||||
|
||||
const SEEKBAR_TOLERANCE = 0.01 // fraction of the track (~1%), covers sub-pixel + thumb rounding
|
||||
const HALF_FRAME_SECONDS = 1 / (2 * FRAME_RATE)
|
||||
|
||||
test.beforeEach(async ({ page }) => {
|
||||
// Mock every backend call so this stays a pure frontend test. The player never
|
||||
// hits the API during play/pause, but this guarantees isolation regardless.
|
||||
//
|
||||
// NOTE: the patterns are anchored to the origin root (/api/, /files/) so they
|
||||
// only match real backend requests and NOT Vite-served source modules whose
|
||||
// paths happen to contain those segments (e.g. /packages/webui/api/client.ts).
|
||||
await page.route(/^https?:\/\/[^/]+\/(api|files)\//, (route) =>
|
||||
route.fulfill({ status: 200, contentType: 'application/json', body: '{}' }),
|
||||
)
|
||||
})
|
||||
|
||||
/**
|
||||
* Wait until the player has settled to a stable, paused, fully-synchronized
|
||||
* frame, then assert the native clock, the readout and the seekbar all agree.
|
||||
*/
|
||||
async function expectPausedAndSynchronized(vp: VideoPlayerPage): Promise<void> {
|
||||
await expect.poll(() => vp.isPaused(), { timeout: 5_000 }).toBe(true)
|
||||
|
||||
// Wait for the pause snap + external-seek nudge to fully settle: currentTime
|
||||
// stops changing between consecutive reads.
|
||||
await expect
|
||||
.poll(
|
||||
async () => {
|
||||
const a = await vp.currentTime()
|
||||
await vp.page.waitForTimeout(80)
|
||||
const b = await vp.currentTime()
|
||||
return Math.abs(b - a) < 1e-3
|
||||
},
|
||||
{ timeout: 5_000 },
|
||||
)
|
||||
.toBe(true)
|
||||
|
||||
// The UI frame and the native-clock frame converge on the same integer.
|
||||
await expect
|
||||
.poll(
|
||||
async () => {
|
||||
const snap = await vp.snapshot()
|
||||
return snap.readoutFrame === snap.nativeFrame
|
||||
},
|
||||
{ timeout: 5_000 },
|
||||
)
|
||||
.toBe(true)
|
||||
|
||||
const snap = await vp.snapshot()
|
||||
|
||||
expect(snap.paused).toBe(true)
|
||||
|
||||
// Readout <-> native media clock.
|
||||
expect(snap.readoutFrame).toBe(snap.nativeFrame)
|
||||
|
||||
// Seekbar fill <-> frame index.
|
||||
expect(Math.abs(snap.seekbarFraction - snap.nativeFrame / TOTAL_FRAMES)).toBeLessThan(
|
||||
SEEKBAR_TOLERANCE,
|
||||
)
|
||||
|
||||
// Native clock is snapped to the paused frame's center time.
|
||||
const frameCenter = snap.nativeFrame / FRAME_RATE + HALF_FRAME_SECONDS
|
||||
expect(Math.abs(snap.currentTime - frameCenter)).toBeLessThan(HALF_FRAME_SECONDS + 1e-6)
|
||||
}
|
||||
|
||||
/** Assert the player is genuinely stopped: the frame does not advance over time. */
|
||||
async function expectPlayheadStopped(vp: VideoPlayerPage): Promise<void> {
|
||||
const first = await vp.snapshot()
|
||||
await vp.page.waitForTimeout(300)
|
||||
const second = await vp.snapshot()
|
||||
// The integer frame is the robust "not advancing" signal.
|
||||
expect(second.readoutFrame).toBe(first.readoutFrame)
|
||||
// currentTime must not advance meaningfully. A playing video would move ~0.3s
|
||||
// in 300ms; a stopped one moves less than a frame (browser seeks land *near*,
|
||||
// not exactly on, the requested frame-center, and the pause snap may still be
|
||||
// settling), so half a frame cleanly separates stopped from playing.
|
||||
expect(Math.abs(second.currentTime - first.currentTime)).toBeLessThan(HALF_FRAME_SECONDS)
|
||||
}
|
||||
|
||||
test.describe('video player play/pause', () => {
|
||||
test('toggles via the play/pause control', async ({ page }) => {
|
||||
const vp = new VideoPlayerPage(page)
|
||||
await vp.goto()
|
||||
await vp.muteNativeVideo()
|
||||
|
||||
// Starts paused at frame 0.
|
||||
const initial = await vp.snapshot()
|
||||
expect(initial.paused).toBe(true)
|
||||
expect(initial.readoutFrame).toBe(0)
|
||||
|
||||
// Play via the control -> playback starts and the readout advances.
|
||||
await vp.clickPlayToggle()
|
||||
await expect.poll(() => vp.isPaused(), { timeout: 5_000 }).toBe(false)
|
||||
await expect
|
||||
.poll(async () => (await vp.snapshot()).readoutFrame, { timeout: 5_000 })
|
||||
.toBeGreaterThan(initial.readoutFrame)
|
||||
|
||||
// Pause via the control -> everything re-synchronizes and stays put.
|
||||
await vp.clickPlayToggle()
|
||||
await expectPausedAndSynchronized(vp)
|
||||
await expectPlayheadStopped(vp)
|
||||
})
|
||||
|
||||
test('toggles via clicking the video area', async ({ page }) => {
|
||||
const vp = new VideoPlayerPage(page)
|
||||
await vp.goto()
|
||||
await vp.muteNativeVideo()
|
||||
|
||||
const initial = await vp.snapshot()
|
||||
expect(initial.paused).toBe(true)
|
||||
expect(initial.readoutFrame).toBe(0)
|
||||
|
||||
// Click the video surface to play.
|
||||
await vp.clickVideoArea()
|
||||
await expect.poll(() => vp.isPaused(), { timeout: 5_000 }).toBe(false)
|
||||
await expect
|
||||
.poll(async () => (await vp.snapshot()).readoutFrame, { timeout: 5_000 })
|
||||
.toBeGreaterThan(initial.readoutFrame)
|
||||
|
||||
// Click again to pause -> native clock, readout and seekbar agree.
|
||||
await vp.clickVideoArea()
|
||||
await expectPausedAndSynchronized(vp)
|
||||
await expectPlayheadStopped(vp)
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user