def test_opsgenie_notification_error_teams(monkeypatch):
    NotifyOpsgenie._config = {'notifications.opsgenie.apikey': API_KEY}

    alert = {
        'alert_changed': True,
        'changed': True,
        'is_alert': True,
        'entity': {
            'id': 'e-1'
        },
        'worker': 'worker-1',
        'alert_evaluation_ts': 1234,
        'alert_def': {
            'name': 'Alert',
            'team': 'zmon',
            'responsible_team': 'zmon',
            'id': 123,
            'priority': 1,
        }
    }

    with pytest.raises(NotificationError):
        NotifyOpsgenie.notify(alert, message=MESSAGE)

    with pytest.raises(NotificationError):
        NotifyOpsgenie.notify(alert,
                              teams='team-1',
                              message=MESSAGE,
                              priority='p1')
def test_opsgenie_notification_error_teams(monkeypatch):
    NotifyOpsgenie._config = {'notifications.opsgenie.apikey': API_KEY}

    with pytest.raises(NotificationError):
        NotifyOpsgenie.notify({}, message=MESSAGE)

    with pytest.raises(NotificationError):
        NotifyOpsgenie.notify({}, teams='team-1', message=MESSAGE, priority='p1')
def test_opsgenie_notification_exception(monkeypatch):
    post = MagicMock()
    post.side_effect = Exception
    monkeypatch.setattr('requests.post', post)

    alert = {
        'alert_changed': True,
        'changed': True,
        'is_alert': True,
        'entity': {
            'id': 'e-1'
        },
        'worker': 'worker-1',
        'alert_def': {
            'name': 'Alert',
            'team': 'zmon',
            'responsible_team': 'zmon',
            'id': 123,
            'priority': 1
        },
    }

    NotifyOpsgenie._config = {'notifications.opsgenie.apikey': API_KEY}

    r = NotifyOpsgenie.notify(alert,
                              message=MESSAGE,
                              per_entity=True,
                              teams='team-1')

    assert r == 0
def test_opsgenie_notification_no_change(monkeypatch):
    alert = {
        'is_alert': True,
        'alert_changed': False,
        'entity': {
            'id': 'e-1'
        },
        'worker': 'worker-1',
        'alert_def': {
            'name': 'Alert',
            'team': 'zmon',
            'responsible_team': 'zmon',
            'id': 123,
            'priority': 1
        },
    }

    NotifyOpsgenie._config = {
        'notifications.opsgenie.apikey': API_KEY,
        'zmon.host': 'https://zmon.example.org/'
    }

    r = NotifyOpsgenie.notify(alert,
                              message=MESSAGE,
                              per_entity=True,
                              teams='team-1')

    assert r == 0
def test_opsgenie_notification_error_api_key(monkeypatch):
    NotifyOpsgenie._config = {}

    alert = {
        'alert_changed': True, 'changed': True, 'is_alert': True, 'entity': {'id': 'e-1'}, 'worker': 'worker-1',
        'alert_evaluation_ts': 1234,
        'alert_def': {
            'name': 'Alert',
            'team': 'zmon',
            'responsible_team': 'zmon',
            'id': 123,
            'priority': 1,
        }
    }

    with pytest.raises(NotificationError):
        NotifyOpsgenie.notify(alert, message=MESSAGE)
def test_opsgenie_notification_per_entity(monkeypatch):
    post = MagicMock()
    monkeypatch.setattr('requests.post', post)

    alert = {
        'changed': True, 'is_alert': True, 'entity': {'id': 'e-1'}, 'worker': 'worker-1', 'time': datetime.now(),
        'alert_evaluation_ts': 1234,
        'alert_def': {
            'name': 'Alert',
            'team': 'team-1',
            'responsible_team': 'zmon',
            'id': 123,
            'priority': 3,
            'tags': ['tag-1'],
        },
    }

    NotifyOpsgenie._config = {
        'notifications.opsgenie.apikey': API_KEY,
        'zmon.host': 'https://zmon.example.org/'
    }

    r = NotifyOpsgenie.notify(alert, message=MESSAGE, per_entity=True, teams='team-1')

    data = {
        'alias': 'ZMON-123-e-1',
        'message': '[zmon] - {}'.format(MESSAGE),
        'description': '',
        'source': 'worker-1',
        'note': 'https://zmon.example.org/#/alert-details/123',
        'entity': 'e-1',
        'details': {
            'worker': alert['worker'],
            'id': alert['alert_def']['id'],
            'name': alert['alert_def']['name'],
            'team': alert['alert_def']['team'],
            'responsible_team': alert['alert_def']['responsible_team'],
            'entity': alert['entity']['id'],
            'infrastructure_account': 'UNKNOWN',
            'alert_evaluation_ts': 1234,
        },
        'priority': 'P3',
        'tags': ['tag-1'],
        'teams': [{'name': 'team-1'}],
    }

    assert r == 0

    post.assert_called_with(URL_CREATE, data=json.dumps(data, cls=JsonDataEncoder, sort_keys=True), headers=HEADERS,
                            timeout=5, params={})
def test_opsgenie_notification_no_change(monkeypatch):
    alert = {
        'is_alert': True, 'alert_changed': False, 'entity': {'id': 'e-1'}, 'worker': 'worker-1',
        'alert_def': {'name': 'Alert', 'team': 'zmon', 'responsible_team': 'zmon', 'id': 123, 'priority': 1},
    }

    NotifyOpsgenie._config = {
        'notifications.opsgenie.apikey': API_KEY,
        'zmon.host': 'https://zmon.example.org/'
    }

    r = NotifyOpsgenie.notify(alert, message=MESSAGE, per_entity=False, teams='team-1', repeat=55)

    assert r == 55
def test_opsgenie_notification(monkeypatch, is_alert, priority):
    post = MagicMock()

    monkeypatch.setattr('requests.post', post)

    alert = {
        'alert_changed': True, 'changed': True, 'is_alert': is_alert, 'entity': {'id': 'e-1'}, 'worker': 'worker-1',
        'alert_def': {'name': 'Alert', 'team': 'zmon', 'responsible_team': 'zmon', 'id': 123, 'priority': 1}
    }

    NotifyOpsgenie._config = {'notifications.opsgenie.apikey': API_KEY}

    kwargs = {}
    if priority:
        kwargs['priority'] = priority
    else:
        priority = 'P1'

    r = NotifyOpsgenie.notify(alert, message=MESSAGE, include_alert=False, teams=['team-1', 'team-2'], **kwargs)

    params = {}

    if is_alert:
        data = {
            'alias': 'ZMON-123',
            'message': '[zmon] - {}'.format(MESSAGE),
            'entity': 'e-1',
            'priority': priority,
            'tags': [],
            'teams': [{'name': 'team-1'}, {'name': 'team-2'}],
            'source': 'worker-1',
            'note': '',
        }
    else:
        data = {
            'user': '******',
            'source': 'worker-1',
            'note': '',

        }

        params = {'identifierType': 'alias'}

    assert r == 0

    URL = URL_CREATE if is_alert else URL_CLOSE.format('ZMON-123')

    post.assert_called_with(URL, data=json.dumps(data, cls=JsonDataEncoder, sort_keys=True), headers=HEADERS, timeout=5,
                            params=params)
def test_opsgenie_notification_exception(monkeypatch):
    post = MagicMock()
    post.side_effect = Exception
    monkeypatch.setattr('requests.post', post)

    alert = {
        'alert_changed': True, 'changed': True, 'is_alert': True, 'entity': {'id': 'e-1'}, 'worker': 'worker-1',
        'alert_def': {'name': 'Alert', 'team': 'zmon', 'responsible_team': 'zmon', 'id': 123, 'priority': 1},
    }

    NotifyOpsgenie._config = {'notifications.opsgenie.apikey': API_KEY}

    r = NotifyOpsgenie.notify(alert, message=MESSAGE, per_entity=True, teams='team-1')

    assert r == 0

    resp = requests.Response()
    resp.status_code = 400
    post.side_effect = requests.HTTPError(response=resp)
    monkeypatch.setattr('requests.post', post)

    r = NotifyOpsgenie.notify(alert, message=MESSAGE, per_entity=True, teams='team-1')

    assert r == 0
def test_opsgenie_notification_per_entity(monkeypatch):
    post = MagicMock()
    monkeypatch.setattr('requests.post', post)

    alert = {
        'changed': True, 'is_alert': True, 'entity': {'id': 'e-1'}, 'worker': 'worker-1', 'time': datetime.now(),
        'alert_evaluation_ts': 1234,
        'alert_def': {
            'name': 'Alert',
            'team': 'team-1',
            'id': 123,
            'responsible_team': 'zmon',
            'priority': 3,
            'tags': ['tag-1'],
        },
    }

    NotifyOpsgenie._config = {
        'notifications.opsgenie.apikey': API_KEY,
        'zmon.host': 'https://zmon.example.org/'
    }

    r = NotifyOpsgenie.notify(alert, message=MESSAGE, per_entity=True, teams='team-1')

    data = {
        'alias': 'ZMON-123-e-1',
        'message': '[zmon] - {}'.format(MESSAGE),
        'description': '',
        'source': 'worker-1',
        'note': 'https://zmon.example.org/#/alert-details/123',
        'entity': 'e-1',
        'details': {
            'worker': alert['worker'],
            'zmon_team': alert['alert_def']['team'],
            'entity': alert['entity']['id'],
            'infrastructure_account': 'UNKNOWN',
            'alert_evaluation_ts': 1234,
            'alert_url': 'https://zmon.example.org/#/alert-details/123',
        },
        'priority': 'P3',
        'tags': ['tag-1', 123],
        'teams': [{'name': 'team-1'}],
    }

    assert r == 0

    post.assert_called_with(URL_CREATE, data=json.dumps(data, cls=JsonDataEncoder, sort_keys=True), headers=HEADERS,
                            timeout=5, params={})
def test_opsgenie_notification(monkeypatch, is_alert):
    post = MagicMock()

    monkeypatch.setattr('requests.post', post)

    alert = {
        'changed': True,
        'is_alert': is_alert,
        'alert_def': {
            'id': 123
        },
        'entity': {
            'id': 'e-1'
        }
    }

    NotifyOpsgenie._config = {'notifications.opsgenie.apikey': API_KEY}

    r = NotifyOpsgenie.notify(alert, message=MESSAGE, include_alert=False)

    data = {
        'apiKey': API_KEY,
        'alias': 'ZMON-123',
        'source': 'ZMON',
        'note': '',
    }

    if is_alert:
        data['message'] = MESSAGE
        data['details'] = {}
        data['entity'] = 'e-1'

    assert r == 0

    URL = URL_CREATE if is_alert else URL_CLOSE

    post.assert_called_with(URL,
                            data=json.dumps(data,
                                            cls=JsonDataEncoder,
                                            sort_keys=True),
                            headers=HEADERS,
                            timeout=5)
def test_opsgenie_notification_per_entity(monkeypatch):
    post = MagicMock()
    monkeypatch.setattr('requests.post', post)

    alert = {
        'changed': True,
        'is_alert': True,
        'alert_def': {
            'id': 123
        },
        'entity': {
            'id': 'e-1'
        },
        'time': datetime.now()
    }

    NotifyOpsgenie._config = {
        'notifications.opsgenie.apikey': API_KEY,
        'zmon.host': 'https://zmon.example.org/'
    }

    r = NotifyOpsgenie.notify(alert, message=MESSAGE, per_entity=True)

    data = {
        'apiKey': API_KEY,
        'alias': 'ZMON-123-e-1',
        'message': MESSAGE,
        'source': 'ZMON',
        'note': 'https://zmon.example.org/#/alert-details/123',
        'entity': 'e-1',
        'details': alert,
    }

    assert r == 0

    post.assert_called_with(URL_CREATE,
                            data=json.dumps(data,
                                            cls=JsonDataEncoder,
                                            sort_keys=True),
                            headers=HEADERS,
                            timeout=5)
def test_opsgenie_notification_exception(monkeypatch):
    post = MagicMock()
    post.side_effect = Exception
    monkeypatch.setattr('requests.post', post)

    alert = {
        'changed': True,
        'is_alert': True,
        'alert_def': {
            'id': 123
        },
        'entity': {
            'id': 'e-1'
        }
    }

    NotifyOpsgenie._config = {'notifications.opsgenie.apikey': API_KEY}

    r = NotifyOpsgenie.notify(alert, message=MESSAGE, per_entity=True)

    assert r == 0
def test_opsgenie_notification_error_api_key(monkeypatch):
    NotifyOpsgenie._config = {}

    with pytest.raises(NotificationError):
        NotifyOpsgenie.notify({}, message=MESSAGE)
def test_opsgenie_notification(monkeypatch, is_alert, priority,
                               override_description, set_custom_fileds):
    post = MagicMock()

    monkeypatch.setattr('requests.post', post)

    alert = {
        'alert_changed': True,
        'changed': True,
        'is_alert': is_alert,
        'entity': {
            'id': 'e-1'
        },
        'worker': 'worker-1',
        'alert_evaluation_ts': 1234,
        'alert_def': {
            'name': 'Alert',
            'team': 'zmon',
            'responsible_team': 'zmon',
            'id': 123,
            'priority': 1,
        }
    }

    NotifyOpsgenie._config = {'notifications.opsgenie.apikey': API_KEY}

    kwargs = {}
    if priority:
        kwargs['priority'] = priority
    else:
        priority = 'P1'

    if override_description:
        r = NotifyOpsgenie.notify(alert,
                                  message=MESSAGE,
                                  include_alert=False,
                                  teams=['team-1', 'team-2'],
                                  description=override_description,
                                  custom_fields=set_custom_fileds,
                                  **kwargs)
    else:
        r = NotifyOpsgenie.notify(alert,
                                  message=MESSAGE,
                                  include_alert=False,
                                  teams=['team-1', 'team-2'],
                                  custom_fields=set_custom_fileds,
                                  **kwargs)

    params = {}

    if is_alert:
        details = {'alert_evaluation_ts': 1234}

        if set_custom_fileds:
            details.update(set_custom_fileds)

        data = {
            'alias': 'ZMON-123',
            'message': MESSAGE,
            'description': '',
            'entity': 'e-1',
            'priority': priority,
            'tags': [123],
            'teams': [{
                'name': 'team-1'
            }, {
                'name': 'team-2'
            }],
            'source': 'worker-1',
            'note': '',
            'details': details,
        }

        if override_description:
            data['description'] = override_description

    else:
        data = {
            'user': '******',
            'source': 'worker-1',
            'note': '',
        }

        params = {'identifierType': 'alias'}

    assert r == 0

    URL = URL_CREATE if is_alert else URL_CLOSE.format('ZMON-123')

    post.assert_called_with(URL,
                            data=json.dumps(data,
                                            cls=JsonDataEncoder,
                                            sort_keys=True),
                            headers=HEADERS,
                            timeout=5,
                            params=params)
def test_opsgenie_notification_large_message(monkeypatch):
    post = MagicMock()

    monkeypatch.setattr('requests.post', post)

    alert = {
        'alert_changed': True,
        'changed': True,
        'is_alert': True,
        'entity': {
            'id': 'e-1'
        },
        'worker': 'worker-1',
        'alert_evaluation_ts': 1234,
        'captures': {
            'foo': 'x'
        },
        'alert_def': {
            'name': 'Alert',
            'team': 'zmon',
            'responsible_team': 'zmon',
            'id': 123,
            'priority': 1,
        }
    }

    NotifyOpsgenie._config = {'notifications.opsgenie.apikey': API_KEY}

    kwargs = {}
    kwargs['priority'] = 'P1'

    r = NotifyOpsgenie.notify(alert,
                              message=MESSAGE + " " + "x" * 130,
                              include_alert=False,
                              include_captures=True,
                              teams=['team-1', 'team-2'],
                              **kwargs)

    params = {}

    details = {'alert_evaluation_ts': 1234, 'captures.foo': 'x'}

    data = {
        'alias': 'ZMON-123',
        'message':
        MESSAGE + " " + "x" * (MAX_MESSAGE_SIZE - len(MESSAGE) - 4) + "...",
        'description': '',
        'entity': 'e-1',
        'priority': 'P1',
        'tags': [123],
        'teams': [{
            'name': 'team-1'
        }, {
            'name': 'team-2'
        }],
        'source': 'worker-1',
        'note': '',
        'details': details,
    }
    assert r == 0

    URL = URL_CREATE
    post.assert_called_with(URL,
                            data=json.dumps(data,
                                            cls=JsonDataEncoder,
                                            sort_keys=True),
                            headers=HEADERS,
                            timeout=5,
                            params=params)
def test_opsgenie_notification(monkeypatch, is_alert, priority, override_description, set_custom_fileds):
    post = MagicMock()

    monkeypatch.setattr('requests.post', post)

    alert = {
        'alert_changed': True, 'changed': True, 'is_alert': is_alert, 'entity': {'id': 'e-1'}, 'worker': 'worker-1',
        'alert_evaluation_ts': 1234,
        'alert_def': {
            'name': 'Alert',
            'team': 'zmon',
            'responsible_team': 'zmon',
            'id': 123,
            'priority': 1,
        }
    }

    NotifyOpsgenie._config = {'notifications.opsgenie.apikey': API_KEY}

    kwargs = {}
    if priority:
        kwargs['priority'] = priority
    else:
        priority = 'P1'

    if override_description:
        r = NotifyOpsgenie.notify(
            alert,
            message=MESSAGE,
            include_alert=False,
            teams=['team-1', 'team-2'],
            description=override_description,
            custom_fields=set_custom_fileds,
            **kwargs
        )
    else:
        r = NotifyOpsgenie.notify(
            alert,
            message=MESSAGE,
            include_alert=False,
            teams=['team-1', 'team-2'],
            custom_fields=set_custom_fileds,
            **kwargs
        )

    params = {}

    if is_alert:
        details = {'alert_evaluation_ts': 1234}

        if set_custom_fileds:
            details.update(set_custom_fileds)

        data = {
            'alias': 'ZMON-123',
            'message': '[zmon] - {}'.format(MESSAGE),
            'description': '',
            'entity': 'e-1',
            'priority': priority,
            'tags': [123],
            'teams': [{'name': 'team-1'}, {'name': 'team-2'}],
            'source': 'worker-1',
            'note': '',
            'details': details,
        }

        if override_description:
            data['description'] = override_description

    else:
        data = {
            'user': '******',
            'source': 'worker-1',
            'note': '',

        }

        params = {'identifierType': 'alias'}

    assert r == 0

    URL = URL_CREATE if is_alert else URL_CLOSE.format('ZMON-123')

    post.assert_called_with(URL, data=json.dumps(data, cls=JsonDataEncoder, sort_keys=True), headers=HEADERS, timeout=5,
                            params=params)