assert HTTPException in pytest

2.7k Views Asked by At
**main.py:**

def bucket_exists(bucket_name):
   try:
    something()

   except ClientError as error:
      error_code = int(error.response['Error']['Code'])
      if error_code == 403:
         raise HTTPException(status_code=403, detail=f"Private Bucket. Forbidden Access!")
      elif error_code == 404:
         raise HTTPException(status_code=404, detail=f"Bucket Does Not Exist!")
return flag



**test_main.py:**
def test_bucket_exists(mock_s3_bucket):
   
      resp = fetch_data.bucket_exists('abc123')
      assert resp == {"detail":"Bucket Does Not Exist!"}

my test has been failing at with error : fastapi.exceptions.HTTPException

please help in handling known httpexception in pytest. I have read other posts but not related to my test case

1

There are 1 best solutions below

1
Tzane On BEST ANSWER

Try catching the exception with pytest.raises into exc_info context and then asserting on the value attribute of it, which contains the raised exception object:

def test_bucket_exists(mock_s3_bucket):
    with pytest.raises(HTTPException) as exc_info:
        fetch_data.bucket_exists('abc123')
    assert isinstance(exc_info.value, HTTPException)
    assert exc_info.value.status_code == 404
    assert exc_info.value.detail == "Bucket Does Not Exist!"