【问题标题】:Flask Testing self.app_context.push() not working?烧瓶测试 self.app_context.push() 不起作用?
【发布时间】:2017-09-30 09:45:26
【问题描述】:

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

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

这很奇怪。我认为这可能是与 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')

【问题讨论】:

  • 我遇到了类似的问题,但pytest。在我的情况下,使用with client 会导致 0 条闪烁的消息(当预期为 1 时),而 with app.app_context() 会失败并使用您提到的 AttributeError

标签: flask flask-login


【解决方案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 语句”很重要的原因。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-23
    • 1970-01-01
    • 2020-07-24
    • 1970-01-01
    • 2017-01-11
    • 2019-01-04
    • 2016-09-02
    相关资源
    最近更新 更多