Пример #1
0
    def test_user_add_admin(self):
        admin_role = Role.query.filter_by(name='Administrator').first()
        admin_user = User.query.filter_by(role=admin_role).first()

        self.assertIsNone(admin_user)

        User.add_admin()
        admin_user2 = User.query.filter_by(role=admin_role).first()
        self.assertIsNotNone(admin_user2)
        self.assertEqual(admin_user2.role, admin_role)
Пример #2
0
    def test_user_confirm_token(self):
        User.generate_fake(count=2)
        user1 = User.query.first()
        user2 = User.query.filter(User.id != user1.id).first()

        token1 = user1.generate_confirmation_token(expiration=3600)
        token2 = user2.generate_confirmation_token(expiration=3600)

        self.assertTrue(user1.confirm(token1))
        self.assertFalse(user1.confirm(token2))
        self.assertTrue(user2.confirm(token2))
        self.assertFalse(user2.confirm(token1))
        self.assertFalse(user1.confirm(''))
Пример #3
0
    def test_user_has_role(self):
        admin_role = Role.query.filter_by(name='Administrator').first()
        user_role = Role.query.filter_by(name='User').first()

        user1 = User(email=forgery_py.internet.email_address(),
                     username=forgery_py.internet.user_name(),
                     password='******',
                     avatar_hash=None,
                     role=user_role,
                     confirmed=True)

        user2 = User(email=forgery_py.internet.email_address(),
                     username=forgery_py.internet.user_name(),
                     password='******',
                     avatar_hash=None,
                     role=admin_role,
                     confirmed=True)

        db.session.add(user1, user2)
        db.session.commit()

        self.assertTrue(user1.has_role(user_role.name))
        self.assertFalse(user1.has_role(admin_role.name))
        self.assertTrue(user2.has_role(admin_role.name))
        self.assertFalse(user2.has_role(user_role.name))
Пример #4
0
    def test_user_suspend(self):
        admin_role = Role.query.filter_by(name='Administrator').first()
        user_role = Role.query.filter_by(name='User').first()

        User.generate_fake(count=1, roles=[admin_role])
        admin_user = User.query.filter_by(role=admin_role).first()

        self.assertEqual(admin_user.role, admin_role)

        is_suspended = admin_user.suspend()
        self.assertTrue(is_suspended)

        self.assertNotEqual(admin_user.role, admin_role)
        self.assertEqual(admin_user.role, user_role)
Пример #5
0
    def test_user_auth_token(self):
        user_role = Role.query.filter_by(name='User').first()
        user = User(email=forgery_py.internet.email_address(),
                    username=forgery_py.internet.user_name(),
                    password='******',
                    avatar_hash=None,
                    role=user_role,
                    confirmed=True)
        db.session.add(user)
        db.session.commit()

        token = user.generate_auth_token(3600)
        self.assertEqual(user, User.verify_auth_token(token))
        self.assertIsNone(User.verify_auth_token(''))
        self.assertEqual(repr(user), "<User '{}'>".format(user.username))
Пример #6
0
    def test_generate_confirmation_token(self):
        user_role = Role.query.filter_by(name='User').first()
        user = User(email=forgery_py.internet.email_address(),
                    username=forgery_py.internet.user_name(),
                    password='******',
                    avatar_hash=None,
                    role=user_role,
                    confirmed=True)
        db.session.add(user)
        db.session.commit()

        token1 = user.generate_confirmation_token(expiration=3600)
        token2 = user.generate_confirmation_token(expiration=3601)

        self.assertNotEqual(token1, token2)
Пример #7
0
    def test_authorized_access_to_get_token(self):
        admin_role = Role.query.filter_by(name='Administrator').first()
        admin = User(
            email='*****@*****.**',
            username='******',
            role=admin_role,
            password='******',
            confirmed=True,
        )
        db.session.add(admin)
        db.session.commit()

        headers = Headers()
        headers.add(*HTTP.basic_auth('*****@*****.**', 'test'))

        response = self.client.get(url_for('webhook.get_token'),
                                   data=json.dumps(TelegramUpdates.EMPTY),
                                   follow_redirects=True,
                                   headers=headers)

        self.assertEqual(response.status_code, 200,
                         'Failed to give access for a valid authorized user')

        response_json = json.loads(response.data)
        self.assertEqual(response_json['expiration'], 3600)
Пример #8
0
    def test_setting_webhook_with_exception_raised(self, mock_requests):
        from requests.exceptions import RequestException
        mock_requests.side_effect = RequestException('Boom!')

        admin_role = Role.query.filter_by(name='Administrator').first()
        admin = User(
            email='*****@*****.**',
            username='******',
            role=admin_role,
            password='******',
            confirmed=True,
        )
        db.session.add(admin)
        db.session.commit()

        headers = Headers()
        headers.add(*HTTP.basic_auth('*****@*****.**', 'test'))

        response = self.client.post(TelegramUpdates.URL_SET_WEBHOOK,
                                    data=json.dumps({}),
                                    follow_redirects=True,
                                    headers=headers)

        response_json = json.loads(response.data)
        self.assertEqual(
            response_json['error_code'], 599,
            'Failed to return error code 599 when RequestException is thrown')
        mock_requests.assert_called()
Пример #9
0
    def test_logout(self):
        anon_logout_response = self.client.get(url_for('auth.logout'),
                                               follow_redirects=True)
        anon_data = anon_logout_response.get_data(as_text=True)
        self.assertNotIn(
            'You have been logged out', anon_data,
            'Failed to redirect anonymous user '
            'attempting to logout to login page first')
        self.assertIn(
            'Please log in to access this page', anon_data,
            'Failed to notify anonymous user to log in '
            'before accessing logout page')

        admin_role = Role.query.filter_by(name='Administrator').first()
        admin = User(
            email='*****@*****.**',
            username='******',
            role=admin_role,
            password='******',
            confirmed=False,
        )
        db.session.add(admin)
        db.session.commit()

        response = self.login(email='*****@*****.**',
                              password='******',
                              follow_redirects=True)

        logged_user_logout_response = self.client.get(url_for('auth.logout'),
                                                      follow_redirects=True)
        logged_user_data = logged_user_logout_response.get_data(as_text=True)

        self.assertIn('You have been logged out', logged_user_data,
                      'Failed to logout user previously logged in')
        self.assertNotIn('Please log in to access this page', logged_user_data)
Пример #10
0
    def test_sethook_moderator_user(self, mock_requests):
        moderator_role = Role.query.filter_by(name='Moderator').first()
        moderator = User(
            email='*****@*****.**',
            username='******',
            role=moderator_role,
            password='******',
            confirmed=True,
        )
        db.session.add(moderator)
        db.session.commit()

        headers = Headers()
        headers.add(*HTTP.basic_auth('*****@*****.**', 'test'))

        response = self.client.post(TelegramUpdates.URL_SET_WEBHOOK,
                                    data=json.dumps({}),
                                    follow_redirects=True,
                                    headers=headers)

        self.assertEqual(response.status_code, 403,
                         'Failed to forbid access for a moderator user')
        with self.assertRaises(AssertionError) as err:
            mock_requests.assert_called()

        self.assertIn("Expected 'post' to have been called",
                      str(err.exception))
Пример #11
0
    def test_user_init(self):
        user_role = Role.query.filter_by(name='User').first()
        admin_role = Role.query.filter_by(name='Administrator').first()

        username0 = forgery_py.internet.user_name()
        u0 = User(email=None,
                  username=username0,
                  password=forgery_py.basic.password(),
                  avatar_hash=None,
                  role=None,
                  confirmed=True)
        db.session.add(u0)
        db.session.commit()

        fetch_u0 = User.query.filter_by(username=username0).first()
        self.assertIsNone(fetch_u0.avatar_hash)

        u1 = User(email=forgery_py.internet.email_address(),
                  username=forgery_py.internet.user_name(),
                  password=forgery_py.basic.password(),
                  avatar_hash=None,
                  role=None,
                  confirmed=True)
        db.session.add(u1)
        db.session.commit()

        fetch_u1 = User.query.first()
        self.assertEqual(fetch_u1.role, user_role)

        u2 = User(email=current_app.config['APP_ADMIN_EMAIL'],
                  username=forgery_py.internet.user_name(),
                  password=forgery_py.basic.password(),
                  avatar_hash=None,
                  role=None,
                  confirmed=True)
        db.session.add(u2)
        db.session.commit()

        fetch_u2 = User.query.filter_by(
            email=current_app.config['APP_ADMIN_EMAIL']).first()
        self.assertEqual(fetch_u2.role, admin_role)

        avatar_hash_expected = hashlib.md5(current_app.config['APP_ADMIN_EMAIL'].\
                                           encode('utf-8')).hexdigest()
        self.assertEqual(fetch_u2.avatar_hash, avatar_hash_expected)
Пример #12
0
    def test_invite_request_get(self):
        number_of_users = current_app.config['APP_ITEMS_PER_PAGE'] * 2
        User.generate_fake(count=number_of_users)
        # will be first user in the list of users, since it's not confirmed yet

        user = self.create_user(email='*****@*****.**',
                                username='******',
                                role_name='User',
                                confirmed=False)
        admin = self.create_user(confirmed=True)
        response = self.login(email='*****@*****.**',
                              password='******',
                              follow_redirects=True)

        response_page_1 = self.client.get(url_for('auth.invite_request'),
                                          follow_redirects=True)
        data_page_1 = response_page_1.get_data(as_text=True)
        self.assertIn(
            '*****@*****.**', data_page_1,
            'Failed to show unconfirmed invited user on the first page '
            'of user invitation form page.')
        response_page_2 = self.client.get(url_for('auth.invite_request',
                                                  page=2),
                                          follow_redirects=True)
        data_page_2 = response_page_2.get_data(as_text=True)
        self.assertNotIn(
            '*****@*****.**', data_page_2,
            'Failed to show invited user on the first page '
            'of user invitation form page.')
        response_page_3 = self.client.get(url_for('auth.invite_request',
                                                  page=3),
                                          follow_redirects=True)
        data_page_3 = response_page_3.get_data(as_text=True)
        self.assertNotIn('*****@*****.**', data_page_3)

        response_page_4 = self.client.get(url_for('auth.invite_request',
                                                  page=4),
                                          follow_redirects=True)
        data_page_4 = response_page_4.get_data(as_text=True)
        self.assertNotIn(
            '@', data_page_4,
            'Failed to show empty list of users when pagination '
            'is exhausted as error_out=False prevents '
            'throwing error 404.')
Пример #13
0
    def test_sethook_administrator_user(self, mock_requests):
        admin_role = Role.query.filter_by(name='Administrator').first()
        admin = User(
            email='*****@*****.**',
            username='******',
            role=admin_role,
            password='******',
            confirmed=True,
        )
        db.session.add(admin)
        db.session.commit()

        # Werkzeug's test client doesn't have embedded
        # Basic HTTP Authentication out of box like requests have,
        # so we have to implement it by making up headers.
        # see also
        # http://stackoverflow.com/a/30248823/4241180
        # http://stackoverflow.com/a/27643297/4241180
        # http://blog.bstpierre.org/flask-testing-auth
        headers = Headers()
        headers.add(*HTTP.basic_auth('*****@*****.**', 'test'))

        response = self.client.post(TelegramUpdates.URL_SET_WEBHOOK,
                                    data=json.dumps({}),
                                    follow_redirects=True,
                                    headers=headers)

        self.assertEqual(response.status_code, 200,
                         'Failed to allow access for an administrator user')

        response_json = json.loads(response.data)
        self.assertTrue(response_json['ok'] is False)
        self.assertEqual(
            response_json['error_code'], 400,
            'Failed to return error code 400 '
            'when setting non-HTTPS Webhook URL: {}'.format(
                response_json['description']))
        self.assertEqual(
            response_json['url'],
            url_for('webhook.handle_webhook', _external=True),
            'Failed to return a JSON with the URL of the Webhook handing view '
            'for an authorized user')
        mock_requests.assert_called()
        self.assertIn(
            call(files=None,
                 json={
                     'url':
                     TelegramUpdates.URL_HANDLE_WEBHOOK,
                     'max_connections':
                     current_app.config['SERVER_MAX_CONNECTIONS'],
                     'allowed_updates': []
                 },
                 timeout=current_app.config['TELEGRAM_REQUEST_TIMEOUT_SEC'] *
                 60,
                 url=current_app.config['TELEGRAM_URL'] + 'setWebhook'),
            mock_requests.call_args_list)
Пример #14
0
    def test_sentiment_json(self):
        User.generate_fake(count=2)
        Sentiment.generate_fake(count=1)
        s = Sentiment.query.first()
        json_data = s.to_json()

        self.assertEqual(json_data['body'], s.body)
        self.assertEqual(json_data['body_html'], s.body_html)
        self.assertEqual(json_data['timestamp'], s.timestamp)

        sentiment_from_json = Sentiment.from_json(json_data)
        self.assertEqual(sentiment_from_json.body, s.body)

        with self.assertRaises(ValidationError) as err:
            Sentiment.from_json({})

        self.assertIn("sentiment does not have a body", str(err.exception))

        self.assertEqual(repr(s), "<Sentiment '{}'>".format(s.body))
Пример #15
0
    def setUp(self):
        """Method called before each unit-test"""
        # create app, set TESTING flag to disable error catching
        self.app = create_app('testing')

        # push app context
        self.app_context = self.app.app_context()
        self.app_context.push()

        # create databases, see config.py for testing db settings
        db.create_all()

        # pre-fill db with minimal needed things
        Role.insert_roles()
        Language.insert_basic_languages()
        User.generate_fake(10)
        Sentiment.generate_fake(25)

        # Werkzeug Client to make requests
        self.client = self.app.test_client(use_cookies=True)
Пример #16
0
    def test_sentiment_generate_fake(self):
        User.generate_fake(count=10)
        self.assertEqual(Sentiment.query.all(), [])

        levels = [i / 10.0 for i in range(100)]
        Sentiment.generate_fake(count=100,
                                subsequent_scores=False,
                                levels=levels)

        sentiments = Sentiment.query.order_by(Sentiment.id.asc()).all()
        self.assertNotEqual(levels, [s.score for s in sentiments])

        Sentiment.query.filter().delete()
        db.session.commit()

        Sentiment.generate_fake(count=100,
                                subsequent_scores=True,
                                levels=levels)
        sentiments = Sentiment.query.order_by(Sentiment.id.asc()).all()
        self.assertEqual(levels, [s.score for s in sentiments])
Пример #17
0
 def create_user(self, role_name='Administrator', email='*****@*****.**',
                 username='******', password='******', invited=True, confirmed=True):
     role = Role.query.filter_by(name=role_name).first()
     user = User(email=email,
                 username=username,
                 role=role,
                 password=password,
                 invited=invited,
                 confirmed=confirmed)
     db.session.add(user)
     db.session.commit()
     return user
Пример #18
0
    def setUp(self):
        """Method called before each unit-test"""
        # create app, set TESTING flag to disable error catching
        self.app = create_app('testing')

        # push app context
        self.app_context = self.app.app_context()
        self.app_context.push()

        # make celery tasks eager
        # celery emulates the API and behavior of AsyncResult,
        # except the result is already evaluated.
        celery.conf.update(CELERY_ALWAYS_EAGER=True)

        # create databases, see config.py for testing db settings
        db.create_all()

        # pre-fill db with minimal needed things
        Role.insert_roles()
        Language.insert_basic_languages()
        User.generate_fake(5)
Пример #19
0
    def test_user_change_email(self):
        User.generate_fake(count=2)
        user1 = User.query.first()
        user2 = User.query.filter(User.id != user1.id).first()

        old_email_user1 = user1.email
        new_email_user2 = forgery_py.internet.email_address()
        valid_token_user1 = user1.generate_email_change_token(
            new_email=new_email_user2)
        invalid_token_user1 = user1.generate_confirmation_token()
        blank_new_email_user2 = user2.generate_email_change_token(
            new_email=None)
        email_already_in_use = user2.generate_email_change_token(
            new_email=user2.email)

        self.assertTrue(user1.change_email(valid_token_user1))
        self.assertEqual(user1.email, new_email_user2)
        self.assertNotEqual(user1.email, old_email_user1)
        self.assertFalse(user1.change_email(''))
        self.assertFalse(user1.change_email(invalid_token_user1))
        self.assertFalse(user2.change_email(blank_new_email_user2))
        self.assertFalse(user2.change_email(email_already_in_use))
Пример #20
0
    def test_user_gravatar(self):
        user_role = Role.query.filter_by(name='User').first()
        user = User(email=forgery_py.internet.email_address(),
                    username=forgery_py.internet.user_name(),
                    password='******',
                    avatar_hash=None,
                    role=user_role,
                    confirmed=True)
        db.session.add(user)
        db.session.commit()

        https_url = 'https://secure.gravatar.com/avatar'
        http_url = 'http://www.gravatar.com/avatar'
        size = 150
        default = 'identicon'
        rating = 'g'
        hash = hashlib.md5(user.email.encode('utf-8')).hexdigest()

        http_gravatar = user.gravatar(size=size,
                                      default=default,
                                      rating=rating)

        self.assertEqual(
            http_gravatar,
            '{url}/{hash}?s={size}&d={default}&r={rating}'.format(
                url=http_url,
                hash=hash,
                size=size,
                default=default,
                rating=rating))
        self.assertNotEqual(
            http_gravatar,
            '{url}/{hash}?s={size}&d={default}&r={rating}'.format(
                url=https_url,
                hash=hash,
                size=size,
                default=default,
                rating=rating))
Пример #21
0
def deploy():
    """Run deployment tasks."""
    from flask_migrate import migrate, upgrade
    from PilosusBot.models import Role, User, Language
    from PilosusBot.utils import download_polyglot_dicts

    # generate an initial migration
    migrate()

    # migrate database to latest revision
    upgrade()

    # insert roles
    Role.insert_roles()

    # create admin
    User.add_admin()

    # insert languages
    Language.insert_basic_languages()

    # download third-party files needed for the app
    download_polyglot_dicts()
Пример #22
0
    def test_unsethook_administrator_user(self, mock_requests):
        admin_role = Role.query.filter_by(name='Administrator').first()
        admin = User(
            email='*****@*****.**',
            username='******',
            role=admin_role,
            password='******',
            confirmed=True,
        )
        db.session.add(admin)
        db.session.commit()

        # Werkzeug's test client doesn't have embedded
        # Basic HTTP Authentication out of box like requests have,
        # so we have to implement it by making up headers.
        # see also
        # http://stackoverflow.com/a/30248823/4241180
        # http://stackoverflow.com/a/27643297/4241180
        # http://blog.bstpierre.org/flask-testing-auth
        headers = Headers()
        headers.add(*HTTP.basic_auth('*****@*****.**', 'test'))

        response = self.client.post(TelegramUpdates.URL_UNSET_WEBHOOK,
                                    data=json.dumps({}),
                                    follow_redirects=True,
                                    headers=headers)

        self.assertEqual(
            response.status_code, 200, 'Failed to return status code 200 '
            'when unsetting Webhook URL by the administrator user')

        response_json = json.loads(response.data)
        self.assertEqual(
            response_json['url'], '',
            'Failed to return an empty field for the URL in JSON '
            'when unsetting Webhook URL by the administrator user')
        mock_requests.assert_called()
        self.assertIn(
            call(files=None,
                 json={
                     'url':
                     '',
                     'max_connections':
                     current_app.config['SERVER_MAX_CONNECTIONS'],
                     'allowed_updates': []
                 },
                 timeout=current_app.config['TELEGRAM_REQUEST_TIMEOUT_SEC'] *
                 60,
                 url=current_app.config['TELEGRAM_URL'] + 'setWebhook'),
            mock_requests.call_args_list)
Пример #23
0
    def test_user_invite(self):
        user_role = Role.query.filter_by(name='User').first()
        User.generate_fake(count=1)
        user1 = User.query.first()
        user2 = User(email=forgery_py.internet.email_address(), role=user_role)
        db.session.add(user2)
        db.session.commit()

        valid_token = user2.generate_invite_token(expiration=3600)
        invalid_token = user2.generate_confirmation_token(expiration=3600)

        valid_invite = user2.accept_invite(token=valid_token,
                                           username='******',
                                           new_password='******')
        invalid_invite = user2.accept_invite(invalid_token, 'username2',
                                             'new_password')
        invalid_invite2 = user2.accept_invite('', 'username2', 'new_password')

        self.assertTrue(valid_invite)
        self.assertTrue(user2.username, 'username2')
        self.assertTrue(user2.verify_password('new_password'))

        self.assertFalse(invalid_invite)
        self.assertFalse(invalid_invite2)
Пример #24
0
    def test_user_password(self):
        user_role = Role.query.filter_by(name='User').first()
        user = User(email=forgery_py.internet.email_address(),
                    username=forgery_py.internet.user_name(),
                    password='******',
                    avatar_hash=None,
                    role=user_role,
                    confirmed=True)
        db.session.add(user)
        db.session.commit()

        with self.assertRaises(AttributeError) as err:
            user.password()

        self.assertTrue(user.verify_password('old_password'.encode('utf-8')))
        user.password = '******'
        self.assertFalse(user.verify_password('old_password'.encode('utf-8')))
        self.assertTrue(user.verify_password('new_password'.encode('utf-8')))
Пример #25
0
    def test_setwebhook_with_SSL_certificate(self, mock_requests):
        # set up SSL certificate
        tmp_cert_file = os.path.join(tempfile.gettempdir(), "SSL.cert")
        with open(tmp_cert_file, 'wb') as fp:
            fp.write(b'SSL Certificate Content')

        # add administrator
        admin_role = Role.query.filter_by(name='Administrator').first()
        admin = User(
            email='*****@*****.**',
            username='******',
            role=admin_role,
            password='******',
            confirmed=True,
        )
        db.session.add(admin)
        db.session.commit()

        # make a request
        headers = Headers()
        headers.add(*HTTP.basic_auth('*****@*****.**', 'test'))

        new_config = {
            'TELEGRAM_URL':
            current_app.config['TELEGRAM_URL'],
            'SERVER_PUBLIC_KEY':
            tmp_cert_file,
            'SERVER_MAX_CONNECTIONS':
            current_app.config['SERVER_MAX_CONNECTIONS'],
            'TELEGRAM_REQUEST_TIMEOUT_SEC':
            current_app.config['TELEGRAM_REQUEST_TIMEOUT_SEC']
        }

        with patch.dict(current_app.config, new_config):
            response = self.client.post(TelegramUpdates.URL_SET_WEBHOOK,
                                        data=json.dumps({}),
                                        follow_redirects=True,
                                        headers=headers)

            self.assertEqual(current_app.config['SERVER_PUBLIC_KEY'],
                             tmp_cert_file)
            self.assertEqual(
                response.status_code, 200, 'Failed to return status code 200 '
                'when setting Webhook URL by the administrator user '
                'with SSL certificate specified')
            mock_requests.assert_called()
Пример #26
0
    def test_login_required_incorrect_username(self):
        admin_role = Role.query.filter_by(name='Administrator').first()
        admin = User(
            email='*****@*****.**',
            username='******',
            role=admin_role,
            password='******',
            confirmed=True,
        )
        db.session.add(admin)
        db.session.commit()

        headers = Headers()
        headers.add(*HTTP.basic_auth('incorrect_username', 'test'))

        response = self.client.post(TelegramUpdates.URL_UNSET_WEBHOOK,
                                    data=json.dumps({}),
                                    follow_redirects=True,
                                    headers=headers)

        self.assertEqual(
            response.status_code, 403, 'Failed to return status code 403 '
            'when unsetting Webhook URL by the '
            'user with incorrect username')
Пример #27
0
    def test_bad_request_response(self, mock_requests):
        admin_role = Role.query.filter_by(name='Administrator').first()
        admin = User(
            email='*****@*****.**',
            username='******',
            role=admin_role,
            password='******',
            confirmed=True,
        )
        db.session.add(admin)
        db.session.commit()

        headers = Headers()
        headers.add(*HTTP.basic_auth('*****@*****.**', 'test'))

        response = self.client.post(TelegramUpdates.URL_SET_WEBHOOK,
                                    data=json.dumps({}),
                                    follow_redirects=True,
                                    headers=headers)

        self.assertEqual(
            response.status_code, 400, 'Failed to return status code 400 '
            'when ValidationError is raised')
        mock_requests.assert_called()
Пример #28
0
    def test_user_ping(self, mock_datetime):
        now = datetime.utcnow()
        mock_datetime.utcnow.return_value = now

        user_role = Role.query.filter_by(name='User').first()
        user = User(email=forgery_py.internet.email_address(),
                    username=forgery_py.internet.user_name(),
                    password='******',
                    avatar_hash=None,
                    role=user_role,
                    confirmed=True)
        db.session.add(user)
        db.session.commit()

        user.ping()
        self.assertEqual(user.last_seen, now)
        user.ping()
        self.assertEqual(user.last_seen, now)
        mock_datetime.utcnow.assert_called()
Пример #29
0
    def test_user_reset_password(self):
        user_role = Role.query.filter_by(name='User').first()
        user = User(email=forgery_py.internet.email_address(),
                    username=forgery_py.internet.user_name(),
                    password='******',
                    avatar_hash=None,
                    role=user_role,
                    confirmed=True)
        db.session.add(user)
        db.session.commit()

        reset_token = user.generate_reset_token()
        confirmation_token = user.generate_confirmation_token()

        valid_result = user.reset_password(token=reset_token,
                                           new_password='******')
        invalid_result = user.reset_password(token='',
                                             new_password='******')
        invalid_result2 = user.reset_password(token=confirmation_token,
                                              new_password='******')

        self.assertTrue(valid_result)
        self.assertFalse(invalid_result)
        self.assertFalse(invalid_result2)