Coverage for tests/test_docs.py: 95%

64 statements  

« prev     ^ index     » next       coverage.py v7.17.0, created at 2026-11-14 09:29 +0000

1"""Runs the code examples in the README and documentation. 

2 

3Every ```python block in a file is executed, in order, in a namespace shared by 

4the file's blocks (so later examples can use earlier ones). A block that 

5follows an HTML comment like `<!-- file: settings.ini -->` and is not python is 

6written to that file name in a temporary folder before the examples run. 

7 

8A python block that starts with `# skip` is not run. In other blocks, the 

9comment lines right after a `print(...)` statement are the expected output, and 

10the test fails if the block prints something else. 

11""" 

12 

13from __future__ import annotations 

14 

15import contextlib 

16import io 

17import os 

18import pathlib 

19import re 

20import sys 

21import types 

22 

23import pytest 

24 

25ROOT = pathlib.Path(__file__).parent.parent 

26FILES = [ROOT / 'README.md', *sorted((ROOT / 'docs').glob('*.md'))] 

27FILE_BLOCK = re.compile( 

28 r'<!-- file: (?P<name>[\w./-]+) -->\s*```\w*\n(?P<text>.*?)```', re.DOTALL 

29) 

30PYTHON_BLOCK = re.compile(r'```python\n(?P<code>.*?)```', re.DOTALL) 

31 

32 

33def expected_output(code: str) -> list[str]: 

34 """Returns the lines in the comments that follow `print` statements.""" 

35 expected: list[str] = [] 

36 depth = 0 

37 in_print = False 

38 collecting = False 

39 for line in code.splitlines(): 

40 stripped = line.strip() 

41 if in_print or stripped.startswith('print('): 

42 in_print = True 

43 collecting = False 

44 depth += stripped.count('(') - stripped.count(')') 

45 if depth <= 0: 45 ↛ 39line 45 didn't jump to line 39 because the condition on line 45 was always true

46 in_print = False 

47 depth = 0 

48 collecting = True 

49 elif collecting and stripped.startswith('#'): 

50 expected.append(stripped[1:].removeprefix(' ').rstrip()) 

51 else: 

52 collecting = False 

53 return expected 

54 

55 

56def actual_output(text: str) -> list[str]: 

57 """Returns printed lines without trailing blank lines.""" 

58 lines = [line.rstrip() for line in text.splitlines()] 

59 while lines and not lines[-1]: 

60 lines.pop() 

61 return lines 

62 

63 

64# The classes that the examples add to the library are removed after each file 

65# by the `restore_library` fixture in conftest.py. 

66 

67 

68@pytest.mark.parametrize('path', FILES, ids = lambda p: p.name) 

69def test_examples_run( 

70 path: pathlib.Path, 

71 tmp_path: pathlib.Path, 

72 monkeypatch: pytest.MonkeyPatch, 

73) -> None: 

74 text = path.read_text(encoding = 'utf-8') 

75 monkeypatch.chdir(tmp_path) 

76 for match in FILE_BLOCK.finditer(text): 

77 target = tmp_path / match['name'] 

78 target.parent.mkdir(parents = True, exist_ok = True) 

79 target.write_text(match['text'], encoding = 'utf-8') 

80 # The examples run as a real module so that classes defined in them (such 

81 # as dataclasses) can find their module. 

82 module = types.ModuleType(f'docs_{path.stem}') 

83 monkeypatch.setitem(sys.modules, module.__name__, module) 

84 namespace = module.__dict__ 

85 for number, match in enumerate(PYTHON_BLOCK.finditer(text), start = 1): 

86 code = match['code'] 

87 if code.startswith('# skip'): 

88 continue 

89 printed = io.StringIO() 

90 try: 

91 with contextlib.redirect_stdout(printed): 

92 exec( # noqa: S102 

93 compile(code, f'{path.name}[block {number}]', 'exec'), 

94 namespace, 

95 ) 

96 except Exception as error: # noqa: BLE001 

97 message = ( 

98 f'{path.name} block {number} failed with {error!r}:\n{code}' 

99 ) 

100 raise AssertionError(message) from error 

101 expected = expected_output(code) 

102 actual = actual_output(printed.getvalue()) 

103 if expected or actual: 

104 assert actual == expected, ( 

105 f'{path.name} block {number} printed different output than ' 

106 f'its comments say:\n{code}' 

107 ) 

108 assert os.getcwd() == str(tmp_path) # noqa: PTH109