测试需要Flask应用或请求上下文的代码


69

我正在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()

Answers:


128

如果要向您的应用程序发出请求,请使用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()

运行shell命令时,Flask脚本或新的Flask cli将自动推送应用上下文。


Flask-Testing 是一个有用的库,其中包含用于测试Flask应用程序的帮助程序。


是的,我包装了与Flask无关的路由或与之相关的功能,这些功能需要请求数据才能起作用;)app_app.test_request_context():并确实起作用。
m3nda

不同环境(测试,应用程序,请求)的摘要。
杰森·斯特林珀

仅供参考,这是app.test_request_context flask.palletsprojects.com/en/1.1.x/api/…的文档。
尼科·切尔尼克

c.get('/ test / url')是否自动创建请求和应用程序上下文?
变量
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.