简体   繁体   English

使用Mock进行第三方API的Django / Python测试

[英]Django/Python testing using Mock for third party API

I have a code which I am trying to test using Mock library/python-django. 我有一个代码正在尝试使用Mock库/ python-django测试。 To give brief summary of my application is: 简要介绍一下我的申请是:

(PHASE I): Client use my app exposed API. (第一阶段):客户端使用我的应用程序公开的API。 The mapped API function make a HTTP Connection request to 3rd party API ( Tropo which are CaaS provider) 映射的API函数向第三方API(作为CaaS提供程序的Tropo)发出HTTP连接请求

(PHASE II): Tropo server(3rd party) respond back with some url back to my server which I mapped to function which send another request to Tropo Server which on their side, make call() to phonenumbers. (第二阶段):Tropo服务器(第三方)以一些URL返回给我,该服务器映射到我映射到功能的服务器,该服务器向Tropo Server发送另一个请求,该请求在他们这边,使call()成为电话号码。


I used Django test client by just using my API which does run but the problem is it also reply on Tropo to make real call to the numbers I give in. So I thought to use mock() library but I have very little knowledge of it. 我只是通过使用可以运行的API来使用Django测试客户端,但问题是它还会在Tropo上进行回复,以真正调用我输入的数字。因此,我想到了使用mock()库,但对此却知之甚少。

What I did is, I see what response I get after first phase from Tropo hard coded it in variable input and I also have expected_output variable which is also hardcoded seeing the output after second phase. 我所做的是,我看到第一阶段从Tropo收到我的响应后,将其硬编码为变量input并且我也有expected_output变量,也看到第二阶段之后的输出也被硬编码。

But I want to architect my test framework properly in which I can mock the whole tropo library in my testing environment and all the request go to this fake library and not the real tropo. 但是我想适当地构建测试框架,在该框架中,我可以在测试环境中模拟整个tropo库,并且所有请求都转到该假库而不是真正的tropo。 But not changing the code. 但不要更改代码。

Any ideas or suggestion. 任何想法或建议。 Please bare me as I am developer and this is something I try to do for testing. 因为我是开发人员,所以请裸露我,这是我尝试进行测试的内容。

Since I am not getting any response I am trying to give more details of what exactly I am stuck in: 由于我没有收到任何回应,因此我试图提供我所坚持的具体细节:

Let say there this snippet of my code in one function... 让我们在一个函数中说一下我的代码片段...

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()

How I can mock this particular connection request? 如何模拟这个特定的连接请求?

I was able to reach at some level of testing by mocking class in my code. 通过在代码中模拟类,我可以达到某种程度的测试。

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)

As you can see I am hardcoding the response I get form Tropo and passing onto the function. 如您所见,我正在硬编码我从Tropo获得的响应并将其传递给函数。 Please let me know if any QA have better solution to this type of problem 请让我知道是否有任何质量检查人员可以更好地解决此类问题

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

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