"""Shared fixtures: build .docx files in a temp dir rather than committing binaries, so the OMML each test exercises is visible in the test that needs it. """ import io import sys from pathlib import Path import pytest from lxml import etree sys.path.insert(0, str(Path(__file__).resolve().parent.parent / 'backend')) M_NS = 'http://schemas.openxmlformats.org/officeDocument/2006/math' @pytest.fixture(scope='session') def app_mod(): import app return app def mrun(text): """An OMML text run.""" return f'{text}' def omath(inner): """Wrap OMML fragments in the element Word puts in a paragraph.""" return etree.fromstring( f'{inner}') # ── OMML fragments, written the way Word itself writes them ────────────────── # A square root: Word marks the (empty) degree hidden rather than omitting it, # which is what makes the stylesheet emit instead of an empty . SQRT_2GH = (f'' f'{mrun("2gh")}') B_SQUARED = f'{mrun("b")}{mrun("2")}' H2O = f'{mrun("H")}{mrun("2")}{mrun("O")}' HALF = f'{mrun("1")}{mrun("2")}' # Word's "boxed formula" and its diagonal-strike (cancel) variant. BOXED = (f'' f'{mrun("E=mc")}') CANCELLED = (f'' f'{mrun("x")}') @pytest.fixture def png_bytes(): """A small but genuine PNG.""" from PIL import Image im = Image.new('RGB', (120, 60), 'white') buf = io.BytesIO() im.save(buf, 'PNG') return buf.getvalue() @pytest.fixture def make_docx(tmp_path): """build([...]) -> path to a .docx. Each item is either a string (a plain paragraph) or a list of parts: strings, ('math', omml_str) or ('img', bytes). """ from docx import Document from docx.shared import Inches counter = {'n': 0} def build(items): doc = Document() for item in items: if isinstance(item, str): doc.add_paragraph(item) continue p = doc.add_paragraph() for part in item: if isinstance(part, str): p.add_run(part) elif part[0] == 'math': p._p.append(omath(part[1])) elif part[0] == 'img': p.add_run().add_picture(io.BytesIO(part[1]), width=Inches(1.5)) counter['n'] += 1 out = tmp_path / f'q{counter["n"]}.docx' doc.save(str(out)) return str(out) return build @pytest.fixture def no_omml_stylesheet(app_mod, monkeypatch): """Simulate the Docker image: no Office, so OMML2MML.XSL is nowhere to be found.""" monkeypatch.setattr(app_mod, 'OMML2MML_PATHS', [r'C:\nonexistent\OMML2MML.XSL']) monkeypatch.setattr(app_mod, '_omml2mml', None) yield app_mod._omml2mml = None @pytest.fixture(autouse=True) def _reset_stylesheet_cache(app_mod): """get_omml2mml() memoises into a module global; keep tests independent.""" yield app_mod._omml2mml = None