|
| 1 | +"""Shared helpers for tutorial-drift tests (T20, T21, ...). |
| 2 | +
|
| 3 | +The HAD tutorial drift tests pin numbers / verdict strings against the |
| 4 | +locked DGP + seed. Without these helpers each drift test re-derived |
| 5 | +numbers but never verified that the rendered notebook surface (markdown |
| 6 | +prose + executed output cells) actually quotes those values. Because |
| 7 | +``nbsphinx_execute = "never"`` in ``docs/conf.py``, CI cannot detect |
| 8 | +drift between the pinned constants and the committed tutorial via |
| 9 | +notebook re-execution; the constants and the notebook can diverge |
| 10 | +silently. These helpers parse the .ipynb JSON directly so each |
| 11 | +tutorial-drift test file can cross-check its pins against the |
| 12 | +rendered surface it claims to protect. |
| 13 | +""" |
| 14 | + |
| 15 | +from __future__ import annotations |
| 16 | + |
| 17 | +import json |
| 18 | +from pathlib import Path |
| 19 | +from typing import Iterable |
| 20 | + |
| 21 | + |
| 22 | +def _read_notebook(nb_relpath: str) -> dict: |
| 23 | + """Load a notebook by repo-relative path (e.g. ``docs/tutorials/X.ipynb``). |
| 24 | +
|
| 25 | + Skips the calling test via ``pytest.skip(...)`` when the notebook file |
| 26 | + is not present. The Rust-test CI job (and the isolated-install job) |
| 27 | + copies only ``tests/`` to ``/tmp/tests`` and runs from there, without |
| 28 | + ``docs/`` available. The repo convention is to skip cleanly when |
| 29 | + artifacts are absent rather than fail (see e.g. |
| 30 | + ``tests/test_notebook_md_extract.py`` and ``tests/test_nprobust_port.py``). |
| 31 | + """ |
| 32 | + import pytest |
| 33 | + |
| 34 | + nb_path = Path(__file__).resolve().parents[1] / nb_relpath |
| 35 | + if not nb_path.exists(): |
| 36 | + pytest.skip( |
| 37 | + f"Notebook {nb_relpath!r} not available in this CI environment " |
| 38 | + "(isolated-install job copies only tests/, not docs/); " |
| 39 | + "rendered-surface cross-check requires a full repo checkout." |
| 40 | + ) |
| 41 | + return json.loads(nb_path.read_text()) |
| 42 | + |
| 43 | + |
| 44 | +def notebook_markdown(nb_relpath: str) -> str: |
| 45 | + """Return all markdown cells concatenated into one string.""" |
| 46 | + nb = _read_notebook(nb_relpath) |
| 47 | + parts = [] |
| 48 | + for cell in nb["cells"]: |
| 49 | + if cell["cell_type"] != "markdown": |
| 50 | + continue |
| 51 | + src = cell["source"] |
| 52 | + if isinstance(src, list): |
| 53 | + src = "".join(src) |
| 54 | + parts.append(src) |
| 55 | + return "\n".join(parts) |
| 56 | + |
| 57 | + |
| 58 | +def notebook_output_text(nb_relpath: str) -> str: |
| 59 | + """Return all executed-output text (``stream`` and ``execute_result`` |
| 60 | + text/plain) from every code cell, concatenated. |
| 61 | +
|
| 62 | + Covers the rendered numeric surface that markdown alone misses — |
| 63 | + e.g. printed verdict strings, formatted summary tables, p-values. |
| 64 | + """ |
| 65 | + nb = _read_notebook(nb_relpath) |
| 66 | + parts = [] |
| 67 | + for cell in nb["cells"]: |
| 68 | + if cell["cell_type"] != "code": |
| 69 | + continue |
| 70 | + for out in cell.get("outputs", []): |
| 71 | + # stream-style outputs (print / stdout / stderr) |
| 72 | + text = out.get("text") |
| 73 | + if text is not None: |
| 74 | + parts.append("".join(text) if isinstance(text, list) else text) |
| 75 | + # execute_result / display_data with text/plain |
| 76 | + data = out.get("data") or {} |
| 77 | + plain = data.get("text/plain") |
| 78 | + if plain is not None: |
| 79 | + parts.append("".join(plain) if isinstance(plain, list) else plain) |
| 80 | + return "\n".join(parts) |
| 81 | + |
| 82 | + |
| 83 | +def notebook_rendered_text(nb_relpath: str) -> str: |
| 84 | + """Return markdown + executed-output text together — the full |
| 85 | + rendered surface a reader sees on RTD.""" |
| 86 | + return notebook_markdown(nb_relpath) + "\n" + notebook_output_text(nb_relpath) |
| 87 | + |
| 88 | + |
| 89 | +def assert_quotes_in_rendered( |
| 90 | + nb_relpath: str, |
| 91 | + expected_quotes: Iterable[str], |
| 92 | + *, |
| 93 | + surface: str = "rendered", |
| 94 | +) -> None: |
| 95 | + """Assert each expected substring appears in the chosen rendered surface. |
| 96 | +
|
| 97 | + Parameters |
| 98 | + ---------- |
| 99 | + nb_relpath |
| 100 | + Notebook path relative to repo root (e.g. |
| 101 | + ``"docs/tutorials/21_had_pretest_workflow.ipynb"``). |
| 102 | + expected_quotes |
| 103 | + Iterable of substrings that MUST appear in the chosen rendered |
| 104 | + surface. Each is checked independently; the assertion message |
| 105 | + lists every missing quote so a single failure surfaces all of |
| 106 | + them. |
| 107 | + surface |
| 108 | + Which slice of the notebook to check: ``"markdown"`` (prose |
| 109 | + only), ``"output"`` (executed output cells only), or |
| 110 | + ``"rendered"`` (both — default; matches what a reader sees |
| 111 | + on RTD). |
| 112 | + """ |
| 113 | + if surface == "markdown": |
| 114 | + text = notebook_markdown(nb_relpath) |
| 115 | + elif surface == "output": |
| 116 | + text = notebook_output_text(nb_relpath) |
| 117 | + elif surface == "rendered": |
| 118 | + text = notebook_rendered_text(nb_relpath) |
| 119 | + else: |
| 120 | + raise ValueError(f"surface must be 'markdown' / 'output' / 'rendered'; got {surface!r}") |
| 121 | + missing = [q for q in expected_quotes if q not in text] |
| 122 | + assert not missing, ( |
| 123 | + f"Tutorial {nb_relpath!r} ({surface=}) is missing load-bearing " |
| 124 | + f"quoted values that the pinned drift constants assume are " |
| 125 | + f"rendered verbatim. Either the notebook drifted from the " |
| 126 | + f"locked DGP output (rerun the tutorial against the pinned " |
| 127 | + f"seed) or the drift-test constants were updated without " |
| 128 | + f"updating the tutorial. Missing: {missing}" |
| 129 | + ) |
0 commit comments