Exemple #1
0
    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,
        )
Exemple #2
0
    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()
Exemple #3
0
    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",
        )
Exemple #4
0
class EventTests(APITransactionTestCase):
    TITLE = 'event title'
    DESCRIPTION = 'description event'

    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()

    def test_create_video(self):
        """
        Ensure we can create a new event with just required arguments
        """
        path_video = 'media/upload/2019/01/15/video.mp4'

        video = Video.objects.create(
            owner=self.user,
            title=self.TITLE,
            description=self.DESCRIPTION,
            file=path_video,
            duration=100000,
            width=720,
            height=1080,
            size=20000,
        )

        self.assertEqual(video.title, self.TITLE)
        self.assertEqual(video.description, self.DESCRIPTION)
        self.assertEqual(video.file, path_video)
        self.assertEqual(video.duration, 100000)
        self.assertEqual(video.width, 720)
        self.assertEqual(video.height, 1080)
        self.assertEqual(video.size, 20000)
Exemple #5
0
    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",
        )
        self.random_state_province = StateProvince.objects.create(
            name="Random StateProvince 1",
            iso_code="RS",
            country=self.random_country)
class StateProvincesIdTests(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,
        )

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

        response = self.client.get(
            reverse(
                'location:stateprovinces_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_stateprovince(self):
        """
        Ensure we can retrieve an stateprovince.
        """

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

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

        response = self.client.get(
            reverse(
                'location:stateprovinces_id',
                kwargs={'pk': self.random_state_province.iso_code},
            )
        )
        data['country'] = dict(
            name=self.random_country.name,
            iso_code=self.random_country.iso_code,
        )

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

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

    def test_update_stateprovince_with_permission(self):
        """
        Ensure we can update a specific stateprovince.
        """

        data = {
            'iso_code': self.random_state_province.iso_code,
            'name': "new state",
            'country': dict(
                name=self.random_country.name,
                iso_code=self.random_country.iso_code,
            ),
        }

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

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

        response = self.client.patch(
            reverse(
                'location:stateprovinces_id',
                kwargs={'pk': self.random_state_province.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_stateprovince_country(self):
        """
        Ensure we can update the country of a stateprovince.
        """
        Country.objects.create(name="New Country", iso_code="NC")

        data = dict(
            iso_code=self.random_state_province.iso_code,
            name=self.random_state_province.name,
            country=dict(
                iso_code="NC",
                name="New Country"
            ),
        )

        data_post = dict(
            iso_code=self.random_state_province.iso_code,
            name=self.random_state_province.name,
            country='NC',
        )

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

        response = self.client.patch(
            reverse(
                'location:stateprovinces_id',
                kwargs={'pk': self.random_state_province.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_stateprovince_without_permission(self):
        """
        Ensure we can't update a specific stateprovince without permission.
        """
        data_post = {
            "name": "my stateprovince",
        }

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

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

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

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

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

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

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

        }

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

        response = self.client.patch(
            reverse(
                'location:stateprovinces_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_stateprovince_with_permission(self):
        """
        Ensure we can delete a specific stateprovince.
        """
        self.client.force_authenticate(user=self.admin)

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

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

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

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

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

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

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

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

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

        response = self.client.delete(
            reverse(
                'location:stateprovinces_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 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_event_manager = UserFactory()
        self.user_event_manager.set_password('Test123!')
        self.user_event_manager.save()

        self.genre1 = Genre.objects.create(
            label='genre_1',
            description='description genre_1',
        )

        self.genre2 = Genre.objects.create(
            label='genre_2',
            description='description genre_2',
        )

        subscription_date = timezone.now()
        with mock.patch('django.utils.timezone.now') as mock_now:
            mock_now.return_value = subscription_date

            self.video_admin = Video.objects.create(
                title='video test 1',
                description='description test 1',
                owner=self.admin,
                duration=1415.081748,
                width=settings.CONSTANT["VIDEO"]["WIDTH"],
                height=settings.CONSTANT["VIDEO"]["HEIGHT"],
                file='/upload/videos/2018/10/01/video.mp4',
                size=settings.CONSTANT["VIDEO"]["SIZE"],
            )
            self.video_admin.genres.add(self.genre1)
            self.video_admin.genres.add(self.genre2)

            self.video_user = Video.objects.create(
                title='video test 2',
                description='description test 2',
                owner=self.user,
                duration=1415.081748,
                width=settings.CONSTANT["VIDEO"]["WIDTH"],
                height=settings.CONSTANT["VIDEO"]["HEIGHT"],
                file='/upload/videos/2018/10/01/video.mp4',
                size=settings.CONSTANT["VIDEO"]["SIZE"])

            self.video_user_inactif = Video.objects.create(
                title='video test 2',
                description='description test 2',
                owner=self.user,
                duration=1415.081748,
                width=settings.CONSTANT["VIDEO"]["WIDTH"],
                height=settings.CONSTANT["VIDEO"]["HEIGHT"],
                file='/upload/videos/2018/10/01/video.mp4',
                size=settings.CONSTANT["VIDEO"]["SIZE"],
                is_actived=subscription_date,
            )

            self.video_user_inactif = Video.objects.create(
                title='video test 2',
                description='description test 2',
                owner=self.user,
                duration=1415.081748,
                width=settings.CONSTANT["VIDEO"]["WIDTH"],
                height=settings.CONSTANT["VIDEO"]["HEIGHT"],
                file='/upload/videos/2018/10/01/video.mp4',
                size=settings.CONSTANT["VIDEO"]["SIZE"],
                is_actived=subscription_date,
                is_deleted=subscription_date)
class VideosTests(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_event_manager = UserFactory()
        self.user_event_manager.set_password('Test123!')
        self.user_event_manager.save()

        self.genre1 = Genre.objects.create(
            label='genre_1',
            description='description genre_1',
        )

        self.genre2 = Genre.objects.create(
            label='genre_2',
            description='description genre_2',
        )

        subscription_date = timezone.now()
        with mock.patch('django.utils.timezone.now') as mock_now:
            mock_now.return_value = subscription_date

            self.video_admin = Video.objects.create(
                title='video test 1',
                description='description test 1',
                owner=self.admin,
                duration=1415.081748,
                width=settings.CONSTANT["VIDEO"]["WIDTH"],
                height=settings.CONSTANT["VIDEO"]["HEIGHT"],
                file='/upload/videos/2018/10/01/video.mp4',
                size=settings.CONSTANT["VIDEO"]["SIZE"],
            )
            self.video_admin.genres.add(self.genre1)
            self.video_admin.genres.add(self.genre2)

            self.video_user = Video.objects.create(
                title='video test 2',
                description='description test 2',
                owner=self.user,
                duration=1415.081748,
                width=settings.CONSTANT["VIDEO"]["WIDTH"],
                height=settings.CONSTANT["VIDEO"]["HEIGHT"],
                file='/upload/videos/2018/10/01/video.mp4',
                size=settings.CONSTANT["VIDEO"]["SIZE"])

            self.video_user_inactif = Video.objects.create(
                title='video test 2',
                description='description test 2',
                owner=self.user,
                duration=1415.081748,
                width=settings.CONSTANT["VIDEO"]["WIDTH"],
                height=settings.CONSTANT["VIDEO"]["HEIGHT"],
                file='/upload/videos/2018/10/01/video.mp4',
                size=settings.CONSTANT["VIDEO"]["SIZE"],
                is_actived=subscription_date,
            )

            self.video_user_inactif = Video.objects.create(
                title='video test 2',
                description='description test 2',
                owner=self.user,
                duration=1415.081748,
                width=settings.CONSTANT["VIDEO"]["WIDTH"],
                height=settings.CONSTANT["VIDEO"]["HEIGHT"],
                file='/upload/videos/2018/10/01/video.mp4',
                size=settings.CONSTANT["VIDEO"]["SIZE"],
                is_actived=subscription_date,
                is_deleted=subscription_date)

    # TODO: create video test
    # def test_create_new_video_with_permission(self):
    # path_video = 'media/upload/2019/01/15/video.mp4'

    # file_mock = mock.MagicMock(spec=File)
    # file_mock.filename = 'video.mp4'
    # self.client.force_authenticate(user=self.admin)
    # with open(__file__, 'rb') as fp:
    #     data = {
    #         'file': fp,
    #     }
    #
    #     response = self.client.post(
    #         reverse('video:videos'),
    #         data,
    #         format='json',
    #         # content_type=client.MULTIPART_CONTENT,
    #         Content_disposition =
    #   'form-data; name="file"; filename="video.mp4"'
    #     )
    #
    #     print(response.data)

    def test_list_videos_with_permissions(self):
        """
        Ensure we can list all videos. (ordered by date_created by default)
        """
        self.client.force_authenticate(user=self.admin)

        response = self.client.get(
            reverse('video:videos'),
            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', 'title', 'owner', 'description', 'height', 'is_created',
            'is_active', 'is_delete', 'width', 'size', 'duration',
            'is_actived', 'is_deleted', 'file', 'genres', 'is_path_file'
        ]

        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_active_videos(self):
        """
        Ensure we can list all videos actived.
        (ordered by date_created by default)
        """
        self.client.force_authenticate(user=self.admin)

        response = self.client.get(
            reverse('video:videos'),
            data={"is_actived": True},
            format='json',
        )

        content = json.loads(response.content)

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

        # Check the system doesn't return attributes not expected
        attributes = [
            'id', 'title', 'owner', 'description', 'height', 'is_created',
            'is_active', 'is_delete', 'width', 'size', 'duration',
            'is_actived', 'is_deleted', 'file'
        ]

        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_active_videos(self):
        """
        Ensure we can list all videos deleted.
        (ordered by date_created by default)
        """
        self.client.force_authenticate(user=self.admin)

        response = self.client.get(
            reverse('video:videos'),
            data={"is_deleted": True},
            format='json',
        )

        content = json.loads(response.content)

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

        # Check the system doesn't return attributes not expected
        attributes = [
            'id', 'title', 'owner', 'description', 'height', 'is_created',
            'is_active', 'is_delete', 'width', 'size', 'duration',
            'is_actived', 'is_deleted', 'file', 'genres', 'is_path_file'
        ]

        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),
        )
Exemple #9
0
class VideosTests(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_event_manager = UserFactory()
        self.user_event_manager.set_password('Test123!')
        self.user_event_manager.save()

        self.pre_signals = (len(signals.pre_delete.receivers), )

        subscription_date = timezone.now()

        with mock.patch('django.utils.timezone.now') as mock_now:
            mock_now.return_value = subscription_date

            self.video_admin = Video.objects.create(
                title='video test 1',
                description='description test 1',
                owner=self.admin,
                duration=1415.081748,
                width=settings.CONSTANT["VIDEO"]["WIDTH"],
                height=settings.CONSTANT["VIDEO"]["HEIGHT"],
                file='/upload/videos/2018/10/01/video.mp4',
                size=settings.CONSTANT["VIDEO"]["SIZE"])

            self.video_user = Video.objects.create(
                title='video test 2',
                description='description test 2',
                owner=self.user,
                duration=1415.081748,
                width=settings.CONSTANT["VIDEO"]["WIDTH"],
                height=settings.CONSTANT["VIDEO"]["HEIGHT"],
                file='/upload/videos/2018/10/01/video.mp4',
                size=settings.CONSTANT["VIDEO"]["SIZE"])

            self.video_user_actif = Video.objects.create(
                title='video test 2',
                description='description test 2',
                owner=self.user,
                duration=1415.081748,
                width=settings.CONSTANT["VIDEO"]["WIDTH"],
                height=settings.CONSTANT["VIDEO"]["HEIGHT"],
                file='/upload/videos/2018/10/01/video.mp4',
                size=settings.CONSTANT["VIDEO"]["SIZE"],
                is_actived=subscription_date,
            )

            self.video_user_delete = Video.objects.create(
                title='video test 2',
                description='description test 2',
                owner=self.user,
                duration=1415.081748,
                width=settings.CONSTANT["VIDEO"]["WIDTH"],
                height=settings.CONSTANT["VIDEO"]["HEIGHT"],
                file='/upload/videos/2018/10/01/video.mp4',
                size=settings.CONSTANT["VIDEO"]["SIZE"],
                is_actived=subscription_date,
                is_deleted=subscription_date)

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

        response = self.client.get(
            reverse(
                'video:videos_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)

    @override_settings(TIME_ZONE='UTC')
    def test_retrieve_video(self):
        """
        Ensure we can retrieve an event.
        """
        self.client.force_authenticate(user=self.user)

        response = self.client.get(
            reverse(
                'video:videos_id',
                kwargs={'pk': self.video_admin.id},
            ))

        result = json.loads(response.content)

        self.assertEqual(result['id'], self.video_admin.id)
        self.assertEqual(result['title'], self.video_admin.title)
        self.assertEqual(result['description'], self.video_admin.description)
        self.assertEqual(
            result['is_created'],
            self.video_admin.is_created.strftime("%Y-%m-%dT%H:%M:%S.%fZ"))
        self.assertEqual(result['owner']['id'], self.video_admin.owner.id)

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

    @override_settings(TIME_ZONE='UTC')
    def test_update_video_with_permission(self):
        """
        Ensure we can update a specific video.
        """
        title = 'new title video'
        description = 'new description video'
        data_post = {
            "title": title,
            "description": description,
        }

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

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

        response = self.client.patch(
            reverse(
                'video:videos_id',
                kwargs={'pk': self.video_admin.id},
            ),
            data_post,
            format='json',
        )

        result = json.loads(response.content)

        self.assertEqual(result['id'], self.video_admin.id)
        self.assertEqual(result['title'], title)
        self.assertEqual(result['description'], description)
        self.assertEqual(
            result['is_created'],
            self.video_admin.is_created.strftime("%Y-%m-%dT%H:%M:%S.%fZ"),
        )
        self.assertEqual(result['owner']['id'], self.video_admin.owner.id)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    def test_update_video_without_permission(self):
        """
        Ensure we can't update a specific event without permission.
        """
        title = 'new title video'
        description = 'new description video'
        data_post = {
            "title": title,
            "description": description,
        }

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

        response = self.client.patch(
            reverse(
                'video:videos_id',
                kwargs={'pk': self.video_user.id},
            ),
            data_post,
            format='json',
        )

        content = {'detail': 'You are not authorized to update a given video.'}
        self.assertEqual(json.loads(response.content), content)
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

    def test_update_video_that_doesnt_exist(self):
        """
        Ensure we can't update a specific video if it doesn't exist.
        """
        data_post = {
            "title": 'new title',
        }

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

        response = self.client.patch(
            reverse(
                'video:videos_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_video_with_permission(self):
        """
        Ensure we can delete a specific video.
        """
        self.client.force_authenticate(user=self.admin)

        try:
            response = self.client.delete(
                reverse(
                    'video:videos_id',
                    kwargs={'pk': self.video_user.id},
                ), )
            self.assertEqual(response.content, b'')
            self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
        except FileNotFoundError:
            pass

    def test_delete_video_without_permission(self):
        """
        Ensure we can't delete a specific video without permission.
        """
        data = []

        def pre_delete_handler(signal, sender, instance, **kwargs):

            data.append((instance, sender, kwargs.get("raw", False)))

        signals.pre_delete.connect(pre_delete_handler, weak=False)

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

        try:

            response = self.client.delete(
                reverse(
                    'video:videos_id',
                    kwargs={'pk': self.video_admin.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)
        except FileNotFoundError:
            pass
        finally:
            signals.pre_delete.disconnect(pre_delete_handler)

    def test_delete_video_that_doesnt_exist(self):
        """
        Ensure we can't delete a specific video if it doesn't exist
        """
        data = []

        def pre_delete_handler(signal, sender, instance, **kwargs):

            data.append((instance, sender, kwargs.get("raw", False)))

        signals.pre_delete.connect(pre_delete_handler, weak=False)

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

        try:
            response = self.client.delete(
                reverse(
                    'video:videos_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)
        except FileNotFoundError:
            pass
        finally:
            signals.pre_delete.disconnect(pre_delete_handler)

    def tearDown(self):
        """
        Save up the number of connected signals so that we can check at the
        end that all the signals we register get properly unregistered
        """
        post_signals = (len(signals.pre_delete.receivers), )

        self.assertEqual(self.pre_signals, post_signals)
Exemple #10
0
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)
Exemple #11
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 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)