【发布时间】:2019-11-05 21:37:20
【问题描述】:
我想避免在类和函数名称中使用“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__))
在这种情况下,钩子“pytest_pycollect_makeitem”为函数“some_global_test”创建测试,但钩子“pytest_generate_tests”没有为函数“some_global_test”执行。
我找到了解决方案,请从我的钩子中拨打collector._genfunctions(name, obj)。但我认为这不是正确的决定,因为_genfunctions 是一个私有方法并且没有声明。
还有其他方法可以解决我的任务吗?
【问题讨论】:
-
pytest仅包含测试函数/类,方法是将它们的名称与pytest_classes/python_files/python_functions中的 glob 进行匹配,但我猜你已经知道并且不想使用他们? -
是的,我不想使用任何前缀,我想实现自己的架构。