【问题标题】:How to mock external servers in Python unit tests?如何在 Python 单元测试中模拟外部服务器?
【发布时间】:2011-04-06 10:53:33
【问题描述】:

由于调用外部服务(Twitter、Facebook、Klout 等),我有几个单元测试需要很长时间(几分钟)

我想缓存这些服务的结果并以透明方式提供它们,同时对我当前的测试进行最小的更改。缓存键取决于 URL、查询参数、标头等,因此相当复杂。

最好的方法是什么?

【问题讨论】:

    标签: python unit-testing mocking


    【解决方案1】:

    您通常会(应该)使用某种适配器来连接到这些外部服务、模块。这些是您与外界的接口,可以是mocked,并根据场景创建虚假响应。

    我尝试了许多模拟库,最后发现Mock 是最适合我的。

    【讨论】:

      【解决方案2】:

      这是代码,我们使用请求库来调用外部 API。因此,我们使用模拟请求对象创建上下文处理器。

      因此,如果我们正在测试 get_data 函数,这将是我们模拟对外部 API 的请求的方式:

      import requests
      import mock
      import unittest
      
      
      def get_data(url):
          resp = requests.get(url)
          return resp
      
      class GetDataTest(unittest.TestCase):
      
          def test_get_data(self):
              with mock.patch.object(requests, 'get') as get_mock:
                  get_mock.return_value = mock_response = mock.Mock()
                  mock_response.status_code = 200
                  mock_response.content = {'twitter_handle': '@twitter'}
                  resp = get_data("http://this_address_does_not_exist.com")
                  self.assertEqual(resp.status_code, 200)
                  self.assertEqual(resp.content['twitter_handle'], '@twitter')
      

      【讨论】:

        【解决方案3】:

        从技术上讲,如果它使用外部服务,则它不是单元测试,而是集成测试。对于单元测试并加快您的测试代码,请使用模拟对象。您可以在此处找到有关 python 模拟对象的详细信息:
        http://python-mock.sourceforge.net/

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2023-03-23
          • 1970-01-01
          • 1970-01-01
          • 2021-09-18
          • 2016-10-28
          • 1970-01-01
          • 2020-10-27
          相关资源
          最近更新 更多