当前位置: 首页>>代码示例>>Python>>正文


Python UserFactory.save方法代码示例

本文整理汇总了Python中kitsune.users.tests.UserFactory.save方法的典型用法代码示例。如果您正苦于以下问题:Python UserFactory.save方法的具体用法?Python UserFactory.save怎么用?Python UserFactory.save使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在kitsune.users.tests.UserFactory的用法示例。


在下文中一共展示了UserFactory.save方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_thread_is_reindexed_on_username_change

# 需要导入模块: from kitsune.users.tests import UserFactory [as 别名]
# 或者: from kitsune.users.tests.UserFactory import save [as 别名]
    def test_thread_is_reindexed_on_username_change(self):
        search = ThreadMappingType.search()

        u = UserFactory(username='dexter')
        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 = 'walter'
        u.save()
        self.refresh()
        eq_(search.query(post_title='hello')[0]['post_author_ord'], [u'walter'])
开发者ID:1234-,项目名称:kitsune,代码行数:16,代码来源:test_es.py

示例2: test_deactivate_button

# 需要导入模块: from kitsune.users.tests import UserFactory [as 别名]
# 或者: from kitsune.users.tests.UserFactory import save [as 别名]
    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='testpass')
        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
开发者ID:1234-,项目名称:kitsune,代码行数:20,代码来源:test_templates.py

示例3: test_aaq_new_question_inactive

# 需要导入模块: from kitsune.users.tests import UserFactory [as 别名]
# 或者: from kitsune.users.tests.UserFactory import save [as 别名]
    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='testpass')

        # 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')
开发者ID:1234-,项目名称:kitsune,代码行数:23,代码来源:test_views.py

示例4: test_questions_inactive_user

# 需要导入模块: from kitsune.users.tests import UserFactory [as 别名]
# 或者: from kitsune.users.tests.UserFactory import save [as 别名]
    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)
开发者ID:1234-,项目名称:kitsune,代码行数:23,代码来源:test_api.py

示例5: test_question_is_reindexed_on_username_change

# 需要导入模块: from kitsune.users.tests import UserFactory [as 别名]
# 或者: from kitsune.users.tests.UserFactory import save [as 别名]
    def test_question_is_reindexed_on_username_change(self):
        search = QuestionMappingType.search()

        u = UserFactory(username='dexter')

        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 = 'walter'
        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'])
开发者ID:1234-,项目名称:kitsune,代码行数:24,代码来源:test_es.py

示例6: LoginTests

# 需要导入模块: from kitsune.users.tests import UserFactory [as 别名]
# 或者: from kitsune.users.tests.UserFactory import save [as 别名]
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': 'foobar'})
        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': 'foobarbizbin', 'password': 'testpass'})
        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': 'testpass'})
        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': 'testpass'})
        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': 'testpass',
                                     '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': 'testpass',
                                     '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': 'testpass'},
                                    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."""
#.........这里部分代码省略.........
开发者ID:1234-,项目名称:kitsune,代码行数:103,代码来源:test_templates.py

示例7: PasswordResetTests

# 需要导入模块: from kitsune.users.tests import UserFactory [as 别名]
# 或者: from kitsune.users.tests.UserFactory import save [as 别名]
class PasswordResetTests(TestCaseBase):

    def setUp(self):
        super(PasswordResetTests, self).setUp()
        self.u = UserFactory(email="[email protected]")
        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': '[email protected]'})
        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()
开发者ID:1234-,项目名称:kitsune,代码行数:88,代码来源:test_templates.py

示例8: LoginTests

# 需要导入模块: from kitsune.users.tests import UserFactory [as 别名]
# 或者: from kitsune.users.tests.UserFactory import save [as 别名]
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': 'foobar'})
        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': 'foobarbizbin', 'password': 'testpass'})
        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': 'testpass'})
        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': 'testpass'})
        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': 'testpass',
                                     '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': 'testpass',
                                     '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"]')
开发者ID:akatsoulas,项目名称:kitsune,代码行数:90,代码来源:test_templates.py

示例9: HelperTestCase

# 需要导入模块: from kitsune.users.tests import UserFactory [as 别名]
# 或者: from kitsune.users.tests.UserFactory import save [as 别名]
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"&#109;&#101;&#64;&#100;&#111;&#109;&#97;&#105;&#110;&#46;&#99;"
            u"&#111;&#109;</span>",
            public_email("[email protected]"),
        )
        eq_(
            u'<span class="email">' u"&#110;&#111;&#116;&#46;&#97;&#110;&#46;&#101;&#109;&#97;&#105;" u"&#108;</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="testuser2")
        UserFactory(username="testuser3")
        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)
开发者ID:chupahanks,项目名称:kitsune,代码行数:65,代码来源:test_helpers.py

示例10: HelperTestCase

# 需要导入模块: from kitsune.users.tests import UserFactory [as 别名]
# 或者: from kitsune.users.tests.UserFactory import save [as 别名]
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'&#109;&#101;&#64;&#100;&#111;&#109;&#97;&#105;&#110;&#46;&#99;'
            u'&#111;&#109;</span>', public_email('[email protected]'))
        eq_(u'<span class="email">'
            u'&#110;&#111;&#116;&#46;&#97;&#110;&#46;&#101;&#109;&#97;&#105;'
            u'&#108;</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='testuser2')
        UserFactory(username='testuser3')
        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)
开发者ID:1234-,项目名称:kitsune,代码行数:64,代码来源:test_templatetags.py

示例11: UserProfileTests

# 需要导入模块: from kitsune.users.tests import UserFactory [as 别名]
# 或者: from kitsune.users.tests.UserFactory import save [as 别名]
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='testpass')
        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='testpass')
        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())
开发者ID:1234-,项目名称:kitsune,代码行数:66,代码来源:test_views.py

示例12: ChangeEmailTestCase

# 需要导入模块: from kitsune.users.tests import UserFactory [as 别名]
# 或者: from kitsune.users.tests.UserFactory import save [as 别名]
class ChangeEmailTestCase(TestCase):
    client_class = LocalizingClient

    def setUp(self):
        self.user = UserFactory()
        self.client.login(username=self.user.username, password='testpass')
        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': '[email protected]'},
                                    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_('[email protected]', 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_('[email protected]', u.email)

    def test_user_change_email_same(self):
        """Changing to same email shows validation error."""
        self.user.email = '[email protected]'
        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='[email protected]')
        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 = '[email protected]'
        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)
开发者ID:1234-,项目名称:kitsune,代码行数:87,代码来源:test_views.py


注:本文中的kitsune.users.tests.UserFactory.save方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。