Skip to content

Instantly share code, notes, and snippets.

@grantcooksey
Last active February 8, 2023 11:21
Show Gist options
  • Save grantcooksey/132ddc85274a50b94b821302649f9d7b to your computer and use it in GitHub Desktop.
Save grantcooksey/132ddc85274a50b94b821302649f9d7b to your computer and use it in GitHub Desktop.
Mocking an S3 bucket using Stubber
import io
import json
import botocore.session
from botocore.stub import Stubber
from botocore.response import StreamingBody
expected_message = {
'message': 'readme'
}
encoded_message = json.dumps(expected_message).encode()
raw_stream = StreamingBody(
io.BytesIO(encoded_message),
len(encoded_message)
)
response = {
'Body': raw_stream
}
expected_params = {
'Bucket': 'test-bucket',
'Key': 'fake'
}
s3 = botocore.session.get_session().create_client('s3')
stubber = Stubber(s3)
stubber.add_response('get_object', response, expected_params)
stubber.activate()
service_response = s3.get_object(Bucket='test-bucket', Key='fake')
message = json.loads(service_response['Body'].read().decode('utf-8'))
assert message == expected_message
@sid22
Copy link

sid22 commented Sep 22, 2020

Thanks a lot for this !

@regebro
Copy link

regebro commented Sep 22, 2020

Thanks!

@antoinedelia
Copy link

Very useful, thanks!

@shrinivdeshmukh
Copy link

Thanks for this. Very useful indeed!

@nojohnny101
Copy link

This is great, thanks so much! Much simpler than using moto (which I found to be slow).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment