unittest.mock を使用して呼び出しを監視する
このステップでは、unittest.mock モジュールを使用して関数呼び出しを監視する方法を探ります。unittest.mock モジュールは、テストとデバッグに強力なツールであり、関数の呼び出し、引数、戻り値を追跡する便利な方法を提供します。
前のステップの greet 関数を引き続き使用しましょう。unittest.mock を使って greet 関数の呼び出しを監視します。
~/project ディレクトリの my_function.py ファイルを変更して、以下のコードを含めます。
## ~/project/my_function.py
from unittest import mock
def greet(name):
"""This function greets the person passed in as a parameter."""
print(f"Hello, {name}!")
## Create a mock object for the greet function
mock_greet = mock.Mock(wraps=greet)
## Example usage
mock_greet("Alice")
mock_greet("Bob")
## Print the number of times the function was called
print(f"The greet function was called {mock_greet.call_count} times.")
## Print the arguments the function was called with
print(f"The calls were: {mock_greet.call_args_list}")
このコードでは、以下のことを行っています。
unittest から mock モジュールをインポートします。
greet 関数をラップする mock.Mock オブジェクトを作成します。wraps 引数は、モックオブジェクトが呼び出されたときに元の greet 関数を呼び出すように指示します。
- その後、元の
greet 関数の代わりに mock_greet オブジェクトを呼び出します。
- 最後に、モックオブジェクトの
call_count と call_args_list 属性を使用して、関数呼び出しに関する情報を取得します。
同じコマンドを使用してスクリプトを再度実行します。
python ~/project/my_function.py
以下のような出力が表示されるはずです。
Hello, Alice!
Hello, Bob!
The greet function was called 2 times.
The calls were: [call('Alice'), call('Bob')]
この出力は、greet 関数が 2 回呼び出されたことを示しており、各呼び出しで関数に渡された引数も表示されています。
次に、call_args_list をもう少し詳しく調べてみましょう。これは call オブジェクトのリストで、それぞれがモック化された関数の 1 回の呼び出しを表しています。call オブジェクトの args と kwargs 属性を使用して、各呼び出しの引数にアクセスすることができます。
たとえば、最初の呼び出しの引数を出力するようにコードを変更してみましょう。
## ~/project/my_function.py
from unittest import mock
def greet(name):
"""This function greets the person passed in as a parameter."""
print(f"Hello, {name}!")
## Create a mock object for the greet function
mock_greet = mock.Mock(wraps=greet)
## Example usage
mock_greet("Alice")
mock_greet("Bob")
## Print the number of times the function was called
print(f"The greet function was called {mock_greet.call_count} times.")
## Print the arguments the function was called with
print(f"The calls were: {mock_greet.call_args_list}")
## Print the arguments of the first call
if mock_greet.call_args_list:
print(f"The arguments of the first call were: {mock_greet.call_args_list[0].args}")
スクリプトを再度実行します。
python ~/project/my_function.py
以下のような出力が表示されるはずです。
Hello, Alice!
Hello, Bob!
The greet function was called 2 times.
The calls were: [call('Alice'), call('Bob')]
The arguments of the first call were: ('Alice',)
この出力は、greet 関数への最初の呼び出しが引数 "Alice" で行われたことを示しています。
unittest.mock モジュールは、Python で関数呼び出しを監視する強力で柔軟な方法を提供します。これは、テスト、デバッグ、パフォーマンス分析にとって貴重なツールです。