[英]Testing code that requires a Flask app or request context
在测试中尝试访问session
时,我正在working outside of request context
。 在测试需要上下文的内容时,如何设置上下文?
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()
如果要向应用程序发出请求,请使用test_client
。
c = app.test_client()
response = c.get('/test/url')
# test response
如果要测试使用应用程序上下文( current_app
、 g
、 url_for
)的代码,请推送app_context
。
with app.app_context():
# test your app context code
如果您想要使用请求上下文( request
, session
)的测试代码,请推送test_request_context
。
with current_app.test_request_context():
# test your request context code
应用程序和请求上下文也可以手动推送,这在使用解释器时很有用。
>>> ctx = app.app_context()
>>> ctx.push()
Flask-Script 或新的 Flask cli 将在运行shell
命令时自动推送应用程序上下文。
Flask-Testing
是一个有用的库,它包含用于测试 Flask 应用程序的帮助程序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.