代码之家  ›  专栏  ›  技术社区  ›  Messa

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

  •  2
  • Messa  · 技术社区  · 7 年前

    我的电脑里有这个密码 conftest.py :

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

    最近,它开始导致以下例外情况:

    $ 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 ================================================
    
    1 回复  |  直到 7 年前
        1
  •  19
  •   Messa    7 年前

    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)
    

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

    去除 Node.get_marker(name) 返回值只能用于存在性检查。

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

    去除 testfunction.markername 属性-使用 Node.iter_markers(name=None) 重复它们。

        2
  •  0
  •   Sameer Girolkar    5 年前

    最新文件建议使用 项目iter_标记

    https://docs.pytest.org/en/latest/example/markers.html#reading-markers-which-were-set-from-multiple-places

    # content of conftest.py
    import sys
    
    
    def pytest_runtest_setup(item):
        for mark in item.iter_markers(name="glob"):
            print("glob args={} kwargs={}".format(mark.args, mark.kwargs))
            sys.stdout.flush()
    
        3
  •  -2
  •   N. C-J F.    6 年前

    在一个非常简单的测试中,使用 pytest version 4.6.3 .在搜索时,我发现了这个 link 我在这里找到了下面的建议并付诸实施。

    pip install pytest==3.10.1

    它马上就起作用了。 我认为这应该是@Messa在他的回答中提到的变化的结果。