Flask测试self.app_context.push()无法正常工作?

问题描述 投票:2回答:1

我目前正在测试我的烧瓶应用程序。我有以下测试案例:

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')

我目前正在测试我的烧瓶应用程序。我有以下测试用例:从烧瓶导入unittest从portal.factory导入get_flashed_messages导入create_app类AuthTestConfig(...] >>

问题是您没有像在“ test_push”中那样使用with语句:

with app.test_client() as c:
    rv = c.get('/?vodka=42')
    assert request.args['vodka'] == '42'

app.test_client()与“ with statement”一起使用时将保留请求上下文。

具体来说,app.test_client()将返回FlaskClient的实例,该实例使用一个标志来决定是否在__enter__方法中保留请求上下文。这就是“ with statement”很重要的原因。

flask flask-login
1个回答
1
投票

问题是您没有像在“ test_push”中那样使用with语句:

© www.soinside.com 2019 - 2024. All rights reserved.