-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdata_fetcher_test.py
More file actions
361 lines (298 loc) · 13.8 KB
/
data_fetcher_test.py
File metadata and controls
361 lines (298 loc) · 13.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
#############################################################################
# data_fetcher_test.py
#
# Unit tests for data_fetcher.py
#
# This section tests only the My Groups module.
# Teammates can add their own test classes below for other modules.
#############################################################################
import unittest
from unittest.mock import patch, MagicMock
from google.cloud import bigquery
from data_fetcher import get_my_groups, get_nearby_groups, get_study_group_recommendations, get_user_identity_data
#############################################################################
# MY GROUPS MODULE TESTS
#############################################################################
class TestMyGroupsDataFetcher(unittest.TestCase):
def test_foo(self):
"""Tests foo."""
pass
@patch("data_fetcher._run_query")
def test_get_my_groups_formats_result_for_ui(self, mock_run_query):
"""Tests that get_my_groups formats database rows for the My Groups UI."""
mock_run_query.return_value = [
{
"group_id": "group-uuid-1",
"title": "GenAI & Systems Design",
"subject": "Computer Science",
"mode": "hybrid",
"location": "Fisk Library, Room 12",
"capacity": 8,
"day_of_week": "Tue",
"start_time": "17:00",
"end_time": "19:00",
"active_members": 2,
}
]
result = get_my_groups("user-uuid-1")
self.assertEqual(len(result), 1)
self.assertEqual(result[0]["group_id"], "group-uuid-1")
self.assertEqual(result[0]["title"], "GenAI & Systems Design")
self.assertEqual(result[0]["icon"], "💻")
self.assertEqual(result[0]["days"], "Tue 17:00-19:00")
self.assertEqual(result[0]["mode"], "hybrid")
self.assertEqual(result[0]["location"], "Fisk Library, Room 12")
self.assertEqual(result[0]["members"], "2/8")
@patch("data_fetcher._run_query")
def test_get_my_groups_returns_empty_list_when_no_groups(self, mock_run_query):
"""Tests that get_my_groups returns an empty list when the user has no groups."""
mock_run_query.return_value = []
result = get_my_groups("missing-user")
self.assertEqual(result, [])
@patch("data_fetcher._run_query")
def test_get_my_groups_handles_missing_schedule_fields(self, mock_run_query):
"""Tests that get_my_groups still works when schedule fields are missing."""
mock_run_query.return_value = [
{
"group_id": "group-uuid-2",
"title": "Calc II Cram",
"subject": "Mathematics",
"mode": "in-person",
"location": "Math Building, Room 3",
"capacity": 6,
"day_of_week": None,
"start_time": None,
"end_time": None,
"active_members": 1,
}
]
result = get_my_groups("user-uuid-2")
self.assertEqual(len(result), 1)
self.assertEqual(result[0]["icon"], "📐")
self.assertEqual(result[0]["days"], "TBD")
self.assertEqual(result[0]["members"], "1/6")
#############################################################################
# GET NEARBY GROUPS TESTS
#
# Add additional test classes below this section for other modules.
#############################################################################
class TestExplorePage(unittest.TestCase):
@patch("data_fetcher._run_query") # patch the function that runs the query
@patch("data_fetcher._get_group_schedule") # patch schedule fetch
def test_get_nearby_groups(self, mock_get_schedule, mock_run_query):
mock_run_query.return_value = [
{
"id": "group-1",
"name": "AI Study Group",
"subject": "Computer Science",
"location_text": "Library",
"description": "Learn AI",
"capacity": 5,
"distance_meters": 100.0,
"schedule": [{"day_of_week": "Mon", "start_time": "10:00 AM"}]
}
]
mock_get_schedule.return_value = [{
"id": "group-1",
"name": "AI Study Group",
"subject": "Computer Science",
"location_text": "Library",
"description": "Learn AI",
"capacity": 5,
"distance_meters": 100.0,
"schedule": [{"day_of_week": "Mon", "start_time": "10:00 AM"}]
}]
result = get_nearby_groups(
user_id="user-1",
search="AI",
filter=["Computer Science"],
lon=-65.83,
lat=18.38
)
# --- Assertions ---
assert len(result) == 1
assert result[0]["name"] == "AI Study Group"
# --- Check params passed ---
# _run_query was called once
assert mock_run_query.called
# params are the second positional argument
called_params = mock_run_query.call_args[0][1]
search_param = next((p for p in called_params if p.name == "search"), None)
filter_param = next((p for p in called_params if p.name == "filter"), None)
assert search_param.value == "AI"
assert filter_param.values == ["Computer Science"]
#############################################################################
# USER PROFILE MODULE TESTS
#############################################################################
from data_fetcher import get_user_profile
class TestGetUserProfile(unittest.TestCase):
@patch("data_fetcher._run_query")
def test_returns_correct_name(self, mock_run_query):
"""Tests that get_user_profile maps first_name and last_name correctly."""
mock_run_query.side_effect = [
[{
"first_name": "Jane",
"last_name": "Doe",
"major": "Computer Science",
"education_level": "Junior Year",
"institution": "Stanford University",
"email": "jane.doe@stanford.edu",
"about_me": "Loves algorithms.",
"preferences": '{"focus_subjects": ["Data Structures", "Machine Learning"], "study_hours": 127, "day_streak": 12}',
"availability": '[{"day": "Mon", "slots": ["9-11 AM"]}, {"day": "Tue", "slots": ["1-3 PM"]}]',
"groups_joined": 4
}],
]
result = get_user_profile("user-uuid-1")
self.assertEqual(result["first_name"], "Jane")
self.assertEqual(result["last_name"], "Doe")
@patch("data_fetcher._run_query")
def test_returns_correct_stats(self, mock_run_query):
"""Tests that study_hours, day_streak, and groups_joined are mapped correctly."""
mock_run_query.side_effect = [
[{
"first_name": "Jane",
"last_name": "Doe",
"major": "Computer Science",
"education_level": "Junior Year",
"institution": "Stanford University",
"email": "jane.doe@stanford.edu",
"about_me": "Loves algorithms.",
"preferences": '{"focus_subjects": ["Data Structures"], "study_hours": 127, "day_streak": 12}',
"availability": '[]',
"groups_joined": 4
}],
]
result = get_user_profile("user-uuid-1")
self.assertEqual(result["study_hours"], 127)
self.assertEqual(result["day_streak"], 12)
self.assertEqual(result["groups_joined"], 4)
@patch("data_fetcher._run_query")
def test_returns_focus_subjects(self, mock_run_query):
"""Tests that focus_subjects is parsed from the preferences JSON field."""
mock_run_query.side_effect = [
[{
"first_name": "Jane",
"last_name": "Doe",
"major": "Computer Science",
"education_level": "Junior Year",
"institution": "Stanford University",
"email": "jane.doe@stanford.edu",
"about_me": "",
"preferences": '{"focus_subjects": ["Data Structures", "Machine Learning"], "study_hours": 0, "day_streak": 0}',
"availability": '[]',
"groups_joined": 2
}],
]
result = get_user_profile("user-uuid-1")
self.assertIn("Data Structures", result["focus_subjects"])
self.assertIn("Machine Learning", result["focus_subjects"])
@patch("data_fetcher._run_query")
def test_returns_none_when_user_not_found(self, mock_run_query):
"""Tests that get_user_profile returns None when no user matches the ID."""
mock_run_query.side_effect = [
[], # no user row
]
result = get_user_profile("nonexistent-id")
self.assertIsNone(result)
@patch("data_fetcher._run_query")
def test_weekly_availability_is_a_list(self, mock_run_query):
"""Tests that weekly_availability is returned as a list of day/slot dicts."""
mock_run_query.side_effect = [
[{
"first_name": "Jane",
"last_name": "Doe",
"major": "Computer Science",
"education_level": "Junior Year",
"institution": "Stanford University",
"email": "jane.doe@stanford.edu",
"about_me": "",
"preferences": '{"focus_subjects": [], "study_hours": 0, "day_streak": 0}',
"availability": '[{"day": "Mon", "slots": ["9-11 AM", "2-4 PM"]}, {"day": "Tue", "slots": ["1-3 PM"]}]',
"groups_joined": 1
}],
]
result = get_user_profile("user-uuid-1")
self.assertIsInstance(result["weekly_availability"], list)
self.assertTrue(any(d["day"] == "Mon" for d in result["weekly_availability"]))
@patch("data_fetcher._run_query")
def test_handles_missing_preferences_gracefully(self, mock_run_query):
"""Tests that get_user_profile still returns a valid dict when preferences is None."""
mock_run_query.side_effect = [
[{
"first_name": "Alex",
"last_name": "Kim",
"major": "Mathematics",
"education_level": "Sophomore Year",
"institution": "MIT",
"email": "alex@mit.edu",
"about_me": "",
"preferences": None,
"availability": None,
}],
[{"groups_joined": 0}],
]
result = get_user_profile("user-uuid-2")
self.assertEqual(result["focus_subjects"], [])
self.assertEqual(result["weekly_availability"], [])
self.assertEqual(result["study_hours"], 0)
self.assertEqual(result["day_streak"], 0)
#############################################################################
# GEN-AI-RECOMMENDATION MODULE TESTS
#############################################################################
class TestDataFetcher(unittest.TestCase):
@patch('google.cloud.bigquery.Client')
def test_get_study_group_recommendations(self, mock_bq_client):
class DummyRow:
def __init__(self, **kwargs):
self.__dict__.update(kwargs) # kwargs: take any number of keyword arguments and bundle them into a dictionary
dummy_results = [
DummyRow(
group_id="group_123",
subject="COMPUTER SCIENCE",
group_name="GenAI & Systems Design",
match_pct=0.98,
features=["Algorithms", "Python"],
day_of_week="Tuesday",
start_time="5:00 PM",
location_text="Fisk Library",
current_members=3,
capacity=5
)
]
mock_query_job = MagicMock()
mock_query_job.result.return_value = dummy_results
mock_client_instance = MagicMock()
mock_client_instance.query.return_value = mock_query_job
mock_bq_client.return_value = mock_client_instance
result = get_study_group_recommendations("user_99")
self.assertEqual(len(result), 1)
self.assertEqual(result[0]["match_pct"], 98)
self.assertEqual(result[0]["time"], "Tuesdays 5:00 PM")
self.assertEqual(result[0]["members"], "3/5")
self.assertEqual(result[0]["title"], "GenAI & Systems Design")
self.assertEqual(result[0]["major"], "COMPUTER SCIENCE")
self.assertEqual(result[0]["location"], "Fisk Library")
self.assertEqual(result[0]["keywords"], ["Algorithms", "Python"])
#############################################################################
# Account Settings Data Fetcher Tests
#############################################################################
class TestAccountSettingsDataFetcher(unittest.TestCase):
@patch('google.cloud.bigquery.Client')
def test_get_user_identity_data_success(self, mock_client):
# Create a fake row
mock_row = MagicMock()
mock_row.to_dict.return_value = {"id": "user-123", "email": "test@fisk.edu"}
# Mock results.empty = False and results.iloc[0] = mock_row
mock_df = MagicMock()
mock_df.empty = False
mock_df.iloc.__getitem__.return_value = mock_row
# Chain: client.query().to_dataframe() -> mock_df
mock_job = MagicMock()
mock_job.to_dataframe.return_value = mock_df
mock_client.return_value.query.return_value = mock_job
# Now 'result' will be the dict, not None
result = get_user_identity_data("user-123")
self.assertEqual(result["id"], "user-123")
if __name__ == "__main__":
unittest.main()