Пример #1
0
    def test_invalid_dates(self):
        resp = self._retrieve_sessions(self._point_url,
                                       self.token,
                                       self.point.id,
                                       self.days[5],
                                       self.days[4],
                                       csv=False)

        self.assertEqual(resp.status_code, 200)
        self.assertTrue(isinstance(resp, JsonResponse))
        body = json.loads(resp.content)

        self.assertTrue(body.get('Point', False))
        self.assertEqual(body['Point'], self.point.id)

        self.assertTrue(body.get('PointOperator', False))
        self.assertEqual(body['PointOperator'],
                         self.point.station_id.operator.username)

        self.assertTrue(body.get('RequestTimestamp', False))
        self.assertTrue(self._elapsed(body['RequestTimestamp']) < 10000)

        self.assertTrue(body.get('PeriodFrom', False))
        self.assertEqual(body['PeriodFrom'],
                         datetime_to_string(self._current_time(self.days[5])))

        self.assertTrue(body.get('PeriodTo', False))
        self.assertEqual(body['PeriodTo'],
                         datetime_to_string(self._current_time(self.days[4])))

        self.assertTrue(body.get('NumberOfChargingSessions', False) == 0)

        self.assertTrue(body.get('ChargingSessionsList', False) == [])
Пример #2
0
    def _verify_ev_res(self, actual, expected):
        self.assertTrue(actual.get('SessionID', False))
        self.assertEqual(int(actual['SessionID']), expected.id)

        self.assertTrue(actual.get('EnergyProvider', False) == None)

        self.assertTrue(actual.get('StartedOn', False))
        self.assertEqual(actual['StartedOn'],
                         datetime_to_string(expected.start))

        self.assertTrue(actual.get('FinishedOn', False))
        self.assertEqual(actual['FinishedOn'],
                         datetime_to_string(expected.end))

        self.assertTrue(actual.get('EnergyDelivered', False))
        self.assertEqual(actual['EnergyDelivered'], expected.energy_delivered)

        self.assertTrue(actual.get('PricePolicyRef', False))
        self.assertEqual(actual['PricePolicyRef'],
                         expected.pricing_id.description)

        self.assertTrue(actual.get('CostPerKWh', False))
        self.assertEqual(actual['CostPerKWh'], expected.pricing_id.price)

        self.assertTrue(actual.get('SessionCost', False))
        self.assertEqual(actual['SessionCost'], expected.total_cost)
Пример #3
0
    def test_invalid_dates(self):
        resp = self._retrieve_sessions(self._ev_url,
                                       self.token,
                                       self.car.licence,
                                       self.days[5],
                                       self.days[4],
                                       csv=False)

        self.assertEqual(resp.status_code, 200)
        self.assertTrue(isinstance(resp, JsonResponse))
        body = json.loads(resp.content)

        self.assertTrue(body.get('VehicleID', False))
        self.assertEqual(body['VehicleID'], self.car.licence)

        self.assertTrue(body.get('RequestTimestamp', False))
        self.assertTrue(self._elapsed(body['RequestTimestamp']) < 10000)

        self.assertTrue(body.get('PeriodFrom', False))
        self.assertEqual(body['PeriodFrom'],
                         datetime_to_string(self._current_time(self.days[5])))

        self.assertTrue(body.get('PeriodTo', False))
        self.assertEqual(body['PeriodTo'],
                         datetime_to_string(self._current_time(self.days[4])))

        self.assertTrue(body.get('TotalEnergyConsumed', False) == 0)

        self.assertTrue(body.get('NumberOfVisitedPoints', False) == 0)

        self.assertTrue(
            body.get('NumberOfVehicleChargingSessions', False) == 0)

        self.assertTrue(body.get('VehicleChargingSessionsList', False) == [])
Пример #4
0
    def get(self, request, user, point_id, date_from, date_to):
        requested_format = self.request.GET.get('format', 'json')

        try:
            start = datetime_from_string(date_from)
            end = datetime_from_string(date_to) + datetime.timedelta(milliseconds=999)
        except ValueError:
            return HttpResponseBadRequest("Invalid date format.")

        try:
            point = Point.objects.get(id=point_id)
        except ObjectDoesNotExist:
            return HttpResponseBadRequest("Point does not exist.")
        except ValueError:
            return HttpResponseBadRequest("Invalid point id")

        if point.station_id.operator != user:
            return HttpResponse("Unauthorized. Point does not belong to you.", status=401)

        sessions = ChargeSession.objects.filter(point_id=point,
                start__gte=start, end__lte=end).order_by('start')

        resp = {
            "Point": point.id,
            "PointOperator": point.station_id.operator.username,
            "RequestTimestamp": datetime_to_string(get_now()),
            "PeriodFrom": datetime_to_string(start),
            "PeriodTo": datetime_to_string(end),
            "NumberOfChargingSessions": len(sessions),
            "ChargingSessionsList": []
        }

        for idx, session in enumerate(sessions, start=1):
            item = {
                "SessionIndex": idx,
                "SessionID": session.id,
                "StartedOn": datetime_to_string(session.start),
                "FinishedOn": datetime_to_string(session.end),
                "Protocol": session.protocol,
                "EnergyDelivered": session.energy_delivered,
                "Payment": session.payment,
                "SessionCost": session.total_cost
            }
            if session.car_id:
                item["VehicleType"] = session.car_id.type

            resp["ChargingSessionsList"].append(item)

        if requested_format == 'csv':
            root_keys = ["Point", "PointOperator", "RequestTimestamp", "PeriodFrom", "PeriodTo",
                    "NumberOfChargingSessions"]
            lst_keys = ["SessionIndex", "SessionID", "StartedOn", "FinishedOn", "Protocol",
                    "EnergyDelivered", "Payment", "VehicleType"]
            return produce_csv_response(resp, root_keys, lst_keys, "ChargingSessionsList")
        elif requested_format == "json":
            return JsonResponse(resp)
        else:
            return HttpResponseBadRequest("Invalid format.")
Пример #5
0
    def test_invalid_date_format(self):
        resp = self.client.get(self._point_url(
            self.point.id, datetime_to_string(self.days[7]), "invalid_format"),
                               HTTP_X_AUTH_OBSERVATORY=self.token)
        self.assertEqual(resp.status_code, 400)

        resp = self.client.get(self._point_url(
            self.point.id, "invalid_format", datetime_to_string(self.days[0])),
                               HTTP_X_AUTH_OBSERVATORY=self.token)
        self.assertEqual(resp.status_code, 400)
Пример #6
0
    def _retrieve_sessions(self, url, token, id, fr, to, csv=False):
        fr = datetime_to_string(self._current_time(fr))
        to = datetime_to_string(self._current_time(to))

        format = "json"
        if csv:
            format = "csv"

        return self.client.get(url(id, fr, to) + "?format=" + format,
                               HTTP_X_AUTH_OBSERVATORY=token)
Пример #7
0
    def test_get_point_charges(self):
        resp = self._retrieve_sessions(self._point_url,
                                       self.token,
                                       self.point.id,
                                       self.days[4],
                                       self.days[0],
                                       csv=False)

        self.assertEqual(resp.status_code, 200)
        self.assertTrue(isinstance(resp, JsonResponse))
        body = json.loads(resp.content)

        self.assertTrue(body.get('Point', False))
        self.assertEqual(body['Point'], self.point.id)

        self.assertTrue(body.get('PointOperator', False))
        self.assertEqual(body['PointOperator'],
                         self.point.station_id.operator.username)

        self.assertTrue(body.get('RequestTimestamp', False))
        self.assertTrue(self._elapsed(body['RequestTimestamp']) < 10000)

        self.assertTrue(body.get('PeriodFrom', False))
        self.assertEqual(body['PeriodFrom'],
                         datetime_to_string(self._current_time(self.days[4])))

        self.assertTrue(body.get('PeriodTo', False))
        self.assertEqual(body['PeriodTo'],
                         datetime_to_string(self._current_time(self.days[0])))

        self.assertTrue(body.get('NumberOfChargingSessions', False))
        self.assertEqual(body['NumberOfChargingSessions'], 2)

        self.assertTrue(body.get('ChargingSessionsList', False))
        self.assertEqual(len(body['ChargingSessionsList']),
                         int(body['NumberOfChargingSessions']))

        # test first result
        first = body['ChargingSessionsList'][0]
        self.assertTrue(first.get('SessionIndex', False))
        self.assertEqual(int(first['SessionIndex']), 1)

        self._verify_point_res(first, self.charge2)

        # test second result
        second = body['ChargingSessionsList'][1]
        self.assertTrue(second.get('SessionIndex', False))
        self.assertEqual(int(second['SessionIndex']), 2)

        self._verify_point_res(second, self.charge3)
Пример #8
0
    def test_get_vehicle_charges(self):
        resp = self._retrieve_sessions(self._ev_url,
                                       self.token,
                                       self.car.licence,
                                       self.days[4],
                                       self.days[0],
                                       csv=False)

        self.assertEqual(resp.status_code, 200)
        self.assertTrue(isinstance(resp, JsonResponse))
        body = json.loads(resp.content)

        self.assertTrue(body.get('VehicleID', False))
        self.assertEqual(body['VehicleID'], self.car.licence)

        self.assertTrue(body.get('RequestTimestamp', False))
        self.assertTrue(self._elapsed(body['RequestTimestamp']) < 10000)

        self.assertTrue(body.get('PeriodFrom', False))
        self.assertEqual(body['PeriodFrom'],
                         datetime_to_string(self._current_time(self.days[4])))

        self.assertTrue(body.get('PeriodTo', False))
        self.assertEqual(body['PeriodTo'],
                         datetime_to_string(self._current_time(self.days[0])))

        self.assertTrue(body.get('NumberOfVisitedPoints', False))
        self.assertEqual(body['NumberOfVisitedPoints'], 2)

        self.assertTrue(body.get('NumberOfVehicleChargingSessions', False))
        self.assertEqual(body['NumberOfVehicleChargingSessions'], 2)

        self.assertTrue(body.get('VehicleChargingSessionsList', False))
        self.assertEqual(len(body['VehicleChargingSessionsList']),
                         int(body['NumberOfVehicleChargingSessions']))

        # test first result
        first = body['VehicleChargingSessionsList'][0]
        self.assertTrue(first.get('SessionIndex', False))
        self.assertEqual(int(first['SessionIndex']), 1)

        self._verify_ev_res(first, self.charge2)

        # test second result
        second = body['VehicleChargingSessionsList'][1]
        self.assertTrue(second.get('SessionIndex', False))
        self.assertEqual(int(second['SessionIndex']), 2)

        self._verify_ev_res(second, self.charge3)
Пример #9
0
    def _verify_point_res(self, actual, expected):
        self.assertTrue(actual.get('SessionID', False))
        self.assertEqual(int(actual['SessionID']), expected.id)

        self.assertTrue(actual.get('StartedOn', False))
        self.assertEqual(actual['StartedOn'],
                         datetime_to_string(expected.start))

        self.assertTrue(actual.get('FinishedOn', False))
        self.assertEqual(actual['FinishedOn'],
                         datetime_to_string(expected.end))

        self.assertTrue(actual.get('Protocol', False))
        self.assertEqual(actual['Protocol'], expected.protocol)

        self.assertTrue(actual.get('EnergyDelivered', False))
        self.assertEqual(actual['EnergyDelivered'], expected.energy_delivered)

        self.assertTrue(actual.get('Payment', False))
        self.assertEqual(actual['Payment'], expected.payment)

        self.assertTrue(actual.get('VehicleType', False))
        self.assertEqual(actual['VehicleType'], expected.car_id.type)
Пример #10
0
    def get(self, request, user, station_id, date_from, date_to):
        requested_format = self.request.GET.get('format', 'json')

        try:
            start = datetime_from_string(date_from)
            end = datetime_from_string(date_to) + datetime.timedelta(
                milliseconds=999)
        except ValueError:
            return HttpResponseBadRequest("Invalid date format.")

        try:
            station = Station.objects.get(id=station_id)
        except ObjectDoesNotExist:
            return HttpResponseBadRequest("Station does not exist.")
        except ValueError:
            return HttpResponseBadRequest("Invalid station id")

        if station.operator != user:
            return HttpResponse(
                "Unauthorized. Station does not belong to you.", status=401)

        points = Point.objects.filter(station_id=station)

        resp = {
            "StationID": station.id,
            "Operator": station.operator.username,
            "RequestTimestamp": datetime_to_string(get_now()),
            "PeriodFrom": datetime_to_string(start),
            "PeriodTo": datetime_to_string(end),
            "TotalEnergyDelivered": 0,
            "NumberOfChargingSessions": 0,
            "NumberOfActivePoints": 0,
            "SessionsSummaryList": []
        }

        for point in points:
            sessions = ChargeSession.objects.filter(
                point_id=point, start__gte=start,
                end__lte=end).order_by('start')
            if len(sessions):
                energy_delivered = sum([x.energy_delivered for x in sessions])
                resp['NumberOfChargingSessions'] += len(sessions)
                resp['NumberOfActivePoints'] += 1
                resp["SessionsSummaryList"].append({
                    "PointID":
                    point.id,
                    "PointSessions":
                    len(sessions),
                    "EnergyDelivered":
                    energy_delivered
                })
                resp['TotalEnergyDelivered'] += energy_delivered

        if requested_format == 'csv':
            root_keys = [
                "StationID", "Operator", "RequestTimestamp", "PeriodFrom",
                "PeriodTo", "TotalEnergyDelivered", "NumberOfChargingSessions",
                "NumberOfActivePoints"
            ]
            lst_keys = ["PointID", "PointSessions", "EnergyDelivered"]
            return produce_csv_response(resp, root_keys, lst_keys,
                                        "SessionsSummaryList")
        elif requested_format == "json":
            return JsonResponse(resp)
        else:
            return HttpResponseBadRequest("Invalid format.")
Пример #11
0
    def get(self, request, user, vehicle_id, date_from, date_to):
        requested_format = self.request.GET.get('format', 'json')

        try:
            start = datetime_from_string(date_from)
            end = datetime_from_string(date_to) + datetime.timedelta(
                milliseconds=999)
        except ValueError:
            return HttpResponseBadRequest("Invalid date format.")

        try:
            car = Car.objects.get(licence=vehicle_id)
        except ObjectDoesNotExist:
            return HttpResponseBadRequest("EV does not exist.")

        if car.user_id != user:
            return HttpResponse(
                "Unauthorized. Vehicle does not belong to you.", status=401)

        sessions = ChargeSession.objects.filter(car_id=car,
                                                start__gte=start,
                                                end__lte=end).order_by('start')

        resp = {
            "VehicleID": car.licence,
            "RequestTimestamp": datetime_to_string(get_now()),
            "PeriodFrom": datetime_to_string(start),
            "PeriodTo": datetime_to_string(end),
            "TotalEnergyConsumed": 0,
            "NumberOfVisitedPoints": 0,
            "NumberOfVehicleChargingSessions": len(sessions),
            "VehicleChargingSessionsList": []
        }

        visited_points = set()
        for idx, session in enumerate(sessions, start=1):
            item = {
                "SessionIndex": idx,
                "SessionID": session.id,
                "EnergyProvider": None,
                "StartedOn": datetime_to_string(session.start),
                "FinishedOn": datetime_to_string(session.end),
                "EnergyDelivered": session.energy_delivered,
                "SessionCost": session.total_cost
            }
            if session.pricing_id:
                item["PricePolicyRef"] = session.pricing_id.description
                item["CostPerKWh"] = session.pricing_id.price

            resp["VehicleChargingSessionsList"].append(item)

            resp["TotalEnergyConsumed"] += session.energy_delivered
            if session.point_id:
                visited_points.add(session.point_id.id)

        resp["NumberOfVisitedPoints"] = len(visited_points)

        if requested_format == 'csv':
            root_keys = [
                "VehicleID", "RequestTimestamp", "PeriodFrom", "PeriodTo",
                "TotalEnergyConsumed", "NumberOfVisitedPoints",
                "NumberOfVehicleChargingSessions"
            ]
            lst_keys = [
                "SessionIndex", "SessionID", "EnergyProvider", "StartedOn",
                "FinishedOn", "EnergyDelivered", "PricePolicyRef",
                "CostPerKWh", "SessionCost"
            ]
            return produce_csv_response(resp, root_keys, lst_keys,
                                        "VehicleChargingSessionsList")
        elif requested_format == "json":
            return JsonResponse(resp)
        else:
            return HttpResponseBadRequest("Invalid format.")
Пример #12
0
    def test_get_station_charges(self):
        resp = self._retrieve_sessions(self._station_url,
                                       self.token,
                                       self.station.id,
                                       self.days[4],
                                       self.days[0],
                                       csv=False)

        self.assertEqual(resp.status_code, 200)
        self.assertTrue(isinstance(resp, JsonResponse))
        body = json.loads(resp.content)

        self.assertTrue(body.get('StationID', False))
        self.assertEqual(body['StationID'], self.station.id)

        self.assertTrue(body.get('Operator', False))
        self.assertEqual(body['Operator'], self.station.operator.username)

        self.assertTrue(body.get('RequestTimestamp', False))
        self.assertTrue(self._elapsed(body['RequestTimestamp']) < 10000)

        self.assertTrue(body.get('PeriodFrom', False))
        self.assertEqual(body['PeriodFrom'],
                         datetime_to_string(self._current_time(self.days[4])))

        self.assertTrue(body.get('PeriodTo', False))
        self.assertEqual(body['PeriodTo'],
                         datetime_to_string(self._current_time(self.days[0])))

        self.assertTrue(body.get('TotalEnergyDelivered', False))
        self.assertEqual(body['TotalEnergyDelivered'], 60)

        self.assertTrue(body.get('NumberOfChargingSessions', False))
        self.assertEqual(body['NumberOfChargingSessions'], 3)

        self.assertTrue(body.get('NumberOfActivePoints', False))
        self.assertEqual(body['NumberOfActivePoints'], 2)

        self.assertTrue(body.get('SessionsSummaryList', False))
        self.assertEqual(len(body['SessionsSummaryList']),
                         body['NumberOfActivePoints'])

        # test first result
        first = body['SessionsSummaryList'][0]
        self.assertTrue(first.get('PointID', False))
        self.assertEqual(int(first['PointID']), self.point1.id)

        self.assertTrue(first.get('PointSessions', False))
        self.assertEqual(first['PointSessions'], 2)

        self.assertTrue(first.get('EnergyDelivered', False))
        self.assertEqual(first['EnergyDelivered'], 30)

        # test second result
        second = body['SessionsSummaryList'][1]
        self.assertTrue(second.get('PointID', False))
        self.assertEqual(int(second['PointID']), self.point2.id)

        self.assertTrue(second.get('PointSessions', False))
        self.assertEqual(second['PointSessions'], 1)

        self.assertTrue(second.get('EnergyDelivered', False))
        self.assertEqual(second['EnergyDelivered'], 30)