Ejemplo n.º 1
0
class ObtainTemporaryAuthTokenTests(APITestCase):

    def setUp(self):
        self.client = APIClient()
        self.user = UserFactory()
        self.user.set_password('Test123!')
        self.user.save()
        self.url = reverse('token_api')

    def test_authenticate(self):
        """
        Ensure we can authenticate on the platform.
        """
        data = {
            'login': '******',
            'password': '******'
        }

        response = self.client.post(self.url, data, format='json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        token = TemporaryToken.objects.get(user__username='******')
        self.assertContains(response, token)

    def test_authenticate_bad_password(self):
        """
        Ensure we can't authenticate with a wrong password'
        """
        data = {
            'login': '******',
            'password': '******'  # No caps on the first letter
        }

        response = self.client.post(self.url, data, format='json')
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

        tokens = TemporaryToken.objects.filter(
            user__username='******'
        ).count()
        self.assertEqual(0, tokens)

    def test_authenticate_bad_username(self):
        """
        Ensure we can't authenticate with a wrong username
        """
        data = {
            'login': '******',  # Forget the `h` in `John`
            'password': '******'
        }

        response = self.client.post(self.url, data, format='json')
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

        tokens = TemporaryToken.objects.filter(
            user__username='******'
        ).count()
        self.assertEqual(0, tokens)
Ejemplo n.º 2
0
class CellTests(APITransactionTestCase):
    def setUp(self):
        self.client = APIClient()

        self.user = UserFactory()
        self.user.set_password('Test123!')
        self.user.save()

        self.admin = AdminFactory()
        self.admin.set_password('Test123!')
        self.admin.save()

        self.random_country = Country.objects.create(
            name="random country",
            iso_code="RC",
        )
        self.random_state_province = StateProvince.objects.create(
            name="random state",
            iso_code="RS",
            country=self.random_country,
        )
        self.address = Address.objects.create(
            address_line1='random address 1',
            postal_code='RAN DOM',
            city='random city',
            state_province=self.random_state_province,
            country=self.random_country,
        )

    def test_create_cell(self):
        """
        Ensure we can create a new cell with just required arguments
        """
        cell = Cell.objects.create(
            name='my cell',
            address=self.address,
        )

        self.assertEqual(cell.name, 'my cell')
        self.assertEqual(cell.address, self.address)

    def test_create_cell_missing_attribute(self):
        """
        Ensure we can't create a new cell without required arguments
        """

        self.assertRaises(IntegrityError, Cell.objects.create)
        self.assertRaises(IntegrityError, Cell.objects.create, name="my cell")
        self.assertRaises(IntegrityError,
                          Cell.objects.create,
                          address=self.address)
Ejemplo n.º 3
0
class TaskTypesTests(APITestCase):
    def setUp(self):
        self.client = APIClient()

        self.user = UserFactory()
        self.user.set_password('Test123!')
        self.user.save()

        self.admin = AdminFactory()
        self.admin.set_password('Test123!')
        self.admin.save()

        self.tasktype = TaskType.objects.create(name='TaskType 1', )

    def test_create_new_tasktype_with_permission(self):
        """
        Ensure we can create a new tasktype if we have the permission.
        """
        data = {
            'name': 'TaskType 3',
        }

        self.client.force_authenticate(user=self.admin)

        response = self.client.post(
            reverse('volunteer:tasktypes'),
            data,
            format='json',
        )

        self.assertEqual(response.status_code, status.HTTP_201_CREATED)

    def test_create_new_tasktype_without_permission(self):
        """
        Ensure we can't create a new tasktype if we don't have the permission.
        """
        data = {
            'name': 'TaskType 3',
        }

        self.client.force_authenticate(user=self.user)

        response = self.client.post(
            reverse('volunteer:tasktypes'),
            data,
            format='json',
        )

        content = {
            "detail": "You are not authorized to create a new tasktype."
        }
        self.assertEqual(json.loads(response.content), content)

        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

    def test_list_tasktype(self):
        """
        Ensure we can list all tasktypes.
        """

        data = [{
            "id": self.tasktype.id,
            "name": self.tasktype.name,
        }]

        self.client.force_authenticate(user=self.user)

        response = self.client.get(reverse('volunteer:tasktypes'))

        self.assertEqual(json.loads(response.content)['results'], data)
        self.assertEqual(json.loads(response.content)['count'], 1)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
Ejemplo n.º 4
0
class ParticipationsIdTests(APITestCase):
    def setUp(self):
        self.client = APIClient()

        self.user = UserFactory()
        self.user.set_password('Test123!')
        self.user.save()

        self.user2 = UserFactory()
        self.user2.set_password('Test123!')
        self.user2.save()

        self.user_cell_manager = UserFactory()
        self.user_cell_manager.set_password('Test123!')

        self.user_cell_manager_no_perms = UserFactory()
        self.user_cell_manager_no_perms.set_password('Test123!')
        self.user_cell_manager_no_perms.save()

        self.admin = AdminFactory()
        self.admin.set_password('Test123!')
        self.admin.save()

        self.random_country = Country.objects.create(
            name="random country",
            iso_code="RC",
        )
        self.random_state_province = StateProvince.objects.create(
            name="random state",
            iso_code="RS",
            country=self.random_country,
        )
        self.address = Address.objects.create(
            address_line1='random address 1',
            postal_code='RAN DOM',
            city='random city',
            state_province=self.random_state_province,
            country=self.random_country,
        )
        self.cell = Cell.objects.create(
            name="my cell",
            address=self.address,
        )
        self.cell_with_manager = Cell.objects.create(
            name="my cell with manager",
            address=self.address,
        )

        self.cell_with_manager.managers = [
            self.user_cell_manager,
        ]
        self.cell_with_manager.save()

        self.cycle = Cycle.objects.create(name="my cycle", )
        self.task_type = TaskType.objects.create(name="my tasktype", )

        start_date = timezone.now() + timezone.timedelta(minutes=100, )
        end_date = start_date + timezone.timedelta(minutes=100, )

        self.event = Event.objects.create(
            cell=self.cell,
            cycle=self.cycle,
            task_type=self.task_type,
            start_date=start_date,
            end_date=end_date,
        )

        self.event2 = Event.objects.create(
            cell=self.cell,
            cycle=self.cycle,
            task_type=self.task_type,
            start_date=start_date,
            end_date=end_date,
        )

        self.event_with_manager = Event.objects.create(
            cell=self.cell_with_manager,
            cycle=self.cycle,
            task_type=self.task_type,
            start_date=start_date,
            end_date=end_date,
        )

        subscription_date = timezone.now()

        with mock.patch('django.utils.timezone.now') as mock_now:
            mock_now.return_value = subscription_date
            self.participation = Participation.objects.create(
                standby=True,
                subscription_date=subscription_date,
                user=self.user,
                event=self.event2,
            )

            self.participation2 = Participation.objects.create(
                standby=True,
                subscription_date=subscription_date,
                user=self.user2,
                event=self.event2,
            )

            self.participation_cell_manager = Participation.objects.create(
                standby=True,
                subscription_date=subscription_date,
                user=self.user2,
                event=self.event_with_manager,
            )

    def test_retrieve_participation_id_not_exist(self):
        """
        Ensure we can't retrieve a participation that doesn't exist.
        """
        self.client.force_authenticate(user=self.user)

        response = self.client.get(
            reverse(
                'volunteer:participations_id',
                kwargs={'pk': 999},
            ),
            format='json',
        )

        content = {"detail": "Not found."}

        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
        self.assertEqual(json.loads(response.content), content)

    def test_retrieve_participation_as_owner(self):
        """
        Ensure we can retrieve a participation as the owner.
        """

        subscription_date_str = self.participation.subscription_date.\
            strftime("%Y-%m-%dT%H:%M:%S.%fZ")

        duration_minutes = self.participation.presence_duration_minutes
        data = dict(
            id=self.participation.id,
            standby=self.participation.standby,
            subscription_date=subscription_date_str,
            event=self.participation.event.id,
            presence_duration_minutes=duration_minutes,
            presence_status=self.participation.presence_status,
        )

        self.client.force_authenticate(user=self.user)

        response = self.client.get(
            reverse(
                'volunteer:participations_id',
                kwargs={'pk': self.participation.id},
            ))

        content = json.loads(response.content)
        del content['user']
        self.assertEqual(content, data)

        self.assertEqual(response.status_code, status.HTTP_200_OK)

    def test_retrieve_participation_basic_serializer(self):
        """
        Ensure we can retrieve a participation.
        Using the BasicSerializer
        """

        subscription_date_str = self.participation2.subscription_date.\
            strftime("%Y-%m-%dT%H:%M:%S.%fZ")

        duration_minutes = self.participation2.presence_duration_minutes
        data = dict(
            id=self.participation2.id,
            standby=self.participation2.standby,
            subscription_date=subscription_date_str,
            event=self.participation2.event.id,
            presence_duration_minutes=duration_minutes,
            presence_status=self.participation2.presence_status,
        )

        self.client.force_authenticate(user=self.user)

        response = self.client.get(
            reverse(
                'volunteer:participations_id',
                kwargs={'pk': self.participation2.id},
            ))

        content = json.loads(response.content)
        del content['user']
        self.assertEqual(content, data)

        self.assertEqual(response.status_code, status.HTTP_200_OK)

    def test_update_participation_with_permission(self):
        """
        Ensure we can update a specific participation if the caller owns it.
        """
        subscription_date = timezone.now()

        subscription_date_str = subscription_date.strftime(
            "%Y-%m-%dT%H:%M:%S.%fZ")

        duration_minutes = self.participation.presence_duration_minutes
        data = dict(
            id=self.participation.id,
            standby=False,
            subscription_date=subscription_date_str,
            event=self.participation.event.id,
            presence_duration_minutes=duration_minutes,
            presence_status=self.participation.presence_status,
        )

        data_post = {
            "standby": False,
        }

        self.client.force_authenticate(user=self.user)

        with mock.patch('django.utils.timezone.now') as mock_now:
            mock_now.return_value = subscription_date
            response = self.client.patch(
                reverse(
                    'volunteer:participations_id',
                    kwargs={'pk': self.participation.id},
                ),
                data_post,
                format='json',
            )

        content = json.loads(response.content)
        del content['user']
        self.assertEqual(content, data)

        self.assertEqual(response.status_code, status.HTTP_200_OK)

    def test_update_participation_with_superuser(self):
        """
        Ensure we can update a specific participation if we are superuser.
        """
        subscription_date = timezone.now()

        subscription_date_str = subscription_date.strftime(
            "%Y-%m-%dT%H:%M:%S.%fZ", )

        data = dict(
            id=self.participation.id,
            standby=self.participation.standby,
            subscription_date=subscription_date_str,
            event=self.participation.event.id,
            presence_duration_minutes=14,
            presence_status='P',
        )

        data_post = {
            "presence_status": 'P',
            "presence_duration_minutes": 14,
        }

        self.client.force_authenticate(user=self.admin)

        with mock.patch('django.utils.timezone.now') as mock_now:
            mock_now.return_value = subscription_date
            response = self.client.patch(
                reverse(
                    'volunteer:participations_id',
                    kwargs={'pk': self.participation.id},
                ),
                data_post,
                format='json',
            )

        content = json.loads(response.content)
        del content['user']
        self.assertEqual(content, data)

        self.assertEqual(response.status_code, status.HTTP_200_OK)

    def test_update_participation_status(self):
        """
        Ensure we can update our own participation status if we're user.
        """
        subscription_date = timezone.now()

        subscription_date_str = subscription_date.strftime(
            "%Y-%m-%dT%H:%M:%S.%fZ", )

        data = dict(
            id=self.participation.id,
            standby=self.participation.standby,
            subscription_date=subscription_date_str,
            event=self.participation.event.id,
            presence_duration_minutes=14,
            presence_status='P',
        )

        data_post = {
            "presence_status": 'P',
            "presence_duration_minutes": 14,
        }

        self.client.force_authenticate(user=self.user)

        with mock.patch('django.utils.timezone.now') as mock_now:
            mock_now.return_value = subscription_date
            response = self.client.patch(
                reverse(
                    'volunteer:participations_id',
                    kwargs={'pk': self.participation.id},
                ),
                data_post,
                format='json',
            )

        content = json.loads(response.content)
        del content['user']
        self.assertEqual(content, data)

        self.assertEqual(response.status_code, status.HTTP_200_OK)

    def test_update_participation_without_permission(self):
        """
        Ensure we can't update a specific participation of another user.
        """
        data_post = {
            "standby": False,
        }

        self.client.force_authenticate(user=self.user)

        response = self.client.patch(
            reverse(
                'volunteer:participations_id',
                kwargs={'pk': self.participation2.id},
            ),
            data_post,
            format='json',
        )

        content = {
            'detail': "You do not have permission to perform this action.",
        }
        self.assertEqual(json.loads(response.content), content)

        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

    def test_update_participation_that_doesnt_exist(self):
        """
        Ensure we can't update a specific participation if it doesn't exist.
        """
        data_post = {
            "standby": True,
        }

        self.client.force_authenticate(user=self.admin)

        response = self.client.patch(
            reverse(
                'volunteer:participations_id',
                kwargs={'pk': 9999},
            ),
            data_post,
            format='json',
        )

        content = {'detail': "Not found."}

        self.assertEqual(json.loads(response.content), content)

        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)

    def test_update_participation_cell_manager(self):
        """
        Ensure we have the right to modify a Participation
        if the user is a Cell manager
        """
        self.client.force_authenticate(user=self.user_cell_manager)

        data_patch = {'presence_status': 'P'}

        subscription_date = timezone.now()

        subscription_date_str = subscription_date.strftime(
            "%Y-%m-%dT%H:%M:%S.%fZ", )

        with mock.patch('django.utils.timezone.now') as mock_now:
            mock_now.return_value = subscription_date
            response = self.client.patch(
                reverse('volunteer:participations_id',
                        kwargs={'pk': self.participation_cell_manager.id}),
                data_patch,
                format='json',
            )

        content = {
            "id": self.participation_cell_manager.id,
            "event": self.participation_cell_manager.event.pk,
            "user": {
                "id": self.user2.id,
                "username": self.user2.username,
                "email": self.user2.email,
                "first_name": self.user2.first_name,
                "last_name": self.user2.last_name,
                "is_active": self.user2.is_active,
                "is_superuser": self.user2.is_superuser,
                "phone": None,
                "mobile": None,
                "managed_cell": []
            },
            "standby": True,
            "subscription_date": subscription_date_str,
            "presence_duration_minutes": None,
            "presence_status": "P"
        }

        self.assertEqual(json.loads(response.content), content)

    def test_update_participation_cell_manager_no_perms(self):
        """
        Ensure we don't have the right to modify a Participation
        if the user is not a Cell manager
        """
        self.client.force_authenticate(user=self.user_cell_manager_no_perms)

        data_patch = {'presence_status': 'P'}

        subscription_date = timezone.now()

        with mock.patch('django.utils.timezone.now') as mock_now:
            mock_now.return_value = subscription_date
            response = self.client.patch(
                reverse('volunteer:participations_id',
                        kwargs={'pk': self.participation_cell_manager.id}),
                data_patch,
                format='json',
            )

        content = {
            'detail': "You do not have permission to perform this action.",
        }

        self.assertEqual(json.loads(response.content), content)

    def test_delete_participation_with_permission(self):
        """
        Ensure we can delete a specific participation if the caller owns it.
        """
        self.client.force_authenticate(user=self.user)

        response = self.client.delete(
            reverse(
                'volunteer:participations_id',
                kwargs={'pk': self.participation.id},
            ), )

        self.assertEqual(response.content, b'')

        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)

    def test_delete_participation_but_event_already_started(self):
        """
        Ensure we can't delete a specific participation if
        the event is already started.
        """
        self.client.force_authenticate(user=self.user)

        start_date = timezone.now()
        end_date = start_date + timezone.timedelta(minutes=100, )

        event = Event.objects.create(
            cell=self.cell,
            cycle=self.cycle,
            task_type=self.task_type,
            start_date=start_date,
            end_date=end_date,
        )

        participation = Participation.objects.create(
            standby=True,
            user=self.user,
            event=event,
        )

        response = self.client.delete(
            reverse(
                'volunteer:participations_id',
                kwargs={'pk': participation.id},
            ), )

        content = {
            'non_field_errors':
            "You can't delete a participation if the "
            "associated event is already started",
        }

        self.assertEqual(json.loads(response.content), content)

        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

    def test_delete_participation_without_permission(self):
        """
        Ensure we can't delete a specific participation without owning it.
        """

        self.client.force_authenticate(user=self.user)

        response = self.client.delete(
            reverse(
                'volunteer:participations_id',
                kwargs={'pk': self.participation2.id},
            ), )

        content = {
            'detail': "You do not have permission to perform this action.",
        }
        self.assertEqual(json.loads(response.content), content)

        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

    def test_delete_participation_that_doesnt_exist(self):
        """
        Ensure we can't delete a specific participation if it doesn't exist
        """
        self.client.force_authenticate(user=self.user)

        response = self.client.delete(
            reverse(
                'volunteer:participations_id',
                kwargs={'pk': 9999},
            ), )

        content = {'detail': "Not found."}
        self.assertEqual(json.loads(response.content), content)

        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
Ejemplo n.º 5
0
class TaskTypesIdTests(APITestCase):

    def setUp(self):
        self.client = APIClient()

        self.user = UserFactory()
        self.user.set_password('Test123!')
        self.user.save()

        self.admin = AdminFactory()
        self.admin.set_password('Test123!')
        self.admin.save()

        self.tasktype = TaskType.objects.create(
            name='TaskType 1',
        )

    def test_retrieve_tasktype_id_not_exist(self):
        """
        Ensure we can't retrieve a TaskType that doesn't exist.
        """
        self.client.force_authenticate(user=self.user)

        response = self.client.get(
            reverse(
                'volunteer:tasktypes_id',
                kwargs={'pk': 999},
            )
        )

        content = {"detail": "Not found."}
        self.assertEqual(json.loads(response.content), content)

        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)

    def test_retrieve_tasktype(self):
        """
        Ensure we can retrieve a TaskType.
        """

        data = {
            "id": self.tasktype.id,
            "name": self.tasktype.name,
        }

        self.client.force_authenticate(user=self.user)

        response = self.client.get(
            reverse(
                'volunteer:tasktypes_id',
                kwargs={'pk': self.tasktype.id},
            )
        )

        self.assertEqual(json.loads(response.content), data)

        self.assertEqual(response.status_code, status.HTTP_200_OK)

    def test_update_tasktype_with_permission(self):
        """
        Ensure we can update a specific TaskType.
        """

        data = {
            "id": self.tasktype.id,
            "name": "my new_name",
        }

        data_post = {
            "name": "my new_name",

        }

        self.client.force_authenticate(user=self.admin)

        response = self.client.patch(
            reverse(
                'volunteer:tasktypes_id',
                kwargs={'pk': self.tasktype.id},
            ),
            data_post,
            format='json',
        )

        self.assertEqual(json.loads(response.content), data)

        self.assertEqual(response.status_code, status.HTTP_200_OK)

    def test_update_tasktype_id_not_exist_with_permission(self):
        """
        Ensure we can update a specific TaskType.
        """

        self.client.force_authenticate(user=self.admin)

        data_post = {
            "name": "my new_name",

        }

        response = self.client.patch(
            reverse(
                'volunteer:tasktypes_id',
                kwargs={'pk': 999},
            ),
            data_post,
            format='json',
        )

        content = {"detail": "Not found."}

        self.assertEqual(json.loads(response.content), content)
        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)

    def test_update_tasktype_without_permission(self):
        """
        Ensure we can't update a specific tasktype without permission.
        """

        data_post = {
            "name": "my new_name",

        }

        self.client.force_authenticate(user=self.user)

        response = self.client.patch(
            reverse(
                'volunteer:tasktypes_id',
                kwargs={'pk': self.tasktype.id},
            ),
            data_post,
            format='json',
        )

        content = {'detail': "You are not authorized to update a tasktype."}

        self.assertEqual(json.loads(response.content), content)

        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

    def test_delete_tasktype_with_permission(self):
        """
        Ensure we can delete a specific TaskType.
        """
        self.client.force_authenticate(user=self.admin)

        response = self.client.delete(
            reverse(
                'volunteer:tasktypes_id',
                kwargs={'pk': self.tasktype.id},
            ),
        )

        self.assertEqual(response.content, b'')

        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)

    def test_delete_tasktype_id_not_exist_with_permission(self):
        """
        Ensure we can delete a specific TaskType.
        """
        self.client.force_authenticate(user=self.admin)

        response = self.client.delete(
            reverse(
                'volunteer:tasktypes_id',
                kwargs={'pk': 999},
            ),
        )

        content = {"detail": "Not found."}

        self.assertEqual(json.loads(response.content), content)
        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)

    def test_delete_tasktype_without_permission(self):
        """
        Ensure we can't delete a specific TaskType without permission.
        """
        self.client.force_authenticate(user=self.user)

        response = self.client.delete(
            reverse(
                'volunteer:tasktypes_id',
                kwargs={'pk': self.tasktype.id},
            ),
        )

        content = {'detail': "You are not authorized to delete a tasktype."}

        self.assertEqual(json.loads(response.content), content)

        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
Ejemplo n.º 6
0
class CellsIdTests(APITestCase):
    def setUp(self):
        self.client = APIClient()

        self.user = UserFactory()
        self.user.set_password('Test123!')
        self.user.save()

        self.other_user = UserFactory()
        self.other_user.set_password('Test123!')
        self.other_user.save()

        self.admin = AdminFactory()
        self.admin.set_password('Test123!')
        self.admin.save()

        self.random_country = Country.objects.create(
            name="Random Country",
            iso_code="RC",
        )
        self.random_state_province = StateProvince.objects.create(
            name="Random State",
            iso_code="RS",
            country=self.random_country,
        )
        self.address = Address.objects.create(
            address_line1='random address 1',
            postal_code='RAN DOM',
            city='random city',
            state_province=self.random_state_province,
            country=self.random_country,
        )
        self.cell = Cell.objects.create(
            name='my cell',
            address=self.address,
        )

    def test_retrieve_cell_id_not_exist(self):
        """
        Ensure we can't retrieve a cell that doesn't exist.
        """
        self.client.force_authenticate(user=self.user)

        response = self.client.get(
            reverse(
                'volunteer:cells_id',
                kwargs={'pk': 999},
            ))

        content = {"detail": "Not found."}
        self.assertEqual(json.loads(response.content), content)

        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)

    def test_retrieve_cell(self):
        """
        Ensure we can retrieve a cell.
        """

        data = {
            "id":
            self.cell.id,
            "name":
            self.cell.name,
            "address":
            dict(
                id=self.address.id,
                address_line1=self.address.address_line1,
                postal_code=self.address.postal_code,
                city=self.address.city,
                state_province=dict(
                    name=self.random_state_province.name,
                    iso_code=self.random_state_province.iso_code,
                ),
                country=dict(
                    name=self.random_country.name,
                    iso_code=self.random_country.iso_code,
                ),
            ),
            "managers": [],
        }

        self.client.force_authenticate(user=self.user)

        response = self.client.get(
            reverse(
                'volunteer:cells_id',
                kwargs={'pk': self.cell.id},
            ))

        data['address']['address_line2'] = ''

        self.assertEqual(json.loads(response.content), data)

        self.assertEqual(response.status_code, status.HTTP_200_OK)

    def test_update_cell_with_permission(self):
        """
        Ensure we can update a specific cell.
        """

        data = {
            "id":
            self.cell.id,
            "name":
            "my new_name",
            "address":
            dict(
                id=self.address.id,
                address_line1=self.address.address_line1,
                address_line2=self.address.address_line2,
                postal_code=self.address.postal_code,
                city=self.address.city,
                state_province=dict(
                    name=self.random_state_province.name,
                    iso_code=self.random_state_province.iso_code,
                ),
                country=dict(
                    name=self.random_country.name,
                    iso_code=self.random_country.iso_code,
                ),
            ),
            "managers": [],
        }

        data_post = {
            "name":
            "my new_name",
            "address":
            dict(
                address_line1=self.address.address_line1,
                postal_code=self.address.postal_code,
                city=self.address.city,
                state_province=dict(
                    name=self.random_state_province.name,
                    iso_code=self.random_state_province.iso_code,
                ),
                country=dict(
                    name=self.random_country.name,
                    iso_code=self.random_country.iso_code,
                ),
            ),
        }

        self.client.force_authenticate(user=self.admin)

        response = self.client.patch(
            reverse(
                'volunteer:cells_id',
                kwargs={'pk': self.cell.id},
            ),
            data_post,
            format='json',
        )

        self.assertEqual(json.loads(response.content), data)

        self.assertEqual(response.status_code, status.HTTP_200_OK)

    def test_update_cell_country(self):
        """
        Ensure we can't update only the country of a cell.
        """

        data_post = {
            "name":
            self.cell.name,
            "address":
            dict(
                address_line1=self.address.address_line1,
                postal_code=self.address.postal_code,
                city=self.address.city,
                state_province=dict(
                    name=self.random_state_province.name,
                    iso_code=self.random_state_province.iso_code,
                ),
                country=dict(
                    name='New Country',
                    iso_code='NC',
                ),
            ),
        }

        self.client.force_authenticate(user=self.admin)

        response = self.client.patch(
            reverse(
                'volunteer:cells_id',
                kwargs={'pk': self.cell.id},
            ),
            data_post,
            format='json',
        )

        # This happens because we are trying to recreate an already existing
        # StateProvince to assign it to a new Country. This causes a iso_code
        # duplication.
        err = {'message': 'A StateProvince with that iso_code already exists'}

        self.assertEqual(json.loads(response.content), err)

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

    def test_update_cell_managers(self):
        """
        Ensure we can update managers of a cells.
        """
        self.assertEqual(self.cell.managers.count(), 0)

        data_post = {"managers": [self.user.id]}

        data = {
            "id":
            self.cell.id,
            "name":
            self.cell.name,
            "address": {
                "id": self.cell.address.id,
                "address_line1": self.cell.address.address_line1,
                "address_line2": '',
                "postal_code": self.cell.address.postal_code,
                "city": self.cell.address.city,
                "state_province": {
                    "name": self.cell.address.state_province.name,
                    "iso_code": self.cell.address.state_province.iso_code,
                },
                "country": {
                    "name": self.cell.address.country.name,
                    "iso_code": self.cell.address.country.iso_code,
                },
            },
            "managers": [
                {
                    "id": self.user.id,
                    "username": self.user.username,
                    "first_name": self.user.first_name,
                    "last_name": self.user.last_name,
                    "email": self.user.email,
                },
            ],
        }
        self.client.force_authenticate(user=self.admin)

        response = self.client.patch(
            reverse(
                'volunteer:cells_id',
                kwargs={'pk': self.cell.id},
            ),
            data_post,
            format='json',
        )

        self.assertEqual(json.loads(response.content), data)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.cell.managers.count(), 1)

        self.assertEquals(self.user.has_perm('volunteer.add_participation'),
                          True)

        self.assertEquals(self.user.has_perm('volunteer.change_participation'),
                          True)

        self.assertEquals(self.user.has_perm('volunteer.delete_participation'),
                          True)

        self.assertEquals(self.user.has_perm('volunteer.add_event'), True)

        self.assertEquals(self.user.has_perm('volunteer.change_event'), True)

        self.assertEquals(self.user.has_perm('volunteer.delete_event'), True)

        # Now let's remove the manager
        data_post = {"managers": []}

        response = self.client.patch(
            reverse(
                'volunteer:cells_id',
                kwargs={'pk': self.cell.id},
            ),
            data_post,
            format='json',
        )

        data['managers'] = []

        self.assertEqual(json.loads(response.content), data)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        self.assertEquals(len(self.user.user_permissions.all()), 0)

        # Testing the signals
        self.cell.managers.add(self.user, self.other_user)
        self.cell.managers.remove(self.user)

    def test_update_multiple_cell_managers(self):
        """
        Ensure we can update multiple managers of a cells.
        """
        self.assertEqual(self.cell.managers.count(), 0)

        data_post = {
            "managers": [
                self.user.id,
                self.admin.id,
            ]
        }

        data = {
            "id":
            self.cell.id,
            "name":
            self.cell.name,
            "address": {
                "id": self.cell.address.id,
                "address_line1": self.cell.address.address_line1,
                "address_line2": '',
                "postal_code": self.cell.address.postal_code,
                "city": self.cell.address.city,
                "state_province": {
                    "name": self.cell.address.state_province.name,
                    "iso_code": self.cell.address.state_province.iso_code,
                },
                "country": {
                    "name": self.cell.address.country.name,
                    "iso_code": self.cell.address.country.iso_code,
                },
            },
            "managers": [
                {
                    "id": self.user.id,
                    "username": self.user.username,
                    "first_name": self.user.first_name,
                    "last_name": self.user.last_name,
                    "email": self.user.email,
                },
                {
                    "id": self.admin.id,
                    "username": self.admin.username,
                    "first_name": self.admin.first_name,
                    "last_name": self.admin.last_name,
                    "email": self.admin.email,
                },
            ],
        }
        self.client.force_authenticate(user=self.admin)

        response = self.client.patch(
            reverse(
                'volunteer:cells_id',
                kwargs={'pk': self.cell.id},
            ),
            data_post,
            format='json',
        )

        self.assertEqual(json.loads(response.content), data)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.cell.managers.count(), 2)

    def test_update_cell_with_empty_address(self):
        """
        Ensure we can't update a cells with an empty address.
        """
        data_post = {
            "address": dict(),
            "managers": [
                self.user.id,
                self.admin.id,
            ]
        }

        self.client.force_authenticate(user=self.admin)

        response = self.client.patch(
            reverse(
                'volunteer:cells_id',
                kwargs={'pk': self.cell.id},
            ),
            data_post,
            format='json',
        )

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

        content = {'message': "Please specify a complete valid address."}
        self.assertEqual(json.loads(response.content), content)

    def test_update_cell_without_permission(self):
        """
        Ensure we can't update a specific cell without permission.
        """
        data_post = {
            "name": "my new_name",
        }

        self.client.force_authenticate(user=self.user)

        response = self.client.patch(
            reverse(
                'volunteer:cells_id',
                kwargs={'pk': self.cell.id},
            ),
            data_post,
            format='json',
        )

        content = {'detail': "You are not authorized to update a cell."}

        self.assertEqual(json.loads(response.content), content)

        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

    def test_update_cell_that_doesnt_exist(self):
        """
        Ensure we can't update a specific cell if it doesn't exist.
        """

        data_post = {
            "name": "my new_name",
        }

        self.client.force_authenticate(user=self.admin)

        response = self.client.patch(
            reverse(
                'volunteer:cells_id',
                kwargs={'pk': 9999},
            ),
            data_post,
            format='json',
        )

        content = {'detail': "Not found."}

        self.assertEqual(json.loads(response.content), content)

        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)

    def test_delete_cell_with_permission(self):
        """
        Ensure we can delete a specific cell.
        """
        self.client.force_authenticate(user=self.admin)

        response = self.client.delete(
            reverse(
                'volunteer:cells_id',
                kwargs={'pk': self.cell.id},
            ), )

        self.assertEqual(response.content, b'')

        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)

    def test_delete_cell_without_permission(self):
        """
        Ensure we can't delete a specific cell without permission.
        """
        self.client.force_authenticate(user=self.user)

        response = self.client.delete(
            reverse(
                'volunteer:cells_id',
                kwargs={'pk': self.cell.id},
            ), )

        content = {'detail': "You are not authorized to delete a cell."}

        self.assertEqual(json.loads(response.content), content)

        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

    def test_delete_cell_that_doesnt_exist(self):
        """
        Ensure we can't delete a specific cell if it doesn't exist
        """
        self.client.force_authenticate(user=self.admin)

        response = self.client.delete(
            reverse(
                'volunteer:cells_id',
                kwargs={'pk': 9999},
            ), )

        content = {'detail': "Not found."}

        self.assertEqual(json.loads(response.content), content)

        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)

    def test_update_cell_with_bad_manager(self):
        """
        Ensure we can't update a cell with a bad manager id.
        """
        self.assertEqual(self.cell.managers.count(), 0)

        data_post = {"managers": [7812]}

        self.client.force_authenticate(user=self.admin)

        response = self.client.patch(
            reverse(
                'volunteer:cells_id',
                kwargs={'pk': self.cell.id},
            ),
            data_post,
            format='json',
        )

        content = json.loads(response.content)
        error = {'message': 'Unknown user with this ID'}
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
        self.assertEqual(content, error)
class EventsIdTests(APITestCase):

    def setUp(self):
        self.client = APIClient()

        self.user = UserFactory()
        self.user.set_password('Test123!')
        self.user.save()

        self.admin = AdminFactory()
        self.admin.set_password('Test123!')
        self.admin.save()

        self.random_country = Country.objects.create(
            name="random country",
            iso_code="RC",
        )
        self.random_state_province = StateProvince.objects.create(
            name="random state",
            iso_code="RS",
            country=self.random_country,
        )
        self.address = Address.objects.create(
            address_line1='random address 1',
            postal_code='RAN DOM',
            city='random city',
            state_province=self.random_state_province,
            country=self.random_country,
        )
        self.cell = Cell.objects.create(
            name="my cell",
            address=self.address,
        )
        self.second_cell = Cell.objects.create(
            name="my second cell",
            address=self.address,
        )
        self.cycle = Cycle.objects.create(
            name="my cycle",
        )
        self.second_cycle = Cycle.objects.create(
            name="my second cycle",
        )
        self.task_type = TaskType.objects.create(
            name="my tasktype",
        )
        self.second_task_type = TaskType.objects.create(
            name="my second tasktype",
        )

        start_date = timezone.now()
        end_date = start_date + timezone.timedelta(
            minutes=100,
        )

        self.event = Event.objects.create(
            cell=self.cell,
            cycle=self.cycle,
            task_type=self.task_type,
            start_date=start_date,
            end_date=end_date,
        )

    def test_retrieve_event_id_not_exist(self):
        """
        Ensure we can't retrieve an event that doesn't exist.
        """
        self.client.force_authenticate(user=self.user)

        response = self.client.get(
            reverse(
                'volunteer:events_id',
                kwargs={'pk': 999},
            ),
            format='json',
        )

        content = {"detail": "Not found."}

        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
        self.assertEqual(json.loads(response.content), content)

    def test_retrieve_event(self):
        """
        Ensure we can retrieve an event.
        """
        self.client.force_authenticate(user=self.user)

        response = self.client.get(
            reverse(
                'volunteer:events_id',
                kwargs={'pk': self.event.id},
            )
        )

        result = json.loads(response.content)
        self.assertEqual(result['id'], self.event.id)
        self.assertEqual(result['cell']['id'], self.event.cell.id)
        self.assertEqual(result['cycle']['id'], self.event.cycle.id)
        self.assertEqual(result['task_type']['id'], self.event.task_type.id)
        self.assertEqual(
            result['nb_volunteers_needed'],
            self.event.nb_volunteers_needed
        )
        self.assertEqual(
            result['nb_volunteers_standby_needed'],
            self.event.nb_volunteers_standby_needed
        )
        self.assertEqual(
            result['nb_volunteers'],
            self.event.nb_volunteers
        )
        self.assertEqual(
            result['nb_volunteers_standby'],
            self.event.nb_volunteers_standby
        )

        self.assertEqual(response.status_code, status.HTTP_200_OK)

    def test_update_event_with_permission(self):
        """
        Ensure we can update a specific event.
        """

        data_post = {
            "nb_volunteers_needed": 10,
            "cell_id": self.second_cell.id,
            "cycle_id": self.second_cycle.id,
            "task_type_id": self.second_task_type.id,
        }

        self.admin.is_superuser = True
        self.admin.save()

        self.client.force_authenticate(user=self.admin)

        response = self.client.patch(
            reverse(
                'volunteer:events_id',
                kwargs={'pk': self.event.id},
            ),
            data_post,
            format='json',
        )

        result = json.loads(response.content)

        self.assertEqual(result['id'], self.event.id)
        self.assertEqual(
            result['cell']['id'],
            self.second_cell.id,
        )
        self.assertEqual(
            result['cycle']['id'],
            self.second_cycle.id,
        )
        self.assertEqual(
            result['task_type']['id'],
            self.second_task_type.id,
        )
        self.assertEqual(result['nb_volunteers_needed'], 10)
        self.assertEqual(
            result['nb_volunteers_standby_needed'],
            self.event.nb_volunteers_standby_needed,
        )
        self.assertEqual(
            result['nb_volunteers'],
            self.event.nb_volunteers
        )
        self.assertEqual(
            result['nb_volunteers_standby'],
            self.event.nb_volunteers_standby
        )

        self.assertEqual(response.status_code, status.HTTP_200_OK)

    def test_update_event_without_permission(self):
        """
        Ensure we can't update a specific event without permission.
        """
        data_post = {
            "nb_volunteers_needed": 10,

        }

        self.client.force_authenticate(user=self.user)

        response = self.client.patch(
            reverse(
                'volunteer:events_id',
                kwargs={'pk': self.event.id},
            ),
            data_post,
            format='json',
        )

        content = {
            'detail': 'You do not have permission to perform this action.'
        }
        self.assertEqual(json.loads(response.content), content)

        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

    def test_update_event_that_doesnt_exist(self):
        """
        Ensure we can't update a specific event if it doesn't exist.
        """
        data_post = {
            "nb_volunteers_needed": 10,
        }

        self.client.force_authenticate(user=self.admin)

        response = self.client.patch(
            reverse(
                'volunteer:events_id',
                kwargs={'pk': 9999},
            ),
            data_post,
            format='json',
        )

        content = {'detail': "Not found."}

        self.assertEqual(json.loads(response.content), content)

        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)

    def test_delete_event_with_permission(self):
        """
        Ensure we can delete a specific event.
        """
        self.client.force_authenticate(user=self.admin)

        response = self.client.delete(
            reverse(
                'volunteer:events_id',
                kwargs={'pk': self.event.id},
            ),
        )

        self.assertEqual(response.content, b'')

        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)

    def test_delete_event_without_permission(self):
        """
        Ensure we can't delete a specific event without permission.
        """
        self.client.force_authenticate(user=self.user)

        response = self.client.delete(
            reverse(
                'volunteer:events_id',
                kwargs={'pk': self.event.id},
            ),
        )

        content = {
            'detail': 'You do not have permission to perform this action.'
        }
        self.assertEqual(json.loads(response.content), content)

        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

    def test_delete_event_that_doesnt_exist(self):
        """
        Ensure we can't delete a specific event if it doesn't exist
        """
        self.client.force_authenticate(user=self.admin)

        response = self.client.delete(
            reverse(
                'volunteer:events_id',
                kwargs={'pk': 9999},
            ),
        )

        content = {'detail': "Not found."}
        self.assertEqual(json.loads(response.content), content)

        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
class ParticipationsTests(APITestCase):
    def setUp(self):
        self.client = APIClient()

        self.user = UserFactory()
        self.user.set_password('Test123!')
        self.user.save()

        self.user2 = UserFactory()
        self.user2.set_password('Test123!')
        self.user2.save()

        self.admin = AdminFactory()
        self.admin.set_password('Test123!')
        self.admin.save()

        self.random_country = Country.objects.create(
            name="random country",
            iso_code="RC",
        )
        self.random_state_province = StateProvince.objects.create(
            name="random state",
            iso_code="RS",
            country=self.random_country,
        )
        self.address = Address.objects.create(
            address_line1='random address 1',
            postal_code='RAN DOM',
            city='random city',
            state_province=self.random_state_province,
            country=self.random_country,
        )
        self.cell = Cell.objects.create(
            name="my cell",
            address=self.address,
        )
        self.cycle = Cycle.objects.create(name="my cycle", )
        self.task_type = TaskType.objects.create(name="my tasktype", )

        start_date = timezone.now() - timezone.timedelta(minutes=100, )
        end_date = start_date + timezone.timedelta(minutes=50, )

        self.cycle_inactive = Cycle.objects.create(
            name="my cycle",
            start_date=start_date,
            end_date=end_date,
        )

        # Some date INSIDE the cycle range
        start_date = start_date + timezone.timedelta(minutes=1, )
        end_date = end_date - timezone.timedelta(minutes=1, )

        self.event = Event.objects.create(
            cell=self.cell,
            cycle=self.cycle,
            task_type=self.task_type,
            start_date=start_date,
            end_date=end_date,
        )

        self.event2 = Event.objects.create(
            cell=self.cell,
            cycle=self.cycle,
            task_type=self.task_type,
            start_date=start_date,
            end_date=end_date,
        )

        subscription_date = timezone.now()

        with mock.patch('django.utils.timezone.now') as mock_now:
            mock_now.return_value = subscription_date
            self.participation = Participation.objects.create(
                standby=True,
                user=self.user,
                event=self.event2,
            )

            self.participation2 = Participation.objects.create(
                standby=True,
                user=self.user2,
                event=self.event2,
            )

            self.participation3 = Participation.objects.create(
                standby=True,
                user=self.user2,
                event=self.event,
            )

    def test_create_new_participation(self):
        """
        Ensure we can create a new participation.
        """
        subscription_date = timezone.now()

        subscription_date_str = subscription_date.strftime(
            "%Y-%m-%dT%H:%M:%S.%fZ", )

        data = {
            'event': self.event.id,
            'user': self.user.id,
            'standby': False,
            'subscription_date': subscription_date,
        }

        self.client.force_authenticate(user=self.user)

        with mock.patch('django.utils.timezone.now') as mock_now:
            mock_now.return_value = subscription_date
            response = self.client.post(
                reverse('volunteer:participations'),
                data,
                format='json',
            )

        content = json.loads(response.content)

        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        self.assertEqual(content['subscription_date'], subscription_date_str)
        self.assertEqual(content['user']['id'], self.user.id)
        self.assertEqual(content['event'], self.event.id)
        self.assertEqual(content['standby'], False)

        # Check the system doesn't return attributes not expected
        attributes = [
            'id',
            'subscription_date',
            'user',
            'event',
            'standby',
            'presence_duration_minutes',
            'presence_status',
        ]

        for key in content.keys():
            self.assertTrue(
                key in attributes,
                'Attribute "{0}" is not expected but is '
                'returned by the system.'.format(key),
            )
            attributes.remove(key)

        # Ensure the system returns all expected attributes
        self.assertTrue(
            len(attributes) == 0,
            'The system failed to return some '
            'attributes : {0}'.format(attributes),
        )

    def test_create_duplicate_participation(self):
        """
        Ensure we can't create a duplicated participation.
        """
        subscription_date = timezone.now()

        data = {
            'event': self.event2.id,
            'standby': False,
        }

        self.client.force_authenticate(user=self.user)

        with mock.patch('django.utils.timezone.now') as mock_now:
            mock_now.return_value = subscription_date
            response = self.client.post(
                reverse('volunteer:participations'),
                data,
                format='json',
            )

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

        content = {
            'non_field_errors': [
                'The fields event, user must make a unique set.',
            ],
        }
        self.assertEqual(json.loads(response.content), content)

    def test_list_participations(self):
        """
        Ensure we can list all participations.
        """
        self.client.force_authenticate(user=self.admin)

        response = self.client.get(
            reverse('volunteer:participations'),
            format='json',
        )

        content = json.loads(response.content)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(content['count'], 3)

        # Check the system doesn't return attributes not expected
        attributes = [
            'id',
            'user',
            'event',
            'subscription_date',
            'standby',
            'presence_duration_minutes',
            'presence_status',
        ]

        for key in content['results'][0].keys():
            self.assertTrue(
                key in attributes,
                'Attribute "{0}" is not expected but is '
                'returned by the system.'.format(key),
            )
            attributes.remove(key)

        # Ensure the system returns all expected attributes
        self.assertTrue(
            len(attributes) == 0,
            'The system failed to return some '
            'attributes : {0}'.format(attributes),
        )

    def test_list_participations_filtered_by_username(self):
        """
        Ensure we can filter permissions by username.
        """
        self.client.force_authenticate(user=self.user)

        url = "{0}?username={1}".format(
            reverse('volunteer:participations'),
            self.user.username,
        )

        response = self.client.get(
            url,
            format='json',
        )

        content = json.loads(response.content)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(content['count'], 1)
        self.assertEqual(content['results'][0]['id'], self.participation.id)

        # Check the system doesn't return attributes not expected
        attributes = [
            'id',
            'user',
            'event',
            'subscription_date',
            'standby',
            'presence_duration_minutes',
            'presence_status',
        ]

        for key in content['results'][0].keys():
            self.assertTrue(
                key in attributes,
                'Attribute "{0}" is not expected but is '
                'returned by the system.'.format(key),
            )
            attributes.remove(key)

        # Ensure the system returns all expected attributes
        self.assertTrue(
            len(attributes) == 0,
            'The system failed to return some '
            'attributes : {0}'.format(attributes),
        )

    def test_list_participations_filter_by_event(self):
        """
        Ensure we can list participations filtered by event.
        """
        self.client.force_authenticate(user=self.admin)

        url = "{0}?event={1}".format(
            reverse('volunteer:participations'),
            self.event.id,
        )

        response = self.client.get(
            url,
            format='json',
        )

        content = json.loads(response.content)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(content['count'], 1)
Ejemplo n.º 9
0
class EventsTests(APITestCase):

    def setUp(self):
        self.client = APIClient()

        self.user = UserFactory()
        self.user.set_password('Test123!')
        self.user.save()

        self.admin = AdminFactory()
        self.admin.set_password('Test123!')
        self.admin.save()

        self.user_cell_manager = UserFactory()
        self.user_cell_manager.set_password('Test123!')
        self.user_cell_manager.save()

        self.random_country = Country.objects.create(
            name="random country",
            iso_code="RC",
        )
        self.random_state_province = StateProvince.objects.create(
            name="random state",
            iso_code="RS",
            country=self.random_country,
        )
        self.address = Address.objects.create(
            address_line1='random address 1',
            postal_code='RAN DOM',
            city='random city',
            state_province=self.random_state_province,
            country=self.random_country,
        )
        self.cell = Cell.objects.create(
            name="my cell",
            address=self.address,
        )

        self.second_cell = Cell.objects.create(
            name="my second cell",
            address=self.address,
        )

        self.cell_with_manager = Cell.objects.create(
            name="my cell with manager",
            address=self.address,
        )
        self.cell_with_manager.save()
        self.cell_with_manager.managers = [self.user_cell_manager, ]
        self.cell_with_manager.save()

        self.cycle = Cycle.objects.create(
            name="my cycle",
        )

        self.task_type = TaskType.objects.create(
            name="my tasktype",
        )

        start_date = timezone.now() - timezone.timedelta(
            minutes=100,
        )
        end_date = start_date + timezone.timedelta(
            minutes=50,
        )

        self.cycle_inactive = Cycle.objects.create(
            name="my cycle",
            start_date=start_date,
            end_date=end_date
        )

        # Some date INSIDE the cycle range
        start_date = start_date + timezone.timedelta(
            minutes=2,
        )
        end_date = end_date - timezone.timedelta(
            minutes=1,
        )

        self.event = Event.objects.create(
            cell=self.cell,
            cycle=self.cycle,
            task_type=self.task_type,
            start_date=start_date,
            end_date=end_date,
        )

        self.event_second_cell = Event.objects.create(
            cell=self.second_cell,
            cycle=self.cycle,
            task_type=self.task_type,
            start_date=start_date,
            end_date=end_date,
        )

        self.event_inactive = Event.objects.create(
            cell=self.cell,
            cycle=self.cycle_inactive,
            task_type=self.task_type,
            start_date=start_date,
            end_date=end_date,
        )

        self.event_inactive_second_cel = Event.objects.create(
            cell=self.second_cell,
            cycle=self.cycle_inactive,
            task_type=self.task_type,
            start_date=start_date,
            end_date=end_date,
        )

        self.event_with_manager = Event.objects.create(
            cell=self.cell_with_manager,
            cycle=self.cycle,
            task_type=self.task_type,
            start_date=start_date,
            end_date=end_date,
        )

        # Decrement start_date for event_2
        start_date = start_date - timezone.timedelta(
            minutes=1,
        )

        self.event_2 = Event.objects.create(
            cell=self.cell,
            cycle=self.cycle_inactive,
            task_type=self.task_type,
            start_date=start_date,
            end_date=end_date,
        )

        self.event_2 = Event.objects.create(
            cell=self.second_cell,
            cycle=self.cycle_inactive,
            task_type=self.task_type,
            start_date=start_date,
            end_date=end_date,
        )

    def test_create_new_event_with_permission(self):
        """
        Ensure we can create a new event if we have the permission.
        """
        start_date = timezone.now()
        end_date = start_date + timezone.timedelta(
            minutes=100,
        )

        start_date_str = start_date.strftime("%Y-%m-%dT%H:%M:%S.%fZ")
        end_date_str = end_date.strftime("%Y-%m-%dT%H:%M:%S.%fZ")

        data = {
            'cell_id': self.cell.id,
            'cycle_id': self.cycle.id,
            'task_type_id': self.task_type.id,
            'start_date': start_date,
            'end_date': end_date,
        }

        self.client.force_authenticate(user=self.admin)

        response = self.client.post(
            reverse('volunteer:events'),
            data,
            format='json',
        )

        content = json.loads(response.content)
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        self.assertEqual(content['start_date'], start_date_str)
        self.assertEqual(content['end_date'], end_date_str)
        self.assertEqual(content['cycle']['id'], self.cycle.id)
        self.assertEqual(content['cell']['id'], self.cell.id)
        self.assertEqual(content['task_type']['id'], self.task_type.id)
        self.assertEqual(content['nb_volunteers_needed'], 0)
        self.assertEqual(content['nb_volunteers_standby_needed'], 0)
        self.assertEqual(content['nb_volunteers'], 0)
        self.assertEqual(content['nb_volunteers_standby'], 0)

        # Check the system doesn't return attributes not expected
        attributes = ['id', 'start_date', 'end_date', 'nb_volunteers_needed',
                      'nb_volunteers_standby_needed', 'volunteers', 'cell',
                      'cycle', 'task_type', 'nb_volunteers_standby',
                      'nb_volunteers']

        for key in content.keys():
            self.assertTrue(
                key in attributes,
                'Attribute "{0}" is not expected but is '
                'returned by the system.'.format(key),
            )
            attributes.remove(key)

        # Ensure the system returns all expected attributes
        self.assertTrue(
            len(attributes) == 0,
            'The system failed to return some '
            'attributes : {0}'.format(attributes),
        )

    def test_create_new_event_with_cell_manager_permission(self):
        """
        Ensure we can create a new event if we have the permission.
        """
        start_date = timezone.now()
        end_date = start_date + timezone.timedelta(
            minutes=100,
        )

        start_date_str = start_date.strftime("%Y-%m-%dT%H:%M:%S.%fZ")
        end_date_str = end_date.strftime("%Y-%m-%dT%H:%M:%S.%fZ")

        data = {
            'cell_id': self.cell_with_manager.id,
            'cycle_id': self.cycle.id,
            'task_type_id': self.task_type.id,
            'start_date': start_date,
            'end_date': end_date,
        }

        self.client.force_authenticate(user=self.user_cell_manager)

        response = self.client.post(
            reverse('volunteer:events'),
            data,
            format='json',
        )

        content = json.loads(response.content)
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        self.assertEqual(content['start_date'], start_date_str)
        self.assertEqual(content['end_date'], end_date_str)
        self.assertEqual(content['cycle']['id'], self.cycle.id)
        self.assertEqual(content['cell']['id'], self.cell_with_manager.id)
        self.assertEqual(content['task_type']['id'], self.task_type.id)
        self.assertEqual(content['nb_volunteers_needed'], 0)
        self.assertEqual(content['nb_volunteers_standby_needed'], 0)
        self.assertEqual(content['nb_volunteers'], 0)
        self.assertEqual(content['nb_volunteers_standby'], 0)

        # Check the system doesn't return attributes not expected
        attributes = ['id', 'start_date', 'end_date', 'nb_volunteers_needed',
                      'nb_volunteers_standby_needed', 'volunteers', 'cell',
                      'cycle', 'task_type', 'nb_volunteers_standby',
                      'nb_volunteers']

        for key in content.keys():
            self.assertTrue(
                key in attributes,
                'Attribute "{0}" is not expected but is '
                'returned by the system.'.format(key),
            )
            attributes.remove(key)

        # Ensure the system returns all expected attributes
        self.assertTrue(
            len(attributes) == 0,
            'The system failed to return some '
            'attributes : {0}'.format(attributes),
        )

    def test_create_new_event_with_start_date_outside_cycle(self):
        """
        Ensure we can't create a new event if start_date is outside
        the cycle specified.
        """
        start_date = self.cycle_inactive.start_date - timezone.timedelta(
            minutes=100,
        )
        end_date = self.cycle_inactive.end_date - timezone.timedelta(
            minutes=1,
        )

        data = {
            'cell_id': self.cell.id,
            'cycle_id': self.cycle_inactive.id,
            'task_type_id': self.task_type.id,
            'start_date': start_date,
            'end_date': end_date,
        }

        self.client.force_authenticate(user=self.admin)

        response = self.client.post(
            reverse('volunteer:events'),
            data,
            format='json',
        )

        content = {
            'non_field_errors': [
                'Start date need to be after start date of the cycle.'
            ]
        }
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
        self.assertEqual(json.loads(response.content), content)

    def test_create_new_event_with_end_date_outside_cycle(self):
        """
        Ensure we can't create a new event if end_date is outside
        the cycle specified.
        """
        start_date = self.cycle_inactive.start_date + timezone.timedelta(
            minutes=1,
        )
        end_date = self.cycle_inactive.end_date + timezone.timedelta(
            minutes=100,
        )

        data = {
            'cell_id': self.cell.id,
            'cycle_id': self.cycle_inactive.id,
            'task_type_id': self.task_type.id,
            'start_date': start_date,
            'end_date': end_date,
        }

        self.client.force_authenticate(user=self.admin)

        response = self.client.post(
            reverse('volunteer:events'),
            data,
            format='json',
        )

        content = {
            'non_field_errors': [
                'End date need to be before the end date of the cycle.'
            ]
        }
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
        self.assertEqual(json.loads(response.content), content)

    def test_create_new_event_with_both_date_outside_cycle(self):
        """
        Ensure we can't create a new event if  both dates are outside
        the cycle specified.
        """
        start_date = self.cycle_inactive.start_date - timezone.timedelta(
            minutes=100,
        )
        end_date = self.cycle_inactive.end_date + timezone.timedelta(
            minutes=100,
        )

        data = {
            'cell_id': self.cell.id,
            'cycle_id': self.cycle_inactive.id,
            'task_type_id': self.task_type.id,
            'start_date': start_date,
            'end_date': end_date,
        }

        self.client.force_authenticate(user=self.admin)

        response = self.client.post(
            reverse('volunteer:events'),
            data,
            format='json',
        )

        content = {
            'non_field_errors': [
                'Start date need to be after start date of the cycle.'
            ]
        }
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
        self.assertEqual(json.loads(response.content), content)

    def test_create_new_event_with_start_date_after_end_date(self):
        """
        Ensure we can't create a new event if a start_date after end_date.
        """
        end_date = self.cycle_inactive.start_date + timezone.timedelta(
            minutes=1,
        )
        start_date = self.cycle_inactive.end_date - timezone.timedelta(
            minutes=1,
        )

        data = {
            'cell_id': self.cell.id,
            'cycle_id': self.cycle_inactive.id,
            'task_type_id': self.task_type.id,
            'start_date': start_date,
            'end_date': end_date,
        }

        self.client.force_authenticate(user=self.admin)

        response = self.client.post(
            reverse('volunteer:events'),
            data,
            format='json',
        )

        content = {
            'non_field_errors': [
                'Start date need to be before the end date.'
            ]
        }
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
        self.assertEqual(json.loads(response.content), content)

    def test_create_new_event_without_permission(self):
        """
        Ensure we can't create a new event if we don't have the permission.
        """
        start_date = timezone.now()
        end_date = start_date + timezone.timedelta(
            minutes=100,
        )

        data = {
            'cell': self.cell.id,
            'cycle': self.cycle.id,
            'task_type': self.task_type.id,
            'start_date': start_date,
            'end_date': end_date,
        }

        self.client.force_authenticate(user=self.user)

        response = self.client.post(
            reverse('volunteer:events'),
            data,
            format='json',
        )

        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

        content = {"detail": "You are not authorized to create a new event."}
        self.assertEqual(json.loads(response.content), content)

    def test_list_events_with_permissions(self):
        """
        Ensure we can list all events. (ordered by start_date by default)
        """
        self.client.force_authenticate(user=self.admin)

        response = self.client.get(
            reverse('volunteer:events'),
            format='json',
        )

        content = json.loads(response.content)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(content['count'], 7)

        # Check the system doesn't return attributes not expected
        attributes = ['id', 'start_date', 'end_date', 'nb_volunteers_needed',
                      'nb_volunteers_standby_needed', 'volunteers', 'cell',
                      'cycle', 'task_type', 'nb_volunteers_standby',
                      'nb_volunteers']

        for key in content['results'][0].keys():
            self.assertTrue(
                key in attributes,
                'Attribute "{0}" is not expected but is '
                'returned by the system.'.format(key),
            )
            attributes.remove(key)

        # Ensure the system returns all expected attributes
        self.assertTrue(
            len(attributes) == 0,
            'The system failed to return some '
            'attributes : {0}'.format(attributes),
        )

        # Make sure the events are ordered in ascending start_date
        self.assertTrue(
            content['results'][0]['start_date'] <=
            content['results'][1]['start_date']
        )
        self.assertTrue(
            content['results'][0]['start_date'] <=
            content['results'][2]['start_date']
        )
        self.assertTrue(
            content['results'][1]['start_date'] <=
            content['results'][2]['start_date']
        )

    def test_list_events_filter_by_cycle(self):
        """
        Ensure we can list event filtered by cycle.
        """
        self.client.force_authenticate(user=self.admin)

        url = "{0}?cycle={1}".format(
            reverse('volunteer:events'),
            self.cycle_inactive.id,
        )

        response = self.client.get(
            url,
            format='json',
        )

        content = json.loads(response.content)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(content['count'], 4)

        # Check the system doesn't return attributes not expected
        attributes = ['id', 'start_date', 'end_date', 'nb_volunteers_needed',
                      'nb_volunteers_standby_needed', 'volunteers', 'cell',
                      'cycle', 'task_type', 'nb_volunteers_standby',
                      'nb_volunteers']

        for key in content['results'][0].keys():
            self.assertTrue(
                key in attributes,
                'Attribute "{0}" is not expected but is '
                'returned by the system.'.format(key),
            )
            attributes.remove(key)

        # Ensure the system returns all expected attributes
        self.assertTrue(
            len(attributes) == 0,
            'The system failed to return some '
            'attributes : {0}'.format(attributes),
        )

    def test_list_events_filter_by_cell(self):
        """
        Ensure we can list event filtered by cycle.
        """
        self.client.force_authenticate(user=self.admin)

        url = "{0}?cell={1}".format(
            reverse('volunteer:events'),
            self.cell.id,
        )

        response = self.client.get(
            url,
            format='json',
        )

        content = json.loads(response.content)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(content['count'], 3)

    def test_list_events_without_permissions(self):
        """
        Ensure we can list only active event (is_active property)
        if we don't have some permissions.
        """
        self.client.force_authenticate(user=self.user)

        response = self.client.get(
            reverse('volunteer:events'),
            format='json',
        )

        content = json.loads(response.content)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(content['count'], 3)

        # Check the system doesn't return attributes not expected
        attributes = ['id', 'start_date', 'end_date', 'nb_volunteers_needed',
                      'nb_volunteers_standby_needed', 'volunteers', 'cell',
                      'cycle', 'task_type', 'nb_volunteers_standby',
                      'nb_volunteers']

        for key in content['results'][0].keys():
            self.assertTrue(
                key in attributes,
                'Attribute "{0}" is not expected but is '
                'returned by the system.'.format(key),
            )
            attributes.remove(key)

        # Ensure the system returns all expected attributes
        self.assertTrue(
            len(attributes) == 0,
            'The system failed to return some '
            'attributes : {0}'.format(attributes),
        )
Ejemplo n.º 10
0
class ParticipationTests(APITransactionTestCase):
    def setUp(self):
        self.client = APIClient()

        self.user = UserFactory()
        self.user.set_password('Test123!')
        self.user.save()

        self.admin = AdminFactory()
        self.admin.set_password('Test123!')
        self.admin.save()

        self.random_country = Country.objects.create(
            name="random country",
            iso_code="RC",
        )
        self.random_state_province = StateProvince.objects.create(
            name="random state",
            iso_code="RS",
            country=self.random_country,
        )
        self.address = Address.objects.create(
            address_line1='random address 1',
            postal_code='RAN DOM',
            city='random city',
            state_province=self.random_state_province,
            country=self.random_country,
        )
        self.cell = Cell.objects.create(
            name="my cell",
            address=self.address,
        )
        self.cycle = Cycle.objects.create(name="my cycle", )
        self.task_type = TaskType.objects.create(name="my tasktype", )

        event_start_date = timezone.now()
        self.event = Event.objects.create(
            cell=self.cell,
            cycle=self.cycle,
            task_type=self.task_type,
            start_date=event_start_date,
            end_date=event_start_date + timezone.timedelta(minutes=100),
        )

        self.participation = Participation.objects.create(
            standby=True,
            user=self.admin,
            event=self.event,
        )

        self.event_2 = Event.objects.create(
            cell=self.cell,
            cycle=self.cycle,
            task_type=self.task_type,
            start_date=event_start_date,
            end_date=event_start_date + timezone.timedelta(minutes=100),
        )

        self.participation_presence = Participation.objects.create(
            standby=True,
            user=self.admin,
            event=self.event_2,
            presence_status='P',
            presence_duration_minutes=300,
        )

    def test_create_participation(self):
        """
        Ensure we can create a new participation with just required arguments
        """

        subscription_date = timezone.now()

        with mock.patch('django.utils.timezone.now') as mock_now:
            mock_now.return_value = subscription_date
            participation = Participation.objects.create(
                standby=True,
                user=self.user,
                event=self.event,
            )

        self.assertEqual(participation.standby, True)
        self.assertEqual(participation.subscription_date, subscription_date)
        self.assertEqual(participation.user.id, self.user.id)
        self.assertEqual(participation.event.id, self.event.id)

    def test_create_participation_missing_event(self):
        """
        Ensure we can't create a new participation without required event
        """
        subscription_date = timezone.now()

        self.assertRaises(
            IntegrityError,
            Participation.objects.create,
            standby=True,
            subscription_date=subscription_date,
            user=self.user,
        )

    def test_create_participation_missing_user(self):
        """
        Ensure we can't create a new participation without required user
        """
        subscription_date = timezone.now()

        self.assertRaises(
            IntegrityError,
            Participation.objects.create,
            standby=True,
            subscription_date=subscription_date,
            event=self.event,
        )

    def test_create_participation_missing_standby(self):
        """
        Ensure we can't create a new participation without required standby
        """
        subscription_date = timezone.now()

        self.assertRaises(
            IntegrityError,
            Participation.objects.create,
            subscription_date=subscription_date,
            user=self.user,
            event=self.event,
        )

    def test_start_date_property(self):
        """
        Check start_date property
        """

        self.assertEqual(self.participation.start_date,
                         self.participation.event.start_date)

    def test_end_date_property(self):
        """
        Check end_date property
        """

        self.assertEqual(self.participation.end_date,
                         self.participation.event.end_date)

    def test_cell_property(self):
        """
        Check cell property
        """

        self.assertEqual(self.participation.cell,
                         self.participation.event.cell.name)

    def test_duration_from_model(self):
        """
        Check duration
        """

        self.assertEqual(self.participation_presence.duration,
                         timedelta(minutes=300))

    def test_duration_from_event_property(self):
        """
        Check duration
        """
        self.assertEqual(self.participation.duration, timedelta(0, 6000))

    def test_name(self):
        self.assertIsNot(self.participation.__str__, None)
class CycleTests(APITestCase):

    def setUp(self):
        pass

    def test_create_cycle(self):
        """
        Ensure we can create a new cycle with just required arguments
        """
        cycle = Cycle.objects.create(
            name='my cycle'
        )

        self.assertEquals(cycle.name, 'my cycle')

    def test_is_active_property_true(self):
        """
        Ensure we have True if the cycle is active
        """
        start_date = timezone.now()
        end_date = start_date + timezone.timedelta(
            minutes=100,
        )

        cycle = Cycle.objects.create(
            name='my cycle',
            start_date=start_date,
            end_date=end_date,
        )

        start_date += timezone.timedelta(days=1)
        end_date += timezone.timedelta(days=1)

        cycle_2 = Cycle.objects.create(
            name='my cycle',
            start_date=start_date,
            end_date=end_date,
        )

        # Event in progress
        self.assertEqual(cycle.is_active, True)
        # Event to come
        self.assertEqual(cycle_2.is_active, True)

    def test_is_active_property_false(self):
        """
        Ensure we have False if the cycle is not active
        """
        start_date = timezone.now()
        end_date = start_date

        cycle = Cycle.objects.create(
            name='my cycle',
            start_date=start_date,
            end_date=end_date,
        )

        # Event has ended
        self.assertEqual(cycle.is_active, False)

    def test_str_method(self):
        """
        Validate the string representation of cycles
        """
        start_date = timezone.now()
        end_date = start_date

        cycle = Cycle.objects.create(
            name='my cycle',
            start_date=start_date,
            end_date=end_date,
        )

        self.assertEqual(str(cycle), cycle.name)

    def test_cycle_generate_report_data_error(self):
        self.user = UserFactory()
        self.user.set_password('Test123!')
        self.user.save()

        self.admin = AdminFactory()
        self.admin.set_password('Test123!')
        self.admin.save()

        self.random_country = Country.objects.create(
            name="random country",
            iso_code="RC",
        )
        self.random_state_province = StateProvince.objects.create(
            name="random state",
            iso_code="RS",
            country=self.random_country,
        )
        self.address = Address.objects.create(
            address_line1='random address 1',
            postal_code='RAN DOM',
            city='random city',
            state_province=self.random_state_province,
            country=self.random_country,
        )
        self.cell = Cell.objects.create(
            name="my cell",
            address=self.address,
        )
        self.cycle = Cycle.objects.create(
            name="my cycle",
        )
        self.task_type = TaskType.objects.create(
            name="my tasktype",
        )

        event_start_date = timezone.now()
        self.event = Event.objects.create(
            cell=self.cell,
            cycle=self.cycle,
            task_type=self.task_type,
            start_date=event_start_date,
            end_date=event_start_date + timezone.timedelta(minutes=100),
        )

        self.participation = Participation.objects.create(
            standby=True,
            user=self.admin,
            event=self.event,
        )

        self.event_2 = Event.objects.create(
            cell=self.cell,
            cycle=self.cycle,
            task_type=self.task_type,
            start_date=event_start_date,
            end_date=event_start_date + timezone.timedelta(minutes=100),
        )

        self.participation_presence = Participation.objects.create(
            standby=True,
            user=self.admin,
            event=self.event_2,
            presence_status='P',
            presence_duration_minutes=300,
        )

        # Test error case
        test_data_error = {
            'error':
                'All of the Participations presence '
                'status must be initialised.',
        }

        data = self.cycle.generate_participation_report_data()

        self.assertEqual(data, test_data_error)

        # Test normal case
        self.participation.presence_status = 'A'
        self.participation.save()

        data = self.cycle.generate_participation_report_data()

        test_data = {
            self.admin.pk: {
                'first_name': self.admin.first_name,
                'last_name': self.admin.last_name,
                'email': self.admin.email,
                'total_time': 300,
            }
        }

        self.assertEqual(data, test_data)
Ejemplo n.º 12
0
class CountriesTests(APITestCase):

    def setUp(self):
        self.client = APIClient()

        self.user = UserFactory()
        self.user.set_password('Test123!')
        self.user.save()

        self.admin = AdminFactory()
        self.admin.set_password('Test123!')
        self.admin.save()

        self.random_country = Country.objects.create(
            name="Random Country 1",
            iso_code="RC",
        )

    def test_create_new_country_with_permission(self):
        """
        Ensure we can create a new country if we have the permission.
        """
        data = dict(
            iso_code='R2',
            name='Random Country 2',
        )

        self.client.force_authenticate(user=self.admin)

        response = self.client.post(
            reverse('location:countries'),
            data,
            format='json',
        )

        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        self.assertEqual(json.loads(response.content), data)

    def test_create_existing_country_with_permission(self):
        """
        Ensure we cannot recreate a country.
        """
        data = dict(
            iso_code='RC',
            name='Random Country 1',
        )

        self.client.force_authenticate(user=self.admin)

        response = self.client.post(
            reverse('location:countries'),
            data,
            format='json',
        )

        err = {
            'iso_code': ['country with this iso code already exists.']
        }

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
        self.assertEqual(json.loads(response.content), err)

    def test_create_new_country_without_permission(self):
        """
        Ensure we can't create a new country if we don't have the permission.
        """
        data = dict(
            iso_code='RC',
            name='Random Country 2',
        )

        self.client.force_authenticate(user=self.user)

        response = self.client.post(
            reverse('location:countries'),
            data,
            format='json',
        )

        content = {"detail": "You are not authorized to create a new country."}
        self.assertEqual(json.loads(response.content), content)

        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

    def test_list_country(self):
        """
        Ensure we can list all countries.
        """

        data = [
            dict(
                iso_code='RC',
                name='Random Country 1',
            ),
        ]

        self.client.force_authenticate(user=self.user)

        response = self.client.get(reverse('location:countries'))

        self.assertEqual(json.loads(response.content)['results'], data)
        self.assertEqual(json.loads(response.content)['count'], 1)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
class AddressesIdTests(APITestCase):
    def setUp(self):
        self.client = APIClient()

        self.user = UserFactory()
        self.user.set_password('Test123!')
        self.user.save()

        self.admin = AdminFactory()
        self.admin.set_password('Test123!')
        self.admin.save()

        self.random_country = Country.objects.create(
            name="Random Country",
            iso_code="RC",
        )
        self.random_state_province = StateProvince.objects.create(
            name="Random State",
            iso_code="RS",
            country=self.random_country,
        )
        self.address = Address.objects.create(
            address_line1='random address 1',
            postal_code='RAN DOM',
            city='random city',
            state_province=self.random_state_province,
            country=self.random_country,
        )

    def test_retrieve_address_id_not_exist(self):
        """
        Ensure we can't retrieve an address that doesn't exist.
        """
        self.client.force_authenticate(user=self.user)

        response = self.client.get(
            reverse(
                'location:addresses_id',
                kwargs={'pk': 999},
            ))

        content = {"detail": "Not found."}
        self.assertEqual(json.loads(response.content), content)

        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)

    def test_retrieve_address(self):
        """
        Ensure we can retrieve an address.
        """

        data = {
            'id':
            self.address.id,
            'address_line1':
            self.address.address_line1,
            'postal_code':
            self.address.postal_code,
            'city':
            self.address.city,
            'state_province':
            dict(
                name=self.random_state_province.name,
                iso_code=self.random_state_province.iso_code,
            ),
            'country':
            dict(
                name=self.random_country.name,
                iso_code=self.random_country.iso_code,
            ),
        }

        self.client.force_authenticate(user=self.user)

        response = self.client.get(
            reverse(
                'location:addresses_id',
                kwargs={'pk': self.address.id},
            ))

        data['address_line2'] = ''

        self.assertEqual(json.loads(response.content), data)

        self.assertEqual(response.status_code, status.HTTP_200_OK)

    def test_update_address_with_permission(self):
        """
        Ensure we can update a specific address.
        """

        data = {
            'id':
            self.address.id,
            'address_line1':
            self.address.address_line1,
            'address_line2':
            "Add second line",
            'postal_code':
            self.address.postal_code,
            'city':
            self.address.city,
            'state_province':
            dict(
                name=self.random_state_province.name,
                iso_code=self.random_state_province.iso_code,
            ),
            'country':
            dict(
                name=self.random_country.name,
                iso_code=self.random_country.iso_code,
            ),
        }

        data_post = {
            'id': self.address.id,
            'address_line1': self.address.address_line1,
            'address_line2': "Add second line",
            'postal_code': self.address.postal_code,
            'city': self.address.city,
            'state_province': self.random_state_province.iso_code,
            'country': self.random_country.iso_code,
        }

        self.client.force_authenticate(user=self.admin)

        response = self.client.patch(
            reverse(
                'location:addresses_id',
                kwargs={'pk': self.address.id},
            ),
            data_post,
            format='json',
        )

        self.assertEqual(json.loads(response.content), data)

        self.assertEqual(response.status_code, status.HTTP_200_OK)

    def test_update_address_country(self):
        """
        Ensure we can't update only the country of an address.
        """
        Country.objects.create(name="New Country", iso_code="NC")

        data_post = dict(
            address_line1=self.address.address_line1,
            postal_code=self.address.postal_code,
            city=self.address.city,
            state_province=self.random_state_province.iso_code,
            country='NC',
        )

        self.client.force_authenticate(user=self.admin)

        response = self.client.patch(
            reverse(
                'location:addresses_id',
                kwargs={'pk': self.address.id},
            ),
            data_post,
            format='json',
        )

        err = {'detail': 'The StateProvince should be linked to the Country'}

        self.assertEqual(json.loads(response.content), err)

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

    def test_update_address_without_permission(self):
        """
        Ensure we can't update a specific address without permission.
        """
        data_post = {
            "address_line1": "my address",
        }

        self.client.force_authenticate(user=self.user)

        response = self.client.patch(
            reverse(
                'location:addresses_id',
                kwargs={'pk': self.address.id},
            ),
            data_post,
            format='json',
        )

        content = {'detail': "You are not authorized to update an address."}

        self.assertEqual(json.loads(response.content), content)

        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

    def test_update_address_that_doesnt_exist(self):
        """
        Ensure we can't update a specific address if it doesn't exist.
        """

        data_post = {
            "name": "my new_name",
        }

        self.client.force_authenticate(user=self.admin)

        response = self.client.patch(
            reverse(
                'location:addresses_id',
                kwargs={'pk': 9999},
            ),
            data_post,
            format='json',
        )

        content = {'detail': "Not found."}

        self.assertEqual(json.loads(response.content), content)

        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)

    def test_delete_address_with_permission(self):
        """
        Ensure we can delete a specific address.
        """
        self.client.force_authenticate(user=self.admin)

        response = self.client.delete(
            reverse(
                'location:addresses_id',
                kwargs={'pk': self.address.id},
            ), )

        self.assertEqual(response.content, b'')

        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)

    def test_delete_address_without_permission(self):
        """
        Ensure we can't delete a specific address without permission.
        """
        self.client.force_authenticate(user=self.user)

        response = self.client.delete(
            reverse(
                'location:addresses_id',
                kwargs={'pk': self.address.id},
            ), )

        content = {'detail': "You are not authorized to delete an address."}

        self.assertEqual(json.loads(response.content), content)

        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

    def test_delete_address_that_doesnt_exist(self):
        """
        Ensure we can't delete a specific address if it doesn't exist
        """
        self.client.force_authenticate(user=self.admin)

        response = self.client.delete(
            reverse(
                'location:addresses_id',
                kwargs={'pk': 9999},
            ), )

        content = {'detail': "Not found."}

        self.assertEqual(json.loads(response.content), content)

        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
class CyclesIdTests(APITestCase):
    def setUp(self):
        self.client = APIClient()

        self.user = UserFactory()
        self.user.set_password('Test123!')
        self.user.save()

        self.admin = AdminFactory()
        self.admin.set_password('Test123!')
        self.admin.save()

        self.cycle = Cycle.objects.create(
            name='Cycle 1',
            start_date=timezone.now(),
            end_date=timezone.now() + timezone.timedelta(minutes=100, ),
        )

    def test_retrieve_cycle_id_not_exist(self):
        """
        Ensure we can't retrieve a cycle that doesn't exist.
        """
        self.client.force_authenticate(user=self.user)

        response = self.client.get(
            reverse(
                'volunteer:cycles_id',
                kwargs={'pk': 999},
            ))

        content = {"detail": "Not found."}
        self.assertEqual(json.loads(response.content), content)

        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)

    def test_retrieve_cycle(self):
        """
        Ensure we can retrieve a cycle.
        """
        start_date = self.cycle.start_date.strftime("%Y-%m-%dT%H:%M:%S.%fZ")
        end_date = self.cycle.end_date.strftime("%Y-%m-%dT%H:%M:%S.%fZ")

        data = {
            "id": self.cycle.id,
            "name": self.cycle.name,
            "start_date": start_date,
            "end_date": end_date,
        }

        self.client.force_authenticate(user=self.user)

        response = self.client.get(
            reverse(
                'volunteer:cycles_id',
                kwargs={'pk': self.cycle.id},
            ))

        self.assertEqual(json.loads(response.content), data)

        self.assertEqual(response.status_code, status.HTTP_200_OK)

    def test_update_cycle_with_permission(self):
        """
        Ensure we can update a specific cycle.
        """
        start_date = self.cycle.start_date.strftime("%Y-%m-%dT%H:%M:%S.%fZ")
        end_date = self.cycle.end_date.strftime("%Y-%m-%dT%H:%M:%S.%fZ")

        data = {
            "id": self.cycle.id,
            "name": "my new_name",
            "start_date": start_date,
            "end_date": end_date,
        }

        data_post = {
            "name": "my new_name",
        }

        self.client.force_authenticate(user=self.admin)

        response = self.client.patch(
            reverse(
                'volunteer:cycles_id',
                kwargs={'pk': self.cycle.id},
            ),
            data_post,
            format='json',
        )

        self.assertEqual(json.loads(response.content), data)

        self.assertEqual(response.status_code, status.HTTP_200_OK)

    def test_update_cycle_without_permission(self):
        """
        Ensure we can't update a specific cycle without permission.
        """
        data_post = {
            "name": "my new_name",
        }

        self.client.force_authenticate(user=self.user)

        response = self.client.patch(
            reverse(
                'volunteer:cycles_id',
                kwargs={'pk': self.cycle.id},
            ),
            data_post,
            format='json',
        )

        content = {'detail': "You are not authorized to update a cycle."}

        self.assertEqual(json.loads(response.content), content)

        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

    def test_update_cycle_that_doesnt_exist(self):
        """
        Ensure we can't update a specific cycle if it doesn't exist.
        """
        start_date = self.cycle.start_date.strftime("%Y-%m-%dT%H:%M:%S.%fZ")
        end_date = self.cycle.end_date.strftime("%Y-%m-%dT%H:%M:%S.%fZ")

        data_post = {
            "name": "my new_name",
        }

        self.client.force_authenticate(user=self.admin)

        response = self.client.patch(
            reverse(
                'volunteer:cycles_id',
                kwargs={'pk': 9999},
            ),
            data_post,
            format='json',
        )

        content = {'detail': "Not found."}

        self.assertEqual(json.loads(response.content), content)

        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)

    def test_delete_cycle_with_permission(self):
        """
        Ensure we can delete a specific cycle.
        """
        self.client.force_authenticate(user=self.admin)

        response = self.client.delete(
            reverse(
                'volunteer:cycles_id',
                kwargs={'pk': self.cycle.id},
            ), )

        self.assertEqual(response.content, b'')

        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)

    def test_delete_cycle_without_permission(self):
        """
        Ensure we can't delete a specific cycle without permission.
        """
        self.client.force_authenticate(user=self.user)

        response = self.client.delete(
            reverse(
                'volunteer:cycles_id',
                kwargs={'pk': self.cycle.id},
            ), )

        content = {'detail': "You are not authorized to delete a cycle."}

        self.assertEqual(json.loads(response.content), content)

        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

    def test_delete_cycle_that_doesnt_exist(self):
        """
        Ensure we can't delete a specific cycle if it doesn't exist
        """
        self.client.force_authenticate(user=self.admin)

        response = self.client.delete(
            reverse(
                'volunteer:cycles_id',
                kwargs={'pk': 9999},
            ), )

        content = {'detail': "Not found."}

        self.assertEqual(json.loads(response.content), content)

        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
Ejemplo n.º 15
0
class ParticipationsTests(APITestCase):
    def setUp(self):

        user = User.objects.create_user('admin', '*****@*****.**',
                                        'password')
        user.is_staff = True
        user.is_superuser = True
        user.save()
        self.client.login(username='******', password='******')

        self.user = UserFactory()
        self.user.set_password('Test123!')
        self.user.save()

        self.user2 = UserFactory()
        self.user2.set_password('Test123!')
        self.user2.save()

        self.random_country = Country.objects.create(
            name="random country",
            iso_code="RC",
        )
        self.random_state_province = StateProvince.objects.create(
            name="random state",
            iso_code="RS",
            country=self.random_country,
        )
        self.address = Address.objects.create(
            address_line1='random address 1',
            postal_code='RAN DOM',
            city='random city',
            state_province=self.random_state_province,
            country=self.random_country,
        )
        self.cell = Cell.objects.create(
            name="my cell",
            address=self.address,
        )
        self.cycle = Cycle.objects.create(name="my cycle", )
        self.task_type = TaskType.objects.create(name="my tasktype", )

        start_date = timezone.now() - timezone.timedelta(minutes=100, )
        end_date = start_date + timezone.timedelta(minutes=50, )

        self.cycle_inactive = Cycle.objects.create(
            name="my cycle",
            start_date=start_date,
            end_date=end_date,
        )

        # Some date INSIDE the cycle range
        start_date = start_date + timezone.timedelta(minutes=1, )
        end_date = end_date - timezone.timedelta(minutes=1, )

        self.event = Event.objects.create(
            cell=self.cell,
            cycle=self.cycle,
            task_type=self.task_type,
            start_date=start_date,
            end_date=end_date,
        )

        self.event2 = Event.objects.create(
            cell=self.cell,
            cycle=self.cycle,
            task_type=self.task_type,
            start_date=start_date,
            end_date=end_date,
        )

        subscription_date = timezone.now()

        with mock.patch('django.utils.timezone.now') as mock_now:
            mock_now.return_value = subscription_date
            self.participation = Participation.objects.create(
                standby=True,
                user=self.user,
                event=self.event2,
            )

            self.participation2 = Participation.objects.create(
                standby=True,
                user=self.user2,
                event=self.event2,
            )

        self.dataset = ParticipationResource().export()

    def test_exportation_header(self):
        csv_header = "standby,first_name,last_name,email,phone," \
                     "mobile,event__start_date,event__end_date,cell"
        self.assertNotIn(self.dataset.csv, csv_header)

    def test_export(self):
        data = {
            'action': ['export_admin_action'],
            'file_format': '0',
            '_selected_action': [str(self.participation.id)],
        }
        response = self.client.post('/admin/volunteer/participation/', data)

        self.assertContains(response,
                            self.participation.user.email,
                            status_code=200)
        self.assertNotContains(response,
                               self.participation2.user.email,
                               status_code=200)
        self.assertTrue(response.has_header("Content-Disposition"))

    def test_export_no_format_selected(self):
        data = {
            'action': ['export_admin_action'],
            '_selected_action': [str(self.participation.id)],
        }
        response = self.client.post('/admin/volunteer/participation/', data)
        self.assertEqual(response.status_code, 302)
Ejemplo n.º 16
0
class ObtainTemporaryAuthTokenTests(APITestCase):

    def setUp(self):
        self.client = APIClient()
        self.user = UserFactory()
        self.user.set_password('Test123!')
        self.user.save()
        self.url = reverse('token_api')

    def test_authenticate(self):
        """
        Ensure we can authenticate on the platform.
        """
        data = {
            'login': self.user.username,
            'password': '******'
        }

        response = self.client.post(self.url, data, format='json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        token = TemporaryToken.objects.get(
            user__username=self.user.username,
        )
        self.assertContains(response, token)

    def test_authenticate_expired_token(self):
        """
        Ensure we can authenticate on the platform when token is expired.
        """
        data = {
            'login': self.user.username,
            'password': '******'
        }

        response = self.client.post(self.url, data, format='json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        token_old = TemporaryToken.objects.get(
            user__username=self.user.username,
        )
        token_old.expire()

        response = self.client.post(self.url, data, format='json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        token_new = TemporaryToken.objects.get(
            user__username=self.user.username,
        )

        self.assertNotContains(response, token_old)
        self.assertContains(response, token_new)

    def test_authenticate_bad_password(self):
        """
        Ensure we can't authenticate with a wrong password'
        """
        data = {
            'login': self.user.username,
            'password': '******'  # No caps on the first letter
        }

        response = self.client.post(self.url, data, format='json')
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

        tokens = TemporaryToken.objects.filter(
            user__username='******'
        ).count()
        self.assertEqual(0, tokens)

    def test_authenticate_bad_username(self):
        """
        Ensure we can't authenticate with a wrong username
        """
        data = {
            'login': '******',  # Forget the `h` in `John`
            'password': '******'
        }

        response = self.client.post(self.url, data, format='json')
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

        tokens = TemporaryToken.objects.filter(
            user__username='******'
        ).count()
        self.assertEqual(0, tokens)

    def test_authenticate_inactive(self):
        """
        Ensure we can't authenticate if user is inactive
        """
        data = {
            'login': self.user.username,
            'password': '******'
        }

        User.objects.filter(id=self.user.id).update(is_active=False)

        response = self.client.post(self.url, data, format='json')

        content = {
            "non_field_errors": [
                "Unable to log in with provided credentials."
                ]
            }

        self.assertEqual(json.loads(response.content), content)
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

        tokens = TemporaryToken.objects.filter(
            user__username=self.user.username
        ).count()
        self.assertEqual(0, tokens)

    def test_authenticate_missing_parameter(self):
        """
        Ensure we can't authenticate if "login" is not provided.
        """
        data = {
            'password': '******'
        }

        response = self.client.post(self.url, data, format='json')

        content = {
            'login': [
                'This field is required.'
                ]
            }

        self.assertEqual(json.loads(response.content), content)
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

        tokens = TemporaryToken.objects.filter(
            user__username=self.user.username
        ).count()
        self.assertEqual(0, tokens)
class CellExportationTests(APITestCase):

    def setUp(self):
        self.client = APIClient()

        self.user = UserFactory()
        self.user.set_password('Test123!')
        self.user.save()

        self.user2 = UserFactory()
        self.user2.set_password('Test123!')
        self.user2.save()

        self.admin = AdminFactory()
        self.admin.set_password('Test123!')
        self.admin.save()

        self.random_country = Country.objects.create(
            name="random country",
            iso_code="RC",
        )
        self.random_state_province = StateProvince.objects.create(
            name="random state",
            iso_code="RS",
            country=self.random_country,
        )
        self.address = Address.objects.create(
            address_line1='random address 1',
            postal_code='RAN DOM',
            city='random city',
            state_province=self.random_state_province,
            country=self.random_country,
        )
        self.cell = Cell.objects.create(
            name="my cell",
            address=self.address,
        )
        self.cycle = Cycle.objects.create(
            name="my cycle",
        )
        self.task_type = TaskType.objects.create(
            name="my tasktype",
        )

        start_date = timezone.now() - timezone.timedelta(
            minutes=100,
        )
        end_date = start_date + timezone.timedelta(
            minutes=50,
        )

        self.cycle_inactive = Cycle.objects.create(
            name="my cycle",
            start_date=start_date,
            end_date=end_date,
        )

        # Some date INSIDE the cycle range
        start_date = start_date + timezone.timedelta(
            minutes=1,
        )
        end_date = end_date - timezone.timedelta(
            minutes=1,
        )

        self.event = Event.objects.create(
            cell=self.cell,
            cycle=self.cycle,
            task_type=self.task_type,
            start_date=start_date,
            end_date=end_date,
        )

        self.event2 = Event.objects.create(
            cell=self.cell,
            cycle=self.cycle,
            task_type=self.task_type,
            start_date=start_date,
            end_date=end_date,
        )

        subscription_date = timezone.now()

        with mock.patch('django.utils.timezone.now') as mock_now:
            mock_now.return_value = subscription_date
            self.participation = Participation.objects.create(
                standby=True,
                user=self.user,
                event=self.event2,
            )

            self.participation2 = Participation.objects.create(
                standby=True,
                user=self.user2,
                event=self.event2,
            )

            self.participation3 = Participation.objects.create(
                standby=True,
                user=self.user2,
                event=self.event,
            )

            "Create temp directory and update MEDIA_ROOT and default storage."
            settings._original_media_root = settings.MEDIA_ROOT
            settings._original_file_storage = settings.DEFAULT_FILE_STORAGE
            self._temp_media = tempfile.mkdtemp()
            settings.MEDIA_ROOT = self._temp_media
            settings.DEFAULT_FILE_STORAGE = \
                'django.core.files.storage.FileSystemStorage'

    def tearDown(self):
        "Delete temp storage."
        shutil.rmtree(self._temp_media, ignore_errors=True)
        settings.MEDIA_ROOT = settings._original_media_root
        del settings._original_media_root
        settings.DEFAULT_FILE_STORAGE = settings._original_file_storage
        del settings._original_file_storage

    @override_settings(DEBUG=True)
    def test_cell_exportation(self):
        """
        Ensure we can export Participation from a Cell.
        """

        self.client.force_authenticate(user=self.user)

        response = self.client.get(
            '/volunteer/cells/%s/export' % self.cell.pk,
            format='json',
        )

        content = json.loads(response.content)

        # get today date without time
        now = timezone.now()
        now = now.replace(hour=0, minute=0, second=0, microsecond=0)

        actual_file_path = \
            '/%scell_export/%s_%s.csv' % \
            (settings.MEDIA_URL, self.cell.pk, now.strftime('%Y%m%d'))

        data_compare = {
            'export_link': actual_file_path
        }

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(content, data_compare)

        data = [
            'standby,first_name,last_name,email,phone,mobile,'
            'event__start_date,event__end_date,task_type,'
            'cell,presence_status,presence_duration_minutes\n',

            '1,%s,%s,%s,,,%s,%s,%s,%s,%s,\n' % (
                self.participation2.user.first_name,
                self.participation2.user.last_name,
                self.participation2.user.email,
                self.participation2.event.start_date
                    .strftime("%Y-%m-%d %H:%M:%S"),
                self.participation2.event.end_date
                    .strftime("%Y-%m-%d %H:%M:%S"),
                self.participation2.event.task_type.name,
                self.participation2.cell,
                self.participation2.presence_status,
            ),

            '1,%s,%s,%s,,,%s,%s,%s,%s,%s,\n' % (
                self.participation.user.first_name,
                self.participation.user.last_name,
                self.participation.user.email,
                self.participation.event.start_date
                    .strftime("%Y-%m-%d %H:%M:%S"),
                self.participation.event.end_date
                    .strftime("%Y-%m-%d %H:%M:%S"),
                self.participation.event.task_type.name,
                self.participation.cell,
                self.participation.presence_status,
            ),

            '1,%s,%s,%s,,,%s,%s,%s,%s,%s,\n' % (
                self.participation3.user.first_name,
                self.participation3.user.last_name,
                self.participation3.user.email,
                self.participation3.event.start_date
                    .strftime("%Y-%m-%d %H:%M:%S"),
                self.participation3.event.end_date
                    .strftime("%Y-%m-%d %H:%M:%S"),
                self.participation3.event.task_type.name,
                self.participation3.cell,
                self.participation3.presence_status,
            )]

        actual_file_path = \
            '%s/cell_export/%s_%s.csv' % \
            (self._temp_media, self.cell.pk, now.strftime('%Y%m%d'))

        with open(actual_file_path) as fp:
            line = fp.readline()
            cnt = 0
            while line:

                self.assertEqual(line, data[cnt])

                line = fp.readline()
                cnt += 1
class CountriesIdTests(APITestCase):
    def setUp(self):
        self.client = APIClient()

        self.user = UserFactory()
        self.user.set_password('Test123!')
        self.user.save()

        self.admin = AdminFactory()
        self.admin.set_password('Test123!')
        self.admin.save()

        self.random_country = Country.objects.create(
            name="Random Country",
            iso_code="RC",
        )

    def test_retrieve_country_id_not_exist(self):
        """
        Ensure we can't retrieve an country that doesn't exist.
        """
        self.client.force_authenticate(user=self.user)

        response = self.client.get(
            reverse(
                'location:countries_id',
                kwargs={'pk': "XX"},
            ))

        content = {"detail": "Not found."}
        self.assertEqual(json.loads(response.content), content)

        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)

    def test_retrieve_country(self):
        """
        Ensure we can retrieve an country.
        """

        data = {
            'name': self.random_country.name,
            'iso_code': self.random_country.iso_code,
        }

        self.client.force_authenticate(user=self.user)

        response = self.client.get(
            reverse(
                'location:countries_id',
                kwargs={'pk': self.random_country.iso_code},
            ))

        self.assertEqual(json.loads(response.content), data)

        self.assertEqual(response.status_code, status.HTTP_200_OK)

    def test_update_country_with_permission(self):
        """
        Ensure we can update a specific country.
        """

        data = {
            'iso_code': self.random_country.iso_code,
            'name': "new country",
        }

        data_post = {
            'iso_code': self.random_country.iso_code,
            'name': "new country",
        }

        self.client.force_authenticate(user=self.admin)

        response = self.client.patch(
            reverse(
                'location:countries_id',
                kwargs={'pk': self.random_country.iso_code},
            ),
            data_post,
            format='json',
        )

        self.assertEqual(json.loads(response.content), data)

        self.assertEqual(response.status_code, status.HTTP_200_OK)

    def test_update_country_without_permission(self):
        """
        Ensure we can't update a specific country without permission.
        """
        data_post = {
            "name": "my country",
        }

        self.client.force_authenticate(user=self.user)

        response = self.client.patch(
            reverse(
                'location:countries_id',
                kwargs={'pk': self.random_country.iso_code},
            ),
            data_post,
            format='json',
        )

        content = {'detail': "You are not authorized to update a country."}

        self.assertEqual(json.loads(response.content), content)

        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

    def test_update_country_that_doesnt_exist(self):
        """
        Ensure we can't update a specific country if it doesn't exist.
        """

        data_post = {
            "name": "my new_name",
        }

        self.client.force_authenticate(user=self.admin)

        response = self.client.patch(
            reverse(
                'location:countries_id',
                kwargs={'pk': "XX"},
            ),
            data_post,
            format='json',
        )

        content = {'detail': "Not found."}

        self.assertEqual(json.loads(response.content), content)

        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)

    def test_delete_country_with_permission(self):
        """
        Ensure we can delete a specific country.
        """
        self.client.force_authenticate(user=self.admin)

        response = self.client.delete(
            reverse(
                'location:countries_id',
                kwargs={'pk': self.random_country.iso_code},
            ), )

        self.assertEqual(response.content, b'')

        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)

    def test_delete_country_without_permission(self):
        """
        Ensure we can't delete a specific country without permission.
        """
        self.client.force_authenticate(user=self.user)

        response = self.client.delete(
            reverse(
                'location:countries_id',
                kwargs={'pk': self.random_country.iso_code},
            ), )

        content = {'detail': "You are not authorized to delete a country."}

        self.assertEqual(json.loads(response.content), content)

        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

    def test_delete_country_that_doesnt_exist(self):
        """
        Ensure we can't delete a specific country if it doesn't exist
        """
        self.client.force_authenticate(user=self.admin)

        response = self.client.delete(
            reverse(
                'location:countries_id',
                kwargs={'pk': "XX"},
            ), )

        content = {'detail': "Not found."}

        self.assertEqual(json.loads(response.content), content)

        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
class AddressesTests(APITestCase):

    def setUp(self):
        self.client = APIClient()

        self.user = UserFactory()
        self.user.set_password('Test123!')
        self.user.save()

        self.admin = AdminFactory()
        self.admin.set_password('Test123!')
        self.admin.save()

        self.random_country = Country.objects.create(
            name="random country",
            iso_code="RC",
        )
        self.random_state_province = StateProvince.objects.create(
            name="random state",
            iso_code="RS",
            country=self.random_country,
        )
        self.random_country2 = Country.objects.create(
            name="random country",
            iso_code="R2",
        )
        self.address = Address.objects.create(
            address_line1='random address 1',
            postal_code='RAN DOM',
            city='random city',
            state_province=self.random_state_province,
            country=self.random_country,
        )

    def test_create_new_address_with_permission(self):
        """
        Ensure we can create a new address if we have the permission.
        """
        data = dict(
            address_line1='random address 2',
            postal_code='RAN DOM',
            city='random city',
            state_province=self.random_state_province.iso_code,
            country=self.random_country.iso_code,
        )

        self.client.force_authenticate(user=self.admin)

        response = self.client.post(
            reverse('location:addresses'),
            data,
            format='json',
        )

        data['address_line2'] = ''
        data['state_province'] = dict(
            name=self.random_state_province.name,
            iso_code=self.random_state_province.iso_code
        )
        data['country'] = dict(
            name=self.random_country.name,
            iso_code=self.random_country.iso_code
        )

        res = json.loads(response.content)
        del res['id']

        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        self.assertEqual(res, data)

    def test_create_new_address_incorrect_state_province(self):
        """
        Ensure we can't create a new address if the StateProvince is not
        in the Country.
        """
        data = dict(
            address_line1='random address 2',
            postal_code='RAN DOM',
            city='random city',
            state_province=self.random_state_province.iso_code,
            country=self.random_country2.iso_code,
        )

        self.client.force_authenticate(user=self.admin)

        response = self.client.post(
            reverse('location:addresses'),
            data,
            format='json',
        )

        res = json.loads(response.content)

        err = {
            'detail': 'The StateProvince should be linked to the Country'
        }

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
        self.assertEqual(res, err)

    def test_create_new_address_without_permission(self):
        """
        Ensure we can't create a new address if we don't have the permission.
        """
        data = dict(
            address_line1='random address 1',
            postal_code='random postal',
            city='random city',
            state_province=self.random_state_province.name,
            country=self.random_country.name,
        )

        self.client.force_authenticate(user=self.user)

        response = self.client.post(
            reverse('location:addresses'),
            data,
            format='json',
        )

        content = {"detail": "You are not authorized to create a new address."}
        self.assertEqual(json.loads(response.content), content)

        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

    def test_list_address(self):
        """
        Ensure we can list all addresses.
        """

        data = [
            dict(
                id=self.address.id,
                address_line1='random address 1',
                address_line2='',
                postal_code='RAN DOM',
                city='random city',
                state_province=dict(
                    iso_code=self.random_state_province.iso_code,
                    name=self.random_state_province.name,
                ),
                country=dict(
                    iso_code=self.random_country.iso_code,
                    name=self.random_country.name,
                ),
            ),
        ]

        self.client.force_authenticate(user=self.user)

        response = self.client.get(reverse('location:addresses'))

        self.assertEqual(json.loads(response.content)['results'], data)
        self.assertEqual(json.loads(response.content)['count'], 1)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
class CyclesTests(APITestCase):
    def setUp(self):
        self.client = APIClient()

        self.user = UserFactory()
        self.user.set_password('Test123!')
        self.user.save()

        self.admin = AdminFactory()
        self.admin.set_password('Test123!')
        self.admin.save()

        self.cycle = Cycle.objects.create(
            name='Cycle 1',
            start_date=timezone.now(),
            end_date=timezone.now() + timezone.timedelta(minutes=100, ),
        )

        self.past_cycle = Cycle.objects.create(
            name='Cycle 2',
            start_date=timezone.now() - timezone.timedelta(days=10, ),
            end_date=timezone.now(),
        )

    def test_create_new_cycle_with_permission(self):
        """
        Ensure we can create a new cycle if we have the permission.
        """
        data = {
            'name': 'Cycle 3',
            'start_date': timezone.now(),
            'end_date': timezone.now() + timezone.timedelta(minutes=100, ),
        }

        self.client.force_authenticate(user=self.admin)

        response = self.client.post(
            reverse('volunteer:cycles'),
            data,
            format='json',
        )

        self.assertEqual(response.status_code, status.HTTP_201_CREATED)

    def test_create_new_cycle_without_permission(self):
        """
        Ensure we can't create a new cycle if we don't have the permission.
        """
        data = {
            'name': 'Cycle 3',
            'start_date': timezone.now(),
            'end_date': timezone.now() + timezone.timedelta(minutes=100),
        }

        self.client.force_authenticate(user=self.user)

        response = self.client.post(
            reverse('volunteer:cycles'),
            data,
            format='json',
        )

        content = {"detail": "You are not authorized to create a new cycle."}
        self.assertEqual(json.loads(response.content), content)

        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

    def test_list_cycle(self):
        """
        Ensure we can list all cycles.
        """
        start_date = self.cycle.start_date.strftime("%Y-%m-%dT%H:%M:%S.%fZ")
        end_date = self.cycle.end_date.strftime("%Y-%m-%dT%H:%M:%S.%fZ")

        data = {
            "id": self.cycle.id,
            "name": self.cycle.name,
            "start_date": start_date,
            "end_date": end_date,
        }

        self.client.force_authenticate(user=self.user)

        response = self.client.get(reverse('volunteer:cycles'))

        self.assertEqual(json.loads(response.content)['results'][0], data)
        self.assertEqual(json.loads(response.content)['count'], 2)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    def test_list_cycle_when_is_active_true(self):
        start_date = self.cycle.start_date.strftime("%Y-%m-%dT%H:%M:%S.%fZ")
        end_date = self.cycle.end_date.strftime("%Y-%m-%dT%H:%M:%S.%fZ")

        data = [{
            "id": self.cycle.id,
            "name": self.cycle.name,
            "start_date": start_date,
            "end_date": end_date,
        }]

        self.client.force_authenticate(user=self.user)

        url = "{0}?is_active=True".format(reverse('volunteer:cycles'))

        response = self.client.get(url)

        self.assertEqual(json.loads(response.content)['results'], data)
        self.assertEqual(json.loads(response.content)['count'], 1)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    def test_list_cycle_when_is_active_false(self):
        start_date = self.past_cycle.start_date\
            .strftime("%Y-%m-%dT%H:%M:%S.%fZ")
        end_date = self.past_cycle.end_date\
            .strftime("%Y-%m-%dT%H:%M:%S.%fZ")

        data = [{
            "id": self.past_cycle.id,
            "name": self.past_cycle.name,
            "start_date": start_date,
            "end_date": end_date,
        }]

        self.client.force_authenticate(user=self.user)

        url = "{0}?is_active=False".format(reverse('volunteer:cycles'))

        response = self.client.get(url)

        self.assertEqual(json.loads(response.content)['count'], 1)
        self.assertEqual(json.loads(response.content)['results'], data)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    def test_list_cycle_when_is_active_bad_input(self):
        start_date = self.cycle.start_date.strftime("%Y-%m-%dT%H:%M:%S.%fZ")
        end_date = self.cycle.end_date.strftime("%Y-%m-%dT%H:%M:%S.%fZ")

        data = {
            "id": self.cycle.id,
            "name": self.cycle.name,
            "start_date": start_date,
            "end_date": end_date,
        }

        self.client.force_authenticate(user=self.user)

        # 'bad' is not a good input
        url = "{0}?is_active=bad".format(reverse('volunteer:cycles'))

        response = self.client.get(url)

        self.assertEqual(json.loads(response.content)['results'][0], data)
        self.assertEqual(json.loads(response.content)['count'], 2)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
Ejemplo n.º 21
0
class CellsTests(APITestCase):
    def setUp(self):
        self.client = APIClient()

        self.user = UserFactory()
        self.user.set_password('Test123!')
        self.user.save()

        self.admin = AdminFactory()
        self.admin.set_password('Test123!')
        self.admin.save()

        self.random_country = Country.objects.create(
            name="Random Country",
            iso_code="RC",
        )
        self.random_state_province = StateProvince.objects.create(
            name="Random State",
            iso_code="RS",
            country=self.random_country,
        )
        self.address = Address.objects.create(
            address_line1='random address 1',
            postal_code='RAN DOM',
            city='random city',
            state_province=self.random_state_province,
            country=self.random_country,
        )
        self.cell = Cell.objects.create(
            name='my cell',
            address=self.address,
        )

    def test_create_new_cell_with_permission(self):
        """
        Ensure we can create a new cell if we have the permission.
        The Address, Country and StateProvince do not exist in the DB.
        """
        data_post = {
            'name': 'Cell 3',
            'address': {
                'address_line1': "my address",
                'postal_code': "RAN DOM",
                'city': 'random city',
                'state_province': {
                    'iso_code': 'NS',
                    'name': 'New State',
                },
                'country': {
                    'iso_code': 'NC',
                    'name': 'New Country',
                },
            },
            'managers': [
                self.user.id,
            ],
        }

        data = {
            'name':
            'Cell 3',
            'address': {
                'address_line1': "my address",
                'postal_code': "RAN DOM",
                'city': 'random city',
                'state_province': {
                    'iso_code': 'NS',
                    'name': 'New State',
                },
                'country': {
                    'iso_code': 'NC',
                    'name': 'New Country',
                },
            },
            'managers': [
                {
                    'id': self.user.id,
                    'username': self.user.username,
                    'first_name': self.user.first_name,
                    'last_name': self.user.last_name,
                    'email': self.user.email,
                },
            ],
        }

        self.assertRaises(
            Address.DoesNotExist, Address.objects.get, **{
                'address_line1': "my address",
                'postal_code': "RAN DOM",
                'city': 'random city'
            })
        self.assertRaises(Country.DoesNotExist, Country.objects.get,
                          **data_post['address']['country'])
        self.assertRaises(StateProvince.DoesNotExist,
                          StateProvince.objects.get,
                          **data_post['address']['state_province'])

        self.client.force_authenticate(user=self.admin)

        response = self.client.post(
            reverse('volunteer:cells'),
            data_post,
            format='json',
        )

        content = json.loads(response.content)
        del content['id']
        del content['address']['id']
        data['address']['address_line2'] = ''

        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        self.assertEqual(content, data)

    def test_create_new_cell_existing_address_different_country(self):
        """
        Ensure we can create a new cell if we have the permission.
        The Address already exists but the Country and StateProvince are
        different.
        """
        data = {
            'name': 'Cell 3',
            'address': {
                'address_line1': "random address 1",
                'postal_code': "RAN DOM",
                'city': 'random city',
                'state_province': {
                    'iso_code': 'NS',
                    'name': 'New State',
                },
                'country': {
                    'iso_code': 'NC',
                    'name': 'New Country',
                },
            },
            'managers': [],
        }

        self.assertRaises(Country.DoesNotExist, Country.objects.get,
                          **data['address']['country'])
        self.assertRaises(StateProvince.DoesNotExist,
                          StateProvince.objects.get,
                          **data['address']['state_province'])

        self.client.force_authenticate(user=self.admin)

        response = self.client.post(
            reverse('volunteer:cells'),
            data,
            format='json',
        )

        content = json.loads(response.content)
        del content['id']
        del content['address']['id']
        data['address']['address_line2'] = ''

        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        self.assertEqual(content, data)

    def test_create_new_cell_existing_country(self):
        """
        Ensure we can create a new cell if we have the permission.
        The Country already exist in the DB.
        """
        data = {
            'name': 'Cell 3',
            'address': {
                'address_line1': "my address",
                'postal_code': "RAN DOM",
                'city': 'random city',
                'state_province': {
                    'iso_code': 'NS',
                    'name': 'New State',
                },
                'country': {
                    'iso_code': 'RC',
                    'name': 'Random Country',
                },
            },
            'managers': [],
        }

        self.client.force_authenticate(user=self.admin)

        response = self.client.post(
            reverse('volunteer:cells'),
            data,
            format='json',
        )

        content = json.loads(response.content)
        del content['id']
        del content['address']['id']
        data['address']['address_line2'] = ''

        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        self.assertEqual(content, data)

    def test_create_new_cell_existing_state_province(self):
        """
        Ensure we can create a new cell if we have the permission.
        The Country and StateProvince already exist in the DB.
        """
        data = {
            'name': 'Cell 3',
            'address': {
                'address_line1': "my address",
                'postal_code': "RAN DOM",
                'city': 'random city',
                'state_province': {
                    'iso_code': 'RS',
                    'name': 'Random State',
                },
                'country': {
                    'iso_code': 'RC',
                    'name': 'Random Country',
                },
            },
            'managers': [],
        }

        self.client.force_authenticate(user=self.admin)

        response = self.client.post(
            reverse('volunteer:cells'),
            data,
            format='json',
        )

        content = json.loads(response.content)
        del content['id']
        del content['address']['id']
        data['address']['address_line2'] = ''

        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        self.assertEqual(content, data)

    def test_create_new_cell_existing_address(self):
        """
        Ensure we can create a new cell if we have the permission.
        The Address, Country and StateProvince already exist in the DB.
        """
        data = {
            'name': 'Cell 3',
            'address': {
                'address_line1': "random address 1",
                'postal_code': "RAN DOM",
                'city': 'random city',
                'state_province': {
                    'iso_code': 'RS',
                    'name': 'Random State',
                },
                'country': {
                    'iso_code': 'RC',
                    'name': 'Random Country',
                },
            },
            'managers': [],
        }

        self.client.force_authenticate(user=self.admin)

        response = self.client.post(
            reverse('volunteer:cells'),
            data,
            format='json',
        )

        content = json.loads(response.content)
        del content['id']
        del content['address']['id']
        data['address']['address_line2'] = ''

        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        self.assertEqual(content, data)

    def test_create_new_cell_with_inexistent_country(self):
        """
        Ensure we can't create a new cell if the state_province already exist
        and is not in the country.
        """
        data = {
            'name': 'Cell 3',
            'address': {
                'address_line1': "my address",
                'postal_code': "RAN DOM",
                'city': 'random city',
                'state_province': {  # Already associated with a country
                    'iso_code': 'RS',
                    'name': 'Random State',
                },
                'country': {  # New country NOT containing the state_province
                    'iso_code': 'NC',
                    'name': 'not created',
                },
            },
        }

        self.client.force_authenticate(user=self.admin)

        response = self.client.post(
            reverse('volunteer:cells'),
            data,
            format='json',
        )

        err = {'message': 'A StateProvince with that iso_code already exists'}

        content = json.loads(response.content)

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
        self.assertEqual(content, err)

    def test_create_new_cell_with_duplicate_state_province(self):
        """
        Ensure we can't create a new cell if the state_province iso_code
        is already associated to another state_province.
        """
        data = {
            'name': 'Cell 3',
            'address': {
                'address_line1': "my address",
                'postal_code': "RAN DOM",
                'city': 'random city',
                'state_province': {
                    'iso_code': 'RS',
                    'name': 'Random State 2',
                },
                'country': {
                    'iso_code': 'NC',
                    'name': 'not created',
                },
            },
        }

        self.client.force_authenticate(user=self.admin)

        response = self.client.post(
            reverse('volunteer:cells'),
            data,
            format='json',
        )

        content = json.loads(response.content)

        err = {'message': 'A StateProvince with that iso_code already exists'}

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
        self.assertEqual(content, err)

    def test_create_new_cell_with_duplicate_country(self):
        """
        Ensure we can't create a new cell if the country iso_code
        is already associated to another country.
        """
        data = {
            'name': 'Cell 3',
            'address': {
                'address_line1': "my address",
                'postal_code': "RAN DOM",
                'city': 'random city',
                'state_province': {
                    'iso_code': 'RA',
                    'name': 'Random State 2',
                },
                'country': {
                    'iso_code': 'RC',
                    'name': 'Random Country Dup',
                },
            },
        }

        self.client.force_authenticate(user=self.admin)

        response = self.client.post(
            reverse('volunteer:cells'),
            data,
            format='json',
        )

        content = json.loads(response.content)

        err = {'message': 'A Country with that iso_code already exists'}

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
        self.assertEqual(content, err)

    def test_create_new_cell_without_permission(self):
        """
        Ensure we can't create a new cell if we don't have the permission.
        """
        data = {
            'name': 'Cell 3',
            'address': {
                'address_line1': "my address",
                'postal_code': "RAN DOM",
                'city': 'random city',
                'state_province': 'RS',
                'country': 'RC',
            },
        }

        self.client.force_authenticate(user=self.user)

        response = self.client.post(
            reverse('volunteer:cells'),
            data,
            format='json',
        )

        content = {"detail": "You are not authorized to create a new cell."}
        self.assertEqual(json.loads(response.content), content)

        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

    def test_list_cell(self):
        """
        Ensure we can list all cells.
        """

        data = [{
            'id': self.cell.id,
            'name': self.cell.name,
            'address': {
                'id': self.address.id,
                'address_line1': self.address.address_line1,
                'address_line2': self.address.address_line2,
                'postal_code': self.address.postal_code,
                'city': self.address.city,
                'state_province': {
                    'iso_code': self.random_state_province.iso_code,
                    'name': self.random_state_province.name,
                },
                'country': {
                    'iso_code': self.random_country.iso_code,
                    'name': self.random_country.name,
                },
            },
            "managers": [],
        }]

        self.client.force_authenticate(user=self.user)

        response = self.client.get(reverse('volunteer:cells'))

        response_parsed = json.loads(response.content)

        self.assertEqual(response_parsed['results'], data)
        self.assertEqual(response_parsed['count'], 1)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    def test_create_new_cell_with_bad_manager(self):
        """
        Ensure we can't create a new cell with a bad idea of manager
        """
        data_post = {
            'name': 'Cell 3',
            'address': {
                'address_line1': "my address",
                'postal_code': "RAN DOM",
                'city': 'random city',
                'state_province': {
                    'iso_code': 'NS',
                    'name': 'New State',
                },
                'country': {
                    'iso_code': 'NC',
                    'name': 'New Country',
                },
            },
            'managers': [
                7812,
            ],
        }

        self.client.force_authenticate(user=self.admin)

        response = self.client.post(
            reverse('volunteer:cells'),
            data_post,
            format='json',
        )

        content = json.loads(response.content)
        error = {'message': 'Unknown user with this ID'}
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
        self.assertEqual(content, error)

    def test_cell_list_ordering(self):
        self.cell_2 = Cell.objects.create(
            name='AAA Cell',
            address=self.address,
        )

        self.client.force_authenticate(user=self.admin)

        response = self.client.get(
            reverse('volunteer:cells'),
            format='json',
        )

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data['results'][0]['name'], 'my cell')
        self.assertEqual(response.data['results'][1]['name'], 'AAA Cell')

        url_ordered = '%s?ordering=name' % reverse('volunteer:cells')

        response = self.client.get(
            url_ordered,
            format='json',
        )

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data['results'][0]['name'], 'AAA Cell')
        self.assertEqual(response.data['results'][1]['name'], 'my cell')