swarmauri_tests_readme_examples 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [2025] [Jacob Stewart @ Swarmauri]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,120 @@
1
+ Metadata-Version: 2.4
2
+ Name: swarmauri_tests_readme_examples
3
+ Version: 0.1.0
4
+ Summary: Pytest plugin that executes README code examples.
5
+ License-Expression: Apache-2.0
6
+ License-File: LICENSE
7
+ Author: Jacob Stewart
8
+ Author-email: jacob@swarmauri.com
9
+ Requires-Python: >=3.10,<3.13
10
+ Classifier: Development Status :: 1 - Planning
11
+ Classifier: License :: OSI Approved :: Apache Software License
12
+ Classifier: Framework :: Pytest
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Description-Content-Type: text/markdown
18
+
19
+ ![Swarmauri Logo](https://github.com/swarmauri/swarmauri-sdk/blob/3d4d1cfa949399d7019ae9d8f296afba773dfb7f/assets/swarmauri.brand.theme.svg)
20
+
21
+ <p align="center">
22
+ <a href="https://pypi.org/project/swarmauri_tests_readme_examples/">
23
+ <img src="https://img.shields.io/pypi/dm/swarmauri_tests_readme_examples" alt="PyPI - Downloads"/></a>
24
+ <a href="https://hits.sh/github.com/swarmauri/swarmauri-sdk/tree/master/pkgs/experimental/swarmauri_tests_readme_examples/">
25
+ <img alt="Hits" src="https://hits.sh/github.com/swarmauri/swarmauri-sdk/tree/master/pkgs/experimental/swarmauri_tests_readme_examples.svg"/></a>
26
+ <a href="https://pypi.org/project/swarmauri_tests_readme_examples/">
27
+ <img src="https://img.shields.io/pypi/pyversions/swarmauri_tests_readme_examples" alt="PyPI - Python Version"/></a>
28
+ <a href="https://pypi.org/project/swarmauri_tests_readme_examples/">
29
+ <img src="https://img.shields.io/pypi/l/swarmauri_tests_readme_examples" alt="PyPI - License"/></a>
30
+ <a href="https://pypi.org/project/swarmauri_tests_readme_examples/">
31
+ <img src="https://img.shields.io/pypi/v/swarmauri_tests_readme_examples?label=swarmauri_tests_readme_examples&color=green" alt="PyPI - Version"/></a>
32
+ </p>
33
+
34
+ ---
35
+
36
+ ## Overview
37
+
38
+ `swarmauri_tests_readme_examples` is a [pytest](https://docs.pytest.org/) plugin that
39
+ turns Markdown code blocks into executable tests. It scans README (or other
40
+ documentation) files for Python examples and verifies that every runnable block
41
+ still executes successfully. This keeps documentation trustworthy without
42
+ hand-maintained `test_readme_example.py` scaffolding.
43
+
44
+ The plugin works out of the box for Python code blocks (` ```python `, ` ```py `,
45
+ ` ```pycon `) and exposes command-line flags and `pyproject.toml` settings so you can
46
+ fine-tune which files and languages are exercised.
47
+
48
+ ## Installation
49
+
50
+ ```bash
51
+ pip install swarmauri_tests_readme_examples
52
+ ```
53
+
54
+ `pytest` discovers the plugin automatically after installation.
55
+
56
+ ## Quick Start
57
+
58
+ Run `pytest` as usual to execute every Python code block in `README.md`:
59
+
60
+ ```bash
61
+ pytest
62
+ ```
63
+
64
+ Sample failure output:
65
+
66
+ ```
67
+ E README.md::block-3 raised ValueError('boom')
68
+ ```
69
+
70
+ ## Configuration
71
+
72
+ You can control the scan through CLI options or `pyproject.toml`:
73
+
74
+ * `--readme-files` – comma/newline separated Markdown files (default: `README.md`)
75
+ * `--readme-languages` – languages to execute (default: `python`, `py`, `pycon`)
76
+ * `--readme-mode` – `parameterized` (default) or `aggregate`
77
+ * `--readme-skip-markers` – comment markers that skip a block when they appear on the first non-empty line
78
+
79
+ `pyproject.toml` example (under `[tool.pytest.ini_options]`):
80
+
81
+ ```toml
82
+ [tool.pytest.ini_options]
83
+ readme_files = """
84
+ README.md
85
+ docs/guide.md
86
+ """
87
+ readme_languages = """
88
+ python
89
+ py
90
+ """
91
+ readme_mode = "aggregate"
92
+ readme_skip_markers = """
93
+ # pytest: skip-example
94
+ # docs: skip
95
+ """
96
+ ```
97
+
98
+ ## Skipping Blocks
99
+
100
+ Place one of the configured skip markers on the first non-empty line to leave a
101
+ code block out of execution:
102
+
103
+ ````markdown
104
+ ```python
105
+ # pytest: skip-example
106
+ print("shown in docs, ignored in tests")
107
+ ```
108
+ ````
109
+
110
+ ## Aggregate Mode
111
+
112
+ Switch to `--readme-mode=aggregate` (or set `readme_mode = "aggregate"`) to
113
+ collapse all README checks into a single pytest item that aggregates every
114
+ failure message. This is handy when you want a brief summary rather than many
115
+ individual tests.
116
+
117
+ ## License
118
+
119
+ Licensed under the [Apache 2.0 License](LICENSE).
120
+
@@ -0,0 +1,101 @@
1
+ ![Swarmauri Logo](https://github.com/swarmauri/swarmauri-sdk/blob/3d4d1cfa949399d7019ae9d8f296afba773dfb7f/assets/swarmauri.brand.theme.svg)
2
+
3
+ <p align="center">
4
+ <a href="https://pypi.org/project/swarmauri_tests_readme_examples/">
5
+ <img src="https://img.shields.io/pypi/dm/swarmauri_tests_readme_examples" alt="PyPI - Downloads"/></a>
6
+ <a href="https://hits.sh/github.com/swarmauri/swarmauri-sdk/tree/master/pkgs/experimental/swarmauri_tests_readme_examples/">
7
+ <img alt="Hits" src="https://hits.sh/github.com/swarmauri/swarmauri-sdk/tree/master/pkgs/experimental/swarmauri_tests_readme_examples.svg"/></a>
8
+ <a href="https://pypi.org/project/swarmauri_tests_readme_examples/">
9
+ <img src="https://img.shields.io/pypi/pyversions/swarmauri_tests_readme_examples" alt="PyPI - Python Version"/></a>
10
+ <a href="https://pypi.org/project/swarmauri_tests_readme_examples/">
11
+ <img src="https://img.shields.io/pypi/l/swarmauri_tests_readme_examples" alt="PyPI - License"/></a>
12
+ <a href="https://pypi.org/project/swarmauri_tests_readme_examples/">
13
+ <img src="https://img.shields.io/pypi/v/swarmauri_tests_readme_examples?label=swarmauri_tests_readme_examples&color=green" alt="PyPI - Version"/></a>
14
+ </p>
15
+
16
+ ---
17
+
18
+ ## Overview
19
+
20
+ `swarmauri_tests_readme_examples` is a [pytest](https://docs.pytest.org/) plugin that
21
+ turns Markdown code blocks into executable tests. It scans README (or other
22
+ documentation) files for Python examples and verifies that every runnable block
23
+ still executes successfully. This keeps documentation trustworthy without
24
+ hand-maintained `test_readme_example.py` scaffolding.
25
+
26
+ The plugin works out of the box for Python code blocks (` ```python `, ` ```py `,
27
+ ` ```pycon `) and exposes command-line flags and `pyproject.toml` settings so you can
28
+ fine-tune which files and languages are exercised.
29
+
30
+ ## Installation
31
+
32
+ ```bash
33
+ pip install swarmauri_tests_readme_examples
34
+ ```
35
+
36
+ `pytest` discovers the plugin automatically after installation.
37
+
38
+ ## Quick Start
39
+
40
+ Run `pytest` as usual to execute every Python code block in `README.md`:
41
+
42
+ ```bash
43
+ pytest
44
+ ```
45
+
46
+ Sample failure output:
47
+
48
+ ```
49
+ E README.md::block-3 raised ValueError('boom')
50
+ ```
51
+
52
+ ## Configuration
53
+
54
+ You can control the scan through CLI options or `pyproject.toml`:
55
+
56
+ * `--readme-files` – comma/newline separated Markdown files (default: `README.md`)
57
+ * `--readme-languages` – languages to execute (default: `python`, `py`, `pycon`)
58
+ * `--readme-mode` – `parameterized` (default) or `aggregate`
59
+ * `--readme-skip-markers` – comment markers that skip a block when they appear on the first non-empty line
60
+
61
+ `pyproject.toml` example (under `[tool.pytest.ini_options]`):
62
+
63
+ ```toml
64
+ [tool.pytest.ini_options]
65
+ readme_files = """
66
+ README.md
67
+ docs/guide.md
68
+ """
69
+ readme_languages = """
70
+ python
71
+ py
72
+ """
73
+ readme_mode = "aggregate"
74
+ readme_skip_markers = """
75
+ # pytest: skip-example
76
+ # docs: skip
77
+ """
78
+ ```
79
+
80
+ ## Skipping Blocks
81
+
82
+ Place one of the configured skip markers on the first non-empty line to leave a
83
+ code block out of execution:
84
+
85
+ ````markdown
86
+ ```python
87
+ # pytest: skip-example
88
+ print("shown in docs, ignored in tests")
89
+ ```
90
+ ````
91
+
92
+ ## Aggregate Mode
93
+
94
+ Switch to `--readme-mode=aggregate` (or set `readme_mode = "aggregate"`) to
95
+ collapse all README checks into a single pytest item that aggregates every
96
+ failure message. This is handy when you want a brief summary rather than many
97
+ individual tests.
98
+
99
+ ## License
100
+
101
+ Licensed under the [Apache 2.0 License](LICENSE).
@@ -0,0 +1,40 @@
1
+ [project]
2
+ name = "swarmauri_tests_readme_examples"
3
+ version = "0.1.0"
4
+ description = "Pytest plugin that executes README code examples."
5
+ authors = [{ name = "Jacob Stewart", email = "jacob@swarmauri.com" }]
6
+ license = "Apache-2.0"
7
+ readme = "README.md"
8
+ repository = "https://github.com/swarmauri/swarmauri-sdk/pkgs/experimental/swarmauri_tests_readme_examples"
9
+ requires-python = ">=3.10,<3.13"
10
+ classifiers = [
11
+ "Development Status :: 1 - Planning",
12
+ "License :: OSI Approved :: Apache Software License",
13
+ "Framework :: Pytest",
14
+ "Programming Language :: Python :: 3",
15
+ "Programming Language :: Python :: 3.10",
16
+ "Programming Language :: Python :: 3.11",
17
+ "Programming Language :: Python :: 3.12",
18
+ ]
19
+
20
+ [project.entry-points.pytest11]
21
+ swarmauri_tests_readme_examples = "swarmauri_tests_readme_examples"
22
+
23
+ [dependency-groups]
24
+ dev = [
25
+ "pytest>=8.0",
26
+ "pytest-asyncio>=0.24.0",
27
+ "pytest-xdist>=3.6.1",
28
+ "pytest-json-report>=1.5.0",
29
+ "python-dotenv",
30
+ "pytest-timeout>=2.3.1",
31
+ "ruff>=0.9.9",
32
+ "pytest-benchmark>=4.0.0",
33
+ ]
34
+
35
+ [tool.pytest.ini_options]
36
+ addopts = ""
37
+
38
+ [build-system]
39
+ requires = ["poetry-core>=1.0.0"]
40
+ build-backend = "poetry.core.masonry.api"
@@ -0,0 +1,380 @@
1
+ """Pytest plugin that turns README code blocks into executable tests."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import io
6
+ import traceback
7
+ from contextlib import redirect_stdout
8
+ from dataclasses import dataclass
9
+ from pathlib import Path
10
+ from typing import Iterable, List, Sequence
11
+
12
+ import pytest
13
+ from _pytest.warning_types import PytestWarning
14
+
15
+ PLUGIN_NAME = "swarmauri_tests_readme_examples"
16
+ DEFAULT_FILES: Sequence[str] = ("README.md",)
17
+ DEFAULT_LANGUAGES: Sequence[str] = ("python", "py")
18
+ DEFAULT_MODE = "parameterized"
19
+ DEFAULT_SKIP_MARKERS: Sequence[str] = ("# pytest: skip-example", "# no-exec")
20
+ UNTAGGED_SENTINEL = "untagged"
21
+ LANGUAGE_ALIASES = {"py": "python", "pycon": "pycon"}
22
+
23
+
24
+ @dataclass
25
+ class ReadmeExample:
26
+ path: Path
27
+ index: int
28
+ line: int
29
+ language: str
30
+ heading: str | None
31
+ code: str
32
+
33
+ @property
34
+ def display_name(self) -> str:
35
+ suffix = f"::{self.heading}" if self.heading else ""
36
+ return f"{self.path.name}{suffix}::block-{self.index}"
37
+
38
+
39
+ def pytest_addoption(parser: pytest.Parser) -> None:
40
+ group = parser.getgroup("readme")
41
+ group.addoption(
42
+ "--readme-mode",
43
+ action="store",
44
+ default=None,
45
+ choices=["parameterized", "aggregate"],
46
+ help="Run README examples as individual tests or a single aggregate.",
47
+ )
48
+ group.addoption(
49
+ "--readme-files",
50
+ action="store",
51
+ default=None,
52
+ help="Comma or newline separated Markdown files to scan for examples.",
53
+ )
54
+ group.addoption(
55
+ "--readme-languages",
56
+ action="store",
57
+ default=None,
58
+ help="Comma or newline separated code block languages to execute.",
59
+ )
60
+ group.addoption(
61
+ "--readme-skip-markers",
62
+ action="store",
63
+ default=None,
64
+ help="Markers that skip the first non-empty line of a block.",
65
+ )
66
+
67
+ parser.addini(
68
+ "readme_mode",
69
+ "Execution mode for README examples (parameterized or aggregate).",
70
+ default=DEFAULT_MODE,
71
+ )
72
+ parser.addini(
73
+ "readme_files",
74
+ "Markdown files that contain executable README examples.",
75
+ type="linelist",
76
+ default=list(DEFAULT_FILES),
77
+ )
78
+ parser.addini(
79
+ "readme_languages",
80
+ "Accepted code block languages (one per line).",
81
+ type="linelist",
82
+ default=list(DEFAULT_LANGUAGES),
83
+ )
84
+ parser.addini(
85
+ "readme_skip_markers",
86
+ "Markers that skip execution when found on the first non-empty line.",
87
+ type="linelist",
88
+ default=list(DEFAULT_SKIP_MARKERS),
89
+ )
90
+
91
+
92
+ def pytest_configure(config: pytest.Config) -> None:
93
+ config.addinivalue_line(
94
+ "markers",
95
+ "readme_example: autogenerated README code block test",
96
+ )
97
+
98
+ files = _resolve_files(config)
99
+ if not files:
100
+ config._readme_examples = []
101
+ config._readme_mode = DEFAULT_MODE
102
+ return
103
+
104
+ languages, allow_untagged = _resolve_languages(config)
105
+ skip_markers = _resolve_skip_markers(config)
106
+
107
+ examples: list[ReadmeExample] = []
108
+ for path in files:
109
+ examples.extend(
110
+ _extract_examples(path, languages, skip_markers, allow_untagged)
111
+ )
112
+
113
+ config._readme_examples = examples
114
+ config._readme_mode = _resolve_mode(config)
115
+ config._readme_allow_untagged = allow_untagged
116
+ config._readme_languages = languages
117
+
118
+
119
+ def pytest_collection_modifyitems(
120
+ session: pytest.Session, config: pytest.Config, items: list[pytest.Item]
121
+ ) -> None:
122
+ if getattr(config, "_readme_items_added", False):
123
+ return
124
+
125
+ examples: list[ReadmeExample] = getattr(config, "_readme_examples", [])
126
+ if not examples:
127
+ config._readme_items_added = True
128
+ return
129
+
130
+ config._readme_items_added = True
131
+ mode: str = getattr(config, "_readme_mode", DEFAULT_MODE)
132
+
133
+ if mode == "parameterized":
134
+ for example in examples:
135
+ item = ReadmeExampleItem.from_parent(
136
+ session,
137
+ name=f"{PLUGIN_NAME}:readme::{example.display_name}",
138
+ example=example,
139
+ )
140
+ items.append(item)
141
+ else:
142
+ item = ReadmeAggregateItem.from_parent(
143
+ session,
144
+ name=f"{PLUGIN_NAME}:readme-aggregate",
145
+ examples=examples,
146
+ )
147
+ items.append(item)
148
+
149
+
150
+ class ReadmeExampleItem(pytest.Item):
151
+ def __init__(self, name: str, parent: pytest.Collector, example: ReadmeExample):
152
+ super().__init__(name, parent)
153
+ self.example = example
154
+ self.path = example.path
155
+
156
+ def runtest(self) -> None:
157
+ failure = _execute_example(self.example)
158
+ if failure:
159
+ pytest.fail(failure, pytrace=False)
160
+
161
+ def reportinfo(self) -> tuple[Path, int, str]:
162
+ return self.example.path, self.example.line, self.example.display_name
163
+
164
+
165
+ class ReadmeAggregateItem(pytest.Item):
166
+ def __init__(
167
+ self, name: str, parent: pytest.Collector, examples: Sequence[ReadmeExample]
168
+ ):
169
+ super().__init__(name, parent)
170
+ self.examples = list(examples)
171
+
172
+ def runtest(self) -> None:
173
+ failures = []
174
+ for example in self.examples:
175
+ failure = _execute_example(example)
176
+ if failure:
177
+ failures.append(failure)
178
+ if failures:
179
+ pytest.fail("\n".join(failures), pytrace=False)
180
+
181
+ def reportinfo(self) -> tuple[str, None, str]:
182
+ return "README examples", None, "aggregate README check"
183
+
184
+
185
+ def _resolve_mode(config: pytest.Config) -> str:
186
+ opt = config.getoption("--readme-mode")
187
+ if opt:
188
+ return opt
189
+ ini_mode = str(config.getini("readme_mode") or "").strip().lower()
190
+ if ini_mode in {"parameterized", "aggregate"}:
191
+ return ini_mode
192
+ return DEFAULT_MODE
193
+
194
+
195
+ def _resolve_files(config: pytest.Config) -> List[Path]:
196
+ cli_values = _split_values(config.getoption("--readme-files"))
197
+ ini_values = _split_values(config.getini("readme_files"))
198
+ candidates = cli_values or ini_values or list(DEFAULT_FILES)
199
+
200
+ resolved: list[Path] = []
201
+ missing: list[str] = []
202
+ root = Path(config.rootpath)
203
+ for entry in candidates:
204
+ path = Path(entry)
205
+ if not path.is_absolute():
206
+ path = root / path
207
+ if path.exists():
208
+ resolved.append(path)
209
+ else:
210
+ missing.append(str(path))
211
+ if missing:
212
+ config.issue_config_time_warning(
213
+ PytestWarning(
214
+ "readme examples plugin: missing files -> " + ", ".join(missing)
215
+ ),
216
+ stacklevel=2,
217
+ )
218
+ return resolved
219
+
220
+
221
+ def _resolve_languages(config: pytest.Config) -> tuple[set[str], bool]:
222
+ cli = _split_values(config.getoption("--readme-languages"))
223
+ ini = _split_values(config.getini("readme_languages"))
224
+ values = cli or ini or list(DEFAULT_LANGUAGES)
225
+ allow_untagged = False
226
+ languages: set[str] = set()
227
+ for value in values:
228
+ lowered = value.lower()
229
+ if not lowered:
230
+ continue
231
+ if lowered in {UNTAGGED_SENTINEL, "auto"}:
232
+ allow_untagged = True
233
+ continue
234
+ languages.add(lowered)
235
+ if not languages:
236
+ languages.update(DEFAULT_LANGUAGES)
237
+ return languages, allow_untagged
238
+
239
+
240
+ def _resolve_skip_markers(config: pytest.Config) -> set[str]:
241
+ cli = _split_values(config.getoption("--readme-skip-markers"))
242
+ ini = _split_values(config.getini("readme_skip_markers"))
243
+ values = cli or ini or list(DEFAULT_SKIP_MARKERS)
244
+ return {value.strip() for value in values if value.strip()}
245
+
246
+
247
+ def _split_values(raw: object) -> list[str]:
248
+ if not raw:
249
+ return []
250
+ if isinstance(raw, (list, tuple)):
251
+ values: list[str] = []
252
+ for entry in raw:
253
+ values.extend(_split_values(entry))
254
+ return values
255
+ text = str(raw).replace("\r", "\n")
256
+ values = []
257
+ for line in text.splitlines():
258
+ if not line.strip():
259
+ continue
260
+ for chunk in line.split(","):
261
+ chunk = chunk.strip()
262
+ if chunk:
263
+ values.append(chunk)
264
+ return values
265
+
266
+
267
+ def _extract_examples(
268
+ path: Path, languages: set[str], skip_markers: set[str], allow_untagged: bool
269
+ ) -> list[ReadmeExample]:
270
+ text = path.read_text(encoding="utf-8")
271
+ examples: list[ReadmeExample] = []
272
+ for index, (lang, code, line, heading) in enumerate(
273
+ _iter_code_blocks(text),
274
+ start=1,
275
+ ):
276
+ raw_language = (lang or "").strip().lower()
277
+ canonical = raw_language
278
+ exec_language = LANGUAGE_ALIASES.get(canonical, canonical)
279
+ if not canonical:
280
+ if not allow_untagged:
281
+ continue
282
+ canonical = UNTAGGED_SENTINEL
283
+ exec_language = "python"
284
+ if canonical not in languages and exec_language not in languages:
285
+ if not (canonical == UNTAGGED_SENTINEL and allow_untagged):
286
+ continue
287
+ normalized = _normalize_code(exec_language, code)
288
+ if _should_skip(normalized, skip_markers):
289
+ continue
290
+ examples.append(
291
+ ReadmeExample(
292
+ path=path,
293
+ index=index,
294
+ line=line,
295
+ language=exec_language,
296
+ heading=heading,
297
+ code=normalized,
298
+ )
299
+ )
300
+ return examples
301
+
302
+
303
+ def _iter_code_blocks(text: str) -> Iterable[tuple[str, str, int, str | None]]:
304
+ lines = text.splitlines()
305
+ heading: str | None = None
306
+ i = 0
307
+ total = len(lines)
308
+ while i < total:
309
+ raw = lines[i]
310
+ stripped = raw.strip()
311
+ if stripped.startswith("#"):
312
+ heading = stripped.lstrip("#").strip() or None
313
+ i += 1
314
+ continue
315
+ if stripped.startswith("```"):
316
+ lang = stripped[3:].strip()
317
+ start_line = i + 2
318
+ i += 1
319
+ block_lines: list[str] = []
320
+ while i < total and not lines[i].strip().startswith("```"):
321
+ block_lines.append(lines[i])
322
+ i += 1
323
+ code = "\n".join(block_lines)
324
+ while i < total and not lines[i].strip().startswith("```"):
325
+ i += 1
326
+ if i < total:
327
+ i += 1
328
+ yield lang, code, start_line, heading
329
+ continue
330
+ i += 1
331
+
332
+
333
+ def _normalize_code(language: str, code: str) -> str:
334
+ if language != "pycon":
335
+ return code
336
+ cleaned: list[str] = []
337
+ for line in code.splitlines():
338
+ if line.startswith(">>> ") or line.startswith("... "):
339
+ cleaned.append(line[4:])
340
+ elif line.startswith(">>>") or line.startswith("..."):
341
+ cleaned.append(line[3:])
342
+ else:
343
+ cleaned.append(line)
344
+ return "\n".join(cleaned)
345
+
346
+
347
+ def _should_skip(code: str, markers: set[str]) -> bool:
348
+ for line in code.splitlines():
349
+ stripped = line.strip()
350
+ if not stripped:
351
+ continue
352
+ for marker in markers:
353
+ if marker in stripped:
354
+ return True
355
+ break
356
+ return False
357
+
358
+
359
+ def _execute_example(example: ReadmeExample) -> str | None:
360
+ namespace: dict[str, object] = {"__name__": "__main__"}
361
+ stdout = io.StringIO()
362
+ code_object = compile(
363
+ example.code,
364
+ f"{example.path}#example-{example.index}",
365
+ "exec",
366
+ )
367
+ try:
368
+ with redirect_stdout(stdout):
369
+ exec(code_object, namespace, namespace)
370
+ except Exception as exc: # pragma: no cover - verified via plugin tests
371
+ summary = "".join(traceback.format_exception_only(exc.__class__, exc)).strip()
372
+ return (
373
+ f"{example.path}:{example.line} ({example.display_name}) raised {summary}"
374
+ )
375
+ return None
376
+
377
+
378
+ __all__ = [
379
+ "ReadmeExample",
380
+ ]