def test_replied_tells_author_and_op_author(self): # Some dude starts a thread author = create_user() content = create_content() op = create_comment(author=author, reply_content=content) # Another dude posts a reply guest_author = create_user() reply = create_comment(replied_comment=op, author=guest_author, parent_comment=op) self.assertEqual(reply.thread.op, op) # A third dude replies to the guest author guest_author_2 = create_user() reply_2 = create_comment(replied_comment=reply, author=guest_author_2, parent_comment=op) self.assertTrue(reply_2.thread.op.author, author) # Issue the action pn = Actions.replied(guest_author_2, reply_2) notifications = expander.expand(pn) print notifications # Now, we should tell both the OP author, and the guest author. notifications = filter(lambda n: n.channel == 'EmailChannel', notifications) self.assertEqual(len(notifications), 2) n1 = notifications[0] n2 = notifications[1] self.assertEqual(n1.action, 'replied') self.assertEqual(n1.recipient, guest_author) self.assertEqual(n2.action, 'thread_replied') self.assertEqual(n2.recipient, author)
def test_followers(self): user = create_user() follower = create_user() follower.follow(user) resp = self.api_post('/api/following/followers', {'username': user.username}) self.assertAPISuccess(resp) self.assertEqual(resp['followers'][0]['username'], follower.username)
def test_actor(self): author = create_user() op = create_comment(author=author, reply_content=create_content()) replier = create_user() reply = create_comment(replied_comment=op, author=replier) activity = ThreadReplyActivity.from_comment(replier, reply) self.assertEqual(activity.actor['id'], replier.id)
def test_wrong_user_cancellation(self): user = create_user(email=self.old_email) user2 = create_user(email=self.old_email) confirmation = EmailConfirmation.objects.create_confirmation( user, self.new_email) self.assertEqual(EmailConfirmation.objects.all().count(), 1) try: resp = self.get(confirmation.cancellation_url(), user=user2) except NotOkay, e: resp = e.response
def test_anonymous_actor(self): author = create_user() op = create_comment(author=author, reply_content=create_content()) for anon in [True, False]: replier = create_user() reply = create_comment(replied_comment=op, author=replier, anonymous=anon) activity = ThreadReplyActivity.from_comment(replier, reply) self.assertEqual(activity.is_actor_anonymous, anon)
def test_update_score(self): user = create_user() comment = create_comment(author=user) for sticker in stickers.primary_types: user = create_user() user.kv.stickers.currency.increment(100) # Sticker the comment a bunch. request = FakeRequest(user) api._sticker_comment(request, comment, sticker.type_id) # Update score comment.update_score()
def test_get_users_by_post(self): user = create_user() user1 = create_user() user2 = create_user() users = [user, user1, user2] data = {'ids': [user.username, user1.username, user2.username, "trololo"]} result = self.post('/public_api/users/', data=data) self.assertAPISuccess(result) json = util.loads(result.content) self.assertEqual(len(users), len(json['users'])) returned_users = [x['user'] for x in json['users']] for u in users: self.assertIn(u.username, returned_users)
def test_already_received(self): with override_service('time', FakeTimeProvider): # Create dummy first, so count of users and count of recipients is unequal. create_user() Services.time.step(60*60*48) user = create_user() self.assertFalse(user in send_24h_email.recipients()) Services.time.step(60*60*48) WelcomeEmailRecipient.objects.create(recipient=user) recipients = send_24h_email.recipients() self.assertFalse(user in recipients) self.assertFalse(recipients)
def test_purchase_multiple_sufficient(self): nyan = stickers.details_for(STORE_ITEM) user = create_user() user.redis.user_kv.hset('sticker:7:count', 1000) result = self.api_post('/api/store/buy', {'item_type': 'sticker', 'item_id': nyan.type_id, 'quantity': '2'}, user=user) self.assertEqual(result, {'success': True, 'new_balance': 1000-(2*nyan.cost) })
def test_inventory_sticker_withinventory(self): user = create_user() user.redis.user_kv.hset('sticker:%s:count' % STORE_ITEM, 1) result = self.api_post('/api/sticker/comment', {'type_id': STORE_ITEM, 'comment_id': self.comment.id}, user=user) for k,v in {'success': True, 'new_counts': {STORE_ITEM: 1}, 'remaining': 0}.iteritems(): self.assertEqual(result[k], v)
def setUp(self): CanvasTestCase.setUp(self) self.group = create_group(founder=create_user()) self.content = create_content() self.text = 'foo bar baz lol what' self.op = self.post_comment(reply_content=self.content.id, category=self.group.name, reply_text=self.text) self.user = create_user() # It would be great to at some point make some kind of "with configOverride(foo=new_value):" self.previousConfig = copy.deepcopy(configuration.Config) Config['minimum_top_replies'] = 1 Config['maximum_top_replies'] = 2 Config['posts_per_top_reply'] = 2 self._per_page = knobs.COMMENTS_PER_PAGE knobs.COMMENTS_PER_PAGE = 2
def test_user_receives(self): user = utils.create_user() pn = Actions.daily_free_stickers(user, 5) ex = expander.get_expander(pn)() recipients = ex.decide_recipients(pn) self.assertEqual(len(recipients), 1) self.assertIn(user, recipients)
def test_unsubscribe_page_without_user_id(self): user = create_user() resp = self.get('/unsubscribe?' + urllib.urlencode({ 'token': util.token(user.email), 'email': user.email, })) self.assertNumCssMatches(0, resp, 'input[name="user_id"]')
def test_no_reply_notifications_for_inactive_users(self): author = create_user() comment = create_comment(author=author) action_func_list = [Actions.remixed, Actions.replied, Actions.thread_replied] # First make sure that the user can receive all possible "comment" # related notifications, like replied, remixed ... etc for func in action_func_list: pending_notification = func(author, comment) self.assertTrue(EmailChannel.enabled_for_recipient_action(pending_notification.action, author, pending_notification)) author.is_active = False author.save() for func in action_func_list: pending_notification = func(author, comment) self.assertFalse(EmailChannel.enabled_for_recipient_action(pending_notification.action, author, pending_notification))
def test_confirmation_cancellation(self): user = create_user(email=self.old_email) confirmation = EmailConfirmation.objects.create_confirmation( user, self.new_email) self.assertEqual(EmailConfirmation.objects.all().count(), 1) self.get(confirmation.cancellation_url(), user=user) self.assertEqual(EmailConfirmation.objects.all().count(), 0)
def test_sticker_kv_purchase_markers(self): sticker = self.sticker user = create_user() assert user.kv.stickers.did_purchase(sticker) == False user.kv.stickers.mark_sticker_purchased(sticker) assert user.kv.stickers.did_purchase(sticker) == True
def test_sticker_from_user(self): user = create_user() comment = create_comment() self.assertFalse(CommentSticker.get_sticker_from_user(comment.id, user)) self.api_post("/api/sticker/comment", {"type_id": "1", "comment_id": comment.id}, user=user) self.assertTrue(CommentSticker.get_sticker_from_user(comment.id, user))
def test_really_old_users_dont_get_it(self): with override_service('time', FakeTimeProvider): user = create_user() Services.time.step(60*60*24) self.assertTrue(user in send_24h_email.recipients()) Services.time.step(60*60*24*30) # a month later. self.assertFalse(user in send_24h_email.recipients())
def test_get_browse_tiles_without_dupes(self): tiles = get_browse_tiles(create_user(), Navigation(sort='hot', offset=0, category=Category.ALL)) self.assertTrue(tiles) tile_ids = [tile.comment.id for tile in tiles] self.assertEqual(sorted(tile_ids), sorted(list(set(tile_ids))))
def test_secure_only_middleware(self): user = create_user() client = self.get_client(user=user) url = reverse('apps.user_settings.views.user_settings') # First set Force HTTPS resp = self.post(url, data={ 'email': user.email, 'force_https': 'on', }, user=user, client=client) # Now try visiting a page without the cookie, and see that it gets set. client = self.get_client(user=user) resp = self.get('/', user=user, client=client) self.assertTrue(resp.cookies.get('secure_only')) # Unset it and check the redis value is gone. self.assertTrue(int(user.redis.user_kv.hget('secure_only') or 0)) def do_form_post(): return self.post(url, data={ 'email': user.email, }, user=user, client=client, https=True) resp = do_form_post() self.assertRedirectsNoFollow(resp, 'https://testserver:80' + url) # Mock SSL and re-POST client.defaults['wsgi.url_scheme'] = 'https' do_form_post() # Now check it had an effect. self.assertFalse(int(user.redis.user_kv.hget('secure_only') or 0))
def test_sticker_from_user(self): user = create_user() comment = create_comment() self.assertFalse(CommentSticker.get_sticker_from_user(comment.id, user)) self.api_post('/api/sticker/comment', {'type_id': '1', 'comment_id': comment.id}, user=user) self.assertTrue(CommentSticker.get_sticker_from_user(comment.id, user))
def test_handle_bad_username(self): user = create_user() username = user.username + "lolol" result = self.get('/public_api/users/{0}'.format(username)) self.assertAPIFailure(result) result = self.post('/public_api/users/{0}'.format(username)) self.assertAPIFailure(result)
def test_five_thousand_points_gives_only_one_level_up(self): user = create_user() user.redis.user_kv.hincrby('sticker_inbox', 5000) result = self.api_post('/api/user/level_up', {}, user=user) self.assertEqual(result['stats']['level_progress'], 4995) self.assertEqual(result['stats']['level'], 1) self.assertEqual(result['reward_stickers'], 3)
def test_follow(self): user = create_user() group = create_group() result = self.api_post('/api/group/follow', {'category_id': group.id}, user=user) self.assertEqual(result['success'], True) fc = FollowCategory.objects.get_or_none(category=group, user=user) self.assertTrue(bool(fc))
def test_multiple_confirmations(self): user = create_user(email=self.old_email) confirmation = EmailConfirmation.objects.create_confirmation( user, 'first' + self.new_email) confirmation = EmailConfirmation.objects.create_confirmation( user, self.new_email) self.assertEqual(EmailConfirmation.objects.all().count(), 1) self.assertEqual(EmailConfirmation.objects.all()[0].new_email, self.new_email)
def test_key_changes(self): user = create_user(email=self.old_email) confirmation = EmailConfirmation.objects.create_confirmation( user, self.new_email) confirmation2 = EmailConfirmation.objects.create_confirmation( user, 'newer' + self.new_email) self.assertNotEqual(confirmation.confirmation_key, confirmation2.confirmation_key)
def test_confirmation_email_contents(self): user = create_user(email=self.old_email) confirmation = user.change_email(self.new_email) subject, msg = confirmation._generate_confirmation_email() # Make sure it has the right links with the confirmation key in the email body. self.assertTrue(confirmation.confirmation_key in msg) self.assertTrue(confirmation._activate_url() in msg)
def test_purchase_multiple_insufficient(self): nyan = stickers.details_for(STORE_ITEM) user = create_user() user.redis.user_kv.hset('sticker:7:count', 100) result = self.api_post('/api/store/buy', {'item_type': 'sticker', 'item_id': nyan.type_id, 'quantity': '1000'}, user=user) self.assertEqual(result, {'success': False, 'reason': 'Insufficient balance.'})
def test_send_small_sticker_get_point_immediately(self): sender = create_user() result = self.api_post('/api/sticker/comment', {'type_id': '1', 'comment_id': self.comment.id}, user=sender) self.author.kv.update() self.assertTrue(result['success']) self.assertEqual(self.author.kv.sticker_inbox.get(), 1)
def _give_epic_sticker(self): sender = create_user() sender.kv.stickers[self._epic_sticker.type_id].increment(1) self._sticker(self.user, sticker_type_id=self._epic_sticker.type_id, sender=sender) self.user.kv.update() for notification in self.user.redis.notifications.get(): self.api_post('/api/notification/acknowledge', {'nkey': notification['nkey']}, user=self.user)
def test_granualr_unsubscribe_blanket_ban(self): all_actions = EmailChannel.all_handled_actions() # ALL has inverted semantics ... make sure it works. all_actions.append("ALL") # Reuse the same user canvas_user = create_user() action = "ALL" actions_dict = {action: "on"} unsubscriptions = self.validate_unsubscript(actions_dict, canvas_user, all_actions) for action in all_actions: # Ensure that we unsubscribed from all of them! assert unsubscriptions.get(action) action = "ALL" # Remove blanket subscription actions_dict = {} request = FakeRequest() views.handle_unsubscribe_post(canvas_user, actions_dict, request) unsubscriptions = views.get_unsubscriptions(canvas_user, all_actions) for action in all_actions: # Ensure that the user is now subscribed for everything, which is the default without the blanket ban. assert not unsubscriptions.get(action)
def validate_unsubscript(self, actions_dict, canvas_user=None, all_actions=None): if not canvas_user: canvas_user = create_user() if not all_actions: all_actions = EmailChannel.all_handled_actions() request = FakeRequest() views.handle_unsubscribe_post(canvas_user, actions_dict, request) unsubscriptions = views.get_unsubscriptions(canvas_user, all_actions) for action in all_actions: if action == 'newsletter': continue value = action if action == "ALL": value = not action if actions_dict.get(action) == "on": assert not unsubscriptions.get(value) else: assert unsubscriptions.get(value) return unsubscriptions
def test_no_reply_notifications_for_muted_threads(self): author = create_user() comment = create_comment(author=author) action_func_list = [Actions.remixed, Actions.replied, Actions.thread_replied] # First make sure that the user can receive all possible "comment" # related notifications, like replied, remixed ... etc for func in action_func_list: pending_notification = func(author, comment) self.assertTrue(EmailChannel.enabled_for_recipient_action(pending_notification.action, author, pending_notification)) # Now, mute the thread author.redis.mute_thread(comment) for func in action_func_list: pending_notification = func(author, comment) self.assertFalse(EmailChannel.enabled_for_recipient_action(pending_notification.action, author, pending_notification))
def test_get_paged_user_posts(self): user = create_user() knobs.PUBLIC_API_PAGINATION_SIZE = 5 first_five = [ create_comment(author=user) for x in range(knobs.PUBLIC_API_PAGINATION_SIZE) ] second_five = [ create_comment(author=user) for x in range(knobs.PUBLIC_API_PAGINATION_SIZE) ] data = {'ids': [user.username]} result = self.post('/public_api/users/', data=data) self.assertAPISuccess(result) json = util.loads(result.content) self.assertEqual(1, len(json['users'])) self.assertEqual(knobs.PUBLIC_API_PAGINATION_SIZE, len(json['users'][0]['posts'])) returned_ids = [x['id'] for x in json['users'][0]['posts']] for x in second_five: self.assertIn(short_id(x.id), returned_ids) data = { 'ids': [{ 'user': user.username, 'skip': knobs.PUBLIC_API_PAGINATION_SIZE }] } result = self.post('/public_api/users/', data=data) self.assertAPISuccess(result) json = util.loads(result.content) self.assertEqual(1, len(json['users'])) self.assertEqual(knobs.PUBLIC_API_PAGINATION_SIZE, len(json['users'][0]['posts'])) returned_ids = [x['id'] for x in json['users'][0]['posts']] for x in first_five: self.assertIn(short_id(x.id), returned_ids)
def test_admins_can_moderate(self): admin = create_user(staff=True) self.assertTrue(admin.can_moderate_flagged) self.assertTrue(admin.can_bestof_all) self.assertNotEqual([], admin.can_moderate_visibility)
def after_setUp(self): self.user = create_user()
def after_setUp(self): self.user = create_user() self._epic_sticker = stickers.get('nyancat')
def test_newsletter_expander_for_user_with_no_email(self): user = create_user(email="") pn = Actions.newsletter(user) self.assertFalse(user.email) notifications = expander.expand(pn) self.assertEqual(len(notifications), 0)
def request(self): return FakeRequest(create_user())
def test_not_yet_receieved(self): with override_service('time', FakeTimeProvider): user = create_user() Services.time.step(60 * 60 * 24) recipients = send_24h_email.recipients() self.assertTrue(user in recipients)
def get_email_message(): user = create_user() pn = Actions.digest(user) notification = Notification.from_pending_notification(pn, user, "EmailChannel") return EmailChannel().make_message(notification, force=True)
def setUp(self): CanvasTestCase.setUp(self) self.user = create_user(is_qa=False) self.request = FakeRequest(self.user)
def _render_replies(self, replies): context = {'request': FakeRequest(create_user())} return jinja_tags.jinja_thread_comments(context, [c.details() for c in replies])
def create_user(*args, **kwargs): return canvas_tests_helpers.create_user(*args, user_cls=User, **kwargs)
def test_pageview_records_view_metric(self): self.assertViewCount(FakeRequest(create_user(), path="/user/foobar"), HttpResponse(status=200), 1)
def test_user_exists(self): user = create_user() resp = self.api_post('/api/user/exists', {'username': user.username}) self.assertAPIFailure(resp)
def test_nonadmins_cant_moderate(self): admin = create_user() self.assertFalse(admin.can_moderate_flagged) self.assertFalse(admin.can_bestof_all) self.assertEqual([], admin.can_moderate_visibility)
def test_staff_with_nonstaff_user(self): request = FakeRequest(user=create_user()) self.assertRaises(PermissionDenied, lambda: self.require_staff(request))
def test_24h_digest_email_has_top_comments(self): COMMENT_COUNT = knobs.TWENTYFOUR_HOUR_EMAIL_COMMENT_COUNT GROUP = create_group(name=Config['featured_groups'][0]) TODAY = datetime.datetime(year=2011, month=2, day=3) with override_service('time', FakeTimeProvider): #TODO refactor into tests_helpers and consolidate w/ other tests that do this (email_channel, models) # Make posts to show up in 'best'. Services.time.t = time.mktime(TODAY.timetuple()) comments = [self.post_comment(reply_content=create_content().id, category=GROUP.name) for _ in xrange(COMMENT_COUNT)] Services.time.step(60*60) # Sticker them. for cmt in comments: self.api_post('/api/sticker/comment', {'type_id': '1', 'comment_id': cmt.id}, user=create_user()) Services.time.step(60*60) cmt.update_score() def merge_scores(): for category in [Category.ALL] + list(Category.objects.all()): category.merge_top_scores() merge_scores() def get_email_message(): user = create_user() pn = Actions.digest(user) notification = Notification.from_pending_notification(pn, user, "EmailChannel") return EmailChannel().make_message(notification, force=True) email_message = get_email_message() for cmt in comments: self.assertTrue(cmt.get_absolute_url() in email_message.body_html) # Wait a couple months, and make sure the comments disappear (so we're only showing top of the month, # not top of the year). Services.time.step(60*60*24*30*2) for cmt in comments: cmt.update_score() merge_scores() email_message = get_email_message() for cmt in comments: self.assertFalse(cmt.get_absolute_url() in email_message.body_html)
def test_user_with_user(self): request = FakeRequest(user=create_user()) response = self.require_user(request) self.assertEqual(response.status_code, 200)
def after_setUp(self): # Create a bunch of comments for i in range(1, 10): create_comment(author=create_user()) self.comments = Comment.all_objects.all()
def test_200_logged_in_frontpage(self): self.assertStatus(200, '/', user=create_user())
def test_staff_gets_staff_branch(self): staff_request = FakeRequest(create_user(staff=True)) self.assertTrue( staff_request.experiments.is_in('forced_into_control', 'experimental'))
def test_url_stripping_user(self): username = create_user().username response = self.get_client().get('/user/%s/' % username) self.assertRedirects(response, '/user/%s' % username)
def test_staff_can_be_forced_into_experiment(self): request = FakeRequest(create_user(staff=True)) force_into_branch(request, "forced_into_experimental", "control") self.assertTrue( request.experiments.is_in("forced_into_experimental", "control"))
def test_used(self): email = '*****@*****.**' self.signup(email=email) dupe = create_user(email=email) self.assertFalse(User.email_is_unused(email))
def test_api_does_not_record_view_metric(self): self.assertViewCount(FakeRequest(create_user(), path="/api/do_stuff"), HttpResponse(status=200), 0)
def before_tearDown(self): self.user = create_user()
def test_overridden_unpurchasable(self): sticker = stickers.Sticker(31337, 'test', cost=1, purchasable=False) self.assertFalse(sticker.is_purchasable(create_user()))
def test_rate_limit_exceeded(self): self._test_rate_limit(create_user(), False)