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 함수가 두 번 호출되었음을 보여주며, 각 호출에서 함수에 전달된 인수도 표시합니다.
이제 call_args_list를 자세히 살펴보겠습니다. 이는 call 객체의 목록이며, 각 객체는 모의 함수에 대한 단일 호출을 나타냅니다. 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 에서 함수 호출을 모니터링하는 강력하고 유연한 방법을 제공합니다. 이는 테스트, 디버깅 및 성능 분석을 위한 귀중한 도구입니다.