Skip to content

Commit

Permalink
refactor: add use_mock parameter to MongoModule constructor
Browse files Browse the repository at this point in the history
  • Loading branch information
wderocco8 committed Jul 14, 2024
1 parent 4101076 commit 6b806d1
Show file tree
Hide file tree
Showing 3 changed files with 74 additions and 43 deletions.
13 changes: 7 additions & 6 deletions chalicelib/modules/mongo.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ class MongoModule:

def __init__(self, use_mock=False):
"""Establishes connection to MongoDB server"""
# if use_mock is true -> use monogmock to execute tests with fake db
self.use_mock = use_mock
if use_mock:
self.mongo_client = mongomock.MongoClient()
Expand All @@ -28,17 +29,17 @@ def __init__(self, use_mock=False):
self.mongo_client = MongoClient(self.uri)

def add_env_suffix(func):
def wrapper(self, collection_name: str, *args, **kwargs):
def wrapper(self, collection: str, *args, **kwargs):
# users collection is dependent on vault so suffix should not be appended
if collection_name == "users":
return func(self, collection_name, *args, **kwargs)
if collection == "users":
return func(self, collection, *args, **kwargs)

if self.is_prod:
collection_name += "-prod"
collection += "-prod"
else:
collection_name += "-dev"
collection += "-dev"

return func(self, collection_name, *args, **kwargs)
return func(self, collection, *args, **kwargs)

return wrapper

Expand Down
74 changes: 37 additions & 37 deletions chalicelib/services/EventService.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@
import datetime
from chalicelib.modules.google_sheets import GoogleSheetsModule
from chalicelib.modules.ses import ses, SesDestination
from typing import Optional


class EventService:
class BSONEncoder(json.JSONEncoder):
Expand All @@ -19,33 +17,35 @@ def default(self, o):
return str(o)
return super().default(o)

def __init__(self):
def __init__(self, mongo_module=mongo_module):
self.mongo_module = mongo_module
self.collection_prefix = "events-"

def create_timeframe(self, timeframe_data: dict):
timeframe_data["dateCreated"] = datetime.datetime.now()
mongo_module.insert_document(
f"{self.collection_prefix}timeframe", timeframe_data
self.mongo_module.insert_document(
collection=f"{self.collection_prefix}timeframe", data=timeframe_data
)
return {"msg": True}

def get_timeframe(self, timeframe_id: str):
timeframe = mongo_module.get_document_by_id(
timeframe = self.mongo_module.get_document_by_id(
f"{self.collection_prefix}timeframe", timeframe_id
)

return json.dumps(timeframe, cls=self.BSONEncoder)

def get_all_timeframes(self):
"""Retrieve all timeframes from the database."""
timeframes = mongo_module.get_all_data_from_collection(
timeframes = self.mongo_module.get_all_data_from_collection(
f"{self.collection_prefix}timeframe"
)

return json.dumps(timeframes, cls=self.BSONEncoder)

def delete_timeframe(self, timeframe_id: str):
# Check if timeframe exists and if it doesn't return errors
timeframe = mongo_module.get_document_by_id(
timeframe = self.mongo_module.get_document_by_id(
f"{self.collection_prefix}timeframe", timeframe_id
)

Expand All @@ -57,12 +57,12 @@ def delete_timeframe(self, timeframe_id: str):

# Delete all the events in the timeframe
for event_id in event_ids:
mongo_module.delete_document_by_id(
self.mongo_module.delete_document_by_id(
f"{self.collection_prefix}event", event_id
)

# If timeframe exists, delete the timeframe document
mongo_module.delete_document_by_id(
self.mongo_module.delete_document_by_id(
f"{self.collection_prefix}timeframe", timeframe_id
)

Expand All @@ -72,7 +72,7 @@ def create_event(self, timeframe_id: str, event_data: dict):
event_data["usersAttended"] = []

# Get Google Spreadsheet ID from timeframe
timeframe_doc = mongo_module.get_document_by_id(
timeframe_doc = self.mongo_module.get_document_by_id(
f"{self.collection_prefix}timeframe", timeframe_id
)
spreadsheet_id = timeframe_doc["spreadsheetId"]
Expand All @@ -86,14 +86,14 @@ def create_event(self, timeframe_id: str, event_data: dict):
event_data["spreadsheetCol"] = col

# Insert the event in event collection
event_id = mongo_module.insert_document(
event_id = self.mongo_module.insert_document(
f"{self.collection_prefix}event", event_data
)

event_data["eventId"] = str(event_id)

# Insert child event in timeframe collection
mongo_module.update_document(
self.mongo_module.update_document(
f"{self.collection_prefix}timeframe",
timeframe_id,
{"$push": {"events": event_data}},
Expand All @@ -102,7 +102,7 @@ def create_event(self, timeframe_id: str, event_data: dict):
return json.dumps(event_data, cls=self.BSONEncoder)

def get_event(self, event_id: str):
event = mongo_module.get_document_by_id(
event = self.mongo_module.get_document_by_id(
f"{self.collection_prefix}event", event_id
)

Expand All @@ -119,13 +119,13 @@ def checkin(self, event_id: str, user: dict) -> dict:
dict -- Dictionary containing status and message.
"""
user_id, user_email = user["id"], user["email"]
member = mongo_module.get_document_by_id(f"users", user_id)
member = self.mongo_module.get_document_by_id(f"users", user_id)
if member is None:
raise NotFoundError(f"User with ID {user_id} does not exist.")

user_name = member["name"]

event = mongo_module.get_document_by_id(
event = self.mongo_module.get_document_by_id(
f"{self.collection_prefix}event", event_id
)

Expand All @@ -139,7 +139,7 @@ def checkin(self, event_id: str, user: dict) -> dict:
}

# Get timeframe document to get Google Sheets info
timeframe = mongo_module.get_document_by_id(
timeframe = self.mongo_module.get_document_by_id(
f"{self.collection_prefix}timeframe", event["timeframeId"]
)

Expand Down Expand Up @@ -173,7 +173,7 @@ def checkin(self, event_id: str, user: dict) -> dict:
)

# Update event collection with checkin data
mongo_module.update_document(
self.mongo_module.update_document(
f"{self.collection_prefix}event",
event_id,
{"$push": {"usersAttended": checkin_data}},
Expand Down Expand Up @@ -207,7 +207,7 @@ def checkin(self, event_id: str, user: dict) -> dict:

def delete(self, event_id: str):
# Check if event exists and if it doesn't return errors
event = mongo_module.get_document_by_id(
event = self.mongo_module.get_document_by_id(
f"{self.collection_prefix}event", event_id
)

Expand All @@ -218,17 +218,17 @@ def delete(self, event_id: str):
timeframe_id = event["timeframeId"]

# Remove event from timeframe
mongo_module.update_document(
self.mongo_module.update_document(
f"{self.collection_prefix}timeframe",
timeframe_id,
{"$pull": {"events": {"_id": ObjectId(event_id)}}},
)

# Delete the event document
mongo_module.delete_document_by_id(f"{self.collection_prefix}event", event_id)
self.mongo_module.delete_document_by_id(f"{self.collection_prefix}event", event_id)

def get_timeframe_sheets(self, timeframe_id: str):
timeframe = mongo_module.get_document_by_id(
timeframe = self.mongo_module.get_document_by_id(
f"{self.collection_prefix}timeframe", timeframe_id
)

Expand All @@ -240,7 +240,7 @@ def get_timeframe_sheets(self, timeframe_id: str):
return [sheet["title"] for sheet in sheets]

def get_rush_categories_and_events(self):
rush_categories = mongo_module.get_all_data_from_collection(
rush_categories = self.mongo_module.get_all_data_from_collection(
f"{self.collection_prefix}rush"
)

Expand All @@ -249,7 +249,7 @@ def get_rush_categories_and_events(self):
def create_rush_category(self, data: dict):
data["dateCreated"] = datetime.datetime.now()
data["events"] = []
mongo_module.insert_document(f"{self.collection_prefix}rush", data)
self.mongo_module.insert_document(f"{self.collection_prefix}rush", data)
return

def create_rush_event(self, data: dict):
Expand All @@ -262,14 +262,14 @@ def create_rush_event(self, data: dict):
# Add event to its own collection
data["attendees"] = []
data["numAttendees"] = 0
event_id = mongo_module.insert_document(
event_id = self.mongo_module.insert_document(
f"{self.collection_prefix}rush-event", data
)

data_copy["eventId"] = str(event_id)

# Add event to rush category
mongo_module.update_document(
self.mongo_module.update_document(
f"{self.collection_prefix}rush",
data["categoryId"],
{"$push": {"events": data_copy}},
Expand All @@ -285,7 +285,7 @@ def modify_rush_event(self, data: dict):
eventId = data["eventId"]

# Check if event exists in the rush-event collection
event = mongo_module.get_document_by_id(
event = self.mongo_module.get_document_by_id(
f"{self.collection_prefix}rush-event", eventId
)

Expand All @@ -312,15 +312,15 @@ def modify_rush_event(self, data: dict):
]

# Modify the event in its category (rush collection)
mongo_module.update_document(
self.mongo_module.update_document(
f"{self.collection_prefix}rush",
event_category_id,
update_query,
array_filters=array_filters
)

# Modify actual event document (rush-event collection)
mongo_module.update_document(
self.mongo_module.update_document(
f"{self.collection_prefix}rush-event",
eventId,
{"$set": data},
Expand Down Expand Up @@ -351,7 +351,7 @@ def modify_rush_settings(self, data: dict):
collection = f"{self.collection_prefix}rush"

# Set all defaultRushCategory fields to false
mongo_module.update_many_documents(
self.mongo_module.update_many_documents(
collection,
{},
{"$set": {"defaultRushCategory": False}}
Expand All @@ -362,7 +362,7 @@ def modify_rush_settings(self, data: dict):
return

# Update the specified document to set its defaultRushCategory to true
result = mongo_module.update_document_by_id(
result = self.mongo_module.update_document_by_id(
collection,
default_rush_category_id,
{"defaultRushCategory": True}
Expand All @@ -374,7 +374,7 @@ def modify_rush_settings(self, data: dict):
return

def get_rush_event(self, event_id: str, hide_attendees: bool = True):
event = mongo_module.get_document_by_id(
event = self.mongo_module.get_document_by_id(
f"{self.collection_prefix}rush-event", event_id
)

Expand All @@ -387,7 +387,7 @@ def get_rush_event(self, event_id: str, hide_attendees: bool = True):
return json.dumps(event, cls=self.BSONEncoder)

def checkin_rush(self, event_id: str, user_data: dict):
event = mongo_module.get_document_by_id(
event = self.mongo_module.get_document_by_id(
f"{self.collection_prefix}rush-event", event_id
)

Expand All @@ -404,7 +404,7 @@ def checkin_rush(self, event_id: str, user_data: dict):
event["attendees"].append(user_data)
event["numAttendees"] += 1

mongo_module.update_document(
self.mongo_module.update_document(
f"{self.collection_prefix}rush-event",
event_id,
{"$set": event},
Expand All @@ -428,7 +428,7 @@ def delete_rush_event(self, event_id: str):
"""
try:
# Check if event exists in the rush-event collection
event = mongo_module.get_document_by_id(
event = self.mongo_module.get_document_by_id(
f"{self.collection_prefix}rush-event", event_id
)

Expand All @@ -438,14 +438,14 @@ def delete_rush_event(self, event_id: str):
event_category_id = event["categoryId"]

# Delete the event from its category
mongo_module.update_document(
self.mongo_module.update_document(
f"{self.collection_prefix}rush",
event_category_id,
{"$pull": {"events": {"eventId": event_id}}},
)

# Delete event data from the rush-event collection
mongo_module.delete_document_by_id(
self.mongo_module.delete_document_by_id(
f"{self.collection_prefix}rush-event", event_id
)
return
Expand Down
30 changes: 30 additions & 0 deletions tests/services/test_event_service.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import pytest
from unittest.mock import MagicMock, patch
from chalicelib.services.EventService import EventService
import datetime


@pytest.fixture
def mock_mongo_module():
with patch("chalicelib.modules.mongo.MongoModule", autospec=True) as MockMongoModule:
mock_instance = MockMongoModule(use_mock=True)
yield mock_instance

@pytest.fixture
def event_service(mock_mongo_module):
return EventService(mock_mongo_module)


def test_insert_document(event_service, mock_mongo_module):
CREATE_TIMEFRAME = { "name": "testTimeframeName", "spreadsheetId": "testSpreadsheetId" }
dateCreated = datetime.datetime.now()

with patch("chalicelib.services.EventService.datetime") as mock_datetime:
mock_datetime.datetime.now.return_value = dateCreated
result = event_service.create_timeframe(CREATE_TIMEFRAME)
CREATE_TIMEFRAME["dateCreated"] = dateCreated
mock_mongo_module.insert_document.assert_called_once_with(
collection="events-timeframe", data=CREATE_TIMEFRAME
)

assert result == {"msg": True}

0 comments on commit 6b806d1

Please sign in to comment.