pytest夹具用于检查调用函数

3 投票
2 回答
2374 浏览
提问于 2025-04-18 11:39

我有一个测试类和一个设置函数,代码大概是这样的:

@pytest.fixture(autouse=True, scope='function')
def setup(self, request):
    self.client = MyClass()
    first_patcher = patch('myclass.myclass.function_to_patch')
    first_mock = first_patcher.start()
    first_mock.return_value = 'foo'
    value_to_return = getattr(request, 'value_name', None)
    second_patcher = patch('myclass.myclass.function_two')
    second_mock = second_patcher.start()
    second_mock.return_value = value_to_return
    #could clean up my mocks here, but don't care right now

我在pytest的文档中看到,可以对模块级别的值进行检查,比如可以用下面的方式获取:

val = getattr(request.module, 'val_name', None)

但是,我想根据我正在进行的测试,返回不同的值。所以我在寻找一种方法,可以检查测试函数,而不是测试模块。

http://pytest.org/latest/fixture.html#fixtures-can-introspect-the-requesting-test-context

2 个回答

0

也许自从接受的答案发布以来,文档内容已经发生了变化。至少对我来说,如何操作并不清楚。

只需跟着链接走。

所以我想更新一下这个讨论,直接提供链接:

https://pytest.org/en/6.2.x/reference.html#request

编辑于2021年12月

即使现在链接是正确的,我觉得pytest文档中的这句话其实是不准确的:

Fixture函数可以接受请求对象,以便检查“请求”这个fixture的测试函数……

虽然我找到了获取模块属性的一些例子,但我没有找到一个可以正常工作的例子来检查请求这个fixture的测试函数。这可能与收集和运行顺序有关。

真正帮助我实现想要的功能的是在pytest文档中稍后提到的工厂模式:

https://pytest.org/en/6.2.x/fixture.html#factories-as-fixtures

设置fixture工厂

@pytest.fixture(scope='function')
def getQueryResult() -> object:
    def _impl(_mrId: int = 7622):
        return QueryResult(_mrId)

    return _impl

用法

# Concrete value
def test_foo(getQueryResult):
    queryResult = getQueryResult(4711)
    ...

# Default value
def test_bar(getQueryResult):
    queryResult = getQueryResult()
    ...
5

你可以用 request.function 来访问测试函数。只需点击你提到的网页上的链接,就能看到测试 request 对象上有哪些可用的内容哦 :)

撰写回答