2
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?

More than 1 year has passed since last update.

【Python+dynamodb-local】引継ぎしたシステムにテストがなかったので実装してみたお話

Posted at

はじめに

引継ぎしたシステムにテストの実装を試みたので簡単にまとめてみます。
コード内容はぼかしています。

技術(一部)

  • Docker
  • Python
  • DynamoDB、dynamodb-local
  • 他各種AWSサービス

状況

  • プロトタイプとして作成されたシステムだったため、テストまでは手を付けられていなかった
  • 同様の理由で、コードも単一責任の原則に従っていなかった
  • 例えばsend_mailという関数で以下の処理が実装されていた
    • トークンの発行
    • トークンとメールアドレスをDBに保存
    • メール送信

テスト対象例

# トークンの発行/トークンとメールアドレスをDBに保存/メール送信
def send_enabled_mail(params):
    token = トークンを発行する関数
    url = 認証URL
    message = メール本文

    to_email = params['address']
    response = add_token(token, to_email)
    if response["statusCode"] == 200:
        r = hogehoge.send_email(message, to_email)
        return r

テストコード例

# メール内容のテスト(一部)
def test_send_enabled_mail(params):
    FROM = os.environ.get('FROM')
    DOMAIN_NAME = os.environ.get('DOMAIN_NAME')

    session = boto3.Session(profile_name='default')
    ses = session.client('ses', region_name='ap-northeast-1')

    ses.verify_email_identity(EmailAddress=FROM)
    params['address'] = FROM
    
    response = send_mail(params)
    assert response['statusCode'] == 200
    actual_body = response['body']['Body']
    assert 'hogehoge@hoge.jp' in actual_body

    dynamodb.delete_table(TableName='hogehoge')

やったこと

  • テスト対象の関数(send_enabled_mail)にadd_token関数とsend_email関数が含まれているのでそれぞれのテストを書く
  • add_token関数でローカルのdynamodbに接続できるようにdynamodb-local環境の設定を追加
  • send_email関数ではstatus codeしか返していなかったのでメール本文も返すように修正
  • SESや依存している関数などはモック

おわりに

引継ぎ時点でテストを実装できれば良かったのかもしれませんが、任されるタスクの緊急度やシステムの理解度などから後々の対応となってしまいました。時間がなくてテストを書けないという人の気持ちが少し分かったような気がします。

2
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
2
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?