def test_post_username(self): username = '******' password = '******' UserFactory.create(email=username, password=password, is_active=True) data = {'username': username.lower(), 'password': password} request = self.create_request('post', auth=False, data=data) view = self.view_class.as_view() response = view(request) self.assertEqual(response.status_code, status.HTTP_200_OK, msg=response.data)
def test_put_invalid_token(self): user = UserFactory.create() other_user = UserFactory.create() token = default_token_generator.make_token(other_user) uid = urlsafe_base64_encode(force_bytes(user.pk)) request = self.create_request('put', auth=False) view = self.view_class.as_view() response = view(request, uidb64=uid, token=token) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
def test_non_existent_email(self): email = '*****@*****.**' UserFactory.create(email='*****@*****.**') request = self.create_request('post', data={'email': email}, auth=False) view = self.view_class.as_view() with patch.object(self.view_class, 'send_email') as send_email: response = view(request) self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) self.assertFalse(send_email.called)
def test_post(self): """Assert user can sign in""" UserFactory.create(email=self.username, password=self.password) request = self.create_request('post', auth=False, data=self.data) view = self.view_class.as_view() response = view(request) self.assertEqual( response.status_code, status.HTTP_200_OK, msg=response.data) # Ensure user has a token now token = self.model.objects.get() self.assertEqual(response.data['token'], token.key)
def test_deserialize_update_email_in_use(self): user = UserFactory.create() other_user = UserFactory.create() data = { 'name': "Robert'); DROP TABLE Students;--'", 'email': other_user.email, 'password': '******', 'password2': 'Sup3RSecre7paSSw0rD', } serializer = serializers.RegistrationSerializer(user, data=data) self.assertFalse(serializer.is_valid()) self.assertEqual(serializer._errors['email'], ['That email address has already been registered.'])
def test_post(self): """Assert user can sign in""" UserFactory.create(email=self.username, password=self.password) request = self.create_request('post', auth=False, data=self.data) view = self.view_class.as_view() response = view(request) self.assertEqual(response.status_code, status.HTTP_200_OK, msg=response.data) # Ensure user has a token now token = self.model.objects.get() self.assertEqual(response.data['token'], token.key)
def test_deserialize_update_email_in_use(self): user = UserFactory.create() other_user = UserFactory.create() data = { 'name': "Robert'); DROP TABLE Students;--'", 'email': other_user.email, 'password': '******', 'password2': 'Sup3RSecre7paSSw0rD', } serializer = serializers.RegistrationSerializer(user, data=data) self.assertFalse(serializer.is_valid()) self.assertEqual( serializer._errors['email'], ['That email address has already been registered.'])
def test_post_user_not_confirmed(self): """Assert non active users can not log in.""" UserFactory.create(email=self.username, password=self.password, is_active=False) request = self.create_request('post', auth=False, data=self.data) view = self.view_class.as_view() response = view(request) self.assertEqual( response.status_code, status.HTTP_400_BAD_REQUEST, msg=response.data, ) expected = 'User account is disabled.' self.assertIn(expected, response.data['non_field_errors']) self.assertNotIn('token', response.data)
def test_post_rate_limit(self): """Ensure the POST requests are rate limited.""" email = '*****@*****.**' UserFactory.create(email=email) data = {'email': email} request = self.create_request('post', data=data, auth=False) view = self.view_class.as_view() response = view(request) self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) # request is throttled response = view(request) self.assertEqual(response.status_code, status.HTTP_429_TOO_MANY_REQUESTS)
def test_post(self): username = '******' password = '******' UserFactory.create(email=username.lower(), password=password) data = {'username': username, 'password': password} request = self.create_request('post', auth=False, data=data) view = self.view_class.as_view() response = view(request) self.assertEqual( response.status_code, status.HTTP_200_OK, msg=response.data) # Ensure user has a token now token = self.model.objects.get(user__email=username.lower()) self.assertEqual(response.data['token'], token.key)
def test_non_existent_email(self): email = '*****@*****.**' UserFactory.create(email='*****@*****.**') request = self.create_request( 'post', data={'email': email}, auth=False, ) view = self.view_class.as_view() with patch(SEND_METHOD) as send_email: response = view(request) self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) self.assertFalse(send_email.called)
def test_post_different_user_logged_in(self): user = UserFactory.create() other_user = UserFactory.create() token = default_token_generator.make_token(user) uid = urlsafe_base64_encode(force_bytes(user.pk)) request = self.create_request('post', user=other_user) view = self.view_class.as_view() response = view(request, uidb64=uid, token=token) self.assertEqual(response.status_code, status.HTTP_201_CREATED) updated_user = User.objects.get(pk=user.pk) self.assertFalse(updated_user.email_verification_required) logged_in_user = User.objects.get(pk=other_user.pk) self.assertTrue(logged_in_user.email_verification_required)
def test_post_rate_limit(self): """Assert POST requests are rate limited.""" user = UserFactory.create() data = {'email': user.email} request = self.create_request('post', data=data, auth=False) view = self.view_class.as_view() response = view(request) self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) # Duplicate the request here as we are accessing request.data twice. To # get the `request.data`, `djangorestframework` `read` the `POST` request # (a stream) without rewinding the stream. # This was producing an `Assertion` error only happening in test where # calling the `view` with the same `request` twice is returning: # {'detail': 'JSON parse error - No JSON object could be decoded'}` # https://github.com/tomchristie/django-rest-framework/blob/650a91ac24cbd3e5b4ad5d7d7c6706fdf6160a78/rest_framework/parsers.py#L60-L64 request = self.create_request('post', data=data, auth=False) view = self.view_class.as_view() response = view(request) self.assertEqual( response.status_code, status.HTTP_429_TOO_MANY_REQUESTS, msg=response.data, )
def test_deserialize(self): user = UserFactory.build() data = { 'name': 'New Name', } serializer = serializers.ProfileSerializer(user, data=data) self.assertTrue(serializer.is_valid())
def test_duplicate_email(self): """Emails should be unique regardless of case.""" # First create a user with the same email. self.data.pop('password2') UserFactory.create(**self.data) # Just for kicks, lets try changing the email case. self.data['email'] = self.data['email'].upper() request = self.create_request('post', auth=False, data=self.data) response = self.view_class.as_view()(request) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) self.assertTrue('email' in response.data, msg=response.data) self.assertEqual(User.objects.count(), 1)
def test_post_different_user_logged_in(self): """Assert a user can have amny accounts and verify one.""" user = UserFactory.create() other_user = UserFactory.create() token = user.generate_validation_token() request = self.create_request('post', user=other_user) view = self.view_class.as_view() response = view(request, token=token) self.assertEqual(response.status_code, status.HTTP_201_CREATED) updated_user = User.objects.get(pk=user.pk) self.assertTrue(updated_user.email_verified) logged_in_user = User.objects.get(pk=other_user.pk) self.assertFalse(logged_in_user.email_verified)
def test_existent_email(self): email = '*****@*****.**' user = UserFactory.create(email=email) context = {} site = Site.objects.get_current() request = self.create_request( 'post', data={'email': email}, auth=False, ) view = self.view_class.as_view() with patch(EMAIL_CONTEXT) as get_context: get_context.return_value = context with patch(SEND_METHOD) as send_email: response = view(request) self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) expected = { 'to': user.email, 'template_name': 'user_management/password_reset_email.txt', 'html_template_name': 'user_management/password_reset_email.html', 'subject': '{} password reset'.format(site.domain), 'context': context, 'headers': {}, } send_email.assert_called_once_with(**expected)
def test_delete_without_avatar(self): user = UserFactory.create() request = self.create_request('delete', user=user) view = self.view_class.as_view() response = view(request) self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
def test_post(self): username = '******' password = '******' UserFactory.create(email=username.lower(), password=password) data = {'username': username, 'password': password} request = self.create_request('post', auth=False, data=data) view = self.view_class.as_view() response = view(request) self.assertEqual(response.status_code, status.HTTP_200_OK, msg=response.data) # Ensure user has a token now token = self.model.objects.get(user__email=username.lower()) self.assertEqual(response.data['token'], token.key)
def test_get_no_avatar(self): user = UserFactory.build() request = self.create_request(user=user) view = self.view_class.as_view() response = view(request) self.assertEqual(response.status_code, 200) self.assertEqual(response.data['avatar'], None)
def test_get(self): user = UserFactory.build(avatar=SIMPLE_PNG) request = self.create_request(user=user) view = self.view_class.as_view() response = view(request) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.data['avatar'], SIMPLE_PNG.url)
def test_get(self): user = UserFactory.build(avatar=SIMPLE_PNG) request = self.create_request(user=user) view = self.view_class.as_view() response = view(request) self.assertEqual(response.status_code, 200) self.assertEqual(response.data['avatar'], SIMPLE_PNG.url)
def test_patch(self): user = UserFactory.build(is_staff=True) other_user = UserFactory.create() data = {'avatar': SIMPLE_PNG} request = APIRequestFactory().patch('/', data=data) request.user = user force_authenticate(request, user) view = self.view_class.as_view() with patch('django.core.files.storage.Storage.url') as mocked_url: mocked_url.return_value = 'mocked-url' response = view(request, pk=other_user.pk) self.assertEqual(response.status_code, status.HTTP_200_OK) SIMPLE_PNG.seek(0) user = User.objects.get(pk=other_user.pk) self.assertEqual(user.avatar.read(), SIMPLE_PNG.read())
def test_get_no_avatar(self): user = UserFactory.build() request = self.create_request(user=user) view = self.view_class.as_view() response = view(request) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.data['avatar'], None)
def test_patch(self): user = UserFactory.build(is_staff=True) other_user = UserFactory.create() data = {'avatar': SIMPLE_PNG} request = APIRequestFactory().patch('/', data=data) request.user = user force_authenticate(request, user) view = self.view_class.as_view() with patch('django.core.files.storage.Storage.url') as mocked_url: mocked_url.return_value = 'mocked-url' response = view(request, pk=other_user.pk) self.assertEqual(response.status_code, 200) SIMPLE_PNG.seek(0) user = User.objects.get(pk=other_user.pk) self.assertEqual(user.avatar.read(), SIMPLE_PNG.read())
def test_post_email_already_verified(self): """Assert email already verified does not trigger another email.""" user = UserFactory.create(email_verified=True) request = self.create_request('post', auth=False, data={'email': user.email}) view = self.view_class.as_view() response = view(request) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) self.assertIn('email', response.data)
def test_post_user_not_confirmed(self): """Assert non active users can not log in.""" UserFactory.create(email=self.username, password=self.password, is_active=False) request = self.create_request('post', auth=False, data=self.data) view = self.view_class.as_view() response = view(request) self.assertEqual( response.status_code, status.HTTP_400_BAD_REQUEST, msg=response.data, ) expected = 'Unable to log in with provided credentials.' self.assertIn(expected, response.data['non_field_errors']) self.assertNotIn('token', response.data)
def test_post_verified_email(self): """Assert verified user cannot verify email.""" user = UserFactory.create(email_verified=True) token = user.generate_validation_token() request = self.create_request('post') view = self.view_class.as_view() response = view(request, token=token) self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
def test_post_verified_email(self): user = UserFactory.create(email_verification_required=False) token = default_token_generator.make_token(user) uid = urlsafe_base64_encode(force_bytes(user.pk)) request = self.create_request('post') view = self.view_class.as_view() response = view(request, uidb64=uid, token=token) self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
def test_send_email_other_user(self): """Assert a user can not request a confirmation email for another user.""" user, other_user = UserFactory.create_batch(2) data = {'email': other_user.email} request = self.create_request('post', user=user, data=data) view = self.view_class.as_view() response = view(request) self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
def test_post_invalid_user(self): """Assert inexisting user verification return a bad request.""" user = UserFactory.build() token = user.generate_validation_token() request = self.create_request('post') view = self.view_class.as_view() response = view(request, token=token) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
def test_options(self): user = UserFactory.create() token = default_token_generator.make_token(user) uid = urlsafe_base64_encode(force_bytes(user.pk)) request = self.create_request('options', auth=False) view = self.view_class.as_view() response = view(request, uidb64=uid, token=token) self.assertEqual(response.status_code, status.HTTP_200_OK)
def test_get(self): user = UserFactory.create() request = self.create_request(user=user) view = self.view_class.as_view() response = view(request) self.assertEqual(response.status_code, status.HTTP_200_OK) expected = [self.expected_data(user)] self.assertEqual(response.data, expected)
def test_deserialize_invalid_new_password(self): new_password = '******' user = UserFactory.build() serializer = serializers.PasswordResetSerializer(user, data={ 'new_password': new_password, 'new_password2': new_password, }) self.assertFalse(serializer.is_valid()) self.assertIn('new_password', serializer.errors)
def test_delete(self): user = UserFactory.create() token = Token.objects.create(user=user) request = self.create_request('delete', user=user) response = self.view_class.as_view()(request) self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) with self.assertRaises(Token.DoesNotExist): Token.objects.get(pk=token.pk)
def test_send_email_subject_setting(self): """Assert the subject is affected by the DUM_VALIDATE_EMAIL_SUBJECT setting.""" user = UserFactory.create() request = self.create_request('post', auth=False, data={'email': user.email}) view = self.view_class.as_view() view(request) self.assertEqual(len(mail.outbox), 1) email = mail.outbox[0] self.assertEqual(email.subject, 'overridden subject')
def test_delete_with_avatar(self): user = UserFactory.create(avatar=SIMPLE_PNG) request = self.create_request('delete', user=user) view = self.view_class.as_view() response = view(request) self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) user = User.objects.get(pk=user.pk) self.assertFalse(user.avatar)
def test_serialize(self): user = UserFactory.build() serializer = serializers.ProfileSerializer(user) expected = { 'name': user.name, 'email': user.email, 'date_joined': user.date_joined, } self.assertEqual(serializer.data, expected)
def test_deserialize_mismatched_passwords(self): new_password = '******' other_password = '******' user = UserFactory.create() serializer = serializers.PasswordResetSerializer(user, data={ 'new_password': new_password, 'new_password2': other_password, }) self.assertFalse(serializer.is_valid())
def test_full_stack_wrong_url(self): """Integration test to check a nonexistent email returns a bad request.""" user = UserFactory.build() token = user.generate_validation_token() view_name = 'user_management_api_verify:verify_user' url = reverse(view_name, kwargs={'token': token}) response = self.client.post(url) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) self.assertTrue(hasattr(response, 'accepted_renderer'))
def test_full_stack_wrong_url(self): user = UserFactory.create() token = default_token_generator.make_token(user) uid = urlsafe_base64_encode(b'0') # Invalid uid, therefore bad url view_name = 'user_management_api_core:password_reset_confirm' url = reverse(view_name, kwargs={'uidb64': uid, 'token': token}) response = self.client.put(url) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) self.assertTrue(hasattr(response, 'accepted_renderer'))
def test_deserialize_passwords(self): new_password = '******' user = UserFactory.create() serializer = serializers.PasswordResetSerializer(user, data={ 'new_password': new_password, 'new_password2': new_password, }) self.assertTrue(serializer.is_valid()) serializer.save() self.assertTrue(user.check_password(new_password))
def test_post(self): """Assert user can request a new confirmation email.""" user = UserFactory.create() data = {'email': user.email} request = self.create_request('post', auth=False, data=data) view = self.view_class.as_view() response = view(request) self.assertEqual( response.status_code, status.HTTP_204_NO_CONTENT, msg=response.data, )