跳转到主要内容

Pytest插件,用于测试文档字符串和Markdown文件中的示例。

项目描述

pytest-examples

CI pypi versions license

pytest-examples是用于测试Python代码示例的Pytest插件,这些示例位于文档字符串和Markdown文件中。

pytest-examples可以

  • 使用ruffblack检查代码示例的语法
  • 运行代码示例
  • 运行代码示例并检查打印语句是否正确地内联在代码中

它还可以就地更新代码示例,以格式化它们并插入或更新打印语句。

安装

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 查看哈希值)

上传时间 Python 3

由以下支持

AWSAWS云计算和安全赞助商DatadogDatadog监控FastlyFastlyCDNGoogleGoogle下载分析MicrosoftMicrosoftPSF赞助商PingdomPingdom监控SentrySentry错误日志StatusPageStatusPage状态页面