Files
mtusi2026lab2/student-tests/test_health.py
T
kokorindenis 5c193f24f7
Skeleton contracts / contracts (pull_request) Canceled after 0s
lab 2 solution
2026-10-23 17:24:27 +03:00

63 lines
3.0 KiB
Python

"""Эндпоинты здоровья: что они отвечают, что им нужно и чего они не трогают.
/health/live - сигнал, по которому супервизор решает, перезапускать ли процесс,
поэтому он не должен зависеть от PostgreSQL и Valkey. /health/ready - сигнал,
которым балансировщик нагрузки пользуется перед отправкой трафика, поэтому он
должен зависеть от обоих. Проверки отказов, которые отсюда следуют, живут в
test_dependency_outage.py: они останавливают контейнеры и потому требуют
ALLOW_OUTAGE=1.
"""
from __future__ import annotations
import unittest
import harness
class Probes(unittest.TestCase):
"""Обе пробы отвечают без учётных данных и не трогают пользовательские данные."""
@classmethod
def setUpClass(cls):
cls.api = harness.client()
def test_liveness(self):
response = self.api.call("GET", "/health/live", 200, schema="Health")
self.assertEqual(response["json"], {"status": "ok"})
self.assertTrue(response["headers"]["X-Request-Id"])
def test_readiness(self):
response = self.api.call("GET", "/health/ready", 200, schema="Health")
self.assertEqual(response["json"], {"status": "ok"})
def test_probes_need_no_credentials(self):
for path in ("/health/live", "/health/ready"):
with self.subTest(path=path):
self.api.call("GET", path, 200, headers={}, schema="Health")
self.api.call("GET", path, 200,
headers={"Authorization": "Bearer nonsense"}, schema="Health")
def test_every_probe_gets_its_own_request_id(self):
seen = set()
for _ in range(5):
seen.add(self.api.call("GET", "/health/ready", 200, schema="Health")
["headers"]["X-Request-Id"])
self.assertEqual(len(seen), 5, "идентификаторы запросов переиспользуются")
def test_readiness_is_not_a_cached_constant(self):
"""Повторные пробы должен обслуживать процесс, а не кешированное тело."""
first = self.api.call("GET", "/health/ready", 200, schema="Health")
second = self.api.call("GET", "/health/ready", 200, schema="Health")
self.assertEqual(first["json"], second["json"])
self.assertNotEqual(first["headers"]["X-Request-Id"],
second["headers"]["X-Request-Id"])
def test_error_envelope_carries_a_request_id(self):
response = self.api.call("GET", "/health/nothing", [404], headers={})
self.assertEqual(response["json"]["error"]["request_id"],
response["headers"]["X-Request-Id"])
if __name__ == "__main__":
unittest.main(verbosity=2)