在模拟测试中运行时,如何从要测试的函数中投掷时,如何获得引发异常的功能?
当我在设备测试中实例化Google模拟时,它会立即引发异常。我试图用lambda解决这个问题,但我不确定如何运行lambda。
如何在测试中创建异常,但只能从我要测试的函数中获得它?
#test_add_entry_to_calendar
@patch("add_entry_to_calendar.build")
def test_add_entry_to_calendar_400(self, mock_build):
#google's mock https://googleapis.github.io/google-api-python-client/docs/mocks.html
http = HttpMock('tests/config-test.json', {'status' : '400'})
service = build("calendar", "v3", http=http)
mock_service = mock_build("calendar", "v3", http=http)
mock_service.events.return_value.insert.return_value.execute.return_value = \
lambda x: service.events().insert(calendarId='primary').execute(http=http)
self.assertEqual(add_entry_to_calendar({"A":"B"}), None)
#add_entry_to_calendar.py
def add_entry_to_calendar(entry, calendarID=TARGET_CALENDAR_ID):
#...
try:
service = build("calendar", "v3", credentials=delegated_credentials)
event = service.events().insert(calendarId=calendarID, body=entry).execute()
#prints <function TestAddEntry.test_add_entry_to_calendar_400.<locals>.<lambda> at 0x7f119a53c310>
#But I don't even want to get to this point.
#I want the HttpError 400 to get thrown when I create "event"
print("event is " + str(event))
except HTTPError as e:
print("HTTPError")
When I instantiate a google Mock in my unit test it instantly throws the exception. I tried to fix the issue with a lambda but I am not sure how to then run the lambda.
How do I create the exception in the test but get only get it to throw from from function I want to test?
#test_add_entry_to_calendar
@patch("add_entry_to_calendar.build")
def test_add_entry_to_calendar_400(self, mock_build):
#google's mock https://googleapis.github.io/google-api-python-client/docs/mocks.html
http = HttpMock('tests/config-test.json', {'status' : '400'})
service = build("calendar", "v3", http=http)
mock_service = mock_build("calendar", "v3", http=http)
mock_service.events.return_value.insert.return_value.execute.return_value = \
lambda x: service.events().insert(calendarId='primary').execute(http=http)
self.assertEqual(add_entry_to_calendar({"A":"B"}), None)
#add_entry_to_calendar.py
def add_entry_to_calendar(entry, calendarID=TARGET_CALENDAR_ID):
#...
try:
service = build("calendar", "v3", credentials=delegated_credentials)
event = service.events().insert(calendarId=calendarID, body=entry).execute()
#prints <function TestAddEntry.test_add_entry_to_calendar_400.<locals>.<lambda> at 0x7f119a53c310>
#But I don't even want to get to this point.
#I want the HttpError 400 to get thrown when I create "event"
print("event is " + str(event))
except HTTPError as e:
print("HTTPError")
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不确定这是“ Pythonic”的方式,甚至是正确的方式,但我提出了解决方案。
Not sure if this is the "pythonic" way or even the correct way but I came to a solution.