I am building a tests for my Flask application, in one of the test there is a need to modify a session key (which itself is a list of values), and then check that app behaviour is altered by the modified key content. I'm using an approach from Flask documentation for modifying session
from tests.
Here is an excerpt example code, to demonstrate the problem (I have added print statements, along with what they are printing during test run):
my_app.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)
My questions are:
- Why is this happening?
- What is the proper way to modify
session['list']
from tests?