Reputation:
Session.cookies
is defined inside the Session constructor and thus I can't mock it. Is there any way to mock it?
from requests import Session
from settings import URL
from unittest.mock import patch
@patch.object(Session, 'cookies', new='my custom mock object')
def test_request():
assert function_that_uses_request_cookies()
This raises AttributeError: <class 'requests.sessions.Session'> does not have the attribute 'cookies'
If session
instance was defined on the module scope, I could patch the session
instance directly. But session
is defined only on function_that_uses_request_cookies
scope. Is there any way to patch the instance inside the function scope?
Upvotes: 1
Views: 1828
Reputation: 2529
As written, the code will patch an attribute of the Session
class, but what you want to do is patch an attribute of a Session
instance. To do this without interrupting other aspects of session behaviour, you can create a mock object that wraps Session
.
def test_request():
mock_session_klass = MagicMock(wraps=Session)
with patch('requests.Session', new=mock_session_klass):
session_instance = mock_session_klass.return_value
session_instance.cookies.return_value = 'my custom mock object'
assert function_that_uses_request_cookies()
Upvotes: 1