多次调用的 pytest 模拟响应

pytest mock response with multiple calls

我正在尝试模拟 api 调用的响应,但在我的一个函数中,我有两个单独的 api 调用,我只想模拟一个。下面是代码,我只想模拟我的第二个 api 调用

apicall.py

def call_api():
    response_of_api1_to_get_token = request.post() # some url to post 1st. DO Not Mock this
    response_of_api2 = request.post() # some url to post 2nd api, i want to mock this
    
# test.py

import pytest
import requests_mock
from requests.exceptions import HTTPError
from apicall import call_api

def test_some_func():
    with requests_mock.mock() as m:
        m.get(requests_mock.ANY, status_code=500, text='some error')

        with pytest.raises(HTTPError):
            # You cannot make any assertion on the result
            # because some_func raises an exception and
            # wouldn't return anything
            call_api(a="a", b="b") # here it mock my first api

我是否可以避免模拟第一次 api 调用并在第二次 api 调用中进行模拟?

您可以将 real_http=True 传递给 Mocker 的 init 调用。这将导致仅模拟您已为其注册 URL 的请求。在下面的示例中,对 test.com 的请求将被模拟,对 google.com 的请求将不会被模拟。

import requests
import requests_mock
with requests_mock.Mocker(real_http=True) as m:
    m.get('http://test.com', text='resp')
    requests.get('http://test.com').text
    requests.get('https://www.google.com').text