You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:如何在Pytest中正确处理抛出HTTPException的FastAPI函数测试失败问题

How to Test FastAPI's 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.value gives you access to the actual HTTPException instance, so you can validate its status_code and detail match 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.01 01:02:33