Files
mtusi2026lab4-fork/student-tests/test_gc.py
2026-11-06 15:49:15 +03:00

82 lines
4.1 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""
Проверка работы фонового reconciler:
1. Создаём запись в attachment_gc и pending-запись в attachments с created_at в прошлом.
2. Ждём, пока фоновый процесс (каждые 2 минуты) их не удалит.
"""
import sys
import time
import subprocess
import uuid
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
from client import Client, run, check, Failure
IMAGE_PATH = Path(__file__).parent / "fixtures" / "Snake_River_(5mb).jpg"
DB_CONTAINER = "mtusi2026lab4-fork-postgres-1"
def execute_sql(sql):
"""Выполняет SQL-запрос в контейнере PostgreSQL."""
cmd = ["docker", "exec", "-i", DB_CONTAINER, "psql", "-U", "messenger", "-d", "messenger", "-t", "-c", sql]
res = subprocess.run(cmd, capture_output=True, text=True)
if res.returncode != 0:
raise Exception(f"Ошибка SQL: {res.stderr}")
return res.stdout.strip()
def main():
if not IMAGE_PATH.exists():
raise FileNotFoundError(f"Файл {IMAGE_PATH} не найден.")
c = Client()
alice, bob, eve, chat = c.bootstrap()
# 1. Подготовка: создадим фейковые записи в БД
print("1. Создание фейковых записей (эмуляция сбоя)...")
gc_key = f"orphan_{uuid.uuid4().hex}"
att_id = str(uuid.uuid4())
# Вставляем запись в attachment_gc (с датой в прошлом)
execute_sql(f"""
INSERT INTO attachment_gc (object_key, reason, created_at)
VALUES ('{gc_key}', 'test_failure', now() - interval '20 minutes');
""")
# Вставляем pending-запись (также в прошлом)
execute_sql(f"""
INSERT INTO attachments (id, chat_id, owner_id, object_key, filename, content_type, size_bytes, sha256, width, height, status, created_at)
VALUES ('{att_id}', '{chat["id"]}', '{alice["id"]}', 'attachments/orphan_pending', 'pending.jpg', 'image/png', 1, repeat('0',64), 1, 1, 'pending', now() - interval '20 minutes');
""")
print(f" Создана запись в attachment_gc: {gc_key}")
print(f" Создана pending-запись: {att_id}")
# 2. Проверяем, что они там есть
count_gc = execute_sql(f"SELECT count(*) FROM attachment_gc WHERE object_key='{gc_key}';")
count_att = execute_sql(f"SELECT count(*) FROM attachments WHERE id='{att_id}';")
print(f" До очистки: gc={count_gc}, att={count_att}")
check(count_gc == "1" and count_att == "1", "Фейковые записи не создались.")
# 3. Ждем срабатывания фонового процесса (тикер 2 минуты + время на запрос)
# Чтобы ускорить тест, можно перезапустить контейнер API (он сразу при старте не запускает очистку, только через 2 минуты),
# либо просто подождать. Мы подождем 130 секунд.
print("2. Ожидание фонового reconciler (макс. 150 секунд)...")
start_time = time.time()
max_wait = 150
success = False
while time.time() - start_time < max_wait:
count_gc = execute_sql(f"SELECT count(*) FROM attachment_gc WHERE object_key='{gc_key}';")
count_att = execute_sql(f"SELECT count(*) FROM attachments WHERE id='{att_id}';")
if count_gc == "0" and count_att == "0":
success = True
break
time.sleep(5)
if success:
print(f"PASS: Обе записи удалены фоновым reconciler за {int(time.time() - start_time)} с.")
else:
# Проверим, есть ли ошибка в логах API
print("ОШИБКА: Записи не были удалены за отведенное время.")
print("Проверьте логи API: docker compose logs api | grep reconcile")
sys.exit(1)
if __name__ == '__main__':
run(main)