freshyo/apps/backend/tests/api/e2e-upload.test.ts
2026-10-20 00:31:05 +05:30

160 lines
5.8 KiB
TypeScript

/**
* E2E-51..55 — golden upload flow (catalogue §2.5).
*
* Live HTTP/tRPC suite. Each `it()` maps to one catalogue row.
*
* `common.generateUploadUrls` issues a presigned PUT under a context folder and
* records a pending `upload_url_status` row. In this local environment the R2
* endpoint and the public assets domain are both reachable, so the PUT + public
* GET path is exercised for real.
*/
import { apiClient, expectTrpcError, uniqueSuffix, type ApiClient } from '../helpers/api'
import { staffClient } from '../helpers/sessions'
import { createProduct, createStore, registerThrowawayUser } from '../helpers/fixtures'
import { getEssentialConsts } from '../helpers/cache'
jest.setTimeout(180_000)
const pathOf = (url: string) => url.split('?')[0]
const keyOf = (url: string) => pathOf(url).split('/').filter(Boolean).slice(-2).join('/')
async function genUploads(
client: ApiClient,
contextString: string,
mimeTypes: string[]
): Promise<string[]> {
const res: any = await client.common.generateUploadUrls.mutate({
contextString,
mimeTypes,
} as any)
return res.uploadUrls
}
function skuInput(name: string, price: number, images: string[] = []): any {
return {
name,
price,
marketPrice: price + 50,
images,
isFlashAvailable: false,
flashPrice: null,
isOutOfStock: false,
isOffer: false,
isComboOnly: false,
isSuspended: false,
features: [{ featureName: 'quantity', featureValue: name }],
}
}
async function createWithImages(
admin: ApiClient,
storeId: number,
name: string,
images: string[]
): Promise<any> {
return admin.admin.product.createProduct.mutate({
name,
shortDescription: 'upload probe',
storeId,
productType: 'item',
skus: [skuInput('1pc', 199, images)],
} as any)
}
/* -------------------------------------------------------------------------- */
/* Presign + PUT + public GET (E2E-51..52) */
/* -------------------------------------------------------------------------- */
describe('upload golden flow (E2E-51..52)', () => {
it('E2E-51: a generated upload URL carries the context folder and extension', async () => {
const urls = await genUploads(await staffClient(), 'review', ['image/png'])
expect(urls).toHaveLength(1)
expect(urls[0]).toContain('X-Amz-Signature=')
expect(pathOf(urls[0])).toContain('/review-images/')
expect(pathOf(urls[0]).endsWith('.png')).toBe(true)
expect(keyOf(urls[0])).toMatch(/^review-images\/\d+\.png$/)
})
it('E2E-52: bytes PUT to the presigned URL are readable at the public assets URL', async () => {
const urls = await genUploads(await staffClient(), 'review', ['image/png'])
const url = urls[0]
const key = keyOf(url)
const body = `hello-e2e-${uniqueSuffix()}`
const put = await fetch(url, {
method: 'PUT',
headers: { 'content-type': 'image/png' },
body,
})
expect(put.status).toBe(200)
const assetsDomain = (await getEssentialConsts()).assetsDomain
const publicUrl = `${assetsDomain}${key}`
const get = await fetch(publicUrl)
expect(get.status).toBe(200)
expect(await get.text()).toBe(body)
})
})
/* -------------------------------------------------------------------------- */
/* Edge cases (E2E-53..55) */
/* -------------------------------------------------------------------------- */
describe('upload golden edges (E2E-53..55)', () => {
it('E2E-53: two identical mime types in one call yield one URL each', async () => {
const urls = await genUploads(await staffClient(), 'review', ['image/png', 'image/png'])
expect(urls).toHaveLength(2)
for (const url of urls) {
expect(pathOf(url)).toContain('/review-images/')
expect(pathOf(url).endsWith('.png')).toBe(true)
expect(url).toContain('X-Amz-Signature=')
}
})
it('E2E-54: an unknown or already-claimed key in product create is 400 before any write', async () => {
const admin = await staffClient()
const store = await createStore()
// (a) Fabricated key that was never issued by the app.
const fabricatedName = `E2E Upload Fabricated ${uniqueSuffix()}`
await expectTrpcError(
() =>
createWithImages(admin, store.storeId, fabricatedName, [
`product-images/fabricated-${uniqueSuffix()}.png`,
]),
'BAD_REQUEST',
'were not uploaded through the app'
)
const listAfterFabricated: any = await admin.admin.product.getProducts.query()
expect(listAfterFabricated.products.some((p: any) => p.name === fabricatedName)).toBe(false)
// (b) A real presigned key already claimed by a previous product.
const urls = await genUploads(admin, 'product_info', ['image/png'])
await createWithImages(admin, store.storeId, `E2E Upload Owner ${uniqueSuffix()}`, [urls[0]])
const reusedName = `E2E Upload Reused ${uniqueSuffix()}`
await expectTrpcError(
() => createWithImages(admin, store.storeId, reusedName, [urls[0]]),
'BAD_REQUEST',
'were not uploaded through the app'
)
const listAfterReused: any = await admin.admin.product.getProducts.query()
expect(listAfterReused.products.some((p: any) => p.name === reusedName)).toBe(false)
})
it('E2E-55: an unknown key in a review is logged but the review still creates', async () => {
const store = await createStore()
const product = await createProduct({ storeId: store.storeId, price: 199 })
const user = await registerThrowawayUser()
const res: any = await apiClient(user.token).user.product.createReview.mutate({
productId: product.skuId,
reviewBody: 'lenient upload contract',
ratings: 5,
uploadUrls: [`review-images/unknown-${uniqueSuffix()}.png`],
})
expect(res.success).toBe(true)
expect(Number(res.review.id)).toBeGreaterThan(0)
})
})