测试需要Flask应用程序或请求上下文的代码 [英] Testing code that requires a Flask app or 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):$ b $ session ['h'] = 'hello'
return session ['h']
$ b $ class MyUnitTest(unittest.TestCase):
def test_unit(self):
t = tests.Test()
t.hello()
要向您的应用程序发出请求,请使用 如果你想测试代码使用应用程序con文本( 如果您想要使用请求上下文( 应用程序和请求上下文也可以被推送手动,这在使用解释器时很有用。 Flask-Script或新的Flask cli将在运行时自动推送应用程序上下文 是一个有用的库,它包含了用于测试Flask应用程序的帮助程序。 I am getting
If you want to make a request to your application, use the If you want to test code which uses an application context ( If you want test code which uses a request context (
Both app and request contexts can also be pushed manually, which is useful when using the interpreter. Flask-Script or the new Flask cli will automatically push an app context when running the 这篇关于测试需要Flask应用程序或请求上下文的代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! test_client $
$ p code $ app $ test_client
response = c.get( '/ test / url')
#test response
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()
shell
命令。
$ b
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()
test_client
.c = app.test_client()
response = c.get('/test/url')
# test response
current_app
, g
, url_for
), push an app_context
.with app.app_context():
# test your app context code
request
, session
), push a test_request_context
.with current_app.test_request_context():
# test your request context code
>>> ctx = app.app_context()
>>> ctx.push()
shell
command.
Flask-Testing
is a useful library that contains helpers for testing Flask apps.