Skip to content

Commit 3cdf14e

Browse files
committed
fix: expose markdown source as __file__
1 parent 8614de6 commit 3cdf14e

3 files changed

Lines changed: 33 additions & 0 deletions

File tree

‎README.md‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,20 @@ assert captured.out == "hello\n"
120120

121121
As you can see above, the fixture value will be injected as a global. For `autouse=True` fixtures, the value is only injected as a global if it's explicitly added using a `fixture:<name>` marker.
122122

123+
### The source file path
124+
125+
Code fences receive a `__file__` global containing the path of the Markdown or
126+
Python file where the fence was found. This makes it possible to load fixtures
127+
stored next to a document:
128+
129+
````markdown
130+
```python
131+
from pathlib import Path
132+
133+
fixture = Path(__file__).with_name("fixture.json").read_text()
134+
```
135+
````
136+
123137
### Async Fixtures (pytest-asyncio)
124138

125139
If you have [pytest-asyncio](https://pypi.org/project/pytest-asyncio/) installed, you can use async fixtures with your markdown tests. The async fixture will be executed and its resolved value will be injected into the test code:

‎src/pytest_markdown_docs/plugin.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,7 @@ def runtest(self):
9595

9696
mod = types.ModuleType("fence") # dummy module
9797
all_globals = mod.__dict__
98+
all_globals["__file__"] = str(self.test_definition.source_path)
9899
for global_set in global_sets:
99100
all_globals.update(global_set)
100101

‎tests/plugin_test.py‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,24 @@ def pytest_markdown_docs_globals():
8585
result.assert_outcomes(passed=1, failed=2)
8686

8787

88+
def test_file_global_points_to_markdown_source(testdir):
89+
testdir.makefile(".txt", neighbor="from neighbor\n")
90+
testdir.makefile(
91+
".md",
92+
test_file="""
93+
```python
94+
from pathlib import Path
95+
96+
assert Path(__file__).name == "test_file.md"
97+
assert Path(__file__).with_name("neighbor.txt").read_text().strip() == "from neighbor"
98+
```
99+
""",
100+
)
101+
102+
result = testdir.runpytest("--markdown-docs")
103+
result.assert_outcomes(passed=1)
104+
105+
88106
def test_continuation(testdir):
89107
testdir.makefile(
90108
".md",

0 commit comments

Comments
 (0)