问题 如何在Python单元测试中模拟外部服务器?


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

我想缓存这些服务的结果并透明地提供它们,对我当前的测试进行最小的更改。缓存键取决于URL,查询参数,标题等,因此它非常复杂。

最好的方法是什么?


11768
2018-04-06 10:53


起源



答案:


您(应该)通常会使用某种适配器来连接这些外部服务模块。这些是你与外界的接口,也可以 嘲笑根据场景创建的ed和假响应。

我已经尝试了一些模拟库,终于找到了 嘲笑 成为最适合我的人。


9
2018-04-06 13:21



为模拟+1。我也认为这是我尝试过的最好的。 - Dan


答案:


您(应该)通常会使用某种适配器来连接这些外部服务模块。这些是你与外界的接口,也可以 嘲笑根据场景创建的ed和假响应。

我已经尝试了一些模拟库,终于找到了 嘲笑 成为最适合我的人。


9
2018-04-06 13:21



为模拟+1。我也认为这是我尝试过的最好的。 - Dan


继承代码,我们使用请求库来调用外部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
2017-08-21 12:49





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


2
2018-04-06 11:03