import tempfile import unittest from pathlib import Path import pymupdf from copienator.crop_exercise_bottoms import process_exercise_pdf class CropExerciseBottomsTests(unittest.TestCase): def setUp(self): self.temp = tempfile.TemporaryDirectory() self.addCleanup(self.temp.cleanup) self.root = Path(self.temp.name) self.review = self.root / "review" def make_pdf(self, name: str, height: float, text_y: float, footer=True) -> Path: path = self.root / name with pymupdf.open() as document: page = document.new_page(width=600, height=height) page.insert_text((80, text_y), "student answer", fontsize=16) if footer: page.insert_text((20, height - 15), "9/9", fontsize=10) document.save(path) return path def test_short_page_is_skipped(self): source = self.make_pdf("short.pdf", 200, 100) destination = self.root / "out" / source.name records = process_exercise_pdf( source, destination, self.review, 800, dpi=150 ) self.assertEqual(records[0]["status"], "skipped-short") self.assertFalse(destination.exists()) def test_isolated_page_number_allows_a_large_bottom_crop(self): source = self.make_pdf("large.pdf", 400, 100) destination = self.root / "out" / source.name records = process_exercise_pdf( source, destination, self.review, 800, dpi=150 ) self.assertEqual(records[0]["status"], "cropped") self.assertGreaterEqual(records[0]["bottom_removed_lines"], 4) with pymupdf.open(destination) as result: self.assertLess(result[0].rect.height, 250) self.assertAlmostEqual(result[0].rect.width, 600) def test_content_in_former_ignored_bottom_strip_is_retained(self): source = self.make_pdf("bottom-content.pdf", 400, 100, footer=False) with pymupdf.open(source) as doc: doc[0].insert_text((20, 399), "Ex 2", fontsize=10) doc.save(self.root / "bottom-label.pdf") records = process_exercise_pdf( self.root / "bottom-label.pdf", self.root / "retained.pdf", self.review, 800, dpi=150 ) self.assertEqual(records[0]["status"], "unchanged-small-crop") self.assertFalse((self.root / "retained.pdf").exists()) def test_crop_smaller_than_four_lines_is_not_written(self): source = self.make_pdf("small.pdf", 400, 330, footer=False) destination = self.root / "out" / source.name records = process_exercise_pdf( source, destination, self.review, 800, dpi=150 ) self.assertEqual(records[0]["status"], "unchanged-small-crop") self.assertFalse(destination.exists()) if __name__ == "__main__": unittest.main()