| 1 | from pathlib import Path |
| 2 | import hashlib |
| 3 | import json |
| 4 | import re |
| 5 | import runpy |
| 6 | import shutil |
| 7 | from tempfile import TemporaryDirectory |
| 8 | import unittest |
| 9 | import xml.etree.ElementTree as ET |
| 10 | |
| 11 | from native_xml import ns |
| 12 | |
| 13 | ROOT = Path(__file__).resolve().parent.parent |
| 14 | FIXTURE = ROOT / 'corpus/attachment-insert' |
| 15 | compare = runpy.run_path(str(ROOT / 'tools/verify-document.py'))['compare'] |
| 16 | |
| 17 | |
| 18 | class AttachmentInsertTest(unittest.TestCase): |
| 19 | def test_files_attached_through_the_editor_open_in_onenote_with_their_bytes(self): |
| 20 | read = FIXTURE / 'cold/read' |
| 21 | with TemporaryDirectory() as temporary: |
| 22 | copy = Path(temporary) / 'read' |
| 23 | shutil.copytree(read, copy) |
| 24 | compare(FIXTURE / 'candidate', copy) |
| 25 | page, = (ET.parse(path).getroot() for path in sorted(read.glob('page-*.xml'))) |
| 26 | paragraphs = [] |
| 27 | for element in page.findall('.//one:OE', ns): |
| 28 | inserted = element.find('one:InsertedFile', ns) |
| 29 | text = element.find('one:T', ns) |
| 30 | paragraphs.append('[%s]' % inserted.get('preferredName') if inserted is not None |
| 31 | else re.sub(r'<[^>]*>', '', text.text or '')) |
| 32 | self.assertEqual(paragraphs, ['Before the file', '[notes 🦀.txt]', 'After the file', '[large.bin]', '']) |
| 33 | # The bytes OneNote hands an application when the file is opened. |
| 34 | payloads = json.loads((read / 'payloads.json').read_text(encoding='utf-8-sig')) |
| 35 | self.assertEqual(sorted(p['bytes'] for p in payloads), [30, 2 << 20]) |
| 36 | for payload in payloads: |
| 37 | data = (read / (payload['sha256'] + '.attachment')).read_bytes() |
| 38 | self.assertEqual(hashlib.sha256(data).hexdigest(), payload['sha256']) |
| 39 | |
| 40 | |
| 41 | if __name__ == '__main__': |
| 42 | unittest.main() |