3

I have a code which I am trying to test using Mock library/python-django. To give brief summary of my application is:

(PHASE I): Client use my app exposed API. The mapped API function make a HTTP Connection request to 3rd party API ( Tropo which are CaaS provider)

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


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.

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.

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. 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?

Anuj
  • 533
  • 1
  • 7
  • 14
  • No one has an idea on how to solve this type of issues ? – Anuj Dec 20 '12 at 21:56
  • Here is something might be helpful for your case - http://stackoverflow.com/questions/295438/how-can-one-mock-stub-python-module-like-urllib – Mutant Mar 01 '13 at 00:21

1 Answers1

0

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. Please let me know if any QA have better solution to this type of problem

Anuj
  • 533
  • 1
  • 7
  • 14