【问题标题】:assert HTTPException in pytest在 pytest 中断言 HTTPException
【发布时间】:2021-12-22 02:08:14
【问题描述】:
**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!"}

我的测试因错误而失败:fastapi.exceptions.HTTPException

请帮助处理 pytest 中已知的 httpexception。我已阅读其他帖子但与我的测试用例无关

【问题讨论】:

    标签: python pytest httpexception


    【解决方案1】:

    尝试使用pytest.raises into exc_info context 捕获异常,然后断言它的value 属性,其中包含引发的异常对象:

    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!"
    

    【讨论】:

    • 完美。它解决了我的问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多