gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 20:27:06 25 4
gpt4 key购买 nike

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

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's docs 中所述:

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.

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 fixture 而不是装饰器:

def test_with_mock_and_capsys(requests_mock, capsys):
pass

背景

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

  • 不像在实例或类方法中那样绑定(bind)到实例或类型;
  • 没有默认值;
  • 不受functools.partial的约束;
  • 不会被替换为 unittest.mock 模拟

被 fixture 值替换,如果它没有为任何参数找到合适的 fixture 将会失败。所以像

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 传递模拟程序:

import pytest
import requests_mock


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

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

关于python - 如何在具有模拟装饰器的测试中使用 pytest capsys?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52060950/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com