我们正在通过此测试获得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)
答案 0 :(得分:1)
尝试在TestBase类中添加它:
...
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