import contextlib import io from pathlib import Path import tempfile import unittest from unittest.mock import patch from tools import exporter class ExporterTests(unittest.TestCase): def setUp(self): self.temp = tempfile.TemporaryDirectory() self.addCleanup(self.temp.cleanup) self.root = Path(self.temp.name) def invoke(self, *args): with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()): return exporter.main(list(map(str, args))) def test_pdf_noop_needs_no_tool_and_creates_nothing(self): source = self.root / 'input.PDF' source.write_bytes(b'%PDF-1.7') with patch.object(exporter, 'find_cli', side_effect=AssertionError('must not load a tool')): self.assertEqual(self.invoke(source, '--output', 'pdf'), 0) self.assertEqual(list(self.root.iterdir()), [source]) def test_rejects_unknown_input_and_output(self): for name, format in [('input.txt', 'pdf'), ('input.pdf', 'html'), ('input.pdf', 'pdf,')]: with self.subTest(name=name, format=format), self.assertRaises(SystemExit) as error: self.invoke(self.root / name, '--output', format) self.assertEqual(error.exception.code, 2) def test_failure_does_not_publish_partial_output(self): source = self.root / 'input.pptx' source.touch() destination = self.root / 'output' def fake_run(command, **kwargs): if command[1] == 'convert': Path(command[-1]).write_bytes(b'%PDF-1.7') return '' raise RuntimeError('render failed') with patch.object(exporter, 'find_cli', return_value=Path('/fake/cli')), patch.object(exporter, 'run', side_effect=fake_run): self.assertEqual(self.invoke(source, '--output', 'pdf,images', '-d', destination), 1) self.assertFalse(destination.exists()) def test_pdf_render_uses_one_based_pages_and_requested_dpi(self): source = self.root / 'input.pdf' source.touch() destination = self.root / 'output' commands = [] def fake_run(command, **kwargs): commands.append(command) if command[1] == 'info': return '{"pages": 2}' Path(command[-1]).write_bytes(b'image') return '' with patch.object(exporter, 'find_cli', return_value=Path('/fake/cli')), patch.object(exporter, 'run', side_effect=fake_run): self.assertEqual(self.invoke(source, '--output', 'pdf,images', '--dpi', 192, '-d', destination), 0) self.assertEqual([command[4] for command in commands[1:]], ['1', '2']) self.assertTrue(all(command[6] == '192' for command in commands[1:])) self.assertEqual(sorted(path.name for path in (destination / 'images').iterdir()), ['page-0001.png', 'page-0002.png']) self.assertFalse((destination / 'input.pdf').exists()) def test_invalid_page_count_does_not_publish(self): source = self.root / 'input.pdf' source.touch() for pages in ('0', '-1', 'null', '"2"', 'true'): with self.subTest(pages=pages), \ patch.object(exporter, 'find_cli', return_value=Path('/fake/cli')), \ patch.object(exporter, 'run', return_value='{"pages": ' + pages + '}'): self.assertEqual(self.invoke(source, '--output', 'images'), 1) self.assertFalse((self.root / 'input_export').exists()) def test_missing_cli_does_not_create_output(self): source = self.root / 'input.pptx' source.touch() with patch.object(exporter, 'find_cli', side_effect=RuntimeError('CLI missing')): self.assertEqual(self.invoke(source, '--output', 'pdf'), 1) self.assertFalse((self.root / 'input_export').exists()) def test_overwrite_removes_stale_pages_but_preserves_other_files(self): source = self.root / 'input.pdf' source.touch() destination = self.root / 'output' images = destination / 'images' images.mkdir(parents=True) (images / 'page-0002.png').write_bytes(b'old') (images / 'notes.txt').write_text('keep me') def fake_run(command, **kwargs): if command[1] == 'info': return '{"pages": 1}' Path(command[-1]).write_bytes(b'new image') return '' with patch.object(exporter, 'find_cli', return_value=Path('/fake/cli')), patch.object(exporter, 'run', side_effect=fake_run): self.assertEqual(self.invoke(source, '--output', 'images', '-d', destination), 1) self.assertEqual(self.invoke(source, '--output', 'images', '-d', destination, '--overwrite'), 0) self.assertEqual((images / 'notes.txt').read_text(), 'keep me') self.assertFalse((images / 'page-0002.png').exists()) self.assertEqual((images / 'page-0001.png').read_bytes(), b'new image') def compressor(self, sizes, commands): sizes = iter(sizes) def fake_run(command, **kwargs): commands.append(command) output = next(arg.split('=', 1)[1] for arg in command if str(arg).startswith('-sOutputFile=')) Path(output).write_bytes(b'x' * next(sizes)) return '' return fake_run def test_target_retries_original_and_stops_below_limit(self): source = self.root / 'input.pdf' source.write_bytes(b'x' * 2000) commands = [] with patch.object(exporter.shutil, 'which', return_value='/fake/gs'), \ patch.object(exporter, 'find_cli', side_effect=AssertionError('PDF compression needs no craft CLI')), \ patch.object(exporter, 'run', side_effect=self.compressor([1500, 1000, 900], commands)): self.assertEqual(self.invoke(source, '--output', 'pdf', '--target-size', '1KB'), 0) self.assertEqual(len(commands), 3) # equal to target is not below it self.assertTrue(all(command[-1] == source for command in commands)) self.assertIn('-dColorImageResolution=300', commands[0]) self.assertIn('-dColorImageResolution=120', commands[-1]) self.assertEqual((self.root / 'input_export/input.pdf').stat().st_size, 900) self.assertEqual(source.stat().st_size, 2000) def test_target_compression_updates_progress_for_each_attempt(self): source = self.root / 'input.pdf' source.write_bytes(b'x' * 2000) bar = unittest.mock.Mock() with contextlib.redirect_stdout(io.StringIO()), \ patch.object(exporter.shutil, 'which', return_value='/fake/gs'), \ patch.object(exporter, 'run', side_effect=self.compressor([1500, 900], [])): result, selected_dpi = exporter.compress_pdf(source, self.root, 'email', 1000, bar) self.assertEqual(result.stat().st_size, 900) self.assertEqual(selected_dpi, 120) self.assertEqual(bar.set.call_args_list, [unittest.mock.call(0, 6), unittest.mock.call(1), unittest.mock.call(2)]) def test_unreachable_target_is_bounded_and_preserves_existing_output(self): source = self.root / 'input.pdf' source.write_bytes(b'x' * 2000) output = self.root / 'input_export' output.mkdir() (output / 'input.pdf').write_bytes(b'keep') commands = [] with patch.object(exporter.shutil, 'which', return_value='/fake/gs'), \ patch.object(exporter, 'run', side_effect=self.compressor([1500] * 7, commands)): self.assertEqual(self.invoke(source, '--output', 'pdf', '--target-size', '100B', '--overwrite'), 1) self.assertEqual(len(commands), 7) self.assertEqual((output / 'input.pdf').read_bytes(), b'keep') def test_email_quality_keeps_original_if_compression_grows_file(self): source = self.root / 'input.pdf' source.write_bytes(b'x' * 1000) commands = [] with patch.object(exporter.shutil, 'which', return_value='/fake/gs'), \ patch.object(exporter, 'run', side_effect=self.compressor([1500], commands)): self.assertEqual(self.invoke(source, '--output', 'pdf', '--pdf-quality', 'email', '--dpi', '24'), 0) self.assertEqual(len(commands), 1) self.assertIn('-dColorImageResolution=150', commands[0]) self.assertEqual((self.root / 'input_export/input.pdf').read_bytes(), source.read_bytes()) def test_exact_pdf_dpi_is_reusable_and_reported(self): source = self.root / 'input.pdf' source.write_bytes(b'x' * 1000) commands = [] output = io.StringIO() with contextlib.redirect_stdout(output), contextlib.redirect_stderr(io.StringIO()), \ patch.object(exporter.shutil, 'which', return_value='/fake/gs'), \ patch.object(exporter, 'run', side_effect=self.compressor([500], commands)): self.assertEqual(exporter.main([str(source), '--output', 'pdf', '--pdf-dpi', '120']), 0) self.assertIn('-dColorImageResolution=120', commands[0]) self.assertIn('120 DPI images; reuse with --pdf-dpi 120', output.getvalue()) def test_already_below_target_needs_no_compressor(self): source = self.root / 'input.pdf' source.write_bytes(b'pdf') with patch.object(exporter.shutil, 'which', side_effect=AssertionError('no tool needed')): self.assertEqual(self.invoke(source, '--output', 'pdf', '--target-size', '1MB'), 0) self.assertEqual((self.root / 'input_export/input.pdf').read_bytes(), b'pdf') def test_missing_compressor_and_failed_pass_publish_nothing(self): source = self.root / 'input.pdf' source.write_bytes(b'pdf') with patch.object(exporter.shutil, 'which', return_value=None): self.assertEqual(self.invoke(source, '--output', 'pdf', '--pdf-quality', 'email'), 1) with patch.object(exporter.shutil, 'which', return_value='/fake/gs'), \ patch.object(exporter, 'run', side_effect=RuntimeError('compression failed')): self.assertEqual(self.invoke(source, '--output', 'pdf', '--pdf-quality', 'email'), 1) self.assertFalse((self.root / 'input_export').exists()) def test_help_lists_ghostscript_package_and_install_commands(self): output = io.StringIO() with contextlib.redirect_stdout(output), self.assertRaises(SystemExit) as error: exporter.main(['--help']) self.assertEqual(error.exception.code, 0) help_text = output.getvalue() self.assertIn('ghostscript` package', help_text) self.assertIn('sudo apt install ghostscript', help_text) self.assertIn('sudo dnf install ghostscript', help_text) self.assertIn('sudo pacman -S ghostscript', help_text) self.assertIn('sudo zypper install ghostscript', help_text) self.assertIn('sudo apk add ghostscript', help_text) def test_size_units_and_pdf_option_validation(self): self.assertEqual(exporter.byte_size('2.5MB'), 2500000) self.assertEqual(exporter.byte_size('2MiB'), 2097152) self.assertEqual(exporter.byte_size('100'), 100) for args in [('--target-size', '0'), ('--target-size', '-2MB'), ('--target-size', 'NaN'), ('--target-size', '5TB'), ('--target-size', '2MB'), ('--pdf-quality', 'email'), ('--pdf-dpi', '120')]: with self.subTest(args=args), self.assertRaises(SystemExit) as error: self.invoke(self.root / 'input.pdf', '--output', 'images', *args) self.assertEqual(error.exception.code, 2) with self.assertRaises(SystemExit) as error: self.invoke(self.root / 'input.pdf', '--output', 'pdf', '--pdf-quality', 'email', '--pdf-dpi', '120') self.assertEqual(error.exception.code, 2) def test_pptx_compresses_after_convert(self): source = self.root / 'input.pptx' source.touch() commands = [] compress = self.compressor([500], commands) def fake_run(command, **kwargs): if command[1] == 'convert': Path(command[-1]).write_bytes(b'x' * 1000) return '' self.assertEqual(Path(command[-1]).name, 'export.pdf') return compress(command) with patch.object(exporter.shutil, 'which', return_value='/fake/gs'), \ patch.object(exporter, 'find_cli', return_value=Path('/fake/cli')), \ patch.object(exporter, 'run', side_effect=fake_run): self.assertEqual(self.invoke(source, '--output', 'pdf', '--pdf-quality', 'email'), 0) self.assertEqual((self.root / 'input_export/input.pdf').stat().st_size, 500) if __name__ == '__main__': unittest.main()