[Python] Make AWS resources mocked with Moto into pytest fixtures

moto is a very useful tool that can mock AWS services.

spulec/moto - GitHub

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.

If you set it to return instead of yield, the teardown process (mock.stop () above) will not be executed.

Recommended Posts

[Python] Make AWS resources mocked with Moto into pytest fixtures
Make Python scripts into Windows-executable .exes with Pyinstaller
Make JSON into CSV with Python from Splunk
AWS CDK with Python
Make ordinary tweets fleet-like with AWS Lambda and Python
Make Puyo Puyo AI with Python
Make a fortune with Python
Let's make a web chat using WebSocket with AWS serverless (Python)!
Make Echolalia LINEbot with Python + heroku
Let's make a GUI with python.
Text extraction with AWS Textract (Python3.6)
Make a recommender system with python
Let's make a graph with python! !!
Notify HipChat with AWS Lambda (Python)
[AWS] [GCP] I tried to make cloud services easy to use with Python
[AWS] Using ini files with Lambda [Python]
Put protocol buffers into sqlite with python
Fractal to make and play with Python
Let's make a voice slowly with Python
I want to play with aws with python
Make pypy submission easier with atcoder-cli (python)
[Python] Let's make matplotlib compatible with Japanese
Connect to s3 with AWS Lambda Python
Let's make a web framework with Python! (1)
Make a desktop app with Python with Electron
Let's make a Twitter Bot with Python!
Let's make a web framework with Python! (2)
Touch AWS with Serverless Framework and Python
Python + Selenium + Headless Chromium with aws lambda
Boto3 (manipulate AWS resources with Python library) API that is often used privately