书中写法如下:

import pytest

def pytest_addoption(parser):
    group = parser.getgroup('nice')
    group.addoption("--nice", action="store_true", help="nice: turn failures into opportunities")

def pytest_report_header():
    if pytest.Config.getoption('nice'):
        return "Thanks for running the test."

但执行会报错:

INTERNALERROR>     raise ex[1].with_traceback(ex[2])
INTERNALERROR>   File "c:\users\86159\appdata\local\programs\python\python38\lib\site-packages\pluggy\_callers.py", line 39, in _multicall
INTERNALERROR>     res = hook_impl.function(*args)
INTERNALERROR>   File "I:\python_prjs\PythonDemo\pytest\ch5\conftest.py", line 15, in pytest_report_header
INTERNALERROR>     if pytest.Config.getoption('nice'):
INTERNALERROR> TypeError: getoption() missing 1 required positional argument: 'name'

具体可以查看pytest.Config这个类来找到原因.不做说明. 现在对pytest源码没有了解, 也不知道这里具体如何改进;

不过后面尝试使用pytestconfig来读配置;但同样会报错;

def pytest_report_header(pytestconfig):
    if pytestconfig.getoption('nice'):
        return "Thanks for running the test."

报错如下:
pluggy._manager.PluginValidationError: Plugin 'I:\\python_prjs\\PythonDemo\\pytest\\ch5\\conftest.py' for hook 'pytest_report_header'
hookimpl definition: pytest_report_header(pytestconfig)
Argument(s) {'pytestconfig'} are declared in the hookimpl but can not be found in the hookspec

看起来似乎和pytest初始化过程中钩子函数的解析顺序有关;

解决方法

pytest.Configconfig直接替换就行

def pytest_addoption(parser):
    group = parser.getgroup('nice')
    group.addoption("--nice", action="store_true", help="nice: turn failures into opportunities")

def pytest_report_header(config):
    if config.getoption('nice'):
        return "Thanks for running the test."

def pytest_report_teststatus(report, config):
    if report.when == 'call':
        if report.failed and config.getoption( 'nice'):
            return (report.outcome, 'O', 'OPPORTRNITY for improvement')

大概原因可以参考这个:https://docs.pytest.org/en/stable/deprecations.html#pytest-config-global 应该是和pytest版本有关系. 我电脑上的版本是

> pytest --version
pytest 7.1.2
最后修改日期: 2024年11月3日

作者

留言

撰写回覆或留言