Python 测试需要 Flask 应用程序或请求上下文的代码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17375340/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Testing code that requires a Flask app or request context
提问by Cory
I am getting working outside of request context
when trying to access session
in a test. How can I set up a context when I'm testing something that requires one?
我在测试中working outside of request context
尝试访问时遇到session
了问题。在测试需要上下文的内容时,如何设置上下文?
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()
采纳答案by tbicr
If you want to make a request to your application, use the test_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 an app_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 应用程序的帮助程序。