如何从requests.session模拟get函数?

时间:2019-01-08 14:51:21

标签: python django mocking python-requests

我正在尝试模拟requests.session中的get函数,但最终还是没有发生。

我有以下代码:

#main.py
import requests

def function_with_get():

    c = requests.session()

    c.get('https://awesome_url.com')

    # do some other stuff

    return c

def second_function_with_get(client):
    c.get('https://awesome_url.com')

    # do some other stuff


#test.py
from unittest import mock
from django.test import TestCase

class Testing(TestCase):
    @mock.patch('main.requests.session.get)
    @mock.patch('main.requests.session)
    def test_which_fails_because_of_get(mock_sess, mock_get):
        client = function_with_get()
        second_function_with_get(client)

        assertEqual(mock_requests_session_get.call_count, 2)

测试抛出一个断言错误,称mock_get被调用0次(0 != 2

应如何嘲笑get的{​​{1}}函数?

1 个答案:

答案 0 :(得分:1)

似乎您已经在模拟请求会话-因为它是MagicMock,所以您不需要额外模拟get方法本身-检查会话上的调用就足够了。

因此,您的test.py可能如下所示:

#test.py
from unittest import mock
from unittest import TestCase

from main import function_with_get, second_function_with_get


class Testing(TestCase):
    @mock.patch('main.requests.session')
    def test_which_fails_because_of_get(self, mock_sess):
        client = function_with_get()
        second_function_with_get(client)

        self.assertEqual(mock_sess.return_value.get.call_count, 2)

您还可以尝试使用模拟SessionMock的方法来创建自己的get类,但是还需要为每个测试正确设置(或重置)该类。就个人而言,我通常会更轻松地使用MagicMock及其return_value链。