import { afterEach, beforeEach, expect, test, vi } from 'vitest' import { mount, flushPromises } from '@vue/test-utils' import ElementPlus from 'element-plus' import CalibrationPage from '@/views/testing/calibrations/index.vue' import ScreenshotCard from '@/views/testing/calibrations/ScreenshotCard.vue' import { applyRecognized, calibrationData, emptyMatrix, partsFor } from '@/views/testing/calibrations/model' const api = vi.hoisted(() => ({ testing: vi.fn(), uploadCalibration: vi.fn(), calibrationEvidence: vi.fn(), recognizeCalibration: vi.fn(), confirm: vi.fn(), success: vi.fn(), info: vi.fn(), rows: [], write: true })) vi.mock('@/views/testing/shared/api', () => api) vi.mock('vue-router', () => ({ useRoute: () => ({ query: {} }) })) vi.mock('element-plus', async original => ({ ...await original(), ElMessageBox: { confirm: api.confirm }, ElMessage: { success: api.success, info: api.info } })) const wrappers = [] /** 用可控异步响应复现改图、关闭弹窗和确认期间继续编辑的竞态。 */ function deferred() { let resolve; const promise = new Promise(done => { resolve = done }); return { promise, resolve } } /** 所有请求替身保持完整的项目及设备身份,不访问开发库或外部模型。 */ beforeEach(() => { vi.clearAllMocks(); api.rows = []; api.write = true; api.confirm.mockResolvedValue('confirm') vi.stubGlobal('URL', { createObjectURL: vi.fn(), revokeObjectURL: vi.fn() }) api.testing.mockImplementation(async (path, method = 'get') => { if (method === 'post') return 99 if (path === '/projects') return [{ id: 7, name: '标定项目' }] if (path === '/capabilities') return { write: api.write } if (path === '/projects/7') return { role: 'MANAGER', robots: [{ id: 9, name: '机器人A' }, { id: 10, name: '机器人B' }] } if (path === '/projects/7/calibrations') return api.rows if (/\/calibration-images\/\d+\/info$/.test(path)) return { id: Number(path.match(/\d+/)[0]), projectId: 7, robotId: 9, partCode: 'POSE_POINTS', name: '当前图.png', width: 600, height: 300 } throw new Error(`Unexpected testing request: ${path}`) }) api.calibrationEvidence.mockImplementation(async id => `blob:image-${id}`) api.recognizeCalibration.mockImplementation(async id => ({ imageId: id, partCode: 'POSE_POINTS', data: { partCode: 'POSE_POINTS', points: [{ name: '1', x: '842.5820', y: '843.911', z: '219.023' }] } })) }) /** 释放组件及全部预览,并移除 Element Plus 的浮层,避免影响下一个测试。 */ afterEach(() => { wrappers.splice(0).forEach(wrapper => wrapper.unmount()); document.body.innerHTML = ''; vi.unstubAllGlobals() }) /** 挂载真实表单和 Element Plus,区域截图使用替身避免列表测试隐含发起下载。 */ async function page() { const wrapper = mount(CalibrationPage, { attachTo: document.body, global: { plugins: [ElementPlus], stubs: { ScreenshotCard: { props: ['partCode', 'modelValue'], template: '
{{partCode}}
' } } } }) wrappers.push(wrapper); await flushPromises(); return wrapper } /** 生成新版记录,图片 ID 与其他字段由场景显式设置。 */ function record(kind, data = calibrationData(kind)) { return { id: 1, robot_id: 9, name: '标定A', kind, version: 1, data } } /** 挂载真实截图组件,并模拟父组件按 v-model 接收上传后的当前图片身份。 */ async function screenshot(props = {}) { let wrapper wrapper = mount(ScreenshotCard, { props: { projectId: 7, robotId: 9, partCode: 'POSE_POINTS', modelValue: 1, ...props, 'onUpdate:modelValue': id => wrapper.setProps({ modelValue: id }) }, global: { plugins: [ElementPlus] } }) wrappers.push(wrapper); await flushPromises(); return wrapper } test('tool retains both axis screenshots and saves one final TCP as a new version', async () => { const data = calibrationData('TOOL'); data.images = { TOOL_AXIS5: 11, TOOL_AXIS6: 12 } const source = record('TOOL', data), wrapper = await page(); wrapper.vm.openForm(source); await flushPromises() expect([...document.querySelectorAll('.screenshot-stub')].map(item => item.textContent)).toEqual(partsFor('TOOL')) wrapper.vm.form.data.tool.axis = 'AXIS6'; wrapper.vm.form.data.tool.result.x = '-0.1230' expect(wrapper.vm.form.data.images).toEqual({ TOOL_AXIS5: 11, TOOL_AXIS6: 12 }) expect(source.data.tool.result.x).toBe('') await wrapper.vm.save() const saved = api.testing.mock.calls.find(call => call[1] === 'post') expect(saved[0]).toBe('/projects/7/calibrations'); expect(saved[2].data.tool.result.x).toBe('-0.1230') expect(saved[2].data.images).toEqual({ TOOL_AXIS5: 11, TOOL_AXIS6: 12 }) }) test('pose recognition fills only the table and preserves manual angles and target count', async () => { const data = calibrationData('POSE'); data.images.POSE_POINTS = 5; data.angles.a = '-115.906'; data.pose.targetCount = 4 const wrapper = await page(); wrapper.vm.openForm(record('POSE', data)); await flushPromises() await wrapper.vm.fillRecognized({ imageId: 5, partCode: 'POSE_POINTS', data: { points: [{ name: '1', x: '842.5820', y: '843.911', z: '219.023' }] } }) expect(wrapper.vm.form.data.points[0].x).toBe('842.5820'); expect(wrapper.vm.form.data.angles.a).toBe('-115.906'); expect(wrapper.vm.form.data.pose.targetCount).toBe(4) expect(data.points).toEqual([]) }) test('coordinate regions are independent and OCR does not synthesize matrix cells', () => { const data = calibrationData('COORDINATE'); data.errors.maximum = '1.1845' const matrix = emptyMatrix(); matrix[0][0] = '-0.699865' applyRecognized(data, 'COORD_MATRIX', { matrix }) expect(data.matrix[3]).toEqual(['', '', '', '']); expect(data.errors.maximum).toBe('1.1845'); expect(data.points).toEqual([]) }) test('a replacement image and edits during confirmation prevent stale candidate overwrite', async () => { const data = calibrationData('POSE'); data.images.POSE_POINTS = 5; data.points = [{ name: '1', x: '9', y: '', z: '' }] const wrapper = await page(); wrapper.vm.openForm(record('POSE', data)); await flushPromises() const candidate = { imageId: 5, partCode: 'POSE_POINTS', data: { points: [{ name: '1', x: '2', y: '', z: '' }] } } const wait = deferred(); api.confirm.mockReturnValueOnce(wait.promise) const filling = wrapper.vm.fillRecognized(candidate); wrapper.vm.form.data.points[0].x = '77'; wait.resolve('confirm'); await filling expect(wrapper.vm.form.data.points[0].x).toBe('77') wrapper.vm.form.data.images.POSE_POINTS = 6; await wrapper.vm.fillRecognized(candidate) expect(wrapper.vm.form.data.points[0].x).toBe('77') }) test('closing and reopening a form invalidates even candidates with the same image ID', async () => { const data = calibrationData('POSE'); data.images.POSE_POINTS = 5; data.points = [{ name: '1', x: '9', y: '', z: '' }] const wrapper = await page(); wrapper.vm.openForm(record('POSE', data)); await flushPromises() const wait = deferred(); api.confirm.mockReturnValueOnce(wait.promise) const filling = wrapper.vm.fillRecognized({ imageId: 5, partCode: 'POSE_POINTS', data: { points: [] } }) wrapper.vm.closeForm(); wrapper.vm.openForm(record('POSE', data)); wait.resolve('confirm'); await filling expect(wrapper.vm.form.data.points[0].x).toBe('9') }) test('old coordinate versions remain read-only and retired types are not listed', async () => { const source = record('COORDINATE', { points: [{ name: '1', referenceX: '621.005', measuredX: '395.174' }], matrix: emptyMatrix(), angles: { a: '-1' }, errors: { maximum: '1.1845' } }) api.rows = [source, { ...source, id: 2, kind: 'CHECK' }] const wrapper = await page(); expect(wrapper.vm.rows).toHaveLength(1) wrapper.vm.openForm(source, true); await flushPromises() expect(document.querySelectorAll('.screenshot-stub')).toHaveLength(0); expect(document.body.textContent).toContain('原版本数据参考') await wrapper.vm.save(); expect(api.testing.mock.calls.filter(call => call[1] === 'post')).toHaveLength(0) expect(source.data.points[0].referenceX).toBe('621.005') }) test('a user without write capability cannot submit a new calibration', async () => { api.write = false; const wrapper = await page(); wrapper.vm.openForm(record('TOOL')); await wrapper.vm.save() expect(api.testing.mock.calls.filter(call => call[1] === 'post')).toHaveLength(0) }) test('screenshot recognition always uses the currently selected image', async () => { const wrapper = await screenshot(); await wrapper.setProps({ modelValue: 2 }); await flushPromises(); await wrapper.vm.recognize() expect(api.recognizeCalibration.mock.calls[0][0]).toBe(2) expect(wrapper.emitted('recognized').at(-1)[0].imageId).toBe(2) }) test('late recognition for a previous image never emits a candidate', async () => { const wait = deferred(); api.recognizeCalibration.mockReturnValueOnce(wait.promise) const wrapper = await screenshot(), pending = wrapper.vm.recognize() await wrapper.setProps({ modelValue: 2 }); wait.resolve({ imageId: 1, partCode: 'POSE_POINTS', data: { points: [] } }); await pending expect(wrapper.emitted('recognized')).toBeUndefined() }) test('upload completion after changing robots cannot attach the old image', async () => { const wait = deferred(); api.uploadCalibration.mockReturnValueOnce(wait.promise) const wrapper = await screenshot({ modelValue: undefined }), pending = wrapper.vm.choose({ raw: new File(['image'], 'current.png', { type: 'image/png' }) }) await wrapper.setProps({ robotId: 10 }); wait.resolve({ id: 3 }); await pending expect(wrapper.emitted('update:modelValue')).toBeUndefined(); expect(api.recognizeCalibration).not.toHaveBeenCalled() }) test('readonly evidence disables all writes and releases the preview when unmounted', async () => { const wrapper = await screenshot({ readonly: true }); await wrapper.vm.recognize(); await wrapper.vm.choose({ raw: new File(['image'], 'x.png') }) expect(api.uploadCalibration).not.toHaveBeenCalled(); expect(api.recognizeCalibration).not.toHaveBeenCalled() wrapper.unmount(); wrappers.splice(wrappers.indexOf(wrapper), 1) expect(URL.revokeObjectURL).toHaveBeenCalledWith('blob:image-1') })