[英]Customize pytest collecting tests
I would like to avoid using the "test" prefix in classes and functions names and implement my own schema of the test parametrization.我想避免在类和函数名称中使用“test”前缀,并实现我自己的测试参数化模式。 I did the next code test.py
我做了下一个代码 test.py
import pytest
# class for inheritance to avoid "Test" prefix
class AtsClass:
__ATS_TEST_CLASS__ = True
# decorator to mark functions as tests (to avoid "Test" prefix)
def ats_test(f):
setattr(f, "__ATS_TEST_CLASS__", True)
return f
def test_1():
pass
@ats_test
def some_global_test():
pass
class MyClass(AtsClass):
def test_4(self):
pass
@ats_test
def some_func(self):
pass
conftest.py conftest.py
import pytest
import inspect
# @pytest.hookimpl(hookwrapper=True)
def pytest_pycollect_makeitem(collector, name, obj):
# outcome = yield
# res = outcome.get_result()
if inspect.isclass(obj) and obj.__name__ != "AtsClass" and hasattr(obj, "__ATS_TEST_CLASS__") and obj.__ATS_TEST_CLASS__ == 1:
print("WE HAVE FOUND OUR CLASS")
return pytest.Class(name, parent=collector)
# outcome.force_result(pytest.Class(name, parent=collector))
if inspect.isfunction(obj) and hasattr(obj, "__ATS_TEST_CLASS__") and obj.__ATS_TEST_CLASS__ == 1:
print("WE HAVE FOUND OUR FUNCTION")
return pytest.Function(name, parent=collector)
# outcome.force_result([pytest.Function(name, parent=collector)])
def pytest_generate_tests(metafunc):
print("-->Generate: {}".format(metafunc.function.__name__))
In this case hook "pytest_pycollect_makeitem" creates test for function "some_global_test", but hook "pytest_generate_tests" is not executed for function "some_global_test".在这种情况下,钩子“pytest_pycollect_makeitem”会为 function“some_global_test”创建测试,但不会为 function“some_global_test”执行钩子“pytest_generate_tests”。
I have found a solution, call collector._genfunctions(name, obj)
from my hook.我找到了一个解决方案,从我的钩子中调用
collector._genfunctions(name, obj)
。 But I think it is not the right decision, cause _genfunctions
is a private method and not declared.但我认为这不是正确的决定,因为
_genfunctions
是私有方法并且未声明。
Is there another way to solve my task?还有其他方法可以解决我的任务吗?
So, nobody knows the answer and I decided to offer my solution (it can be useful for others):所以,没有人知道答案,我决定提供我的解决方案(它可能对其他人有用):
class TestBaseClass:
__test__ = True
def mark_test(f):
setattr(f, "__test__", True)
return f
# using base class and decorator
class MyTestClass(TestBaseClass):
@mark_test
def some_func(self):
pass
Pytest uses attribute __test__
to detect nose-tests, so you can use nose-library or just use such base class and decorator. Pytest 使用属性
__test__
来检测鼻子测试,因此您可以使用鼻子库或仅使用此类基础 class 和装饰器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.