如何在单元测试中设置get请求的返回值?

时间:2019-01-15 17:39:05

标签: python django unit-testing mocking

我正在尝试在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'

设置return_value请求的get以便我可以测试post请求的参数的正确方法是什么?

2 个答案:

答案 0 :(得分:2)

我想您几乎拥有了它,只是您缺少了session()的返回值-因为实例化了session来创建client实例。我想您也可以放下[0]

尝试:

mock_sess.return_value.get.return_value.content = 'User1'

答案 1 :(得分:0)

尝试使用.text,因为它适用于字符串。

s = requests.Session()

s.get('https://httpbin.org/cookies/         set/sessioncookie/123456789')
r = s.get('https://httpbin.org/    cookies')

print(r.text)

http://docs.python-requests.org/en/master/user/advanced/