gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 00:08:24 24 4
gpt4 key购买 nike

通过此测试,我们得到 FlaskClient 对象没有属性“app_context”:

应用程序.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)

测试文件.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()

运行时错误:使用以下代码在应用程序上下文之外工作:

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)

最佳答案

尝试将其添加到您的 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

关于python - 在应用程序上下文之外工作; FlaskClient 对象没有属性 'app_context',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44417552/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com