I am trying to mock the response of api call but in my one function i have two seperate api call and i want to mock only one. below is the code and i want o mock only my second api call
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
is there anyway i can avoid mocking 1st api call and do mock on 2nd api call?
CodePudding user response:
You can pass in real_http=True
to the Mocker's init call. This will result in only mocking the requests that you have registered a URL for. In the example below, the request to test.com will be mocked, the one to google.com will not be mocked.
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