我试图在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'对象没有属性'content'
设置get
请求的return_value
的正确方法是什么,这样我就可以测试post
请求的参数了?你知道吗
我认为您几乎已经拥有了它,只是缺少了
session()
的返回值—因为session
被实例化以创建client
实例。我想你也可以放下[0]
。你知道吗尝试:
尝试使用.text,因为这应该适用于字符串。你知道吗
http://docs.python-requests.org/en/master/user/advanced/
相关问题 更多 >
编程相关推荐