async def notify(log_level: int = None) -> NoReturn: """Notify our users periodically of the number of red metrics.""" logging.getLogger().setLevel(log_level or logging.ERROR) sleep_duration = int(os.environ.get("NOTIFIER_SLEEP_DURATION", 60)) api_version = "v3" reports_url = ( f"http://{os.environ.get('SERVER_HOST', 'localhost')}:" f"{os.environ.get('SERVER_PORT', '5001')}/api/{api_version}/reports") data_model = await retrieve_data_model(api_version) most_recent_measurement_seen = datetime.max.replace(tzinfo=timezone.utc) outbox = Outbox() notification_finder = NotificationFinder(data_model) while True: record_health() logging.info("Determining notifications...") try: async with aiohttp.ClientSession(raise_for_status=True, trust_env=True) as session: response = await session.get(reports_url) json = await response.json() except Exception as reason: # pylint: disable=broad-except logging.error("Could not get reports from %s: %s", reports_url, reason) json = dict(reports=[]) notifications = notification_finder.get_notifications( json, most_recent_measurement_seen) outbox.add_notifications(notifications) outbox.send_notifications() most_recent_measurement_seen = most_recent_measurement_timestamp(json) logging.info("Sleeping %.1f seconds...", sleep_duration) await asyncio.sleep(sleep_duration)
def test_notifications_without_destination(self, mocked_ready): """Test that notifications without a destination aren't sent.""" mocked_ready.side_effect = [True, True] notifications = self.notifications notifications[0].destination["webhook"] = None notifications[1].destination["webhook"] = None outbox = Outbox(notifications) self.assertEqual(0, outbox.send_notifications())
def test_deletion_of_notifications(self, mocked_send, mocked_ready): """Test that notifications are deleted after sending.""" mocked_ready.side_effect = [True, True] mocked_send.side_effect = [None, None] outbox = Outbox(self.notifications) self.assertEqual(2, outbox.send_notifications())
def test_send_notifications(self, mocked_send, mocked_ready): """Test that notifications can be sent.""" mocked_ready.side_effect = [True, False] outbox = Outbox(self.notifications) outbox.send_notifications() mocked_send.assert_called_once()