Skip to content

Commit

Permalink
Fix a bug in the handling of single line docstrings (#15)
Browse files Browse the repository at this point in the history
  • Loading branch information
dmontagu authored Jul 11, 2023
1 parent 4b1634a commit b086bcb
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 2 deletions.
4 changes: 2 additions & 2 deletions pytest_examples/find_examples.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,8 +140,8 @@ def find_examples(*paths: str | Path, skip: bool = False) -> Iterable[CodeExampl
group = uuid4()
if path.suffix == '.py':
code = path.read_text('utf-8')
for m_docstring in re.finditer(r'(^ *)(r?""".*?\n)(.+?)\1"""', code, flags=re.M | re.S):
start_line = code[: m_docstring.start()].count('\n') + 1
for m_docstring in re.finditer(r'(^ *)(r?""")(.+?)\1"""', code, flags=re.M | re.S):
start_line = code[: m_docstring.start()].count('\n')
docstring = m_docstring.group(3)
index_offset = m_docstring.start() + len(m_docstring.group(1)) + len(m_docstring.group(2))
yield from _extract_code_chunks(
Expand Down
65 changes: 65 additions & 0 deletions tests/test_find_examples.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,71 @@ def test_find_examples(example):
assert 'test_find_examples[my_file.py:30-34] PASSED' in output


def test_find_py_example_with_module_docstring(pytester: pytest.Pytester):
pytester.makefile(
'.py',
# language=Python
my_file='''
"""Module docstring."""
def func_a():
"""
```py
a = 1
b = 2
assert a + b == 3
```
"""
pass
def func_b():
"""
```py
c = 3
d = 4
assert c + d == 7
```
```py
e = 5
f = 6
assert e + f == 11
```
"""
pass
def func_c():
"""Does cool things.
```py
g = 7
h = 8
assert g + h == 15
```
"""
''',
)
pytester.makepyfile(
# language=Python
"""
from pytest_examples import find_examples
import pytest
@pytest.mark.parametrize('example', find_examples('.'), ids=str)
def test_find_examples(example):
assert example.indent == 4
"""
)

result = pytester.runpytest('-p', 'no:pretty', '-vs')
result.assert_outcomes(passed=4)

output = '\n'.join(result.outlines)
assert 'test_find_examples[my_file.py:4-8] PASSED' in output
assert 'test_find_examples[my_file.py:15-19] PASSED' in output
assert 'test_find_examples[my_file.py:21-25] PASSED' in output
assert 'test_find_examples[my_file.py:31-35] PASSED' in output


def test_find_file_example(pytester: pytest.Pytester):
pytester.makefile(
'.md',
Expand Down

0 comments on commit b086bcb

Please sign in to comment.