"""The health check (Sentry DTF-API-B): an R2 blip is not the API down. Runs in the API image: python -m unittest tests.test_health -v. """ import unittest from contextlib import contextmanager from unittest import mock from fastapi import HTTPException from app.api import health as module @contextmanager def database(up=True): if not up: raise RuntimeError('no database') yield mock.MagicMock() class HealthTests(unittest.TestCase): def setUp(self): module._storage.update(down_since=None, reported=False) patches = [mock.patch.object(module.db, 'connect', database), mock.patch.object(module.time, 'sleep')] for patch in patches: patch.start() self.addCleanup(patch.stop) def check(self, storage_up, now=0): storage = mock.MagicMock() if not storage_up: storage.health.side_effect = RuntimeError('R2 500') with mock.patch.object(module, 'storage', storage), \ mock.patch.object(module.time, 'monotonic', return_value=now), \ mock.patch.object(module.logging, 'error') as error: try: return module.health(), error.call_count except HTTPException as exc: return exc.status_code, error.call_count def test_a_storage_blip_is_reported_but_not_a_503(self): answer, errors = self.check(storage_up=False, now=100) self.assertEqual((answer['storage'], errors), ('unavailable', 0)) answer, _ = self.check(storage_up=True, now=150) self.assertNotEqual(answer['storage'], 'unavailable') def test_storage_down_for_five_minutes_is_a_503_reported_once(self): self.check(storage_up=False, now=0) self.assertEqual(self.check(storage_up=False, now=299)[0]['storage'], 'unavailable') self.assertEqual(self.check(storage_up=False, now=300), (503, 1)) self.assertEqual(self.check(storage_up=False, now=400), (503, 0)) def test_one_retry_rides_out_a_single_failure(self): storage = mock.MagicMock() storage.health.side_effect = [RuntimeError('R2 500'), None] with mock.patch.object(module, 'storage', storage): self.assertTrue(module.storage_answers()) def test_the_database_down_is_a_503_at_once(self): with mock.patch.object(module.db, 'connect', lambda: database(up=False)): with self.assertRaises(HTTPException) as caught: module.health() self.assertEqual(caught.exception.status_code, 503) if __name__ == '__main__': unittest.main()