Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added test code for files in alerters folder #284

Merged
merged 1 commit into from
Jun 19, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions elastalert/alerters/pagerduty.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,9 +103,9 @@ def alert(self, matches):

if self.pagerduty_event_type == 'trigger':
elastalert_logger.info("Trigger sent to PagerDuty")
elif self.pagerduty_event_type == 'resolve':
if self.pagerduty_event_type == 'resolve':
elastalert_logger.info("Resolve sent to PagerDuty")
elif self.pagerduty_event_type == 'acknowledge':
if self.pagerduty_event_type == 'acknowledge':
elastalert_logger.info("acknowledge sent to PagerDuty")

def resolve_formatted_key(self, key, args, matches):
Expand Down
201 changes: 197 additions & 4 deletions tests/alerters/alerta_test.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import datetime
import json
import logging

from unittest import mock
import pytest
Expand All @@ -10,7 +11,8 @@
from elastalert.util import EAException


def test_alerta_no_auth():
def test_alerta_no_auth(caplog):
caplog.set_level(logging.INFO)
rule = {
'name': 'Test Alerta rule!',
'alerta_api_url': 'http://elastalerthost:8080/api/alert',
Expand Down Expand Up @@ -73,6 +75,7 @@ def test_alerta_no_auth():
)
assert expected_data == json.loads(
mock_post_request.call_args_list[0][1]['data'])
assert ('elastalert', logging.INFO, 'Alert sent to Alerta') == caplog.record_tuples[0]


def test_alerta_auth():
Expand Down Expand Up @@ -616,7 +619,7 @@ def test_alerta_tags():


def test_alerta_ea_exception():
try:
with pytest.raises(EAException) as ea:
rule = {
'name': 'Test Alerta rule!',
'alerta_api_url': 'http://elastalerthost:8080/api/alert',
Expand Down Expand Up @@ -649,8 +652,7 @@ def test_alerta_ea_exception():
mock_run = mock.MagicMock(side_effect=RequestException)
with mock.patch('requests.post', mock_run), pytest.raises(RequestException):
alert.alert([match])
except EAException:
assert True
assert 'Error posting to Alerta: ' in str(ea)


def test_alerta_getinfo():
Expand Down Expand Up @@ -705,3 +707,194 @@ def test_alerta_required_error(alerta_api_url, expected_data):
assert expected_data == actual_data
except Exception as ea:
assert expected_data in str(ea)


@pytest.mark.parametrize('query_key, expected_data', [
('hostname', 'Test Alerta rule!.aProbe'),
('test', 'Test Alerta rule!'),
('', 'Test Alerta rule!'),
])
def test_alerta_create_default_title(query_key, expected_data):
rule = {
'name': 'Test Alerta rule!',
'alerta_api_url': 'http://elastalerthost:8080/api/alert',
'timeframe': datetime.timedelta(hours=1),
'timestamp_field': '@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 = AlertaAlerter(rule)

result = alert.create_default_title(match)
assert expected_data == result


def test_alerta_match_timestamp_none():
rule = {
'name': 'Test Alerta rule!',
'alerta_api_url': 'http://elastalerthost:8080/api/alert',
'timeframe': datetime.timedelta(hours=1),
'alerta_attributes_keys': ["hostname", "TimestampEvent", "senderIP"],
'alerta_attributes_values': ["{hostname}", "{logdate}", "{sender_ip}"],
'alerta_correlate': ["ProbeUP", "ProbeDOWN"],
'alerta_event': "ProbeUP",
'alerta_group': "Health",
'alerta_origin': "ElastAlert 2",
'alerta_severity': "debug",
'alerta_text': "Probe {hostname} is UP at {logdate} GMT",
'alerta_value': "UP",
'type': 'any',
'alerta_use_match_timestamp': True,
'alerta_tags': ['elastalert2'],
'alert': 'alerta'
}

match = {
'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])

expected_data = {
"origin": "ElastAlert 2",
"resource": "elastalert",
"severity": "debug",
"service": ["elastalert"],
"tags": ['elastalert2'],
"text": "Probe aProbe is UP at <MISSING VALUE> GMT",
"value": "UP",
"environment": "Production",
"timeout": 86400,
"correlate": ["ProbeUP", "ProbeDOWN"],
"group": "Health",
"attributes": {"senderIP": "1.1.1.1", "hostname": "aProbe", "TimestampEvent": "<MISSING VALUE>"},
"type": "elastalert",
"event": "ProbeUP"
}

mock_post_request.assert_called_once_with(
alert.url,
data=mock.ANY,
verify=True,
headers={
'content-type': 'application/json'}
)

actual_data = json.loads(
mock_post_request.call_args_list[0][1]['data'])
del actual_data['createTime']
del actual_data['rawData']
assert expected_data == actual_data


def test_alerta_use_match_timestamp():
rule = {
'name': 'Test Alerta rule!',
'alerta_api_url': 'http://elastalerthost:8080/api/alert',
'timeframe': datetime.timedelta(hours=1),
'alerta_attributes_keys': ["hostname", "TimestampEvent", "senderIP"],
'alerta_attributes_values': ["{hostname}", "{logdate}", "{sender_ip}"],
'alerta_correlate': ["ProbeUP", "ProbeDOWN"],
'alerta_event': "ProbeUP",
'alerta_group': "Health",
'alerta_origin': "ElastAlert 2",
'alerta_severity': "debug",
'alerta_text': "Probe {hostname} is UP at {logdate} GMT",
'alerta_value': "UP",
'type': 'any',
'alerta_use_match_timestamp': False,
'alerta_tags': ['elastalert2'],
'alert': 'alerta'
}

match = {
'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])

expected_data = {
"origin": "ElastAlert 2",
"resource": "elastalert",
"severity": "debug",
"service": ["elastalert"],
"tags": ['elastalert2'],
"text": "Probe aProbe is UP at <MISSING VALUE> GMT",
"value": "UP",
"environment": "Production",
"timeout": 86400,
"correlate": ["ProbeUP", "ProbeDOWN"],
"group": "Health",
"attributes": {"senderIP": "1.1.1.1", "hostname": "aProbe", "TimestampEvent": "<MISSING VALUE>"},
"type": "elastalert",
"event": "ProbeUP"
}

mock_post_request.assert_called_once_with(
alert.url,
data=mock.ANY,
verify=True,
headers={
'content-type': 'application/json'}
)

actual_data = json.loads(
mock_post_request.call_args_list[0][1]['data'])
del actual_data['createTime']
del actual_data['rawData']
assert expected_data == actual_data


def test_get_json_payload_error():
rule = {
'name': 'Test Alerta rule!',
'alerta_api_url': 'http://elastalerthost:8080/api/alert',
'timeframe': datetime.timedelta(hours=1),
'timestamp_field': '@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)
11 changes: 7 additions & 4 deletions tests/alerters/chatwork_test.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import logging

from unittest import mock
import pytest
from requests import RequestException
Expand All @@ -8,7 +10,8 @@
from elastalert.util import EAException


def test_chatwork():
def test_chatwork(caplog):
caplog.set_level(logging.INFO)
rule = {
'name': 'Test Chatwork Rule',
'type': 'any',
Expand Down Expand Up @@ -39,6 +42,7 @@ def test_chatwork():

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_chatwork_proxy():
Expand Down Expand Up @@ -78,7 +82,7 @@ def test_chatwork_proxy():


def test_chatwork_ea_exception():
try:
with pytest.raises(EAException) as ea:
rule = {
'name': 'Test Chatwork Rule',
'type': 'any',
Expand All @@ -99,8 +103,7 @@ def test_chatwork_ea_exception():
mock_run = mock.MagicMock(side_effect=RequestException)
with mock.patch('requests.post', mock_run), pytest.raises(RequestException):
alert.alert([match])
except EAException:
assert True
assert 'Error posting to Chattwork: . Details: ' in str(ea)


def test_chatwork_getinfo():
Expand Down
8 changes: 3 additions & 5 deletions tests/alerters/datadog_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,8 @@ def test_datadog_alerter(caplog):
assert ('elastalert', logging.INFO, 'Alert sent to Datadog') == caplog.record_tuples[0]


def test_datadog_alerterea_exception():
try:
def test_datadog_ea_exception():
with pytest.raises(EAException) as ea:
rule = {
'name': 'Test Datadog Event Alerter',
'type': 'any',
Expand All @@ -68,9 +68,7 @@ def test_datadog_alerterea_exception():
mock_run = mock.MagicMock(side_effect=RequestException)
with mock.patch('requests.post', mock_run), pytest.raises(RequestException):
alert.alert([match])
assert False
except EAException as ea:
assert 'Error posting event to Datadog:' in str(ea)
assert 'Error posting event to Datadog:' in str(ea)


def test_datadog_getinfo():
Expand Down
54 changes: 54 additions & 0 deletions tests/alerters/debug_test.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import logging

from elastalert.alerters.debug import DebugAlerter
from elastalert.loaders import FileRulesLoader

Expand All @@ -18,3 +20,55 @@ def test_debug_getinfo():
}
actual_data = alert.get_info()
assert expected_data == actual_data


def test_debug_alerter(caplog):
caplog.set_level(logging.INFO)
rule = {
'name': 'Test Debug Event Alerter',
'type': 'any',
'alert': [],
'timestamp_field': 'timestamp'
}
rules_loader = FileRulesLoader({})
rules_loader.load_modules(rule)
alert = DebugAlerter(rule)
match = {
'@timestamp': '2021-01-01T00:00:00',
'name': 'debug-test-name'
}
alert.alert([match])

excepted1 = 'Alert for Test Debug Event Alerter 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 += 'name: debug-test-name\n'
assert ('elastalert', logging.INFO, excepted2) == caplog.record_tuples[1]


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]
Loading