如何在具有模拟装饰器的测试中使用 pytest capsys?

问题描述

我一直在尝试找到一种同时使用模拟装饰器和 pytest capsys 的方法,但我找不到正确的方法.

I have being trying to find a way to use mocking decorators and pytest capsys at the same time but I wasn't able to find the right way to do it.

import pytest
import requests_mock


@requests_mock.mock()
def test_with_mock(m):
    pass

def test_with_capsys(capsys):
    pass


# how to write a test that works with both?


解决方案

request-mock 的文档:

As stated in the request-mock's docs:

pytest 有自己的注册和加载自定义夹具的方法.requests-mock 提供了一个用 pytest 注册的外部夹具,因此只需将其指定为参数即可使用.无需导入requests-mock,只需要安装并指定参数requests_mock.

pytest has its own method of registering and loading custom fixtures. requests-mock provides an external fixture registered with pytest such that it is usable simply by specifying it as a parameter. There is no need to import requests-mock it simply needs to be installed and specify the argument requests_mock.

然后,fixture 提供与 requests_mock.Mocker 相同的接口,让您可以按预期使用 requests-mock.

The fixture then provides the same interface as the requests_mock.Mocker letting you use requests-mock as you would expect.

>>> import pytest
>>> import requests

>>> def test_url(requests_mock):
...     requests_mock.get('http://test.com', text='data')
...     assert 'data' == requests.get('http://test.com').text
...

所以只需使用 requests_mock 夹具而不是装饰器:

So just use the requests_mock fixture instead of the decorator:

def test_with_mock_and_capsys(requests_mock, capsys):
    pass

背景

pytest 不能与向测试函数添加位置参数的函数装饰器一起使用.pytest 考虑所有参数

Background

pytest doesn't play along with function decorators that add positional arguments to the test function. pytest considers all arguments that

  • 不像在实例或类方法中那样绑定到实例或类型;
  • 没有默认值;
  • 不与 functools.partial;
  • 绑定
  • 不替换为 unittest.mock 模拟

被替换为夹具值,如果没有找到适合任何参数的夹具,则会失败.所以像

to be replaced with fixture values, and will fail if it doesn't find a suitable fixture for any argument. So stuff like

import functools
import pytest


def deco(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        args += ('spam',)
        return func(*args, **kwargs)
    return wrapper


@deco
def test_spam(spam_arg):
    assert True

会失败,而这正是 requests-mock 所做的.一种解决方法是通过关键字 args 传递 mocker:

will fail, and this is exactly what requests-mock does. A workaround to that would be passing the mocker via keyword args:

import pytest
import requests_mock


@requests_mock.Mocker(kw='m')
def test_with_mock_and_fixtures(capsys, **kwargs):
    m = kwargs['m']
    ...

但是既然 requests-mock 已经提供了一个fixture,为什么还要使用装饰器呢?

but since requests-mock already offers a fixture, why bother using the decorator?

相关文章