繁体   English   中英

定制 pytest 采集测试

[英]Customize pytest collecting tests

我想避免在类和函数名称中使用“test”前缀,并实现我自己的测试参数化模式。 我做了下一个代码 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”会为 function“some_global_test”创建测试,但不会为 function“some_global_test”执行钩子“pytest_generate_tests”。

我找到了一个解决方案,从我的钩子中调用collector._genfunctions(name, obj) 但我认为这不是正确的决定,因为_genfunctions是私有方法并且未声明。

还有其他方法可以解决我的任务吗?

如果您只想更改测试的前缀,您可以在pytest.ini设置自定义python_functionspython_classes选项。

欲了解更多信息,请点击链接

所以,没有人知道答案,我决定提供我的解决方案(它可能对其他人有用):

    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__来检测鼻子测试,因此您可以使用鼻子库或仅使用此类基础 class 和装饰器。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM