def test_get_logged_in_user(self): me = UserFactory() UserFactory() url = reverse("users-me") response = self.assertSchemaGet(url, None, "$userResponse", me) self.assertEqual(response.data["id"], me.pk)
def test_can_only_update_own_settings(self): user = UserFactory() other_user = UserFactory() url = reverse("notification_settings-detail", args=[user.notification_settings.first().pk]) data = {"allow_push": False, "allow_email": False} # A user can update their own settings response = self.assertSchemaPatch(url, "$notificationSettingRequest", "$notificationSettingResponse", data, user) self.assertEqual(response.data["id"], user.notification_settings.first().pk) self.assertFalse(response.data["allow_push"]) self.assertFalse(response.data["allow_email"]) # A user cannot update someone else's settings other_url = reverse("notification_settings-detail", args=[other_user.notification_settings.first().pk]) self.assertSchemaPatch(other_url, "$notificationSettingRequest", "$notificationSettingResponse", data, user, unauthorized=True)
def test_bulk_update_notification_settings(self): url = reverse("notification_settings-list") user = UserFactory() bad_user = UserFactory() notification_settings = user.notification_settings.all() data = [{ "id": notification_settings[0].pk, "allow_email": False }, { "id": notification_settings[1].pk, "allow_email": False }] # Can't update another user's notification settings self.assertSchemaPut(url, "$notificationSettingBulkRequest", "$notificationSettingResponse", data, bad_user, forbidden=True) self.assertTrue( NotificationSetting.objects.get( pk=notification_settings[0].pk).allow_email) self.assertSchemaPut(url, "$notificationSettingBulkRequest", "$notificationSettingResponse", data, user) self.assertFalse( NotificationSetting.objects.get( pk=notification_settings[0].pk).allow_email)
def test_user_can_reset_password(self): url = reverse("password_new") beverly = UserFactory(username="******") beverly.set_password("jack") beverly.save() mismatch_password_data = { "uid": urlsafe_base64_encode(force_bytes(beverly.pk)).decode(), "token": default_token_generator.make_token(beverly), "password": encode_string("wesley"), "confirm_password": encode_string("WESLEY") } response = self.client.post(url, mismatch_password_data, format='json') self.assertEqual(response.status_code, 400) self.assertFalse(User.objects.get(username='******').check_password('wesley')) bad_uid_data = { "uid": urlsafe_base64_encode(force_bytes(UserFactory().pk)).decode(), "token": default_token_generator.make_token(beverly), "password": encode_string("wesley"), "confirm_password": encode_string("wesley") } response = self.client.post(url, bad_uid_data, format='json') self.assertEqual(response.status_code, 400) self.assertFalse(User.objects.get(username='******').check_password('wesley')) good_data = { "uid": urlsafe_base64_encode(force_bytes(beverly.pk)).decode(), "token": default_token_generator.make_token(beverly), "password": encode_string("wesley"), "confirm_password": encode_string("wesley") } self.assertSchemaPost(url, "$setPasswordRequest", "$userResponse", good_data, None, status_OK=True) self.assertTrue(User.objects.get(username='******').check_password('wesley'))
def test_update_user(self): me = UserFactory() stranger = UserFactory() url = reverse("users-detail", args=[me.pk]) data = { "fullname": "Hodor", "username": me.username # Don't freak out if unchanged unique data is sent } # Unauthenticated user can't update a user's profile self.assertSchemaPatch(url, "$userRequest", "$userResponse", data, None, unauthorized=True) self.assertEqual(User.objects.get(pk=me.pk).fullname, None) # Stranger can't update another user's profile self.assertSchemaPatch(url, "$userRequest", "$userResponse", data, stranger, unauthorized=True) self.assertEqual(User.objects.get(pk=me.pk).fullname, None) # User can update their own profile self.assertSchemaPatch(url, "$userRequest", "$userResponse", data, me) self.assertEqual(User.objects.get(pk=me.pk).fullname, "Hodor")
def test_can_only_see_own_notification_settings(self): user = UserFactory() UserFactory() url = reverse("notification_settings-list") response = self.assertSchemaGet(url, None, "$notificationSettingResponse", user) self.assertEqual(response.data["count"], NotificationType.objects.count())
def setUp(self): super(NotificationsTestCase, self).setUp() self.social_obj = PostFactory() self.receiver = UserFactory() self.reporter = UserFactory() self.notification_type = NotificationType.objects.get(slug="comment") PushwooshClient.invoke = MagicMock(return_value={"status_code": 200}) PushClient.invoke = MagicMock(return_value={"status_code": 200})
def setUp(self): super(NotificationsTestCase, self).setUp() self.social_obj = PostFactory() self.receiver = UserFactory() self.reporter = UserFactory() self.notification_type = NotificationType.objects.get(slug="comment") patcher = patch('yak.rest_notifications.utils.submit_to_pushwoosh') self.addCleanup(patcher.stop) self.mock_submit_to_pushwoosh = patcher.start() self.mock_submit_to_pushwoosh.return_value = {"status_code": 200}
def test_autocomplete(self): """ Tests that when a string is sent with the user's name or username, we return a filtered list of users """ url = reverse("users-list") bob = UserFactory(username="******") frank = UserFactory(username="******") UserFactory(username="******") parameters = {"search": "fra"} response = self.assertSchemaGet(url, parameters, "$userResponse", bob) self.assertEqual(response.data["count"], 1) self.assertEqual(response.data["results"][0]["username"], frank.username)
def test_edit_user_to_inexact_match(self): """ You also can't edit a user to an inexact match of someone else's username. This fails correctly at the DB level, but need to add validation in the API to give better errors """ user1 = UserFactory(username="******") UserFactory(username="******") url = reverse("users-detail", args=[user1.pk]) data = {"username": "******"} self.add_credentials(user1) response = self.client.patch(url, data, format="json") self.assertHttpBadRequest(response)
def test_bulk_follow(self): user1 = UserFactory() user2 = UserFactory() url = reverse('follows-bulk-create') user_content_type = ContentType.objects.get_for_model(User) data = [ {'content_type': user_content_type.pk, 'object_id': user1.pk}, {'content_type': user_content_type.pk, 'object_id': user2.pk} ] self.assertSchemaPost(url, "$followRequest", "$followResponse", data, self.dev_user) self.assertEqual(user1.user_followers_count(), 1) self.assertEqual(user2.user_followers_count(), 1)
def test_users_can_share_content_multiple_times(self): sharing_user = UserFactory() test_user = UserFactory() content_type = ContentType.objects.get_for_model(Post) shares_url = reverse('shares-list') data = { 'content_type': content_type.pk, 'object_id': PostFactory().pk, 'shared_with': [test_user.pk] } self.assertSchemaPost(shares_url, "$shareRequest", "$shareResponse", data, sharing_user) data['shared_with'] = [self.dev_user.pk] self.assertSchemaPost(shares_url, "$shareRequest", "$shareResponse", data, sharing_user)
def test_follow_id(self): follower = UserFactory() user_content_type = ContentType.objects.get_for_model(User) follow_object = Follow.objects.create(content_type=user_content_type, object_id=self.dev_user.pk, user=follower) url = reverse("users-detail", args=[self.dev_user.pk]) response = self.assertSchemaGet(url, None, "$userResponse", follower) self.assertEqual(response.data['follow_id'], follow_object.pk) not_follower = UserFactory() url = reverse("users-detail", args=[self.dev_user.pk]) response = self.assertSchemaGet(url, None, "$userResponse", not_follower) self.assertIsNone(response.data['follow_id'])
def test_users_can_flag_content(self): test_user = UserFactory() content_type = ContentType.objects.get_for_model(Post) flag_url = reverse('flag') data = {'content_type': content_type.pk, 'object_id': PostFactory().pk} self.assertSchemaPost(flag_url, "$flagRequest", "$flagResponse", data, test_user)
def test_photo_resize(self): me = UserFactory() url = reverse("users-detail", args=[me.pk]) data = { "original_photo": open(settings.PROJECT_ROOT + "/test_app/tests/img/yeti.jpg", 'r') } self.assertSchemaPatch(url, "$userRequest", "$userResponse", data, me, format="multipart") user = User.objects.get(pk=me.pk) # Check the original photo is saved self.assertEqual( user.original_photo.file.read(), open(settings.PROJECT_ROOT + "/test_app/tests/img/yeti.jpg", 'r').read()) # Check the photo is correctly resized for size_field, size in User.SIZES.iteritems(): w, h = get_image_dimensions(getattr(user, size_field).file) self.assertEqual(size['height'], h) self.assertEqual(size['width'], w)
def test_follower_endpoint(self): test_user1 = UserFactory() test_user2 = UserFactory() user_content_type = ContentType.objects.get_for_model(User) # Dev User to follow User 1, User 2 to follow Dev User Follow.objects.create(content_type=user_content_type, object_id=test_user1.pk, user=self.dev_user) Follow.objects.create(content_type=user_content_type, object_id=self.dev_user.pk, user=test_user2) followers_url = reverse('users-followers', args=[self.dev_user.pk]) response = self.assertSchemaGet(followers_url, None, "$followResponse", self.dev_user) self.assertEqual(len(response.data), 1) self.assertEqual(response.data[0]['follower']['username'], test_user2.username)
def test_user_can_get_reset_password_email(self): jeanluc = UserFactory(username="******") url = reverse("password_reset") data = {"email": jeanluc.email} self.assertSchemaPost(url, "$resetPasswordRequest", "$resetPasswordResponse", data, None, status_OK=True) self.assertEqual(len(mail.outbox), 1)
def test_settings_only_updated_or_listed(self): # Cannot be created or destroyed user = UserFactory() create_url = reverse("notification_settings-list") delete_url = reverse("notification_settings-detail", args=[user.notification_settings.first().pk]) data = { "allow_push": False, "allow_email": False } self.assertSchemaPost(create_url, "$notificationSettingRequest", "$notificationSettingResponse", data, user, unauthorized=True) self.assertSchemaDelete(delete_url, user, unauthorized=True)
def test_user_following_and_follower_count(self): follower1 = UserFactory() follower2 = UserFactory() following = UserFactory() user_content_type = ContentType.objects.get_for_model(User) # Follower setup Follow.objects.create(content_type=user_content_type, object_id=following.pk, user=self.dev_user) Follow.objects.create(content_type=user_content_type, object_id=self.dev_user.pk, user=follower1) Follow.objects.create(content_type=user_content_type, object_id=self.dev_user.pk, user=follower2) users_url = reverse('users-detail', kwargs={'pk': self.dev_user.pk}) response = self.assertSchemaGet(users_url, None, "$userResponse", self.dev_user) self.assertEqual(response.data['user_following_count'], 1) self.assertEqual(response.data['user_followers_count'], 2)
def test_user_can_change_password(self): felicia = UserFactory(username='******') felicia.set_password('password') felicia.save() url = reverse("password_change") data = { "old_password": encode_string("password"), "password": encode_string("felicia"), "confirm_password": encode_string("felicia") } # Unauthenticated user can't change password self.assertSchemaPatch(url, "$changePasswordRequest", "$changePasswordResponse", data, None, unauthorized=True) self.assertFalse(User.objects.get(pk=felicia.pk).check_password("felicia")) # User can't change password if the old / current password is incorrect bad_data = { "old_password": encode_string("wrong_password"), "password": encode_string("felicia"), "confirm_password": encode_string("felicia") } self.assertSchemaPatch(url, "$changePasswordRequest", "$changePasswordResponse", bad_data, felicia, unauthorized=True) self.assertFalse(User.objects.get(pk=felicia.pk).check_password("felicia")) # User can't change password if the two new passwords don't match mismatch_password_data = { "old_password": encode_string("password"), "password": encode_string("felicia"), "confirm_password": encode_string("FELICIA") } self.add_credentials(felicia) response = self.client.patch(url, mismatch_password_data, format='json') self.assertEqual(response.status_code, 400) self.assertFalse(User.objects.get(pk=felicia.pk).check_password("felicia")) # User can change their own password self.assertSchemaPatch(url, "$changePasswordRequest", "$changePasswordResponse", data, felicia) self.assertTrue(User.objects.get(pk=felicia.pk).check_password("felicia"))
def test_user_can_follow_each_other(self): test_user1 = UserFactory() user_content_type = ContentType.objects.get_for_model(User) follow_url = reverse('follows-list') # Dev User to follow Test User 1 data = { 'content_type': user_content_type.pk, 'object_id': test_user1.pk } response = self.assertSchemaPost(follow_url, "$followRequest", "$followResponse", data, self.dev_user) self.assertEqual(response.data['following']['username'], test_user1.username)
def test_serialization_when_content_object_deleted(self): mention_notification = NotificationType.objects.get(slug="mention") content_type = ContentType.objects.get_for_model(Post) user = UserFactory() post = PostFactory(user=user) Notification.objects.create(notification_type=mention_notification, content_type=content_type, object_id=post.pk, user=user, reporter=self.reporter) post.delete() other_post = PostFactory(user=user) Notification.objects.create(notification_type=mention_notification, content_type=content_type, object_id=other_post.pk, user=user, reporter=self.reporter) url = reverse("notifications") response = self.assertSchemaGet(url, None, "$notificationResponse", user) self.assertEqual(response.data['count'], 1) self.assertEqual(response.data['results'][0]['post']['id'], other_post.pk)
def test_user_can_change_password(self): felicia = UserFactory(username='******') felicia.set_password('password') felicia.save() url = reverse("password_change") data = { "old_password": base64.encodestring("password"), "password": base64.encodestring("felicia"), "confirm_password": base64.encodestring("felicia") } # Unauthenticated user can't change password self.assertSchemaPatch(url, "$changePasswordRequest", "$changePasswordResponse", data, None, unauthorized=True) self.assertFalse( User.objects.get(pk=felicia.pk).check_password("felicia")) # User can't change password if the old / current password is incorrect bad_data = { "old_password": base64.encodestring("wrong_password"), "password": base64.encodestring("felicia"), "confirm_password": base64.encodestring("felicia") } self.assertSchemaPatch(url, "$changePasswordRequest", "$changePasswordResponse", bad_data, felicia, unauthorized=True) self.assertFalse( User.objects.get(pk=felicia.pk).check_password("felicia")) # User can't change password if the two new passwords don't match mismatch_password_data = { "old_password": base64.encodestring("password"), "password": base64.encodestring("felicia"), "confirm_password": base64.encodestring("FELICIA") } self.add_credentials(felicia) response = self.client.patch(url, mismatch_password_data, format='json') self.assertEqual(response.status_code, 400) self.assertFalse( User.objects.get(pk=felicia.pk).check_password("felicia")) # User can change their own password self.assertSchemaPatch(url, "$changePasswordRequest", "$changePasswordResponse", data, felicia) self.assertTrue( User.objects.get(pk=felicia.pk).check_password("felicia"))
def test_content_object_serialization(self): """ Content object is serialized using the standard serialization for that object type The `content_objectt` key is replaced for each different type of object serialized """ article = Article.objects.create(title="Cool article") user = UserFactory() create_notification(user, self.reporter, self.social_obj, self.notification_type) create_notification(user, self.receiver, article, self.notification_type) url = reverse("notifications") response = self.assertSchemaGet(url, None, "$notificationResponse", user) self.assertEqual(response.data["count"], 2) self.assertIn("article", response.data["results"][0]) self.assertNotIn("post", response.data["results"][0]) self.assertIn("post", response.data["results"][1]) self.assertNotIn("article", response.data["results"][1])
def test_follow_pagination(self): user_content_type = ContentType.objects.get_for_model(User) for _ in range(0, 30): user = UserFactory() Follow.objects.create(content_type=user_content_type, object_id=self.dev_user.pk, user=user) followers_url = reverse('users-followers', args=[self.dev_user.pk]) response = self.assertSchemaGet(followers_url, None, "$followResponse", self.dev_user) self.assertEqual(len(response.data), settings.REST_FRAMEWORK['PAGE_SIZE']) response = self.assertSchemaGet(followers_url, {"page": 2}, "$followResponse", self.dev_user) self.assertEqual(len(response.data), 30 - settings.REST_FRAMEWORK['PAGE_SIZE'])
def test_user_can_unfollow_user(self): follower = UserFactory() user_content_type = ContentType.objects.get_for_model(User) follow_object = Follow.objects.create(content_type=user_content_type, object_id=self.dev_user.pk, user=follower) follows_url = reverse('follows-detail', kwargs={'pk': follow_object.pk}) # If you are not the follower of the user, you cannot unfollow the user self.assertSchemaDelete(follows_url, self.dev_user, unauthorized=True) # If you are the follower of that user, you can unfollow the user self.assertSchemaDelete(follows_url, follower) # Check that original follow object no longer exists self.assertEqual( Follow.objects.filter(pk=follow_object.pk).exists(), False)
def test_comments_for_specific_object(self): test_user = UserFactory() post_content_type = ContentType.objects.get_for_model(Post) post = PostFactory(user=test_user) comment = CommentFactory(content_type=post_content_type, object_id=post.pk) post2 = PostFactory(user=test_user) CommentFactory(content_type=post_content_type, object_id=post2.pk) url = reverse('comments-list') parameters = { 'content_type': post_content_type.pk, 'object_id': post.pk, } response = self.assertSchemaGet(url, parameters, "$commentResponse", self.dev_user) self.assertEqual(len(response.data["results"]), 1) self.assertEqual(response.data["results"][0]["id"], comment.pk)
def test_user_can_reset_password(self): url = reverse("password_new") beverly = UserFactory(username="******") beverly.set_password("jack") beverly.save() mismatch_password_data = { "uid": urlsafe_base64_encode(force_bytes(beverly.pk)).decode(), "token": default_token_generator.make_token(beverly), "password": encode_string("wesley"), "confirm_password": encode_string("WESLEY") } response = self.client.post(url, mismatch_password_data, format='json') self.assertEqual(response.status_code, 400) self.assertFalse( User.objects.get(username='******').check_password('wesley')) bad_uid_data = { "uid": urlsafe_base64_encode(force_bytes(UserFactory().pk)).decode(), "token": default_token_generator.make_token(beverly), "password": encode_string("wesley"), "confirm_password": encode_string("wesley") } response = self.client.post(url, bad_uid_data, format='json') self.assertEqual(response.status_code, 400) self.assertFalse( User.objects.get(username='******').check_password('wesley')) good_data = { "uid": urlsafe_base64_encode(force_bytes(beverly.pk)).decode(), "token": default_token_generator.make_token(beverly), "password": encode_string("wesley"), "confirm_password": encode_string("wesley") } self.assertSchemaPost(url, "$setPasswordRequest", "$userResponse", good_data, None, status_OK=True) self.assertTrue( User.objects.get(username='******').check_password('wesley'))
def test_only_authed_user_can_create_post(self): """ For default permission `IsOwnerOrReadOnly` verifies that any logged in user can create a post Non-authenticated users cannot create a post """ url = reverse("posts-list") old_post_count = Post.objects.count() data = { "title": "i'm not logged in", "description": "so this shouldn't work" } self.assertSchemaPost(url, "$postRequest", "$postResponse", data, None, unauthorized=True) self.assertEqual(old_post_count, Post.objects.count()) self.assertSchemaPost(url, "$postRequest", "$postResponse", data, UserFactory()) self.assertEqual(old_post_count + 1, Post.objects.count())
def test_inexact_signup(self): """ Email and username are case insensitive """ UserFactory(username="******", email="*****@*****.**") url = reverse("sign_up") data = { 'username': '******', 'email': '*****@*****.**', 'password': "******" } response = self.client.post(url, data, format="json") self.assertHttpBadRequest(response) data = { 'username': "******", 'email': '*****@*****.**', 'password': "******" } response = self.client.post(url, data, format="json") self.assertHttpBadRequest(response)
def test_bulk_follow(self): user1 = UserFactory() user2 = UserFactory() url = reverse('follows-bulk-create') user_content_type = ContentType.objects.get_for_model(User) data = [{ 'content_type': user_content_type.pk, 'object_id': user1.pk }, { 'content_type': user_content_type.pk, 'object_id': user2.pk }] self.assertSchemaPost(url, "$followRequest", "$followResponse", data, self.dev_user) self.assertEqual(user1.user_followers_count(), 1) self.assertEqual(user2.user_followers_count(), 1)
def setUp(self): super(BaseAPITests, self).setUp() self.dev_user = UserFactory()