Files

112 lines
6.6 KiB
Python

"""Regressions for lab3 shared message results, real PostgreSQL (no mocks)."""
from concurrent.futures import ThreadPoolExecutor
import uuid
from psycopg import sql
from test_api import client, user, login
def setup_chat(c, extra=None):
u, body = user(c)
headers, _ = login(c, body)
members = [u['id']] + (extra or [])
chat = c.post('/api/v1/chats', headers=headers, json={'title':'Идемпотентность', 'member_ids':members}).json()
return u, headers, '/api/v1/chats/'+chat['id']+'/messages'
def test_instance_alias_on_success_and_errors(client):
responses = [client.get('/health/live'), client.get('/health/ready'), client.get('/api/v1/users/me'),
client.get('/unknown'), client.post('/api/v1/users', content='{', headers={'Content-Type':'application/json'})]
ids = [r.headers.get('X-Instance-Id') for r in responses]
assert ids[0] and len(set(ids)) == 1
assert all(r.headers.get('X-Request-Id') for r in responses)
def test_key_required_replay_and_conflict(client):
_, headers, path = setup_chat(client)
assert client.post(path, headers=headers, json={'text':'same'}).status_code == 400
for key in ['', 'a b', 'bad/', 'x'*129]:
assert client.post(path, headers={**headers,'Idempotency-Key':key},json={'text':'same'}).status_code == 400
h = {**headers, 'Idempotency-Key':'valid:._-123'}
first = client.post(path, headers=h, json={'text':'same'})
assert first.status_code == 201
replay = client.post(path, headers={**h,'Content-Type':'application/json'},content=' { "text" : "same" } ')
assert replay.status_code == 201 and replay.json() == first.json()
assert client.post(path, headers=h, json={'text':'other'}).status_code == 409
assert len(client.get(path,headers=headers).json()['items']) == 1
def test_concurrent_key_produces_one_message(client):
_, headers, path = setup_chat(client)
h = {**headers, 'Idempotency-Key':uuid.uuid4().hex}
with ThreadPoolExecutor(max_workers=8) as pool:
results = list(pool.map(lambda _: client.post(path,headers=h,json={'text':'concurrent'}), range(16)))
assert [r.status_code for r in results] == [201]*16
assert all(r.json() == results[0].json() for r in results)
assert client.get(path,headers=headers).json()['items'] == [results[0].json()]
def test_scope_and_replay_rechecks_authorization(client):
b, bb = user(client)
bh, _ = login(client, bb)
a, ah, path = setup_chat(client, [b['id']])
key = 'same-in-independent-scopes'
first = client.post(path,headers={**ah,'Idempotency-Key':key},json={'text':'a'}).json()
second = client.post(path,headers={**bh,'Idempotency-Key':key},json={'text':'b'})
assert second.status_code == 201 and second.json()['id'] != first['id']
chat = client.post('/api/v1/chats',headers=ah,json={'title':'Другая область','member_ids':[a['id']]}).json()
other_path = '/api/v1/chats/'+chat['id']+'/messages'
third = client.post(other_path,headers={**ah,'Idempotency-Key':key},json={'text':'a'})
assert third.status_code == 201 and third.json()['id'] != first['id']
outsider, ob = user(client)
oh, _ = login(client, ob)
assert client.post(path,headers={**oh,'Idempotency-Key':key},json={'text':'a'}).status_code == 404
assert client.delete('/api/v1/auth/sessions/current',headers=ah).status_code == 204
assert client.post(path,headers={**ah,'Idempotency-Key':key},json={'text':'a'}).status_code == 401
def test_expired_key_can_be_reused(client):
u, h, path = setup_chat(client)
key = uuid.uuid4().hex
first = client.post(path,headers={**h,'Idempotency-Key':key},json={'text':'first'}).json()
with client.app.state.db.pool.connection() as conn:
ttl = conn.execute('SELECT extract(epoch FROM expires_at-clock_timestamp()) AS seconds FROM idempotency_records WHERE user_id=%s AND key=%s',(u['id'],key)).fetchone()['seconds']
assert 86390 <= ttl <= 86400
conn.execute("UPDATE idempotency_records SET expires_at=clock_timestamp()-interval '1 second' WHERE user_id=%s AND key=%s", (u['id'],key))
second = client.post(path,headers={**h,'Idempotency-Key':key},json={'text':'second'})
assert second.status_code == 201 and second.json()['id'] != first['id']
assert len(client.get(path,headers=h).json()['items']) == 2
def test_rollback_side_effect_and_key_on_database_error(client):
u, h, path = setup_chat(client)
key = uuid.uuid4().hex
text = 'fault_' + uuid.uuid4().hex
function = 'fault_' + uuid.uuid4().hex
trigger = 'trigger_' + uuid.uuid4().hex
db = client.app.state.db
# AFTER INSERT fails after the side effect. This is a DB-only test fixture, not a production hook.
with db.pool.connection() as conn:
conn.execute(sql.SQL("CREATE FUNCTION {}() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.text = {} THEN RAISE EXCEPTION 'synthetic insert fault'; END IF; RETURN NEW; END $$").format(sql.Identifier(function), sql.Literal(text)))
conn.execute(sql.SQL('CREATE TRIGGER {} AFTER INSERT ON messages FOR EACH ROW EXECUTE FUNCTION {}()').format(sql.Identifier(trigger),sql.Identifier(function)))
try:
failed = client.post(path,headers={**h,'Idempotency-Key':key},json={'text':text})
assert failed.status_code == 500
assert failed.headers['X-Instance-Id']
with db.pool.connection() as conn:
assert conn.execute('SELECT count(*) AS n FROM messages WHERE text=%s',(text,)).fetchone()['n'] == 0
assert conn.execute('SELECT count(*) AS n FROM idempotency_records WHERE user_id=%s AND key=%s',(u['id'],key)).fetchone()['n'] == 0
finally:
with db.pool.connection() as conn:
conn.execute(sql.SQL('DROP TRIGGER IF EXISTS {} ON messages').format(sql.Identifier(trigger)))
conn.execute(sql.SQL('DROP FUNCTION IF EXISTS {}()').format(sql.Identifier(function)))
retried = client.post(path,headers={**h,'Idempotency-Key':key},json={'text':text})
assert retried.status_code == 201
assert client.get(path,headers=h).json()['items'] == [retried.json()]
def test_ready_requires_compatible_schema(client):
temporary = 'temporarily_unavailable_' + uuid.uuid4().hex
with client.app.state.db.pool.connection() as conn:
conn.execute(sql.SQL('ALTER TABLE idempotency_records RENAME TO {}').format(sql.Identifier(temporary)))
try:
r = client.get('/health/ready')
assert r.status_code == 503
assert r.json()['error']['code'] == 'unavailable'
assert client.get('/health/live').status_code == 200
finally:
with client.app.state.db.pool.connection() as conn:
conn.execute(sql.SQL('ALTER TABLE {} RENAME TO idempotency_records').format(sql.Identifier(temporary)))