我有一个简单的功能。哪个内部调用db,但在本地测试期间它无法连接数据库,因此我写了特定的异常,我想做同样的副作用,但它不起作用。
这是我的代码
def support_issue_contact(message, message_headers):
# Check if reporter_email_address is present in message
logger = message_headers.get('logger')
reporter_email = message.get('reporter_email_address', None)
if reporter_email is None:
return None
elif validators.email(reporter_email):
# look up message in our contact table to see if it exists
rule = {
"lookup_documents": [{
"document_type": "hub",
"hub_table": "hubs",
"entity": "contact",
"lookup_key_path": "reporter_email_address"
}]
}
try:
retrieve_documents(message, rule)
except StaleEventException:
return None
# Catch the retrieve_documents function if no 'Item' exists in the response it gets from Dynamo
# If no 'Item' exists then no contact exists so it should create a new contact
except KeyError as valid_exception:
if 'Item' in valid_exception.args:
# validate context to see if it is on 'Item'
contact_message = {
"business_key": reporter_email,
"source_system": 'gsac',
"source_system_id": reporter_email,
"source_sequence": message.get('source_sequence'),
"email": reporter_email,
"full_name": message.get('reporter_display_name', ''),
"customer_domain":
derive_customer_domain(reporter_email),
"status": "ACTIVE",
"id": reporter_email
}
return {
"payload": contact_message,
"schema": "it-bdm/contact-schema-v3.5.json",
"type": "avi:hydra-gsac:contact:upsert",
}
elif ('payload' in valid_exception.args) or ('satellite_name' in valid_exception.args):
# This means that the item exists within the hubs so we don't want to do anything
return None
else:
raise valid_exception
# All other exceptions should be raised
except Exception as e:
logger.error(e.__str__())
raise e
else:
return None
而且我希望retrieve_documents
函数应该提高CustomKeyError
所以我写这些方式并且两者都不起作用。
class SupportIssueContactTest(unittest.TestCase):
raw_event = parse_json_file(os.path.join(DIR_TEST_DATA, 'support-issue', 'support_issue.json'))
transformed_event = parse_json_file(os.path.join(DIR_TEST_DATA, 'support-issue', 'transformed_support_issue.json'))
def test_support_issue_contact_context(self):
with mock.patch('src.datavault_helper.retrieve_documents') as retrieve_documents_mock:
retrieve_documents_mock.side_effect = CustomKeyError()
assert self.transformed_event == support_issue_contact(message=self.raw_event, message_headers={'logger': config.logger})
@mock.patch('src.datavault_helper.retrieve_documents')
def test_support_issue_contact_decorator(self, retrieve_documents_mock):
retrieve_documents_mock.side_effect = CustomKeyError()
assert self.transformed_event == support_issue_contact(message=self.raw_event,
message_headers={'logger': config.logger})
我想出了答案。
def test_support_issue_contact_context(self):
with mock.patch('path_of_function_where_it_is_called_for_mock') as retrieve_documents_mock:
retrieve_documents_mock.side_effect = CustomKeyError()
assert self.transformed_event == support_issue_contact(message=self.raw_event, message_headers={'logger': config.logger})