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

时间:2022-11-28
本文介绍了如何在具有模拟装饰器的测试中使用 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?

这篇关于如何在具有模拟装饰器的测试中使用 pytest capsys?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!

上一篇:在 Python 中模拟套接字连接 下一篇:我如何检查调用参数是否会随 unittest.mock 改变

相关文章

最新文章