首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在pytest中断言HTTPException

在pytest中断言HTTPException
EN

Stack Overflow用户
提问于 2021-11-09 11:01:33
回答 1查看 717关注 0票数 0
代码语言:javascript
复制
**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。我读过其他文章,但与我的测试用例无关。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-11-09 13:58:58

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

代码语言:javascript
复制
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!"
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69896958

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档