猿问

requests.session 的模拟 cookie 属性

Session.cookies是在 Session 构造函数中定义的,因此我无法模拟它。有什么办法可以嘲笑它吗?


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

这引发 AttributeError: <class 'requests.sessions.Session'> does not have the attribute 'cookies'


如果session在模块作用域上定义了session实例,我可以直接修补实例。但session仅在function_that_uses_request_cookies范围上定义。有没有办法修补函数作用域内的实例?


桃花长相依
浏览 181回答 1
1回答

泛舟湖上清波郎朗

如所写,代码将修补Session类的属性,但您要做的是修补Session实例的属性。要在不中断会话行为的其他方面做到这一点,您可以创建一个模拟对象,将Session.def test_request():&nbsp; &nbsp; mock_session_klass = MagicMock(wraps=Session)&nbsp; &nbsp; with patch('requests.Session', new=mock_session_klass):&nbsp; &nbsp; &nbsp; &nbsp; session_instance = mock_session_klass.return_value&nbsp; &nbsp; &nbsp; &nbsp; session_instance.cookies.return_value = 'my custom mock object'&nbsp; &nbsp; &nbsp; &nbsp; assert function_that_uses_request_cookies()
随时随地看视频慕课网APP

相关分类

Python
我要回答