class CallGatewayTest(unittest.TestCase):
    """ Provides function coverage for CallGateway. """

    def setUp(self):
        self.AgentGateway = AgentGateway()
        self.CallGateway = CallGateway()
        self.agentToInsert = None
        self.ANI = "212555555" + str(random.randrange(9))
        self.createdCall = None
        self.activeCalls = []

    def tearDown(self):
        if self.agentToInsert:
            self.agentToInsert.delete()
        if self.createdCall:
            self.createdCall.delete()
        if len(self.activeCalls) > 0:
            for call in self.activeCalls:
                call.delete()

    def test_addCall(self):
        # calls need an agent
        self.agentToInsert = self.AgentGateway.registerAgentForServiceToday(self.ANI)

        self.createdCall = self.CallGateway.addCall(self.agentToInsert)

        self.assertEqual(self.createdCall.agent.ani, self.agentToInsert.ani)
        self.assertNotEqual(self.createdCall.call_start, None)

    def test_getLastCallForAgent(self):
        # create some calls for an agent
        self.agentToInsert = self.AgentGateway.registerAgentForServiceToday(self.ANI)
        now = datetime.datetime.now()
        self.activeCalls.append(
            self.CallGateway.addCall(self.agentToInsert, callEnd=(now + datetime.timedelta(seconds=50)))
        )  # [0]
        self.activeCalls.append(
            self.CallGateway.addCall(self.agentToInsert, callEnd=(now + datetime.timedelta(seconds=60)))
        )  # [1]

        lastCall = self.CallGateway.getLastCallForAgent(self.agentToInsert)

        # should return [1]
        self.assertEqual(lastCall.call_id, self.activeCalls[1].call_id)

    def test_endCall(self):
        self.agentToInsert = self.AgentGateway.registerAgentForServiceToday(self.ANI)
        self.createdCall = self.CallGateway.addCall(self.agentToInsert)

        self.assertEqual(self.createdCall.call_end, None)

        # end call
        endedCall = self.CallGateway.endCall(self.createdCall.call_id)

        self.assertEqual(self.createdCall.call_id, endedCall.call_id)
        self.assertNotEqual(endedCall.call_end, None)
def end_call(request):
    """ Ends a current call.
    """
    log.info("end_call. retrieved request to end call with id: " + request.POST['IVRCallID'])
    callGateway = CallGateway()
    response = callGateway.endCall(request.POST['IVRCallID'])
    if response:
        return HttpResponse('call_end.successful')
    else:
        return HttpResponse('call_end.unsuccessful')