在应用程序上下文之外工作; FlaskClient 对象没有属性 'app_context'

Working outside of application context; FlaskClient object has no attribute 'app_context'

我们通过此测试获得 FlaskClient object has no attribute 'app_context'

app.py:

import logging
from logging.handlers import RotatingFileHandler

from blueprints import default, otherstuff
from global_vars import app, db


def generate_app():
    app.config.from_object('config.flask_config')
    db.init_app(app)


   # registering blueprints
    app.register_blueprint(default.default)
    app.before_request(oauth_package.authenticate_all_requests)
    return app

if __name__ == '__main__':
    flask_app = generate_app()
    flask_app.run(port=5002, debug=True)

testfile.py:

import unittest
import mock
from starter_file import generate_app
import flask
import blueprints


class TestBase(unittest.TestCase):

    def setUp(self):
        # creates a test client
        app = generate_app()
        app.testing = True
        self.app = app.test_client()
        # propagate the exceptions to the test client

    @mock.patch('blueprints.default.get_current_user_role')
    def test_qppage_without_coockie(self,  mocked_get_current_user_role):
        mocked_get_current_user_role.return_value = 'ap'
        with self.app.app_context():
            result = blueprints.default.home()
            print result
            # assert the status code of the response
            self.assertEqual(result.status_code, 302)


if __name__ == '__main__':
    unittest.main()

Runtime error: Working outside of application context 使用此代码:

class TestBase(unittest.TestCase):

    def setUp(self):
        # creates a test client
        app = generate_app()
        app.testing = True
        self.app = app.test_client()
        # propagate the exceptions to the test client

    @mock.patch('blueprints.default.get_current_user_role')
    def test_qppage_without_coockie(self,  mocked_get_current_user_role):
        mocked_get_current_user_role.return_value = 'ap'
        result = blueprints.default.home()
        print result
        # assert the status code of the response
        self.assertEqual(result.status_code, 302)

尝试将此添加到您的测试库中 class:

...

from flask import current_app

...

@classmethod
def setUpClass(cls):
    cls.app = generate_app()


def setUp(self):
    """Set up application for testing."""
    with self.app.app_context():
        self.test_app = current_app.test_client()

# Here goes the rest of your code