【问题标题】:Customize pytest collecting tests自定义 pytest 收集测试
【发布时间】: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 进行匹配,但我猜你已经知道并且不想使用他们?
  • 是的,我不想使用任何前缀,我想实现自己的架构。

标签: python pytest


【解决方案1】:

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

    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 或者只使用这样的基类和装饰器。

【讨论】:

    【解决方案2】:

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

    如需了解更多信息,请关注link

    【讨论】:

    • 不,我不想使用任何前缀。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-09
    • 1970-01-01
    相关资源
    最近更新 更多