通过pytest运行markdown代码隔离区
项目描述
Pytest Markdown Docs
一个用于 pytest 的插件,它使用来自markdown文件的代码片段和docstrings作为测试。
检测markdown文件中的Python代码隔离区(三重反引号转义块)以及行内Python docstrings(类似于doctests),并将它们作为测试运行。
Python文件示例
# mymodule.py
class Foo:
def bar(self):
"""Bar the foo
This is a sample docstring for the bar method
Usage:
```python
import mymodule
result = mymodule.Foo().bar()
assert result == "hello"
```
"""
return "hello"
Markdown文件示例
# Title
Lorem ipsum yada yada yada
```python
import mymodule
result = mymodule.Foo().bar()
assert result == "hello"
```
使用方法
首先,请确保安装该插件
pip install pytest-markdown-docs
要启用markdown python测试,向pytest传递 --markdown-docs
标志
pytest --markdown-docs
您还可以使用 markdown-docs
标志来 仅 过滤markdown-docs测试
pytest --markdown-docs -m markdown-docs
检测条件
以 python
、python3
或 py
语言定义开始的隔离区(```
)在Python (.py) 文件中被检测为测试,在类和函数的docstrings内部
.md
、.mdx
和.svx
文件- 中
跳过测试
要排除Python代码隔离区从测试中,向代码隔离区添加一个 notest
info字符串,例如
```python notest
print("this will not be run")
```
代码块依赖
有时你可能希望运行依赖于已声明在代码作用域中的实体的代码块,而不必显式声明它们。目前使用 pytest-markdown 有两种方法可以实现这一点。
注入全局/局部变量
如果你有一些常用的导入或其他常用变量,你想要在代码片段中使用,你可以通过在 conftest.py
中创建一个 pytest_markdown_docs_globals
钩子来添加它们。
def pytest_markdown_docs_globals():
import math
return {"math": math, "myvar": "hello"}
有了这个 conftest,你就可以运行以下 markdown 片段作为测试,而不会引发错误。
```python
print(myvar, math.pi)
```
测试夹具
你可以在 conftest.py
中使用 autouse=True
pytest 测试夹具,或者使用命名夹具与你的 markdown 测试一起使用。要指定命名夹具,请向代码围栏信息字符串添加 fixture:<name>
标记,例如:
```python fixture:capsys
print("hello")
captured = capsys.readouterr()
assert captured.out == "hello\n"
```
如上所示,夹具值将被注入为全局。对于 autouse=True
夹具,值只有在显式使用 fixture:<name>
标记添加的情况下才作为全局值注入。
依赖于之前的片段
如果你有多个连续的片段,并且想要保留前一个片段的副作用,你可以通过在代码围栏中添加 continuation
信息字符串来实现。
```python
a = "hello"
```
```python continuation
assert a + " world" == "hello world"
```
此插件的测试
你可以使用 pytest 测试此模块本身(遗憾的是目前无法使用 markdown 测试),
> poetry run pytest
或者为了乐趣,你可以使用此插件来测试本 README.md 文件中片段的有效性。
> poetry run pytest --markdown-docs
已知问题
- 文档字符串内联测试发现的可能可以做得更好(类似于 doctest 的方式)。目前,有时似乎会遍历到 Python 的标准库,这不是很好...
- 跟踪逻辑极其拙劣,不奇怪有时跟踪回溯看起来很奇怪。
- 行号对于文档字符串内联片段“不正确”(因为我们不知道文档字符串在哪里开始)。
- 行号对于续行块即使在纯 markdown 文件中也是“不正确”的(可以通过一些重构来解决)。
- 可能还有更合适的方法来使用 pytest 内部 API 来“免费”获得更多功能 - 当前代码的状态有点“修补到它工作”。
- 断言不像默认的常规 pytest 测试那样使用漂亮的 数据结构检查来重写。
项目详情
下载文件
下载适用于您平台的文件。如果您不确定选择哪个,请了解有关 安装包 的更多信息。
源分布
构建分布
pytest_markdown_docs-0.5.1.tar.gz 的散列
算法 | 散列摘要 | |
---|---|---|
SHA256 | acf9b678b589779e817f740bb1c8c4984a1bdca23ddc1c68ea6377918f5a871c |
|
MD5 | d8ca67a90b9a7492f76eaba47692c61d |
|
BLAKE2b-256 | 加密哈希:e9616afa1701b8fc3ba5eac82dddb919b3fa81cdbc4573848110594e24eb6b30 |