Files
vibemake-admin/tests/project-upload.spec.ts
T

136 lines
7.2 KiB
TypeScript

import { expect, test, type Page, type Route } from '@playwright/test';
import { MAX_PROJECT_UPLOAD_TOTAL, validateProjectUpload } from '../src/components/project/projectUpload';
import type { ManagedProjectView, SelectedFile } from '../src/api/types';
const project: ManagedProjectView = {
project: {
projectCode: 'upload-test', name: '上传测试项目', description: '', coverUrl: null,
urdfMainUrl: null, urdfBaseUrl: null, projectType: 'WHEELED',
owner: { userCode: null, nickname: '社区官方' }, repoStatus: 'READY', publishStatus: 'UNPUBLISHED',
publishedCommitSha: null, publishedAt: null, sourceProjectCode: null, sourceCommitSha: null,
likeCount: 0, commentCount: 0, liked: false, sourceRepositoryUrl: null, sourceLicense: null,
createdAt: '2026-10-27T00:00:00', updatedAt: '2026-10-27T00:00:00',
},
moderationStatus: 'NORMAL', moderationReason: null, deleted: false,
};
async function ok(route: Route, data: unknown) {
await route.fulfill({ json: { code: 'OK', message: '成功', data, requestId: null } });
}
async function prepare(page: Page, onCommit: (route: Route) => Promise<void>) {
await page.addInitScript(() => localStorage.setItem('vibemake_admin_token', 'test-token'));
await page.route('https://fonts.googleapis.com/**', (route) => route.abort());
await page.route('**/admin-api/**', async (route) => {
const path = new URL(route.request().url()).pathname.replace('/admin-api', '');
if (path === '/auth/me') return ok(route, { userCode: 'admin', nickname: '测试管理员', role: 'ADMIN' });
if (path === '/projects/types') return ok(route, [{ code: 'WHEELED', name: '轮式机器人' }]);
if (path === '/projects/upload-test') return ok(route, project);
if (path.endsWith('/tree')) return ok(route, { commitSha: 'main-sha', path: '', entries: [] });
if (path.endsWith('/commits')) return ok(route, { items: [], page: 1, size: 20, total: 0 });
if (path.endsWith('/uploads/commit')) return onCommit(route);
return ok(route, { items: [], page: 1, size: 20, total: 0 });
});
await page.goto('/projects/upload-test');
await page.getByRole('button', { name: '上传' }).click();
}
async function chooseDirectory(page: Page) {
const parent = await import('node:fs/promises').then(({ mkdtemp }) => mkdtemp('/tmp/project-upload-'));
const fs = await import('node:fs/promises');
const path = await import('node:path');
const directory = path.join(parent, 'robot');
try {
await fs.mkdir(path.join(directory, 'left'), { recursive: true });
await fs.mkdir(path.join(directory, 'right'), { recursive: true });
await fs.writeFile(path.join(directory, 'left', 'model.stl'), '1234');
await fs.writeFile(path.join(directory, 'right', 'notes.txt'), 'abcd');
const chooser = page.waitForEvent('filechooser');
await page.getByRole('menuitem', { name: '上传文件夹' }).click();
await (await chooser).setFiles(directory);
} finally {
await fs.rm(parent, { recursive: true, force: true });
}
}
test('项目文件夹上传可勾选路径并展示实际上传进度', async ({ page }) => {
let requestBody = '';
let finishCommit!: () => void;
const commitGate = new Promise<void>((resolve) => { finishCommit = resolve; });
await prepare(page, async (route) => {
requestBody = route.request().postDataBuffer()?.toString('utf8') ?? '';
await commitGate;
await ok(route, { commitSha: 'new-sha', message: '上传文件' });
});
await chooseDirectory(page);
const keepRoot = page.getByRole('checkbox', { name: '保留所选文件夹名称' });
await expect(keepRoot).not.toBeChecked();
await expect(page.getByText('left/model.stl', { exact: true })).toBeVisible();
await expect(page.getByText('right/notes.txt', { exact: true })).toBeVisible();
const notes = page.getByRole('checkbox', { name: '选择 right/notes.txt' });
await notes.uncheck();
await expect(page.getByText(/目标目录:.*1 个文件 · 4 B/)).toBeVisible();
await keepRoot.check();
await expect(page.getByRole('checkbox', { name: '选择 robot/left/model.stl' })).toBeChecked();
await expect(page.getByRole('checkbox', { name: '选择 robot/right/notes.txt' })).not.toBeChecked();
await page.getByRole('checkbox', { name: '选择 robot/left/model.stl' }).uncheck();
await expect(page.getByText('至少选择一个文件', { exact: true })).toBeVisible();
await expect(page.getByRole('button', { name: '提交上传' })).toBeDisabled();
await page.getByRole('checkbox', { name: '选择 robot/left/model.stl' }).check();
await page.getByPlaceholder('提交说明(必填)').fill('只上传模型');
await page.getByRole('button', { name: '提交上传' }).click();
const failsafe = setTimeout(finishCommit, 8000);
await expect(page.getByText('正在上传文件')).toBeVisible();
await expect(page.getByRole('progressbar')).toBeVisible();
await expect(page.getByPlaceholder('提交说明(必填)')).toBeDisabled();
finishCommit();
await expect(page.getByText('上传成功,新版本 new-sha')).toBeVisible();
expect(requestBody).toContain('robot/left/model.stl');
expect(requestBody).not.toContain('robot/right/notes.txt');
expect(requestBody).toContain('只上传模型');
clearTimeout(failsafe);
});
test('上传失败保留弹窗和选择状态,可重试', async ({ page }) => {
let attempts = 0;
await prepare(page, async (route) => {
attempts += 1;
if (attempts === 1) {
await route.fulfill({ status: 500, json: { code: 'UPLOAD_FAILED', message: '模拟上传失败', data: null } });
} else {
await ok(route, { commitSha: 'retry-sha', message: '重试上传' });
}
});
await chooseDirectory(page);
const first = page.getByRole('checkbox', { name: '选择 left/model.stl' });
await first.uncheck();
await page.getByRole('button', { name: '提交上传' }).click();
await expect(page.getByText('上传失败,可修改选择后重试')).toBeVisible();
await expect(first).not.toBeChecked();
await expect(page.getByRole('button', { name: '提交上传' })).toBeEnabled();
await first.check();
await page.getByRole('button', { name: '提交上传' }).click();
await expect(page.getByText('上传成功,新版本 retry-sha')).toBeVisible();
expect(attempts).toBe(2);
});
test('项目文件上传只限制合计 500 MiB,允许单个大文件并只计算已选文件', () => {
const file = (size: number, relativePath: string): SelectedFile => ({
file: { size } as File,
relativePath,
});
expect(MAX_PROJECT_UPLOAD_TOTAL).toBe(524288000);
const exactTotal = [file(300 * 1024 * 1024, 'first.bin'), file(200 * 1024 * 1024, 'last.bin')];
expect(validateProjectUpload(exactTotal, '')).toEqual([]);
expect(validateProjectUpload([file(MAX_PROJECT_UPLOAD_TOTAL, 'large.bin')], '')).toEqual([]);
expect(validateProjectUpload([...exactTotal, file(1, 'overflow.bin')], '')[0]).toContain('超过 500 MiB');
expect(validateProjectUpload(Array.from({ length: 501 }, (_, index) => file(1, `${index}.txt`)), '')[0]).toContain('最多 500 个');
expect(validateProjectUpload([], '')[0]).toBe('至少选择一个文件');
expect(validateProjectUpload([file(MAX_PROJECT_UPLOAD_TOTAL + 1, 'ignored.bin')], '').length).toBeGreaterThan(0);
expect(validateProjectUpload([file(1, 'kept.txt')], '')).toEqual([]);
});