Skip to content Skip to sidebar Skip to footer

How To Mock Session In Python's Request Library?

I have been trying to figure out how exactly to mock the session of Python's request library but couldn't find a solution till now. Here's my code of common.py that i need to write

Solution 1:

Just mock the whole _request_url function, and not bother with the session object. All that the function does is provide a response object, mock that function and return a mock response object.

However, if you are testing the _request_url function itself, then just mock the session name; the additional calls will all be passed to the mock. You can then provide a response object of your choosing for the mocked.return_value.rquest.return_value object.

So

from unittest import mock

with mock.patch('requests.session') as mock_session:
    session_instance = mock_session.return_value
    mock_response = session_instance.request.return_value

    response = _request_url('METHOD', 'some url')

    assert response is mock_response
    session_instance.mount.assert_called()
    session_instance.request.assert_called_with('METHOD', 'some url')

or in a TestCase method:

@mock.patch('requests.session')deftest_request_url(self,  mock_session):
    session_instance = mock_session.return_value
    mock_response = session_instance.request.return_value

    response = _request_url('METHOD', 'some url')

    self.assertTrue(response is mock_response)
    session_instance.mount.assert_called()
    session_instance.request.assert_called_with('METHOD', 'some url')

Demo:

>>>from unittest import mock>>>import requests, ssl>>>classTlsAdapter:...# mocked adapter, just for illustration purposes...def__init__(self, *args, **kwargs): pass...>>>def_request_url(method, url):...    session = requests.session()...    adapter = TlsAdapter(ssl.OP_NO_TLSv1 | ssl.OP_NO_TLSv1_1)...    session.mount("https://", adapter)...return session.request(method, url)...>>>with mock.patch('requests.session') as mock_session:...    session_instance = mock_session.return_value...    mock_response = session_instance.request.return_value...    response = _request_url('METHOD', 'some url')...assert response is mock_response...    session_instance.mount.assert_called()...    session_instance.request.assert_called_with('METHOD', 'some url')...>>># nothing happened, because the test passed, no assertion errors were raised...

Post a Comment for "How To Mock Session In Python's Request Library?"