使用Mock for third party API进行Django/Python测试

2024-06-16 12:04:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个代码,我正试图用Mock library/pythondjango测试它。对我的申请作一个简短的总结是:

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

(第二阶段):Tropo服务器(第三方)用一些url返回到我的服务器,我将其映射到向Tropo服务器发送另一个请求的函数,对phonenumbers进行call()。在


我使用了Django测试客户机,只使用了我的API,但问题是它也在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()

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


Tags: 函数代码服务器框架apijson编码application
1条回答
网友
1楼 · 发布于 2024-06-16 12:04:35

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

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得到的响应,并将其传递给函数。请让我知道,如果任何质量保证有更好的解决这类问题的办法

相关问题 更多 >