except 블록을 테스트하기 위해 Exception을 발생시키는 함수 모킹
내가 함수 (이 foo또 다른 함수를 호출) ( bar). 호출이 경우 bar()을 제기 HttpError상태 코드는 달리 재 인상, 404 인 경우, 내가 특별히 그것을 처리 할.
이 foo함수에 대한 일부 단위 테스트를 작성 하여 bar(). 불행히도 bar()내 except블록에서 잡은 예외를 발생 시키는 모의 호출을 얻을 수 없습니다 .
내 문제를 설명하는 코드는 다음과 같습니다.
import unittest
import mock
from apiclient.errors import HttpError
class FooTests(unittest.TestCase):
@mock.patch('my_tests.bar')
def test_foo_shouldReturnResultOfBar_whenBarSucceeds(self, barMock):
barMock.return_value = True
result = foo()
self.assertTrue(result) # passes
@mock.patch('my_tests.bar')
def test_foo_shouldReturnNone_whenBarRaiseHttpError404(self, barMock):
barMock.side_effect = HttpError(mock.Mock(return_value={'status': 404}), 'not found')
result = foo()
self.assertIsNone(result) # fails, test raises HttpError
@mock.patch('my_tests.bar')
def test_foo_shouldRaiseHttpError_whenBarRaiseHttpErrorNot404(self, barMock):
barMock.side_effect = HttpError(mock.Mock(return_value={'status': 500}), 'error')
with self.assertRaises(HttpError): # passes
foo()
def foo():
try:
result = bar()
return result
except HttpError as error:
if error.resp.status == 404:
print '404 - %s' % error.message
return None
raise
def bar():
raise NotImplementedError()
나는 다음 모의 문서 는 설정해야합니다 말 side_effect의 Mock에 인스턴스를 Exception조롱 기능 인상을 오류를 가지고 클래스를.
나는 또한 다른 관련 StackOverflow Q & A를 살펴 보았고, 그들이 모의에 의해 발생하는 예외와 똑같은 일을하고있는 것처럼 보입니다.
왜 설정되어 side_effect의 barMock예상 원인이되지 Exception제기 할 수는? 내가 이상한 일을하고 있다면 내 except블록 에서 로직 테스트를 어떻게해야 합니까?
당신의 모의는 예외를 잘 일으키고 있지만 error.resp.status값이 없습니다. 을 사용하는 대신 속성 이라고 return_value말하면됩니다 .Mockstatus
barMock.side_effect = HttpError(mock.Mock(status=404), 'not found')
의 추가 키워드 인수 Mock()는 결과 개체의 특성으로 설정됩니다.
I put your foo and bar definitions in a my_tests module, added in the HttpError class so I could use it too, and your test then can be ran to success:
>>> from my_tests import foo, HttpError
>>> import mock
>>> with mock.patch('my_tests.bar') as barMock:
... barMock.side_effect = HttpError(mock.Mock(status=404), 'not found')
... result = my_test.foo()
...
404 -
>>> result is None
True
You can even see the print '404 - %s' % error.message line run, but I think you wanted to use error.content there instead; that's the attribute HttpError() sets from the second argument, at any rate.
'programing tip' 카테고리의 다른 글
| 일부 플랫폼에서는 char **, 다른 플랫폼에서는 const char **를받는 C ++ 함수를 이식 가능하게 호출 할 수있는 방법은 무엇입니까? (0) | 2020.09.04 |
|---|---|
| scala.concurrent.Promise의 사용 사례는 무엇입니까? (0) | 2020.09.04 |
| xml을 사용하여 Android TextView에서 사용자 정의 글꼴 사용 (0) | 2020.09.04 |
| 2 단계 인증을 사용하여 https를 통해 GitHub에서 Git 클론 (0) | 2020.09.04 |
| 'git pull origin mybranch'는 로컬 mybranch N이 원점보다 먼저 커밋합니다. (0) | 2020.09.04 |