問題描述
我一直在嘗試找到一種同時使用模擬裝飾器和 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
注冊的外部夾具,因此只需將其指定為參數(shù)即可使用.無需導入requests-mock
,只需要安裝并指定參數(shù)requests_mock
.
pytest
has its own method of registering and loading custom fixtures.requests-mock
provides an external fixture registered withpytest
such that it is usable simply by specifying it as a parameter. There is no need to importrequests-mock
it simply needs to be installed and specify the argumentrequests_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
不能與向測試函數(shù)添加位置參數(shù)的函數(shù)裝飾器一起使用.pytest
考慮所有參數(shù)
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
模擬
被替換為夾具值,如果沒有找到適合任何參數(shù)的夾具,則會失敗.所以像
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
已經(jīng)提供了一個fixture,為什么還要使用裝飾器呢?
but since requests-mock
already offers a fixture, why bother using the decorator?
這篇關于如何在具有模擬裝飾器的測試中使用 pytest capsys?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!