Flask Testing self.app_context.push() not working?

旧时模样 提交于 2019-12-07 22:56:39

问题


I am currently testing my flask application. I have the following test cases:

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 passes while test_push is failing:

$ 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

This is very weird. I thought this might an issue related to Flask-Login but it doesn't seem like it.

Why is this happening?

Source code for 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')

来源:https://stackoverflow.com/questions/46501549/flask-testing-self-app-context-push-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!