motoとは AWSサービスをモック化できる非常に便利なツール。
これをpytestのフィクスチャと組み合わせればconftest.py
のsetUpで自動的にAWSサービスをモックできる。
参考 - Issue with Moto and creating pytest fixture #620
SQSの例
- SQSのモックキューを作成
- モックキューにメッセージ送信
- モックキューのメッセージを検証
import boto3
import pytest
from moto import mock_sqs
import json
@pytest.fixture()
def mock_fixture():
"""キューを作成してメッセージを1件送信する"""
mock = mock_sqs()
mock.start() # モックの開始
client = boto3.client('sqs')
# モックキューを作成
response = client.create_queue(QueueName='example')
queue_url = response['QueueUrl']
# メッセージを送信
client.send_message(QueueUrl=queue_url,
MessageBody=json.dumps({'msg': 'hello'}))
yield client, queue_url # ここでテストに遷移する
mock.stop() # モックの終了
def test_moto_sqs(mock_fixture):
"""フィクスチャのテスト"""
client, queue_url = mock_fixture
messages = client.receive_message(QueueUrl=queue_url)['Messages']
assert messages[0]['Body'] == '{"msg": "hello"}'
ポイントは3点。
mock.start()
mock.stop()
-
yield
によるフィクスチャ生成がポイント。
yield
ではなくreturn
にしてしまうととティアダウン処理(上記のmock.stop()
)は実行されない。