Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

pytest mock response with multiple calls

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading