def test_victorops_message_type(message_type, except_message_type): rule = { 'name': 'Test VictorOps Rule', 'type': 'any', 'victorops_api_key': 'xxxx1', 'victorops_routing_key': 'xxxx2', 'victorops_message_type': message_type, 'victorops_entity_display_name': 'no entity display name', 'alert': [] } rules_loader = FileRulesLoader({}) rules_loader.load_modules(rule) alert = VictorOpsAlerter(rule) match = {'@timestamp': '2021-01-01T00:00:00', 'somefield': 'foobarbaz'} with mock.patch('requests.post') as mock_post_request: alert.alert([match]) expected_data = { 'message_type': except_message_type, 'entity_display_name': rule['victorops_entity_display_name'], 'monitoring_tool': 'ElastAlert', 'state_message': 'Test VictorOps Rule\n\n@timestamp: 2021-01-01T00:00:00\nsomefield: foobarbaz\n', '@timestamp': '2021-01-01T00:00:00', 'somefield': 'foobarbaz' } mock_post_request.assert_called_once_with( 'https://alert.victorops.com/integrations/generic/20131114/alert/xxxx1/xxxx2', data=mock.ANY, headers={'content-type': 'application/json'}, proxies=None) actual_data = json.loads(mock_post_request.call_args_list[0][1]['data']) assert expected_data == actual_data
def test_ses_create_default_title(query_key, expected_data): rule = { 'name': 'Test SES rule!', 'alerta_api_url': 'http://*****:*****@timestamp', 'type': 'any', 'alert': 'alerta' } if query_key: rule['query_key'] = query_key match = [{ '@timestamp': '2014-10-10T00:00:00', 'sender_ip': '1.1.1.1', 'hostname': 'aProbe' }, { '@timestamp': '2014-10-10T00:00:00', 'sender_ip': '1.1.1.1', 'hostname2': 'aProbe' }] rules_loader = FileRulesLoader({}) rules_loader.load_modules(rule) alert = SesAlerter(rule) result = alert.create_default_title(match) assert expected_data == result
def test_tencentsms_template_parm(tencent_sms_template_parm, expected_data): rule = { 'name': 'Test tencentsms Template Parm', 'type': 'any', 'alert': ["tencent_sms"], "tencent_sms_secret_id": "secret_id", "tencent_sms_secret_key": "secret_key", "tencent_sms_sdk_appid": "1400006666", "tencent_sms_to_number": ["+8613711112222"], "tencent_sms_template_id": "1123835", "tencent_sms_template_parm": tencent_sms_template_parm } rules_loader = FileRulesLoader({}) rules_loader.load_modules(rule) alert = TencentSMSAlerter(rule) match = [{ "kubernetes": { "namespace_name": "nginx", "pod_name": "ngin.nginx-6bd96d6f74-2ts4x" }, "time": "2021-09-04T03:13:24.192875Z", "message": "2021-09-03T14:34:08+0000|INFO|vector eps : 192.168.0.2:10000,", }] actual = alert.create_template_parm(match) assert expected_data == actual
def test_twilio_use_copilot(twilio_use_copilot, twilio_message_service_sid, twilio_from_number, expected_data): try: rule = { 'name': 'Test Rule', 'type': 'any', 'alert_subject': 'Cool subject', 'twilio_account_sid': 'xxxxx1', 'twilio_auth_token': 'xxxxx2', 'twilio_to_number': 'xxxxx3', 'alert': [] } if twilio_use_copilot: rule['twilio_use_copilot'] = twilio_use_copilot if twilio_message_service_sid: rule['twilio_message_service_sid'] = twilio_message_service_sid if twilio_from_number: rule['twilio_from_number'] = twilio_from_number rules_loader = FileRulesLoader({}) rules_loader.load_modules(rule) alert = TwilioAlerter(rule) match = {'@timestamp': '2021-01-01T00:00:00', 'somefield': 'foobarbaz'} alert.alert([match]) except EAException: assert expected_data
def test_chatwork_maxlength(): rule = { 'name': 'Test Chatwork Rule' + ('a' * 2069), 'type': 'any', 'chatwork_apikey': 'xxxx1', 'chatwork_room_id': 'xxxx2', 'alert': [] } rules_loader = FileRulesLoader({}) rules_loader.load_modules(rule) alert = ChatworkAlerter(rule) match = {'@timestamp': '2021-01-01T00:00:00', 'somefield': 'foobarbaz'} with mock.patch('requests.post') as mock_post_request: alert.alert([match]) expected_data = { 'body': 'Test Chatwork Rule' + ('a' * 1932) + '\n *message was cropped according to chatwork embed description limits!*' } mock_post_request.assert_called_once_with( 'https://api.chatwork.com/v2/rooms/xxxx2/messages', params=mock.ANY, headers={'X-ChatWorkToken': 'xxxx1'}, proxies=None, auth=None) actual_data = mock_post_request.call_args_list[0][1]['params'] assert expected_data == actual_data
def test_stomp_ea_exception(): with pytest.raises(EAException) as ea: rule = { 'name': 'Test Rule', 'type': 'any', 'timestamp_field': '@timestamp', 'alert_subject': 'Cool subject', 'stomp_hostname': 'localhost', 'stomp_hostport': '61613', 'stomp_login': '******', 'stomp_password': '******', 'alert': [], 'rule_file': '/tmp/foo.yaml' } match = { '@timestamp': '2021-01-10T00:00:00', 'sender_ip': '1.1.1.1', 'hostname': 'aProbe' } rules_loader = FileRulesLoader({}) rules_loader.load_modules(rule) alert = StompAlerter(rule) alert.alert([match]) assert 'Error posting to Stomp: ' in str(ea)
def test_twilio(caplog): caplog.set_level(logging.INFO) rule = { 'name': 'Test Rule', 'type': 'any', 'alert_subject': 'Cool subject', 'twilio_account_sid': 'xxxxx1', 'twilio_auth_token': 'xxxxx2', 'twilio_to_number': 'xxxxx3', 'twilio_from_number': 'xxxxx4', 'alert': [] } match = { '@timestamp': '2021-01-10T00:00:00', 'sender_ip': '1.1.1.1', 'hostname': 'aProbe' } rules_loader = FileRulesLoader({}) rules_loader.load_modules(rule) with mock.patch( 'elastalert.alerters.twilio.TwilioClient.messages') as mock_twilio: mock_twilio.messages.create() mock_twilio.return_value = 200 alert = TwilioAlerter(rule) alert.alert([match]) expected = [ mock.call.messages.create(), mock.call.create(body='Test Rule', from_='xxxxx4', to='xxxxx3'), ] assert mock_twilio.mock_calls == expected assert ('elastalert', logging.INFO, 'Trigger sent to Twilio') == caplog.record_tuples[0]
def test_get_json_payload_error(): rule = { 'name': 'Test Alerta rule!', 'alerta_api_url': 'http://*****:*****@timestamp', 'type': 'any', 'alert': 'alerta', 'query_key': 'hostname' } match = { '@timestamp': '2014-10-10T00:00:00', 'sender_ip': '1.1.1.1', 'hostname': 'aProbe' } rules_loader = FileRulesLoader({}) rules_loader.load_modules(rule) alert = AlertaAlerter(rule) mock_run = mock.MagicMock(side_effect=Exception) with mock.patch('json.dumps', mock_run): with pytest.raises(Exception) as e: alert.get_json_payload(match) assert 'Error building Alerta request: ' in str(e)
def test_exotel_status_cod_not_200(): with pytest.raises(EAException) as ea: rule = { 'name': 'Test Rule', 'type': 'any', 'alert_subject': 'Cool subject', 'exotel_account_sid': 'xxxxx1', 'exotel_auth_token': 'xxxxx2', 'exotel_to_number': 'xxxxx3', 'exotel_from_number': 'xxxxx4', 'alert': [] } match = { '@timestamp': '2021-01-10T00:00:00', 'sender_ip': '1.1.1.1', 'hostname': 'aProbe' } rules_loader = FileRulesLoader({}) rules_loader.load_modules(rule) with mock.patch( 'elastalert.alerters.exotel.Exotel.sms') as mock_exotel: mock_exotel.return_value = 201 alert = ExotelAlerter(rule) alert.alert([match]) assert 'Error posting to Exotel, response code is' in str(ea)
def test_line_notify(caplog): caplog.set_level(logging.INFO) rule = { 'name': 'Test LineNotify Rule', 'type': 'any', 'linenotify_access_token': 'xxxxx', 'alert': [] } rules_loader = FileRulesLoader({}) rules_loader.load_modules(rule) alert = LineNotifyAlerter(rule) match = {'@timestamp': '2021-01-01T00:00:00', 'somefield': 'foobarbaz'} with mock.patch('requests.post') as mock_post_request: alert.alert([match]) expected_data = { 'message': 'Test LineNotify Rule\n\n@timestamp: 2021-01-01T00:00:00\nsomefield: foobarbaz\n' } mock_post_request.assert_called_once_with( 'https://notify-api.line.me/api/notify', data=mock.ANY, headers={ 'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': 'Bearer {}'.format('xxxxx') }) actual_data = mock_post_request.call_args_list[0][1]['data'] assert expected_data == actual_data assert ('elastalert', logging.INFO, 'Alert sent to Line Notify') == caplog.record_tuples[0]
def test_alerta_auth(): rule = { 'name': 'Test Alerta rule!', 'alerta_api_url': 'http://*****:*****@timestamp', 'alerta_severity': "debug", 'type': 'any', 'alerta_use_match_timestamp': True, 'alert': 'alerta' } match = { '@timestamp': '2014-10-10T00:00:00', 'sender_ip': '1.1.1.1', 'hostname': 'aProbe' } rules_loader = FileRulesLoader({}) rules_loader.load_modules(rule) alert = AlertaAlerter(rule) with mock.patch('requests.post') as mock_post_request: alert.alert([match]) mock_post_request.assert_called_once_with(alert.url, data=mock.ANY, verify=True, headers={ 'content-type': 'application/json', 'Authorization': 'Key {}'.format( rule['alerta_api_key']) })
def test_line_notify_maxlength(): rule = { 'name': 'Test LineNotify Rule' + ('a' * 1000), 'type': 'any', 'linenotify_access_token': 'xxxxx', 'alert': [] } rules_loader = FileRulesLoader({}) rules_loader.load_modules(rule) alert = LineNotifyAlerter(rule) match = {'@timestamp': '2021-01-01T00:00:00', 'somefield': 'foobarbaz'} with mock.patch('requests.post') as mock_post_request: alert.alert([match]) expected_data = { 'message': 'Test LineNotify Rule' + ('a' * 880) + '\n *message was cropped according to line notify embed description limits!*' } mock_post_request.assert_called_once_with( 'https://notify-api.line.me/api/notify', data=mock.ANY, headers={ 'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': 'Bearer {}'.format('xxxxx') }) actual_data = mock_post_request.call_args_list[0][1]['data'] assert expected_data == actual_data
def test_debug_alerter_querykey(caplog): caplog.set_level(logging.INFO) rule = { 'name': 'Test Debug Event Alerter', 'type': 'any', 'alert': [], 'timestamp_field': 'timestamp', 'query_key': 'hostname' } rules_loader = FileRulesLoader({}) rules_loader.load_modules(rule) alert = DebugAlerter(rule) match = { '@timestamp': '2021-01-01T00:00:00', 'name': 'debug-test-name', 'hostname': 'aProbe' } alert.alert([match]) excepted1 = 'Alert for Test Debug Event Alerter, aProbe at None:' assert ('elastalert', logging.INFO, excepted1) == caplog.record_tuples[0] excepted2 = 'Test Debug Event Alerter\n\n@timestamp: 2021-01-01T00:00:00\n' excepted2 += 'hostname: aProbe\nname: debug-test-name\n' assert ('elastalert', logging.INFO, excepted2) == caplog.record_tuples[1]
def test_gitter_proxy(): rule = { 'name': 'Test Gitter Rule', 'type': 'any', 'gitter_webhook_url': 'https://webhooks.gitter.im/e/xxxxx', 'gitter_msg_level': 'error', 'gitter_proxy': 'http://proxy.url', 'alert': [] } rules_loader = FileRulesLoader({}) rules_loader.load_modules(rule) alert = GitterAlerter(rule) match = { '@timestamp': '2021-01-01T00:00:00', 'somefield': 'foobarbaz' } with mock.patch('requests.post') as mock_post_request: alert.alert([match]) expected_data = { 'message': 'Test Gitter Rule\n\n@timestamp: 2021-01-01T00:00:00\nsomefield: foobarbaz\n', 'level': 'error' } mock_post_request.assert_called_once_with( rule['gitter_webhook_url'], data=mock.ANY, headers={'content-type': 'application/json'}, proxies={'https': 'http://proxy.url'} ) actual_data = json.loads(mock_post_request.call_args_list[0][1]['data']) assert expected_data == actual_data
def test_pagerduty_alerter_custom_alert_subject(): rule = { 'name': 'Test PD Rule', 'type': 'any', 'alert_subject': 'Hungry kittens', 'pagerduty_service_key': 'magicalbadgers', 'pagerduty_client_name': 'ponies inc.', 'pagerduty_incident_key': 'custom {0}', 'pagerduty_incident_key_args': ['somefield'], 'alert': [] } rules_loader = FileRulesLoader({}) rules_loader.load_modules(rule) alert = PagerDutyAlerter(rule) match = {'@timestamp': '2017-01-01T00:00:00', 'somefield': 'foobarbaz'} with mock.patch('requests.post') as mock_post_request: alert.alert([match]) expected_data = { 'client': 'ponies inc.', 'description': 'Hungry kittens', 'details': { 'information': 'Test PD Rule\n\n@timestamp: 2017-01-01T00:00:00\nsomefield: foobarbaz\n' }, 'event_type': 'trigger', 'incident_key': 'custom foobarbaz', 'service_key': 'magicalbadgers', } mock_post_request.assert_called_once_with( alert.url, data=mock.ANY, headers={'content-type': 'application/json'}, proxies=None) assert expected_data == json.loads( mock_post_request.call_args_list[0][1]['data'])
def test_exotel_request_error(): with pytest.raises(EAException) as ea: rule = { 'name': 'Test Rule', 'type': 'any', 'alert_subject': 'Cool subject', 'exotel_account_sid': 'xxxxx1', 'exotel_auth_token': 'xxxxx2', 'exotel_to_number': 'xxxxx3', 'exotel_from_number': 'xxxxx4', 'alert': [] } match = { '@timestamp': '2021-01-10T00:00:00', 'sender_ip': '1.1.1.1', 'hostname': 'aProbe' } rules_loader = FileRulesLoader({}) rules_loader.load_modules(rule) mock_run = mock.MagicMock(side_effect=RequestException) with mock.patch( 'elastalert.alerters.exotel.Exotel.sms', mock_run), pytest.raises(RequestException) as mock_exotel: mock_exotel.return_value = 200 alert = ExotelAlerter(rule) alert.alert([match]) assert 'Error posting to Exotel' in str(ea)
def test_pagerduty_ea_exception(): with pytest.raises(EAException) as ea: rule = { 'name': 'Test PD Rule', 'type': 'any', 'alert_subject': '{0} kittens', 'alert_subject_args': ['somefield'], 'pagerduty_service_key': 'magicalbadgers', 'pagerduty_event_type': 'trigger', 'pagerduty_client_name': 'ponies inc.', 'pagerduty_incident_key': 'custom {0}', 'pagerduty_incident_key_args': ['someotherfield'], 'pagerduty_proxy': 'http://proxy.url', 'alert': [] } rules_loader = FileRulesLoader({}) rules_loader.load_modules(rule) alert = PagerDutyAlerter(rule) match = { '@timestamp': '2017-01-01T00:00:00', 'somefield': 'Stinkiest', 'someotherfield': 'foobarbaz' } mock_run = mock.MagicMock(side_effect=RequestException) with mock.patch('requests.post', mock_run), pytest.raises(RequestException): alert.alert([match]) assert 'Error posting to pagerduty: ' in str(ea)
def test_exotel_required_error(exotel_account_sid, exotel_auth_token, exotel_to_number, exotel_from_number, expected_data): try: rule = {'name': 'Test Rule', 'type': 'any', 'alert': []} if exotel_account_sid: rule['exotel_account_sid'] = exotel_account_sid if exotel_auth_token: rule['exotel_auth_token'] = exotel_auth_token if exotel_to_number: rule['exotel_to_number'] = exotel_to_number if exotel_from_number: rule['exotel_from_number'] = exotel_from_number rules_loader = FileRulesLoader({}) rules_loader.load_modules(rule) alert = ExotelAlerter(rule) actual_data = alert.get_info() assert expected_data == actual_data except Exception as ea: assert expected_data in str(ea)
def test_google_chat_basic(caplog): caplog.set_level(logging.INFO) rule = { 'name': 'Test GoogleChat Rule', 'type': 'any', 'googlechat_webhook_url': 'http://xxxxxxx', 'alert': [] } rules_loader = FileRulesLoader({}) rules_loader.load_modules(rule) alert = GoogleChatAlerter(rule) match = {'@timestamp': '2021-01-01T00:00:00', 'somefield': 'foobarbaz'} with mock.patch('requests.post') as mock_post_request: alert.alert([match]) expected_data = { 'text': 'Test GoogleChat Rule\n\n@timestamp: 2021-01-01T00:00:00\nsomefield: foobarbaz\n' } mock_post_request.assert_called_once_with( rule['googlechat_webhook_url'], data=mock.ANY, headers={'content-type': 'application/json'}) actual_data = json.loads(mock_post_request.call_args_list[0][1]['data']) assert expected_data == actual_data assert ('elastalert', logging.INFO, 'Alert sent to Google Chat!') == caplog.record_tuples[0]
def test_exotel(caplog): caplog.set_level(logging.INFO) rule = { 'name': 'Test Rule', 'type': 'any', 'alert_subject': 'Cool subject', 'exotel_account_sid': 'xxxxx1', 'exotel_auth_token': 'xxxxx2', 'exotel_to_number': 'xxxxx3', 'exotel_from_number': 'xxxxx4', 'alert': [] } match = { '@timestamp': '2021-01-10T00:00:00', 'sender_ip': '1.1.1.1', 'hostname': 'aProbe' } rules_loader = FileRulesLoader({}) rules_loader.load_modules(rule) with mock.patch('elastalert.alerters.exotel.Exotel.sms') as mock_exotel: mock_exotel.return_value = 200 alert = ExotelAlerter(rule) alert.alert([match]) expected = [mock.call()('xxxxx4', 'xxxxx3', 'Test Rule')] assert mock_exotel.mock_calls == expected assert ('elastalert', logging.INFO, 'Trigger sent to Exotel') == caplog.record_tuples[0]
def test_twilio_required_error(twilio_account_sid, twilio_auth_token, twilio_to_number, expected_data): try: rule = { 'name': 'Test Rule', 'type': 'any', 'alert_subject': 'Cool subject', 'twilio_from_number': 'xxxxx4', 'alert': [] } if twilio_account_sid: rule['twilio_account_sid'] = twilio_account_sid if twilio_auth_token: rule['twilio_auth_token'] = twilio_auth_token if twilio_to_number: rule['twilio_to_number'] = twilio_to_number rules_loader = FileRulesLoader({}) rules_loader.load_modules(rule) alert = TwilioAlerter(rule) actual_data = alert.get_info() assert expected_data == actual_data except Exception as ea: assert expected_data in str(ea)
def test_mattermost_msg_fields(): rule = { 'name': 'Test Mattermost Rule', 'type': 'any', 'alert_text_type': 'alert_text_only', 'mattermost_webhook_url': 'http://xxxxx', 'mattermost_msg_pretext': 'aaaaa', 'mattermost_msg_color': 'danger', 'mattermost_msg_fields': [ { 'title': 'Stack', 'value': "{0} {1}", 'short': False, 'args': ["type", "msg.status_code"] }, { 'title': 'Name', 'value': 'static field', 'short': False } ], 'alert': [], 'alert_subject': 'Test Mattermost' } rules_loader = FileRulesLoader({}) rules_loader.load_modules(rule) alert = MattermostAlerter(rule) match = { '@timestamp': '2021-01-01T00:00:00', 'somefield': 'foobarbaz' } with mock.patch('requests.post') as mock_post_request: alert.alert([match]) expected_data = { 'attachments': [ { 'fallback': 'Test Mattermost: aaaaa', 'color': 'danger', 'title': 'Test Mattermost', 'pretext': 'aaaaa', 'fields': [ {'title': 'Stack', 'value': '<MISSING VALUE> <MISSING VALUE>', 'short': False}, {'title': 'Name', 'value': 'static field', 'short': False} ], 'text': 'Test Mattermost Rule\n\n' } ], 'username': '******' } mock_post_request.assert_called_once_with( rule['mattermost_webhook_url'], data=mock.ANY, headers={'content-type': 'application/json'}, verify=True, proxies=None ) actual_data = json.loads(mock_post_request.call_args_list[0][1]['data']) assert expected_data == actual_data
def test_chatwork(caplog): caplog.set_level(logging.INFO) rule = { 'name': 'Test Chatwork Rule', 'type': 'any', 'chatwork_apikey': 'xxxx1', 'chatwork_room_id': 'xxxx2', 'alert': [] } rules_loader = FileRulesLoader({}) rules_loader.load_modules(rule) alert = ChatworkAlerter(rule) match = {'@timestamp': '2021-01-01T00:00:00', 'somefield': 'foobarbaz'} with mock.patch('requests.post') as mock_post_request: alert.alert([match]) expected_data = { 'body': 'Test Chatwork Rule\n\n@timestamp: 2021-01-01T00:00:00\nsomefield: foobarbaz\n', } mock_post_request.assert_called_once_with( 'https://api.chatwork.com/v2/rooms/xxxx2/messages', params=mock.ANY, headers={'X-ChatWorkToken': 'xxxx1'}, proxies=None, auth=None) actual_data = mock_post_request.call_args_list[0][1]['params'] assert expected_data == actual_data assert ('elastalert', logging.INFO, 'Alert sent to Chatwork room xxxx2') == caplog.record_tuples[0]
def test_ms_teams_proxy(): rule = { 'name': 'Test Rule', 'type': 'any', 'ms_teams_webhook_url': 'http://test.webhook.url', 'ms_teams_alert_summary': 'Alert from ElastAlert', 'ms_teams_proxy': 'https://test.proxy.url', 'alert_subject': 'Cool subject', 'alert': [] } rules_loader = FileRulesLoader({}) rules_loader.load_modules(rule) alert = MsTeamsAlerter(rule) match = {'@timestamp': '2016-01-01T00:00:00', 'somefield': 'foobarbaz'} with mock.patch('requests.post') as mock_post_request: alert.alert([match]) expected_data = { '@type': 'MessageCard', '@context': 'http://schema.org/extensions', 'summary': rule['ms_teams_alert_summary'], 'title': rule['alert_subject'], 'text': BasicMatchString(rule, match).__str__() } mock_post_request.assert_called_once_with( rule['ms_teams_webhook_url'], data=mock.ANY, headers={'content-type': 'application/json'}, proxies={'https': rule['ms_teams_proxy']}) assert expected_data == json.loads( mock_post_request.call_args_list[0][1]['data'])
def test_chatwork_proxy(): rule = { 'name': 'Test Chatwork Rule', 'type': 'any', 'chatwork_apikey': 'xxxx1', 'chatwork_room_id': 'xxxx2', 'chatwork_proxy': 'http://proxy.url', 'chatwork_proxy_login': '******', 'chatwork_proxy_pass': '******', 'alert': [] } rules_loader = FileRulesLoader({}) rules_loader.load_modules(rule) alert = ChatworkAlerter(rule) match = {'@timestamp': '2021-01-01T00:00:00', 'somefield': 'foobarbaz'} with mock.patch('requests.post') as mock_post_request: alert.alert([match]) expected_data = { 'body': 'Test Chatwork Rule\n\n@timestamp: 2021-01-01T00:00:00\nsomefield: foobarbaz\n', } mock_post_request.assert_called_once_with( 'https://api.chatwork.com/v2/rooms/xxxx2/messages', params=mock.ANY, headers={'X-ChatWorkToken': 'xxxx1'}, proxies={'https': 'http://proxy.url'}, auth=HTTPProxyAuth('admin', 'password')) actual_data = mock_post_request.call_args_list[0][1]['params'] assert expected_data == actual_data
def test_zabbix_basic(caplog): caplog.set_level(logging.WARNING) rule = { 'name': 'Basic Zabbix test', 'type': 'any', 'alert_text_type': 'alert_text_only', 'alert': [], 'alert_subject': 'Test Zabbix', 'zbx_host': 'example.com', 'zbx_key': 'example-key' } rules_loader = FileRulesLoader({}) rules_loader.load_modules(rule) alert = ZabbixAlerter(rule) match = { '@timestamp': '2021-01-01T00:00:00Z', 'somefield': 'foobarbaz' } with mock.patch('pyzabbix.ZabbixSender.send') as mock_zbx_send: alert.alert([match]) zabbix_metrics = { "host": "example.com", "key": "example-key", "value": "1", "clock": 1609459200 } alerter_args = mock_zbx_send.call_args.args assert vars(alerter_args[0][0]) == zabbix_metrics log_messeage = "Missing zabbix host 'example.com' or host's item 'example-key', alert will be discarded" assert ('elastalert', logging.WARNING, log_messeage) == caplog.record_tuples[0]
def test_http_alerter_without_payload(): rule = { 'name': 'Test HTTP Post Alerter Without Payload', 'type': 'any', 'http_post_url': 'http://test.webhook.url', 'http_post_static_payload': { 'name': 'somestaticname' }, 'alert': [] } rules_loader = FileRulesLoader({}) rules_loader.load_modules(rule) alert = HTTPPostAlerter(rule) match = {'@timestamp': '2017-01-01T00:00:00', 'somefield': 'foobarbaz'} with mock.patch('requests.post') as mock_post_request: alert.alert([match]) expected_data = { '@timestamp': '2017-01-01T00:00:00', 'somefield': 'foobarbaz', 'name': 'somestaticname' } mock_post_request.assert_called_once_with( rule['http_post_url'], data=mock.ANY, headers={ 'Content-Type': 'application/json', 'Accept': 'application/json;charset=utf-8' }, proxies=None, timeout=10, verify=True) assert expected_data == json.loads( mock_post_request.call_args_list[0][1]['data'])
def test_datadog_alerter(caplog): caplog.set_level(logging.INFO) rule = { 'name': 'Test Datadog Event Alerter', 'type': 'any', 'datadog_api_key': 'test-api-key', 'datadog_app_key': 'test-app-key', 'alert': [], 'alert_subject': 'Test Datadog Event Alert' } rules_loader = FileRulesLoader({}) rules_loader.load_modules(rule) alert = DatadogAlerter(rule) match = {'@timestamp': '2021-01-01T00:00:00', 'name': 'datadog-test-name'} with mock.patch('requests.post') as mock_post_request: alert.alert([match]) expected_data = { 'title': rule['alert_subject'], 'text': "Test Datadog Event Alerter\n\n@timestamp: 2021-01-01T00:00:00\nname: datadog-test-name\n" } mock_post_request.assert_called_once_with( "https://api.datadoghq.com/api/v1/events", data=mock.ANY, headers={ 'Content-Type': 'application/json', 'DD-API-KEY': rule['datadog_api_key'], 'DD-APPLICATION-KEY': rule['datadog_app_key'] }) actual_data = json.loads(mock_post_request.call_args_list[0][1]['data']) assert expected_data == actual_data assert ('elastalert', logging.INFO, 'Alert sent to Datadog') == caplog.record_tuples[0]
def test_slack_uses_list_of_custom_slack_channel(): rule = { 'name': 'Test Rule', 'type': 'any', 'slack_webhook_url': ['http://please.dontgohere.slack'], 'slack_channel_override': ['#test-alert', '#test-alert2'], 'alert': [] } rules_loader = FileRulesLoader({}) rules_loader.load_modules(rule) alert = SlackAlerter(rule) match = { '@timestamp': '2016-01-01T00:00:00', 'somefield': 'foobarbaz' } with mock.patch('requests.post') as mock_post_request: alert.alert([match]) expected_data1 = { 'username': '******', 'channel': '#test-alert', 'icon_emoji': ':ghost:', 'attachments': [ { 'color': 'danger', 'title': rule['name'], 'text': BasicMatchString(rule, match).__str__(), 'mrkdwn_in': ['text', 'pretext'], 'fields': [] } ], 'text': '', 'parse': 'none' } expected_data2 = { 'username': '******', 'channel': '#test-alert2', 'icon_emoji': ':ghost:', 'attachments': [ { 'color': 'danger', 'title': rule['name'], 'text': BasicMatchString(rule, match).__str__(), 'mrkdwn_in': ['text', 'pretext'], 'fields': [] } ], 'text': '', 'parse': 'none' } mock_post_request.assert_called_with( rule['slack_webhook_url'][0], data=mock.ANY, headers={'content-type': 'application/json'}, proxies=None, verify=True, timeout=10 ) assert expected_data1 == json.loads(mock_post_request.call_args_list[0][1]['data']) assert expected_data2 == json.loads(mock_post_request.call_args_list[1][1]['data'])
def test_telegram_text_maxlength(): rule = { 'name': 'Test Telegram Rule' + ('a' * 3985), 'type': 'any', 'telegram_bot_token': 'xxxxx1', 'telegram_room_id': 'xxxxx2', 'alert': [] } rules_loader = FileRulesLoader({}) rules_loader.load_modules(rule) alert = TelegramAlerter(rule) match = {'@timestamp': '2021-01-01T00:00:00', 'somefield': 'foobarbaz'} with mock.patch('requests.post') as mock_post_request: alert.alert([match]) expected_data = { 'chat_id': rule['telegram_room_id'], 'text': '⚠ *Test Telegram Rule' + ('a' * 3979) + '\n⚠ *message was cropped according to telegram limits!* ⚠ ```', 'parse_mode': 'markdown', 'disable_web_page_preview': True } mock_post_request.assert_called_once_with( 'https://api.telegram.org/botxxxxx1/sendMessage', data=mock.ANY, headers={'content-type': 'application/json'}, proxies=None, auth=None) actual_data = json.loads(mock_post_request.call_args_list[0][1]['data']) assert expected_data == actual_data