moto is a very useful tool that can mock AWS services.
If you combine this with a pytest fixture, you can automatically mock AWS services with setUp in conftest.py
.
Reference-Issue with Moto and creating pytest fixture # 620
SQS example
--Create a mock queue for SQS --Send a message to the mock queue --Verify mock queue messages
import boto3
import pytest
from moto import mock_sqs
import json
@pytest.fixture()
def mock_fixture():
"""Create a queue and send one message"""
mock = mock_sqs()
mock.start() #Start mock
client = boto3.client('sqs')
#Create a mock queue
response = client.create_queue(QueueName='example')
queue_url = response['QueueUrl']
#Send message
client.send_message(QueueUrl=queue_url,
MessageBody=json.dumps({'msg': 'hello'}))
yield client, queue_url #Transition to test here
mock.stop() #End of mock
def test_moto_sqs(mock_fixture):
"""Fixture test"""
client, queue_url = mock_fixture
messages = client.receive_message(QueueUrl=queue_url)['Messages']
assert messages[0]['Body'] == '{"msg": "hello"}'
There are 3 points.
mock.start()
mock.stop()
--The point is to generate fixtures by yield
.If you set it to return
instead of yield
, the teardown process (mock.stop ()
above) will not be executed.
Recommended Posts