반응형
Python mock의 모의 속성?
mock
Python에서 사용하는 데 많은 어려움이 있습니다 .
def method_under_test():
r = requests.post("http://localhost/post")
print r.ok # prints "<MagicMock name='post().ok' id='11111111'>"
if r.ok:
return StartResult()
else:
raise Exception()
class MethodUnderTestTest(TestCase):
def test_method_under_test(self):
with patch('requests.post') as patched_post:
patched_post.return_value.ok = True
result = method_under_test()
self.assertEqual(type(result), StartResult,
"Failed to return a StartResult.")
시험은 올바른 값을 반환하지만 r.ok
모의 목적 True
. 에서는 mock
라이브러리 에서 속성을 어떻게 모의 소개?
return_value
및 다음 을을합니다 .PropertyMock
with patch('requests.post') as patched_post:
type(patched_post.return_value).ok = PropertyMock(return_value=True)
즉 requests.post
,을 호출 할 때 해당 호출 의 반환 값 에서 값을 반환하도록 PropertyMock
속성 ok
에 대해 를 설정 합니다 True
.
수행하는 간결이를하고 간단한 방법은 new_callable
patch
의 속성 을 사용하여 모의 object-를 만드는 대신 강제 patch
로 사용하는 PropertyMock
을 구석으로입니다 MagicMock
. 전달 된 다른 인수는 개체 patch
를 만드는 데 사용 PropertyMock
됩니다.
with patch('requests.post', new_callable=PropertyMock, return_value=True) as mock_post:
"""Your test"""
모의 버전 '1.0.1'에서는 질문에 언급 된 더 간단한 구문이 지원되고있는 그대로 작동합니다!
업데이트 된 예제 코드 (unittest 대신 py.test가 사용됨) :
import mock
import requests
def method_under_test():
r = requests.post("http://localhost/post")
print r.ok
if r.ok:
return r.ok
else:
raise Exception()
def test_method_under_test():
with mock.patch('requests.post') as patched_post:
patched_post.return_value.ok = True
result = method_under_test()
assert result is True, "mock ok failed"
이 코드를 다음과 같이 실행하십시오. (pytest를 설치했는지 확인하십시오)
$ py.test -s -v mock_attributes.py
======= test session starts =======================
platform linux2 -- Python 2.7.10 -- py-1.4.30 -- pytest-2.7.2 -- /home/developer/miniconda/bin/python
rootdir: /home/developer/projects/learn/scripts/misc, inifile:
plugins: httpbin, cov
collected 1 items
mock_attributes.py::test_method_under_test True
PASSED
======= 1 passed in 0.03 seconds =================
참고 URL : https://stackoverflow.com/questions/16867509/mock-attributes-in-python-mock
반응형
'ProgramingTip' 카테고리의 다른 글
UIWebView에서 앱 URL을 처리하는 방법은 무엇입니까? (0) | 2020.12.01 |
---|---|
PDF를 병합하는 Ghostscript는 결과를 압축합니다. (0) | 2020.12.01 |
SHA512에서 해시 된 길이는 얼마입니까? (0) | 2020.12.01 |
Golang 메모리를 분석하는 방법? (0) | 2020.12.01 |
Runnable :: new 대 new Runnable () (0) | 2020.12.01 |