diff --git a/api/main.py b/api/main.py index c649e1a..4c339a0 100644 --- a/api/main.py +++ b/api/main.py @@ -90,6 +90,7 @@ async def generate_discharge_note( # Create a temp file to store the consultation data temp_file = UPLOAD_DIR / f"consultation_{id(request)}.json" + output_path: Path | None = None try: with temp_file.open("w") as f: json.dump(request.consultation_data, f) @@ -107,8 +108,12 @@ async def generate_discharge_note( # Clean up temporary files if temp_file.exists(): temp_file.unlink() - if output_path.exists(): - output_path.unlink() + # output_path might remain None if discharge_generator.process_file fails + if output_path: + if output_path.exists(): + output_path.unlink() + else: + logger.info(f"Skipping cleanup for output_path as it does not exist: {output_path}") except Exception as e: logger.error(f"❌ Error generating discharge note: {e}") diff --git a/tests/unit/api/test_main.py b/tests/unit/api/test_main.py index 86c9623..e44c874 100644 --- a/tests/unit/api/test_main.py +++ b/tests/unit/api/test_main.py @@ -117,31 +117,29 @@ def test_generate_endpoint_error( mock_generator.process_file.side_effect = ValueError("Test error") mock_upload_dir.__truediv__.return_value = Path("test_file.json") - # Mock Path.exists and Path.unlink to avoid UnboundLocalError for output_path - with patch("pathlib.Path.exists", return_value=False): # Avoid trying to unlink files - # Execute - response = test_client.post( - "/generate", - json={ - "consultation_data": { - "patient": { - "name": "Max", - "species": "Dog", - "breed": "Golden Retriever", - "gender": "Male", - "neutered": True, - "date_of_birth": "2018-05-10", - "weight": "32 kg", - }, - "consultation": { - "date": "2023-07-15", - "time": "10:30", - "reason": "Vomiting", - "type": "Outpatient", - }, - } - }, - ) + # Execute without patching Path.exists to ensure cleanup handles None output_path + response = test_client.post( + "/generate", + json={ + "consultation_data": { + "patient": { + "name": "Max", + "species": "Dog", + "breed": "Golden Retriever", + "gender": "Male", + "neutered": True, + "date_of_birth": "2018-05-10", + "weight": "32 kg", + }, + "consultation": { + "date": "2023-07-15", + "time": "10:30", + "reason": "Vomiting", + "type": "Outpatient", + }, + } + }, + ) # Assert assert response.status_code == 500