【发布时间】:2019-01-15 17:39:04
【问题描述】:
我正在尝试在 python 中设置get 请求的返回值,以便进行单元测试,该测试测试是否使用正确的参数调用post 请求。假设我有以下代码要测试
# main.py
import requests
from django.contrib.auth.models import User
def function_with_get():
client = requests.session()
some_data = str(client.get('https://cool_site.com').content)
return some_data
def function_to_test(data):
for user in User.objects.all():
if user.username in data:
post_data = dict(data=user.username)
else:
post_data = dict(data='Not found')
client.post('https://not_cool_site.com', data=post_data)
#test.py
from unittest import mock
from unittest import TestCase
from main import function_with_get, function_to_test
class Testing(TestCase):
@mock.patch('main.requests.session')
def test_which_fails_because_of_get(self, mock_sess):
mock_sess.get[0].return_value.content = 'User1'
data = function_with_get()
function_to_test(data)
assertIn('Not Found', mock_sess.retrun_value.post.call_args_list[1])
遗憾的是,这不起作用,我也尝试在没有 content 的情况下设置它,但是,我收到错误 AttributeError: 'str' object has no attribute 'content'
设置get 请求的return_value 的正确方法是什么,以便我可以测试post 请求的参数?
【问题讨论】:
-
你试过没有
[0]吗?如果您想多次获取不同的结果,请查看side_effect并创建您自己的 MagicMocks。 -
删除
[0]并没有帮助。
标签: python django unit-testing mocking