我有一个代码正在尝试使用Mock库/ python-django测试。简要介绍一下我的申请是:

(第一阶段):客户端使用我的应用程序公开的API。映射的API函数向第三方API(作为CaaS提供程序的Tropo)发出HTTP连接请求

(第二阶段):Tropo服务器(第3方)以一些URL返回给我,该地址映射到我的服务器,该服务器映射到函数,该函数向Tropo Server发送另一个请求,然后在他们这边,将call()设置为电话号码。



我只是通过使用可以运行的API来使用Django测试客户端,但问题是它还会在Tropo上进行回复,以对所输入的数字进行真正的调用。因此,我想到了使用mock()库,但对此却知之甚少。

我所做的是,我看到第一阶段从Tropo收到的响应是在变量input中对其进行硬编码的,我也有expected_output变量,也看到第二阶段之后的输出也进行了硬编码。

但是我想适当地构建我的测试框架,在该框架中,我可以在测试环境中模拟整个tropo库,并且所有请求都传递给该假库而不是真正的tropo。但不要更改代码。

任何想法或建议。因为我是开发人员,所以请裸露我,这是我尝试进行测试的内容。

由于我没有收到任何回应,因此我试图提供我所坚持的具体细节:

让我们在一个函数中说一下我的代码片段...

conn     = httplib.HTTPConnection('Some_External_URI')

    headers = {"accept": "application/json", "Content-type":"application/json"}
    params  = ''

    conn.request('POST', data, params, headers)

    response  = conn.getresponse()
    payload   = response.read()


如何模拟这个特定的连接请求?

最佳答案

通过在代码中模拟类,我可以达到某种程度的测试。

test.py

    from mock import patch, MagicMock
    from tropo.conferencing import TropoConferencing

    @patch.object(TropoConferencing, 'sendTriggerCallRequest')
    def test_ConferenceCreation(self, sendTriggerCallRequest):
        response_conference = self._createConference(sendTriggerCallRequest)
        self.assertContains(response_conference, 200)

   def _createConference(self, sendTriggerCallRequest):
        self._twoParticipants_PhaseI(sendTriggerCallRequest)

        response_conference = self.client.post(self.const.create_conferenceApi , {'title':self.const.title,'participants':self.const.participants})
        obj = json.loads(response_conference.content)
        self.conf_id =  obj['details']['conference_id']

        try:
            conference_id =  Conference.objects.get(conferenceId=self.conf_id)
        except Conference.DoesNotExist:
            print 'Conference not found'

        # PHASE II
        self._twoParticipants_PhaseII()

        return response_conference

    def _twoParticipants_PhaseI(self, sendTriggerCallRequest):
        list_of_return_values= [{'json': {'session_id': 'e85ea1229f2dd02c7d7534c2a4392b32', 'address': u'xxxxxxxxx'}, 'response': True},
                            {'json': {'session_id': 'e72bf728d4de2aa039f39843097de14f', 'address': u'xxxxxxxx'}, 'response': True}
                            ]
        def side_effect(*args, **kwargs):
            return list_of_return_values.pop()

        sendTriggerCallRequest.side_effect = side_effect

    def _twoParticipants_PhaseII(self):

        input           = {"session":{"id":"e72bf728d4de2aa039f39843097de14f","accountId":"xxxxx","timestamp":"2013-01-07T18:32:20.905Z","userType":"NONE","initialText":'null',"callId":'null',"parameters":{"phonenumber":"xxxxxxx","action":"create","conference_id":str(self.conf_id),"format":"form"}}}
        expectedOutput  = '{"tropo": [{"call": {"to": "xxxxxxx", "allowSignals": "exit", "from": "xxxxxxx", "timeout": 60}}, {"ask": {"name": "join_conference", "say": {"value": "Please press one to join conference"}, "choices": {"terminator": "*", "value": "1", "mode": "dtmf"}, "attempts": 1, "timeout": 5, "voice": "Susan"}}, {"on": {"event": "mute", "next": "' + self.const.muteEvent+ str(self.conf_id) + '/xxxxxx"}}, {"on": {"event": "unmute", "next": "/conference/rest/v1/conference/events/unmute/'+ str(self.conf_id) + '/xxxxxxx"}}, {"on": {"event": "hangup", "next": "'+ str(self.conf_id) + '/xxxxxx"}}, {"on": {"event": "continue", "next": "'+ str(self.conf_id) + '/xxxxxx"}}, {"on": {"event": "exit", "next": "'+ str(self.conf_id) + '/xxxxxx"}}, {"on": {"event": "error", "next": "/conference/rest/v1/conference/events/hangup/'+ str(self.conf_id) + '/xxxxxxx"}}, {"on": {"event": "incomplete", "next": "'+ str(self.conf_id) + '/xxxxxxx"}}, {"say": {"value": ""}}]}'

        callbackPayload = json.dumps(input)
        request = MagicMock()
        request.raw_post_data = callbackPayload

        response = call(request)

        self.assertEqual(response.content, expectedOutput)


如您所见,我正在硬编码我从Tropo获得的响应并将其传递给函数。请让我知道是否有任何质量检查人员可以更好地解决此类问题

关于python - 使用Mock进行第三方API的Django/Python测试,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13964031/

10-11 23:39