Pytest插件,用于测试文档字符串和Markdown文件中的示例。
项目描述
pytest-examples
pytest-examples是用于测试Python代码示例的Pytest插件,这些示例位于文档字符串和Markdown文件中。
pytest-examples
可以
- 使用
ruff
和black
检查代码示例的语法 - 运行代码示例
- 运行代码示例并检查打印语句是否正确地内联在代码中
它还可以就地更新代码示例,以格式化它们并插入或更新打印语句。
安装
pip install -U pytest-examples
使用方法
基本用法
以下是一个基本用法的示例 - 检查并运行位于foo_dir
目录和bar_file.py
文件中的示例。
import pytest
from pytest_examples import find_examples, CodeExample, EvalExample
@pytest.mark.parametrize('example', find_examples('foo_dir', 'bar_file.py'), ids=str)
def test_docstrings(example: CodeExample, eval_example: EvalExample):
eval_example.lint(example)
eval_example.run(example)
检查打印语句
pytest-examples
还可以检查打印语句是否正确插入。
以下是文档字符串中打印语句的预期格式
def add_two_things(a, b):
"""
```py
from my_lib import add_two_things
print(add_two_things(1, 2))
#> 3
```
"""
return a + b
以下是一个Markdown文件的示例,同样用于记录add_two_things
# How `add_two_things` works
```py
from my_lib import add_two_things
print(add_two_things(1, 2))
#> 3
```
pytest-examples
然后运行代码并检查打印语句是否正确
import pytest
from pytest_examples import find_examples, CodeExample, EvalExample
@pytest.mark.parametrize('example', find_examples('foo_dir'), ids=str)
def test_docstrings(example: CodeExample, eval_example: EvalExample):
eval_example.run_print_check(example)
更新文件
除了检查语法和打印语句是否正确外,我们还可以更新文件。
这需要使用--update-examples
标志和使用format()
和run_print_update()
方法。
以下是一个单元测试的完整示例,它检查在正常调用时代码,但在设置标志时可以更新它
import pytest
from pytest_examples import find_examples, CodeExample, EvalExample
@pytest.mark.parametrize('example', find_examples('README.md'), ids=str)
def test_readme(example: CodeExample, eval_example: EvalExample):
if eval_example.update_examples:
eval_example.format(example)
eval_example.run_print_update(example)
else:
eval_example.lint(example)
eval_example.run_print_check(example)
项目详情
下载文件
下载适合您平台的文件。如果您不确定该选择哪个,请了解更多关于 安装包 的信息。
源代码分布
pytest_examples-0.0.13.tar.gz (20.4 kB 查看哈希值)
构建分布
pytest_examples-0.0.13-py3-none-any.whl (17.3 kB 查看哈希值)
关闭
pytest_examples-0.0.13.tar.gz 的哈希值
算法 | 哈希摘要 | |
---|---|---|
SHA256 | 4d6fd78154953e84444f58f193eb6cc8d853bca7f0ee9f44ea75db043a2c19b5 |
|
MD5 | 99c40547a91ff86a3290ca90b990821c |
|
BLAKE2b-256 | 0d679d3486460bde76a5fd3709de38eea6cbeab7f41b1fe2c657f52a71b19575 |
关闭
pytest_examples-0.0.13-py3-none-any.whl 的哈希值
算法 | 哈希摘要 | |
---|---|---|
SHA256 | 8c05cc66459199963c7970ff417300ae7e5b7b4c9d5bd859f1e74a35db75555b |
|
MD5 | 22519fe73429b193de278135ae96b611 |
|
BLAKE2b-256 | 17c49b639b46dc0aa246847c5d82171d4167218bcceb2108f566e25afdfd229f |