Python 测试需要Flask应用程序或请求上下文的代码
在测试中尝试访问会话时,我在请求上下文之外工作。当我测试需要上下文的东西时,如何设置上下文Python 测试需要Flask应用程序或请求上下文的代码,python,flask,Python,Flask,在测试中尝试访问会话时,我在请求上下文之外工作。当我测试需要上下文的东西时,如何设置上下文 import unittest from flask import Flask, session app = Flask(__name__) @app.route('/') def hello_world(): t = Test() hello = t.hello() return hello class Test: def hello(self):
import unittest
from flask import Flask, session
app = Flask(__name__)
@app.route('/')
def hello_world():
t = Test()
hello = t.hello()
return hello
class Test:
def hello(self):
session['h'] = 'hello'
return session['h']
class MyUnitTest(unittest.TestCase):
def test_unit(self):
t = tests.Test()
t.hello()
如果要向应用程序发出请求,请使用 如果要测试使用应用程序上下文的代码(
current\u app
,g
,url\u for
),请按
如果您想要使用请求上下文(请求
,会话
)的测试代码,请按
应用程序和请求上下文也可以手动推送,这在使用解释器时非常有用
>>> ctx = app.app_context()
>>> ctx.push()
运行shell
命令时,Flask脚本或新的Flask cli将自动推送应用程序上下文
是一个有用的库,其中包含用于测试Flask应用程序的帮助程序。是的,我已经包装了与Flask无关的函数,这些函数需要请求数据才能工作;)使用
app\u-app.test\u-request\u-context():
确实有效。不同上下文(测试、应用程序、请求)的精彩总结。仅供参考,以下是app.test\u-request\u-context
的文档。c.get('/test/url')是否自动创建请求和应用程序上下文?
with app.app_context():
# test your app context code
with current_app.test_request_context():
# test your request context code
>>> ctx = app.app_context()
>>> ctx.push()