我正在为我的 Flask 应用程序构建一个测试,在其中一个测试中需要修改一个会话密钥(它本身是一个值列表),然后检查应用程序行为是否被修改后的密钥内容改变。我正在使用Flask 文档中的一种方法来修改session
测试。
这是一个示例代码摘录,用于演示问题(我添加了打印语句,以及它们在测试运行期间打印的内容):
我的应用程序.py
from flask import (
Flask,
session,
)
app = Flask(__name__)
app.secret_key = 'bad secret key'
@app.route('/create_list/', methods=['POST'])
def create_list():
session['list'] = ['1', '2']
return "List created!"
@app.route('/in_list/')
def in_list():
print(str(session['list'])) # ['1', '2'], but why?
if '3' in session['list']:
return "session['list'] contains '3'!"
else:
return "Oy vey! '3' is not in the session['list']"
test_my_app.py
import flask
from unittest import TestCase
import my_app
class TestApp(TestCase):
def setUp(self):
self.test_client = my_app.app.test_client()
self.test_client.post('/create_list/')
def testAppendList(self):
with self.test_client as client:
with client.session_transaction() as sess:
sess['list'].append('3')
print(str(sess['list'])) # ['1', '2', '3'], as expected
response = client.get('/in_list/')
expected_response = "session['list'] contains '3'!".encode('ascii')
self.assertTrue(expected_response == response.data)
我的问题是:
- 为什么会这样?
session['list']
从测试中修改的正确方法是什么?