我正在测试我的烧瓶应用程序。我有以下测试用例:
import unittest
from flask import get_flashed_messages
from portal.factory import create_app
class AuthTestConfig(object):
SQLALCHEMY_TRACK_MODIFICATIONS = False
TESTING = True
LOGIN_DISABLED = False
SERVER_NAME = 'Testing'
SECRET_KEY = 'secret'
DEBUG = True
SQLALCHEMY_DATABASE_URI = 'sqlite:///:memory:'
class DebugTestCase(unittest.TestCase):
def setUp(self):
self.app = create_app(AuthTestConfig)
self.client = self.app.test_client(use_cookies=True)
def test_with(self):
with self.client:
r = self.client.get('/user/member/')
ms = get_flashed_messages()
assert len(ms) == 1
assert ms[0].startswith('You must be signed in to access ')
def test_push(self):
self.app_context = self.app.app_context()
self.app_context.push()
r = self.client.get('/user/member/')
ms = get_flashed_messages()
assert len(ms) == 1
assert ms[0].startswith('You must be signed in to access ')
当test_push失败时,test_with传递:
$ python -m unittest discover
E.
======================================================================
ERROR: test_push (testing.test_debug.DebugTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
File "testing/test_debug.py", line 37, in test_push
ms = get_flashed_messages()
File "/Users/vng/.virtualenvs/portal/lib/python2.7/site-packages/flask/helpers.py", line 420, in get_flashed_messages
flashes = _request_ctx_stack.top.flashes
AttributeError: 'NoneType' object has no attribute 'flashes'
----------------------------------------------------------------------
Ran 2 tests in 0.033s
这很奇怪。我认为这可能是与Flask-Login相关的问题,但它看起来并不像。
user_views.py
的源代码from flask_user import current_user, login_required, roles_accepted
@user_blueprint.route('/member')
@login_required
def member_page():
if current_user.has_role('admin'):
return redirect('/admin')
return render_template('/user/member_page.html')
答案 0 :(得分:1)
问题是您没有像这样在“ test_push”中使用with语句:
with app.test_client() as c:
rv = c.get('/?vodka=42')
assert request.args['vodka'] == '42'
app.test_client()
与“ with语句”一起使用时将保留请求上下文。
具体来说,app.test_client()
将返回FlaskClient
的实例,该实例使用一个标志来决定是否在__enter__
方法中保留请求上下文。这就是为什么“ with statement”很重要。