Example #1
0
def test_bad_config(log_mock):
    """Load output config - bad config"""
    mock = mock_open(read_data='non-json string that will log an error')
    with patch('__builtin__.open', mock):
        handler(None, None)

    log_mock.assert_called_with(
        'The \'%s\' file could not be loaded into json', 'conf/outputs.json')
Example #2
0
def test_handler_run(run_mock):
    """Main handler `run` call params"""
    context = get_mock_context()
    handler(None, context)

    # This test will load the actual config, so we should compare the
    # function call against the same config here.
    run_mock.assert_called_with(None, REGION, FUNCTION_NAME, _load_output_config())
Example #3
0
def test_handler_run(run_mock):
    """Main handler `run` call params"""
    context = _get_mock_context()
    message = {'default': {'record': {'size': '9982'}}}
    event = {'Records': [{'Sns': {'Message': json.dumps(message)}}]}
    handler(event, context)

    # This test will load the actual config, so we should compare the
    # function call against the same config here.
    run_mock.assert_called_with(message, REGION, FUNCTION_NAME,
                                _load_output_config())
Example #4
0
def test_handler_malformed_message(log_mock):
    """Main handler decode failure logging"""
    # The @patch() decorator allows us to 'introspect' what occurs down the chain
    # and verify the params a function was LAST called with. For instance, here
    # we are checking the last call to `logging.Logger.error` and verifying that the
    # function was called with two params, the first being 'Malformed SNS: %s' and
    # the second being the dictionary contained within `message`
    # This call should happen at stream_alert/alert_processor/main.py:62
    context = _get_mock_context()
    message = {'not_default': {'record': {'size': '9982'}}}
    event = {'Records': [{'Sns': {'Message': json.dumps(message)}}]}
    handler(event, context)

    log_mock.assert_called_with('Malformed SNS: %s', message)
Example #5
0
    def test_processor(self, alerts):
        """Perform integration tests for the 'alert' Lambda function. Alerts
        that are fed through this are resultant from the rule processor tests.
        In order to end up here, the log must be configured to trigger a rule
        that would result in an alert being sent.

        Args:
            alerts (list): list of alerts to be processed that have been fed in
                from the rule processor.

        Return:
            bool: status of the alert processor dispatching
        """
        # Set the logger level to info so its not too noisy
        StreamOutput.LOGGER.setLevel(logging.ERROR)
        for alert in alerts:
            if self.context.mocked:
                self.setup_outputs(alert)

            # Convert alert to the Dynamo event format expected by the alert processor
            event = alert.dynamo_record()
            event['Outputs'] = list(event['Outputs'])

            for output, current_test_passed in StreamOutput.handler(
                    event, self.context).items():
                self.all_tests_passed = current_test_passed and self.all_tests_passed
                service, descriptor = output.split(':')
                message = 'sending alert to \'{}\''.format(descriptor)
                report_output(current_test_passed,
                              ['', 'alert', service, message])

                self._alert_fail_pass[current_test_passed] += 1
Example #6
0
def test_handler_return():
    """Main handler return value"""
    context = get_mock_context()
    event = {'Records': []}
    value = handler(event, context)

    assert_is_instance(value, list)
Example #7
0
    def test_processor(self, alerts):
        """Perform integration tests for the 'alert' Lambda function. Alerts
        that are fed through this are resultant from the rule processor tests.
        In order to end up here, the log must be configured to trigger a rule
        that would result in an alert being sent.

        Args:
            alerts [list]: list of alerts to be processed that have been fed in
                from the rule processor.

        Return:
            [bool] boolean indicating the status of the alert processor dispatching
        """
        # Set the logger level to info so its not too noisy
        StreamOutput.LOGGER.setLevel(logging.ERROR)
        for alert in alerts:
            if self.context.mocked:
                self.setup_outputs(alert)

            for current_test_passed, output in StreamOutput.handler(alert, self.context):
                self.all_tests_passed = current_test_passed and self.all_tests_passed
                service, descriptor = output.split(':')
                message = 'sending alert to \'{}\''.format(descriptor)
                report_output([
                    current_test_passed,
                    '',
                    'alert',
                    service,
                    message
                ])

                self._alert_fail_pass[current_test_passed] += 1
Example #8
0
    def test_handler(self, mock_run):
        """Alert Processor - Lambda Handler"""
        context = MagicMock()
        context.invoked_function_arn = _ARN

        result = handler(_EVENT, context)
        mock_run.assert_called_once_with(_EVENT)
        assert_equal({'out1': True}, result)
Example #9
0
 def test_handler(self, mock_run):
     """Alert Processor - Lambda Handler"""
     context = MagicMock()
     context.invoked_function_arn = _ARN
     event = {'AlertID': 'abc', 'RuleName': 'hello_world'}
     result = handler(event, context)
     assert_equal({'output': True}, result)
     mock_run.assert_called_once_with(event)
Example #10
0
def test_handler_bad_message(log_mock):
    """Main handler decode failure logging"""
    context = _get_mock_context()
    event = {
        'Records': [{
            'Sns': {
                'Message': 'this\nvalue\nshould\nfail\nto\ndecode'
            }
        }]
    }
    handler(event, context)

    assert_equal(
        str(log_mock.call_args_list[0]),
        str(
            call('An error occurred while decoding message to JSON: %s',
                 ValueError('No JSON object could be decoded', ))))
Example #11
0
def test_running_exception_occurred(creds_mock, dispatch_mock, config_mock, get_mock, log_mock):
    """Alert Processor run handler - exception occurred"""
    # Use TypeError as the mock's side_effect
    err = TypeError('bad error')
    creds_mock.return_value = {'url': 'mock.url'}
    dispatch_mock.return_value.dispatch.side_effect = err
    config_mock.return_value = _load_output_config('tests/unit/conf/outputs.json')
    get_mock.return_value.status_code = 200

    alert = _sort_dict(get_alert())
    context = get_mock_context()

    handler(alert, context)

    log_mock.assert_called_with(
        'An error occurred while sending alert '
        'to %s:%s: %s. alert:\n%s', 'slack', 'unit_test_channel',
        err, json.dumps(alert, indent=2))
Example #12
0
def test_running_no_dispatcher(dispatch_mock, config_mock):
    """Alert Processor run handler - no dispatcher"""
    config_mock.return_value = _load_output_config('tests/unit/conf/outputs.json')
    dispatch_mock.return_value = None

    alert = get_alert()
    context = get_mock_context()

    result = handler(alert, context)

    assert_is_instance(result, list)
    assert_list_equal(result, [])
Example #13
0
def test_running_bad_output(config_mock, log_mock):
    """Alert Processor run handler - bad output"""
    config_mock.return_value = _load_output_config('tests/unit/conf/outputs.json')

    alert = get_alert()
    alert['outputs'] = ['slack']
    context = get_mock_context()

    handler(alert, context)

    log_mock.assert_called_with(
        'Improperly formatted output [%s]. Outputs for rules must '
        'be declared with both a service and a descriptor for the '
        'integration (ie: \'slack:my_channel\')', 'slack')

    alert['outputs'] = ['slakc:test']

    handler(alert, context)

    log_mock.assert_called_with(
        'The output \'%s\' does not exist!', 'slakc:test')
Example #14
0
def test_running_success(creds_mock, config_mock, get_mock):
    """Alert Processor run handler - success"""
    config_mock.return_value = _load_output_config('tests/unit/conf/outputs.json')
    creds_mock.return_value = {'url': 'http://mock.url'}
    get_mock.return_value.status_code = 200

    alert = get_alert()
    context = get_mock_context()

    result = handler(alert, context)
    assert_is_instance(result, list)

    assert_true(result[0][0])
Example #15
0
    def test_processor(self, alerts):
        """Perform integration tests for the 'alert' Lambda function. Alerts
        that are fed through this are resultant from the rule processor tests.
        In order to end up here, the log must be configured to trigger a rule
        that would result in an alert being sent.

        Args:
            alerts [list]: list of alerts to be processed that have been fed in
                from the rule processor.
            url_mock [mock.patch]: patch to mock out urlopen calls

        Return:
            [bool] boolean indicating the status of the alert processor dispatching
        """
        status = True
        # Set the logger level to info so its not too noisy
        StreamOutput.LOGGER.setLevel(logging.ERROR)
        for alert in alerts:
            # Establish the mocked outputs if the context is being mocked
            if self.context.mocked:
                self.setup_outputs(alert)
            event = {
                'Records': [{
                    'Sns': {
                        'Message': json.dumps({'default': alert})
                    }
                }]
            }
            for passed, output in StreamOutput.handler(event, self.context):
                status = status and passed
                service, descriptor = output.split(':')
                message = 'sending alert to \'{}\''.format(descriptor)
                report_output([passed, '', 'alert', service, message])

                self._alert_fail_pass[passed] += 1

        return status
Example #16
0
 def test_handler(self, mock_run):
     """Alert Processor - Lambda Handler"""
     event = {'AlertID': 'abc', 'RuleName': 'hello_world'}
     result = handler(event, None)
     assert_equal({'output': True}, result)
     mock_run.assert_called_once_with(event)