Study

Python Testing 기법 기초 내용 정리

chronosa 2020. 6. 7. 18:43

Python Testing 기법 

Mocking

단위 테스트를 작성할 때 외부에 의존하는 부분을 임의의 가짜로 대체하는 기법

Patching

mock.patch

unittest.mock.patch(target, new=DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs)
patch()는 함수 데코레이터, 클래스 데코레이터 또는 컨텍스트 관리자 역할을 합니다. 함수 본문이나 with 문 내부에서, target은 new 객체로 패치됩니다. 함수/with 문이 종료될 때 패치가 복구됩니다.
new가 생략되면, 대상(target)은 패치된 객체가 비동기 함수이면 AsyncMock으로, 그렇지 않으면 MagicMock으로 치환됩니다. patch()가 데코레이터로 사용되고 new가 생략되면, 만들어진 모의 객체는 데코레이트 되는 함수에 대한 추가 인자로 전달됩니다. patch()가 컨텍스트 관리자로 사용되면 만들어진 모의 객체는 컨텍스트 관리자에 의해 반환됩니다.
target은 'package.module.ClassName' 형식의 문자열이어야 합니다. target이 임포트되고 지정된 객체를 new 객체로 치환하므로, patch()를 호출하는 환경에서 target을 임포트 할 수 있어야 합니다. 데코레이트 하는 시간이 아니라 데코레이트 된 함수가 실행될 때 대상(target)을 임포트 합니다.

 

mock.patch.dict

Patch a dictionary, or dictionary like object, and restore the dictionary to its original state after the test.

in_dict can be a dictionary or a mapping like container. If it is a mapping then it must at least support getting, setting and deleting items plus iterating over keys.

in_dict can also be a string specifying the name of the dictionary, which will then be fetched by importing it.

 

참조할 예시 코드는 아래 블로그들에 굉장히 잘 정리가 되어있다.

https://www.daleseo.com/python-unittest-mock-patch/

 

[파이썬] 테스트 모킹 - patch

Engineering Blog by Dale Seo

www.daleseo.com

https://medium.com/uckey/how-mock-patch-decorator-works-in-python-37acd8b78ae

 

How mock.patch decorator works in python

I faced the trouble around mock.patch and parameterized and checked out how these works in general so I would write up here. This post will…

medium.com

 

https://docs.python.org/3/library/unittest.mock.html#patch-dict

 

unittest.mock — mock object library — Python 3.8.3 documentation

Source code: Lib/unittest/mock.py unittest.mock is a library for testing in Python. It allows you to replace parts of your system under test with mock objects and make assertions about how they have been used. unittest.mock provides a core Mock class remov

docs.python.org

 

'Study' 카테고리의 다른 글

Troubleshooting - ERR_CONNECTION_RESET 해결 기록  (0) 2021.02.02
Django Tutorial  (0) 2020.08.30
AWS Lambda/Kinesis Stream Best Practice  (0) 2020.06.07
[Ansible] OS 별 include_tasks 분기  (0) 2020.05.31