|
| 1 | +# SPDX-License-Identifier: LGPL-3.0-or-later |
| 2 | + |
| 3 | +"""Test that code examples in README.md actually work""" |
| 4 | + |
| 5 | +# pylint does not understand pytest fixtures.. |
| 6 | +# pylint: disable=redefined-outer-name |
| 7 | + |
| 8 | +__author__ = "Martin Pitt" |
| 9 | +__copyright__ = """ |
| 10 | +(c) 2026 Martin Pitt <martin@piware.de> |
| 11 | +""" |
| 12 | + |
| 13 | +import subprocess |
| 14 | +import sys |
| 15 | +from pathlib import Path |
| 16 | + |
| 17 | +import pytest |
| 18 | + |
| 19 | + |
| 20 | +@pytest.fixture(scope="module") |
| 21 | +def readme_blocks(): |
| 22 | + """Extract Python code blocks from README.md""" |
| 23 | + readme_path = Path(__file__).parent.parent / "README.md" |
| 24 | + content = readme_path.read_text() |
| 25 | + blocks = [] |
| 26 | + in_python_block = False |
| 27 | + current_block = [] |
| 28 | + |
| 29 | + for line in content.splitlines(): |
| 30 | + if line.strip() == "```python": |
| 31 | + in_python_block = True |
| 32 | + current_block = [] |
| 33 | + elif line.strip() == "```" and in_python_block: |
| 34 | + in_python_block = False |
| 35 | + if current_block: |
| 36 | + blocks.append("\n".join(current_block)) |
| 37 | + current_block = [] |
| 38 | + elif in_python_block: |
| 39 | + current_block.append(line) |
| 40 | + |
| 41 | + return blocks |
| 42 | + |
| 43 | + |
| 44 | +def test_examples_exist(readme_blocks): |
| 45 | + """Verify that we found some Python code blocks""" |
| 46 | + assert len(readme_blocks) > 0 |
| 47 | + |
| 48 | + |
| 49 | +def test_readme_examples(readme_blocks, tmp_path): |
| 50 | + """Test all README examples by running them through pytest""" |
| 51 | + for i, code_block in enumerate(readme_blocks): |
| 52 | + # Write the code to a temporary file (works in read-only source directories) |
| 53 | + test_file = tmp_path / f"test_readme_example_{i}.py" |
| 54 | + test_file.write_text(code_block) |
| 55 | + |
| 56 | + # Run pytest on the temporary file - will raise CalledProcessError if it fails |
| 57 | + subprocess.run( |
| 58 | + [sys.executable, "-m", "pytest", str(test_file), "-v"], |
| 59 | + check=True, |
| 60 | + ) |
0 commit comments