Files
dtf-system/tests/test_grade_check.py
Cauê Faleiros 5aafd9ee91
All checks were successful
Build and deploy / Publish images (push) Successful in 1m5s
Build and deploy / Validate source (push) Successful in 5s
Build and deploy / Integration suite on a real stack (push) Successful in 5m7s
Build and deploy / Secret scan and release gate (push) Successful in 6s
fix: review of phase-2 stage 0 and fronts 5, 6 and 11
- A paid treatment adds its 24 h to Arte recebida's acceptable time, on
  the card and in Números (fronts 5 and 11).
- TINY_PRODUCT_TREATMENT is a required Tiny setting once the treatment
  has a price, instead of every treated order failing at the Tiny.
- A quote reads each PDF once: Files caches the header and the DPI.
- A proof made from the parent's final split into parts uses the part
  that holds the finest stroke, not the last one (0.1).
- Prumo report: one format line per item, the time from the claim (kept
  on the finished print file), and the stroke class in customer words.
- The Site says the Prumo checks the art, and a too-tall PNG no longer
  says "Este PDF".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 10:45:43 -03:00

138 lines
6.2 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, '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_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)
if __name__ == '__main__':
unittest.main()