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



我有一个代码,我正在尝试使用Mock library/python-django进行测试。简要总结一下我的申请是:

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

(第二阶段):Tropo服务器(第三方)用一些URL响应我的服务器,我映射到的功能向Tropo服务器发送另一个请求,在他们这边,向电话号码发出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 获得的响应进行硬编码并传递给函数。如果有任何QA对此类问题有更好的解决方案,请告诉我

最新更新