0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

pytest時に mock_aws と実リソースを切り替える

Posted at

pytest時に mock_aws と実リソースを切り替える

準備

with で mock_aws を使用するか環境変数に任せるかを選択し、テストコードを実行します。
サンプルコードでは AWS_INTEGRATION という環境変数に 0 を設定することで mock 試験、1 を設定することで実際のAWS環境を使用となっています。


from contextlib import contextmanager
import boto3
import os

"""
MOCK or 実環境のフラグ
# mock 環境
export AWS_INTEGRATION=0
# 実環境
export AWS_INTEGRATION=1
"""

@contextmanager
def mock_or_aws():
    if os.getenv("AWS_INTEGRATION", "0") == "1":
        yield
    else:
        with mock_aws():
            yield

@pytest.fixture
def dynamodb_client():
    with mock_or_aws():
        yield boto3.resource('dynamodb')

使い方

def test_create_account_ok(dynamodb_client):
    with mock_or_aws(): # 環境変数によりmockかAWSを使うか選択される
        create_tables()
        create_test_records()
        resp = AccountService().create_account()
        # ~ 省略 ~

以上です

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?