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

发布于 2021-01-29 14:55:32

我正在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()
关注者
0
被浏览
161
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

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


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



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看