Skip to content

Commit c27f63d

Browse files
fix: initialize batch_id before try block in start_processing to prevent UnboundLocalError
Agent-Logs-Url: https://github.com/microsoft/Modernize-your-code-solution-accelerator/sessions/1182bdcf-25b8-4af7-b0e9-da0938566ee0 Co-authored-by: Abdul-Microsoft <192570837+Abdul-Microsoft@users.noreply.github.com>
1 parent d5daa8e commit c27f63d

2 files changed

Lines changed: 21 additions & 1 deletion

File tree

src/backend/api/api_routes.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,7 @@ async def start_processing(request: Request):
9191
500:
9292
description: Internal server error
9393
"""
94+
batch_id = None
9495
try:
9596
payload = await request.json()
9697
batch_id = payload.get("batch_id")
@@ -113,7 +114,10 @@ async def start_processing(request: Request):
113114
"message": "Files processed",
114115
}
115116
except Exception as e:
116-
track_event_if_configured("ProcessingFailed", {"batch_id": batch_id, "error": str(e)})
117+
event_data = {"error": str(e)}
118+
if batch_id is not None:
119+
event_data["batch_id"] = batch_id
120+
track_event_if_configured("ProcessingFailed", event_data)
117121
record_exception_to_trace(e)
118122
raise HTTPException(status_code=500, detail=str(e)) from e
119123

src/tests/backend/api/api_routes_test.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,22 @@ async def test_start_processing_exception(self, mock_process_batch, mock_track_e
138138
await start_processing(mock_request)
139139
assert exc_info.value.status_code == 500
140140

141+
@pytest.mark.asyncio
142+
async def test_start_processing_json_parse_error(self, mock_track_event):
143+
"""Test processing start when request.json() raises before batch_id is assigned."""
144+
mock_request = AsyncMock()
145+
mock_request.json = AsyncMock(side_effect=Exception("Invalid JSON"))
146+
147+
with patch("backend.api.api_routes.record_exception_to_trace"):
148+
with pytest.raises(HTTPException) as exc_info:
149+
await start_processing(mock_request)
150+
assert exc_info.value.status_code == 500
151+
# batch_id should not be in the telemetry event data when it was never assigned
152+
called_args = mock_track_event.call_args
153+
assert called_args is not None
154+
event_data = called_args[0][1]
155+
assert "batch_id" not in event_data
156+
141157

142158
class TestDownloadFiles:
143159
"""Tests for download_files endpoint."""

0 commit comments

Comments
 (0)