用于测试flake8插件的pytest插件。
项目描述
用于测试flake8插件的pytest插件。
快速示例
def test_simple_run(flake8_path):
(flake8_path / "example.py").write_text("x = 1\n")
result = flake8_path.run_flake8()
assert result.out_lines == [
"./example.py:1:2: E221 multiple spaces before operator"
]
安装
使用 pip
python -m pip install pytest-flake8-path
支持Python 3.8到3.12。
在Django项目中工作? 查看我的书籍 加速您的Django测试,其中涵盖了大量编写更快、更准确的测试的方法。
API
flake8_path 插件
一个pytest插件,它包装了Pytest的内置 tmp_path 插件(文档),以创建一个临时目录,允许添加文件并运行flake8。它像一个 pathlib.Path 对象,有一个额外的方法。
如果您正在使用此插件测试flake8插件,请确保flake8在测试期间识别您的插件。通常这通过一个 setup.cfg 入口点来完成,这使得tox成为确保此操作就绪的最简单方法,因为它将在运行测试之前安装您的项目。
flake8dir.run_flake8(extra_args: list[str] | None = None) -> Flake8Result
运行flake8并返回一个表示结果的Flake8Result。
extra_args可能是一个传递给flake8的额外标志列表,例如传递["--ignore", "E101"]。注意,一些参数已经传递,以确保flake8以独立方式运行 - 请参阅源代码。
Flake8Result
表示flake8运行的解析输出。
Flake8Result.out: str
flake8生成的完整输出字符串(stdout)。
Flake8Result.err: str
flake8生成的完整错误输出字符串(stderr)。
Flake8Result.exit_code: int
flake8运行退出的退出代码。
Flake8Result.out_lines: list[str]
输出行的列表,没有尾随换行符。这是制作断言最有用的工具。
在Windows上,文件路径被规范化为Unix格式(\被替换为/)。这允许测试套件在所有操作系统上运行相同的测试。
例如,给定一个结果,您可以检查特定的行是否被输出
result = flake8_path.run_flake8()
expected = "./example.py:1:2: E221 multiple spaces before operator"
assert expected in result.out_lines
Flake8Result.err_lines: list[str]
与out_lines类似,但用于错误输出。
示例
基本
使用Path.write_text() (文档),我们可以创建一个包含代码的example.py文件。然后,使用flake8_path.run_flake8()运行flake8并检查预期的错误。
def test_simple(flake8_path):
(flake8_path / "example.py").write_text("x = 1\n")
result = flake8_path.run_flake8()
assert result.out_lines == [
"./example.py:1:2: E221 multiple spaces before operator"
]
assert result.err_lines == []
assert result.exit_code == 1
使用dedent
标准库中的textwrap.dedent() (文档)对于包含多行文件很有用。使用三引号的多行字符串,并使用初始反斜杠防止空白的第一行。
def test_multi_line(flake8_path):
(flake8_path / "example.py").write_text(
dedent(
"""\
x = 1
y = 2
"""
)
)
result = flake8_path.run_flake8()
assert result.out_lines == [
"./example.py:1:2: E221 multiple spaces before operator",
"./example.py:2:2: E221 multiple spaces before operator",
]
assert result.err_lines == []
assert result.exit_code == 1
配置flake8
在运行flake8之前,编写一个setup.cfg文件来配置flake8。
def test_with_setup_cfg(flake8_path):
(flake8_path / "setup.cfg").write_text(
dedent(
"""\
[flake8]
ignore = E221
"""
)
)
(flake8_path / "example.py").write_text("x = 1\n")
result = flake8_path.run_flake8()
assert result.out_lines == []
assert result.err_lines == []
assert result.exit_code == 0
历史
pytest-flake8-path是pytest-flake8dir的后续产品。pytest-flake8dir基于pytest的tmpdir固定装置,返回一个传统的py.path.local对象。从版本3.9.0开始,pytest提供了tmp_path固定装置,它返回一个标准库的pathlib.Path对象。pytest-flake8-path是pytest-flake8dir的改写,以使用tmp_path而不是tmpdir。