繁体   English   中英

如何使用Mock @patch获取呼叫计数?

[英]How to get the call count using Mock @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函数的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对返回的对象进行进一步的声明。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM