小编典典

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

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()

阅读 473

收藏
2020-04-05

共1个答案

小编典典

如果要向你的应用程序发出请求,请使用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脚本或新的Flask cli将自动推送应用上下文。

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

2020-04-05