All checks were successful
Build and deploy / Validate source (push) Successful in 5s
Build and deploy / Integration suite on a real stack (push) Successful in 7m55s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 1m43s
Replaces 7111995 (only 57,0 cm entered; a whole order of 56,5-56,9 cm
sheets was refused, DTF-WEB-2C). Marcus's rules, for Arquivo por metro,
Premium (57 cm) and UV (27 cm):
1. A known width up to the film (PNG recording 200 DPI or more, or a PDF
page) enters at its real size, centred, billed by its real height.
2. Narrower: his warning before the cart, confirmation required
(Imprimir no tamanho real / Enviar outro arquivo); recorded in the
Prumo report ("cliente confirmou folha de 35,8 cm no tamanho real") and
shown in the cart and payment summaries.
3. Wider than the film: refused with his message.
4. Unknown width: taken as the film's, DPI from the pixels; 200 or more
with a confirmation, under 200 refused with the artes avulsas hint.
Within 0,1 cm of the film counts as the film. The server checks it all
again at checkout (sheet_width_issue, centred placement, size_confirmed).
Also ops.stretched_sheets: the ready-sheet orders since 16/10 laid out
wider than their real width (number, real width, factor), for Marcus.
Contract: output/revisao/contrato-folha-real.md.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
350 lines
18 KiB
Python
350 lines
18 KiB
Python
"""The server's grade against real image and PDF files.
|
||
|
||
Runs where Pillow and pikepdf are installed (the API image).
|
||
"""
|
||
import io
|
||
import tempfile
|
||
import unittest
|
||
from unittest import mock
|
||
|
||
import pikepdf
|
||
from PIL import Image
|
||
|
||
from app import grade_check
|
||
|
||
|
||
class FakeFiles:
|
||
def __init__(self, blobs):
|
||
self.blobs = blobs
|
||
|
||
def head(self, row):
|
||
return self.blobs[row['name']][:grade_check.HEAD_BYTES]
|
||
|
||
def pdf_dpi(self, row):
|
||
with tempfile.NamedTemporaryFile(suffix='.pdf') as handle:
|
||
handle.write(self.blobs[row['name']])
|
||
handle.flush()
|
||
return grade_check.pdf_dpi(handle.name)
|
||
|
||
|
||
class CountingStorage:
|
||
"""A storage that counts every read, keyed by object_key as the real one."""
|
||
|
||
def __init__(self, blobs):
|
||
self.bucket = 'bucket'
|
||
self.blobs = blobs
|
||
self.downloads = 0
|
||
self.heads = 0
|
||
self.client = self
|
||
|
||
def get_object(self, Bucket, Key, Range=None):
|
||
self.heads += 1
|
||
return {'Body': io.BytesIO(self.blobs[Key][:grade_check.HEAD_BYTES])}
|
||
|
||
def download_fileobj(self, bucket, key, handle):
|
||
self.downloads += 1
|
||
handle.write(self.blobs[key])
|
||
|
||
|
||
def encoded(fmt, size, **options):
|
||
out = io.BytesIO()
|
||
Image.new('RGBA' if fmt in ('PNG', 'WEBP') else 'RGB', size, (200, 30, 30)).save(out, fmt, **options)
|
||
return out.getvalue()
|
||
|
||
|
||
def item(kind, grade, sources):
|
||
return {'grade': grade, 'production': {'sources': [
|
||
{'upload_id': name, 'kind': kind, 'width_cm': width, 'rotation_degrees': rotation}
|
||
for name, width, rotation in sources]}}
|
||
|
||
|
||
class GradeCheckTests(unittest.TestCase):
|
||
def test_image_sizes_from_the_first_bytes(self):
|
||
for fmt, options in (('PNG', {}), ('JPEG', {'quality': 80}), ('JPEG', {'progressive': True}),
|
||
('WEBP', {'lossless': True}), ('WEBP', {'quality': 80})):
|
||
self.assertEqual(grade_check.image_size(encoded(fmt, (1234, 567), **options)), (1234, 567), (fmt, options))
|
||
# A JPEG with a large metadata block before the frame header.
|
||
exif = Image.Exif()
|
||
exif[0x010E] = 'x' * 60000
|
||
self.assertEqual(grade_check.image_size(encoded('JPEG', (800, 600), exif=exif)), (800, 600))
|
||
self.assertIsNone(grade_check.image_size(b'not an image at all'))
|
||
|
||
def test_pdf_dpi_is_the_images_area_weighted(self):
|
||
out = io.BytesIO()
|
||
Image.new('RGB', (1500, 750), 'white').save(out, 'PDF', resolution=150)
|
||
with tempfile.NamedTemporaryFile(suffix='.pdf') as handle:
|
||
handle.write(out.getvalue()); handle.flush()
|
||
self.assertEqual(grade_check.pdf_dpi(handle.name), 150)
|
||
vector = pikepdf.new()
|
||
vector.add_blank_page(page_size=(1615, 850))
|
||
with tempfile.NamedTemporaryFile(suffix='.pdf') as handle:
|
||
vector.save(handle.name)
|
||
self.assertEqual(grade_check.pdf_dpi(handle.name), 300)
|
||
|
||
def test_grades_follow_the_site(self):
|
||
# 57 cm is 22.44 in: the new clean threshold is 200 DPI.
|
||
files = FakeFiles({'a.png': encoded('PNG', (6059, 100)), 'b.jpg': encoded('JPEG', (3366, 100)),
|
||
'tall.png': encoded('PNG', (100, 2362)), 'x.cdr': b'CDR'})
|
||
rows = {n: {'name': n, 'size': 1} for n in files.blobs}
|
||
# A sheet takes the worst sheet's grade.
|
||
self.assertEqual(grade_check.item_grade(files, item('sheet', 0, [('a.png', 57, 0)]), rows), 100)
|
||
self.assertEqual(grade_check.item_grade(files, item('sheet', 0, [('a.png', 57, 0), ('b.jpg', 57, 0)]), rows), 75)
|
||
# Artworks average; a rotated one is measured along its height.
|
||
self.assertEqual(grade_check.item_grade(files, item('artwork', 0, [('a.png', 57, 0), ('b.jpg', 57, 0)]), rows), 88)
|
||
self.assertEqual(grade_check.item_grade(files, item('artwork', 0, [('tall.png', 20, 90)]), rows), 100)
|
||
self.assertIsNone(grade_check.item_grade(files, item('sheet', 0, [('x.cdr', 57, 0)]), rows))
|
||
# What the cart claims is checked, with a point or two of rounding.
|
||
claim = lambda g, src: grade_check.mismatch(files, [item('sheet', g, src)], rows)
|
||
self.assertIsNone(claim(100, [('a.png', 57, 0)]))
|
||
self.assertIsNone(claim(77, [('b.jpg', 57, 0)]))
|
||
self.assertEqual(claim(100, [('b.jpg', 57, 0)]), 'Nota 100 maior que a do arquivo (75)')
|
||
self.assertEqual(claim(40, [('x.cdr', 57, 0)]), 'Nota não conferida no servidor')
|
||
self.assertIsNone(claim(0, [('x.cdr', 57, 0)]))
|
||
|
||
def test_a_file_is_read_once_per_quote(self):
|
||
storage = CountingStorage({'k.pdf': b'%PDF-1.4 test', 'k.png': encoded('PNG', (100, 50))})
|
||
files = grade_check.Files(storage)
|
||
pdf_row = {'object_key': 'k.pdf', 'size': 15, 'name': 'a.pdf'}
|
||
with mock.patch.object(grade_check, 'bounded_pdf_dpi', return_value=300):
|
||
self.assertEqual(files.pdf_dpi(pdf_row), 300)
|
||
self.assertEqual(files.pdf_dpi(pdf_row), 300)
|
||
self.assertEqual(storage.downloads, 1)
|
||
png_row = {'object_key': 'k.png', 'size': 1, 'name': 'a.png'}
|
||
self.assertEqual(files.head(png_row)[:8], b'\x89PNG\r\n\x1a\n')
|
||
self.assertEqual(files.head(png_row)[:8], b'\x89PNG\r\n\x1a\n')
|
||
self.assertEqual(storage.heads, 1)
|
||
|
||
def test_a_scanned_pdf_is_not_read_again(self):
|
||
storage = CountingStorage({'k.pdf': b'%PDF-1.4 test'})
|
||
files = grade_check.Files(storage)
|
||
self.assertEqual(files.pdf_dpi({'object_key': 'k.pdf', 'size': 15, 'name': 'a.pdf',
|
||
'pdf_checked': True, 'pdf_dpi': 150}), 150)
|
||
self.assertIsNone(files.pdf_dpi({'object_key': 'unreadable.pdf', 'size': 1, 'name': 'b.pdf',
|
||
'pdf_checked': True, 'pdf_dpi': None}))
|
||
self.assertIsNone(files.pdf_dpi({'object_key': 'big.pdf', 'size': grade_check.PDF_MAX_BYTES + 1,
|
||
'name': 'big.pdf'}))
|
||
self.assertEqual(storage.downloads, 0)
|
||
|
||
def test_resolution_boundaries_and_consent(self):
|
||
width = lambda dpi: int(dpi * 57 / 2.54) + 1
|
||
files = FakeFiles({f'{dpi}.png': encoded('PNG', (width(dpi), 20))
|
||
for dpi in (95, 96, 199, 200, 287, 293)})
|
||
rows = {name: {'name': name, 'size': 1} for name in files.blobs}
|
||
def issue(dpi, status='ok', acknowledged=False):
|
||
spec = item('sheet', 0, [(f'{dpi}.png', 57, 0)])
|
||
spec.update(quality_status=status, quality_acknowledged=acknowledged)
|
||
return grade_check.resolution_issue(files, [spec], rows)
|
||
self.assertIn('abaixo do mínimo', issue(95))
|
||
self.assertIn('confirme a ressalva', issue(96))
|
||
self.assertIn('confirme a ressalva', issue(199))
|
||
self.assertIsNone(issue(96, 'warning', True))
|
||
self.assertIsNone(issue(199, 'warning', True))
|
||
for dpi in (200, 287, 293):
|
||
self.assertIsNone(issue(dpi), dpi)
|
||
self.assertEqual(grade_check.grade_of(dpi), 100)
|
||
# The Site shows the rounded DPI: 95.6 is 96 and passes; 95.4 is 95
|
||
# and is refused. The warning band starts at the shown 199.
|
||
width_px = lambda dpi: round(dpi * 57 / 2.54)
|
||
for dpi in (95.6, 95.4, 199.6, 199.4):
|
||
files.blobs[f'{dpi}.png'] = encoded('PNG', (width_px(dpi), 20))
|
||
rows[f'{dpi}.png'] = {'name': f'{dpi}.png', 'size': 1}
|
||
# 95.6 is shown as 96: the warning band, not the refusal; acknowledged,
|
||
# it goes through. 95.4 is shown as 95 and refused.
|
||
self.assertNotIn('abaixo do mínimo', issue(95.6))
|
||
self.assertIn('confirme a ressalva', issue(95.6))
|
||
self.assertIsNone(issue(95.6, 'warning', True))
|
||
self.assertIn('95 DPI', issue(95.4))
|
||
self.assertIsNone(issue(199.6))
|
||
self.assertIn('confirme a ressalva', issue(199.4))
|
||
|
||
|
||
def nested_forms_pdf(path, fanout=10, levels=8):
|
||
"""A 2 KB PDF whose page draws form F0 ten times, F0 draws F1 ten times,
|
||
eight deep: 10^8 draws for a reader that walks them."""
|
||
pdf = pikepdf.new()
|
||
pdf.add_blank_page(page_size=(200, 200))
|
||
forms = []
|
||
for level in reversed(range(levels)):
|
||
if forms:
|
||
content = b''.join(b'q /F%d Do Q\n' % (level + 1) for _ in range(fanout))
|
||
resources = pikepdf.Dictionary(XObject=pikepdf.Dictionary({'/F%d' % (level + 1): forms[0]}))
|
||
else:
|
||
content, resources = b'0 0 1 1 re f\n', pikepdf.Dictionary()
|
||
form = pikepdf.Stream(pdf, content)
|
||
form.Type, form.Subtype, form.BBox, form.Resources = (pikepdf.Name.XObject, pikepdf.Name.Form,
|
||
[0, 0, 1, 1], resources)
|
||
forms.insert(0, pdf.make_indirect(form))
|
||
page = pdf.pages[0]
|
||
page.obj.Resources = pikepdf.Dictionary(XObject=pikepdf.Dictionary({'/F0': forms[0]}))
|
||
page.obj.Contents = pdf.make_indirect(pikepdf.Stream(pdf, b''.join(b'q /F0 Do Q\n' for _ in range(fanout))))
|
||
pdf.save(path)
|
||
|
||
|
||
class HostilePdfTests(unittest.TestCase):
|
||
"""A tiny PDF must not hold the scanner's one thread (security review,
|
||
2026-11-27): it held it for hours, and every upload behind it."""
|
||
|
||
def test_nested_forms_end_unknown_in_seconds(self):
|
||
import time
|
||
with tempfile.NamedTemporaryFile(suffix='.pdf') as handle:
|
||
nested_forms_pdf(handle.name)
|
||
start = time.monotonic()
|
||
self.assertIsNone(grade_check.pdf_dpi(handle.name))
|
||
self.assertLess(time.monotonic() - start, grade_check.PDF_MAX_SECONDS + 2)
|
||
start = time.monotonic()
|
||
self.assertIsNone(grade_check.bounded_pdf_dpi(handle.name))
|
||
self.assertLess(time.monotonic() - start, grade_check.PDF_MAX_SECONDS + 10)
|
||
|
||
def test_a_heavy_vector_page_is_still_read(self):
|
||
# Vector art has many paths and few draws: only draws are counted.
|
||
pdf = pikepdf.new()
|
||
pdf.add_blank_page(page_size=(200, 200))
|
||
pdf.pages[0].obj.Contents = pdf.make_indirect(pikepdf.Stream(pdf, b'0 0 1 1 re f\n' * 200000))
|
||
with tempfile.NamedTemporaryFile(suffix='.pdf') as handle:
|
||
pdf.save(handle.name)
|
||
self.assertEqual(grade_check.pdf_dpi(handle.name), grade_check.PDF_VECTOR_DPI)
|
||
|
||
def test_a_scan_held_on_one_file_is_reported(self):
|
||
from app import scanning
|
||
import time
|
||
self.assertFalse(scanning.stuck())
|
||
with mock.patch.object(scanning, 'busy_since', time.monotonic() - scanning.SCAN_STUCK_SECONDS - 1):
|
||
self.assertTrue(scanning.stuck())
|
||
with mock.patch.object(scanning, 'busy_since', time.monotonic()):
|
||
self.assertFalse(scanning.stuck())
|
||
|
||
|
||
class ProportionTests(unittest.TestCase):
|
||
"""A file laid out at proportions it does not have is refused before
|
||
payment, not found at print time (a 5 m sheet sent as 10 cm)."""
|
||
|
||
def cart(self, length, rotation=0, top=0, bottom=0, name='sheet.png'):
|
||
source = {'upload_id': name, 'kind': 'sheet', 'width_cm': 57, 'length_cm': length,
|
||
'rotation_degrees': rotation, 'trim_top_cm': top, 'trim_bottom_cm': bottom}
|
||
return [{'production': {'sources': [source]}}], {name: {'name': name}}
|
||
|
||
def test_the_files_own_proportions_pass(self):
|
||
files = FakeFiles({'sheet.png': encoded('PNG', (570, 1000)), 'turned.png': encoded('PNG', (1000, 570))})
|
||
for args in ((100,), (90, 0, 4, 6)):
|
||
items, rows = self.cart(*args)
|
||
self.assertIsNone(grade_check.proportion_issue(files, items, rows), args)
|
||
items, rows = self.cart(100, 90, name='turned.png')
|
||
self.assertIsNone(grade_check.proportion_issue(files, items, rows))
|
||
|
||
def test_other_proportions_are_refused(self):
|
||
files = FakeFiles({'sheet.png': encoded('PNG', (570, 50000))})
|
||
items, rows = self.cart(10)
|
||
self.assertIn('não são as proporções', grade_check.proportion_issue(files, items, rows))
|
||
|
||
def test_a_pdf_is_left_to_the_print_file(self):
|
||
files = FakeFiles({})
|
||
items, rows = self.cart(10, name='sheet.pdf')
|
||
self.assertIsNone(grade_check.proportion_issue(files, items, rows))
|
||
|
||
|
||
class SheetWidthTests(unittest.TestCase):
|
||
"""A ready sheet prints at its real size, centred on the film
|
||
(contrato-folha-real.md, Server V1–V5)."""
|
||
|
||
def cart(self, mode, name, width_cm=57, **source):
|
||
source = {'upload_id': name, 'kind': 'sheet', 'width_cm': width_cm,
|
||
'measurement': 'file', **source}
|
||
return [{'mode': mode, 'production': {'sources': [source]}}], {name: {'name': name}}
|
||
|
||
def test_an_unknown_sheet_is_laid_out_at_the_film_width(self):
|
||
# Rule 4: no DPI recorded, the sheet is taken as 57 cm; another width is a stretched layout.
|
||
files = FakeFiles({'sheet.png': encoded('PNG', (6732, 100))})
|
||
items, rows = self.cart('file', 'sheet.png', width_cm=40, size_confirmed=True)
|
||
self.assertIn('foi montada com 40,0 cm, mas tem 57 cm', grade_check.sheet_width_issue(files, items, rows))
|
||
|
||
def test_a_narrow_known_sheet_asks_for_confirmation(self):
|
||
# V3: 4227 px at 300 DPI is 35,8 cm, below the 57 cm film.
|
||
files = FakeFiles({'sheet.png': encoded('PNG', (4227, 100), dpi=(300, 300))})
|
||
items, rows = self.cart('file', 'sheet.png', width_cm=35.79)
|
||
issue = grade_check.sheet_width_issue(files, items, rows)
|
||
self.assertIn('confirme a folha 1 de 35,8 cm no tamanho real', issue)
|
||
|
||
def test_a_confirmed_narrow_sheet_passes(self):
|
||
files = FakeFiles({'sheet.png': encoded('PNG', (4227, 100), dpi=(300, 300))})
|
||
items, rows = self.cart('file', 'sheet.png', width_cm=35.79, size_confirmed=True)
|
||
self.assertIsNone(grade_check.sheet_width_issue(files, items, rows))
|
||
|
||
def test_a_stretched_sheet_must_be_mounted_again(self):
|
||
# V2: the source says 57 cm, the file measures 35,8 cm.
|
||
files = FakeFiles({'sheet.png': encoded('PNG', (4227, 100), dpi=(300, 300))})
|
||
items, rows = self.cart('file', 'sheet.png', width_cm=57)
|
||
issue = grade_check.sheet_width_issue(files, items, rows)
|
||
self.assertIn('foi montada com 57,0 cm, mas tem 35,8 cm', issue)
|
||
|
||
def test_a_sheet_wider_than_the_film_is_refused(self):
|
||
# V1: 7200 px at 300 DPI is 61,0 cm.
|
||
files = FakeFiles({'sheet.png': encoded('PNG', (7200, 100), dpi=(300, 300))})
|
||
items, rows = self.cart('file', 'sheet.png')
|
||
issue = grade_check.sheet_width_issue(files, items, rows)
|
||
self.assertIn('61,0 cm', issue)
|
||
self.assertIn('não cabe', issue)
|
||
|
||
def test_a_sheet_within_tolerance_of_the_film_passes(self):
|
||
# 6732 px at 300 DPI is 56,998 cm: within 0,1 cm of the film, no dialog.
|
||
files = FakeFiles({'sheet.png': encoded('PNG', (6732, 100), dpi=(300, 300))})
|
||
items, rows = self.cart('file', 'sheet.png', width_cm=56.998)
|
||
self.assertIsNone(grade_check.sheet_width_issue(files, items, rows))
|
||
|
||
def test_an_unknown_width_is_taken_as_the_film(self):
|
||
# V5: no pHYs, 6732 px over 57 cm is 300 effective DPI.
|
||
files = FakeFiles({'sheet.png': encoded('PNG', (6732, 100))})
|
||
items, rows = self.cart('file', 'sheet.png')
|
||
issue = grade_check.sheet_width_issue(files, items, rows)
|
||
self.assertIn('confirme a folha 1 de 57 cm antes de pagar', issue)
|
||
items, rows = self.cart('file', 'sheet.png', size_confirmed=True)
|
||
self.assertIsNone(grade_check.sheet_width_issue(files, items, rows))
|
||
|
||
def test_an_unknown_width_under_the_minimum_dpi_is_refused(self):
|
||
# V4: 2154 px over 57 cm is 96 effective DPI.
|
||
files = FakeFiles({'sheet.png': encoded('PNG', (2154, 100))})
|
||
items, rows = self.cart('file', 'sheet.png')
|
||
issue = grade_check.sheet_width_issue(files, items, rows)
|
||
self.assertIn('96 DPI em 57 cm', issue)
|
||
|
||
def test_uv_uses_the_27_cm_film(self):
|
||
# 2362 px at 300 DPI is 20,0 cm on the 27 cm UV film.
|
||
files = FakeFiles({'sheet.png': encoded('PNG', (2362, 100), dpi=(300, 300))})
|
||
items, rows = self.cart('uvfile', 'sheet.png', width_cm=20)
|
||
issue = grade_check.sheet_width_issue(files, items, rows)
|
||
self.assertIn('confirme a folha 1 de 20,0 cm no tamanho real', issue)
|
||
|
||
def test_a_narrow_pdf_asks_for_confirmation(self):
|
||
files = FakeFiles({})
|
||
items, rows = self.cart('file', 'sheet.pdf', width_cm=30)
|
||
issue = grade_check.sheet_width_issue(files, items, rows)
|
||
self.assertIn('confirme a folha 1 de 30,0 cm no tamanho real', issue)
|
||
|
||
def test_a_pdf_wider_than_the_film_is_refused(self):
|
||
files = FakeFiles({})
|
||
items, rows = self.cart('file', 'sheet.pdf', width_cm=60)
|
||
issue = grade_check.sheet_width_issue(files, items, rows)
|
||
self.assertIn('não cabe', issue)
|
||
self.assertIn('60,0 cm', issue)
|
||
|
||
def test_customer_measured_sheets_pass(self):
|
||
files = FakeFiles({'sheet.png': encoded('PNG', (4227, 100), dpi=(300, 300))})
|
||
items, rows = self.cart('file', 'sheet.png', width_cm=35.79, measurement='customer')
|
||
self.assertIsNone(grade_check.sheet_width_issue(files, items, rows))
|
||
|
||
def test_loose_art_is_not_checked(self):
|
||
files = FakeFiles({'sheet.png': encoded('PNG', (4227, 100), dpi=(300, 300))})
|
||
items, rows = self.cart('avulsa', 'sheet.png', width_cm=35.79)
|
||
self.assertIsNone(grade_check.sheet_width_issue(files, items, rows))
|
||
|
||
def test_png_saved_dpi(self):
|
||
head = encoded('PNG', (4227, 100), dpi=(300, 300))
|
||
self.assertEqual(grade_check.png_saved_dpi(head), 300)
|
||
self.assertIsNone(grade_check.png_saved_dpi(encoded('PNG', (4227, 100))))
|
||
self.assertIsNone(grade_check.png_saved_dpi(b'not a png at all'))
|
||
cut = head.index(b'pHYs') + 8 # four of the pHYs data bytes
|
||
self.assertIsNone(grade_check.png_saved_dpi(head[:cut]))
|
||
|
||
|
||
if __name__ == '__main__':
|
||
unittest.main()
|