【问题标题】:Testing code that requires a Flask app or request context测试需要 Flask 应用程序或请求上下文的代码
【发布时间】:2013-06-26 20:30:42
【问题描述】:

我在测试中尝试访问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()

【问题讨论】:

标签: python flask


【解决方案1】:

如果您想向您的应用程序发出请求,请使用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 应用程序的帮助程序。

【讨论】:

  • 是的,我已经用app_app.test_request_context(): 包装了既没有路由也没有与 Flask 相关的函数,这些函数需要请求数据才能工作;)并且确实有效。
  • 不同上下文(测试、应用、请求)的精彩总结。
  • 仅供参考,这里是 app.test_request_context flask.palletsprojects.com/en/1.1.x/api/… 的文档。
  • c.get('/test/url') 会自动创建请求和应用上下文吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-09-06
  • 2014-05-19
  • 2016-03-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多