测试需要Flask应用程序或请求上下文的代码 [英] Testing code that requires a Flask app or request context

查看:148
本文介绍了测试需要Flask应用程序或请求上下文的代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当试图在测试中访问 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):$ b $ session ['h'] = 'hello'
return session ['h']
$ b $ class MyUnitTest(unittest.TestCase):
def test_unit(self):
t = tests.Test()
t.hello()


解决方案

要向您的应用程序发出请求,请使用 test_client
$ p code $ app $ test_client
response = c.get( '/ test / url')
#test response

如果你想测试代码使用应用程序con文本( current_app g url_for ), app_context 。测试你的应用上下文代码

$ b $ $ p $ $ $ $

如果您想要使用请求上下文( request , session ),推一个 test_request_context code>

  with current_app.test_request_context():
#测试您的请求上下文代码






应用程序和请求上下文也可以被推送手动,这在使用解释器时很有用。

 >>> ctx = app.app_context()
>>> ctx.push()

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




是一个有用的库,它包含了用于测试Flask应用程序的帮助程序。


I am getting working outside of request context when trying to access session in a test. How can I set up a context when I'm testing something that requires one?

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

解决方案

If you want to make a request to your application, use the test_client.

c = app.test_client()
response = c.get('/test/url')
# test response

If you want to test code which uses an application context (current_app, g, url_for), push an app_context.

with app.app_context():
    # test your app context code

If you want test code which uses a request context (request, session), push a test_request_context.

with current_app.test_request_context():
    # test your request context code


Both app and request contexts can also be pushed manually, which is useful when using the interpreter.

>>> ctx = app.app_context()
>>> ctx.push()

Flask-Script or the new Flask cli will automatically push an app context when running the shell command.


Flask-Testing is a useful library that contains helpers for testing Flask apps.

这篇关于测试需要Flask应用程序或请求上下文的代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆