LoginSignup
5
3

More than 3 years have passed since last update.

【Python】MotoでモックしたAWSリソースをpytestフィクスチャ化する

Last updated at Posted at 2020-01-16

motoとは AWSサービスをモック化できる非常に便利なツール。

spulec/moto - GitHub

これを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())は実行されない。

5
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
3