test: verify level-four failures and history index
This commit is contained in:
@@ -4,7 +4,7 @@ CA_FILE ?=
|
||||
ACTION_SCRIPT ?=
|
||||
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)
|
||||
|
||||
.PHONY: help check validate test load test-persistence
|
||||
.PHONY: help check validate test load test-persistence test-level4
|
||||
|
||||
help:
|
||||
@echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes"
|
||||
@@ -24,3 +24,9 @@ load:
|
||||
test-persistence:
|
||||
@test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable restart hook"; exit 2)
|
||||
$(PYTHON) tests/resilience.py --mode persistence --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||
|
||||
test-level4:
|
||||
docker compose --env-file .env exec -T api python - < student-tests/test_database.py
|
||||
docker compose --env-file .env exec -T api python - < student-tests/test_auth.py
|
||||
docker compose --env-file .env exec -T api python - < student-tests/test_cache_failures.py
|
||||
CHECK_COMPOSE_FAILURES=1 $(PYTHON) student-tests/test_compose_failures.py
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# Отчёт — лабораторная 2
|
||||
|
||||
- Автор, группа: Самохвалов Андрей Ремович, БПИ-2302.
|
||||
- Целевая оценка: 5, трек 2 (сравнение запросов и восстановление). Кэш и отказы проверены; индекс и исследование трека дополняются в следующих блоках.
|
||||
- Целевая оценка: 5, трек 2 (сравнение запросов и восстановление). Уровень 4 проверен; исследование трека 2 выполняется следующим блоком.
|
||||
- Ветка: `solution/bpi2302-samohvalov`; commit/PR указываются после публикации.
|
||||
- Источники: `README.md`, `COURSE.md`, `contracts/README.md`, `contracts/openapi.json`, публичные тесты и примеры этого репозитория; FastAPI, psycopg, PostgreSQL и Argon2id. Код и инструкции подготовлены с помощью ИИ Codex и проверяются запуском команд ниже.
|
||||
|
||||
@@ -55,14 +55,19 @@ make test-persistence ACTION_SCRIPT=scripts/restart.sh
|
||||
| Сохранность уровня 3 | `make test-persistence ACTION_SCRIPT=scripts/restart.sh` | PASS: прежние данные и сессия после рестарта обоих сервисов | `evidence/restart-2026-10-02.txt` |
|
||||
| Отказ обязательной БД | Остановить `postgres`, запросить readiness и защищённый endpoint | Оба HTTP 503; затем БД восстановлена, сервисы healthy | `evidence/restart-2026-10-02.txt` |
|
||||
| Кэш и отказы уровня 4 | `docker compose exec -T api python - < student-tests/test_cache_failures.py`; отказ Valkey/БД | Два интеграционных теста PASS; SQL 2/1/2 на miss/hit/reload; Valkey hit/miss 1/2; smoke проходит без кэша; при отказе БД 503, отозванный токен после рестарта кэша 401 | `evidence/cache-2026-10-02.txt` |
|
||||
| Индекс и остальные проверки уровня 4 | Выполняются в следующем блоке | Пока не заявлены как проверенные | — |
|
||||
| Негативные, конкурентные проверки уровня 4 | `make test-level4` | 10 тестов PASS: короткий TTL 2 с и неизменный expiry после рестарта API, logout/повторный logout, одинаковая ошибка неверных credentials, гонка username 201/409, откат чата после ошибки второй membership, обход отказавшего Valkey, ограниченный 503 при отказе БД и 401 после перезапуска Valkey. Оба списка отвечают 400 на limit из 4301 цифры | `evidence/level4-tests.txt` |
|
||||
| Индекс истории уровня 4 | `docker compose --env-file .env exec -T api python - --count 10000 --deep-offset 8000 < scripts/seed_history.py` | 10 000 сообщений в одном чате; первая и глубокая страницы по 51 строке, порядок и отсутствие повторов проверены. Обе страницы используют `messages_history_idx` | `evidence/history-explain.txt` |
|
||||
| Трек 5 | Выполняется после уровня 4 | Пока не заявлен как проверенный | — |
|
||||
|
||||
У `api`, `postgres` и `valkey` изменились времена `StartedAt` при сохранении именованного volume; точные значения приведены в evidence. Это подтверждает фактический перезапуск трёх контейнеров. Проверка `make validate` локально пока не завершена: DNS до `files.pythonhosted.org` не позволил установить `openapi-spec-validator==0.7.2`; отдельный CI workflow устанавливает зависимости из `requirements-dev.txt` для проверки контракта.
|
||||
|
||||
## Эксперименты и отказы
|
||||
|
||||
Исследование производительности и восстановления выполняется в блоках уровня 4 и трека 5. Текущий стенд — Colima на arm64 macOS с Docker/Compose; значения производительности здесь не заявлены.
|
||||
Стенд — Colima на arm64 macOS с Docker/Compose, 2 CPU и 2 054 840 320 байт памяти. `make test-level4` запускает тесты БД, auth, кэша внутри API-контейнера и отдельный HTTP-сценарий, который последовательно останавливает/восстанавливает Valkey и PostgreSQL. Он работает только на учебном стенде с локальным `.env`, не удаляет volumes и не публикует токены. Отказ второй вставки участника инъецируется после записи чата и первой membership: отсутствие нового чата и membership после исключения доказывает rollback, в отличие от одной предварительной проверки входных данных.
|
||||
|
||||
Для SQL-плана `scripts/seed_history.py` создаёт отдельный синтетический чат с 10 000 сообщениями, выполняет `ANALYZE messages` и проверяет 51 упорядоченную строку на первой и странице после курсора 8000-й записи. Команда и полный `EXPLAIN (ANALYZE, BUFFERS)` сохранены в `evidence/history-explain.txt`. PostgreSQL 17.6 выбрал `Index Scan using messages_history_idx` с условием `chat_id` для первой страницы и `(chat_id, (created_at,id) > cursor)` для глубокой. Обе прочли лишь 3 и 4 буфера из cache, выполнились за 0,010 и 0,014 мс в этом прогоне; это время SQL на прогретых страницах, не HTTP latency и не прогноз для других размеров истории. В запросах приложения также используется keyset `(created_at,id)` с индексом `(chat_id,created_at,id)`, поэтому глубокая страница не пропускает заново первые 8000 строк.
|
||||
|
||||
Сравнение на ≥100 000 сообщениях и восстановление в новое хранилище выполняются в блоке трека 5.
|
||||
|
||||
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
||||
| --- | --- | --- | --- |
|
||||
@@ -74,4 +79,4 @@ make test-persistence ACTION_SCRIPT=scripts/restart.sh
|
||||
|
||||
## Ограничения и следующие шаги
|
||||
|
||||
Подтверждён рестарт одного API, одного PostgreSQL и Valkey с сохранением volume БД. Это не высокая доступность: отказ БД временно делает API недоступным, а заполненный кэш не может заменить проверку сессии. Локальный HTTP не предназначен для удалённой передачи паролей без TLS. Проверки индекса на ≥10 000 сообщений, сравнение ≥100 000 сообщений и восстановление в новое хранилище ещё должны быть добавлены; их результаты нельзя выводить из smoke или persistence теста.
|
||||
Подтверждён рестарт одного API, одного PostgreSQL и Valkey с сохранением volume БД. Это не высокая доступность: отказ БД временно делает API недоступным, а заполненный кэш не может заменить проверку сессии. Локальный HTTP не предназначен для удалённой передачи паролей без TLS. Сравнение ≥100 000 сообщений и восстановление в новое хранилище ещё должны быть добавлены; их результаты нельзя выводить из smoke, persistence или 10 000 строк одного чата.
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
Lab 2 U5 history index evidence
|
||||
Base commit at measurement: d59d3f4; local Colima Docker: 2 CPUs, 2054840320 bytes memory.
|
||||
Command: docker compose --env-file .env exec -T api python - --count 10000 --deep-offset 8000 < scripts/seed_history.py
|
||||
Each run creates a new synthetic user/chat and appends its own messages to the disposable test database.
|
||||
UTC: 2026-10-02T08:41:04.204691+00:00
|
||||
PostgreSQL: 17.6 (Debian 17.6-2.pgdg12+1)
|
||||
Synthetic chat messages: 10000
|
||||
Deep cursor ordinal: 8000
|
||||
History index: CREATE INDEX messages_history_idx ON public.messages USING btree (chat_id, created_at, id)
|
||||
Verified: first/deep pages each have 51 ordered rows with no shared IDs
|
||||
|
||||
First page: EXPLAIN (ANALYZE, BUFFERS)
|
||||
Limit (cost=0.29..6.76 rows=51 width=70) (actual time=0.003..0.007 rows=51 loops=1)
|
||||
Buffers: shared hit=3
|
||||
-> Index Scan using messages_history_idx on messages (cost=0.29..1269.95 rows=10000 width=70) (actual time=0.003..0.005 rows=51 loops=1)
|
||||
Index Cond: (chat_id = '86684ee0-6818-4f81-ad7f-e7bf9069b8e8'::uuid)
|
||||
Buffers: shared hit=3
|
||||
Planning Time: 0.014 ms
|
||||
Execution Time: 0.010 ms
|
||||
|
||||
Deep page: EXPLAIN (ANALYZE, BUFFERS)
|
||||
Limit (cost=0.29..11.51 rows=51 width=70) (actual time=0.003..0.010 rows=51 loops=1)
|
||||
Buffers: shared hit=4
|
||||
-> Index Scan using messages_history_idx on messages (cost=0.29..439.78 rows=1996 width=70) (actual time=0.003..0.007 rows=51 loops=1)
|
||||
Index Cond: ((chat_id = '86684ee0-6818-4f81-ad7f-e7bf9069b8e8'::uuid) AND (ROW(created_at, id) > ROW('2026-10-02 08:41:04.152402+00'::timestamp with time zone, '492d2f70-1f2b-4e98-a87d-5bab4668d05c'::uuid)))
|
||||
Buffers: shared hit=4
|
||||
Planning Time: 0.016 ms
|
||||
Execution Time: 0.014 ms
|
||||
@@ -0,0 +1,30 @@
|
||||
Lab 2 U5 level-4 checks, 2026-10-02, base commit d59d3f4 plus local changes.
|
||||
Local Colima Docker: 2 CPUs, 2054840320 bytes memory; disposable Compose stack.
|
||||
Command: make test-level4 (secrets and session tokens never printed).
|
||||
|
||||
docker compose --env-file .env exec -T api python - < student-tests/test_database.py
|
||||
...
|
||||
----------------------------------------------------------------------
|
||||
Ran 3 tests in 1.252s
|
||||
|
||||
OK
|
||||
docker compose --env-file .env exec -T api python - < student-tests/test_auth.py
|
||||
....
|
||||
----------------------------------------------------------------------
|
||||
Ran 4 tests in 5.335s
|
||||
|
||||
OK
|
||||
docker compose --env-file .env exec -T api python - < student-tests/test_cache_failures.py
|
||||
..
|
||||
----------------------------------------------------------------------
|
||||
Ran 2 tests in 0.300s
|
||||
|
||||
OK
|
||||
SQL queries (miss/hit/reload): 2/1/2; Valkey hit/miss deltas: 1/2
|
||||
CHECK_COMPOSE_FAILURES=1 python3 student-tests/test_compose_failures.py
|
||||
.
|
||||
----------------------------------------------------------------------
|
||||
Ran 1 test in 13.472s
|
||||
|
||||
OK
|
||||
Valkey outage: 200; PostgreSQL outage: readiness/auth 503; revoked token after Valkey restart: 401
|
||||
@@ -0,0 +1,71 @@
|
||||
"""Seed one synthetic chat and explain the two real history page queries."""
|
||||
|
||||
import argparse
|
||||
import secrets
|
||||
from datetime import datetime, timezone
|
||||
from uuid import uuid4
|
||||
|
||||
from src.store import Store, connection
|
||||
|
||||
|
||||
def explain(conn, label, query, params):
|
||||
print(f"\n{label}: EXPLAIN (ANALYZE, BUFFERS)")
|
||||
for row in conn.execute("EXPLAIN (ANALYZE, BUFFERS) " + query, params):
|
||||
print(row["QUERY PLAN"])
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--count", type=int, default=10_000)
|
||||
parser.add_argument("--deep-offset", type=int, default=8_000)
|
||||
args = parser.parse_args()
|
||||
if args.count < 10_000 or not 0 < args.deep_offset < args.count - 50:
|
||||
parser.error("count must be >=10000 and deep-offset must leave a full 50-row page")
|
||||
|
||||
store = Store()
|
||||
user = store.register("u_" + uuid4().hex[:16], "Synthetic history", secrets.token_urlsafe(18))
|
||||
chat = store.create_chat(user["id"], "Synthetic history", [user["id"]])
|
||||
base = datetime.now(timezone.utc)
|
||||
with connection() as conn:
|
||||
conn.execute(
|
||||
"INSERT INTO messages (id,chat_id,sender_id,text,created_at) "
|
||||
"SELECT gen_random_uuid(), %s, %s, 'synthetic-' || n, "
|
||||
"%s::timestamptz + n * interval '1 microsecond' "
|
||||
"FROM generate_series(1,%s) AS n",
|
||||
(chat["id"], user["id"], base, args.count),
|
||||
)
|
||||
conn.execute("ANALYZE messages")
|
||||
count = conn.execute("SELECT count(*) FROM messages WHERE chat_id=%s", (chat["id"],)).fetchone()["count"]
|
||||
assert count == args.count
|
||||
index = conn.execute(
|
||||
"SELECT indexdef FROM pg_indexes WHERE tablename='messages' AND indexname='messages_history_idx'"
|
||||
).fetchone()["indexdef"]
|
||||
cursor = conn.execute(
|
||||
"SELECT created_at,id FROM messages WHERE chat_id=%s "
|
||||
"ORDER BY created_at,id OFFSET %s LIMIT 1",
|
||||
(chat["id"], args.deep_offset - 1),
|
||||
).fetchone()
|
||||
projection = "SELECT id,chat_id,sender_id,text,created_at FROM messages WHERE chat_id=%s"
|
||||
first = projection + " ORDER BY created_at,id LIMIT 51"
|
||||
deep = projection + " AND (created_at,id)>(%s,%s) ORDER BY created_at,id LIMIT 51"
|
||||
first_params = (chat["id"],)
|
||||
deep_params = (chat["id"], cursor["created_at"], cursor["id"])
|
||||
first_rows = conn.execute(first, first_params).fetchall()
|
||||
deep_rows = conn.execute(deep, deep_params).fetchall()
|
||||
assert len(first_rows) == len(deep_rows) == 51
|
||||
assert not {row["id"] for row in first_rows} & {row["id"] for row in deep_rows}
|
||||
assert all((a["created_at"], a["id"]) < (b["created_at"], b["id"])
|
||||
for rows in (first_rows, deep_rows) for a, b in zip(rows, rows[1:]))
|
||||
print("Lab 2 U5 history index evidence")
|
||||
print("UTC:", datetime.now(timezone.utc).isoformat())
|
||||
print("PostgreSQL:", conn.execute("SHOW server_version").fetchone()["server_version"])
|
||||
print("Synthetic chat messages:", count)
|
||||
print("Deep cursor ordinal:", args.deep_offset)
|
||||
print("History index:", index)
|
||||
print("Verified: first/deep pages each have 51 ordered rows with no shared IDs")
|
||||
explain(conn, "First page", first, first_params)
|
||||
explain(conn, "Deep page", deep, deep_params)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+12
-6
@@ -39,6 +39,16 @@ def current_user(request: Request) -> dict:
|
||||
return store.authenticated(bearer_token(request.headers.get("authorization")))
|
||||
|
||||
|
||||
def page_limit(raw: str) -> int:
|
||||
digits = raw.lstrip("0")
|
||||
if not raw.isdecimal() or not digits or len(digits) > 3:
|
||||
raise HTTPException(400)
|
||||
limit = int(digits)
|
||||
if not 1 <= limit <= 100:
|
||||
raise HTTPException(400)
|
||||
return limit
|
||||
|
||||
|
||||
@router.delete("/api/v1/auth/sessions/current", status_code=204)
|
||||
def revoke_session(request: Request):
|
||||
store.revoke_session(bearer_token(request.headers.get("authorization")))
|
||||
@@ -59,9 +69,7 @@ def create_chat(body: CreateChat, actor: dict = Depends(current_user)):
|
||||
def list_chats(
|
||||
limit: str = Query("50"), cursor: str | None = Query(None, min_length=1), actor: dict = Depends(current_user)
|
||||
):
|
||||
if not limit.isdecimal() or not 1 <= int(limit) <= 100:
|
||||
raise HTTPException(400)
|
||||
return store.list_chats(actor["id"], int(limit), cursor)
|
||||
return store.list_chats(actor["id"], page_limit(limit), cursor)
|
||||
|
||||
|
||||
@router.get("/api/v1/chats/{chat_id}")
|
||||
@@ -81,6 +89,4 @@ def list_messages(
|
||||
cursor: str | None = Query(None, min_length=1),
|
||||
actor: dict = Depends(current_user),
|
||||
):
|
||||
if not limit.isdecimal() or not 1 <= int(limit) <= 100:
|
||||
raise HTTPException(400)
|
||||
return store.list_messages(actor["id"], str(chat_id), int(limit), cursor)
|
||||
return store.list_messages(actor["id"], str(chat_id), page_limit(limit), cursor)
|
||||
|
||||
@@ -14,12 +14,13 @@ import urllib.request
|
||||
from uuid import uuid4
|
||||
|
||||
import psycopg
|
||||
from src.db import database_url
|
||||
|
||||
|
||||
URL = os.environ.get("DATABASE_URL")
|
||||
URL = database_url() if os.environ.get("DATABASE_URL") or os.environ.get("DATABASE_URL_FILE") else None
|
||||
|
||||
|
||||
@unittest.skipUnless(URL, "set DATABASE_URL to a disposable PostgreSQL database")
|
||||
@unittest.skipUnless(URL, "set DATABASE_URL or DATABASE_URL_FILE to a disposable PostgreSQL database")
|
||||
class AuthTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
@@ -81,7 +82,7 @@ class AuthTests(unittest.TestCase):
|
||||
status = response.status
|
||||
response_headers = response.headers
|
||||
data = response.read()
|
||||
assert status == expected, (method, path, expected, status)
|
||||
assert status == expected, (method, path.split("?", 1)[0], expected, status)
|
||||
request_id = response_headers.get("X-Request-Id")
|
||||
assert request_id
|
||||
payload = json.loads(data) if data else None
|
||||
@@ -140,6 +141,15 @@ class AuthTests(unittest.TestCase):
|
||||
self.assertEqual(headers.get("WWW-Authenticate"), 'Basic realm="messenger", charset="UTF-8"')
|
||||
self.call("POST", "/api/v1/auth/sessions", authorization="Basic " + encoded, body={"unexpected": True}, expected=400)
|
||||
|
||||
def test_huge_page_limit_is_bad_request(self):
|
||||
user, password = self.user()
|
||||
session, _ = self.login(user["username"], password)
|
||||
bearer = "Bearer " + session["token"]
|
||||
for path in ("/api/v1/chats", f"/api/v1/chats/{uuid4()}/messages"):
|
||||
self.call("GET", path + "?limit=" + "9" * 4301, authorization=bearer, expected=400)
|
||||
self.call("GET", "/api/v1/chats?limit=0001", authorization=bearer)
|
||||
self.call("GET", "/api/v1/chats?limit=%D9%A0", authorization=bearer, expected=400)
|
||||
|
||||
def test_z_short_ttl_survives_server_restart_without_extension(self):
|
||||
self.stop_server()
|
||||
self.start_server(ttl="2")
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
"""Opt-in HTTP checks that stop only disposable Compose dependencies."""
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
|
||||
from client import Client
|
||||
|
||||
|
||||
def compose(*args):
|
||||
subprocess.run(
|
||||
["docker", "compose", "--env-file", ".env", *args],
|
||||
check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
|
||||
)
|
||||
|
||||
|
||||
@unittest.skipUnless(os.environ.get("CHECK_COMPOSE_FAILURES") == "1", "opt in on the disposable Compose stack")
|
||||
class ComposeFailureTests(unittest.TestCase):
|
||||
def test_cache_bypass_database_refusal_and_revocation(self):
|
||||
client = Client(base_url="http://127.0.0.1:8080", timeout=15)
|
||||
actor = client.user("outage")
|
||||
client.call("GET", "/api/v1/users/me", actor=actor, schema="User") # fill User cache
|
||||
|
||||
try:
|
||||
compose("stop", "valkey")
|
||||
client.call("GET", "/api/v1/users/me", actor=actor, schema="User")
|
||||
finally:
|
||||
compose("up", "-d", "--no-deps", "--wait", "valkey")
|
||||
|
||||
try:
|
||||
compose("stop", "postgres")
|
||||
client.call("GET", "/health/ready", expected=503)
|
||||
client.call("GET", "/api/v1/users/me", actor=actor, expected=503)
|
||||
finally:
|
||||
compose("up", "-d", "--no-deps", "--wait", "postgres")
|
||||
|
||||
client.call("GET", "/api/v1/users/me", actor=actor, schema="User")
|
||||
client.call("DELETE", "/api/v1/auth/sessions/current", actor=actor, expected=204)
|
||||
try:
|
||||
compose("restart", "valkey")
|
||||
finally:
|
||||
compose("up", "-d", "--no-deps", "--wait", "valkey")
|
||||
client.call("GET", "/api/v1/users/me", actor=actor, expected=401)
|
||||
print("Valkey outage: 200; PostgreSQL outage: readiness/auth 503; revoked token after Valkey restart: 401")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -5,17 +5,20 @@ import subprocess
|
||||
import sys
|
||||
import unittest
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from contextlib import contextmanager
|
||||
from unittest.mock import patch
|
||||
from uuid import uuid4
|
||||
|
||||
import psycopg
|
||||
|
||||
from src.store import Store
|
||||
from src.db import database_url
|
||||
from src.store import Store, connection
|
||||
|
||||
|
||||
URL = os.environ.get("DATABASE_URL")
|
||||
URL = database_url() if os.environ.get("DATABASE_URL") or os.environ.get("DATABASE_URL_FILE") else None
|
||||
|
||||
|
||||
@unittest.skipUnless(URL, "set DATABASE_URL to a disposable PostgreSQL database")
|
||||
@unittest.skipUnless(URL, "set DATABASE_URL or DATABASE_URL_FILE to a disposable PostgreSQL database")
|
||||
class DatabaseTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
@@ -80,6 +83,37 @@ class DatabaseTests(unittest.TestCase):
|
||||
self.store.chat(eve["id"], chat["id"])
|
||||
self.assertEqual(hidden.exception.status_code, 404)
|
||||
|
||||
def test_membership_failure_rolls_back_inserted_chat(self):
|
||||
alice, bob = self.user(), self.user()
|
||||
title = "rollback-" + uuid4().hex
|
||||
|
||||
class FailingConnection:
|
||||
def __init__(self, wrapped):
|
||||
self.wrapped = wrapped
|
||||
self.memberships = 0
|
||||
|
||||
def execute(self, query, params=None):
|
||||
if query.startswith("INSERT INTO memberships"):
|
||||
self.memberships += 1
|
||||
if self.memberships == 2:
|
||||
raise RuntimeError("synthetic second membership failure")
|
||||
return self.wrapped.execute(query, params)
|
||||
|
||||
@contextmanager
|
||||
def failing_connection():
|
||||
with connection() as conn:
|
||||
yield FailingConnection(conn)
|
||||
|
||||
with patch("src.store.connection", failing_connection):
|
||||
with self.assertRaisesRegex(RuntimeError, "synthetic second membership failure"):
|
||||
self.store.create_chat(alice["id"], title, [alice["id"], bob["id"]])
|
||||
with psycopg.connect(URL) as conn:
|
||||
self.assertEqual(conn.execute("SELECT count(*) FROM chats WHERE title=%s", (title,)).fetchone()[0], 0)
|
||||
self.assertEqual(conn.execute(
|
||||
"SELECT count(*) FROM memberships WHERE user_id IN (%s,%s)",
|
||||
(alice["id"], bob["id"]),
|
||||
).fetchone()[0], 0)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
Reference in New Issue
Block a user