def get(self, request, phone_number): # Validate if the phone number received is valid is_valid_phone = re.compile(r'^\d{10,11}$').match(phone_number) month = request.GET.get('month', None) year = request.GET.get('year', None) if not is_valid_phone: raise PhoneNumberInvalidAPIError() if(month is not None and (int(month) <= 1 or int(month) >= 12)): raise MonthInvalidAPIError() month, year = get_previous_month(month, year) # Get phone calls if has the number passed by args and has end calls = Call.objects.filter(call_start__source=phone_number, call_end__timestamp__month=month, call_end__timestamp__year=year) if(calls.count() == 0): return Response(data=( {"Msg": "No phone calls in %s %s" % (month, year)}), status=status.HTTP_200_OK) calls_dict = [] for call in calls: a = {'destination': call.call_start.get().destination, 'date': call.call_start.get().timestamp.date(), 'time': call.call_start.get().timestamp.time(), 'duration': call.format_duration, 'price': call.format_price} calls_dict.append(a) serializer = MonthBillSerializer(calls_dict, many=True) return Response(serializer.data)
def test_month_invalid(self): with self.assertRaises(MonthInvalidAPIError): get_previous_month(13, 2018)
def test_month_changed_by_year(self): with self.assertRaises(MonthInvalidAPIError): get_previous_month(2018)
def test_last_month_actual_year(self): month = datetime.now().month - 1 year = datetime.now().year self.assertListEqual(get_previous_month(month, year), [month, year])
def test_next_month_last_year(self): month = datetime.now().month + 1 year = datetime.now().year - 1 self.assertListEqual(get_previous_month(month, year), [month, year])
def test_actual_month_next_year(self): month = datetime.now().month year = datetime.now().year + 1 self.assertListEqual(get_previous_month(month, year), [month - 1, year - 1])
def test_none_month_none_year(self): month = datetime.now().month - 1 year = datetime.now().year self.assertListEqual(get_previous_month(None, None), [month, year])
def test_when_month_is_none(self): month = datetime.now().month - 1 year = datetime.now().year self.assertListEqual(get_previous_month(None, year), [month, year])