-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtest_fastapi_oop.py
More file actions
513 lines (418 loc) · 15.9 KB
/
Copy pathtest_fastapi_oop.py
File metadata and controls
513 lines (418 loc) · 15.9 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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
"""
Unit and Integration Tests for FastAPI OOP Example
Demonstrates:
- Unit testing service layer with mocked repositories
- Integration testing API endpoints
- Testing validation logic
- Testing business logic in domain models
"""
import pytest
from datetime import datetime
from unittest.mock import AsyncMock, MagicMock
from typing import List
from fastapi.testclient import TestClient
from fastapi_oop_example import (
app,
Engineer,
EngineerService,
IEngineerRepository,
InMemoryEngineerRepository,
EngineerNotFoundError,
EngineerAlreadyExistsError,
CertificationLevel,
CloudPlatform,
EngineerCreate,
EngineerUpdate,
CertificationCreate,
)
# ============================================================================
# DOMAIN MODEL TESTS
# ============================================================================
class TestEngineerDomainModel:
"""Test the Engineer domain entity business logic."""
def test_engineer_initialization(self):
"""Test engineer object creation."""
engineer = Engineer(
id=1,
name="Test Engineer",
email="test@example.com",
specialty="Testing",
hourly_rate=100,
certification_level=CertificationLevel.MID
)
assert engineer.id == 1
assert engineer.name == "Test Engineer"
assert engineer.certifications == []
assert engineer.is_available is True
def test_add_certification(self):
"""Test adding certifications to an engineer."""
engineer = Engineer(
id=1,
name="Test",
email="test@example.com",
specialty="Cloud",
hourly_rate=100,
certification_level=CertificationLevel.MID
)
engineer.add_certification("AZ-104")
assert "AZ-104" in engineer.certifications
# Adding duplicate should not duplicate
engineer.add_certification("AZ-104")
assert engineer.certifications.count("AZ-104") == 1
def test_calculate_monthly_revenue(self):
"""Test revenue calculation."""
engineer = Engineer(
id=1,
name="Test",
email="test@example.com",
specialty="Cloud",
hourly_rate=100,
certification_level=CertificationLevel.MID
)
# Default 160 hours
assert engineer.calculate_monthly_revenue() == 16000
# Custom hours
assert engineer.calculate_monthly_revenue(140) == 14000
def test_can_work_on_platform(self):
"""Test platform certification checking."""
engineer = Engineer(
id=1,
name="Test",
email="test@example.com",
specialty="Cloud",
hourly_rate=100,
certification_level=CertificationLevel.MID,
certifications=["AZ-104", "AZ-700", "AWS-SAA"]
)
assert engineer.can_work_on_platform(CloudPlatform.AZURE) is True
assert engineer.can_work_on_platform(CloudPlatform.AWS) is True
assert engineer.can_work_on_platform(CloudPlatform.GCP) is False
def test_to_dict(self):
"""Test dictionary serialization."""
created_at = datetime(2026, 2, 7, 10, 0, 0)
engineer = Engineer(
id=1,
name="Test",
email="test@example.com",
specialty="Cloud",
hourly_rate=100,
certification_level=CertificationLevel.MID,
created_at=created_at
)
result = engineer.to_dict()
assert result["id"] == 1
assert result["name"] == "Test"
assert result["certification_level"] == "mid"
assert result["created_at"] == created_at.isoformat()
# ============================================================================
# REPOSITORY TESTS
# ============================================================================
class TestInMemoryEngineerRepository:
"""Test the in-memory repository implementation."""
@pytest.mark.asyncio
async def test_create_engineer(self):
"""Test creating an engineer."""
repo = InMemoryEngineerRepository()
engineer = Engineer(
id=0,
name="Test",
email="test@example.com",
specialty="Cloud",
hourly_rate=100,
certification_level=CertificationLevel.MID
)
result = await repo.create(engineer)
assert result.id == 1
assert result.name == "Test"
@pytest.mark.asyncio
async def test_create_duplicate_email(self):
"""Test creating engineer with duplicate email raises error."""
repo = InMemoryEngineerRepository()
engineer1 = Engineer(
id=0,
name="Test1",
email="test@example.com",
specialty="Cloud",
hourly_rate=100,
certification_level=CertificationLevel.MID
)
await repo.create(engineer1)
engineer2 = Engineer(
id=0,
name="Test2",
email="test@example.com",
specialty="Cloud",
hourly_rate=100,
certification_level=CertificationLevel.MID
)
with pytest.raises(EngineerAlreadyExistsError):
await repo.create(engineer2)
@pytest.mark.asyncio
async def test_get_by_id(self):
"""Test retrieving engineer by ID."""
repo = InMemoryEngineerRepository()
engineer = Engineer(
id=0,
name="Test",
email="test@example.com",
specialty="Cloud",
hourly_rate=100,
certification_level=CertificationLevel.MID
)
created = await repo.create(engineer)
result = await repo.get_by_id(created.id)
assert result is not None
assert result.id == created.id
assert result.email == "test@example.com"
@pytest.mark.asyncio
async def test_get_by_id_not_found(self):
"""Test retrieving non-existent engineer returns None."""
repo = InMemoryEngineerRepository()
result = await repo.get_by_id(999)
assert result is None
@pytest.mark.asyncio
async def test_get_by_email(self):
"""Test retrieving engineer by email."""
repo = InMemoryEngineerRepository()
engineer = Engineer(
id=0,
name="Test",
email="test@example.com",
specialty="Cloud",
hourly_rate=100,
certification_level=CertificationLevel.MID
)
await repo.create(engineer)
result = await repo.get_by_email("test@example.com")
assert result is not None
assert result.email == "test@example.com"
@pytest.mark.asyncio
async def test_get_all(self):
"""Test retrieving all engineers."""
repo = InMemoryEngineerRepository()
for i in range(3):
engineer = Engineer(
id=0,
name=f"Test{i}",
email=f"test{i}@example.com",
specialty="Cloud",
hourly_rate=100,
certification_level=CertificationLevel.MID
)
await repo.create(engineer)
result = await repo.get_all()
assert len(result) == 3
@pytest.mark.asyncio
async def test_update_engineer(self):
"""Test updating an engineer."""
repo = InMemoryEngineerRepository()
engineer = Engineer(
id=0,
name="Test",
email="test@example.com",
specialty="Cloud",
hourly_rate=100,
certification_level=CertificationLevel.MID
)
created = await repo.create(engineer)
created.hourly_rate = 120
result = await repo.update(created)
assert result.hourly_rate == 120
@pytest.mark.asyncio
async def test_update_nonexistent_engineer(self):
"""Test updating non-existent engineer raises error."""
repo = InMemoryEngineerRepository()
engineer = Engineer(
id=999,
name="Test",
email="test@example.com",
specialty="Cloud",
hourly_rate=100,
certification_level=CertificationLevel.MID
)
with pytest.raises(EngineerNotFoundError):
await repo.update(engineer)
@pytest.mark.asyncio
async def test_delete_engineer(self):
"""Test deleting an engineer."""
repo = InMemoryEngineerRepository()
engineer = Engineer(
id=0,
name="Test",
email="test@example.com",
specialty="Cloud",
hourly_rate=100,
certification_level=CertificationLevel.MID
)
created = await repo.create(engineer)
result = await repo.delete(created.id)
assert result is True
assert await repo.get_by_id(created.id) is None
@pytest.mark.asyncio
async def test_find_available(self):
"""Test finding available engineers."""
repo = InMemoryEngineerRepository()
# Create available engineer
eng1 = Engineer(
id=0,
name="Available",
email="available@example.com",
specialty="Cloud",
hourly_rate=100,
certification_level=CertificationLevel.MID,
is_available=True
)
await repo.create(eng1)
# Create unavailable engineer
eng2 = Engineer(
id=0,
name="Busy",
email="busy@example.com",
specialty="Cloud",
hourly_rate=100,
certification_level=CertificationLevel.MID,
is_available=False
)
await repo.create(eng2)
result = await repo.find_available()
assert len(result) == 1
assert result[0].is_available is True
# ============================================================================
# SERVICE LAYER TESTS (with mocked repository)
# ============================================================================
class TestEngineerService:
"""Test the service layer with mocked dependencies."""
@pytest.mark.asyncio
async def test_create_engineer(self):
"""Test creating engineer through service."""
# Mock repository
mock_repo = AsyncMock(spec=IEngineerRepository)
mock_repo.create.return_value = Engineer(
id=1,
name="Test",
email="test@example.com",
specialty="Cloud",
hourly_rate=100,
certification_level=CertificationLevel.MID
)
service = EngineerService(mock_repo)
engineer_data = EngineerCreate(
name="Test",
email="test@example.com",
specialty="Cloud",
hourly_rate=100,
certification_level=CertificationLevel.MID
)
result = await service.create_engineer(engineer_data)
assert result.id == 1
assert result.name == "Test"
mock_repo.create.assert_called_once()
@pytest.mark.asyncio
async def test_get_engineer(self):
"""Test getting engineer through service."""
mock_repo = AsyncMock(spec=IEngineerRepository)
mock_repo.get_by_id.return_value = Engineer(
id=1,
name="Test",
email="test@example.com",
specialty="Cloud",
hourly_rate=100,
certification_level=CertificationLevel.MID
)
service = EngineerService(mock_repo)
result = await service.get_engineer(1)
assert result.id == 1
mock_repo.get_by_id.assert_called_once_with(1)
@pytest.mark.asyncio
async def test_get_engineer_not_found(self):
"""Test getting non-existent engineer raises error."""
mock_repo = AsyncMock(spec=IEngineerRepository)
mock_repo.get_by_id.return_value = None
service = EngineerService(mock_repo)
with pytest.raises(EngineerNotFoundError):
await service.get_engineer(999)
@pytest.mark.asyncio
async def test_update_engineer(self):
"""Test updating engineer through service."""
existing_engineer = Engineer(
id=1,
name="Original",
email="original@example.com",
specialty="Cloud",
hourly_rate=100,
certification_level=CertificationLevel.MID
)
mock_repo = AsyncMock(spec=IEngineerRepository)
mock_repo.get_by_id.return_value = existing_engineer
mock_repo.update.return_value = existing_engineer
service = EngineerService(mock_repo)
update_data = EngineerUpdate(hourly_rate=120)
result = await service.update_engineer(1, update_data)
assert result.hourly_rate == 120
assert result.name == "Original" # Unchanged
mock_repo.update.assert_called_once()
# ============================================================================
# API INTEGRATION TESTS
# ============================================================================
@pytest.fixture
def client():
"""Create test client."""
return TestClient(app)
class TestEngineerAPI:
"""Integration tests for the API endpoints."""
def test_list_engineers(self, client):
"""Test listing all engineers."""
response = client.get("/engineers")
assert response.status_code == 200
assert isinstance(response.json(), list)
def test_create_engineer(self, client):
"""Test creating engineer via API."""
engineer_data = {
"name": "API Test Engineer",
"email": "apitest@example.com",
"specialty": "Testing",
"hourly_rate": 105,
"certification_level": "mid"
}
response = client.post("/engineers", json=engineer_data)
assert response.status_code == 201
data = response.json()
assert data["name"] == "API Test Engineer"
assert data["email"] == "apitest@example.com"
assert "id" in data
def test_create_engineer_validation_error(self, client):
"""Test validation errors on create."""
invalid_data = {
"name": "Test",
"email": "invalid-email", # Invalid email
"specialty": "Testing",
"hourly_rate": 100,
"certification_level": "mid"
}
response = client.post("/engineers", json=invalid_data)
assert response.status_code == 422 # Validation error
def test_get_engineer(self, client):
"""Test getting specific engineer."""
response = client.get("/engineers/1")
assert response.status_code in [200, 404]
if response.status_code == 200:
data = response.json()
assert "id" in data
assert "name" in data
def test_get_nonexistent_engineer(self, client):
"""Test getting non-existent engineer returns 404."""
response = client.get("/engineers/9999")
assert response.status_code == 404
def test_revenue_report(self, client):
"""Test revenue report endpoint."""
response = client.get("/reports/revenue")
assert response.status_code == 200
data = response.json()
assert "total_available_engineers" in data
assert "total_monthly_revenue_potential" in data
assert "by_certification_level" in data
# ============================================================================
# RUN TESTS
# ============================================================================
if __name__ == "__main__":
pytest.main([__file__, "-v", "--tb=short"])