test(lab5): add fault injection script and expose ports for testing
This commit is contained in:
@@ -26,6 +26,8 @@ services:
|
||||
timeout: 3s
|
||||
retries: 10
|
||||
start_period: 5s
|
||||
ports:
|
||||
- "5432:5432"
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
@@ -74,6 +76,7 @@ services:
|
||||
- rabbitmq_data:/var/lib/rabbitmq
|
||||
ports:
|
||||
- "15672:15672"
|
||||
- "5672:5672"
|
||||
healthcheck:
|
||||
test: ["CMD", "rabbitmq-diagnostics", "-q", "ping"]
|
||||
interval: 5s
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
#!/usr/bin/env python3
|
||||
import sys
|
||||
import time
|
||||
import json
|
||||
import pika
|
||||
import psycopg2
|
||||
from pathlib import Path
|
||||
|
||||
RABBITMQ_URL = "amqp://messenger:sdsdjhkjshdjkhsdkjhkjsdh@localhost:5672/"
|
||||
DB_URL = "postgresql://messenger:1de200d38ea7d870f772acfbf1887572@localhost:5432/messenger"
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'tests'))
|
||||
from client import Client, arguments, check, run
|
||||
|
||||
def get_db():
|
||||
return psycopg2.connect(DB_URL)
|
||||
|
||||
def publish_duplicate(attachment_id: str, pipeline_version: int):
|
||||
connection = pika.BlockingConnection(pika.URLParameters(RABBITMQ_URL))
|
||||
channel = connection.channel()
|
||||
|
||||
payload = json.dumps({
|
||||
"attachment_id": attachment_id,
|
||||
"pipeline_version": pipeline_version,
|
||||
"attempt": 1
|
||||
})
|
||||
|
||||
channel.basic_publish(
|
||||
exchange='attachments',
|
||||
routing_key='process',
|
||||
body=payload.encode(),
|
||||
properties=pika.BasicProperties(delivery_mode=2)
|
||||
)
|
||||
connection.close()
|
||||
|
||||
def main():
|
||||
args = arguments('Fault Injection (Track 2)')
|
||||
c = Client(args.base_url, args.ca_file)
|
||||
|
||||
print("=== ТЕСТ 1: Идемпотентность при дублировании сообщений ===")
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
|
||||
att, content = c.attachment(alice, chat)
|
||||
att_id = att['id']
|
||||
print(f"Загружено вложение: {att_id}")
|
||||
|
||||
ready_att = c.wait_ready(bob, att)
|
||||
print("Первая обработка успешна. Статус: ready.")
|
||||
|
||||
with get_db() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("SELECT COUNT(*) FROM attachment_variants WHERE attachment_id = %s", (att_id,))
|
||||
count_before = cur.fetchone()[0]
|
||||
|
||||
print(f"Вариантов в БД до дубля: {count_before}")
|
||||
check(count_before == 3, "Ожидалось 3 варианта (thumbnail, crop, optimized)")
|
||||
|
||||
print("Публикуем дубликат сообщения в RabbitMQ...")
|
||||
publish_duplicate(att_id, 1)
|
||||
time.sleep(2)
|
||||
|
||||
with get_db() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("SELECT COUNT(*) FROM attachment_variants WHERE attachment_id = %s", (att_id,))
|
||||
count_after = cur.fetchone()[0]
|
||||
|
||||
check(count_after == count_before, "Дубликат сообщения создал лишние варианты (НАРУШЕНИЕ ИДЕМПОТЕНТНОСТИ)")
|
||||
print("PASS: Дубликат проигнорирован, лишних вариантов не создано.")
|
||||
|
||||
print("\n=== ТЕСТ 2: Защита от устаревшей версии (Versioned Pipeline) ===")
|
||||
att2, _ = c.attachment(alice, chat)
|
||||
att2_id = att2['id']
|
||||
print(f"Загружено вложение 2: {att2_id}")
|
||||
|
||||
with get_db() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("UPDATE attachments SET pipeline_version = 2, status = 'queued' WHERE id = %s", (att2_id,))
|
||||
conn.commit()
|
||||
|
||||
print("Мы вручную поменяли версию на 2.")
|
||||
print("Публикуем сообщение со СТАРОЙ версией (1)...")
|
||||
publish_duplicate(att2_id, 1)
|
||||
time.sleep(2)
|
||||
|
||||
with get_db() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("SELECT status FROM attachments WHERE id = %s", (att2_id,))
|
||||
status = cur.fetchone()[0]
|
||||
|
||||
check(status == 'queued', f"Старый воркер перезаписал статус! Текущий статус: {status}")
|
||||
print("PASS: Задача со старой версией проигнорирована. Статус остался 'queued'.")
|
||||
print("\nВСЕ ТЕСТЫ FAULT INJECTION ПРОЙДЕНЫ!")
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
Reference in New Issue
Block a user