如何使用模拟@patch获取呼叫计数



我正在为我们正在处理的某个库编写单元测试。此库利用requests.post()对外部服务器执行 POST HTTP 请求。

在我的UT中,我显然不想联系真正的服务器,而是嘲笑响应。

为此,我编写了一个函数

,如下所示:
def mocked_post(url, headers, data, **kwargs):
    response = Mock()
    # Some logic, irrelevant here.
    return response

我在我的单元测试类周围修补了这个函数:

@patch('mylib.requests.post', mocked_post)
class MyTest(TestCase):
    def test_foo(self):
        # Some test logic

这工作得很好。

现在我想获取对我的模拟函数的调用次数。我试过mocked_post.call_count但这不存在。我试图在许多不同的对象(包括mylib.requests.post)上找到此属性,但到目前为止没有运气。

如何访问此模拟函数的call_count

我不会在这里使用mocked_post作为new参数。我会设置新Mockside_effect属性:

@patch('mylib.requests.post')
class MyTest(TestCase):
    def test_foo(self, post_mock):
        post_mock.side_effect = mocked_post
        # Some test logic
        self.assertEqual(post_mock.call_count, 3)

现在,您有了patch为您生成的Mock对象,作为所有测试方法的参数,因此您可以测试该模拟被调用了多少次。

您还应该能够在装饰器中设置 side_effect 属性,以应用于所有测试:

@patch('mylib.requests.post', side_effect=mocked_post)
class MyTest(TestCase):
    def test_foo(self, post_mock):
        # Some test logic
        self.assertEqual(post_mock.call_count, 3)

但是,您仍然无法访问返回的response对象;您可能希望从mocked_post返回mock.DEFAULT,而不是在函数中创建,以便您可以使用post_mock.return_value对返回的对象进行进一步的断言。

9年后到来,但你也可以做:

   @patch('mylib.requests.post')
   class MyTest(TestCase):
      def test_foo(self, post_mock):
        # Some test logic
        assert post_mock.call_count == 3
        #if you need to mock the return value
        post_mock.return_value = "success"

最新更新