求助:如何在Pytest中正确处理抛出HTTPException的FastAPI函数测试失败问题
HTTPException in Pytest Your test is failing because the bucket_exists function doesn't return an error dictionary like {"detail":"Bucket Does Not Exist!"} when hitting a 404 or 403 error — instead, it raises an HTTPException directly. Your current test tries to assert a return value, but the function never reaches the return flag line in those error cases.
Here's how to fix your test case properly:
Step 1: Use pytest.raises to Catch the Exception
Pytest provides the pytest.raises context manager to verify that an expected exception is raised during function execution. You can access the exception instance inside the context to check its status_code and detail attributes.
Modified test_main.py
import pytest from fastapi.exceptions import HTTPException import fetch_data # Adjust the import path to match your project structure def test_bucket_exists_404(mock_s3_bucket): # Catch the expected HTTPException using pytest.raises with pytest.raises(HTTPException) as exc_info: fetch_data.bucket_exists('abc123') # Validate the exception's properties match your expected behavior assert exc_info.value.status_code == 404 assert exc_info.value.detail == "Bucket Does Not Exist!" # Optional: Add a test for the 403 forbidden scenario def test_bucket_exists_403(mock_s3_private_bucket): with pytest.raises(HTTPException) as exc_info: fetch_data.bucket_exists('private-bucket') assert exc_info.value.status_code == 403 assert exc_info.value.detail == "Private Bucket. Forbidden Access!"
Step 2: Validate Your Mock Setup
Make sure your mock_s3_bucket fixture is correctly configured to throw a ClientError with the appropriate error code. For example, if using unittest.mock:
from botocore.exceptions import ClientError from unittest.mock import patch import pytest @pytest.fixture def mock_s3_bucket(): with patch("main.something") as mock_something: # Configure the mock to trigger a 404 ClientError error_response = { 'Error': { 'Code': '404', 'Message': 'Not Found' } } mock_something.side_effect = ClientError(error_response, 'HeadBucket') yield
Why This Works
pytest.raises(HTTPException)confirms that the function raises the exact exception you expect (if it doesn't, the test fails immediately).exc_info.valuegives you access to the actualHTTPExceptioninstance, so you can validate itsstatus_codeanddetailmatch what your function defines.
This approach aligns with how FastAPI handles errors: functions raise exceptions that FastAPI automatically converts into HTTP responses. Your tests need to reflect this behavior instead of expecting a return value.
内容的提问来源于stack exchange,提问作者Sai

