#!/usr/bin/env python3
"""Exact bbox decoding tests; no lossy XML recovery or text normalization."""
from pathlib import Path
import runpy
import unittest
import xml.etree.ElementTree as ET
ROOT = Path(__file__).resolve().parents[1]
parse = runpy.run_path(str(ROOT / "scripts/check-native-paragraphs.py"))["parse_bbox"]
compare = runpy.run_path(str(ROOT / "scripts/check-native-format-articles.py"))["compare_words"]
def bbox(text):
return ('
'
'' + text +
'').encode("utf-8")
class ExactBbox(unittest.TestCase):
def test_control_noncharacter_astral_and_collision_like_strings_are_retained(self):
text = ''.join(map(chr, range(32))) + '\u007f\u0080\ue000\ue001\ufffe\U0001f600%CONTROL0012%'
self.assertEqual(parse(bbox(text))[0][0][0], text)
def test_entities_are_decoded_once_and_numeric_controls_are_retained(self):
self.assertEqual(parse(bbox('<>"'😀'))[0][0][0],
'<>"\'\x12\x13\ue000\U0001f600')
def test_valid_xml_retains_the_previous_coordinates_and_text(self):
data = bbox('A & B 😀')
expected = [(node.text, {key: float(value) for key, value in node.attrib.items()})
for node in ET.fromstring(data).iter() if node.tag.endswith('}word')]
self.assertEqual(parse(data), [expected])
def test_malformed_structure_and_entities_still_fail(self):
for text in ['&unknown;', '&', '', 'a & b', '', '']:
with self.subTest(text=text), self.assertRaises(ET.ParseError):
parse(bbox(text))
with self.assertRaises(ET.ParseError):
parse(bbox('okay').replace(b'', b'\x12'))
def test_characters_and_order_remain_mandatory(self):
for actual, expected in [('(', '\x12'), ('\x12', '\x13'), ('\x12\x13', '\x13\x12'),
('A', 'A\x00'), ('\ue000', '\ue001')]:
self.assertFalse(compare(parse(bbox(actual)), parse(bbox(expected)), .02)['passed'])
def test_a2_delimiter_character_and_word_order_difference_still_fails(self):
# The original failure had two separately positioned delimiter words.
def pair(left, right):
return bbox(left).replace(b'', ('' +
right + '').encode('utf-8'), 1)
actual = parse(pair('(', ')'))
expected = parse(pair('\x13', '\x12'))
self.assertFalse(compare(actual, expected, .02)['passed'])
self.assertEqual([text for text, _ in actual[0] if text in ['(', ')', '\x12', '\x13']], ['(', ')'])
self.assertEqual([text for text, _ in expected[0] if text in ['(', ')', '\x12', '\x13']], ['\x13', '\x12'])
if __name__ == '__main__':
unittest.main()