skillhub/web/e2e/helpers/test-data-builder.ts
dongmucat 50a6c4b7fe test(e2e,ci): migrate web e2e to real API and add PR e2e workflow (#198)
* chore(workflow): align local hooks and e2e guidance

* test(e2e): expand reusable api mock helpers

* test(skill): stabilize share button e2e assertions

* chore(test): add e2e make target and tune playwright workers

* test(web): expand e2e coverage and smoke suite

* test(e2e): migrate to real API flows and add request-based data builder

* ci(e2e): add PR workflow for real-service frontend e2e

* ci(e2e): install playwright chromium in PR workflow

* test(e2e): relax timeout and force single worker in CI

* test(e2e): stabilize not-found assertions and harden CI session bootstrap

* chore(agents): align tester role with web/e2e workflow
2026-04-01 14:41:23 +08:00

284 lines
7.9 KiB
TypeScript

import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { execFileSync } from 'node:child_process'
import path from 'node:path'
import type { APIRequestContext, Page, TestInfo } from '@playwright/test'
type CleanupTask = () => Promise<void>
export interface SeededNamespace {
id: number
slug: string
displayName: string
}
export interface SeededSkill {
skillId: number
namespace: string
slug: string
version: string
status: string
}
export interface SeededReviewData {
namespace: SeededNamespace
skill: SeededSkill
}
interface ApiEnvelope<T> {
code: number
msg: string
data: T
}
interface ApiFailure extends Error {
status?: number
code?: number
}
function asApiErrorBody(value: unknown): string {
if (!value || typeof value !== 'object') {
return ''
}
const maybe = value as { msg?: unknown }
return typeof maybe.msg === 'string' ? maybe.msg : ''
}
function uniqueSuffix(testInfo?: TestInfo): string {
const worker = testInfo?.parallelIndex ?? 0
return `${worker}_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`
}
function buildSkillPackageZipBuffer(suffix: string): Buffer {
const tempRoot = mkdtempSync(path.join(tmpdir(), 'skillhub-e2e-'))
try {
const packageDir = path.join(tempRoot, `pkg-${suffix}`)
const zipPath = path.join(tempRoot, `pkg-${suffix}.zip`)
const skillName = `e2e-skill-${suffix}`.slice(0, 48)
const skillMd = `---
name: ${skillName}
description: E2E generated skill for real-request tests
version: 1.0.0
---
# ${skillName}
Generated by Playwright E2E.
`
execFileSync('mkdir', ['-p', packageDir])
writeFileSync(path.join(packageDir, 'SKILL.md'), skillMd, 'utf8')
writeFileSync(path.join(packageDir, 'README.md'), `# ${skillName}\n`, 'utf8')
execFileSync('zip', ['-q', '-r', zipPath, 'SKILL.md', 'README.md'], { cwd: packageDir })
return readFileSync(zipPath)
} finally {
rmSync(tempRoot, { recursive: true, force: true })
}
}
function createSkillPackageZipFile(suffix: string): { filePath: string; cleanup: () => void } {
const tempRoot = mkdtempSync(path.join(tmpdir(), 'skillhub-e2e-file-'))
const packageDir = path.join(tempRoot, `pkg-${suffix}`)
const zipPath = path.join(tempRoot, `pkg-${suffix}.zip`)
const skillName = `e2e-skill-${suffix}`.slice(0, 48)
const skillMd = `---
name: ${skillName}
description: E2E generated skill for real-request tests
version: 1.0.0
---
# ${skillName}
Generated by Playwright E2E.
`
execFileSync('mkdir', ['-p', packageDir])
writeFileSync(path.join(packageDir, 'SKILL.md'), skillMd, 'utf8')
writeFileSync(path.join(packageDir, 'README.md'), `# ${skillName}\n`, 'utf8')
execFileSync('zip', ['-q', '-r', zipPath, 'SKILL.md', 'README.md'], { cwd: packageDir })
return {
filePath: zipPath,
cleanup: () => {
rmSync(tempRoot, { recursive: true, force: true })
},
}
}
async function parseEnvelope<T>(response: Awaited<ReturnType<APIRequestContext['fetch']>>): Promise<T> {
const text = await response.text()
let parsed: ApiEnvelope<T> | null = null
try {
parsed = JSON.parse(text) as ApiEnvelope<T>
} catch {
throw new Error(`Non-JSON response: status=${response.status()} body=${text.slice(0, 200)}`)
}
if (!response.ok() || parsed.code !== 0) {
const error = new Error(
`API failed: status=${response.status()} code=${parsed.code} msg=${asApiErrorBody(parsed) || parsed.msg}`,
) as ApiFailure
error.status = response.status()
error.code = parsed.code
throw error
}
return parsed.data
}
export class E2eTestDataBuilder {
private readonly request: APIRequestContext
private readonly suffix: string
private readonly cleanupTasks: CleanupTask[] = []
private ensuredNamespace?: SeededNamespace
constructor(
private readonly page: Page,
testInfo?: TestInfo,
) {
this.request = page.context().request
this.suffix = uniqueSuffix(testInfo)
}
async init(): Promise<void> {
// Prime CSRF/session cookie path used by write endpoints.
await this.request.get('/api/v1/auth/providers')
}
async cleanup(): Promise<void> {
for (let i = this.cleanupTasks.length - 1; i >= 0; i -= 1) {
try {
await this.cleanupTasks[i]()
} catch {
// Best-effort cleanup for E2E environments.
}
}
}
async createNamespace(base = 'e2e-team'): Promise<SeededNamespace> {
const slug = `${base}-${this.suffix}`.slice(0, 64)
const displayName = `E2E ${slug}`
const created = await parseEnvelope<SeededNamespace>(
await this.request.post('/api/v1/namespaces', {
data: {
slug,
displayName,
description: `E2E namespace ${slug}`,
},
}),
)
this.cleanupTasks.push(async () => {
await this.request.post(`/api/web/namespaces/${encodeURIComponent(created.slug)}/archive`, {
data: { reason: 'e2e cleanup' },
})
})
return created
}
async listMyNamespaces(): Promise<SeededNamespace[]> {
return parseEnvelope<SeededNamespace[]>(
await this.request.get('/api/web/me/namespaces'),
)
}
async ensureWritableNamespace(): Promise<SeededNamespace> {
if (this.ensuredNamespace) {
return this.ensuredNamespace
}
try {
const created = await this.createNamespace('e2e-team')
this.ensuredNamespace = created
return created
} catch (error) {
const failure = error as ApiFailure
if (failure.status !== 403) {
throw error
}
}
const namespaces = await this.listMyNamespaces()
const writable = namespaces.find((item) => item.slug !== 'global') ?? namespaces[0]
if (!writable) {
throw new Error('No namespace available for e2e data seeding')
}
this.ensuredNamespace = writable
return writable
}
private async getMySkillInNamespace(namespaceSlug: string): Promise<SeededSkill | null> {
const page = await parseEnvelope<{
items: Array<{
id: number
namespace: string
slug: string
headlineVersion?: { version: string; status: string }
}>
}>(
await this.request.get('/api/web/me/skills?page=0&size=50'),
)
const hit = page.items.find((item) => item.namespace === namespaceSlug)
if (!hit || !hit.headlineVersion) {
return null
}
return {
skillId: hit.id,
namespace: hit.namespace,
slug: hit.slug,
version: hit.headlineVersion.version,
status: hit.headlineVersion.status,
}
}
async publishSkill(namespaceSlug: string): Promise<SeededSkill> {
const unique = `${this.suffix}_${Math.random().toString(36).slice(2, 6)}`
const zipBuffer = buildSkillPackageZipBuffer(unique)
let result: SeededSkill
try {
result = await parseEnvelope<SeededSkill>(
await this.request.post(`/api/web/skills/${encodeURIComponent(namespaceSlug)}/publish`, {
multipart: {
file: {
name: 'sample-skill.zip',
mimeType: 'application/zip',
buffer: zipBuffer,
},
visibility: 'PUBLIC',
},
}),
)
} catch (error) {
const fallback = await this.getMySkillInNamespace(namespaceSlug)
if (!fallback) {
throw error
}
return fallback
}
this.cleanupTasks.push(async () => {
await this.request.delete(`/api/web/skills/${encodeURIComponent(result.namespace)}/${encodeURIComponent(result.slug)}`)
})
return result
}
createSkillPackageFile(): string {
const unique = `${this.suffix}_${Math.random().toString(36).slice(2, 6)}`
const { filePath, cleanup } = createSkillPackageZipFile(unique)
this.cleanupTasks.push(async () => {
cleanup()
})
return filePath
}
async createReviewData(): Promise<SeededReviewData> {
const namespace = await this.ensureWritableNamespace()
const skill = await this.publishSkill(namespace.slug)
return { namespace, skill }
}
}