diff --git a/monitoring/api/v3/alerts-client/snippets.py b/monitoring/api/v3/alerts-client/snippets.py index 2790e0f06004..62c84bf8d801 100644 --- a/monitoring/api/v3/alerts-client/snippets.py +++ b/monitoring/api/v3/alerts-client/snippets.py @@ -90,6 +90,23 @@ def replace_notification_channels(project_name, alert_policy_id, channel_ids): # [END monitoring_alert_replace_channels] +# [START monitoring_alert_delete_channel] +def delete_notification_channels(project_name, channel_ids, force=None): + channel_client = monitoring_v3.NotificationChannelServiceClient() + for channel_id in channel_ids: + channel_name = '{}/notificationChannels/{}'.format( + project_name, channel_id) + try: + channel_client.delete_notification_channel( + channel_name, force=force) + print('Channel {} deleted'.format(channel_name)) + except ValueError: + print('The parameters are invalid') + except Exception as e: + print('API call failed: {}'.format(e)) +# [END monitoring_alert_delete_channel] + + # [START monitoring_alert_backup_policies] def backup(project_name): alert_client = monitoring_v3.AlertPolicyServiceClient() diff --git a/monitoring/api/v3/alerts-client/snippets_test.py b/monitoring/api/v3/alerts-client/snippets_test.py index e58dc39858a4..8aba3fc59439 100644 --- a/monitoring/api/v3/alerts-client/snippets_test.py +++ b/monitoring/api/v3/alerts-client/snippets_test.py @@ -63,8 +63,9 @@ def __enter__(self): def __exit__(self, type, value, traceback): # Delete the policy and channel we created. self.alert_policy_client.delete_alert_policy(self.alert_policy.name) - self.notification_channel_client.delete_notification_channel( - self.notification_channel.name) + if self.notification_channel.name: + self.notification_channel_client.delete_notification_channel( + self.notification_channel.name) @pytest.fixture(scope='session') @@ -114,3 +115,12 @@ def test_backup_and_restore(capsys, pochan): assert "Updated {0}".format(pochan.alert_policy.name) in out assert "Updating channel {0}".format( pochan.notification_channel.display_name) in out + + +def test_delete_channels(capsys, pochan): + notification_channel_id = pochan.notification_channel.name.split('/')[-1] + snippets.delete_notification_channels( + pochan.project_name, [notification_channel_id], force=True) + out, _ = capsys.readouterr() + assert "{0} deleted".format(notification_channel_id) in out + pochan.notification_channel.name = '' # So teardown is not tried