74 lines
3.0 KiB
Python
74 lines
3.0 KiB
Python
import contextlib
|
|
import io
|
|
from pathlib import Path
|
|
import tempfile
|
|
import unittest
|
|
from unittest.mock import patch
|
|
|
|
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_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')
|
|
|
|
|
|
if __name__ == '__main__':
|
|
unittest.main()
|