Flask-Login is_authenticated不一致

时间:2015-10-03 18:35:47

标签: python flask flask-login

我正在使用测试单元验证Flask-Login的登录。这样做的目的是验证凭据不正确的用户的行为:

    def test_login_user(self):
        '''test user login'''
        user = User(email='teste@teste.com', pass='teste')
        db.session.add(user)
        db.session.commit()

        response = self.app.post('/login_user', data={'email':
             'teste@teste.com', 'pass': 'tste'}, follow_redirects=True)

        print(response.get_data(), user.is_authenticated)
        assert user.is_authenticated == True
        self.assertEqual(response.status, "200 OK")

问题是assert user.is_authenticated通过了测试,即使最后一个断言失败了:

Traceback (most recent call last):
File "./test.py", line 58, in test_login_user
self.assertEqual(response.status, "200 OK")
AssertionError: '401 UNAUTHORIZED' != '200 OK'
- 401 UNAUTHORIZED
+ 200 OK

我的登录视图实现如下:

@app.route('/login_user', methods=['GET', 'POST'])
def login_user():
if request.method == 'POST':
    user_requested = User.query.filter_by(email=request.form['email']).first()
    if user_requested is not None:
        if sha256_crypt.verify(request.form['pass'], user_requested.pass):
            return redirect(url_for('student'))
    return redirect(url_for('error'))

此外,在类User上,我正在扩展UserMixin。为什么user.is_authenticated不返回False?

1 个答案:

答案 0 :(得分:1)

您没有在登录视图中调用def index = Action.async { val crewType = "x" Future(Crew.findCaptainByCrewType(crewType)).flatMap(_.fold( Future.successful(BadRequest(s"Invalid crew name provided: $crewType; will not run.")) )(crew => system.actorSelection(s"/user/${crew.cptName}randomness").resolveOne().map {actorRef => actorRef ! "hi hi" Logger.info("success") Ok("success") }.recover { case ex: ActorNotFound => Logger.error("failure", ex) BadRequest("failure") }) ) } 。重定向时,login_user在受保护的视图上失败。在重定向之前,将您从数据库中提取的用户传递给login_required

所有用户实例都经过身份验证,即使他们未登录。只有匿名用户未经过身份验证。查看上下文中的login_user以查看登录的用户。您可以使用current_user块来保持上下文。

with app.test_client() as c

这是Flask-Login设置和测试的最小示例。

with app.test_client() as c:
    r = c.post('/login', data={...})
    self.assertEqual(current_user.email, '...')
import unittest
from flask import Flask, redirect, url_for, request
from flask.ext.login import login_required
from flask_login import LoginManager, UserMixin, login_user, current_user

class TestApp(unittest.TestCase):
    def setUp(self):
        app.testing = True

    def tearDown(self):
        app.testing = False

    def test_login(self):
        with app.test_client() as c:
            r = c.post('/login', data={'id': 400617}, follow_redirects=True)
            # current_user is only set in context
            self.assertEqual(current_user.id, 400617)

        # resopnse doesn't depend on context, so can be tested outside block
        self.assertEqual(r.status, '200 OK')
        # any non-anonymous user is authenticated, even if not logged in
        self.assertTrue(User(123).is_authenticated)

app = Flask(__name__)
app.secret_key = 'Stack Overflow'
login = LoginManager(app)
login.login_view = 'login'

class User(UserMixin):
    def __init__(self, id):
        self.id = id

@login.user_loader
def user_loader(id):
    return User(int(id))

@app.route('/')
@login_required
def index():
    return 'index'

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        user = User(id=request.form.get('id', type=int))
        login_user(user)
        return redirect(url_for('index'))

    return 'login'