[英]Testing code that requires a Flask app or request context
I am getting working outside of request context
when trying to access session
in a test.在测试中尝试访问
session
时,我正在working outside of request context
。 How can I set up a context when I'm testing something that requires one?在测试需要上下文的内容时,如何设置上下文?
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()
If you want to make a request to your application, use thetest_client
.如果要向应用程序发出请求,请使用
test_client
。
c = app.test_client()
response = c.get('/test/url')
# test response
If you want to test code which uses an application context ( current_app
, g
, url_for
), push anapp_context
.如果要测试使用应用程序上下文(
current_app
、 g
、 url_for
)的代码,请推送app_context
。
with app.app_context():
# test your app context code
If you want test code which uses a request context ( request
, session
), push a test_request_context
.如果您想要使用请求上下文(
request
, session
)的测试代码,请推送test_request_context
。
with current_app.test_request_context():
# test your request context code
Both app and request contexts can also be pushed manually, which is useful when using the interpreter.应用程序和请求上下文也可以手动推送,这在使用解释器时很有用。
>>> ctx = app.app_context()
>>> ctx.push()
Flask-Script or the new Flask cli will automatically push an app context when running the shell
command. Flask-Script 或新的 Flask cli 将在运行
shell
命令时自动推送应用程序上下文。
Flask-Testing
is a useful library that contains helpers for testing Flask apps. Flask-Testing
是一个有用的库,它包含用于测试 Flask 应用程序的帮助程序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.