py.test :可以在测试函数级别应用多个标记吗? [英] py.test : Can multiple markers be applied at the test function level?
问题描述
我从 pytest 文档 中看到,我们可以一次应用多个标记类或模块级别.我没有找到在测试功能级别执行此操作的文档.有没有人成功地做到了这一点?
I have seen from the pytest docs that we can apply multiple markers at once on the Class or module level. I didn't find documentation for doing it at the test function level. Has anybody done this before with success?
我想在理想情况下将其作为标记列表来执行,例如在上面的类文档中完成的操作(引用自文档):
I would like to ideally do this as a list of markers as being done in the above doc for Classes, for example (quoting from the docs):
class TestClass:
pytestmark = [pytest.mark.webtest, pytest.mark.slowtest]
因此,pytest 文档讨论了使用 pytestmark
在类和模块级别指定标记.但是,它没有谈论在测试功能级别有类似的东西.我必须在测试函数之上单独指定标记,以便用它们中的每一个标记它们.随着测试函数顶部标记数量的增加,这使得测试代码看起来有点笨拙.
So, the pytest documentation talks about using pytestmark
to specify the markers at the class and module level. However, it doesn't talk about having something similar at the test function level. I would have to specify the markers individually on top of test functions to get them marked with each one of them. This makes the test code look a little clunky with the increasing number of markers on top of test functions.
test_example.py:
test_example.py:
pytestmark = [class1, class2]
class TestFeature(TestCase):
@pytest.mark.marker1
@pytest.mark.marker2
@pytest.mark.marker3
def test_function(self):
assert True
推荐答案
对于函数,你只需重复装饰器:
For functions you just repeat the decorator:
@pytest.mark.webtest
@pytest.mark.slowtest
def test_something(...):
...
如果你想在多个测试中重用它,你应该记住装饰器只是返回装饰物的函数,所以几个装饰器只是一个组合:
If you want to reuse that for several tests you should remember that decorators are just functions returning decorated thing, so several decorators is just a composition:
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(...):
...
或者您可以使用通用组合,例如我的 funcy 库:
Or you can use general purpose composition such as my funcy library has:
from funcy import compose
all_marks = compose(pytest.mark.webtest, pytest.mark.slowtest)
请注意,通过这种方式,您可以组合任何装饰器,而不仅仅是 pytest 标记.
Note that this way you can compose any decorators, not only pytest marks.
这篇关于py.test :可以在测试函数级别应用多个标记吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!