py.test:可以在测试功能级别应用多个标记吗?

hpn*_*hpn 8 python markers pytest

我从pytest文档中看到,我们可以在类或模块级别一次应用多个标记.我没有找到在测试功能级别执行此操作的文档.有没有人在成功之前做过这件事?

我想在理想情况下将此作为标记列表,例如在上面的类文档中完成(例如,引用文档):

class TestClass:
    pytestmark = [pytest.mark.webtest, pytest.mark.slowtest]
Run Code Online (Sandbox Code Playgroud)

因此,pytest文档讨论了如何pytestmark在类和模块级别指定标记.但是,它没有谈到在测试功能级别上有类似的东西.我必须在测试函数之上单独指定标记,以便用它们中的每一个标记它们.这使得测试代码在测试函数之上越来越多的标记看起来有点笨拙.

test_example.py:

pytestmark = [class1, class2]

class TestFeature(TestCase):

    @pytest.mark.marker1
    @pytest.mark.marker2
    @pytest.mark.marker3
    def test_function(self):
        assert True
Run Code Online (Sandbox Code Playgroud)

Suo*_*uor 9

对于函数,您只需重复装饰器:

@pytest.mark.webtest
@pytest.mark.slowtest
def test_something(...):
    ...
Run Code Online (Sandbox Code Playgroud)

如果你想为多个测试重用它,你应该记住装饰器只是返回装饰物的函数,所以几个装饰器只是一个组合:

def compose_decos(decos):
    def composition(func):
        for deco in reversed(decos):
            func = deco(func)
        return func
    return composition

all_marks = compose_decos(pytest.mark.webtest, pytest.mark.slowtest)

@all_marks
def test_something(...):
    ...
Run Code Online (Sandbox Code Playgroud)

或者您可以使用通用组合,例如我的funcy库具有:

from funcy import compose

all_marks = compose(pytest.mark.webtest, pytest.mark.slowtest)
Run Code Online (Sandbox Code Playgroud)

请注意,通过这种方式,您可以组合任何装饰器,而不仅仅是pytest标记.