当使用带有Flask 0.8 的Google App Engine 1.6.4测试平台,特别是Flask-Login 0.1 包(source)时,我在命令行单元测试中遇到了一个奇怪的问题。
下面是一个演示该问题的示例。注意注释行 ( from google.appengine.ext import testbed
)。注释此行时,测试按预期工作。
当取消注释该行时,@login_required
装饰器Flask-Login
停止识别登录用户,即current_user.is_authenticated()
返回 False。罪魁祸首似乎是进口testbed
。
#!/usr/bin/env python2.7
import unittest
import sys
from flask import Flask, current_app, url_for
from flaskext import login
sys.path.append('/usr/local/google_appengine')
# Go ahead and uncomment this:
# from google.appengine.ext import testbed
app = Flask('test')
app.secret_key = 'abc'
login_manager = login.LoginManager()
login_manager.setup_app(app)
login_manager.login_view = 'index'
class User(login.UserMixin):
def get_id(self):
return "1"
@login_manager.user_loader
def load_user(user_id):
return User()
@app.route('/')
@login.login_required
def index():
pass
@login_manager.unauthorized_handler
def unauthorized():
raise Exception("Unauthorized.")
class MyTest(unittest.TestCase):
def setUp(self):
self.app = app
self.client = app.test_client()
def test_user(self):
with self.app.test_request_context():
logged_in = login.login_user(User())
r = self.client.get('/')
if __name__ == '__main__':
unittest.main()
具体的例外是:
ERROR:test:Exception on / [GET]
Traceback (most recent call last):
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/Flask-0.8-py2.7.egg/flask/app.py", line 1504, in wsgi_app
response = self.full_dispatch_request()
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/Flask-0.8-py2.7.egg/flask/app.py", line 1264, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/Flask-0.8-py2.7.egg/flask/app.py", line 1262, in full_dispatch_request
rv = self.dispatch_request()
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/Flask-0.8-py2.7.egg/flask/app.py", line 1248, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/Flask_Login-0.1-py2.7.egg/flaskext/login.py", line 479, in decorated_view
return current_app.login_manager.unauthorized()
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/Flask_Login-0.1-py2.7.egg/flaskext/login.py", line 250, in unauthorized
return self.unauthorized_callback()
File "./test.py", line 34, in unauthorized
raise Exception("Unauthorized.")
Exception: Unauthorized.
我期望的行为是导入(和使用)对 Flask 上下文堆栈没有影响,并且通过扩展,即使已导入testbed
Flask-Login 将继续在单元测试环境中工作。testbed
我已经盯着这个看了一会儿,但无济于事,如果有任何关于这个问题的潜在解决方案的见解和建议,我将不胜感激。
感谢您的阅读。