【发布时间】:2018-10-19 09:10:58
【问题描述】:
我正在使用pytest-flake8 插件来检查我的 Python 代码。 每次我像这样运行 linting:
pytest --flake8
除了 linting 之外,还会运行所有测试。 但我只想运行 linter 检查。
我如何配置 pytest,使其只检查代码但跳过我的所有测试,最好通过命令行(或 conftest.py) - 无需在我的测试中添加跳过标记?
【问题讨论】:
我正在使用pytest-flake8 插件来检查我的 Python 代码。 每次我像这样运行 linting:
pytest --flake8
除了 linting 之外,还会运行所有测试。 但我只想运行 linter 检查。
我如何配置 pytest,使其只检查代码但跳过我的所有测试,最好通过命令行(或 conftest.py) - 无需在我的测试中添加跳过标记?
【问题讨论】:
flake8 测试标有flake8 标记,因此您只能通过运行选择那些:
pytest --flake8 -m flake8
【讨论】:
如果您的所有测试都在一个目录中,那么 Pytests --ignore <<path>> 选项在这里也很有效。
我通常将其隐藏在 make 命令后面。在这种情况下,我的 Makefile 和 tests 目录都位于存储库的根目录中。
.PHONY: lint
lint:
pytest --flake8 --ignore tests
【讨论】:
我遇到了同样的问题,经过一番挖掘,我意识到我只想运行flake8:
flake8 <path to folder>
就是这样。无需运行其他任何东西,因为您的 flake8 configuration 独立于 PyTest。
【讨论】:
pytest 的解决方案,但在我看来,这不是最好的方法。正如我所说,我遇到了同样的问题,当我对pytest 本身进行调整时,我意识到这需要付出很多努力并增加项目的额外(在我看来是不必要的)复杂性。只运行flake8 是一个简单而干净的替代方案,可以解决给定的问题。
您可以自己更改测试运行逻辑,例如在--flake8 arg 通过时忽略收集的测试:
# conftest.py
def pytest_collection_modifyitems(session, config, items):
if config.getoption('--flake8'):
items[:] = [item for item in items if item.get_closest_marker('flake8')]
现在只执行 flake8 测试,其余的将被忽略。
【讨论】:
经过更多思考,这是我想出的解决方案 - 它适用于 pytest 5.3.5(来自https://stackoverflow.com/a/52891274/319905 的get_marker 不再存在)。
它允许我通过命令行运行特定的 linting 检查。 由于我仍然喜欢保留同时运行 linting 检查和测试的选项,因此我添加了一个标志,告诉 pytest 是否应该只执行 linting。
用法:
# Run only flake8 and mypy, no tests
pytest --lint-only --flake8 --mypy
# Run tests and flake8
pytest --flake8
代码:
# conftest.py
def pytest_addoption(parser):
parser.addoption(
"--lint-only",
action="store_true",
default=False,
help="Only run linting checks",
)
def pytest_collection_modifyitems(session, config, items):
if config.getoption("--lint-only"):
lint_items = []
for linter in ["flake8", "black", "mypy"]:
if config.getoption(f"--{linter}"):
lint_items.extend(
[item for item in items if item.get_closest_marker(linter)]
)
items[:] = lint_items
【讨论】:
get_marker 已替换为 get_closest_marker,请参阅 Updating code。更新了答案。
from _pytest.config.argparsing import Parser,但是什么是session/config/items?
from _pytest.config import Config 用于配置,我猜。