あなたは私はあなたのコードが含まれて私はs3.py
と呼ばれるモジュールにそれらを追加したいくつかのプライベートメソッドのテストされたよう:他のモジュールtest_s3.py
で、私はを考慮あなたのコードをテストし、
import json
def _connect_to_s3():
raise
def _get_customer_bucket(conn):
raise
def _get_customer_key(bucket, customer):
raise
def build_customer_registry_dict(cust):
raise
def write_to_customer_registry(customer):
# establish a connection with S3
conn = _connect_to_s3()
# build customer registry dict and convert it to json
customer_registry_dict = json.dumps(build_customer_registry_dict(customer))
# attempt to access requested bucket
bucket = _get_customer_bucket(conn)
s3_key = _get_customer_key(bucket, customer)
s3_key.set_metadata('Content-Type', 'application/json')
s3_key.set_contents_from_string(customer_registry_dict)
return s3_key
次へユニットテストでは、s3へのネットワークコールなどの第三者とのすべてのやりとりにパッチを当てる必要があります:
from unittest.mock import MagicMock, Mock, patch
from s3 import write_to_customer_registry
import json
@patch('json.dumps', return_value={})
@patch('s3._get_customer_key')
@patch('s3.build_customer_registry_dict')
@patch('s3._get_customer_bucket')
@patch('s3._connect_to_s3')
def test_write_to_customer_registry(connect_mock, get_bucket_mock, build_customer_registry_dict_mock, get_customer_key_mock, json_mock):
customer = MagicMock()
connect_mock.return_value = 'connection'
get_bucket_mock.return_value = 'bucket'
get_customer_key_mock.return_value = MagicMock()
write_to_customer_registry(customer)
assert connect_mock.call_count == 1
assert get_bucket_mock.call_count == 1
assert get_customer_key_mock.call_count == 1
get_bucket_mock.assert_called_with('connection')
get_customer_key_mock.assert_called_with('bucket', customer)
get_customer_key_mock.return_value.set_metadata.assert_called_with('Content-Type', 'application/json')
get_customer_key_mock.return_value.set_contents_from_string.assert_called_with({})
テスト私はset_contents_from_string
が(これはすでにbotoライブラリによってテストされているはずですが)実行されていることをテストしていませんが、適切な引数で呼び出されています。 あなたがまだのbotoライブラリが適切にあなたが常にあなたがテストすることができ、他のboto Githubまたはboto3 Github
何かでそれを自分でチェックすることができるように呼んでテストしていないことを疑う場合は、あなたが適切にあなたのコード内の別の例外とエッジケースを処理しているということです。
最後に、docsでパッチとモックの詳細を確認できます。通常は約where to patchのセクションが本当に便利です。
blog postとpython mock gotchasまたはblog post Stackoverflowで関連するpytest、patching、mocking questionsに回答した後、自分自身(恥知らずな自己プラグ)を書きました。