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

1"""Tests that the python examples in the documentation run without error.""" 

2 

3from __future__ import annotations 

4 

5import pathlib 

6import re 

7import sys 

8import types 

9 

10import pytest 

11 

12DOCS = pathlib.Path(__file__).parents[1] / 'docs' 

13 

14 

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. 

18 

19 Args: 

20 name: name of the documentation page. 

21 

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__] 

34 

35 

36def test_documented_results() -> None: 

37 """Checks a few of the results quoted in the documentation comments.""" 

38 from dataclasses import dataclass 

39 

40 from bunches import Catalog, ChainDict, DictList, Dictionary, Listing 

41 

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] 

55 

56 @dataclass 

57 class Step: 

58 name: str 

59 

60 pipeline = DictList([Step('load'), Step('clean'), Step('save')]) 

61 pipeline.insert(1, Step('validate')) 

62 assert pipeline.keys() == ('load', 'validate', 'clean', 'save')