dylanglenister commited on
Commit
bd7ffcf
·
1 Parent(s): 620fcb9

Account tests pass 2

Browse files
Files changed (1) hide show
  1. tests/test_account.py +186 -40
tests/test_account.py CHANGED
@@ -1,77 +1,223 @@
1
  import unittest
2
  from datetime import datetime
3
 
4
- from src.data.connection import Collections
5
- from src.data.repositories.account import (create_account, get_account,
6
- get_account_by_name,
7
- search_accounts, update_account)
 
 
 
8
  from src.utils.logger import logger
9
  from tests.base_test import BaseMongoTest
10
 
11
 
12
  class TestAccountRepository(BaseMongoTest):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
  def test_create_account(self):
14
- """Test account creation with various parameters"""
15
  # Test basic creation
16
- account_id = create_account(
17
- name="Test Doctor",
18
- role="Doctor",
19
- collection_name=self._collections[Collections.ACCOUNT]
 
 
20
  )
21
- self.assertIsNotNone(account_id)
 
 
 
 
 
 
 
22
 
23
  # Test creation with specialty
24
- account_id = create_account(
25
  name="Specialist",
26
  role="Doctor",
27
  specialty="Cardiology",
28
- collection_name=self._collections[Collections.ACCOUNT]
29
  )
30
- doc = self.get_doc_by_id(Collections.ACCOUNT, account_id)
31
- self.assertIsNotNone(doc)
32
- self.assertEqual(doc["specialty"], "Cardiology") # type: ignore
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
 
34
  def test_update_account(self):
35
- """Test account updates"""
36
- account_id = create_account(
37
  name="Update Test",
38
  role="Doctor",
39
- collection_name=self._collections[Collections.ACCOUNT]
40
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
41
 
42
- # Test name update
43
- success = update_account(
 
 
 
 
44
  account_id,
45
- {"name": "Updated Name"},
46
- collection_name=self._collections[Collections.ACCOUNT]
47
  )
48
  self.assertTrue(success)
49
-
50
- # Verify created_at wasn't modified
51
- doc = self.get_doc_by_id(Collections.ACCOUNT, account_id)
52
- self.assertIsNotNone(doc)
53
- self.assertIsInstance(doc["created_at"], datetime) # type: ignore
54
- self.assertLess(doc["created_at"], doc["updated_at"]) # type: ignore
55
 
56
  def test_search_accounts(self):
57
- """Test account search functionality"""
58
- # Create test accounts
59
- create_account("Alpha Doctor", "Doctor", collection_name=self._collections[Collections.ACCOUNT])
60
- create_account("Beta Doctor", "Doctor", collection_name=self._collections[Collections.ACCOUNT])
61
- create_account("Charlie Doctor", "Doctor", collection_name=self._collections[Collections.ACCOUNT])
62
-
63
- # Test search
64
- results = search_accounts("beta", collection_name=self._collections[Collections.ACCOUNT])
65
  self.assertEqual(len(results), 1)
66
  self.assertEqual(results[0]["name"], "Beta Doctor")
67
 
68
- # Test case insensitive
69
- results = search_accounts("ALPHA", collection_name=self._collections[Collections.ACCOUNT])
70
  self.assertEqual(len(results), 1)
71
 
72
- # Test limit
73
- results = search_accounts("Doctor", limit=2, collection_name=self._collections[Collections.ACCOUNT])
74
  self.assertEqual(len(results), 2)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75
 
76
  if __name__ == "__main__":
77
  try:
 
1
  import unittest
2
  from datetime import datetime
3
 
4
+ from bson import ObjectId
5
+ from pandas import DataFrame
6
+ from pymongo import ASCENDING
7
+ from pymongo.errors import DuplicateKeyError
8
+
9
+ from src.data.connection import Collections, get_collection
10
+ from src.data.repositories import account as Repo
11
  from src.utils.logger import logger
12
  from tests.base_test import BaseMongoTest
13
 
14
 
15
  class TestAccountRepository(BaseMongoTest):
16
+
17
+ def setUp(self):
18
+ """Set up the test environment before each test."""
19
+ super().setUp()
20
+ self.test_collection = self._collections[Collections.ACCOUNT]
21
+
22
+ # Call the updated init function directly to set up the test collection
23
+ Repo.init(collection_name=self.test_collection, drop=True)
24
+
25
+ # Add a unique index on 'name' to test for duplicate key errors
26
+ get_collection(self.test_collection).create_index(
27
+ [("name", ASCENDING)], unique=True
28
+ )
29
+
30
+ def test_init_functionality(self):
31
+ """Test the init function's ability to create and drop collections."""
32
+ # 1. Verify the collection exists after setUp
33
+ self.assertIn(self.test_collection, self.db.list_collection_names())
34
+
35
+ # 2. Test the drop functionality
36
+ Repo.create_account("ToDelete", "Doctor", collection_name=self.test_collection)
37
+ self.assertEqual(get_collection(self.test_collection).count_documents({}), 1)
38
+
39
+ # Re-initialize with drop=True
40
+ Repo.init(collection_name=self.test_collection, drop=True)
41
+
42
+ # Assert the collection is now empty but still exists
43
+ self.assertEqual(get_collection(self.test_collection).count_documents({}), 0)
44
+ self.assertIn(self.test_collection, self.db.list_collection_names())
45
+
46
  def test_create_account(self):
47
+ """Test account creation with various parameters and constraints."""
48
  # Test basic creation
49
+ name = "Test Doctor"
50
+ role = "Doctor"
51
+ account_id = Repo.create_account(
52
+ name=name,
53
+ role=role,
54
+ collection_name=self.test_collection
55
  )
56
+ self.assertIsInstance(account_id, str)
57
+ doc = self.get_doc_by_id(Collections.ACCOUNT, account_id)
58
+ self.assertIsNotNone(doc)
59
+ self.assertEqual(doc["name"], name) # type: ignore
60
+ self.assertEqual(doc["role"], role) # type: ignore
61
+ self.assertIn("created_at", doc) # type: ignore
62
+ self.assertIn("updated_at", doc) # type: ignore
63
+ self.assertEqual(doc["created_at"], doc["updated_at"]) # type: ignore
64
 
65
  # Test creation with specialty
66
+ account_id_spec = Repo.create_account(
67
  name="Specialist",
68
  role="Doctor",
69
  specialty="Cardiology",
70
+ collection_name=self.test_collection
71
  )
72
+ doc_spec = self.get_doc_by_id(Collections.ACCOUNT, account_id_spec)
73
+ self.assertIsNotNone(doc_spec)
74
+ self.assertEqual(doc_spec["specialty"], "Cardiology") # type: ignore
75
+
76
+ # Test creating a user with a duplicate name raises an error
77
+ with self.assertRaises(DuplicateKeyError):
78
+ Repo.create_account(name=name, role="Nurse", collection_name=self.test_collection)
79
+
80
+ def test_get_account(self):
81
+ """Test retrieving a single account by its ID."""
82
+ account_id = Repo.create_account(
83
+ "GetMe", "Doctor", collection_name=self.test_collection
84
+ )
85
+ original_doc = self.get_doc_by_id(Collections.ACCOUNT, account_id)
86
+ self.assertNotIn("last_seen", original_doc) # type: ignore
87
+
88
+ # Get the account and verify 'last_seen' is updated
89
+ account = Repo.get_account(account_id, collection_name=self.test_collection)
90
+ self.assertIsNotNone(account)
91
+ self.assertEqual(account["_id"], account_id) # type: ignore
92
+ self.assertEqual(account["name"], "GetMe") # type: ignore
93
+ self.assertIn("last_seen", account) # type: ignore
94
+ self.assertIsInstance(account["last_seen"], datetime) # type: ignore
95
+ self.assertIsInstance(account["_id"], str) # type: ignore
96
+
97
+ # Test retrieval of a non-existent account returns None
98
+ non_existent_id = str(ObjectId())
99
+ account = Repo.get_account(non_existent_id, collection_name=self.test_collection)
100
+ self.assertIsNone(account)
101
+
102
+ def test_get_account_by_name(self):
103
+ """Test retrieving an account by name."""
104
+ name = "FindByName"
105
+ Repo.create_account(name, "Nurse", collection_name=self.test_collection)
106
+
107
+ account = Repo.get_account_by_name(name, collection_name=self.test_collection)
108
+ self.assertIsNotNone(account)
109
+ self.assertEqual(account["name"], name) # type: ignore
110
+ self.assertIsInstance(account["_id"], str) # type: ignore
111
+
112
+ # Test retrieval of a non-existent name returns None
113
+ account = Repo.get_account_by_name("NonExistent", collection_name=self.test_collection)
114
+ self.assertIsNone(account)
115
 
116
  def test_update_account(self):
117
+ """Test updating an existing account's data."""
118
+ account_id = Repo.create_account(
119
  name="Update Test",
120
  role="Doctor",
121
+ collection_name=self.test_collection
122
  )
123
+ original_doc = self.get_doc_by_id(Collections.ACCOUNT, account_id)
124
+ self.assertIsNotNone(original_doc)
125
+
126
+ updates = {"name": "Updated Name", "specialty": "Pediatrics"}
127
+ success = Repo.update_account(account_id, updates, collection_name=self.test_collection)
128
+ self.assertTrue(success)
129
+
130
+ updated_doc = self.get_doc_by_id(Collections.ACCOUNT, account_id)
131
+ self.assertIsNotNone(updated_doc)
132
+ self.assertEqual(updated_doc["name"], "Updated Name") # type: ignore
133
+ self.assertEqual(updated_doc["specialty"], "Pediatrics") # type: ignore
134
+ self.assertEqual(updated_doc["created_at"], original_doc["created_at"]) # type: ignore
135
+ self.assertLess(original_doc["updated_at"], updated_doc["updated_at"]) # type: ignore
136
 
137
+ # Test that updating a non-existent account returns False
138
+ success = Repo.update_account(str(ObjectId()), {"name": "No One"}, collection_name=self.test_collection)
139
+ self.assertFalse(success)
140
+
141
+ # Test that 'created_at' is ignored in updates and does not change
142
+ success = Repo.update_account(
143
  account_id,
144
+ {"created_at": datetime(2000, 1, 1)},
145
+ collection_name=self.test_collection
146
  )
147
  self.assertTrue(success)
148
+ final_doc = self.get_doc_by_id(Collections.ACCOUNT, account_id)
149
+ self.assertEqual(final_doc["created_at"], original_doc["created_at"]) # type: ignore
 
 
 
 
150
 
151
  def test_search_accounts(self):
152
+ """Test account search functionality for various cases."""
153
+ Repo.create_account("Alpha Doctor", "Doctor", collection_name=self.test_collection)
154
+ Repo.create_account("Beta Doctor", "Doctor", collection_name=self.test_collection)
155
+ Repo.create_account("Charlie Medical", "Medical Student", collection_name=self.test_collection)
156
+
157
+ # Test case-insensitive partial match
158
+ results = Repo.search_accounts("beta", collection_name=self.test_collection)
 
159
  self.assertEqual(len(results), 1)
160
  self.assertEqual(results[0]["name"], "Beta Doctor")
161
 
162
+ # Test case-insensitive full match
163
+ results = Repo.search_accounts("ALPHA DOCTOR", collection_name=self.test_collection)
164
  self.assertEqual(len(results), 1)
165
 
166
+ # Test query that matches multiple entries with a limit
167
+ results = Repo.search_accounts("Doctor", limit=2, collection_name=self.test_collection)
168
  self.assertEqual(len(results), 2)
169
+ self.assertEqual(results[0]['name'], 'Alpha Doctor') # Assumes ascending sort by name
170
+ self.assertEqual(results[1]['name'], 'Beta Doctor')
171
+
172
+ # Test query with no matches
173
+ results = Repo.search_accounts("NonExistent", collection_name=self.test_collection)
174
+ self.assertEqual(len(results), 0)
175
+
176
+ # Test empty query string returns an empty list
177
+ results = Repo.search_accounts("", collection_name=self.test_collection)
178
+ self.assertEqual(len(results), 0)
179
+
180
+ def test_get_all_accounts(self):
181
+ """Test retrieving all accounts with limit and sorting."""
182
+ Repo.create_account("Charlie", "Doctor", collection_name=self.test_collection)
183
+ Repo.create_account("Alpha", "Nurse", collection_name=self.test_collection)
184
+ Repo.create_account("Beta", "Caregiver", collection_name=self.test_collection)
185
+
186
+ # Test getting all accounts, verifying ascending sort order by name
187
+ all_accounts = Repo.get_all_accounts(collection_name=self.test_collection)
188
+ self.assertEqual(len(all_accounts), 3)
189
+ self.assertEqual(all_accounts[0]["name"], "Alpha")
190
+ self.assertEqual(all_accounts[1]["name"], "Beta")
191
+ self.assertEqual(all_accounts[2]["name"], "Charlie")
192
+
193
+ # Test with a limit
194
+ limited_accounts = Repo.get_all_accounts(limit=2, collection_name=self.test_collection)
195
+ self.assertEqual(len(limited_accounts), 2)
196
+ self.assertEqual(limited_accounts[0]["name"], "Alpha")
197
+ self.assertEqual(limited_accounts[1]["name"], "Beta")
198
+
199
+ def test_get_account_frame(self):
200
+ """Test retrieving accounts as a pandas DataFrame."""
201
+ # Test with an empty collection
202
+ df_empty = Repo.get_account_frame(collection_name=self.test_collection)
203
+ self.assertIsInstance(df_empty, DataFrame)
204
+ self.assertTrue(df_empty.empty)
205
+
206
+ # Add data and test again
207
+ id1 = Repo.create_account("Frame Alpha", "Doctor", collection_name=self.test_collection)
208
+ Repo.create_account("Frame Beta", "Nurse", specialty="ICU", collection_name=self.test_collection)
209
+
210
+ df = Repo.get_account_frame(collection_name=self.test_collection)
211
+ self.assertIsInstance(df, DataFrame)
212
+ self.assertEqual(len(df), 2)
213
+
214
+ # Check if expected columns are present
215
+ expected_cols = {"_id", "name", "role", "created_at", "updated_at"}
216
+ self.assertTrue(expected_cols.issubset(set(df.columns)))
217
+
218
+ # Verify content of a specific row
219
+ alpha_row = df[df['_id'] == ObjectId(id1)]
220
+ self.assertEqual(alpha_row.iloc[0]["name"], "Frame Alpha")
221
 
222
  if __name__ == "__main__":
223
  try: