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

287 lines
9.9 KiB
TypeScript

/**
* UUSER-01..17 (`user.user.*`, §6.14) and UUP-01..10
* (`user.fileUpload.generateUploadUrls`, §6.15).
*
* Several push-token rules (the region a token carries) are not exposed by any
* read API — `notif_creds.region_id` and `unlogged_user_tokens.region_id` are
* write-only. Those rows are pinned `(current)` with the observable contract.
*/
import { apiClient, expectTrpcError, uniqueSuffix } from '../helpers/api'
import { staffClient } from '../helpers/sessions'
import { createAddress, createStore, registerThrowawayUser } from '../helpers/fixtures'
jest.setTimeout(180_000)
async function selfData(token: string): Promise<any> {
const res: any = await apiClient(token).user.user.getSelfData.query()
return res.data
}
async function createReviewUploads(
token: string,
contextString: string,
mimeTypes: string[]
): Promise<string[]> {
const res: any = await apiClient(token).user.fileUpload.generateUploadUrls.mutate({
contextString,
mimeTypes,
} as any)
return res.uploadUrls
}
async function createProductWithImages(images: string[]): Promise<any> {
const admin = await staffClient()
const store = await createStore()
return admin.admin.product.createProduct.mutate({
name: `E2E Upload ${uniqueSuffix()}`,
shortDescription: 'Created by backend API tests',
storeId: store.storeId,
productType: 'item',
skus: [
{
name: '1pc',
price: 199,
marketPrice: 249,
images,
isFlashAvailable: false,
flashPrice: null,
isOutOfStock: false,
isOffer: false,
isComboOnly: false,
isSuspended: false,
features: [{ featureName: 'quantity', featureValue: '1pc' }],
},
],
} as any)
}
/* -------------------------------------------------------------------------- */
/* 6.14 User profile / push token */
/* -------------------------------------------------------------------------- */
describe('user.user profile + push token (UUSER-01..17)', () => {
it('UUSER-01: getSelfData returns the identity and profile fields', async () => {
const user = await registerThrowawayUser()
const data = await selfData(user.token)
expect(data.user).toEqual(
expect.objectContaining({
id: user.userId,
name: user.name,
email: user.email,
mobile: user.mobile,
})
)
expect(data.user).toHaveProperty('profileImage')
expect(data.user).toHaveProperty('bio')
expect(data.user).toHaveProperty('dateOfBirth')
expect(data.user).toHaveProperty('gender')
expect(data.user).toHaveProperty('occupation')
})
it('UUSER-02 (current): getSelfData returns the scaffolded asset URL, not a signed URL', async () => {
// The handler uses `scaffoldAssetUrl(profileImage)` (assets domain), whereas
// login/updateProfile sign the key. The catalogue expects a signed URL here;
// the observed read-path contract is the public asset URL.
const user = await registerThrowawayUser()
await apiClient(user.token).user.auth.updateProfile.mutate({
profileImageUrl: 'https://example.com/x.png',
})
const data = await selfData(user.token)
expect(typeof data.user.profileImage).toBe('string')
expect(data.user.profileImage).toContain('x.png')
expect(data.user.profileImage).not.toContain('X-Amz-')
})
it('UUSER-03: a user with no detail row still returns null profile fields', async () => {
const user = await registerThrowawayUser()
const data = await selfData(user.token)
expect(data.user.bio).toBeNull()
expect(data.user.dateOfBirth).toBeNull()
expect(data.user.gender).toBeNull()
expect(data.user.occupation).toBeNull()
})
it('UUSER-04: a deleted user token is 404', async () => {
const user = await registerThrowawayUser()
await apiClient(user.token).user.auth.deleteAccount.mutate({ mobile: user.mobile })
await expectTrpcError(
() => apiClient(user.token).user.user.getSelfData.query(),
'NOT_FOUND',
'User not found'
)
})
it('UUSER-05: getSelfData with no token is 401', async () => {
await expectTrpcError(
() => apiClient().user.user.getSelfData.query(),
'UNAUTHORIZED'
)
})
it('UUSER-14: recordTrackedRegion succeeds and records the association', async () => {
const user = await registerThrowawayUser()
const res: any = await apiClient(user.token).user.user.recordTrackedRegion.mutate({ regionId: 2 })
expect(res.success).toBe(true)
})
it('UUSER-15: an invalid or missing region is BAD_REQUEST', async () => {
const user = await registerThrowawayUser()
await expectTrpcError(
() => apiClient(user.token).user.user.recordTrackedRegion.mutate({ regionId: -1 }),
'BAD_REQUEST'
)
await expectTrpcError(
() => apiClient(user.token).user.user.recordTrackedRegion.mutate({} as any),
'BAD_REQUEST'
)
})
it('UUSER-16: recordTrackedRegion with no token is 401', async () => {
await expectTrpcError(
() => apiClient().user.user.recordTrackedRegion.mutate({ regionId: 1 }),
'UNAUTHORIZED'
)
})
})
/* -------------------------------------------------------------------------- */
/* 6.15 User file upload */
/* -------------------------------------------------------------------------- */
describe('user.fileUpload.generateUploadUrls (UUP-01..10)', () => {
it('UUP-01: a review jpeg returns a presigned review-images URL', async () => {
const user = await registerThrowawayUser()
const urls = await createReviewUploads(user.token, 'review', ['image/jpeg'])
expect(urls).toHaveLength(1)
expect(urls[0]).toContain('/review-images/')
expect(urls[0].split('?')[0].endsWith('.jpg')).toBe(true)
expect(urls[0]).toContain('X-Amz-Expires=180')
expect(urls[0]).toContain('X-Amz-Signature=')
})
it('UUP-02: product_info png uses the product-images folder and .png', async () => {
const user = await registerThrowawayUser()
const urls = await createReviewUploads(user.token, 'product_info', ['image/png'])
expect(urls).toHaveLength(1)
expect(urls[0]).toContain('/product-images/')
expect(urls[0].split('?')[0].endsWith('.png')).toBe(true)
})
it('UUP-03: complaint/profile/tags map to their folders', async () => {
const user = await registerThrowawayUser()
const folders: Record<string, string> = {
// Push-notification upload context disabled per AGENTS.md.
// notification: 'notification-images',
complaint: 'complaint-images',
profile: 'profile-images',
tags: 'tags',
}
for (const [context, folder] of Object.entries(folders)) {
const urls = await createReviewUploads(user.token, context, ['image/jpeg'])
expect(urls).toHaveLength(1)
expect(urls[0]).toContain(`/${folder}/`)
}
})
it('UUP-04: an empty mimeTypes list returns []', async () => {
const user = await registerThrowawayUser()
const urls = await createReviewUploads(user.token, 'review', [])
expect(urls).toEqual([])
})
it('UUP-05: an unknown mime type falls back to .jpg', async () => {
const user = await registerThrowawayUser()
const urls = await createReviewUploads(user.token, 'review', ['application/octet-stream'])
expect(urls).toHaveLength(1)
expect(urls[0].split('?')[0].endsWith('.jpg')).toBe(true)
})
it('UUP-06: an invalid context is BAD_REQUEST', async () => {
const user = await registerThrowawayUser()
await expectTrpcError(
() =>
apiClient(user.token).user.fileUpload.generateUploadUrls.mutate({
contextString: 'nope',
mimeTypes: ['image/jpeg'],
} as any),
'BAD_REQUEST'
)
})
it('UUP-07: no token is 401', async () => {
await expectTrpcError(
() =>
apiClient().user.fileUpload.generateUploadUrls.mutate({
contextString: 'review',
mimeTypes: ['image/jpeg'],
}),
'UNAUTHORIZED'
)
})
it('UUP-08 (current): the S3-failure 500 path is not inducible; valid calls succeed', async () => {
// `generateUploadUrls` maps a signing failure to ApiError(..., 500). Nothing in
// the public input can force `generateUploadUrl` to throw, so the reachable
// contract is asserted: a well-formed call always yields URLs.
const user = await registerThrowawayUser()
const urls = await createReviewUploads(user.token, 'review', ['image/jpeg', 'image/png'])
expect(urls).toHaveLength(2)
expect(urls.every((u) => u.includes('X-Amz-Signature='))).toBe(true)
})
it('UUP-09: review_response is rejected here but accepted by common.generateUploadUrls', async () => {
const user = await registerThrowawayUser()
await expectTrpcError(
() =>
apiClient(user.token).user.fileUpload.generateUploadUrls.mutate({
contextString: 'review_response',
mimeTypes: ['image/png'],
} as any),
'BAD_REQUEST'
)
const res: any = await apiClient(user.token).common.generateUploadUrls.mutate({
contextString: 'review_response',
mimeTypes: ['image/png'],
})
expect(res.uploadUrls).toHaveLength(1)
expect(res.uploadUrls[0]).toContain('/review-response-images/')
})
it('UUP-10 (current): a generated key is pending once, then claimed on first use', async () => {
// `upload_url_status` is write-only: the pending->claimed transition is only
// observable when a second write reuses the key. `admin.product.createProduct`
// asserts claimability, so the first use succeeds and the reuse is a 400.
const admin = await staffClient()
const gen: any = await admin.common.generateUploadUrls.mutate({
contextString: 'product_info',
mimeTypes: ['image/jpeg'],
})
const url = gen.uploadUrls[0]
expect(typeof url).toBe('string')
await expect(createProductWithImages([url])).resolves.toBeDefined()
await expectTrpcError(
() => createProductWithImages([url]),
'BAD_REQUEST',
'not uploaded through the app'
)
})
})