[英]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.