测试需要Flask应用或请求上下文的代码
我正在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()
-
如果要向您的应用程序发出请求,请使用
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()
运行
shell
命令时,Flask-Script或新的Flask cli将自动推送应用上下文。
Flask-Testing
是一个有用的库,其中包含用于测试Flask应用程序的帮助程序。