Coverage for tests/test_docs.py: 100%
39 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-10-30 23:02 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-10-30 23:02 +0000
1"""Tests that the python examples in the documentation run without error."""
3from __future__ import annotations
5import pathlib
6import re
7import sys
8import types
10import pytest
12DOCS = pathlib.Path(__file__).parents[1] / 'docs'
15@pytest.mark.parametrize('name', ['tutorial', 'advanced', 'recipes'])
16def test_doc_examples_run(name: str) -> None:
17 """Executes all of the python code blocks of a documentation page.
19 Args:
20 name: name of the documentation page.
22 """
23 text = (DOCS / f'{name}.md').read_text(encoding = 'utf-8')
24 blocks = re.findall(r'```python\n(.*?)```', text, flags = re.DOTALL)
25 assert blocks
26 module = types.ModuleType(f'docs_{name}')
27 sys.modules[module.__name__] = module
28 try:
29 for block in blocks:
30 code = compile(block, f'{name}.md', 'exec')
31 exec(code, module.__dict__) # noqa: S102
32 finally:
33 del sys.modules[module.__name__]
36def test_documented_results() -> None:
37 """Checks a few of the results quoted in the documentation comments."""
38 from dataclasses import dataclass
40 from bunches import Catalog, ChainDict, DictList, Dictionary, Listing
42 colors = Dictionary({'red': 1, 'green': 2}, default_factory = 0)
43 colors.add({'blue': 3})
44 assert colors.get('purple') == 0
45 assert colors.keys() == ('red', 'green', 'blue')
46 catalog = Catalog({'tree': 'DecisionTree', 'forest': 'RandomForest'})
47 catalog.default = 'forest'
48 assert catalog['default'] == 'RandomForest'
49 settings = ChainDict([
50 Dictionary({'debug': True}),
51 Dictionary({'debug': False, 'name': 'app'})])
52 settings.return_first = False
53 assert settings['debug'] == [True, False]
54 assert Listing([1, 2, 3]).subset(exclude = 2, returns = 'simple') == [1, 3]
56 @dataclass
57 class Step:
58 name: str
60 pipeline = DictList([Step('load'), Step('clean'), Step('save')])
61 pipeline.insert(1, Step('validate'))
62 assert pipeline.keys() == ('load', 'validate', 'clean', 'save')