pytest AttributeError:“函数”对象没有属性“ get_marker”

Mes*_*ssa 7 python pytest

我的代码conftest.py如下:

def pytest_collection_modifyitems(config, items):
    items.sort(key=lambda x: 2 if x.get_marker('slow') else 1)
Run Code Online (Sandbox Code Playgroud)

最近,它开始引起以下异常:

$ venv/bin/py.test  -vv --tb=short tests
============================================================================ test session starts ============================================================================
platform darwin -- Python 3.5.6, pytest-4.1.1, py-1.7.0, pluggy-0.8.1 -- /Users/.../venv/bin/python3.5
cachedir: .pytest_cache
rootdir: /Users/..., inifile:
collecting ... INTERNALERROR> Traceback (most recent call last):
INTERNALERROR>   File "/Users/.../venv/lib/python3.5/site-packages/_pytest/main.py", line 203, in wrap_session
...
INTERNALERROR>   File "/Users/.../venv/lib/python3.5/site-packages/pluggy/callers.py", line 187, in _multicall
INTERNALERROR>     res = hook_impl.function(*args)
INTERNALERROR>   File "/Users/.../tests/conftest.py", line 14, in pytest_collection_modifyitems
INTERNALERROR>     items.sort(key=lambda x: 2 if x.get_marker('slow') else 1)
INTERNALERROR>   File "/Users/.../tests/conftest.py", line 14, in <lambda>
INTERNALERROR>     items.sort(key=lambda x: 2 if x.get_marker('slow') else 1)
INTERNALERROR> AttributeError: 'Function' object has no attribute 'get_marker'

======================================================================= no tests ran in 0.30 seconds ================================================
Run Code Online (Sandbox Code Playgroud)

Mes*_*ssa 8

Pytest在版本4中更改了其API。

快速解决方案:使用get_closest_marker()代替get_marker()

def pytest_collection_modifyitems(config, items):
    items.sort(key=lambda x: 2 if x.get_closest_marker('slow') else 1)
Run Code Online (Sandbox Code Playgroud)

参见https://github.com/pytest-dev/pytest/pull/4564

删除Node.get_marker(name)返回值不能用于存在检查。

使用Node.get_closest_marker(name)作为替代。

删除testfunction.markername属性-用于Node.iter_markers(name=None)迭代它们。