Moto测试没有提出适当的例外

时间:2018-06-01 20:00:30

标签: pytest boto3 botocore moto

我希望测试以下功能:

    def download(self):
        s3 = boto3.client('s3')
        try:
            with open(self.flow_cells +'.tar', 'wb') as data:
                s3.download_fileobj(
                    self.source_s3_bucket,
                    self.source_key,
                    data
                )
            return True
        except botocore.exceptions.ClientError as error:
            print(error.response['Error']['Code'])

我正在使用pytest来测试带有moto的代码。除此之外,所有其他测试和botocore异常都会被标记。我在标准中捕获它正在进入异常函数并打印正确的代码,但moto没有将其标记为异常

这是我的测试代码。

def test_download(parse_args, file_test):
 with moto.mock_s3():
    s3 = boto3.resource('s3')
    s3.create_bucket(Bucket=parse_args.glacier_s3_bucket, CreateBucketConfiguration={
        'LocationConstraint': 'us-east-1'
        })
    s3.create_bucket(Bucket=parse_args.output_s3_bucket, CreateBucketConfiguration={
        'LocationConstraint': 'us-east-1'
        })
    bucket_version = s3.BucketVersioning(parse_args.glacier_s3_bucket)
    bucket_version.enable()
    s3.Object(parse_args.glacier_s3_bucket, 'flowcells/flowcell-testing.tar').put\
    (Body=open(file_test, 'rb'))
    glacier_client = GlacierRestoreClient(parse_args)
    assert glacier_client.download() is True
    s3.Object(glacier_client.source_s3_bucket, glacier_client.source_key).delete()
    with pytest.raises(Exception) as error:
        glacier_client.download()
    assert 'Error' in error

1 个答案:

答案 0 :(得分:1)

except botocore.exceptions.ClientError as error: print(error.response['Error']['Code']) raise 子句内,异常被静音而不会传播,所以你需要重新提升它:

raise

刚刚抓住的raise re-raises例外情况。

PS。无耻的插件:我是20年前要求Guido添加裸{{1}}的人之一! : - )