"""The mml2omml stylesheet is now compiled once and shared between formulas. These tests pin the two properties that makes safe: the output must match a freshly compiled transform, and reusing the compiled object must not let one formula affect the next. """ import os import unittest import latex2mathml.converter from lxml import etree from md2gost import package_dir from md2gost.latex_math import latex_to_omml _FORMULAS = [ "x^2 + y^2 = z^2", r"\frac{a}{b}", r"\frac{a + b}{c + d}", r"\sum_{i=1}^{n} i", r"\sqrt{x+1}", r"\int_0^1 f(x)dx", r"\alpha \beta \gamma", r"E = mc^2", ] def _freshly_compiled(latex_equation: str) -> bytes: """Pre-optimization behaviour: parse and compile the stylesheet per call.""" mathml = latex2mathml.converter.convert(latex_equation) tree = etree.fromstring(mathml) transform = etree.XSLT(etree.parse(os.path.join(package_dir(), "mml2omml"))) return etree.tostring(transform(tree).getroot()) class TestLatexToOmml(unittest.TestCase): def test_matches_freshly_compiled_transform(self): for formula in _FORMULAS: with self.subTest(formula=formula): self.assertEqual(_freshly_compiled(formula), etree.tostring(latex_to_omml(formula))) def test_repeated_calls_are_identical(self): for formula in _FORMULAS: with self.subTest(formula=formula): outputs = {etree.tostring(latex_to_omml(formula)) for _ in range(5)} self.assertEqual(1, len(outputs)) def test_interleaved_formulas_do_not_interfere(self): expected = {f: etree.tostring(latex_to_omml(f)) for f in _FORMULAS} for _ in range(3): for formula in reversed(_FORMULAS): self.assertEqual(expected[formula], etree.tostring(latex_to_omml(formula))) def test_invalid_formula_still_raises_value_error(self): with self.assertRaises(ValueError): latex_to_omml(r"\frac{") if __name__ == "__main__": unittest.main()