260 lines
14 KiB
JavaScript
260 lines
14 KiB
JavaScript
|
|
/**
|
|
* End-to-end acceptance for an isolated material service.
|
|
*
|
|
* Required environment: XIAOYI_QA_BASE, XIAOYI_QA_DESKTOP_TOKEN,
|
|
* XIAOYI_QA_OTHER_TOKEN, XIAOYI_QA_EXTERNAL_KEY, XIAOYI_QA_VIDEO_PATH.
|
|
* Optional XIAOYI_QA_LISTING_KEY exercises status callbacks with a scoped Key.
|
|
* The service must use isolated test data and storage. The script creates three
|
|
* projects, uploaded files and materials in that isolated environment.
|
|
*/
|
|
import assert from 'node:assert/strict'
|
|
import { readFile } from 'node:fs/promises'
|
|
import { createHash, randomUUID } from 'node:crypto'
|
|
import JSZip from 'jszip'
|
|
import sharp from 'sharp'
|
|
|
|
const required = name => {
|
|
const value = process.env[name]
|
|
if (!value) throw Error('Missing environment setting: ' + name)
|
|
return value
|
|
}
|
|
const origin = new URL(required('XIAOYI_QA_BASE'))
|
|
assert.ok(['127.0.0.1', 'localhost', '[::1]'].includes(origin.hostname), 'Acceptance requires a loopback-only test service')
|
|
const owner = required('XIAOYI_QA_DESKTOP_TOKEN')
|
|
const other = required('XIAOYI_QA_OTHER_TOKEN')
|
|
const externalKey = required('XIAOYI_QA_EXTERNAL_KEY')
|
|
const listingKey = process.env.XIAOYI_QA_LISTING_KEY
|
|
assert.notEqual(owner, other, 'Owner and second user require distinct sessions')
|
|
const video = await readFile(required('XIAOYI_QA_VIDEO_PATH'))
|
|
assert.ok(video.length > 32, 'Use a valid synthetic MP4 fixture')
|
|
const pngs = await Promise.all(['#d64242', '#429c42', '#4242d6', '#d6b642'].map(background =>
|
|
sharp({ create: { width: 64, height: 64, channels: 3, background } }).png().toBuffer(),
|
|
))
|
|
const chunkSize = 256 * 1024
|
|
|
|
async function request(method, pathname, { token = owner, data, bytes, headers = {} } = {}) {
|
|
const url = new URL(pathname, origin)
|
|
assert.equal(url.origin, origin.origin)
|
|
const response = await fetch(url, {
|
|
method,
|
|
headers: {
|
|
...(token ? { Authorization: 'Bearer ' + token } : {}),
|
|
...(data ? { 'Content-Type': 'application/json' } : {}),
|
|
...headers,
|
|
},
|
|
...(data ? { body: JSON.stringify(data) } : {}),
|
|
...(bytes ? { body: bytes } : {}),
|
|
redirect: 'manual',
|
|
})
|
|
const type = response.headers.get('content-type') ?? ''
|
|
const body = type.includes('application/json') ? await response.json() : null
|
|
return { status: response.status, body, response }
|
|
}
|
|
|
|
function expectStatus(result, allowed, name) {
|
|
assert.ok(allowed.includes(result.status), name + ' returned HTTP ' + result.status + ' ' + ' ' + (result.body?.error?.code ?? result.body?.code ?? ''))
|
|
}
|
|
|
|
async function project(name) {
|
|
const id = randomUUID()
|
|
const input = {
|
|
revision: 0, status: 'draft', document: {
|
|
version: 1, id, name, screens: [{ id: 'screen', width: 750, height: 400, layers: [] }],
|
|
},
|
|
}
|
|
const result = await request('PUT', '/api/desktop/projects/desktop/' + id, { data: input })
|
|
expectStatus(result, [200], 'create isolated project')
|
|
return id
|
|
}
|
|
|
|
async function upload(projectId, requestId, name, bytes, exerciseRecovery = false) {
|
|
const init = await request('POST', '/api/materials/upload/init', { data: {
|
|
fileName: name, fileSize: bytes.length, totalChunks: Math.ceil(bytes.length / chunkSize),
|
|
chunkSize, uploadPurpose: 'xiaoyi:' + projectId + ':' + requestId,
|
|
} })
|
|
expectStatus(init, [200], 'upload init')
|
|
const { uploadId } = init.body
|
|
assert.ok(uploadId)
|
|
const sendChunk = (token, index) => {
|
|
const part = bytes.subarray(index * chunkSize, Math.min(bytes.length, (index + 1) * chunkSize))
|
|
return request('POST', '/api/materials/upload/chunk', { token, bytes: part, headers: {
|
|
'Content-Type': 'application/octet-stream', 'Content-Length': String(part.length),
|
|
'X-Upload-Id': uploadId, 'X-Chunk-Index': String(index),
|
|
'X-Chunk-Size': String(part.length), 'X-File-Name': encodeURIComponent(name),
|
|
} })
|
|
}
|
|
if (exerciseRecovery) {
|
|
const denied = await sendChunk(other, 0)
|
|
expectStatus(denied, [401, 403, 404], 'cross-account chunk')
|
|
const incomplete = await request('POST', '/api/materials/upload/complete', { data: { uploadId } })
|
|
expectStatus(incomplete, [400, 404, 409, 422], 'incomplete upload')
|
|
}
|
|
for (let index = 0; index < Math.ceil(bytes.length / chunkSize); index++) {
|
|
const chunk = await sendChunk(owner, index)
|
|
expectStatus(chunk, [200], 'upload chunk')
|
|
}
|
|
const merged = await request('POST', '/api/materials/upload/complete', { data: { uploadId } })
|
|
expectStatus(merged, [200], 'merge chunks')
|
|
assert.equal(merged.body.uploadId, uploadId)
|
|
const repeated = await request('POST', '/api/materials/upload/complete', { data: { uploadId } })
|
|
expectStatus(repeated, [200], 'retry merge')
|
|
assert.equal(repeated.body.uploadId, uploadId)
|
|
return { uploadId, fileName: name, fileSize: bytes.length, sha256: createHash('sha256').update(bytes).digest('hex') }
|
|
}
|
|
|
|
async function externalMaterial(materialId) {
|
|
const reply = await request('GET', '/api/external/product-assets?materialId=' + encodeURIComponent(materialId), {
|
|
token: null, headers: { 'X-API-Key': externalKey },
|
|
})
|
|
expectStatus(reply, [200], 'external material read')
|
|
const object = reply.body?.data ?? reply.body
|
|
assert.equal(object.materialId, materialId)
|
|
return object
|
|
}
|
|
|
|
async function verifyDownload(material, expectedBytes) {
|
|
const address = material.downloadUrls?.all ?? material.downloadUrl ?? material.files?.[0]?.downloadUrl
|
|
assert.ok(address, 'External result has no download URL')
|
|
let url = new URL(address, origin)
|
|
if (url.origin === 'https://sc.jiansun.vip') url = new URL(url.pathname + url.search, origin)
|
|
for (let attempt = 0; attempt < 4; attempt++) {
|
|
assert.ok(['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname), 'Download must stay in the isolated loopback environment')
|
|
const response = await fetch(url, { redirect: 'manual' })
|
|
if (response.status >= 300 && response.status < 400) {
|
|
url = new URL(response.headers.get('location'), url)
|
|
continue
|
|
}
|
|
assert.equal(response.status, 200, 'material download failed')
|
|
const result = Buffer.from(await response.arrayBuffer())
|
|
assert.ok(result.length, 'material download is empty')
|
|
if (result.subarray(0, 2).toString() === 'PK') {
|
|
const archive = await JSZip.loadAsync(result)
|
|
const members = await Promise.all(Object.values(archive.files).filter(file => !file.dir).map(file => file.async('nodebuffer')))
|
|
for (const bytes of expectedBytes) assert.ok(members.some(member => member.equals(bytes)), 'expected delivered file missing from archive')
|
|
} else {
|
|
assert.equal(expectedBytes.length, 1)
|
|
assert.deepEqual(result, expectedBytes[0], 'downloaded bytes differ from delivered file')
|
|
}
|
|
return
|
|
}
|
|
throw Error('material download redirected too many times')
|
|
}
|
|
|
|
async function checkListingReport(found, projectId, kind) {
|
|
const materialId = found.materialId
|
|
const endpoint = '/api/external/product-assets?materialId=' + encodeURIComponent(materialId)
|
|
const keyHeaders = { token: null, headers: { 'X-API-Key': listingKey } }
|
|
const report = (data, credentials = keyHeaders) => request('PATCH', endpoint, { ...credentials, data })
|
|
const read = () => request('GET', '/api/desktop/deliveries/' + projectId + '/' + kind)
|
|
const initial = await request('GET', endpoint, keyHeaders)
|
|
expectStatus(initial, [200], 'scoped material read')
|
|
const event = initial.body.data.eventId
|
|
assert.ok(event)
|
|
assert.equal(initial.body.data.listingStatus.state, 'pending')
|
|
const first = { eventId: event, sequence: 1, state: 'listing' }
|
|
expectStatus(await report(first, { token: null }), [401], 'missing callback key')
|
|
expectStatus(await report(first, { token: null, headers: { 'X-API-Key': externalKey } }), [403], 'general key cannot report status')
|
|
expectStatus(await request('DELETE', endpoint, keyHeaders), [401], 'scoped key cannot delete')
|
|
expectStatus(await report({ ...first, eventId: randomUUID() }), [409], 'wrong event')
|
|
expectStatus(await report({ ...first, sequence: 0 }), [400], 'invalid sequence')
|
|
expectStatus(await report(first), [200], 'listing in progress')
|
|
assert.equal((await read()).body.listingStatus.state, 'listing')
|
|
const failed = { ...first, sequence: 2, state: 'failed', message: '测试失败原因' }
|
|
expectStatus(await report(failed), [200], 'listing failure')
|
|
assert.equal((await read()).body.listingStatus.message, failed.message)
|
|
const listed = { ...first, sequence: 3, state: 'listed', listingId: 'QA-listing' }
|
|
const [reportA, reportB] = await Promise.all([report(listed), report(listed)])
|
|
expectStatus(reportA, [200], 'listing result')
|
|
expectStatus(reportB, [200], 'concurrent duplicate listing result')
|
|
assert.deepEqual([reportA.body.data.applied, reportB.body.data.applied].sort(), [false, true])
|
|
assert.equal((await report(failed)).body.data.applied, false)
|
|
expectStatus(await report({ ...listed, listingId: 'different' }), [409], 'sequence content collision')
|
|
expectStatus(await report({ ...failed, sequence: 4 }), [409], 'reported success cannot regress')
|
|
const last = await read()
|
|
assert.equal(last.body.listingStatus.state, 'listed')
|
|
assert.equal(last.body.listingStatus.listingId, listed.listingId)
|
|
}
|
|
|
|
async function runCase(kind, materialType) {
|
|
const projectId = await project('验收用 ' + kind)
|
|
const requestId = randomUUID()
|
|
const assets = { main: [], sku: [], detail: [], files: [] }
|
|
if (kind === 'detail') {
|
|
assets.main.push(await upload(projectId, requestId, '主图.png', pngs[0], true))
|
|
assets.sku.push(await upload(projectId, requestId, 'SKU.png', pngs[1]))
|
|
assets.detail.push(await upload(projectId, requestId, '详情.png', pngs[2]))
|
|
} else if (kind === 'video') {
|
|
assets.files.push(await upload(projectId, requestId, '成片.mp4', video))
|
|
} else {
|
|
assets.files.push(await upload(projectId, requestId, '买家秀.png', pngs[3]))
|
|
}
|
|
const body = { projectId, kind, requestId, productModel: 'QA-' + randomUUID(),
|
|
categoryName: '', productCategoryName: '验收品类', assets }
|
|
if (kind === 'detail') {
|
|
const sourceInit = await request('POST', '/api/materials/upload/init', { data: {
|
|
fileName: '源文件.psd', fileSize: pngs[0].length, totalChunks: 1,
|
|
chunkSize, uploadPurpose: 'xiaoyi:' + projectId + ':' + requestId,
|
|
} })
|
|
expectStatus(sourceInit, [400, 409, 422], 'detail source upload rejected')
|
|
const uploaded = await upload(projectId, requestId, '候选.jpg', pngs[0])
|
|
const source = { ...uploaded, fileName: '源文件.psd' }
|
|
const rejected = await request('POST', '/api/desktop/deliveries', {
|
|
data: { ...body, assets: { ...assets, files: [source] } },
|
|
})
|
|
expectStatus(rejected, [400, 409, 422], 'detail source file rejected')
|
|
const wrongGroup = await request('POST', '/api/desktop/deliveries', {
|
|
data: { ...body, assets: { ...assets, main: [...assets.main, source] } },
|
|
})
|
|
expectStatus(wrongGroup, [400, 409, 422], 'detail source file rejected in image group')
|
|
}
|
|
const wrongRequest = await request('POST', '/api/desktop/deliveries', {
|
|
data: { ...body, requestId: randomUUID() },
|
|
})
|
|
expectStatus(wrongRequest, [400, 403, 404, 409, 422], 'upload belongs to a different request')
|
|
const [first, retry] = await Promise.all([
|
|
request('POST', '/api/desktop/deliveries', { data: body }),
|
|
request('POST', '/api/desktop/deliveries', { data: body }),
|
|
])
|
|
expectStatus(first, [200, 201], 'finish material')
|
|
expectStatus(retry, [200, 201], 'concurrent finish')
|
|
assert.equal(first.body.materialId, retry.body.materialId, 'concurrent retry created a duplicate material')
|
|
assert.equal(first.body.materialType, materialType)
|
|
const materialId = first.body.materialId
|
|
const again = await request('POST', '/api/desktop/deliveries', { data: body })
|
|
expectStatus(again, [200, 201], 'repeat finish')
|
|
assert.equal(again.body.materialId, materialId)
|
|
const receipt = await request('GET', '/api/desktop/deliveries/' + projectId + '/' + kind)
|
|
expectStatus(receipt, [200], 'saved receipt')
|
|
assert.equal(receipt.body.materialId, materialId)
|
|
const forbidden = await request('GET', '/api/desktop/deliveries/' + projectId + '/' + kind, { token: other })
|
|
expectStatus(forbidden, [401, 403, 404], 'cross-account receipt')
|
|
const crossSubmit = await request('POST', '/api/desktop/deliveries', { token: other, data: body })
|
|
expectStatus(crossSubmit, [401, 403, 404, 409], 'cross-account delivery')
|
|
const found = await externalMaterial(materialId)
|
|
assert.ok(!found.categoryName, 'A brand was substituted for an unspecified shop')
|
|
if (kind === 'detail') {
|
|
assert.ok(found.assets?.main?.length > 0 && found.assets?.sku?.length > 0 && found.assets?.detail?.length > 0,
|
|
'External detail result must expose all three asset groups')
|
|
assert.ok(!found.assets?.source?.length && !found.files?.length, 'Detail delivery must not contain source files')
|
|
} else {
|
|
assert.ok(found.files?.length > 0 || found.assets?.files?.length > 0,
|
|
'External result must expose the submitted files')
|
|
}
|
|
await verifyDownload(found, kind === 'detail' ? pngs.slice(0, 3) : [kind === 'video' ? video : pngs[3]])
|
|
const groupedFiles = kind === 'detail'
|
|
? [[found.assets.main[0], pngs[0]], [found.assets.sku[0], pngs[1]], [found.assets.detail[0], pngs[2]]]
|
|
: [[found.files[0], kind === 'video' ? video : pngs[3]]]
|
|
for (const [file, bytes] of groupedFiles) {
|
|
assert.ok(file.downloadUrl, 'Single-file download URL is missing')
|
|
await verifyDownload({ downloadUrl: file.downloadUrl }, [bytes])
|
|
}
|
|
if (listingKey) await checkListingReport(found, projectId, kind)
|
|
console.log(JSON.stringify({ kind, materialType, materialId, repeatedId: true, crossAccountDenied: true,
|
|
externalReadable: true, listingReported: Boolean(listingKey) }))
|
|
}
|
|
|
|
await runCase('detail', '自动上架-详情')
|
|
await runCase('video', '自动上架-视频')
|
|
await runCase('buyer_show', '自动上架-买家秀')
|