def test_thread_is_reindexed_on_username_change(self): search = ThreadMappingType.search() u = UserFactory(username="******") ThreadFactory(creator=u, title="Hello") self.refresh() eq_(search.query(post_title="hello")[0]["post_author_ord"], ["dexter"]) # Change the username and verify the index. u.username = "******" u.save() self.refresh() eq_(search.query(post_title="hello")[0]["post_author_ord"], ["walter"])
def test_inactive_user(self): """ An inactive user cannot access the AAQ flow """ user = UserFactory(is_superuser=False) self.client.login(username=user.username, password="******") # After log in, set user to inactive user.is_active = False user.save() url = reverse("questions.aaq_step1") response = self.client.get(url, follow=True) assert not template_used(response, "questions/new_question.html")
def test_thread_is_reindexed_on_username_change(self): search = ThreadMappingType.search() u = UserFactory(username='******') ThreadFactory(creator=u, title='Hello') self.refresh() eq_(search.query(post_title='hello')[0]['post_author_ord'], ['dexter']) # Change the username and verify the index. u.username = '******' u.save() self.refresh() eq_(search.query(post_title='hello')[0]['post_author_ord'], ['walter'])
def test_thread_is_reindexed_on_username_change(self): search = ThreadMappingType.search() u = UserFactory(username='******') ThreadFactory(creator=u, title=u'Hello') self.refresh() eq_(search.query(post_title='hello')[0]['post_author_ord'], [u'dexter']) # Change the username and verify the index. u.username = '******' u.save() self.refresh() eq_(search.query(post_title='hello')[0]['post_author_ord'], [u'walter'])
def test_deactivate_button(self): """Check that the deactivate button is shown appropriately""" u = UserFactory() r = self.client.get(reverse('users.profile', args=[u.username])) assert 'Deactivate this user' not in r.content add_permission(self.u, Profile, 'deactivate_users') self.client.login(username=self.u.username, password='******') r = self.client.get(reverse('users.profile', args=[u.username])) assert 'Deactivate this user' in r.content u.is_active = False u.save() r = self.client.get(reverse('users.profile', args=[u.username])) assert 'This user has been deactivated.' in r.content r = self.client.get(reverse('users.profile', args=[self.u.username])) assert 'Deactivate this user' not in r.content
def test_aaq_new_question_inactive(self, get_current): """New question is posted through mobile.""" get_current.return_value.domain = 'testserver' # Log in first. u = UserFactory() self.client.login(username=u.username, password='******') # Then become inactive. u.is_active = False u.save() # Set 'in-aaq' for the session. It isn't already set because this # test doesn't do a GET of the form first. s = self.client.session s['in-aaq'] = True s.save() response = self._new_question(post_it=True) eq_(200, response.status_code) assert template_used(response, 'questions/mobile/confirm_email.html')
def test_questions_inactive_user(self): """Verify questions from inactive users aren't counted.""" # Two questions for an inactive user. # They shouldn't show up in the count. u = UserFactory(is_active=False) QuestionFactory(creator=u) QuestionFactory(creator=u) r = self._get_api_result('api.kpi.questions') eq_(len(r['objects']), 0) # Activate the user, now the questions should count. u.is_active = True u.save() cache.clear() # We need to clear the cache for new results. url = reverse('api.kpi.questions') response = self.client.get(url + '?format=json') eq_(200, response.status_code) r = json.loads(response.content) eq_(r['objects'][0]['questions'], 2)
def test_question_is_reindexed_on_username_change(self): search = QuestionMappingType.search() u = UserFactory(username='******') QuestionFactory(creator=u, title='Hello') AnswerFactory(creator=u, content='I love you') self.refresh() eq_(search.query(question_title__match='hello')[0]['question_creator'], 'dexter') query = search.query(question_answer_content__match='love') eq_(query[0]['question_answer_creator'], ['dexter']) # Change the username and verify the index. u.username = '******' u.save() self.refresh() eq_(search.query(question_title__match='hello')[0]['question_creator'], 'walter') query = search.query(question_answer_content__match='love') eq_(query[0]['question_answer_creator'], ['walter'])
def test_question_is_reindexed_on_username_change(self): search = QuestionMappingType.search() u = UserFactory(username='******') QuestionFactory(creator=u, title=u'Hello') AnswerFactory(creator=u, content=u'I love you') self.refresh() eq_(search.query(question_title__match='hello')[0]['question_creator'], u'dexter') query = search.query(question_answer_content__match='love') eq_(query[0]['question_answer_creator'], [u'dexter']) # Change the username and verify the index. u.username = '******' u.save() self.refresh() eq_(search.query(question_title__match='hello')[0]['question_creator'], u'walter') query = search.query(question_answer_content__match='love') eq_(query[0]['question_answer_creator'], [u'walter'])
def test_question_is_reindexed_on_username_change(self): search = QuestionMappingType.search() u = UserFactory(username="******") QuestionFactory(creator=u, title="Hello") AnswerFactory(creator=u, content="I love you") self.refresh() eq_( search.query(question_title__match="hello")[0]["question_creator"], "dexter") query = search.query(question_answer_content__match="love") eq_(query[0]["question_answer_creator"], ["dexter"]) # Change the username and verify the index. u.username = "******" u.save() self.refresh() eq_( search.query(question_title__match="hello")[0]["question_creator"], "walter") query = search.query(question_answer_content__match="love") eq_(query[0]["question_answer_creator"], ["walter"])
class PasswordResetTests(TestCaseBase): def setUp(self): super(PasswordResetTests, self).setUp() self.u = UserFactory(email="*****@*****.**") self.uidb36 = int_to_base36(self.u.id) self.token = default_token_generator.make_token(self.u) self.orig_debug = settings.DEBUG settings.DEBUG = True def tearDown(self): super(PasswordResetTests, self).tearDown() settings.DEBUG = self.orig_debug def test_bad_email(self): r = self.client.post(reverse('users.pw_reset'), {'email': '*****@*****.**'}) eq_(302, r.status_code) eq_('http://testserver/en-US/users/pwresetsent', r['location']) eq_(0, len(mail.outbox)) @mock.patch.object(Site.objects, 'get_current') def test_success(self, get_current): get_current.return_value.domain = 'testserver.com' r = self.client.post(reverse('users.pw_reset'), {'email': self.u.email}) eq_(302, r.status_code) eq_('http://testserver/en-US/users/pwresetsent', r['location']) eq_(1, len(mail.outbox)) assert mail.outbox[0].subject.find('Password reset') == 0 assert mail.outbox[0].body.find('pwreset/%s' % self.uidb36) > 0 @mock.patch.object(PasswordResetForm, 'save') def test_smtp_error(self, pwform_save): def raise_smtp(*a, **kw): raise SMTPRecipientsRefused(recipients=[self.u.email]) pwform_save.side_effect = raise_smtp r = self.client.post(reverse('users.pw_reset'), {'email': self.u.email}) self.assertContains(r, unicode(ERROR_SEND_EMAIL)) def _get_reset_url(self): return reverse('users.pw_reset_confirm', args=[self.uidb36, self.token]) def test_bad_reset_url(self): r = self.client.get('/users/pwreset/junk/', follow=True) eq_(r.status_code, 404) r = self.client.get(reverse('users.pw_reset_confirm', args=[self.uidb36, '12-345'])) eq_(200, r.status_code) doc = pq(r.content) eq_('Password reset unsuccessful', doc('article h1').text()) def test_reset_fail(self): url = self._get_reset_url() r = self.client.post(url, {'new_password1': '', 'new_password2': ''}) eq_(200, r.status_code) doc = pq(r.content) eq_(1, len(doc('ul.errorlist'))) r = self.client.post(url, {'new_password1': 'onetwo12', 'new_password2': 'twotwo22'}) eq_(200, r.status_code) doc = pq(r.content) eq_("The two password fields didn't match.", doc('ul.errorlist li').text()) def test_reset_success(self): url = self._get_reset_url() new_pw = 'fjdka387fvstrongpassword!' assert self.u.check_password(new_pw) is False r = self.client.post(url, {'new_password1': new_pw, 'new_password2': new_pw}) eq_(302, r.status_code) eq_('http://testserver/en-US/users/pwresetcomplete', r['location']) self.u = User.objects.get(username=self.u.username) assert self.u.check_password(new_pw) def test_reset_user_with_unusable_password(self): """Verify that user's with unusable passwords can reset them.""" self.u.set_unusable_password() self.u.save() self.test_success()
class LoginTests(TestCaseBase): """Login tests.""" def setUp(self): super(LoginTests, self).setUp() self.u = UserFactory() self.profile_url = reverse('users.profile', args=[self.u.username], locale=settings.LANGUAGE_CODE) + '?fpa=1' def test_login_bad_password(self): '''Test login with a good username and bad password.''' response = post(self.client, 'users.login', { 'username': self.u.username, 'password': '******' }) eq_(200, response.status_code) doc = pq(response.content) eq_( 'Please enter a correct username and password. Note that both ' 'fields are case-sensitive.', doc('ul.errorlist li').text()) def test_login_bad_username(self): '''Test login with a bad username.''' response = post(self.client, 'users.login', { 'username': '******', 'password': '******' }) eq_(200, response.status_code) doc = pq(response.content) eq_( 'Please enter a correct username and password. Note that both ' 'fields are case-sensitive.', doc('ul.errorlist li').text()) def test_login_password_disabled(self): """Test logging in as a user with PASSWORD_DISABLED doesn't 500.""" self.u.set_unusable_password() self.u.save() response = self.client.post(reverse('users.login'), { 'username': self.u.username, 'password': '******' }) eq_(200, response.status_code) def test_login(self): '''Test a valid login.''' response = self.client.post(reverse('users.login'), { 'username': self.u.username, 'password': '******' }) eq_(302, response.status_code) eq_(self.profile_url, response['location']) def test_login_next_parameter(self): '''Test with a valid ?next=url parameter.''' next = self.profile_url # Verify that next parameter is set in form hidden field. response = self.client.get(urlparams(reverse('users.login'), next=next), follow=True) eq_(200, response.status_code) doc = pq(response.content) eq_(next, doc('#login input[name="next"]')[0].attrib['value']) # Verify that it gets used on form POST. response = self.client.post(reverse('users.login'), { 'username': self.u.username, 'password': '******', 'next': next }) eq_(302, response.status_code) eq_(next, response['location']) def test_login_invalid_next_parameter(self): '''Test with an invalid ?next=http://example.com parameter.''' invalid_next = 'http://foobar.com/evil/' valid_next = reverse('home', locale=settings.LANGUAGE_CODE) # Verify that _valid_ next parameter is set in form hidden field. url = urlparams(reverse('users.login'), next=invalid_next) response = self.client.get(url, follow=True) eq_(200, response.status_code) doc = pq(response.content) eq_(valid_next, doc('#login input[name="next"]')[0].attrib['value']) # Verify that it gets used on form POST. response = self.client.post( reverse('users.login'), { 'username': self.u.username, 'password': '******', 'next': invalid_next }) eq_(302, response.status_code) eq_(self.profile_url, response['location']) def test_fxa_deprecation_warning(self): """ Test that a SUMO login shows FXA deprecation warning """ response = self.client.post(reverse('users.login'), { 'username': self.u.username, 'password': '******' }, follow=True) doc = pq(response.content) eq_(1, len(doc('#fxa-notification-deprecated')))
class ProfileDocumentSignalsTests(Elastic7TestCase): def setUp(self): self.user = UserFactory() self.user_id = self.user.id def get_doc(self): return ProfileDocument.get(self.user_id) def test_user_save(self): self.user.username = "******" self.user.save() self.assertEqual(self.get_doc().username, "jdoe") def test_profile_save(self): profile = self.user.profile profile.locale = "foobar" profile.save() self.assertEqual(self.get_doc().locale, "foobar") def test_user_groups_change(self): group = GroupFactory() self.user.groups.add(group) self.assertIn(group.id, self.get_doc().group_ids) self.user.groups.remove(group) self.assertNotIn(group.id, self.get_doc().group_ids) def test_user_products_change(self): profile = self.user.profile product = ProductFactory() profile.products.add(product) self.assertIn(product.id, self.get_doc().product_ids) profile.products.remove(product) self.assertNotIn(product.id, self.get_doc().product_ids) def test_user_delete(self): self.user.delete() with self.assertRaises(NotFoundError): self.get_doc() def test_profile_delete(self): self.user.profile.delete() with self.assertRaises(NotFoundError): self.get_doc() def test_group_delete(self): group = GroupFactory() self.user.groups.add(group) group.delete() self.assertEqual(self.get_doc().group_ids, []) def test_product_delete(self): profile = self.user.profile product = ProductFactory() profile.products.add(product) product.delete() self.assertEqual(self.get_doc().product_ids, [])
class ChangeEmailTestCase(TestCase): client_class = LocalizingClient def setUp(self): self.user = UserFactory() self.client.login(username=self.user.username, password='******') super(ChangeEmailTestCase, self).setUp() def test_redirect(self): """Test our redirect from old url to new one.""" response = self.client.get(reverse('users.old_change_email', locale='en-US'), follow=False) eq_(301, response.status_code) eq_('http://testserver/en-US/users/change_email', response['location']) @mock.patch.object(Site.objects, 'get_current') def test_user_change_email(self, get_current): """Send email to change user's email and then change it.""" get_current.return_value.domain = 'su.mo.com' # Attempt to change email. response = self.client.post(reverse('users.change_email'), {'email': '*****@*****.**'}, follow=True) eq_(200, response.status_code) # Be notified to click a confirmation link. eq_(1, len(mail.outbox)) assert mail.outbox[0].subject.find('Please confirm your') == 0 ec = EmailChange.objects.all()[0] assert ec.activation_key in mail.outbox[0].body eq_('*****@*****.**', ec.email) # Visit confirmation link to change email. response = self.client.get(reverse('users.confirm_email', args=[ec.activation_key])) eq_(200, response.status_code) u = User.objects.get(username=self.user.username) eq_('*****@*****.**', u.email) def test_user_change_email_same(self): """Changing to same email shows validation error.""" self.user.email = '*****@*****.**' self.user.save() response = self.client.post(reverse('users.change_email'), {'email': self.user.email}) eq_(200, response.status_code) doc = pq(response.content) eq_('This is your current email.', doc('ul.errorlist').text()) def test_user_change_email_duplicate(self): """Changing to same email shows validation error.""" u = UserFactory(email='*****@*****.**') response = self.client.post(reverse('users.change_email'), {'email': u.email}) eq_(200, response.status_code) doc = pq(response.content) eq_('A user with that email address already exists.', doc('ul.errorlist').text()) @mock.patch.object(Site.objects, 'get_current') def test_user_confirm_email_duplicate(self, get_current): """If we detect a duplicate email when confirming an email change, don't change it and notify the user.""" get_current.return_value.domain = 'su.mo.com' old_email = self.user.email new_email = '*****@*****.**' response = self.client.post(reverse('users.change_email'), {'email': new_email}) eq_(200, response.status_code) assert mail.outbox[0].subject.find('Please confirm your') == 0 ec = EmailChange.objects.all()[0] # Before new email is confirmed, give the same email to a user u = UserFactory(email=new_email) # Visit confirmation link and verify email wasn't changed. response = self.client.get(reverse('users.confirm_email', args=[ec.activation_key])) eq_(200, response.status_code) doc = pq(response.content) eq_(u'Unable to change email for user %s' % self.user.username, doc('article h1').text()) u = User.objects.get(username=self.user.username) eq_(old_email, u.email)
class UserProfileTests(TestCase): def setUp(self): self.user = UserFactory() self.profile = self.user.profile self.userrl = reverse('users.profile', args=[self.user.username], locale='en-US') super(UserProfileTests, self).setUp() def test_ProfileFactory(self): res = self.client.get(self.userrl) self.assertContains(res, self.user.username) def test_profile_redirect(self): """Ensure that old profile URL's get redirected.""" res = self.client.get(reverse('users.profile', args=[self.user.pk], locale='en-US')) eq_(302, res.status_code) def test_profile_inactive(self): """Inactive users don't have a public profile.""" self.user.is_active = False self.user.save() res = self.client.get(self.userrl) eq_(404, res.status_code) def test_profile_post(self): res = self.client.post(self.userrl) eq_(405, res.status_code) def test_profile_deactivate(self): """Test user deactivation""" p = UserFactory().profile self.client.login(username=self.user.username, password='******') res = self.client.post(reverse('users.deactivate', locale='en-US'), {'user_id': p.user.id}) eq_(403, res.status_code) add_permission(self.user, Profile, 'deactivate_users') res = self.client.post(reverse('users.deactivate', locale='en-US'), {'user_id': p.user.id}) eq_(302, res.status_code) log = Deactivation.objects.get(user_id=p.user_id) eq_(log.moderator_id, self.user.id) p = Profile.objects.get(user_id=p.user_id) assert not p.user.is_active def test_deactivate_and_flag_spam(self): self.client.login(username=self.user.username, password='******') add_permission(self.user, Profile, 'deactivate_users') # Verify content is flagged as spam when requested. u = UserFactory() AnswerFactory(creator=u) QuestionFactory(creator=u) url = reverse('users.deactivate-spam', locale='en-US') res = self.client.post(url, {'user_id': u.id}) eq_(302, res.status_code) eq_(1, Question.objects.filter(creator=u, is_spam=True).count()) eq_(0, Question.objects.filter(creator=u, is_spam=False).count()) eq_(1, Answer.objects.filter(creator=u, is_spam=True).count()) eq_(0, Answer.objects.filter(creator=u, is_spam=False).count())
class LoginTests(TestCaseBase): """Login tests.""" def setUp(self): super(LoginTests, self).setUp() self.u = UserFactory() def test_login_bad_password(self): '''Test login with a good username and bad password.''' response = post(self.client, 'users.login', { 'username': self.u.username, 'password': '******' }) eq_(200, response.status_code) doc = pq(response.content) eq_( 'Please enter a correct username and password. Note that both ' 'fields are case-sensitive.', doc('ul.errorlist li').text()) def test_login_bad_username(self): '''Test login with a bad username.''' response = post(self.client, 'users.login', { 'username': '******', 'password': '******' }) eq_(200, response.status_code) doc = pq(response.content) eq_( 'Please enter a correct username and password. Note that both ' 'fields are case-sensitive.', doc('ul.errorlist li').text()) def test_login_password_disabled(self): """Test logging in as a user with PASSWORD_DISABLED doesn't 500.""" self.u.set_unusable_password() self.u.save() response = self.client.post(reverse('users.login'), { 'username': self.u.username, 'password': '******' }) eq_(200, response.status_code) def test_login(self): '''Test a valid login.''' response = self.client.post(reverse('users.login'), { 'username': self.u.username, 'password': '******' }) eq_(302, response.status_code) eq_( reverse('home', locale=settings.LANGUAGE_CODE) + '?fpa=1', response['location']) def test_login_next_parameter(self): '''Test with a valid ?next=url parameter.''' next = '/kb/new' # Verify that next parameter is set in form hidden field. response = self.client.get(urlparams(reverse('users.login'), next=next), follow=True) eq_(200, response.status_code) doc = pq(response.content) eq_(next, doc('#login input[name="next"]')[0].attrib['value']) # Verify that it gets used on form POST. response = self.client.post(reverse('users.login'), { 'username': self.u.username, 'password': '******', 'next': next }) eq_(302, response.status_code) eq_(next + '?fpa=1', response['location']) def test_login_invalid_next_parameter(self): '''Test with an invalid ?next=http://example.com parameter.''' invalid_next = 'http://foobar.com/evil/' valid_next = reverse('home', locale=settings.LANGUAGE_CODE) # Verify that _valid_ next parameter is set in form hidden field. url = urlparams(reverse('users.login'), next=invalid_next) response = self.client.get(url, follow=True) eq_(200, response.status_code) doc = pq(response.content) eq_(valid_next, doc('#login input[name="next"]')[0].attrib['value']) # Verify that it gets used on form POST. response = self.client.post( reverse('users.login'), { 'username': self.u.username, 'password': '******', 'next': invalid_next }) eq_(302, response.status_code) eq_(valid_next + '?fpa=1', response['location']) def test_login_mobile_csrf(self): """The mobile login view should have a CSRF token.""" response = self.client.get(reverse('users.login'), {'mobile': 1}) eq_(200, response.status_code) doc = pq(response.content) assert doc('#content form input[name="csrfmiddlewaretoken"]')
class PasswordResetTests(TestCaseBase): def setUp(self): super(PasswordResetTests, self).setUp() self.u = UserFactory(email="*****@*****.**") self.uidb36 = int_to_base36(self.u.id) self.token = default_token_generator.make_token(self.u) def test_bad_email(self): r = self.client.post(reverse('users.pw_reset'), {'email': '*****@*****.**'}) eq_(302, r.status_code) eq_('/en-US/users/pwresetsent', r['location']) eq_(0, len(mail.outbox)) def test_success(self): r = self.client.post(reverse('users.pw_reset'), {'email': self.u.email}) eq_(302, r.status_code) eq_('/en-US/users/pwresetsent', r['location']) eq_(1, len(mail.outbox)) assert mail.outbox[0].subject.find('Password reset') == 0 assert mail.outbox[0].body.find('pwreset/%s' % self.uidb36) > 0 @mock.patch.object(PasswordResetForm, 'save') def test_smtp_error(self, pwform_save): def raise_smtp(*a, **kw): raise SMTPRecipientsRefused(recipients=[self.u.email]) pwform_save.side_effect = raise_smtp r = self.client.post(reverse('users.pw_reset'), {'email': self.u.email}) self.assertContains(r, unicode(ERROR_SEND_EMAIL)) def _get_reset_url(self): return reverse('users.pw_reset_confirm', args=[self.uidb36, self.token]) def test_bad_reset_url(self): r = self.client.get('/users/pwreset/junk/', follow=True) eq_(r.status_code, 404) r = self.client.get( reverse('users.pw_reset_confirm', args=[self.uidb36, '12-345'])) eq_(200, r.status_code) doc = pq(r.content) eq_('Password reset unsuccessful', doc('article h1').text()) def test_reset_fail(self): url = self._get_reset_url() r = self.client.post(url, {'new_password1': '', 'new_password2': ''}) eq_(200, r.status_code) doc = pq(r.content) eq_(1, len(doc('ul.errorlist'))) r = self.client.post(url, { 'new_password1': 'onetwo12', 'new_password2': 'twotwo22' }) eq_(200, r.status_code) doc = pq(r.content) eq_("The two password fields didn't match.", doc('ul.errorlist li').text()) def test_reset_success(self): url = self._get_reset_url() new_pw = 'fjdka387fvstrongpassword!' assert self.u.check_password(new_pw) is False r = self.client.post(url, { 'new_password1': new_pw, 'new_password2': new_pw }) eq_(302, r.status_code) eq_('/en-US/users/pwresetcomplete', r['location']) self.u = User.objects.get(username=self.u.username) assert self.u.check_password(new_pw) def test_reset_user_with_unusable_password(self): """Verify that user's with unusable passwords can reset them.""" self.u.set_unusable_password() self.u.save() self.test_success()
class HelperTestCase(TestCase): def setUp(self): super(HelperTestCase, self).setUp() self.u = UserFactory() def test_profile_url(self): eq_(u'/user/%s' % self.u.username, profile_url(self.u)) def test_profile_avatar_default(self): email_hash = hashlib.md5(self.u.email.lower()).hexdigest() gravatar_url = 'https://secure.gravatar.com/avatar/%s?s=48' % ( email_hash) assert profile_avatar(self.u).startswith(gravatar_url) def test_profile_avatar_anonymous(self): email_hash = '00000000000000000000000000000000' gravatar_url = 'https://secure.gravatar.com/avatar/%s?s=48' % ( email_hash) assert profile_avatar(AnonymousUser()).startswith(gravatar_url) def test_profile_avatar(self): self.u.profile.avatar = 'images/foo.png' self.u.profile.save() email_hash = hashlib.md5(self.u.email.lower()).hexdigest() gravatar_url = 'https://secure.gravatar.com/avatar/%s?s=48' % ( email_hash) assert profile_avatar(self.u).startswith(gravatar_url) def test_profile_avatar_unicode(self): self.u.email = u'rá[email protected]' self.u.save() gravatar_url = 'https://secure.gravatar.com/' assert profile_avatar(self.u).startswith(gravatar_url) def test_public_email(self): eq_(u'<span class="email">' u'me@domain.c' u'om</span>', public_email('*****@*****.**')) eq_(u'<span class="email">' u'not.an.emai' u'l</span>', public_email('not.an.email')) def test_display_name(self): eq_(self.u.profile.name, display_name(self.u)) self.u.profile.name = u'Test User' self.u.profile.save() eq_(u'Test User', display_name(self.u)) def test_display_name_anonymous(self): eq_(u'', display_name(AnonymousUser())) def test_user_list(self): UserFactory(username='******') UserFactory(username='******') users = User.objects.all() list = user_list(users) assert isinstance(list, Markup) fragment = pq(list) eq_(len(users), len(fragment('a'))) a = fragment('a')[1] assert a.attrib['href'].endswith(str(users[1].username)) eq_(users[1].username, a.text)
class HelperTestCase(TestCase): def setUp(self): super(HelperTestCase, self).setUp() self.u = UserFactory() def test_profile_url(self): eq_(u"/user/%s" % self.u.username, profile_url(self.u)) def test_profile_avatar_default(self): email_hash = hashlib.md5(self.u.email.lower()).hexdigest() gravatar_url = "https://secure.gravatar.com/avatar/%s?s=48" % (email_hash) assert profile_avatar(self.u).startswith(gravatar_url) def test_profile_avatar_anonymous(self): email_hash = "00000000000000000000000000000000" gravatar_url = "https://secure.gravatar.com/avatar/%s?s=48" % (email_hash) assert profile_avatar(AnonymousUser()).startswith(gravatar_url) def test_profile_avatar(self): self.u.profile.avatar = "images/foo.png" self.u.profile.save() email_hash = hashlib.md5(self.u.email.lower()).hexdigest() gravatar_url = "https://secure.gravatar.com/avatar/%s?s=48" % (email_hash) assert profile_avatar(self.u).startswith(gravatar_url) def test_profile_avatar_unicode(self): self.u.email = u"rá[email protected]" self.u.save() gravatar_url = "https://secure.gravatar.com/" assert profile_avatar(self.u).startswith(gravatar_url) def test_public_email(self): eq_( u'<span class="email">' u"me@domain.c" u"om</span>", public_email("*****@*****.**"), ) eq_( u'<span class="email">' u"not.an.emai" u"l</span>", public_email("not.an.email"), ) def test_display_name(self): eq_(self.u.profile.name, display_name(self.u)) self.u.profile.name = u"Test User" self.u.profile.save() eq_(u"Test User", display_name(self.u)) def test_display_name_anonymous(self): eq_(u"", display_name(AnonymousUser())) def test_user_list(self): UserFactory(username="******") UserFactory(username="******") users = User.objects.all() list = user_list(users) assert isinstance(list, Markup) fragment = pq(list) eq_(len(users), len(fragment("a"))) a = fragment("a")[1] assert a.attrib["href"].endswith(str(users[1].username)) eq_(users[1].username, a.text)
class LoginTests(TestCaseBase): """Login tests.""" def setUp(self): super(LoginTests, self).setUp() self.u = UserFactory() def test_login_bad_password(self): '''Test login with a good username and bad password.''' response = post(self.client, 'users.login', { 'username': self.u.username, 'password': '******' }) eq_(200, response.status_code) doc = pq(response.content) eq_( 'Please enter a correct username and password. Note that both ' 'fields are case-sensitive.', doc('ul.errorlist li').text()) def test_login_bad_username(self): '''Test login with a bad username.''' response = post(self.client, 'users.login', { 'username': '******', 'password': '******' }) eq_(200, response.status_code) doc = pq(response.content) eq_( 'Please enter a correct username and password. Note that both ' 'fields are case-sensitive.', doc('ul.errorlist li').text()) def test_login_password_disabled(self): """Test logging in as a user with PASSWORD_DISABLED doesn't 500.""" self.u.set_unusable_password() self.u.save() response = self.client.post(reverse('users.login'), { 'username': self.u.username, 'password': '******' }) eq_(200, response.status_code) def test_login(self): '''Test a valid login.''' response = self.client.post(reverse('users.login'), { 'username': self.u.username, 'password': '******' }) eq_(302, response.status_code) eq_( 'http://testserver' + reverse('home', locale=settings.LANGUAGE_CODE) + '?fpa=1', response['location']) def test_login_next_parameter(self): '''Test with a valid ?next=url parameter.''' next = '/kb/new' # Verify that next parameter is set in form hidden field. response = self.client.get(urlparams(reverse('users.login'), next=next), follow=True) eq_(200, response.status_code) doc = pq(response.content) eq_(next, doc('#login input[name="next"]')[0].attrib['value']) # Verify that it gets used on form POST. response = self.client.post(reverse('users.login'), { 'username': self.u.username, 'password': '******', 'next': next }) eq_(302, response.status_code) eq_('http://testserver' + next + '?fpa=1', response['location']) @mock.patch.object(Site.objects, 'get_current') def test_login_invalid_next_parameter(self, get_current): '''Test with an invalid ?next=http://example.com parameter.''' get_current.return_value.domain = 'testserver.com' invalid_next = 'http://foobar.com/evil/' valid_next = reverse('home', locale=settings.LANGUAGE_CODE) # Verify that _valid_ next parameter is set in form hidden field. url = urlparams(reverse('users.login'), next=invalid_next) response = self.client.get(url, follow=True) eq_(200, response.status_code) doc = pq(response.content) eq_(valid_next, doc('#login input[name="next"]')[0].attrib['value']) # Verify that it gets used on form POST. response = self.client.post( reverse('users.login'), { 'username': self.u.username, 'password': '******', 'next': invalid_next }) eq_(302, response.status_code) eq_('http://testserver' + valid_next + '?fpa=1', response['location']) def test_ga_custom_variable_on_registered_login(self): """After logging in, there should be a ga-push data attr on body.""" user_ = UserFactory() # User should be "Registered": response = self.client.post(reverse('users.login'), { 'username': user_.username, 'password': '******' }, follow=True) eq_(200, response.status_code) doc = pq(response.content) assert '"Registered"' in doc('body').attr('data-ga-push') def test_ga_custom_variable_on_contributor_login(self): """After logging in, there should be a ga-push data attr on body.""" user_ = UserFactory() # Add user to Contributors and so should be "Contributor": user_.groups.add(GroupFactory(name='Contributors')) response = self.client.post(reverse('users.login'), { 'username': user_.username, 'password': '******' }, follow=True) eq_(200, response.status_code) doc = pq(response.content) assert '"Contributor"' in doc('body').attr('data-ga-push') def test_ga_custom_variable_on_admin_login(self): """After logging in, there should be a ga-push data attr on body.""" user_ = UserFactory() # Add user to Administrators and so should be "Contributor - Admin": user_.groups.add(GroupFactory(name='Administrators')) response = self.client.post(reverse('users.login'), { 'username': user_.username, 'password': '******' }, follow=True) eq_(200, response.status_code) doc = pq(response.content) assert '"Contributor - Admin"' in doc('body').attr('data-ga-push') def test_login_mobile_csrf(self): """The mobile login view should have a CSRF token.""" response = self.client.get(reverse('users.login'), {'mobile': 1}) eq_(200, response.status_code) doc = pq(response.content) assert doc('#content form input[name="csrfmiddlewaretoken"]')
class LoginTests(TestCaseBase): """Login tests.""" def setUp(self): super(LoginTests, self).setUp() self.u = UserFactory() def test_login_bad_password(self): '''Test login with a good username and bad password.''' response = post(self.client, 'users.login', {'username': self.u.username, 'password': '******'}) eq_(200, response.status_code) doc = pq(response.content) eq_('Please enter a correct username and password. Note that both ' 'fields are case-sensitive.', doc('ul.errorlist li').text()) def test_login_bad_username(self): '''Test login with a bad username.''' response = post(self.client, 'users.login', {'username': '******', 'password': '******'}) eq_(200, response.status_code) doc = pq(response.content) eq_('Please enter a correct username and password. Note that both ' 'fields are case-sensitive.', doc('ul.errorlist li').text()) def test_login_password_disabled(self): """Test logging in as a user with PASSWORD_DISABLED doesn't 500.""" self.u.set_unusable_password() self.u.save() response = self.client.post(reverse('users.login'), {'username': self.u.username, 'password': '******'}) eq_(200, response.status_code) def test_login(self): '''Test a valid login.''' response = self.client.post(reverse('users.login'), {'username': self.u.username, 'password': '******'}) eq_(302, response.status_code) eq_(reverse('home', locale=settings.LANGUAGE_CODE) + '?fpa=1', response['location']) def test_login_next_parameter(self): '''Test with a valid ?next=url parameter.''' next = '/kb/new' # Verify that next parameter is set in form hidden field. response = self.client.get( urlparams(reverse('users.login'), next=next), follow=True) eq_(200, response.status_code) doc = pq(response.content) eq_(next, doc('#login input[name="next"]')[0].attrib['value']) # Verify that it gets used on form POST. response = self.client.post(reverse('users.login'), {'username': self.u.username, 'password': '******', 'next': next}) eq_(302, response.status_code) eq_(next + '?fpa=1', response['location']) def test_login_invalid_next_parameter(self): '''Test with an invalid ?next=http://example.com parameter.''' invalid_next = 'http://foobar.com/evil/' valid_next = reverse('home', locale=settings.LANGUAGE_CODE) # Verify that _valid_ next parameter is set in form hidden field. url = urlparams(reverse('users.login'), next=invalid_next) response = self.client.get(url, follow=True) eq_(200, response.status_code) doc = pq(response.content) eq_(valid_next, doc('#login input[name="next"]')[0].attrib['value']) # Verify that it gets used on form POST. response = self.client.post(reverse('users.login'), {'username': self.u.username, 'password': '******', 'next': invalid_next}) eq_(302, response.status_code) eq_(valid_next + '?fpa=1', response['location']) def test_login_mobile_csrf(self): """The mobile login view should have a CSRF token.""" response = self.client.get(reverse('users.login'), {'mobile': 1}) eq_(200, response.status_code) doc = pq(response.content) assert doc('#content form input[name="csrfmiddlewaretoken"]')
class HelperTestCase(TestCase): def setUp(self): super(HelperTestCase, self).setUp() self.u = UserFactory() def test_profile_url(self): eq_(u'/user/%s' % self.u.username, profile_url(self.u)) def test_profile_avatar_default(self): email_hash = hashlib.md5(self.u.email.lower()).hexdigest() gravatar_url = 'https://secure.gravatar.com/avatar/%s?s=48' % ( email_hash) assert profile_avatar(self.u).startswith(gravatar_url) def test_profile_avatar_anonymous(self): email_hash = '00000000000000000000000000000000' gravatar_url = 'https://secure.gravatar.com/avatar/%s?s=48' % ( email_hash) assert profile_avatar(AnonymousUser()).startswith(gravatar_url) def test_profile_avatar(self): self.u.profile.avatar = 'images/foo.png' self.u.profile.save() email_hash = hashlib.md5(self.u.email.lower()).hexdigest() gravatar_url = 'https://secure.gravatar.com/avatar/%s?s=48' % ( email_hash) assert profile_avatar(self.u).startswith(gravatar_url) def test_profile_avatar_unicode(self): self.u.email = u'rá[email protected]' self.u.save() gravatar_url = 'https://secure.gravatar.com/' assert profile_avatar(self.u).startswith(gravatar_url) def test_public_email(self): eq_( u'<span class="email">' u'me@domain.c' u'om</span>', public_email('*****@*****.**')) eq_( u'<span class="email">' u'not.an.emai' u'l</span>', public_email('not.an.email')) def test_display_name(self): eq_(self.u.profile.name, display_name(self.u)) self.u.profile.name = u'Test User' self.u.profile.save() eq_(u'Test User', display_name(self.u)) def test_display_name_anonymous(self): eq_(u'', display_name(AnonymousUser())) def test_user_list(self): UserFactory(username='******') UserFactory(username='******') users = User.objects.all() list = user_list(users) assert isinstance(list, Markup) fragment = pq(list) eq_(len(users), len(fragment('a'))) a = fragment('a')[1] assert a.attrib['href'].endswith(str(users[1].username)) eq_(users[1].username, a.text)
class LoginTests(TestCaseBase): """Login tests.""" def setUp(self): super(LoginTests, self).setUp() self.u = UserFactory() def test_login_bad_password(self): '''Test login with a good username and bad password.''' response = post(self.client, 'users.login', {'username': self.u.username, 'password': '******'}) eq_(200, response.status_code) doc = pq(response.content) eq_('Please enter a correct username and password. Note that both ' 'fields are case-sensitive.', doc('ul.errorlist li').text()) def test_login_bad_username(self): '''Test login with a bad username.''' response = post(self.client, 'users.login', {'username': '******', 'password': '******'}) eq_(200, response.status_code) doc = pq(response.content) eq_('Please enter a correct username and password. Note that both ' 'fields are case-sensitive.', doc('ul.errorlist li').text()) def test_login_password_disabled(self): """Test logging in as a user with PASSWORD_DISABLED doesn't 500.""" self.u.set_unusable_password() self.u.save() response = self.client.post(reverse('users.login'), {'username': self.u.username, 'password': '******'}) eq_(200, response.status_code) def test_login(self): '''Test a valid login.''' response = self.client.post(reverse('users.login'), {'username': self.u.username, 'password': '******'}) eq_(302, response.status_code) eq_('http://testserver' + reverse('home', locale=settings.LANGUAGE_CODE) + '?fpa=1', response['location']) def test_login_next_parameter(self): '''Test with a valid ?next=url parameter.''' next = '/kb/new' # Verify that next parameter is set in form hidden field. response = self.client.get( urlparams(reverse('users.login'), next=next), follow=True) eq_(200, response.status_code) doc = pq(response.content) eq_(next, doc('#login input[name="next"]')[0].attrib['value']) # Verify that it gets used on form POST. response = self.client.post(reverse('users.login'), {'username': self.u.username, 'password': '******', 'next': next}) eq_(302, response.status_code) eq_('http://testserver' + next + '?fpa=1', response['location']) @mock.patch.object(Site.objects, 'get_current') def test_login_invalid_next_parameter(self, get_current): '''Test with an invalid ?next=http://example.com parameter.''' get_current.return_value.domain = 'testserver.com' invalid_next = 'http://foobar.com/evil/' valid_next = reverse('home', locale=settings.LANGUAGE_CODE) # Verify that _valid_ next parameter is set in form hidden field. url = urlparams(reverse('users.login'), next=invalid_next) response = self.client.get(url, follow=True) eq_(200, response.status_code) doc = pq(response.content) eq_(valid_next, doc('#login input[name="next"]')[0].attrib['value']) # Verify that it gets used on form POST. response = self.client.post(reverse('users.login'), {'username': self.u.username, 'password': '******', 'next': invalid_next}) eq_(302, response.status_code) eq_('http://testserver' + valid_next + '?fpa=1', response['location']) def test_ga_custom_variable_on_registered_login(self): """After logging in, there should be a ga-push data attr on body.""" user_ = UserFactory() # User should be "Registered": response = self.client.post(reverse('users.login'), {'username': user_.username, 'password': '******'}, follow=True) eq_(200, response.status_code) doc = pq(response.content) assert '"Registered"' in doc('body').attr('data-ga-push') def test_ga_custom_variable_on_contributor_login(self): """After logging in, there should be a ga-push data attr on body.""" user_ = UserFactory() # Add user to Contributors and so should be "Contributor": user_.groups.add(GroupFactory(name='Contributors')) response = self.client.post(reverse('users.login'), {'username': user_.username, 'password': '******'}, follow=True) eq_(200, response.status_code) doc = pq(response.content) assert '"Contributor"' in doc('body').attr('data-ga-push') def test_ga_custom_variable_on_admin_login(self): """After logging in, there should be a ga-push data attr on body.""" user_ = UserFactory() # Add user to Administrators and so should be "Contributor - Admin": user_.groups.add(GroupFactory(name='Administrators')) response = self.client.post(reverse('users.login'), {'username': user_.username, 'password': '******'}, follow=True) eq_(200, response.status_code) doc = pq(response.content) assert '"Contributor - Admin"' in doc('body').attr('data-ga-push') def test_login_mobile_csrf(self): """The mobile login view should have a CSRF token.""" response = self.client.get(reverse('users.login'), {'mobile': 1}) eq_(200, response.status_code) doc = pq(response.content) assert doc('#content form input[name="csrfmiddlewaretoken"]')
class ChangeEmailTestCase(TestCase): client_class = LocalizingClient def setUp(self): self.user = UserFactory() self.client.login(username=self.user.username, password='******') super(ChangeEmailTestCase, self).setUp() def test_redirect(self): """Test our redirect from old url to new one.""" response = self.client.get(reverse('users.old_change_email', locale='en-US'), follow=False) eq_(301, response.status_code) eq_('/en-US/users/change_email', response['location']) @mock.patch.object(Site.objects, 'get_current') def test_user_change_email(self, get_current): """Send email to change user's email and then change it.""" get_current.return_value.domain = 'su.mo.com' # Attempt to change email. response = self.client.post(reverse('users.change_email'), {'email': '*****@*****.**'}, follow=True) eq_(200, response.status_code) # Be notified to click a confirmation link. eq_(1, len(mail.outbox)) assert mail.outbox[0].subject.find('Please confirm your') == 0 ec = EmailChange.objects.all()[0] assert ec.activation_key in mail.outbox[0].body eq_('*****@*****.**', ec.email) # Visit confirmation link to change email. response = self.client.get(reverse('users.confirm_email', args=[ec.activation_key])) eq_(200, response.status_code) u = User.objects.get(username=self.user.username) eq_('*****@*****.**', u.email) def test_user_change_email_same(self): """Changing to same email shows validation error.""" self.user.email = '*****@*****.**' self.user.save() response = self.client.post(reverse('users.change_email'), {'email': self.user.email}) eq_(200, response.status_code) doc = pq(response.content) eq_('This is your current email.', doc('ul.errorlist').text()) def test_user_change_email_duplicate(self): """Changing to same email shows validation error.""" u = UserFactory(email='*****@*****.**') response = self.client.post(reverse('users.change_email'), {'email': u.email}) eq_(200, response.status_code) doc = pq(response.content) eq_('A user with that email address already exists.', doc('ul.errorlist').text()) @mock.patch.object(Site.objects, 'get_current') def test_user_confirm_email_duplicate(self, get_current): """If we detect a duplicate email when confirming an email change, don't change it and notify the user.""" get_current.return_value.domain = 'su.mo.com' old_email = self.user.email new_email = '*****@*****.**' response = self.client.post(reverse('users.change_email'), {'email': new_email}) eq_(200, response.status_code) assert mail.outbox[0].subject.find('Please confirm your') == 0 ec = EmailChange.objects.all()[0] # Before new email is confirmed, give the same email to a user u = UserFactory(email=new_email) # Visit confirmation link and verify email wasn't changed. response = self.client.get(reverse('users.confirm_email', args=[ec.activation_key])) eq_(200, response.status_code) doc = pq(response.content) eq_(u'Unable to change email for user %s' % self.user.username, doc('article h1').text()) u = User.objects.get(username=self.user.username) eq_(old_email, u.email)
class HelperTestCase(TestCase): def setUp(self): super(HelperTestCase, self).setUp() self.u = UserFactory() def test_profile_url(self): eq_("/user/%s" % self.u.username, profile_url(self.u)) def test_profile_avatar_default(self): email_hash = hashlib.md5(self.u.email.lower().encode()).hexdigest() gravatar_url = "https://secure.gravatar.com/avatar/%s?s=200" % (email_hash) assert profile_avatar(self.u).startswith(gravatar_url) def test_profile_avatar_anonymous(self): email_hash = "00000000000000000000000000000000" gravatar_url = "https://secure.gravatar.com/avatar/%s?s=200" % (email_hash) assert profile_avatar(AnonymousUser()).startswith(gravatar_url) def test_profile_avatar(self): self.u.profile.avatar = "images/foo.png" self.u.profile.save() email_hash = hashlib.md5(self.u.email.lower().encode()).hexdigest() gravatar_url = "https://secure.gravatar.com/avatar/%s?s=200" % (email_hash) assert profile_avatar(self.u).startswith(gravatar_url) def test_profile_avatar_unicode(self): self.u.email = "rá[email protected]" self.u.save() gravatar_url = "https://secure.gravatar.com/" assert profile_avatar(self.u).startswith(gravatar_url) def test_public_email(self): eq_( '<span class="email">' "me@domain.c" "om</span>", public_email("*****@*****.**"), ) eq_( '<span class="email">' "not.an.emai" "l</span>", public_email("not.an.email"), ) def test_display_name(self): eq_(self.u.profile.name, display_name(self.u)) self.u.profile.name = "Test User" self.u.profile.save() eq_("Test User", display_name(self.u)) def test_display_name_anonymous(self): eq_("", display_name(AnonymousUser())) def test_user_list(self): UserFactory(username="******") UserFactory(username="******") users = User.objects.all() list = user_list(users) assert isinstance(list, Markup) fragment = pq(list) eq_(len(users), len(fragment("a"))) a = fragment("a")[1] assert a.attrib["href"].endswith(str(users[1].username)) eq_(display_name(users[1]), a.text)