示例#1
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)
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)
class ResetPasswordTests(APITestCase):
    def setUp(self):
        self.client = APIClient()

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

    @override_settings(
        CONSTANT={
            "EMAIL_SERVICE": True,
            "FRONTEND_INTEGRATION": {
                "FORGOT_PASSWORD_URL": "fake_url",
            }
        })
    def test_create_new_token(self):
        """
        Ensure we can have a new token to change our password
        """
        data = {
            'email': self.user.email,
        }

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

        # Test that one message was sent:
        self.assertEqual(len(mail.outbox), 1)

        # The token has been created
        tokens = ActionToken.objects.filter(
            user=self.user,
            type='password_change',
        )

        self.assertEqual(response.content, b'')
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        self.assertTrue(len(tokens) == 1)

    @override_settings(
        CONSTANT={
            "EMAIL_SERVICE": True,
            "FRONTEND_INTEGRATION": {
                "FORGOT_PASSWORD_URL1": "fake_url",
            }
        })
    def test_create_new_token_with_call_exception(self):
        """
        Ensure we can not have a new token to change our
        password because exception
        """
        data = {
            'email': self.user.email,
        }

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

        # The token has been created
        tokens = ActionToken.objects.filter(
            user=self.user,
            type='password_change',
        )
        content = {
            'detail':
            "Your token has been created but no "
            "email has been sent. Please contact "
            "the administration."
        }

        self.assertEqual(json.loads(response.content), content)
        # Test that one message was sent:
        self.assertEqual(len(mail.outbox), 0)
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        self.assertTrue(len(tokens) == 1)

    @override_settings(
        CONSTANT={
            "EMAIL_SERVICE": True,
            "FRONTEND_INTEGRATION": {
                "FORGOT_PASSWORD_URL": "fake_url",
            }
        })
    def test_create_new_token_without_email_param(self):
        """
        Ensure we can't have a new token to change our password without
        give our email in param
        """
        data = dict()

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

        # The token has been created
        tokens = ActionToken.objects.filter(
            user=self.user,
            type='password_change',
        )

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

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

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

        self.assertTrue(len(tokens) == 0)

    @override_settings(
        CONSTANT={
            "EMAIL_SERVICE": True,
            "FRONTEND_INTEGRATION": {
                "FORGOT_PASSWORD_URL": "fake_url",
            }
        })
    def test_create_new_token_with_an_empty_email_param(self):
        """
        Ensure we can't have a new token to change our password without
        give our email in param
        """
        data = {
            'email': '',
        }

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

        # The token has been created
        tokens = ActionToken.objects.filter(
            user=self.user,
            type='password_change',
        )

        content = {
            'email': ["This field may not be blank."],
        }

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

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

        self.assertTrue(len(tokens) == 0)

    @override_settings(
        CONSTANT={
            "EMAIL_SERVICE": True,
            "FRONTEND_INTEGRATION": {
                "FORGOT_PASSWORD_URL": "fake_url",
            }
        })
    def test_create_new_token_with_bad_email(self):
        """
        Ensure we can't have a new token to change our password without
        a valid email
        """
        data = {
            'email': 'test',
        }

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

        # The token has been created
        tokens = ActionToken.objects.filter(
            user=self.user,
            type='password_change',
        )

        content = {
            'email': ["Enter a valid email address."],
        }
        self.assertEqual(json.loads(response.content), content)

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

        self.assertTrue(len(tokens) == 0)

    @override_settings(
        CONSTANT={
            "EMAIL_SERVICE": True,
            "FRONTEND_INTEGRATION": {
                "FORGOT_PASSWORD_URL": "fake_url",
            }
        })
    def test_create_new_token_when_token_already_exist(self):
        """
        Ensure we can have a new token to change our password
        """
        # We create a token before launch the test
        ActionToken.objects.create(
            user=self.user,
            type='password_change',
        )

        data = {
            'email': self.user.email,
        }

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

        # Test that one message was sent:
        self.assertEqual(len(mail.outbox), 1)

        # The token has been created
        tokens = ActionToken.objects.filter(
            user=self.user,
            type='password_change',
            expired=False,
        )

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

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

        self.assertTrue(len(tokens) == 1)

    @override_settings(
        CONSTANT={
            "EMAIL_SERVICE": False,
            "FRONTEND_INTEGRATION": {
                "FORGOT_PASSWORD_URL": "fake_url",
            }
        })
    def test_create_new_token_without_email_service(self):
        """
        Ensure we can have a new token to change our password
        """
        data = {
            'email': self.user.email,
        }

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

        # Test that one message was not sent:
        self.assertEqual(len(mail.outbox), 0)

        # The token has been created
        tokens = ActionToken.objects.filter(
            user=self.user,
            type='password_change',
        )

        self.assertEqual(response.content, b'')
        self.assertEqual(response.status_code, status.HTTP_501_NOT_IMPLEMENTED)
        self.assertTrue(len(tokens) == 0)

    @override_settings(
        CONSTANT={
            "EMAIL_SERVICE": True,
            "FRONTEND_INTEGRATION": {
                "FORGOT_PASSWORD_URL": "fake_url",
            }
        }, )
    def test_create_new_token_with_failure_email(self):
        """
        Ensure we can nt send email after create new token
        """
        data = {
            'email': self.user.email,
        }

        @receiver(pre_send, weak=False)
        def cancel_pre_send(sender, message, esp_name, **kwargs):
            raise AnymailCancelSend("whoa there")

        self.addCleanup(pre_send.disconnect, receiver=cancel_pre_send)

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

        # Test that one message wasn't sent:
        self.assertEqual(len(mail.outbox), 0)

        # The token has been created
        tokens = ActionToken.objects.filter(
            user=self.user,
            type='password_change',
        )

        content = {
            'detail':
            "Your token has been created "
            "but no email has been sent. "
            "Please contact the administration."
        }

        self.assertEqual(json.loads(response.content), content)
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        self.assertTrue(len(tokens) == 1)
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),
        )
示例#5
0
class UsersActivationTests(APITestCase):
    def setUp(self):
        self.client = APIClient()

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

        self.activation_token = ActionToken.objects.create(
            user=self.user,
            type='account_activation',
        )

    def test_activate_user(self):
        """
        Ensure we can activate a user by using an ActionToken.
        """
        self.client.force_authenticate(user=self.user)

        data = {
            'activation_token': self.activation_token.key,
        }

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

        # It's the good user
        self.assertEqual(json.loads(response.content)['id'], self.user.id)

        # We read a new time the user to be synchronized
        user_sync = User.objects.get(id=self.user.id)

        # The user is now active
        self.assertTrue(user_sync.is_active)

        # The token has been removed
        tokens = ActionToken.objects.filter(
            user=user_sync,
            type='account_activation',
        )
        self.assertTrue(len(tokens) == 0)

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

    def test_activate_user_with_bad_token(self):
        """
        Ensure we can't activate a user without a good ActionToken.
        """
        self.client.force_authenticate(user=self.user)

        data = {
            'activation_token': 'bad_token',
        }

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

        content = {
            'non_field_errors': '"bad_token" is not a valid activation_token.'
        }
        self.assertEqual(json.loads(response.content), content)

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
示例#6
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)
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.email, 'password': '******'}

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

        token = TemporaryToken.objects.get(user__email=self.user.email, )
        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.email, '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__email=self.user.email, )
        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__email=self.user.email, )

        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.email,
            '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__email='*****@*****.**').count()
        self.assertEqual(0, tokens)

    def test_authenticate_bad_email(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__email='*****@*****.**').count()
        self.assertEqual(0, tokens)

    def test_authenticate_inactive(self):
        """
        Ensure we can't authenticate if user is inactive
        """
        data = {'login': self.user.email, '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__email=self.user.email).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__email=self.user.email).count()
        self.assertEqual(0, tokens)
class ChangePasswordTests(APITestCase):
    def setUp(self):
        self.client = APIClient()

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

        self.token = ActionToken.objects.create(
            user=self.user,
            type='password_change',
        )

    def test_change_password(self):
        """
        Ensure we can change a password with a valid token and a good password
        """
        data = {'token': self.token.key, 'new_password': '******'}

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

        tokens = ActionToken.objects.filter(
            user=self.user,
            type='password_change',
            expired=False,
        )

        self.assertEqual(json.loads(response.content)['id'], self.user.id)

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

        # We sync user after this change
        user = User.objects.get(id=self.user.id)
        self.assertTrue(user.check_password('dWqq!Kld3#9dw'))

        self.assertTrue(len(tokens) == 0)

    def test_change_password_with_bad_token(self):
        """
        Ensure we can't change a password with an invalid token
        """
        data = {'token': 'test', 'new_password': '******'}

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

        tokens = ActionToken.objects.filter(
            user=self.user,
            type='password_change',
        )

        content = {
            'non_field_errors': "test is not a valid token.",
        }
        self.assertEqual(json.loads(response.content), content)

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

        self.assertTrue(len(tokens) == 1)

        self.assertFalse(self.user.check_password('dWqq!Kld3#9dw'))

    def test_change_password_without_token(self):
        """
        Ensure we can't change a password without token
        """
        data = {'new_password': '******'}

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

        tokens = ActionToken.objects.filter(
            user=self.user,
            type='password_change',
        )

        content = {
            'token': ["This field is required."],
        }
        self.assertEqual(json.loads(response.content), content)

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

        self.assertTrue(len(tokens) == 1)

        self.assertFalse(self.user.check_password('dWqq!Kld3#9dw'))

    def test_change_password_with_an_empty_token(self):
        """
        Ensure we can't change a password with an empty token
        """
        data = {'token': '', 'new_password': '******'}

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

        tokens = ActionToken.objects.filter(
            user=self.user,
            type='password_change',
        )

        content = {
            'token': ["This field may not be blank."],
        }
        self.assertEqual(json.loads(response.content), content)

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

        self.assertTrue(len(tokens) == 1)

        self.assertFalse(self.user.check_password('dWqq!Kld3#9dw'))

    def test_change_password_without_new_password(self):
        """
        Ensure we can't change a password without a new password
        """
        data = {
            'token': self.token.key,
        }

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

        tokens = ActionToken.objects.filter(
            user=self.user,
            type='password_change',
        )

        content = {
            'new_password': ["This field is required."],
        }
        self.assertEqual(json.loads(response.content), content)

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

        self.assertTrue(len(tokens) == 1)

        self.assertFalse(self.user.check_password('dWqq!Kld3#9dw'))

    def test_change_password_with_an_empty_new_password(self):
        """
        Ensure we can't change a password without a valid new password
        """
        data = {
            'token': self.token.key,
            'new_password': '',
        }

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

        tokens = ActionToken.objects.filter(
            user=self.user,
            type='password_change',
        )

        content = {
            'new_password': ["This field may not be blank."],
        }
        self.assertEqual(json.loads(response.content), content)

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

        self.assertTrue(len(tokens) == 1)

        self.assertFalse(self.user.check_password('dWqq!Kld3#9dw'))

    def test_change_password_with_a_weak_new_password(self):
        """
        Ensure we can't change a password with a weak new password
        """
        data = {'token': self.token.key, 'new_password': '******'}

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

        tokens = ActionToken.objects.filter(
            user=self.user,
            type='password_change',
        )

        content = {
            'non_field_errors': [
                'This password is too short. '
                'It must contain at least 8 characters.',
            ],
        }
        self.assertEqual(json.loads(response.content), content)

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

        self.assertTrue(len(tokens) == 1)

        self.assertFalse(self.user.check_password('akrent'))
示例#9
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)
示例#10
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)