【问题标题】:How to set the return value of a get request in an unit test?如何在单元测试中设置get请求的返回值?
【发布时间】: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


【解决方案1】:

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

试试:

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

【讨论】:

  • 嗯...那次失踪return_value 花了我几个小时。
【解决方案2】:

尝试使用 .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/

【讨论】:

    猜你喜欢
    • 2021-04-25
    • 2016-03-17
    • 2021-10-25
    • 1970-01-01
    • 2020-04-17
    • 2018-09-02
    • 2019-06-30
    • 2016-12-25
    • 1970-01-01
    相关资源
    最近更新 更多