Как смоделировать побочный эффект внутренней функции - PullRequest
0 голосов
/ 03 апреля 2019

HI У меня есть простая функция. Который внутренне вызывает 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})

1 Ответ

0 голосов
/ 05 апреля 2019

Я разобрался с ответом.

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})
...