gpt4 book ai didi

python - '类型错误 : catching classes that do not inherit from BaseException is not allowed' when trying to mock an exception

转载 作者:行者123 更新时间:2023-12-05 06:05:15 28 4
gpt4 key购买 nike

我正在尝试测试与 Amazon Forecast 服务交互的代码块,它看起来与 https://github.com/aws-samples/amazon-forecast-samples/blob/master/ml_ops/visualization_blog/lambdas/createdataset/dataset.py 中提供的示例非常相似.

更具体地说,我正在尝试测试我是否正确处理了异常。假设 'forecast' 是 Amazon Forecast boto3 客户端,代码结构如下:

def example_function(dataset):
try:
forecast.describe_dataset(dataset)
#do some stuff
except forecast.exceptions.ResourceNotFoundException:
#do other stuff

我有一个看起来像这样的测试用例:

from moto.forecast.exceptions import ResourceNotFoundException

@patch('forecast client')
def test(self, mock_forecast):
mock_forecast.describe_dataset.side_effect = ResourceNotFoundException
example_function(dataset)

这会产生“TypeError:不允许捕获不从 BaseException 继承的类”,这让我感到困惑,因为 moto.forecast.exceptions.ResourceNotFoundException 继承了 moto 类“AWSError”,而后者又继承了“Exception”。

如果我无法将 side_effect 设置为异常,我对如何在不实际与预测服务交互的情况下测试代码的“except” block 一头雾水。任何想法将不胜感激!

最佳答案

问题可能是您用模拟覆盖了原始预测对象,并在检查异常时将模拟对象返回到 example 函数中的 forecast.exceptions.ResourceNotFoundException分支机构。

所以你必须将测试修改成这样:

from moto.forecast.exceptions import ResourceNotFoundException

@patch('forecast client')
def test(self, mock_forecast):
mock_forecast.exceptions.ResourceNotFoundException = ResourceNotFoundException
mock_forecast.describe_dataset.side_effect = ResourceNotFoundException("Exception message")
example_function(dataset)

关于python - '类型错误 : catching classes that do not inherit from BaseException is not allowed' when trying to mock an exception,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66069807/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com