| 1 | import json |
| 2 | from pathlib import Path |
| 3 | import runpy |
| 4 | import shutil |
| 5 | from tempfile import TemporaryDirectory |
| 6 | import unittest |
| 7 | import xml.etree.ElementTree as ET |
| 8 | |
| 9 | from native_format import native_characters |
| 10 | from native_xml import ns |
| 11 | |
| 12 | ROOT = Path(__file__).resolve().parent.parent |
| 13 | FIXTURE = ROOT / 'corpus/formatted-insertion' |
| 14 | compare = runpy.run_path(str(ROOT / 'tools/verify-document.py'))['compare'] |
| 15 | |
| 16 | |
| 17 | class FormattedInsertionTest(unittest.TestCase): |
| 18 | def test_cold_native_content_and_formatting(self): |
| 19 | manifest = json.loads((FIXTURE / 'manifest.json').read_text()) |
| 20 | for case in manifest['cases']: |
| 21 | with self.subTest(case=case['name']), TemporaryDirectory() as temporary: |
| 22 | fixture = FIXTURE / case['name'] |
| 23 | native = Path(temporary) / 'read' |
| 24 | shutil.copytree(fixture / 'cold/read', native) |
| 25 | compare(fixture / 'candidate', native) |
| 26 | with TemporaryDirectory() as temporary: |
| 27 | fixture = FIXTURE / 'empty/typed-after-cold' |
| 28 | native = Path(temporary) / 'read' |
| 29 | shutil.copytree(fixture / 'read', native) |
| 30 | compare(fixture / 'candidate', native) |
| 31 | |
| 32 | def test_native_edits_preserve_the_observed_character_styles(self): |
| 33 | manifest = json.loads((FIXTURE / 'manifest.json').read_text()) |
| 34 | for case in manifest['cases']: |
| 35 | for variant, before_file, prefix in [('reverse', 'edit-before.xml', 'Native '), |
| 36 | ('ui', 'before-read/page-000.xml', 'UI ')]: |
| 37 | if variant + '_sha256' not in case: |
| 38 | continue |
| 39 | with self.subTest(case=case['name'], variant=variant), TemporaryDirectory() as temporary: |
| 40 | fixture = FIXTURE / case['name'] / variant |
| 41 | native = Path(temporary) / 'read' |
| 42 | shutil.copytree(fixture / 'read', native) |
| 43 | compare(fixture / 'notebook', native) |
| 44 | before = ET.parse(fixture / before_file).getroot() |
| 45 | after = ET.parse(native / 'page-000.xml').getroot() |
| 46 | expected = native_characters(before, before.findall('one:Outline', ns)) |
| 47 | changed = 0 |
| 48 | for index, paragraph in enumerate(expected): |
| 49 | if ''.join(char for char, _ in paragraph).startswith(('Bold ', 'Typed ')): |
| 50 | expected[index] = [(char, paragraph[0][1]) for char in prefix] + paragraph |
| 51 | changed += 1 |
| 52 | self.assertEqual(changed, 1) |
| 53 | self.assertEqual(native_characters(after, after.findall('one:Outline', ns)), expected) |
| 54 | |
| 55 | |
| 56 | if __name__ == '__main__': |
| 57 | unittest.main() |