简体   繁体   中英

Mock cookies attribute of requests.session

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?

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM