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

Cor*_*ory 48 python 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()
Run Code Online (Sandbox Code Playgroud)

tbi*_*icr 99

如果您想向您的应用程序发出请求,请使用test_client.

c = app.test_client()
response = c.get('/test/url')
# test response
Run Code Online (Sandbox Code Playgroud)

如果你想测试它使用一个应用程序上下文代码(current_app,g,url_for),推送app_context.

with app.app_context():
    # test your app context code
Run Code Online (Sandbox Code Playgroud)

如果您想要使用请求上下文(request,session)的测试代码,请按a test_request_context.

with current_app.test_request_context():
    # test your request context code
Run Code Online (Sandbox Code Playgroud)

app和request上下文也可以手动推送,这在使用解释器时很有用.

>>> ctx = app.app_context()
>>> ctx.push()
Run Code Online (Sandbox Code Playgroud)

Flask-Script或新的Flask cli将在运行shell命令时自动推送应用程序上下文.


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