#!/usr/bin/env python3 """Проверка отказа Redis/PostgreSQL (уровень 4). Требует Docker и RUN_INFRA_TEST=1.""" import json import os import subprocess import sys import time import unittest import urllib.error import urllib.request import uuid from pathlib import Path ROOT = Path(__file__).resolve().parents[1] BASE = os.environ.get('BASE_URL', 'http://localhost:8080').rstrip('/') def compose_argv(): override = os.environ.get('COMPOSE', '').strip() if override: return override.split() return ['docker', 'compose'] def compose(*args): result = subprocess.run( [*compose_argv(), *args], cwd=ROOT, capture_output=True, text=True, check=False, ) if result.returncode != 0: raise RuntimeError( COMPOSE + ' ' + ' '.join(args) + ' failed: ' + (result.stderr or result.stdout) ) def http(method, path, token=None, expected=None, body=None): headers = {'Accept': 'application/json'} if token: headers['Authorization'] = 'Bearer ' + token data = None if body is not None: data = json.dumps(body).encode('utf-8') headers['Content-Type'] = 'application/json' req = urllib.request.Request(BASE + path, data=data, headers=headers, method=method) try: response = urllib.request.urlopen(req, timeout=5) except urllib.error.HTTPError as error: response = error with response: body = response.read() payload = json.loads(body) if body else None if expected is not None: if isinstance(expected, int): expected = [expected] if response.code not in expected: raise AssertionError( f'{method} {path}: expected {expected}, got {response.code} {payload}' ) return response.code, payload def wait_ready(deadline=60): end = time.monotonic() + deadline while time.monotonic() < end: try: code, _ = http('GET', '/health/ready') if code == 200: return except (urllib.error.URLError, TimeoutError, ConnectionError, json.JSONDecodeError): pass time.sleep(0.5) raise TimeoutError('API did not become ready') @unittest.skipUnless( os.environ.get('RUN_INFRA_TEST') == '1', 'Set RUN_INFRA_TEST=1 to run Docker dependency failure tests', ) class DependencyFailureTests(unittest.TestCase): token = None @classmethod def setUpClass(cls): wait_ready() sys.path.insert(0, str(ROOT / 'tests')) from client import Client # noqa: WPS433 actor = Client(BASE).user('dep') cls.token = actor['token'] def tearDown(self): compose('start', 'redis', 'postgres') wait_ready() def test_redis_down_ready_and_auth(self): compose('stop', 'redis') time.sleep(1) code, payload = http('GET', '/health/ready') self.assertEqual(code, 503) self.assertEqual(payload['error']['code'], 'unavailable') code, payload = http('GET', '/api/v1/users/me', token=self.token) self.assertEqual(code, 503) self.assertEqual(payload['error']['code'], 'unavailable') def test_postgres_down_ready(self): compose('stop', 'postgres') time.sleep(1) code, payload = http('GET', '/health/ready') self.assertEqual(code, 503) self.assertEqual(payload['error']['code'], 'unavailable') def test_postgres_down_registration_returns_unavailable(self): compose('stop', 'postgres') code, payload = http( 'POST', '/api/v1/users', expected=503, body={ 'username': 'u_down_' + uuid.uuid4().hex[:12], 'display_name': 'Database unavailable', 'password': 'T3st-' + uuid.uuid4().hex, }, ) self.assertEqual(code, 503) self.assertEqual(payload['error']['code'], 'unavailable') if __name__ == '__main__': unittest.main()