我正试着用nose测试下面的代码。app.py文件如下:
from flask import Flask, session, redirect, url_for, request
app = Flask(__name__)
@app.route('/')
def index():
session['key'] = 'value'
print('>>>> session:', session)
return redirect(url_for("game"))
测试文件如下:
from nose.tools import *
from flask import session
from app import app
app.config['TESTING'] = True
web = app.test_client()
def test_index():
with app.test_request_context('/'):
print('>>>>test session:', session)
assert_equal(session.get('key'), 'value')
当我运行测试文件时,我得到一个断言错误
None != 'value'
测试文件中的print语句打印空会话对象。此外,app.py文件中的print语句不会打印任何内容。这是否意味着索引函数没有运行?
为什么会这样?根据烧瓶文件(
http://flask.pocoo.org/docs/1.0/testing/#other-testing-tricks
)
我应该可以通过test_request_context()访问会话内容。
另外,如果我像这样编写test_index函数,测试也会正常工作(app.py和测试文件中的print语句都会执行):
def test_index():
with app.test_client() as c:
rv = c.get('/')
print('>>>>test session:', session)
assert_equal(session.get('key'), 'value')
在“with”语句中使用flask.test_client()和flask.test_request_上下文有什么区别?据我所知,两者的重点都是让请求上下文保持更长的时间。