[英]Python Unit test with mocking boto3 S3 resource
我是 Python 的新手,并且在 python 中编写了一些代码,但没有进行很多单元测试,尤其是涉及 mocking 的代码。
我想为这个使用 boto3 的 python function 编写单元测试。
简单输入.py
s3 = boto3.resource('s3')
def simpleput(bucket: str, filename: str):
// s3 = boto3.resource('s3')
s3bucket = s3.Bucket(bucket)
s3.Object(bucket, filename).put(Body='one\ntwo')
我找到botocore stubber
并继续使用它: https://botocore.amazonaws.com/v1/documentation/api/latest/reference/stubber.html
由于我在代码中使用boto3.resource
而不是boto3.client
,因此基于此建议,我编写了以下测试:
import unittest
import boto3
from botocore.stub import Stubber
import simpleput
class TestModule(unittest.TestCase):
def test_seed(self):
s3_resource = boto3.resource('s3')
client = s3_resource.meta.client
stubber = Stubber(client)
simpleput.s3 = s3_resource // Setting this on file I want to test
response = {"Expiration": "whatever", "ETag": "12345", "VersionId": "1.0"}
expected_params = {
"Body": 'one\ntwo',
"Bucket": 'mybucket',
"Key": 'mykey',
}
stubber.add_response('put_object', response, expected_params)
with stubber:
service_response = client.put_object(Body='one\ntwo', Bucket='mybucket', Key='mykey')
simpleput.simpleput('mybucket', 'mykey')
assert service_response == response
现在无法弄清楚如何使用这个模拟/存根来注入/拦截对我想要测试的实际 function simpleput(bucket, filename)
的调用。
如果我按照代码所示进行操作,则会出现以下错误:
raise UnStubbedResponseError( botocore.exceptions.UnStubbedResponseError: Error getting response stub for operation PutObject: Unexpected API Call: A call was made but no additional calls expected. Either the API Call was not stubbed or it was called multiple times.
我发现了这个问题。 我只对stubber.add_response(..)进行了一次调用,即stubber.add_response('put_object', response, expected_params)
这意味着我只期望它一次,但是使用以下代码,我进行了 2 次调用,因此出现此错误.
with stubber:
service_response = client.put_object(Body='one\ntwo', Bucket='mybucket', Key='mykey')
simpleput.simpleput('mybucket', 'mykey')
所以只需删除第一个调用(我添加它只是为了测试存根是否正常工作)它就起作用了:
with stubber:
simpleput.simpleput('mybucket', 'mykey')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.