Files
dtf-system/tests/upload_limits_test.py
Cauê Faleiros 31776ca353 fix: 96 DPI is accepted as the Site shows it; big carts upload 4 at a time (Sentry 12/11)
The server compared the raw lowest resolution (95,6) with 96 but printed
it rounded, refusing '96 DPI abaixo do mínimo de 96'; it now decides on the
same rounded value the Site shows. A big cart started every upload at once
and hit the limit of 10 pending uploads (429): the limit is 30, that
refusal carries Retry-After so the Site retries by itself, and the Site
runs at most 4 uploads at a time.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-12 09:38:51 -03:00

112 lines
5.7 KiB
Python

"""The upload limits: a 66-file cart fits, the per-source bucket still
refuses above its own limit (Marcus's bugs of 2026-11-11, B1), and a quote
takes up to 200 files per item (Sentry DTF-WEB-1).
Run against the local stack: python -m tests.upload_limits_test
"""
import json
import os
import secrets
from pathlib import Path
from urllib.error import HTTPError
from urllib.request import Request
from uuid import UUID, uuid4
from fastapi import HTTPException
from app.api.uploads import UPLOAD_START_IP_LIMIT, UPLOAD_START_LIMIT
from app.core import db
from app.core.auth import rate_limit
from tests.smoke_test import BASE, Client, upload_bytes, with_host
PNG = (Path(__file__).resolve().parent / 'fixtures' / 'final-300.png').read_bytes()
TOO_MANY = 'Este item tem mais de 200 arquivos. Divida em dois itens.'
def item_with(uploads):
"""One ready-sheet item: one source per upload, stacked in a row."""
count = len(uploads)
height = count * 0.3
return {
'mode': 'file', 'metres': round(height / 100, 4), 'grade': 100, 'uploads': uploads,
'production': {
'version': 3, 'film_width_cm': 57, 'height_cm': height,
'sources': [{'upload_id': uid, 'kind': 'sheet', 'width_cm': 0.5, 'length_cm': 0.25,
'copies': 1, 'rotation_degrees': 0, 'mirrored': False,
'measurement': 'file'} for uid in uploads],
'placements': [{'source_index': index, 'copy_index': 0, 'x_cm': 0,
'y_cm': round(index * 0.3, 4), 'width_cm': 0.5, 'length_cm': 0.25,
'rotation_degrees': 0, 'mirrored': False} for index in range(count)]},
'quality_status': 'ok', 'quality_acknowledged': False, 'residue_accepted': 0}
def run():
assert (UPLOAD_START_LIMIT, UPLOAD_START_IP_LIMIT) == (1000, 3000)
client = Client()
scope = client.call('/session')['cart_scope']
try:
# A 66-file cart, with retries, fits in one session. Each reservation is
# cancelled so the pending-upload quota (unchanged) does not stop the test.
for index in range(70):
uid = client.call('/uploads', {'name': f'LIMIT-{index}.png', 'size': 1})['id']
client.call(f'/uploads/{uid}', expected=200, method='DELETE')
# The per-source bucket, exercised directly with a small limit: 3000 real
# starts would only slow CI. A unique key keeps other suites out of it.
key = 'upload-start-ip-test-' + secrets.token_hex(8)
for _ in range(3):
rate_limit('upload-start-ip', key, 3, 900)
try:
rate_limit('upload-start-ip', key, 3, 900)
except HTTPException as error:
assert error.status_code == 429, error
assert error.headers.get('Retry-After') == '900', error.headers
else:
raise AssertionError('the per-source upload bucket accepted above its limit')
# DTF-WEB-3: a burst above MAX_PENDING_UPLOADS (now 30). The 31st start
# answers 429 with Retry-After 15, so the Site waits and retries alone.
assert int(os.environ.get('MAX_PENDING_UPLOADS', '30')) == 30
pending = []
for index in range(30):
pending.append(client.call('/uploads', {'name': f'PENDING-{index}.png', 'size': 1})['id'])
burst = Request(BASE + '/api/uploads',
data=json.dumps({'name': 'PENDING-31.png', 'size': 1}).encode(),
headers=with_host({'Content-Type': 'application/json'}), method='POST')
try:
with client.opener.open(burst, timeout=30) as response:
raise AssertionError('the pending-upload cap accepted the 31st upload')
except HTTPError as error:
assert error.code == 429, error
assert error.headers.get('Retry-After') == '15', error.headers
assert json.load(error)['detail'] == 'Muitos envios ao mesmo tempo. O site tenta de novo sozinho.'
for uid in pending:
client.call(f'/uploads/{uid}', expected=200, method='DELETE')
# Sentry DTF-WEB-1: 66 sheets in one ready-sheet item is quoted and
# approved; the old cap of 20 refused it with a generic 422.
uploads = [upload_bytes(client, PNG, name=f'SHEET66-{index}.png') for index in range(66)]
body = {'request_key': str(uuid4()), 'customer': {'name': 'Carrinho Grande',
'cnpj': '11222333000181', 'zap': '11999999999', 'mail': 'sheet66@example.test'},
'items': [item_with(uploads)], 'freight': {'service': 'pickup'}}
quote = client.call('/quotes', body)
assert quote['status'] == 'approved', quote
approved = client.call('/quotes/' + quote['id'])['approved']['items'][0]
assert (len(approved['uploads']), len(approved['production']['sources']),
len(approved['production']['placements'])) == (66, 66, 66), approved
# The old cap's message: one more file is refused with a readable text.
too_many = {**body, 'request_key': str(uuid4()),
'items': [{**item_with(uploads), 'uploads': [str(uuid4()) for _ in range(201)]}]}
detail = client.call('/quotes', too_many, expected=422)['detail']
messages = [entry.get('msg', '') for entry in detail if isinstance(entry, dict)]
assert any(TOO_MANY in message for message in messages), detail
print('PASS: 70 upload starts in one session; the per-source bucket refuses above its limit; '
'a 66-sheet item is quoted and 201 is refused with the readable message')
finally:
with db.connect() as c:
c.execute('DELETE FROM dtf_local.quotes WHERE owner=%s', (UUID(scope),))
c.execute('DELETE FROM dtf_local.uploads WHERE owner=%s', (UUID(scope),))
if __name__ == '__main__':
run()