我想避免在类和函数名称中使用“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
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__))
在这种情况下,钩子(Hook)“pytest_pycollect_makeitem”为函数“some_global_test”创建测试,但钩子(Hook)“pytest_generate_tests”不会为函数“some_global_test”执行。
我找到了一个解决方案,从我的钩子(Hook)中调用collector._genfunctions(name, obj)
。但我认为这不是正确的决定,因为 _genfunctions
是一个私有(private)方法并且未声明。
还有其他方法可以解决我的任务吗?
最佳答案
所以,没有人知道答案,我决定提供我的解决方案(对其他人可能有用):
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使用属性__test__
来检测nose-tests,所以你可以使用nose-library或者只使用这样的基类和装饰器。
关于python - 自定义 pytest 收集测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58451128/