Files
mtusi2026lab7/student-tests/tests_helpers.py
T

90 lines
3.3 KiB
Python

"""Обвязки для собственных проверок ЛР3: docker compose и карта реплик.
Собственные тесты лежат в student-tests/ (CONTRIBUTING.md). X-Instance-Id равен
hostname контейнера, поэтому по нему можно найти реально обслуживший контейнер.
"""
import subprocess
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'scripts'))
from lab7_environment import Environment
from securityctl import GATEWAY_PAIRS
def compose(*args, check=True, env=None):
environment = Environment()
environment.process_env.update(env or {})
owners = [value for value in args[1:] if value in GATEWAY_PAIRS] if args else []
children = [child for owner in owners for child in GATEWAY_PAIRS[owner]]
operation = args[0] if args else ''
if operation == 'stop':
return environment.compose(*args, *(child for child in children if child not in args), check=check)
result = environment.compose(*args, check=check)
if result.returncode == 0 and operation in ('up', 'start', 'restart') and children:
environment.compose('up', '-d', '--no-build', '--force-recreate', '--no-deps', *children)
return result
def jobctl(*args, check=True):
"""Run the dedicated operator CLI, never the worker's application credentials."""
return operator_command('jobctl', *args, check=check)
def psql(sql):
"""Read a scalar/list through the dedicated TLS PostgreSQL operator."""
return operator_command('psql', data=sql).stdout.strip()
def operator_command(command, *args, data=None, check=True):
environment = Environment()
return environment.run(
[sys.executable, str(ROOT / 'scripts/securityctl.py'), command, *map(str, args)],
data=data, check=check,
)
def redis(*args):
"""Run authenticated Redis TLS operator probes without exposing credentials."""
return operator_command('redis', *args).stdout.strip()
def containers_by_hostname(service='api'):
"""{hostname: {id, name, status}} для контейнеров сервиса."""
listed = compose('ps', '-q', service).stdout.split()
result = {}
for container in listed:
info = subprocess.run(
['docker', 'inspect', '--format', '{{.Config.Hostname}} {{.Name}} {{.State.Status}}', container],
capture_output=True,
text=True,
check=True,
).stdout.split()
result[info[0]] = {'id': container[:12], 'name': info[1].lstrip('/'), 'status': info[2]}
return result
def messages_path(chat):
return '/api/v1/chats/' + chat['id'] + '/messages'
if __name__ == '__main__':
if len(sys.argv) < 2:
raise SystemExit('expected compose, psql, redis or jobctl command')
command, *args = sys.argv[1:]
if command == 'compose':
result = compose(*args, check=False)
elif command in ('psql', 'redis', 'jobctl'):
result = operator_command(command, *args, data=sys.stdin.read() if command == 'psql' else None,
check=False)
else:
raise SystemExit('unsupported operator helper command')
sys.stdout.write(result.stdout)
sys.stderr.write(result.stderr)
raise SystemExit(result.returncode)