175 lines
9.8 KiB
TypeScript
175 lines
9.8 KiB
TypeScript
import { expect, test, type Page, type Route } from '@playwright/test';
|
|
import { mkdtemp, mkdir, rm, writeFile } from 'node:fs/promises';
|
|
import { tmpdir } from 'node:os';
|
|
import { dirname, join } from 'node:path';
|
|
import type { ManagedProjectView, UrdfFile } from '../src/api/types';
|
|
import { filterUrdfFiles } from '../src/components/project/urdfFiles';
|
|
|
|
const resources = [
|
|
'robot.URDF', 'meshes/base.STL', 'meshes/body.dae', 'meshes/arm.obj',
|
|
'materials/arm.mtl', 'meshes/sensor.gltf', 'meshes/sensor.bin',
|
|
'textures/base.PNG', 'textures/arm.ktx2',
|
|
];
|
|
const unrelated = [
|
|
'README.md', 'src/main.py', 'package.xml', 'config/settings.yaml', 'archive.zip',
|
|
'.git/backup.urdf', '.DS_Store', '__MACOSX/._base.stl', 'node_modules/example/mesh.obj',
|
|
];
|
|
|
|
const project: ManagedProjectView = {
|
|
project: {
|
|
projectCode: 'test-robot', 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, entry: 'project' | 'import') {
|
|
const signed: UrdfFile[][] = [];
|
|
const confirmed: UrdfFile[][] = [];
|
|
await page.addInitScript(() => localStorage.setItem('vibemake_admin_token', 'test-token'));
|
|
await page.addInitScript(() => {
|
|
const originalFetch = window.fetch.bind(window);
|
|
window.fetch = (input, init) => {
|
|
const url = typeof input === 'string' ? input : input instanceof Request ? input.url : input.href;
|
|
if (new URL(url, window.location.href).pathname === '/mock-oss' && init?.body instanceof FormData) {
|
|
const uploads = JSON.parse(localStorage.getItem('urdf_test_uploads') ?? '[]');
|
|
uploads.push(Object.fromEntries([...init.body.entries()].map(([key, value]) => [key, value instanceof File ? value.name : value])));
|
|
localStorage.setItem('urdf_test_uploads', JSON.stringify(uploads));
|
|
}
|
|
return originalFetch(input, init);
|
|
};
|
|
});
|
|
await page.route('https://fonts.googleapis.com/**', (route) => route.abort());
|
|
await page.route('**/mock-oss', async (route) => {
|
|
await route.fulfill({ status: 204 });
|
|
});
|
|
// 拦截全部管理 API 和 OSS,测试不会向真实后端上传或创建项目。
|
|
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/test-robot') return ok(route, project);
|
|
if (path.endsWith('/tree')) return ok(route, { commitSha: 'main-sha', path: '', entries: [] });
|
|
if (path === '/project-imports/preview') return ok(route, {
|
|
repositoryUrl: 'https://github.com/example/robot', defaultBranch: 'main', name: '测试机器人',
|
|
description: '', license: null, existingProjectCode: null,
|
|
});
|
|
if (path.endsWith('/urdf/signature')) {
|
|
const files = route.request().postDataJSON().files as UrdfFile[];
|
|
signed.push(files);
|
|
return ok(route, {
|
|
batchCode: 'test-batch', mainRelativePath: files[0].relativePath,
|
|
uploadUrl: 'http://127.0.0.1:5190/mock-oss',
|
|
files: files.map(({ relativePath }) => ({ relativePath, formFields: { key: relativePath } })),
|
|
});
|
|
}
|
|
if (path.endsWith('/urdf') && route.request().method() === 'PUT') {
|
|
confirmed.push(route.request().postDataJSON().files);
|
|
return ok(route, project.project);
|
|
}
|
|
if (path === '/project-imports' && route.request().method() === 'POST') {
|
|
confirmed.push(route.request().postDataJSON().urdf.files);
|
|
// 留在创建页,便于断言本次提交,避免进入任务轮询。
|
|
return route.fulfill({ status: 409, json: { code: 'DUPLICATE_SOURCE', message: '模拟重复来源', data: null } });
|
|
}
|
|
return ok(route, { items: [], page: 1, size: 20, total: 0 });
|
|
});
|
|
if (entry === 'project') {
|
|
await page.goto('/projects/test-robot');
|
|
await page.getByRole('tab', { name: 'URDF', exact: true }).click();
|
|
} else {
|
|
await page.goto('/imports/new');
|
|
await page.getByRole('textbox', { name: 'GitHub 仓库地址' }).fill('https://github.com/example/robot');
|
|
await page.getByRole('button', { name: /预\s*检/, exact: true }).click();
|
|
await page.getByRole('combobox', { name: '项目类型' }).click();
|
|
await page.getByText('轮式机器人', { exact: true }).click();
|
|
}
|
|
return { signed, confirmed };
|
|
}
|
|
|
|
async function chooseDirectory(page: Page, paths: string[], label = '选择 URDF 目录') {
|
|
const parent = await mkdtemp(join(tmpdir(), 'urdf-filter-'));
|
|
const directory = join(parent, 'robot');
|
|
try {
|
|
await Promise.all(paths.map(async (path) => {
|
|
const fullPath = join(directory, path);
|
|
await mkdir(dirname(fullPath), { recursive: true });
|
|
await writeFile(fullPath, 'test');
|
|
}));
|
|
const chooser = page.waitForEvent('filechooser');
|
|
await page.getByRole('button', { name: new RegExp(label) }).click();
|
|
await (await chooser).setFiles(directory);
|
|
await expect(page.getByRole('button', { name: '重新选择目录' })).toBeVisible();
|
|
} finally {
|
|
await rm(parent, { recursive: true, force: true });
|
|
}
|
|
}
|
|
|
|
for (const entry of ['project', 'import'] as const) {
|
|
test(`${entry} URDF 目录仅签名、上传和绑定渲染资源,保留嵌套引用路径`, async ({ page }) => {
|
|
const requests = await prepare(page, entry);
|
|
await chooseDirectory(page, [...resources, ...unrelated]);
|
|
await expect(page.getByText(`已过滤 ${unrelated.length} 个无关文件`, { exact: false })).toBeVisible();
|
|
await expect(page.locator('.file-list-row')).toHaveCount(resources.length);
|
|
await expect(page.locator('.file-list-main')).toHaveText('robot.URDF');
|
|
|
|
const keepRoot = page.getByRole('checkbox', { name: '保留所选文件夹名称' });
|
|
await keepRoot.check();
|
|
await expect(page.locator('.file-list-main')).toHaveText('robot/robot.URDF');
|
|
if (entry === 'project') await keepRoot.uncheck();
|
|
const expected = resources.map((relativePath) => ({
|
|
relativePath: entry === 'import' ? `robot/${relativePath}` : relativePath, sizeBytes: 4,
|
|
})).sort((a, b) => a.relativePath.localeCompare(b.relativePath));
|
|
await page.getByRole('button', { name: entry === 'project' ? '上传并绑定' : '创建迁移任务', exact: true }).click();
|
|
await expect.poll(() => requests.confirmed.length).toBe(1);
|
|
expect(requests.signed).toHaveLength(1);
|
|
expect([...requests.signed[0]].sort((a, b) => a.relativePath.localeCompare(b.relativePath))).toEqual(expected);
|
|
expect(requests.confirmed[0]).toEqual(requests.signed[0]);
|
|
await expect.poll(() => page.evaluate(() => JSON.parse(localStorage.getItem('urdf_test_uploads') ?? '[]').length)).toBe(expected.length);
|
|
const uploads = await page.evaluate(() => JSON.parse(localStorage.getItem('urdf_test_uploads') ?? '[]')) as Record<string, string>[];
|
|
expect(uploads.map(({ key }) => key).sort()).toEqual(expected.map((file) => file.relativePath).sort());
|
|
expect(uploads.map(({ file }) => file).sort()).toEqual(expected.map((file) => file.relativePath.split('/').at(-1)!).sort());
|
|
});
|
|
}
|
|
|
|
test('过滤后仍校验多个或缺失的 URDF,全部过滤时阻止创建,清除后可继续', async ({ page }) => {
|
|
const requests = await prepare(page, 'import');
|
|
await chooseDirectory(page, ['first.urdf', 'second.URDF', 'README.md']);
|
|
await expect(page.getByText('目录中必须有且仅有一个 .urdf 文件(当前 2 个)', { exact: true })).toBeVisible();
|
|
await chooseDirectory(page, ['meshes/base.stl'], '重新选择目录');
|
|
await expect(page.getByText('目录中必须有且仅有一个 .urdf 文件(当前 0 个)', { exact: true })).toBeVisible();
|
|
await chooseDirectory(page, ['README.md', 'src/main.py'], '重新选择目录');
|
|
await expect(page.getByText('所选目录中没有可上传的 URDF 渲染资源,请重新选择目录或清除选择')).toBeVisible();
|
|
await expect(page.locator('.file-list-row')).toHaveCount(0);
|
|
await page.getByRole('button', { name: '创建迁移任务', exact: true }).click();
|
|
await expect(page.getByText('URDF 目录不符合要求,请重新选择或清除后再创建')).toBeVisible();
|
|
expect(requests.signed).toHaveLength(0);
|
|
expect(requests.confirmed).toHaveLength(0);
|
|
await page.getByRole('button', { name: /清\s*除/, exact: true }).click();
|
|
await expect(page.getByText('所选目录中没有可上传的 URDF 渲染资源,请重新选择目录或清除选择')).toHaveCount(0);
|
|
await expect(page.getByRole('button', { name: '选择 URDF 目录' })).toBeVisible();
|
|
});
|
|
|
|
test('扩展名大小写不敏感,保留材质和贴图数据,排除伪装扩展名和隐藏路径', () => {
|
|
const paths = [
|
|
'robot.URDF', 'meshes/arm.OBJ', 'materials/arm.MTL', 'textures/base.KTX2', 'mesh.bin',
|
|
'robot.urdf.bak', 'mesh.stl.zip', '.hidden.urdf', '.cache/mesh.stl',
|
|
'assets/.git/mesh.stl', '__MACOSX/mesh.stl', 'node_modules/pkg/model.glb',
|
|
];
|
|
const files = paths.map((path) => {
|
|
const file = new File(['test'], path.split('/').at(-1)!);
|
|
Object.defineProperty(file, 'webkitRelativePath', { value: `robot/${path}` });
|
|
return file;
|
|
});
|
|
expect(filterUrdfFiles(files)).toEqual(files.slice(0, 5));
|
|
expect(filterUrdfFiles([new File(['test'], 'standalone.STL')])).toHaveLength(1);
|
|
});
|