Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support python console REPL. #78

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -154,3 +154,35 @@ The following gives an error:
````

The keyword `expect-exception` is also possible.

#### Doctest-style code blocks

Code blocks starting with `">>>"` will be treated as interactive Python shell code, and tested by [doctest](https://docs.python.org/3/library/doctest.html).

````markdown
```python
>>> print("Hello")
Hello
>>> 2+3
5
```
````
You can concatenate multiple doctest-style code blocks with `<!--pytest-codeblocks:cont-->`, but cannot mix doctest-style ones with normal python code blocks, or vice versa.

There are two ways to indicate expected exceptions in doctest-style code blocks. One is to include the expected exception into you code block, and let doctest handle it.

````markdown
```python
>>> raise Exception("This should fail")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
Exception: This should fail
```
````
The other way is to use the `<!--pytest-codeblocks:expect-exception-->`, and let pytest handle it.
````markdown
<!--pytest-codeblocks:expect-exception-->
```python
>>> raise Exception("This should fail")
```
````
11 changes: 11 additions & 0 deletions src/pytest_codeblocks/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,13 @@
# namedtuple with default arguments
# <https://stackoverflow.com/a/18348004/353337>
from dataclasses import dataclass
from doctest import DebugRunner, DocTestFinder
from io import StringIO
from pathlib import Path

finder = DocTestFinder()
runner = DebugRunner()


@dataclass
class CodeBlock:
Expand All @@ -21,6 +25,13 @@ class CodeBlock:
skip: bool = False
skipif: str | None = None

def exec(self, globs: dict) -> None:
if self.code.startswith(">>>"):
for test in finder.find(self.code, name=f"line {self.lineno}", globs=globs):
runner.run(test)
else:
exec(self.code, globs)


def extract_from_file(
f: str | bytes | Path, encoding: str | None = "utf-8", *args, **kwargs
Expand Down
4 changes: 2 additions & 2 deletions src/pytest_codeblocks/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,12 +64,12 @@ def runtest(self):
if self.obj.syntax == "python":
if self.obj.expect_exception:
with pytest.raises(Exception):
exec(self.obj.code, {"__MODULE__": "__main__"})
self.obj.exec({"__MODULE__": "__main__"})
else:
with stdout_io() as s:
try:
# https://stackoverflow.com/a/62851176/353337
exec(self.obj.code, {"__MODULE__": "__main__"})
self.obj.exec({"__MODULE__": "__main__"})
except Exception as e:
raise RuntimeError(
f"{self.name}, line {self.obj.lineno}:\n```\n"
Expand Down
56 changes: 56 additions & 0 deletions tests/test_repl.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import pathlib

from pytest import skip

import pytest_codeblocks


def test_repr(testdir):
string1 = """
```python
>>> print("Hello World!")
Hello World!
```
"""
testdir.makefile(".md", string1)
result = testdir.runpytest("--codeblocks")
result.assert_outcomes(passed=1)


def test_cont(testdir):
string1 = """
```python
>>> def add(a, b):
... return a + b
```

<!--pytest-codeblocks:cont-->
```python
>>> add(2,7)
9
```
"""
testdir.makefile(".md", string1)
result = testdir.runpytest("--codeblocks")
result.assert_outcomes(passed=1)


def test_exception(testdir):
string1 = """
Handle the exception by doctest:
```python
>>> raise Exception("This should fail")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
Exception: This should fail
```

Handle the exception by pytest:
<!--pytest-codeblocks:expect-exception-->
```python
>>> raise Exception("This should fail")
```
"""
testdir.makefile(".md", string1)
result = testdir.runpytest("--codeblocks")
result.assert_outcomes(passed=2)