Skip to content

Commit 2985c84

Browse files
Week07 code added.
1 parent f57fe55 commit 2985c84

1 file changed

Lines changed: 59 additions & 26 deletions

File tree

backend/customer_service/tests/test_main.py

Lines changed: 59 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# week03/example-3/backend/customer_service/tests/test_main.py
1+
# week07/backend/customer_service/tests/test_main.py
22

33
"""
44
Integration tests for the Customer Service API.
@@ -31,6 +31,7 @@
3131

3232
# --- Pytest Fixtures ---
3333

34+
3435
@pytest.fixture(scope="session", autouse=True)
3536
def setup_database_for_tests():
3637
"""
@@ -42,24 +43,37 @@ def setup_database_for_tests():
4243
retry_delay_seconds = 3
4344
for i in range(max_retries):
4445
try:
45-
logging.info(f"Customer Service Tests: Attempting to connect to PostgreSQL for test setup (attempt {i+1}/{max_retries})...")
46+
logging.info(
47+
f"Customer Service Tests: Attempting to connect to PostgreSQL for test setup (attempt {i+1}/{max_retries})..."
48+
)
4649
# Explicitly drop all tables first to ensure a clean slate for the session
4750
Base.metadata.drop_all(bind=engine)
48-
logging.info("Customer Service Tests: Successfully dropped all tables in PostgreSQL for test setup.")
51+
logging.info(
52+
"Customer Service Tests: Successfully dropped all tables in PostgreSQL for test setup."
53+
)
4954

5055
# Then create all tables required by the application
5156
Base.metadata.create_all(bind=engine)
52-
logging.info("Customer Service Tests: Successfully created all tables in PostgreSQL for test setup.")
57+
logging.info(
58+
"Customer Service Tests: Successfully created all tables in PostgreSQL for test setup."
59+
)
5360
break
5461
except OperationalError as e:
55-
logging.warning(f"Customer Service Tests: Test setup DB connection failed: {e}. Retrying in {retry_delay_seconds} seconds...")
62+
logging.warning(
63+
f"Customer Service Tests: Test setup DB connection failed: {e}. Retrying in {retry_delay_seconds} seconds..."
64+
)
5665
time.sleep(retry_delay_seconds)
5766
if i == max_retries - 1:
58-
pytest.fail(f"Could not connect to PostgreSQL for Customer Service test setup after {max_retries} attempts: {e}")
67+
pytest.fail(
68+
f"Could not connect to PostgreSQL for Customer Service test setup after {max_retries} attempts: {e}"
69+
)
5970
except Exception as e:
60-
pytest.fail(f"Customer Service Tests: An unexpected error occurred during test DB setup: {e}", pytrace=True)
61-
62-
yield # Yield control to the tests
71+
pytest.fail(
72+
f"Customer Service Tests: An unexpected error occurred during test DB setup: {e}",
73+
pytrace=True,
74+
)
75+
76+
yield # Yield control to the tests
6377

6478
# Optional: Uncomment to drop tables after all tests in the session
6579
# logging.info("Customer Service Tests: Dropping tables from PostgreSQL after test session.")
@@ -89,6 +103,7 @@ def override_get_db():
89103
connection.close()
90104
app.dependency_overrides.pop(get_db, None)
91105

106+
92107
@pytest.fixture(scope="module")
93108
def client():
94109
"""
@@ -97,20 +112,24 @@ def client():
97112
with TestClient(app) as test_client:
98113
yield test_client
99114

115+
100116
# --- Customer Service Tests ---
101117

118+
102119
def test_read_root(client: TestClient):
103120
"""Test the root endpoint."""
104121
response = client.get("/")
105122
assert response.status_code == 200
106123
assert response.json() == {"message": "Welcome to the Customer Service!"}
107124

125+
108126
def test_health_check(client: TestClient):
109127
"""Test the health check endpoint."""
110128
response = client.get("/health")
111129
assert response.status_code == 200
112130
assert response.json() == {"status": "ok", "service": "customer-service"}
113131

132+
114133
def test_create_customer_success(client: TestClient, db_session_for_test: Session):
115134
"""Tests successful creation of a customer."""
116135
customer_data = {
@@ -119,19 +138,23 @@ def test_create_customer_success(client: TestClient, db_session_for_test: Sessio
119138
"first_name": "Alice",
120139
"last_name": "Smith",
121140
"phone_number": "111-222-3333",
122-
"shipping_address": "123 Main St"
141+
"shipping_address": "123 Main St",
123142
}
124143
response = client.post("/customers/", json=customer_data)
125-
144+
126145
assert response.status_code == 201
127146
response_data = response.json()
128147
assert response_data["email"] == customer_data["email"]
129148
assert response_data["first_name"] == customer_data["first_name"]
130149
assert "customer_id" in response_data
131150
assert isinstance(response_data["customer_id"], int)
132-
151+
133152
# Verify customer exists in DB
134-
db_customer = db_session_for_test.query(Customer).filter(Customer.customer_id == response_data["customer_id"]).first()
153+
db_customer = (
154+
db_session_for_test.query(Customer)
155+
.filter(Customer.customer_id == response_data["customer_id"])
156+
.first()
157+
)
135158
assert db_customer is not None
136159
assert db_customer.email == customer_data["email"]
137160

@@ -142,7 +165,7 @@ def test_get_customer_success(client: TestClient, db_session_for_test: Session):
142165
"email": "getme@example.com",
143166
"password": "getpassword",
144167
"first_name": "Diana",
145-
"last_name": "Prince"
168+
"last_name": "Prince",
146169
}
147170
create_response = client.post("/customers/", json=customer_data)
148171
customer_id = create_response.json()["customer_id"]
@@ -153,79 +176,89 @@ def test_get_customer_success(client: TestClient, db_session_for_test: Session):
153176
assert response_data["customer_id"] == customer_id
154177
assert response_data["email"] == customer_data["email"]
155178

179+
156180
def test_get_customer_not_found(client: TestClient):
157181
"""Tests retrieving a non-existent customer, expecting 404."""
158182
response = client.get("/customers/999999")
159183
assert response.status_code == 404
160184
assert response.json()["detail"] == "Customer not found"
161185

186+
162187
def test_list_customers_empty(client: TestClient, db_session_for_test: Session):
163188
"""Tests listing customers when none exist."""
164189
# Ensure no customers in DB for this test (fixture handles rollback)
165190
response = client.get("/customers/")
166191
assert response.status_code == 200
167192
assert response.json() == []
168193

194+
169195
def test_update_customer_success(client: TestClient, db_session_for_test: Session):
170196
"""Tests updating an existing customer."""
171197
customer_data = {
172198
"email": "updateme@example.com",
173199
"password": "oldpassword",
174200
"first_name": "Grace",
175201
"last_name": "Hopper",
176-
"shipping_address": "Old Address"
202+
"shipping_address": "Old Address",
177203
}
178204
create_response = client.post("/customers/", json=customer_data)
179205
customer_id = create_response.json()["customer_id"]
180206

181-
update_payload = {
182-
"first_name": "Graceful",
183-
"shipping_address": "New Address Lane"
184-
}
207+
update_payload = {"first_name": "Graceful", "shipping_address": "New Address Lane"}
185208
response = client.put(f"/customers/{customer_id}", json=update_payload)
186209

187210
assert response.status_code == 200
188211
response_data = response.json()
189212
assert response_data["customer_id"] == customer_id
190213
assert response_data["first_name"] == "Graceful"
191214
assert response_data["shipping_address"] == "New Address Lane"
192-
assert response_data["email"] == "updateme@example.com" # Email not changed
215+
assert response_data["email"] == "updateme@example.com" # Email not changed
193216

194217
# Verify in DB
195-
db_customer = db_session_for_test.query(Customer).filter(Customer.customer_id == customer_id).first()
218+
db_customer = (
219+
db_session_for_test.query(Customer)
220+
.filter(Customer.customer_id == customer_id)
221+
.first()
222+
)
196223
assert db_customer.first_name == "Graceful"
197224
assert db_customer.shipping_address == "New Address Lane"
198225

226+
199227
def test_update_customer_not_found(client: TestClient):
200228
"""Tests updating a non-existent customer, expecting 404."""
201229
response = client.put("/customers/999999", json={"first_name": "NonExistent"})
202230
assert response.status_code == 404
203231
assert response.json()["detail"] == "Customer not found"
204232

233+
205234
def test_delete_customer_success(client: TestClient, db_session_for_test: Session):
206235
"""Tests successful deletion of a customer."""
207236
customer_data = {
208237
"email": "deleteme@example.com",
209238
"password": "delpassword",
210239
"first_name": "Ivan",
211-
"last_name": "Terrible"
240+
"last_name": "Terrible",
212241
}
213242
create_response = client.post("/customers/", json=customer_data)
214243
customer_id = create_response.json()["customer_id"]
215244

216245
response = client.delete(f"/customers/{customer_id}")
217-
assert response.status_code == 204 # No Content
246+
assert response.status_code == 204 # No Content
218247

219248
# Verify customer is deleted
220249
get_response = client.get(f"/customers/{customer_id}")
221250
assert get_response.status_code == 404
222-
223-
db_customer = db_session_for_test.query(Customer).filter(Customer.customer_id == customer_id).first()
251+
252+
db_customer = (
253+
db_session_for_test.query(Customer)
254+
.filter(Customer.customer_id == customer_id)
255+
.first()
256+
)
224257
assert db_customer is None
225258

259+
226260
def test_delete_customer_not_found(client: TestClient):
227261
"""Tests deleting a non-existent customer, expecting 404."""
228262
response = client.delete("/customers/999999")
229263
assert response.status_code == 404
230264
assert response.json()["detail"] == "Customer not found"
231-

0 commit comments

Comments
 (0)