簡體   English   中英

測試需要 Flask 應用程序或請求上下文的代碼

[英]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_appgurl_for )的代碼,請推送app_context

with app.app_context():
    # test your app context code

如果您想要使用請求上下文( requestsession )的測試代碼,請推送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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM