def test_ambulance_get_list_viewset(self):

        # instantiate client
        client = Client()

        # login as admin
        client.login(username=settings.MQTT['USERNAME'],
                     password=settings.MQTT['PASSWORD'])

        # retrieve ambulances
        response = client.get('/api/ambulance/', follow=True)
        self.assertEqual(response.status_code, 200)
        result = JSONParser().parse(BytesIO(response.content))
        answer = [
            AmbulanceSerializer(self.a1).data,
            AmbulanceSerializer(self.a2).data,
            AmbulanceSerializer(self.a3).data
        ]
        self.assertCountEqual(result, answer)

        # logout
        client.logout()

        # login as testuser1
        client.login(username='******', password='******')

        # retrieve ambulances
        response = client.get('/api/ambulance/', follow=True)
        self.assertEqual(response.status_code, 200)
        result = JSONParser().parse(BytesIO(response.content))
        answer = []
        self.assertCountEqual(result, answer)

        # logout
        client.logout()

        # login as testuser2
        client.login(username='******', password='******')

        # retrieve ambulances
        response = client.get('/api/ambulance/', follow=True)
        self.assertEqual(response.status_code, 200)
        result = JSONParser().parse(BytesIO(response.content))
        answer = [  # AmbulanceSerializer(self.a1).data, # can't read
            AmbulanceSerializer(Ambulance.objects.get(id=self.a3.id)).data
        ]
        self.assertCountEqual(result, answer)

        # logout
        client.logout()
    def test_ambulance_create_serializer(self):
        serializer = AmbulanceSerializer(
            data={
                'identifier': 'NEW-1897',
                'capability': AmbulanceCapability.R.name,
                'comment': 'no comments'
            })
        serializer.is_valid()
        serializer.save(updated_by=self.u1)

        # test AmbulanceSerializer
        a = Ambulance.objects.get(identifier='NEW-1897')
        serializer = AmbulanceSerializer(a)
        result = {
            'id': a.id,
            'identifier': 'NEW-1897',
            'comment': 'no comments',
            'capability': AmbulanceCapability.R.name,
            'status': AmbulanceStatus.UK.name,
            'orientation': a.orientation,
            'location': point2str(a.location),
            'timestamp': date2iso(a.timestamp),
            'client_id': None,
            'updated_by': self.u1.id,
            'updated_on': date2iso(a.updated_on)
        }
        self.assertDictEqual(serializer.data, result)
 def test_ambulance_serializer(self):
     # test AmbulanceSerializer
     for a in (self.a1, self.a2, self.a3):
         serializer = AmbulanceSerializer(a)
         result = {
             'id': a.id,
             'identifier': a.identifier,
             'comment': a.comment,
             'capability': a.capability,
             'status': AmbulanceStatus.UK.name,
             'orientation': a.orientation,
             'location': point2str(a.location),
             'timestamp': date2iso(a.timestamp),
             'client_id': None,
             'updated_by': a.updated_by.id,
             'updated_on': date2iso(a.updated_on)
         }
         self.assertDictEqual(serializer.data, result)
Beispiel #4
0
    def on_ambulance(self, clnt, userdata, msg):

        try:

            logger.debug("on_ambulance: msg = '{}'".format(
                msg.topic, msg.payload))

            # parse topic
            user, client, data, ambulance_id = self.parse_topic(msg, 4)

        except Exception as e:

            logger.debug("on_ambulance: ParseException '{}'".format(e))
            return

        try:

            # retrieve ambulance
            logger.debug('ambulance_id = {}'.format(ambulance_id))
            ambulance = Ambulance.objects.get(id=ambulance_id)

        except Ambulance.DoesNotExist:

            # send error message to user
            self.send_error_message(
                user, client, msg.topic, msg.payload,
                "Ambulance with id '{}' does not exist".format(ambulance_id))
            return

        except Exception as e:

            # send error message to user
            self.send_error_message(user, client, msg.topic, msg.payload,
                                    "Exception: '{}'".format(e))
            return

        try:

            logger.debug("on_ambulance: ambulance = '{}', data = '{}'".format(
                ambulance, data))

            is_valid = False
            if isinstance(data, (list, tuple)):

                # bulk updates must match location_client
                if ambulance.location_client is None or ambulance.location_client.client_id != client.client_id:

                    # send error message to user
                    self.send_error_message(
                        user, client, msg.topic, msg.payload,
                        "Client '{}' is not currently authorized to update ambulance '{}'"
                        .format(client.client_id, ambulance.identifier))
                    return

                # update ambulances in bulk
                serializer = AmbulanceUpdateSerializer(data=data,
                                                       many=True,
                                                       partial=True)

                if serializer.is_valid():

                    # save to database
                    serializer.save(ambulance=ambulance, updated_by=user)
                    is_valid = True

            else:

                # update ambulance
                serializer = AmbulanceSerializer(ambulance,
                                                 data=data,
                                                 partial=True)

                if serializer.is_valid():

                    try:

                        # wrap in atomic in case of errors
                        with transaction.atomic():

                            # current location client
                            old_location_client = ambulance.location_client

                            # save to database
                            serializer.save(updated_by=user)
                            is_valid = True

                            # retrieve location client
                            new_location_client = Ambulance.objects.get(
                                id=ambulance_id).location_client

                            # logger.debug("old_location_client: {}".format(old_location_client))
                            # logger.debug("new_location_client: {}".format(new_location_client))

                            # change in location client?
                            if old_location_client != new_location_client:

                                # logger.debug("location_client changed from '{}' to {}".format(old_location_client,
                                #                                                               new_location_client))

                                # log out old client
                                if old_location_client:
                                    client_ambulance = old_location_client.ambulance
                                    if client_ambulance:
                                        details = client_ambulance.identifier
                                    else:
                                        details = 'None'
                                    log = ClientLog(
                                        client=old_location_client,
                                        status=old_location_client.status,
                                        activity=ClientActivity.TL.name,
                                        details=details)
                                    log.save()

                                # log in new client
                                if new_location_client:
                                    client_ambulance = new_location_client.ambulance
                                    if client_ambulance:
                                        details = client_ambulance.identifier
                                    else:
                                        details = 'None'
                                    log = ClientLog(
                                        client=new_location_client,
                                        status=new_location_client.status,
                                        activity=ClientActivity.SL.name,
                                        details=details)
                                    log.save()

                            # otherwise must match location_client
                            elif ambulance.location_client is None or ambulance.location_client.client_id != client.client_id:

                                # raise error to rollback transaction
                                raise ClientException()

                    except ClientException:

                        # send error message to user
                        self.send_error_message(
                            user, client, msg.topic, msg.payload,
                            "Client '{}' is not currently authorized to update ambulance '{}'"
                            .format(client.client_id, ambulance.identifier))

            if not is_valid:

                logger.debug('on_ambulance: INVALID serializer')

                # send error message to user
                self.send_error_message(user, client, msg.topic, msg.payload,
                                        serializer.errors)

        except Exception as e:

            logger.debug('on_ambulance: serializer EXCEPTION')

            # send error message to user
            self.send_error_message(user, client, msg.topic, msg.payload, e)

        logger.debug('on_ambulance: DONE')
Beispiel #5
0
 def publish_ambulance(self, ambulance, qos=2, retain=False):
     self.publish_topic('ambulance/{}/data'.format(ambulance.id),
                        AmbulanceSerializer(ambulance),
                        qos=qos,
                        retain=retain)
Beispiel #6
0
    def on_ambulance(self, clnt, userdata, msg):

        try:

            logger.debug("on_ambulance: msg = '{}'".format(
                msg.topic, msg.payload))

            # parse topic
            user, client, data, ambulance_id = self.parse_topic(msg, 4)

        except Exception as e:

            logger.debug("on_ambulance: ParseException '{}'".format(e))
            return

        try:

            # retrieve ambulance
            logger.debug('ambulance_id = {}'.format(ambulance_id))
            ambulance = Ambulance.objects.get(id=ambulance_id)

        except Ambulance.DoesNotExist:

            # send error message to user
            self.send_error_message(
                user, client, msg.topic, msg.payload,
                "Ambulance with id '{}' does not exist".format(ambulance_id))
            return

        except Exception as e:

            # send error message to user
            self.send_error_message(user, client, msg.topic, msg.payload,
                                    "Exception: '{}'".format(e))
            return

        try:

            logger.debug("on_ambulance: ambulance = '{}', data = '{}'".format(
                ambulance, data))

            # updates must match client
            if client.ambulance != ambulance:
                # send error message to user
                self.send_error_message(
                    user, client, msg.topic, msg.payload,
                    "Client '{}' is not currently authorized to update ambulance '{}'"
                    .format(client.client_id, ambulance.identifier))
                return

            is_valid = False
            if isinstance(data, (list, tuple)):

                # update ambulances in bulk
                serializer = AmbulanceUpdateSerializer(data=data,
                                                       many=True,
                                                       partial=True)

                if serializer.is_valid():

                    # save to database
                    serializer.save(ambulance=ambulance, updated_by=user)
                    is_valid = True

            else:

                # update ambulance
                serializer = AmbulanceSerializer(ambulance,
                                                 data=data,
                                                 partial=True)

                if serializer.is_valid():

                    # save to database
                    serializer.save(updated_by=user)
                    is_valid = True

            if not is_valid:

                logger.debug('on_ambulance: INVALID serializer')

                # send error message to user
                self.send_error_message(user, client, msg.topic, msg.payload,
                                        serializer.errors)

        except Exception as e:

            logger.debug('on_ambulance: EXCEPTION')

            # send error message to user
            self.send_error_message(user, client, msg.topic, msg.payload,
                                    "Exception '{}'".format(e))

        logger.debug('on_ambulance: DONE')
Beispiel #7
0
    def on_ambulance(self, client, userdata, msg):

        logger.debug("on_ambulance: msg = '{}:{}'".format(
            msg.topic, msg.payload))

        # parse topic
        values = self.parse_topic(msg)
        if not values:
            return

        logger.debug("on_ambulance: values = '{}'".format(values))

        try:

            # retrieve parsed values
            user, data, ambulance_id = values

            logger.debug('ambulance_id = {}'.format(ambulance_id))

            # retrieve ambulance
            ambulance = Ambulance.objects.get(id=ambulance_id)

        except ObjectDoesNotExist:

            # send error message to user
            self.send_error_message(
                user, msg.topic, msg.payload,
                "Ambulance with id '{}' does not exist".format(ambulance_id))
            return

        except Exception as e:

            # send error message to user
            self.send_error_message(user, msg.topic, msg.payload,
                                    "Exception: '{}'".format(e))
            return

        logger.debug('on_ambulance: ambulance = {}'.format(ambulance))

        try:

            # update ambulance
            serializer = AmbulanceSerializer(ambulance,
                                             data=data,
                                             partial=True)
            if serializer.is_valid():

                logger.debug('on_ambulance: valid serializer')

                # save to database
                serializer.save(updated_by=user)

            else:

                logger.debug('on_ambulance: INVALID serializer')

                # send error message to user
                self.send_error_message(user, msg.topic, msg.payload,
                                        serializer.errors)

        except Exception as e:

            logger.debug('on_ambulance: serializer EXCEPTION')

            # send error message to user
            self.send_error_message(user, msg.topic, msg.payload, e)

        logger.debug('on_ambulance: DONE')
    def test(self):

        # Bulk update ambulance a1
        a = self.a1
        user = self.u1

        location0 = {'latitude': -3., 'longitude': 6.}
        location = {'latitude': -2., 'longitude': 7.}
        orientation = calculate_orientation(dict2point(location0),
                                            dict2point(location))
        data = [{
            'status': AmbulanceStatus.AH.name,
            'location': location0,
        }, {
            'location': location,
            'timestamp': timezone.now()
        }, {
            'status': AmbulanceStatus.OS.name
        }]

        serializer = AmbulanceUpdateSerializer(data=data,
                                               many=True,
                                               partial=True)
        serializer.is_valid(raise_exception=True)
        serializer.save(ambulance=Ambulance.objects.get(id=a.id),
                        updated_by=user)

        # test AmbulanceUpdateSerializer
        queryset = AmbulanceUpdate.objects.filter(ambulance=a)
        answer1 = []
        for u in queryset:
            serializer = AmbulanceUpdateSerializer(u)
            result = {
                'id': u.id,
                'ambulance_id': u.ambulance.id,
                'ambulance_identifier': u.ambulance.identifier,
                'comment': u.comment,
                'capability': u.capability,
                'status': u.status,
                'orientation': u.orientation,
                'location': point2str(u.location),
                'timestamp': date2iso(u.timestamp),
                'updated_by_username': u.updated_by.username,
                'updated_on': date2iso(u.updated_on)
            }
            answer1.append(serializer.data)
            self.assertDictEqual(serializer.data, result)

        # make sure last update is reflected in ambulance
        a = Ambulance.objects.get(id=a.id)
        serializer = AmbulanceSerializer(a)
        self.assertEqual(math.fabs(orientation - a.orientation) < 1e-4, True)
        orientation = a.orientation
        result = {
            'id': a.id,
            'identifier': a.identifier,
            'comment': a.comment,
            'capability': a.capability,
            'status': AmbulanceStatus.OS.name,
            'orientation': orientation,
            'location': point2str(location),
            'timestamp': date2iso(a.timestamp),
            'client_id': None,
            'updated_by': a.updated_by.id,
            'updated_on': date2iso(a.updated_on)
        }
        self.assertDictEqual(serializer.data, result)

        # Bulk update ambulance a2
        a = self.a3
        user = self.u3

        data = [{
            'status': AmbulanceStatus.AH.name,
            'location': location0
        }, {
            'status': AmbulanceStatus.OS.name
        }, {
            'location': location,
            'timestamp': timezone.now()
        }]

        serializer = AmbulanceUpdateSerializer(data=data,
                                               many=True,
                                               partial=True)
        serializer.is_valid(raise_exception=True)
        serializer.save(ambulance=Ambulance.objects.get(id=a.id),
                        updated_by=user)

        # test AmbulanceUpdateSerializer
        queryset = AmbulanceUpdate.objects.filter(ambulance=a)
        answer3 = []
        for u in queryset:
            serializer = AmbulanceUpdateSerializer(u)
            result = {
                'id': u.id,
                'ambulance_id': a.id,
                'ambulance_identifier': a.identifier,
                'comment': u.comment,
                'capability': u.capability,
                'status': u.status,
                'orientation': u.orientation,
                'location': point2str(u.location),
                'timestamp': date2iso(u.timestamp),
                'updated_by_username': u.updated_by.username,
                'updated_on': date2iso(u.updated_on)
            }
            answer3.append(serializer.data)
            self.assertDictEqual(serializer.data, result)

        # make sure last update is reflected in ambulance
        a = Ambulance.objects.get(id=a.id)
        serializer = AmbulanceSerializer(a)
        self.assertEqual(math.fabs(orientation - a.orientation) < 1e-4, True)
        orientation = a.orientation
        result = {
            'id': a.id,
            'identifier': a.identifier,
            'comment': a.comment,
            'capability': a.capability,
            'status': AmbulanceStatus.OS.name,
            'orientation': orientation,
            'location': point2str(location),
            'timestamp': date2iso(a.timestamp),
            'client_id': None,
            'updated_by': a.updated_by.id,
            'updated_on': date2iso(a.updated_on)
        }
        self.assertDictEqual(serializer.data, result)

        # Test api

        # instantiate client
        client = Client()

        # login as admin
        client.login(username=settings.MQTT['USERNAME'],
                     password=settings.MQTT['PASSWORD'])

        # retrieve ambulances updates
        response = client.get('/en/api/ambulance/{}/updates/'.format(
            self.a1.id),
                              follow=True)
        self.assertEqual(response.status_code, 200)
        result = JSONParser().parse(BytesIO(response.content))
        self.assertCountEqual(result, answer1)
        self.assertEqual(len(result), 4)

        # retrieve ambulances updates
        response = client.get('/en/api/ambulance/{}/updates/'.format(
            self.a3.id),
                              follow=True)
        self.assertEqual(response.status_code, 200)
        result = JSONParser().parse(BytesIO(response.content))
        self.assertCountEqual(result, answer3)
        self.assertEqual(len(result), 4)

        # logout
        client.logout()

        # login as testuser1
        client.login(username='******', password='******')

        # retrieve ambulances
        response = client.get('/en/api/ambulance/{}/updates/'.format(
            self.a1.id),
                              follow=True)
        self.assertEqual(response.status_code, 404)

        # retrieve ambulances
        response = client.get('/en/api/ambulance/{}/updates/'.format(
            self.a3.id),
                              follow=True)
        self.assertEqual(response.status_code, 404)

        # logout
        client.logout()

        # login as testuser2
        client.login(username='******', password='******')

        # retrieve ambulances
        response = client.get('/en/api/ambulance/{}/updates/'.format(
            self.a1.id),
                              follow=True)
        self.assertEqual(response.status_code, 404)

        # retrieve ambulances updates
        response = client.get('/en/api/ambulance/{}/updates/'.format(
            self.a3.id),
                              follow=True)
        self.assertEqual(response.status_code, 200)
        result = JSONParser().parse(BytesIO(response.content))
        self.assertCountEqual(result, answer3)
        self.assertEqual(len(result), 4)

        # logout
        client.logout()
    def test(self):

        # Update ambulance a1
        a = self.a1
        user = self.u1

        status = AmbulanceStatus.AH.name
        serializer = AmbulanceSerializer(Ambulance.objects.get(id=a.id),
                                         data={
                                             'status': status,
                                         },
                                         partial=True)
        serializer.is_valid()
        serializer.save(updated_by=user)

        timestamp = timezone.now()
        location = {'latitude': -2., 'longitude': 7.}

        serializer = AmbulanceSerializer(Ambulance.objects.get(id=a.id),
                                         data={
                                             'location': location,
                                             'timestamp': timestamp
                                         },
                                         partial=True)
        serializer.is_valid()
        serializer.save(updated_by=user)

        status = AmbulanceStatus.OS.name
        serializer = AmbulanceSerializer(Ambulance.objects.get(id=a.id),
                                         data={
                                             'status': status,
                                         },
                                         partial=True)
        serializer.is_valid()
        serializer.save(updated_by=user)

        # This update does not go to AmbulanceUpdate!
        serializer = AmbulanceSerializer(Ambulance.objects.get(id=a.id),
                                         data={
                                             'identifier': 'someid',
                                         },
                                         partial=True)
        serializer.is_valid()
        serializer.save(updated_by=user)

        # test AmbulanceUpdateSerializer
        queryset = AmbulanceUpdate.objects.filter(ambulance=a)
        answer1 = []
        for u in queryset:
            serializer = AmbulanceUpdateSerializer(u)
            result = {
                'id': u.id,
                'ambulance_id': u.ambulance.id,
                'ambulance_identifier': u.ambulance.identifier,
                'comment': u.comment,
                'capability': u.capability,
                'status': u.status,
                'orientation': u.orientation,
                'location': point2str(u.location),
                'timestamp': date2iso(u.timestamp),
                'updated_by_username': u.updated_by.username,
                'updated_on': date2iso(u.updated_on)
            }
            answer1.append(serializer.data)
            self.assertDictEqual(serializer.data, result)

        # Update ambulance a2
        a = self.a3
        user = self.u3

        status = AmbulanceStatus.AH.name
        serializer = AmbulanceSerializer(a,
                                         data={
                                             'status': status,
                                         },
                                         partial=True)
        serializer.is_valid()
        serializer.save(updated_by=user)

        timestamp = timezone.now()
        location = {'latitude': -2., 'longitude': 7.}

        serializer = AmbulanceSerializer(a,
                                         data={
                                             'location': location,
                                             'timestamp': timestamp
                                         },
                                         partial=True)
        serializer.is_valid()
        serializer.save(updated_by=user)

        status = AmbulanceStatus.OS.name
        serializer = AmbulanceSerializer(a,
                                         data={
                                             'status': status,
                                         },
                                         partial=True)
        serializer.is_valid()
        serializer.save(updated_by=user)

        # test AmbulanceUpdateSerializer
        queryset = AmbulanceUpdate.objects.filter(ambulance=a)
        answer3 = []
        for u in queryset:
            serializer = AmbulanceUpdateSerializer(u)
            result = {
                'id': u.id,
                'ambulance_id': u.ambulance.id,
                'ambulance_identifier': a.identifier,
                'comment': u.comment,
                'capability': u.capability,
                'status': u.status,
                'orientation': u.orientation,
                'location': point2str(u.location),
                'timestamp': date2iso(u.timestamp),
                'updated_by_username': u.updated_by.username,
                'updated_on': date2iso(u.updated_on)
            }
            answer3.append(serializer.data)
            self.assertDictEqual(serializer.data, result)

        # Test api

        # instantiate client
        client = Client()

        # login as admin
        client.login(username=settings.MQTT['USERNAME'],
                     password=settings.MQTT['PASSWORD'])

        # retrieve ambulances updates
        response = client.get('/en/api/ambulance/{}/updates/'.format(
            self.a1.id),
                              follow=True)
        self.assertEqual(response.status_code, 200)
        result = JSONParser().parse(BytesIO(response.content))
        self.assertCountEqual(result, answer1)
        self.assertEqual(len(result), 4)

        # retrieve ambulances updates
        response = client.get('/en/api/ambulance/{}/updates/'.format(
            self.a3.id),
                              follow=True)
        self.assertEqual(response.status_code, 200)
        result = JSONParser().parse(BytesIO(response.content))
        self.assertCountEqual(result, answer3)
        self.assertEqual(len(result), 4)

        # logout
        client.logout()

        # login as testuser1
        client.login(username='******', password='******')

        # retrieve ambulances
        response = client.get('/en/api/ambulance/{}/updates/'.format(
            self.a1.id),
                              follow=True)
        self.assertEqual(response.status_code, 404)

        # retrieve ambulances
        response = client.get('/en/api/ambulance/{}/updates/'.format(
            self.a3.id),
                              follow=True)
        self.assertEqual(response.status_code, 404)

        # logout
        client.logout()

        # login as testuser2
        client.login(username='******', password='******')

        # retrieve ambulances
        response = client.get('/en/api/ambulance/{}/updates/'.format(
            self.a1.id),
                              follow=True)
        self.assertEqual(response.status_code, 404)

        # retrieve ambulances updates
        response = client.get('/en/api/ambulance/{}/updates/'.format(
            self.a3.id),
                              follow=True)
        self.assertEqual(response.status_code, 200)
        result = JSONParser().parse(BytesIO(response.content))
        self.assertCountEqual(result, answer3)
        self.assertEqual(len(result), 4)

        # logout
        client.logout()
    def test_ambulance_post_viewset(self):
        # instantiate client
        client = Client()

        # login as admin
        client.login(username=settings.MQTT['USERNAME'],
                     password=settings.MQTT['PASSWORD'])

        # create ambulance
        response = client.post(
            '/en/api/ambulance/', {
                'identifier': 'NEW-1897',
                'capability': AmbulanceCapability.R.name,
                'comment': 'no comments'
            })
        self.assertEqual(response.status_code, 201)
        a = Ambulance.objects.get(identifier='NEW-1897')

        # retrieve ambulance
        response = client.get('/en/api/ambulance/{}/'.format(str(a.id)))
        self.assertEqual(response.status_code, 200)
        result = JSONParser().parse(BytesIO(response.content))
        answer = AmbulanceSerializer(a).data
        self.assertDictEqual(result, answer)

        # create ambulance (repeated identifier)
        response = client.post(
            '/en/api/ambulance/', {
                'identifier': 'NEW-1897',
                'capability': AmbulanceCapability.R.name,
                'comment': 'no comments'
            })
        self.assertEqual(response.status_code, 400)
        result = JSONParser().parse(BytesIO(response.content))
        self.assertEqual(result['identifier'],
                         ['ambulance with this identifier already exists.'])

        # logout
        client.logout()

        # login as testuser2
        client.login(username='******', password='******')

        response = client.post(
            '/en/api/ambulance/', {
                'identifier': 'NEW-NEW-1897',
                'capability': AmbulanceCapability.B.name,
                'comment': 'more comments'
            })
        self.assertEqual(response.status_code, 403)

        # logout
        client.logout()

        # login as testuser1
        client.login(username='******', password='******')

        response = client.post(
            '/en/api/ambulance/', {
                'identifier': 'NEW-NEW-1897',
                'capability': AmbulanceCapability.B.name,
                'comment': 'more comments'
            })
        self.assertEqual(response.status_code, 403)

        # logout
        client.logout()
    def test_ambulance_patch_viewset(self):

        # instantiate client
        client = Client()

        # login as admin
        client.login(username=settings.MQTT['USERNAME'],
                     password=settings.MQTT['PASSWORD'])

        # retrieve ambulance
        response = client.get('/en/api/ambulance/{}/'.format(str(self.a1.id)),
                              follow=True)
        self.assertEqual(response.status_code, 200)
        result = JSONParser().parse(BytesIO(response.content))
        answer = AmbulanceSerializer(self.a1).data
        self.assertDictEqual(result, answer)

        # set status ambulance
        status = AmbulanceStatus.OS.name
        response = client.patch('/en/api/ambulance/{}/'.format(str(
            self.a1.id)),
                                content_type='application/json',
                                data=json.dumps({
                                    'status': status,
                                }),
                                follow=True)
        self.assertEqual(response.status_code, 200)
        result = JSONParser().parse(BytesIO(response.content))
        answer = AmbulanceSerializer(Ambulance.objects.get(id=self.a1.id)).data
        self.assertDictEqual(result, answer)

        # retrieve new ambulance status
        response = client.get('/en/api/ambulance/{}/'.format(str(self.a1.id)),
                              follow=True)
        self.assertEqual(response.status_code, 200)
        result = JSONParser().parse(BytesIO(response.content))
        self.assertEqual(result['status'], status)

        # set status location
        timestamp = timezone.now()
        location = {'latitude': -2., 'longitude': 7.}

        response = client.patch('/en/api/ambulance/{}/'.format(str(
            self.a1.id)),
                                content_type='application/json',
                                data=json.dumps({
                                    'location':
                                    point2str(location),
                                    'timestamp':
                                    date2iso(timestamp),
                                }),
                                follow=True)
        self.assertEqual(response.status_code, 200)
        result = JSONParser().parse(BytesIO(response.content))
        answer = AmbulanceSerializer(Ambulance.objects.get(id=self.a1.id)).data
        if math.fabs(answer['orientation'] - result['orientation']) < 1e-4:
            answer['orientation'] = result['orientation']
        self.assertDictEqual(result, answer)

        # retrieve new ambulance location
        response = client.get('/en/api/ambulance/{}/'.format(str(self.a1.id)))
        self.assertEqual(response.status_code, 200)
        result = JSONParser().parse(BytesIO(response.content))
        self.assertEqual(result['status'], status)
        self.assertEqual(result['location'], point2str(location))
        self.assertEqual(result['timestamp'], date2iso(timestamp))

        # set wrong attribute
        response = client.patch('/en/api/ambulance/{}/'.format(str(
            self.a1.id)),
                                content_type='application/json',
                                data=json.dumps({'status': 'will fail'}),
                                follow=True)
        self.assertEqual(response.status_code, 400)

        # set wrong ambulance id
        response = client.patch('/en/api/ambulance/100/',
                                data=json.dumps({'status': status}),
                                follow=True)
        self.assertEqual(response.status_code, 404)

        # logout
        client.logout()

        # login as testuser2
        client.login(username='******', password='******')

        # retrieve ambulance
        response = client.get('/en/api/ambulance/{}/'.format(str(self.a3.id)),
                              follow=True)
        self.assertEqual(response.status_code, 200)
        result = JSONParser().parse(BytesIO(response.content))
        answer = AmbulanceSerializer(self.a3).data
        self.assertDictEqual(result, answer)

        # set status ambulance
        status = AmbulanceStatus.OS.name
        response = client.patch('/en/api/ambulance/{}/'.format(str(
            self.a3.id)),
                                content_type='application/json',
                                data=json.dumps({
                                    'status': status,
                                }),
                                follow=True)
        self.assertEqual(response.status_code, 200)
        result = JSONParser().parse(BytesIO(response.content))
        answer = AmbulanceSerializer(Ambulance.objects.get(id=self.a3.id)).data
        self.assertDictEqual(result, answer)

        # retrieve new ambulance status
        response = client.get('/en/api/ambulance/{}/'.format(str(self.a3.id)),
                              follow=True)
        self.assertEqual(response.status_code, 200)
        result = JSONParser().parse(BytesIO(response.content))
        self.assertEqual(result['status'], status)

        # set location
        timestamp = timezone.now()
        location = {'latitude': -2., 'longitude': 7.}

        response = client.patch('/en/api/ambulance/{}/'.format(str(
            self.a3.id)),
                                content_type='application/json',
                                data=json.dumps({
                                    'location':
                                    point2str(location),
                                    'timestamp':
                                    date2iso(timestamp),
                                }),
                                follow=True)
        self.assertEqual(response.status_code, 200)
        result = JSONParser().parse(BytesIO(response.content))
        answer = AmbulanceSerializer(Ambulance.objects.get(id=self.a3.id)).data
        if math.fabs(answer['orientation'] - result['orientation']) < 1e-4:
            answer['orientation'] = result['orientation']
        self.assertDictEqual(result, answer)

        # retrieve new ambulance location
        response = client.get('/en/api/ambulance/{}/'.format(str(self.a3.id)),
                              follow=True)
        self.assertEqual(response.status_code, 200)
        result = JSONParser().parse(BytesIO(response.content))
        self.assertEqual(result['status'], status)
        self.assertEqual(result['location'], point2str(location))
        self.assertEqual(result['timestamp'], date2iso(timestamp))

        # set status ambulance
        status = AmbulanceStatus.OS.name
        response = client.patch('/en/api/ambulance/{}/'.format(str(
            self.a1.id)),
                                content_type='application/json',
                                data=json.dumps({
                                    'status': status,
                                }),
                                follow=True)
        self.assertEqual(response.status_code, 404)

        # set status ambulance
        status = AmbulanceStatus.OS.name
        response = client.patch('/en/api/ambulance/{}/'.format(str(
            self.a2.id)),
                                content_type='application/json',
                                data=json.dumps({
                                    'status': status,
                                }),
                                follow=True)
        self.assertEqual(response.status_code, 404)

        # logout
        client.logout()

        # login as testuser1
        client.login(username='******', password='******')

        # set status ambulance
        status = AmbulanceStatus.OS.name
        response = client.patch('/en/api/ambulance/{}/'.format(str(
            self.a1.id)),
                                content_type='application/json',
                                data=json.dumps({
                                    'status': status,
                                }),
                                follow=True)
        self.assertEqual(response.status_code, 404)

        # set status ambulance
        status = AmbulanceStatus.OS.name
        response = client.patch('/en/api/ambulance/{}/'.format(str(
            self.a2.id)),
                                content_type='application/json',
                                data=json.dumps({
                                    'status': status,
                                }),
                                follow=True)
        self.assertEqual(response.status_code, 404)

        # set status ambulance
        status = AmbulanceStatus.OS.name
        response = client.patch('/en/api/ambulance/{}/'.format(str(
            self.a3.id)),
                                content_type='application/json',
                                data=json.dumps({
                                    'status': status,
                                }),
                                follow=True)
        self.assertEqual(response.status_code, 404)

        # logout
        client.logout()
    def test_ambulance_get_viewset(self):
        # instantiate client
        client = Client()

        # login as admin
        client.login(username=settings.MQTT['USERNAME'],
                     password=settings.MQTT['PASSWORD'])

        # retrieve any ambulance
        response = client.get('/en/api/ambulance/{}/'.format(str(self.a1.id)),
                              follow=True)
        self.assertEqual(response.status_code, 200)
        result = JSONParser().parse(BytesIO(response.content))
        answer = AmbulanceSerializer(Ambulance.objects.get(id=self.a1.id)).data
        self.assertDictEqual(result, answer)

        # retrieve any ambulance
        response = client.get('/en/api/ambulance/{}/'.format(str(self.a2.id)),
                              follow=True)
        self.assertEqual(response.status_code, 200)
        result = JSONParser().parse(BytesIO(response.content))
        answer = AmbulanceSerializer(Ambulance.objects.get(id=self.a2.id)).data
        self.assertDictEqual(result, answer)

        # retrieve any ambulance
        response = client.get('/en/api/ambulance/{}/'.format(str(self.a3.id)),
                              follow=True)
        self.assertEqual(response.status_code, 200)
        result = JSONParser().parse(BytesIO(response.content))
        answer = AmbulanceSerializer(Ambulance.objects.get(id=self.a3.id)).data
        self.assertDictEqual(result, answer)

        # logout
        client.logout()

        # login as testuser2
        client.login(username='******', password='******')

        # retrieve own
        response = client.get('/en/api/ambulance/{}/'.format(str(self.a3.id)),
                              follow=True)
        self.assertEqual(response.status_code, 200)
        result = JSONParser().parse(BytesIO(response.content))
        answer = AmbulanceSerializer(Ambulance.objects.get(id=self.a3.id)).data
        self.assertDictEqual(result, answer)

        # retrieve someone else's
        response = client.get('/en/api/ambulance/{}/'.format(str(self.a2.id)),
                              follow=True)
        self.assertEqual(response.status_code, 404)

        # can't read
        response = client.get('/en/api/ambulance/{}/'.format(str(self.a1.id)),
                              follow=True)
        self.assertEqual(response.status_code, 404)

        # logout
        client.logout()

        # login as testuser1
        client.login(username='******', password='******')

        # retrieve someone else's
        response = client.get('/en/api/ambulance/{}/'.format(str(self.a1.id)),
                              follow=True)
        self.assertEqual(response.status_code, 404)

        # retrieve someone else's
        response = client.get('/en/api/ambulance/{}/'.format(str(self.a2.id)),
                              follow=True)
        self.assertEqual(response.status_code, 404)

        response = client.get('/en/api/ambulance/{}/'.format(str(self.a1.id)),
                              follow=True)
        self.assertEqual(response.status_code, 404)

        # logout
        client.logout()
    def test_ambulance_update_serializer(self):

        # superuser first

        # Update ambulance status
        a = self.a1
        user = self.u1
        status = AmbulanceStatus.AH.name

        serializer = AmbulanceSerializer(a,
                                         data={
                                             'status': status,
                                         },
                                         partial=True)
        serializer.is_valid()
        serializer.save(updated_by=user)

        # test
        serializer = AmbulanceSerializer(a)
        result = {
            'id': a.id,
            'identifier': a.identifier,
            'comment': a.comment,
            'capability': a.capability,
            'status': status,
            'orientation': a.orientation,
            'location': point2str(a.location),
            'client_id': None,
            'timestamp': date2iso(a.timestamp),
            'updated_by': user.id,
            'updated_on': date2iso(a.updated_on)
        }
        self.assertDictEqual(serializer.data, result)

        # Update ambulance location
        timestamp = timezone.now()
        location = {'latitude': -2., 'longitude': 7.}

        serializer = AmbulanceSerializer(a,
                                         data={
                                             'location': location,
                                             'timestamp': timestamp,
                                         },
                                         partial=True)
        serializer.is_valid()
        serializer.save(updated_by=user)

        # test
        serializer = AmbulanceSerializer(a)
        result = {
            'id': a.id,
            'identifier': a.identifier,
            'comment': a.comment,
            'capability': a.capability,
            'status': a.status,
            'orientation': a.orientation,
            'location': point2str(location),
            'client_id': None,
            'timestamp': date2iso(timestamp),
            'updated_by': user.id,
            'updated_on': date2iso(a.updated_on)
        }
        self.assertDictEqual(serializer.data, result)

        # error update timestamp without location or status
        serializer = AmbulanceSerializer(a,
                                         data={
                                             'timestamp': timestamp,
                                         },
                                         partial=True)
        self.assertEqual(serializer.is_valid(), False)

        # regular authorized user

        # Update ambulance status
        a = self.a3
        user = self.u3
        status = AmbulanceStatus.AH.name

        serializer = AmbulanceSerializer(a,
                                         data={
                                             'status': status,
                                         },
                                         partial=True)
        serializer.is_valid()
        serializer.save(updated_by=user)

        # test
        serializer = AmbulanceSerializer(a)
        result = {
            'id': a.id,
            'identifier': a.identifier,
            'comment': a.comment,
            'capability': a.capability,
            'status': status,
            'orientation': a.orientation,
            'location': point2str(a.location),
            'client_id': None,
            'timestamp': date2iso(a.timestamp),
            'updated_by': user.id,
            'updated_on': date2iso(a.updated_on)
        }
        self.assertDictEqual(serializer.data, result)

        # Update ambulance location
        timestamp = timezone.now()
        location = {'latitude': -2., 'longitude': 7.}

        serializer = AmbulanceSerializer(a,
                                         data={
                                             'location': location,
                                             'timestamp': timestamp
                                         },
                                         partial=True)
        serializer.is_valid()
        serializer.save(updated_by=user)

        # test
        serializer = AmbulanceSerializer(a)
        result = {
            'id': a.id,
            'identifier': a.identifier,
            'comment': a.comment,
            'capability': a.capability,
            'status': a.status,
            'orientation': a.orientation,
            'location': point2str(location),
            'client_id': None,
            'timestamp': date2iso(timestamp),
            'updated_by': user.id,
            'updated_on': date2iso(a.updated_on)
        }
        self.assertDictEqual(serializer.data, result)

        # error update timestamp without location or status
        serializer = AmbulanceSerializer(a,
                                         data={
                                             'timestamp': timestamp,
                                         },
                                         partial=True)
        self.assertEqual(serializer.is_valid(), False)

        # update client
        client1 = loginClient(client_id='client_id_1',
                              user_id=self.u1.id,
                              ambulance=a)
        client1.save()

        client2 = loginClient(client_id='client_id_2', user_id=self.u3.id)
        client2.save()

        self.assertEqual(client1.ambulance, a)
        self.assertEqual(client2.ambulance, None)
        self.assertEqual(a.client, client1)

        # test
        serializer = AmbulanceSerializer(a)
        result = {
            'id': a.id,
            'identifier': a.identifier,
            'comment': a.comment,
            'capability': a.capability,
            'status': a.status,
            'orientation': a.orientation,
            'location': point2str(location),
            'timestamp': date2iso(timestamp),
            'client_id': client1.client_id,
            'updated_by': user.id,
            'updated_on': date2iso(a.updated_on)
        }
        self.assertDictEqual(serializer.data, result)

        # will not change
        client2.ambulance = self.a2
        with self.assertRaises(Exception) as raised:
            with transaction.atomic():
                client2.save()
        self.assertEqual(PermissionDenied, type(raised.exception))

        # will not change
        client2.ambulance = a
        with self.assertRaises(Exception) as raised:
            with transaction.atomic():
                client2.save()
        self.assertEqual(IntegrityError, type(raised.exception))

        client2 = loginClient.objects.get(client_id='client_id_2')
        a = Ambulance.objects.get(id=a.id)

        self.assertEqual(client1.ambulance, a)
        self.assertEqual(client2.ambulance, None)
        self.assertEqual(a.client, client1)

        # test
        serializer = AmbulanceSerializer(a)
        result = {
            'id': a.id,
            'identifier': a.identifier,
            'comment': a.comment,
            'capability': a.capability,
            'status': a.status,
            'orientation': a.orientation,
            'location': point2str(location),
            'timestamp': date2iso(timestamp),
            'client_id': client1.client_id,
            'updated_by': user.id,
            'updated_on': date2iso(a.updated_on)
        }
        self.assertDictEqual(serializer.data, result)

        # will reset
        client1.ambulance = None
        client1.save()
        a = Ambulance.objects.get(id=a.id)

        self.assertEqual(client1.ambulance, None)
        self.assertEqual(client2.ambulance, None)
        self.assertEqual(hasattr(a, 'client'), False)

        # test
        serializer = AmbulanceSerializer(a)
        result = {
            'id': a.id,
            'identifier': a.identifier,
            'comment': a.comment,
            'capability': a.capability,
            'status': a.status,
            'orientation': a.orientation,
            'location': point2str(location),
            'timestamp': date2iso(timestamp),
            'client_id': None,
            'updated_by': user.id,
            'updated_on': date2iso(a.updated_on)
        }
        self.assertDictEqual(serializer.data, result)

        # will change
        client2.ambulance = a
        client2.save()

        self.assertEqual(client1.ambulance, None)
        self.assertEqual(client2.ambulance, a)
        self.assertEqual(a.client, client2)

        # test
        serializer = AmbulanceSerializer(a)
        result = {
            'id': a.id,
            'identifier': a.identifier,
            'comment': a.comment,
            'capability': a.capability,
            'status': a.status,
            'orientation': a.orientation,
            'location': point2str(location),
            'timestamp': date2iso(timestamp),
            'client_id': client2.client_id,
            'updated_by': user.id,
            'updated_on': date2iso(a.updated_on)
        }
        self.assertDictEqual(serializer.data, result)

        # will not change in partial update
        serializer = AmbulanceSerializer(
            a, data={'status': AmbulanceStatus.OS.name}, partial=True)
        serializer.is_valid()
        serializer.save(updated_by=user)

        # test
        serializer = AmbulanceSerializer(a)
        result = {
            'id': a.id,
            'identifier': a.identifier,
            'comment': a.comment,
            'capability': a.capability,
            'status': AmbulanceStatus.OS.name,
            'orientation': a.orientation,
            'location': point2str(location),
            'timestamp': date2iso(timestamp),
            'client_id': client2.client_id,
            'updated_by': user.id,
            'updated_on': date2iso(a.updated_on)
        }
        self.assertDictEqual(serializer.data, result)

        # will not change in partial update
        serializer = AmbulanceSerializer(a,
                                         data={
                                             'status': AmbulanceStatus.PB.name,
                                         },
                                         partial=True)
        serializer.is_valid()
        serializer.save(updated_by=user)

        # test
        serializer = AmbulanceSerializer(a)
        result = {
            'id': a.id,
            'identifier': a.identifier,
            'comment': a.comment,
            'capability': a.capability,
            'status': AmbulanceStatus.PB.name,
            'orientation': a.orientation,
            'location': point2str(location),
            'timestamp': date2iso(timestamp),
            'client_id': client2.client_id,
            'updated_by': user.id,
            'updated_on': date2iso(a.updated_on)
        }
        self.assertDictEqual(serializer.data, result)
Beispiel #14
0
    def test_mqttseed(self):

        # seed
        from django.core import management

        management.call_command('mqttseed', verbosity=1)

        print('>> Processing messages...')

        # Start client as admin
        broker = {
            'HOST': 'localhost',
            'PORT': 1883,
            'KEEPALIVE': 60,
            'CLEAN_SESSION': True
        }
        broker.update(settings.MQTT)
        broker['CLIENT_ID'] = 'test_mqttseed_admin'

        client = MQTTTestClient(broker)
        self.is_connected(client)

        qos = 0

        # Expect settings
        client.expect('settings',
                      JSONRenderer().render(SettingsView.get_settings()), qos)

        # Expect all ambulances
        for ambulance in Ambulance.objects.all():
            client.expect(
                'ambulance/{}/data'.format(ambulance.id),
                JSONRenderer().render(AmbulanceSerializer(ambulance).data),
                qos)

        # Expect all hospitals
        for hospital in Hospital.objects.all():
            client.expect(
                'hospital/{}/data'.format(hospital.id),
                JSONRenderer().render(HospitalSerializer(hospital).data), qos)
            hospital_equipment = hospital.hospitalequipment_set.values(
                'equipment')
            equipment = Equipment.objects.filter(id__in=hospital_equipment)
            client.expect(
                'hospital/{}/metadata'.format(hospital.id),
                JSONRenderer().render(
                    EquipmentSerializer(equipment, many=True).data), qos)

        # Expect all hospital equipments
        for e in HospitalEquipment.objects.all():
            client.expect(
                'hospital/{}/equipment/{}/data'.format(e.hospital.id,
                                                       e.equipment.name),
                JSONRenderer().render(HospitalEquipmentSerializer(e).data),
                qos)

        # Expect all profiles
        for obj in Profile.objects.all():
            client.expect(
                'user/{}/profile'.format(obj.user.username),
                JSONRenderer().render(ExtendedProfileSerializer(obj).data),
                qos)

        # Subscribed?
        self.is_subscribed(client)

        # Done?
        self.loop(client)
        client.wait()

        # Repeat with same client

        client = MQTTTestClient(broker)
        self.is_connected(client)

        qos = 0

        # Expect settings
        client.expect('settings',
                      JSONRenderer().render(SettingsView.get_settings()), qos)

        # Expect all ambulances
        for ambulance in Ambulance.objects.all():
            client.expect(
                'ambulance/{}/data'.format(ambulance.id),
                JSONRenderer().render(AmbulanceSerializer(ambulance).data),
                qos)

        # Expect all hospitals
        for hospital in Hospital.objects.all():
            client.expect(
                'hospital/{}/data'.format(hospital.id),
                JSONRenderer().render(HospitalSerializer(hospital).data), qos)
            hospital_equipment = hospital.hospitalequipment_set.values(
                'equipment')
            equipment = Equipment.objects.filter(id__in=hospital_equipment)
            client.expect(
                'hospital/{}/metadata'.format(hospital.id),
                JSONRenderer().render(
                    EquipmentSerializer(equipment, many=True).data), qos)

        # Expect all hospital equipments
        for e in HospitalEquipment.objects.all():
            client.expect(
                'hospital/{}/equipment/{}/data'.format(e.hospital.id,
                                                       e.equipment.name),
                JSONRenderer().render(HospitalEquipmentSerializer(e).data),
                qos)

        # Expect all profiles
        for obj in Profile.objects.all():
            client.expect(
                'user/{}/profile'.format(obj.user.username),
                JSONRenderer().render(ExtendedProfileSerializer(obj).data),
                qos)

        # Subscribed?
        self.is_subscribed(client)

        # Done?
        self.loop(client)
        client.wait()

        # Repeat with same client and different qos

        client = MQTTTestClient(broker)
        self.is_connected(client)

        qos = 2

        # Expect settings
        client.expect('settings',
                      JSONRenderer().render(SettingsView.get_settings()), qos)

        # Expect all ambulances
        for ambulance in Ambulance.objects.all():
            client.expect(
                'ambulance/{}/data'.format(ambulance.id),
                JSONRenderer().render(AmbulanceSerializer(ambulance).data),
                qos)

        # Expect all hospitals
        for hospital in Hospital.objects.all():
            client.expect(
                'hospital/{}/data'.format(hospital.id),
                JSONRenderer().render(HospitalSerializer(hospital).data), qos)
            hospital_equipment = hospital.hospitalequipment_set.values(
                'equipment')
            equipment = Equipment.objects.filter(id__in=hospital_equipment)
            client.expect(
                'hospital/{}/metadata'.format(hospital.id),
                JSONRenderer().render(
                    EquipmentSerializer(equipment, many=True).data), qos)

        # Expect all hospital equipments
        for e in HospitalEquipment.objects.all():
            client.expect(
                'hospital/{}/equipment/{}/data'.format(e.hospital.id,
                                                       e.equipment.name),
                JSONRenderer().render(HospitalEquipmentSerializer(e).data),
                qos)

        # Expect all profiles
        for obj in Profile.objects.all():
            client.expect(
                'user/{}/profile'.format(obj.user.username),
                JSONRenderer().render(ExtendedProfileSerializer(obj).data),
                qos)

        # Subscribed?
        self.is_subscribed(client)

        # Done?
        self.loop(client)
        client.wait()

        # repeat with another user

        qos = 0

        # Start client as common user
        broker['USERNAME'] = '******'
        broker['PASSWORD'] = '******'
        broker['CLIENT_ID'] = 'test_mqttseed_testuser1'

        client = MQTTTestClient(broker)
        self.is_connected(client)

        # Expect settings
        client.expect('settings',
                      JSONRenderer().render(SettingsView.get_settings()), qos)

        # Expect user profile
        profile = Profile.objects.get(user__username='******')
        client.expect(
            'user/testuser1/profile',
            JSONRenderer().render(ExtendedProfileSerializer(profile).data),
            qos)

        # User Ambulances
        can_read = profile.ambulances.filter(
            can_read=True).values('ambulance_id')
        for ambulance in Ambulance.objects.filter(id__in=can_read):
            client.expect(
                'ambulance/{}/data'.format(ambulance.id),
                JSONRenderer().render(AmbulanceSerializer(ambulance).data),
                qos)

        # User Hospitals
        can_read = profile.hospitals.filter(
            can_read=True).values('hospital_id')
        for hospital in Hospital.objects.filter(id__in=can_read):
            client.expect(
                'hospital/{}/data'.format(hospital.id),
                JSONRenderer().render(HospitalSerializer(hospital).data), qos)

        # Expect all user hospital equipments
        for e in HospitalEquipment.objects.filter(hospital__id__in=can_read):
            client.expect(
                'hospital/{}/equipment/{}/data'.format(e.hospital.id,
                                                       e.equipment.name),
                JSONRenderer().render(HospitalEquipmentSerializer(e).data),
                qos)

        # Subscribed?
        self.is_subscribed(client)

        # Done?
        self.loop(client)
        client.wait()

        # repeat with another user

        qos = 0

        # Start client as common user
        broker['USERNAME'] = '******'
        broker['PASSWORD'] = '******'
        broker['CLIENT_ID'] = 'test_mqttseed_testuser2'

        client = MQTTTestClient(broker)
        self.is_connected(client)

        # Expect settings
        client.expect('settings',
                      JSONRenderer().render(SettingsView.get_settings()), qos)

        # Expect user profile
        profile = Profile.objects.get(user__username='******')
        client.expect(
            'user/testuser2/profile',
            JSONRenderer().render(ExtendedProfileSerializer(profile).data),
            qos)

        # User Ambulances
        can_read = profile.ambulances.filter(
            can_read=True).values('ambulance_id')
        for ambulance in Ambulance.objects.filter(id__in=can_read):
            client.expect(
                'ambulance/{}/data'.format(ambulance.id),
                JSONRenderer().render(AmbulanceSerializer(ambulance).data),
                qos)

        # User Hospitals
        can_read = profile.hospitals.filter(
            can_read=True).values('hospital_id')
        for hospital in Hospital.objects.filter(id__in=can_read):
            client.expect(
                'hospital/{}/data'.format(hospital.id),
                JSONRenderer().render(HospitalSerializer(hospital).data), qos)

        # Expect all user hospital equipments
        for e in HospitalEquipment.objects.filter(hospital__id__in=can_read):
            client.expect(
                'hospital/{}/equipment/{}/data'.format(e.hospital.id,
                                                       e.equipment.name),
                JSONRenderer().render(HospitalEquipmentSerializer(e).data),
                qos)

        # Subscribed?
        self.is_subscribed(client)

        # Done?
        self.loop(client)
        client.wait()
    def test_ambulance_update_serializer(self):

        # superuser first

        # Update ambulance status
        a = self.a1
        user = self.u1
        status = AmbulanceStatus.AH.name

        serializer = AmbulanceSerializer(a,
                                         data={
                                             'status': status,
                                         },
                                         partial=True)
        serializer.is_valid()
        serializer.save(updated_by=user)

        # test
        serializer = AmbulanceSerializer(a)
        result = {
            'id': a.id,
            'identifier': a.identifier,
            'comment': a.comment,
            'capability': a.capability,
            'status': status,
            'orientation': a.orientation,
            'location': point2str(a.location),
            'location_timestamp': date2iso(a.location_timestamp),
            'updated_by': user.id,
            'updated_on': date2iso(a.updated_on)
        }
        self.assertDictEqual(serializer.data, result)

        # Update ambulance location
        location_timestamp = timezone.now()
        location = {'latitude': -2., 'longitude': 7.}

        serializer = AmbulanceSerializer(a,
                                         data={
                                             'location':
                                             location,
                                             'location_timestamp':
                                             location_timestamp,
                                         },
                                         partial=True)
        serializer.is_valid()
        serializer.save(updated_by=user)

        # test
        serializer = AmbulanceSerializer(a)
        result = {
            'id': a.id,
            'identifier': a.identifier,
            'comment': a.comment,
            'capability': a.capability,
            'status': a.status,
            'orientation': a.orientation,
            'location': point2str(location),
            'location_timestamp': date2iso(location_timestamp),
            'updated_by': user.id,
            'updated_on': date2iso(a.updated_on)
        }
        self.assertDictEqual(serializer.data, result)

        # error update location with timestamp
        serializer = AmbulanceSerializer(a,
                                         data={
                                             'location': location,
                                         },
                                         partial=True)
        self.assertEqual(serializer.is_valid(), False)

        # error update timestamp without location
        serializer = AmbulanceSerializer(a,
                                         data={
                                             'location_timestamp':
                                             location_timestamp,
                                         },
                                         partial=True)
        self.assertEqual(serializer.is_valid(), False)

        # regular authorized user

        # Update ambulance status
        a = self.a3
        user = self.u3
        status = AmbulanceStatus.AH.name

        serializer = AmbulanceSerializer(a,
                                         data={
                                             'status': status,
                                         },
                                         partial=True)
        serializer.is_valid()
        serializer.save(updated_by=user)

        # test
        serializer = AmbulanceSerializer(a)
        result = {
            'id': a.id,
            'identifier': a.identifier,
            'comment': a.comment,
            'capability': a.capability,
            'status': status,
            'orientation': a.orientation,
            'location': point2str(a.location),
            'location_timestamp': date2iso(a.location_timestamp),
            'updated_by': user.id,
            'updated_on': date2iso(a.updated_on)
        }
        self.assertDictEqual(serializer.data, result)

        # Update ambulance location
        location_timestamp = timezone.now()
        location = {'latitude': -2., 'longitude': 7.}

        serializer = AmbulanceSerializer(a,
                                         data={
                                             'location':
                                             location,
                                             'location_timestamp':
                                             location_timestamp
                                         },
                                         partial=True)
        serializer.is_valid()
        serializer.save(updated_by=user)

        # test
        serializer = AmbulanceSerializer(a)
        result = {
            'id': a.id,
            'identifier': a.identifier,
            'comment': a.comment,
            'capability': a.capability,
            'status': a.status,
            'orientation': a.orientation,
            'location': point2str(location),
            'location_timestamp': date2iso(location_timestamp),
            'updated_by': user.id,
            'updated_on': date2iso(a.updated_on)
        }
        self.assertDictEqual(serializer.data, result)

        # error update location with timestamp
        serializer = AmbulanceSerializer(a,
                                         data={'location': location},
                                         partial=True)
        self.assertEqual(serializer.is_valid(), False)

        # error update timestamp without location
        serializer = AmbulanceSerializer(a,
                                         data={
                                             'location_timestamp':
                                             location_timestamp,
                                         },
                                         partial=True)
        self.assertEqual(serializer.is_valid(), False)
Beispiel #16
0
    def test_ambulance_update_serializer(self):

        # superuser first

        # Update ambulance status
        a = self.a1
        user = self.u1
        status = AmbulanceStatus.AH.name

        serializer = AmbulanceSerializer(a,
                                         data={
                                             'status': status,
                                         },
                                         partial=True)
        serializer.is_valid()
        serializer.save(updated_by=user)

        # test
        serializer = AmbulanceSerializer(a)
        result = {
            'id': a.id,
            'identifier': a.identifier,
            'comment': a.comment,
            'capability': a.capability,
            'status': status,
            'orientation': a.orientation,
            'location': point2str(a.location),
            'location_client_id': None,
            'timestamp': date2iso(a.timestamp),
            'updated_by': user.id,
            'updated_on': date2iso(a.updated_on)
        }
        self.assertDictEqual(serializer.data, result)

        # Update ambulance location
        timestamp = timezone.now()
        location = {'latitude': -2., 'longitude': 7.}

        serializer = AmbulanceSerializer(a,
                                         data={
                                             'location': location,
                                             'timestamp': timestamp,
                                         },
                                         partial=True)
        serializer.is_valid()
        serializer.save(updated_by=user)

        # test
        serializer = AmbulanceSerializer(a)
        result = {
            'id': a.id,
            'identifier': a.identifier,
            'comment': a.comment,
            'capability': a.capability,
            'status': a.status,
            'orientation': a.orientation,
            'location': point2str(location),
            'location_client_id': None,
            'timestamp': date2iso(timestamp),
            'updated_by': user.id,
            'updated_on': date2iso(a.updated_on)
        }
        self.assertDictEqual(serializer.data, result)

        # error update timestamp without location or status
        serializer = AmbulanceSerializer(a,
                                         data={
                                             'timestamp': timestamp,
                                         },
                                         partial=True)
        self.assertEqual(serializer.is_valid(), False)

        # regular authorized user

        # Update ambulance status
        a = self.a3
        user = self.u3
        status = AmbulanceStatus.AH.name

        serializer = AmbulanceSerializer(a,
                                         data={
                                             'status': status,
                                         },
                                         partial=True)
        serializer.is_valid()
        serializer.save(updated_by=user)

        # test
        serializer = AmbulanceSerializer(a)
        result = {
            'id': a.id,
            'identifier': a.identifier,
            'comment': a.comment,
            'capability': a.capability,
            'status': status,
            'orientation': a.orientation,
            'location': point2str(a.location),
            'location_client_id': None,
            'timestamp': date2iso(a.timestamp),
            'updated_by': user.id,
            'updated_on': date2iso(a.updated_on)
        }
        self.assertDictEqual(serializer.data, result)

        # Update ambulance location
        timestamp = timezone.now()
        location = {'latitude': -2., 'longitude': 7.}

        serializer = AmbulanceSerializer(a,
                                         data={
                                             'location': location,
                                             'timestamp': timestamp
                                         },
                                         partial=True)
        serializer.is_valid()
        serializer.save(updated_by=user)

        # test
        serializer = AmbulanceSerializer(a)
        result = {
            'id': a.id,
            'identifier': a.identifier,
            'comment': a.comment,
            'capability': a.capability,
            'status': a.status,
            'orientation': a.orientation,
            'location': point2str(location),
            'location_client_id': None,
            'timestamp': date2iso(timestamp),
            'updated_by': user.id,
            'updated_on': date2iso(a.updated_on)
        }
        self.assertDictEqual(serializer.data, result)

        # error update timestamp without location or status
        serializer = AmbulanceSerializer(a,
                                         data={
                                             'timestamp': timestamp,
                                         },
                                         partial=True)
        self.assertEqual(serializer.is_valid(), False)

        # update location_client
        client1 = loginClient(client_id='client_id_1', user_id=self.u1.id)
        client1.save()

        client2 = loginClient(client_id='client_id_2', user_id=self.u2.id)
        client2.save()

        serializer = AmbulanceSerializer(
            a, data={'location_client_id': client1.client_id}, partial=True)
        serializer.is_valid()
        serializer.save(updated_by=user)

        # test
        serializer = AmbulanceSerializer(a)
        result = {
            'id': a.id,
            'identifier': a.identifier,
            'comment': a.comment,
            'capability': a.capability,
            'status': a.status,
            'orientation': a.orientation,
            'location': point2str(location),
            'timestamp': date2iso(timestamp),
            'location_client_id': client1.client_id,
            'updated_by': user.id,
            'updated_on': date2iso(a.updated_on)
        }
        self.assertDictEqual(serializer.data, result)

        # will not change
        serializer = AmbulanceSerializer(
            a, data={'location_client_id': client2.client_id}, partial=True)
        serializer.is_valid()
        serializer.save(updated_by=user)

        # test
        serializer = AmbulanceSerializer(a)
        result = {
            'id': a.id,
            'identifier': a.identifier,
            'comment': a.comment,
            'capability': a.capability,
            'status': a.status,
            'orientation': a.orientation,
            'location': point2str(location),
            'timestamp': date2iso(timestamp),
            'location_client_id': client1.client_id,
            'updated_by': user.id,
            'updated_on': date2iso(a.updated_on)
        }
        self.assertDictEqual(serializer.data, result)

        # will reset
        serializer = AmbulanceSerializer(a,
                                         data={'location_client_id': None},
                                         partial=True)
        serializer.is_valid()
        serializer.save(updated_by=user)

        # test
        serializer = AmbulanceSerializer(a)
        result = {
            'id': a.id,
            'identifier': a.identifier,
            'comment': a.comment,
            'capability': a.capability,
            'status': a.status,
            'orientation': a.orientation,
            'location': point2str(location),
            'timestamp': date2iso(timestamp),
            'location_client_id': None,
            'updated_by': user.id,
            'updated_on': date2iso(a.updated_on)
        }
        self.assertDictEqual(serializer.data, result)

        # will change
        serializer = AmbulanceSerializer(
            a, data={'location_client_id': client2.client_id}, partial=True)
        serializer.is_valid()
        serializer.save(updated_by=user)

        # test
        serializer = AmbulanceSerializer(a)
        result = {
            'id': a.id,
            'identifier': a.identifier,
            'comment': a.comment,
            'capability': a.capability,
            'status': a.status,
            'orientation': a.orientation,
            'location': point2str(location),
            'timestamp': date2iso(timestamp),
            'location_client_id': client2.client_id,
            'updated_by': user.id,
            'updated_on': date2iso(a.updated_on)
        }
        self.assertDictEqual(serializer.data, result)

        # will not change in partial update
        serializer = AmbulanceSerializer(
            a, data={'status': AmbulanceStatus.OS.name}, partial=True)
        serializer.is_valid()
        serializer.save(updated_by=user)

        # test
        serializer = AmbulanceSerializer(a)
        result = {
            'id': a.id,
            'identifier': a.identifier,
            'comment': a.comment,
            'capability': a.capability,
            'status': AmbulanceStatus.OS.name,
            'orientation': a.orientation,
            'location': point2str(location),
            'timestamp': date2iso(timestamp),
            'location_client_id': client2.client_id,
            'updated_by': user.id,
            'updated_on': date2iso(a.updated_on)
        }
        self.assertDictEqual(serializer.data, result)

        # will not change in partial update
        serializer = AmbulanceSerializer(a,
                                         data={
                                             'status':
                                             AmbulanceStatus.PB.name,
                                             'location_client_id':
                                             client1.client_id
                                         },
                                         partial=True)
        serializer.is_valid()
        serializer.save(updated_by=user)

        # test
        serializer = AmbulanceSerializer(a)
        result = {
            'id': a.id,
            'identifier': a.identifier,
            'comment': a.comment,
            'capability': a.capability,
            'status': AmbulanceStatus.PB.name,
            'orientation': a.orientation,
            'location': point2str(location),
            'timestamp': date2iso(timestamp),
            'location_client_id': client2.client_id,
            'updated_by': user.id,
            'updated_on': date2iso(a.updated_on)
        }
        self.assertDictEqual(serializer.data, result)

        # invalid client id
        serializer = AmbulanceSerializer(a,
                                         data={
                                             'status': AmbulanceStatus.PB.name,
                                             'location_client_id':
                                             '__invalid__'
                                         },
                                         partial=True)

        self.assertFalse(serializer.is_valid())