【发布时间】:2019-08-05 12:34:57
【问题描述】:
我正在尝试模拟 python3 requests
这是我的单元测试:
from source.automation.my_web_session import MyWebSession
from unittest.mock import patch
@patch('requests.Session', autospec=True)
def test_initialize_session(mock_session):
# Arrange
user_agent = 'mobile user agent'
mock_session.headers = {'user-agent' : user_agent}
csrftoken = 'csrftoken'
mock_session.cookies = {'csrftoken' : csrftoken}
my_web_session = MyWebSession()
# Act
print(my_web_session.session.cookies)
# Assert
assert my_web_session.session.cookies['csrftoken'] == csrftoken
这是我正在测试的课程:
import requests
class MyWebSession:
def __init__(self):
self.session = requests.Session()
我正在尝试模拟用户代理的设置和更新。但是,运行我的测试时出现以下错误:
================================== FAILURES ===================================
___________________________ test_initialize_session ___________________________
mock_session = <MagicMock name='Session' spec='Session' id='81084944'>
@patch('requests.Session', autospec=True)
def test_initialize_session(mock_session):
# Arrange
user_agent = 'mobile user agent'
mock_session.headers = {'user-agent' : user_agent}
csrftoken = 'csrftoken'
mock_session.cookies = {'csrftoken' : csrftoken}
my_web_session = MyWebSession()
# Act
> print(my_web_session.session.cookies)
my_web_session_test.py:14:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
self = <NonCallableMagicMock name='Session()' spec='Session' id='80148752'>
name = 'cookies'
def __getattr__(self, name):
if name in {'_mock_methods', '_mock_unsafe'}:
raise AttributeError(name)
elif self._mock_methods is not None:
if name not in self._mock_methods or name in _all_magics:
> raise AttributeError("Mock object has no attribute %r" % name)
E AttributeError: Mock object has no attribute 'cookies'
我在这里做错了什么?
【问题讨论】:
-
哪里出错了?
-
我已经用完整的回溯编辑了 OP。
-
添加
mocked_session.headers = {}。 -
执行
mocked_session.headers = {'user-agent':'some_user_agent'}有效...但是为什么呢? -
因为现在
mocked_session确实有一个属性headers。
标签: python unit-testing mocking python-requests