| 1 |
import json |
| 2 |
from contextlib import contextmanager |
| 3 |
|
| 4 |
import flask |
| 5 |
from flask_session.redis import RedisSession |
| 6 |
from redis import Redis |
| 7 |
|
| 8 |
|
| 9 |
class TestRedisSession: |
| 10 |
"""This requires package: redis""" |
| 11 |
|
| 12 |
@contextmanager |
| 13 |
def setup_redis(self): |
| 14 |
self.r = Redis() |
| 15 |
try: |
| 16 |
self.r.flushall() |
| 17 |
yield |
| 18 |
finally: |
| 19 |
self.r.flushall() |
| 20 |
self.r.close() |
| 21 |
|
| 22 |
def retrieve_stored_session(self, key): |
| 23 |
return self.r.get(key) |
| 24 |
|
| 25 |
def test_redis_default(self, app_utils): |
| 26 |
with self.setup_redis(): |
| 27 |
app = app_utils.create_app( |
| 28 |
{"SESSION_TYPE": "redis", "SESSION_REDIS": self.r} |
| 29 |
) |
| 30 |
|
| 31 |
with app.test_request_context(): |
| 32 |
assert isinstance(flask.session, RedisSession) |
| 33 |
app_utils.test_session(app) |
| 34 |
|
| 35 |
# Check if the session is stored in Redis |
| 36 |
cookie = app_utils.test_session_with_cookie(app) |
| 37 |
session_id = cookie.split(";")[0].split("=")[1] |
| 38 |
byte_string = self.retrieve_stored_session(f"session:{session_id}") |
| 39 |
stored_session = ( |
| 40 |
json.loads(byte_string.decode("utf-8")) if byte_string else {} |
| 41 |
) |
| 42 |
assert stored_session.get("value") == "44" |