| 1 |
import json |
| 2 |
from contextlib import contextmanager |
| 3 |
|
| 4 |
import flask |
| 5 |
from flask_session.mongodb import MongoDBSession |
| 6 |
from itsdangerous import want_bytes |
| 7 |
from pymongo import MongoClient |
| 8 |
|
| 9 |
|
| 10 |
class TestMongoSession: |
| 11 |
"""This requires package: pymongo""" |
| 12 |
|
| 13 |
@contextmanager |
| 14 |
def setup_mongo(self): |
| 15 |
self.client = MongoClient() |
| 16 |
self.db = self.client.flask_session |
| 17 |
self.collection = self.db.sessions |
| 18 |
try: |
| 19 |
self.collection.delete_many({}) |
| 20 |
yield |
| 21 |
finally: |
| 22 |
self.collection.delete_many({}) |
| 23 |
self.client.close() |
| 24 |
|
| 25 |
def retrieve_stored_session(self, key): |
| 26 |
document = self.collection.find_one({"id": key}) |
| 27 |
return want_bytes(document["val"]) |
| 28 |
|
| 29 |
def test_mongo_default(self, app_utils): |
| 30 |
with self.setup_mongo(): |
| 31 |
app = app_utils.create_app( |
| 32 |
{ |
| 33 |
"SESSION_TYPE": "mongodb", |
| 34 |
"SESSION_MONGODB": self.client, |
| 35 |
} |
| 36 |
) |
| 37 |
|
| 38 |
with app.test_request_context(): |
| 39 |
assert isinstance(flask.session, MongoDBSession) |
| 40 |
app_utils.test_session(app) |
| 41 |
|
| 42 |
# Check if the session is stored in MongoDB |
| 43 |
cookie = app_utils.test_session_with_cookie(app) |
| 44 |
session_id = cookie.split(";")[0].split("=")[1] |
| 45 |
byte_string = self.retrieve_stored_session(f"session:{session_id}") |
| 46 |
stored_session = ( |
| 47 |
json.loads(byte_string.decode("utf-8")) if byte_string else {} |
| 48 |
) |
| 49 |
assert stored_session.get("value") == "44" |