我当前正在测试烧瓶应用程序。我有以下测试用例:
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_with在test_push失败时通过:
$ 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
这很奇怪。我认为这可能是与烧瓶 - login有关的问题,但似乎并没有。
为什么会发生这种情况?
user_views.pys.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')
问题是您没有像这样的" test_push"中使用语句:
with app.test_client() as c:
rv = c.get('/?vodka=42')
assert request.args['vodka'] == '42'
app.test_client()
将与"有关语句"一起使用时保留请求上下文。
是特定的,app.test_client()
将返回FlaskClient
的实例,该实例使用标志来决定Wheather在__enter__
方法中保留请求上下文。这就是为什么" with语句"很重要。