1from pathlib import Path
2import hashlib
3import json
4import re
5import runpy
6import shutil
7from tempfile import TemporaryDirectory
8import unittest
9import xml.etree.ElementTree as ET
10
11from native_xml import ns
12
13ROOT = Path(__file__).resolve().parent.parent
14FIXTURE = ROOT / 'corpus/attachment-insert'
15compare = runpy.run_path(str(ROOT / 'tools/verify-document.py'))['compare']
16
17
18class 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
41if __name__ == '__main__':
42 unittest.main()