This commit is contained in:
Xabenskie
2026-11-10 18:09:43 +03:00
parent 276dbdad8a
commit f3393a8b1b
65 changed files with 4553 additions and 42 deletions
+141
View File
@@ -0,0 +1,141 @@
"""Integration tests: real PostgreSQL and Redis, isolated synthetic identities."""
import base64
import json
import time
import uuid
from concurrent.futures import ThreadPoolExecutor
import pytest
from fastapi.testclient import TestClient
from messenger.app import create_app
PASSWORD = 'Тестовый:пароль🔐' * 8
@pytest.fixture
def client():
with TestClient(create_app()) as c:
yield c
def user(c):
body = dict(username='u_' + uuid.uuid4().hex[:24], display_name='Алиса 👋', password=PASSWORD)
r = c.post('/api/v1/users', json=body)
assert r.status_code == 201, r.text
return r.json(), body
def login(c, body):
credentials = base64.b64encode((body['username'] + ':' + body['password']).encode()).decode()
r = c.post('/api/v1/auth/sessions', headers={'Authorization': 'Basic ' + credentials})
assert r.status_code == 201, r.text
return {'Authorization': 'Bearer ' + r.json()['token']}, r.json()
def test_auth_unicode_logout_and_cache(client):
u, body = user(client)
h, session = login(client, body)
assert session['user'] == u
assert len(session['token']) >= 43
key = 'user:' + u['id']
client.app.state.db.cache.delete(key)
for _ in range(2):
assert client.get('/api/v1/users/me', headers=h).json() == u
cached = json.loads(client.app.state.db.cache.get(key))
assert cached == u
assert 0 < client.app.state.db.cache.ttl(key) <= 60
assert client.delete('/api/v1/auth/sessions/current', headers=h).status_code == 204
r = client.get('/api/v1/users/me', headers=h)
assert r.status_code == 401
assert r.headers['www-authenticate'] == 'Bearer realm="messenger"'
assert r.json()['error']['request_id'] == r.headers['x-request-id']
def test_session_expiry(monkeypatch):
monkeypatch.setenv('SESSION_TTL_SECONDS', '2')
with TestClient(create_app()) as client:
_, body = user(client)
h, _ = login(client, body)
assert client.get('/api/v1/users/me', headers=h).status_code == 200
time.sleep(2.1)
assert client.get('/api/v1/users/me', headers=h).status_code == 401
def test_registration_race(client):
body = dict(username='race_' + uuid.uuid4().hex[:22], display_name='Race', password=PASSWORD)
with ThreadPoolExecutor(max_workers=6) as executor:
codes = list(executor.map(lambda _: client.post('/api/v1/users', json=body).status_code, range(6)))
assert sorted(codes) == [201, 409, 409, 409, 409, 409]
def test_chat_rollback_after_insert(client):
u, body = user(client)
h, _ = login(client, body)
title = 'rollback_' + uuid.uuid4().hex
r = client.post('/api/v1/chats', headers=h, json={'title': title, 'member_ids': [u['id'], str(uuid.uuid4())]})
assert r.status_code == 400
with client.app.state.db.pool.connection() as conn:
assert conn.execute('SELECT count(*) AS n FROM chats WHERE title=%s', (title,)).fetchone()['n'] == 0
assert conn.execute('SELECT count(*) AS n FROM chat_members m LEFT JOIN chats c ON c.id=m.chat_id WHERE c.id IS NULL').fetchone()['n'] == 0
def test_cursor_access_and_strict_validation(client):
a, ab = user(client)
b, bb = user(client)
ah, _ = login(client, ab)
bh, _ = login(client, bb)
chats = [client.post('/api/v1/chats', headers=ah, json={'title':'Чат','member_ids':[a['id']]}).json() for _ in range(2)]
path = '/api/v1/chats/' + chats[0]['id']
for text in ['Один 👋', 'Два', 'Три']:
assert client.post(path+'/messages', headers={**ah,'Idempotency-Key':uuid.uuid4().hex}, json={'text':text}).status_code == 201
p = client.get(path+'/messages?limit=2', headers=ah).json()
assert [m['text'] for m in p['items']] == ['Один 👋','Два']
tail = client.get(path+'/messages', headers=ah, params={'cursor':p['next_cursor'],'limit':1}).json()
assert [m['text'] for m in tail['items']] == ['Три']
assert tail['next_cursor'] is None
r = client.get('/api/v1/chats/'+chats[1]['id']+'/messages',headers=ah, params={'cursor':p['next_cursor']})
assert r.status_code == 400
assert client.get(path, headers=bh).status_code == 404
for payload in [{'text':123}, {'text':' '}, {'text':'ok','sender_id':b['id']}, {'text':'x'*4001}]:
assert client.post(path+'/messages',headers={**ah,'Idempotency-Key':uuid.uuid4().hex},json=payload).status_code == 400
for query in ['limit=0','limit=101','limit=1.0','cursor=bad','cursor=']:
assert client.get(path+'/messages?'+query,headers=ah).status_code == 400
for payload in [{'username':123,'display_name':'a','password':PASSWORD}, {'username':'valid','display_name':' ','password':PASSWORD}]:
assert client.post('/api/v1/users',json=payload).status_code == 400
assert client.post('/api/v1/users',content='{',headers={'Content-Type':'application/json'}).status_code == 400
def test_session_storage_and_migrations(client):
from messenger.migrate import main as migrate
u, body = user(client)
_, session = login(client, body)
db = client.app.state.db
def snapshot():
with db.pool.connection() as conn:
return {table: conn.execute('SELECT count(*) AS n FROM '+table).fetchone()['n']
for table in ['users','chats','chat_members','messages','sessions','schema_migrations','idempotency_records']}
before = snapshot()
migrate()
migrate()
assert snapshot() == before
with db.pool.connection() as conn:
row = conn.execute('SELECT token_hash,expires_at FROM sessions WHERE user_id=%s', (u['id'],)).fetchone()
assert row['token_hash'] != session['token']
assert len(row['token_hash']) == 64
stored = conn.execute('SELECT password_hash FROM users WHERE id=%s', (u['id'],)).fetchone()['password_hash']
assert stored.startswith('$argon2id$')
assert stored != body['password']
def test_json_media_type_and_utf8(client):
body = dict(username='media_' + uuid.uuid4().hex[:24], display_name='UTF8', password=PASSWORD)
raw = json.dumps(body).encode()
for headers in [{}, {'Content-Type':'text/plain'}, {'Content-Type':'application/xml'}]:
r = client.post('/api/v1/users',content=raw,headers=headers)
assert r.status_code == 415
assert r.json()['error']['code'] == 'unsupported_media_type'
for encoding in ['utf-16', 'utf-16-le', 'utf-16-be', 'utf-32-le', 'utf-32-be']:
r = client.post('/api/v1/users',content=json.dumps(body).encode(encoding),headers={'Content-Type':'application/json'})
assert r.status_code == 400, encoding
r = client.post('/api/v1/chats',content=b'{}',headers={'Content-Type':'text/plain'})
assert r.status_code == 401
+187
View File
@@ -0,0 +1,187 @@
"""Real PostgreSQL + private S3 integration; synthetic images only."""
import hashlib
import io
import struct
import uuid
import zlib
from PIL import Image
from psycopg import sql
from test_api import client, user, login
def image_bytes(kind='PNG'):
stream = io.BytesIO()
Image.new('RGB',(320,200),(45,110,190)).save(stream,format=kind)
return stream.getvalue()
def actors(c):
a,ab=user(c)
b,bb=user(c)
e,eb=user(c)
ah,_=login(c,ab)
bh,_=login(c,bb)
eh,_=login(c,eb)
chat=c.post('/api/v1/chats',headers=ah,json={'title':'Файлы','member_ids':[a['id'],b['id']]}).json()
return ah,bh,eh,chat
def upload(c,headers,chat,raw=None,mime='image/png',filename='Фото.png'):
raw=image_bytes() if raw is None else raw
return c.post('/api/v1/chats/'+chat['id']+'/attachments',params={'filename':filename},content=raw,
headers={**headers,'Content-Type':mime})
def finish(client,attachment_id):
from messenger.jobs import work
with client.app.state.db.pool.connection() as conn:
job=conn.execute('SELECT id FROM attachment_jobs WHERE attachment_id=%s',(attachment_id,)).fetchone()['id']
work(client.app.state.db,client.app.state.storage,job)
import time
for _ in range(100):
with client.app.state.db.pool.connection() as conn:
status=conn.execute('SELECT status FROM attachments WHERE id=%s',(attachment_id,)).fetchone()['status']
if status=='ready': return
time.sleep(.1)
raise AssertionError('Job did not become ready: '+status)
def test_original_png_jpeg_and_message(client):
ah,bh,eh,chat=actors(client)
for kind,mime in [('PNG','image/png'),('JPEG','image/jpeg')]:
raw=image_bytes(kind)
r=upload(client,ah,chat,raw,mime)
assert r.status_code==202
att=r.json()
assert att['status']=='queued' and att['variants']==[] and att['error_code'] is None
assert client.get('/api/v1/attachments/'+att['id']+'/content',headers=bh).status_code==409
finish(client,att['id'])
att=client.get('/api/v1/attachments/'+att['id'],headers=bh).json()
assert att['status']=='ready' and len(att['variants'])==3
assert att['sha256']==hashlib.sha256(raw).hexdigest() and att['size_bytes']==len(raw)
assert 'object_key' not in att and 'bucket' not in att
path='/api/v1/attachments/'+att['id']
assert client.get(path,headers=bh).json()==att
content=client.get(path+'/content',headers=bh)
assert content.status_code==200 and content.content==raw
assert content.headers['Content-Type']==mime
for suffix in ['', '/content']:
assert client.get(path+suffix,headers=eh).status_code==404
assert client.get(path+'/content?variant=thumbnail',headers=bh).status_code==200
response=client.post('/api/v1/chats/'+chat['id']+'/messages',headers={**ah,'Idempotency-Key':uuid.uuid4().hex},
json={'text':'','attachment_ids':[att['id']]})
assert response.status_code==201
assert response.json()['attachment_ids']==[att['id']]
def test_invalid_media_corruption_limits_and_filename(client):
ah,_,_,chat=actors(client)
cases=[(b'not an image','image/png',415),(image_bytes(),'image/jpeg',415),
(image_bytes('JPEG'),'image/png',415),(image_bytes()[:40],'image/png',415),
(image_bytes(),'text/plain',415),(b'x'*(10485760+1),'image/png',413)]
for raw,mime,expected in cases:
response=upload(client,ah,chat,raw,mime)
assert response.status_code==expected
assert response.json()['error']['request_id']==response.headers['X-Request-Id']
# Valid PNG header advertises >40Mp; reject before attempting decompression.
header=struct.pack('!IIBBBBB',10001,4000,8,2,0,0,0)
chunk=lambda tag,data: struct.pack('!I',len(data))+tag+data+struct.pack('!I',zlib.crc32(tag+data)&0xffffffff)
bomb=b'\x89PNG\r\n\x1a\n'+chunk(b'IHDR',header)+chunk(b'IDAT',zlib.compress(b''))+chunk(b'IEND',b'')
assert upload(client,ah,chat,bomb).status_code==413
for filename in ['../x.png','a\\b.png','bad\x00.png','bad\x1f.png','bad\x7f.png',' ','x'*256]:
assert upload(client,ah,chat,filename=filename).status_code==400
def test_foreign_attachment_binding_and_normalized_replay(client):
ah,bh,eh,chat=actors(client)
att=upload(client,ah,chat).json()
other=client.post('/api/v1/chats',headers=bh,json={'title':'Другой чат','member_ids':[chat['member_ids'][0],chat['member_ids'][1]]}).json()
path='/api/v1/chats/'+other['id']+'/messages'
for aid in [att['id'],str(uuid.uuid4())]:
response=client.post(path,headers={**bh,'Idempotency-Key':uuid.uuid4().hex},json={'text':'test','attachment_ids':[aid]})
assert response.status_code==404
assert upload(client,eh,chat).status_code==404
h={**ah,'Idempotency-Key':uuid.uuid4().hex}
path='/api/v1/chats/'+chat['id']+'/messages'
first=client.post(path,headers=h,json={'text':'same'})
replay=client.post(path,headers=h,json={'attachment_ids':[],'text':'same'})
assert first.status_code==replay.status_code==201 and first.json()==replay.json()
conflict=client.post(path,headers=h,json={'text':'same','attachment_ids':[att['id']]})
assert conflict.status_code==409
duplicates=client.post(path,headers={**ah,'Idempotency-Key':uuid.uuid4().hex},json={'text':'','attachment_ids':[att['id'],att['id']]})
assert duplicates.status_code==400
def test_compensate_s3_when_metadata_insert_fails(client):
ah,_,_,chat=actors(client)
db=client.app.state.db
store=client.app.state.storage
before={item['Key'] for page in store.pages(prefix="staging/") for item in page.get('Contents',[])}
function='fail_attachment_'+uuid.uuid4().hex
trigger='fail_attachment_'+uuid.uuid4().hex
filename='fault_'+uuid.uuid4().hex+'.png'
with db.pool.connection() as conn:
conn.execute(sql.SQL("CREATE FUNCTION {}() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.filename={} THEN RAISE EXCEPTION 'synthetic metadata failure'; END IF; RETURN NEW; END $$").format(sql.Identifier(function),sql.Literal(filename)))
conn.execute(sql.SQL('CREATE TRIGGER {} BEFORE INSERT ON attachments FOR EACH ROW EXECUTE FUNCTION {}()').format(sql.Identifier(trigger),sql.Identifier(function)))
try:
response=upload(client,ah,chat,filename=filename)
assert response.status_code==503
with db.pool.connection() as conn:
assert conn.execute('SELECT count(*) AS n FROM attachments WHERE filename=%s',(filename,)).fetchone()['n']==0
after={item['Key'] for page in store.pages(prefix="staging/") for item in page.get('Contents',[])}
assert after==before
finally:
with db.pool.connection() as conn:
conn.execute(sql.SQL('DROP TRIGGER IF EXISTS {} ON attachments').format(sql.Identifier(trigger)))
conn.execute(sql.SQL('DROP FUNCTION IF EXISTS {}()').format(sql.Identifier(function)))
def test_compensation_preserves_committed_object(client):
from messenger.attachments import compensate
ah,_,_,chat=actors(client)
att=upload(client,ah,chat).json()
finish(client,att['id'])
with client.app.state.db.pool.connection() as conn:
key=conn.execute('SELECT object_key FROM attachments WHERE id=%s',(att['id'],)).fetchone()['object_key']
# A retry after an unknown COMMIT result must never delete an already tracked object.
compensate(client.app.state.db,client.app.state.storage,key)
content=client.get('/api/v1/attachments/'+att['id']+'/content',headers=ah)
assert content.status_code==200 and content.content==image_bytes()
def test_stream_close_even_if_headers_cannot_be_sent(client):
import asyncio
import pytest
from messenger.attachments import ObjectResponse
ah,_,_,chat=actors(client)
att=upload(client,ah,chat).json()
finish(client,att['id'])
with client.app.state.db.pool.connection() as conn:
key=conn.execute('SELECT object_key FROM attachments WHERE id=%s',(att['id'],)).fetchone()['object_key']
store=client.app.state.storage
opened=store.get(key)
response=ObjectResponse(opened,media_type='image/png')
async def fail_send(message):
raise OSError('synthetic disconnected transport')
async def receive():
return {'type':'http.disconnect'}
with pytest.raises(Exception):
asyncio.run(response({'type':'http','asgi':{'spec_version':'2.4'}},receive,fail_send))
assert opened.closed
acquired=0
try:
for _ in range(8):
assert store.gate.acquire(blocking=False)
acquired+=1
finally:
for _ in range(acquired):
store.gate.release()
def test_chunked_upload_is_limited_without_content_length(client):
ah,_,_,chat=actors(client)
chunks=iter([b'x'*1048576]*10+[b'x'])
response=client.post('/api/v1/chats/'+chat['id']+'/attachments?filename=chunked.png',
content=chunks,headers={**ah,'Content-Type':'image/png'})
assert response.status_code==413
assert response.json()['error']['code']=='payload_too_large'
+119
View File
@@ -0,0 +1,119 @@
"""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)))
+63
View File
@@ -0,0 +1,63 @@
import io
import pytest
from messenger.jobs import work, replay
from test_attachments import actors,upload,image_bytes,finish
from test_api import client
def job_for(client,aid):
with client.app.state.db.pool.connection() as conn:
return conn.execute('SELECT id FROM attachment_jobs WHERE attachment_id=%s',(aid,)).fetchone()['id']
def test_duplicate_ready_is_noop_and_not_replayable(client):
ah,_,_,chat=actors(client)
att=upload(client,ah,chat).json()
finish(client,att['id'])
path='/api/v1/attachments/'+att['id']
before=client.get(path,headers=ah).json()
job=job_for(client,att['id'])
for _ in range(3): assert work(client.app.state.db,client.app.state.storage,job,1)
assert client.get(path,headers=ah).json()==before
with pytest.raises(ValueError): replay(client.app.state.db,job,'must reject ready')
with client.app.state.db.pool.connection() as conn:
row=conn.execute('SELECT attempt FROM attachment_jobs WHERE id=%s',(job,)).fetchone()
assert row['attempt']==1
assert conn.execute('SELECT staging_key FROM attachments WHERE id=%s',(att['id'],)).fetchone()['staging_key'] is None
def test_old_delivery_does_not_consume_attempt(client):
# Direct invocation avoids consumer timing; it exercises the same real DB/S3 code.
ah,_,_,chat=actors(client)
att=upload(client,ah,chat).json()
job=job_for(client,att['id'])
assert work(client.app.state.db,client.app.state.storage,job,999)
with client.app.state.db.pool.connection() as conn:
row=conn.execute('SELECT attempt FROM attachment_jobs WHERE id=%s',(job,)).fetchone()
assert row['attempt'] in (0,1) # independent live consumer may already finish this job
finish(client,att['id'])
def test_replay_sql_failure_releases_session_lock(client):
import psycopg
from messenger.db import setting
from psycopg.rows import dict_row
ah,_,_,chat=actors(client)
att=upload(client,ah,chat).json()
finish(client,att['id'])
job=job_for(client,att['id'])
db=client.app.state.db
with db.pool.connection() as conn:
conn.execute("UPDATE attachments SET status='failed',staging_key=%s WHERE id=%s",('staging/'+att['id'],att['id']))
conn.execute("CREATE FUNCTION lab5_fail_audit() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'synthetic audit failure'; END $$")
conn.execute('CREATE TRIGGER lab5_fail_audit BEFORE INSERT ON job_replays FOR EACH ROW EXECUTE FUNCTION lab5_fail_audit()')
try:
with pytest.raises(psycopg.Error): replay(db,job,'test failed transaction unlock')
with psycopg.connect(setting('DATABASE_URL'),row_factory=dict_row) as other:
acquired=other.execute('SELECT pg_try_advisory_lock(hashtextextended(%s,0)) AS ok',('job:'+str(job),)).fetchone()['ok']
if acquired: other.execute('SELECT pg_advisory_unlock(hashtextextended(%s,0))',('job:'+str(job),))
assert acquired, 'Aborted replay leaked a session advisory lock into the pool'
finally:
with db.pool.connection() as conn:
conn.execute('DROP TRIGGER lab5_fail_audit ON job_replays')
conn.execute('DROP FUNCTION lab5_fail_audit()')
+72
View File
@@ -0,0 +1,72 @@
"""Real image transformations, no mock storage."""
import hashlib
import io
import json
import subprocess
import sys
from PIL import Image
def test_worker_variants_and_original(tmp_path):
source=tmp_path/'input'
original=Image.new('RGBA',(320,200),(30,90,150,70))
original.save(source,format='PNG')
before=hashlib.sha256(source.read_bytes()).hexdigest()
result=subprocess.run([sys.executable,'-m','messenger.pipeline',str(source),str(tmp_path)],capture_output=True)
assert result.returncode==0, result.stderr
manifest=json.loads(result.stdout)
assert hashlib.sha256(source.read_bytes()).hexdigest()==before
for kind,fmt,size in [('thumbnail','JPEG',(256,160)),('crop','JPEG',(128,128)),('optimized','WEBP',(320,200))]:
item=manifest[kind]
with Image.open(tmp_path/kind) as image:
assert image.format==fmt and image.size==size
assert not image.getexif()
raw=(tmp_path/kind).read_bytes()
assert item['sha256']==hashlib.sha256(raw).hexdigest()
assert item['size_bytes']==len(raw)
def test_no_upscale_thumbnail_and_exif(tmp_path):
source=tmp_path/'input'
image=Image.new('RGB',(80,40),'red')
exif=Image.Exif();exif[274]=6
image.save(source,format='JPEG',exif=exif)
result=subprocess.run([sys.executable,'-m','messenger.pipeline',str(source),str(tmp_path)],capture_output=True)
assert result.returncode==0, result.stderr
with Image.open(tmp_path/'thumbnail') as output:
assert output.size==(40,80)
assert not output.getexif()
def test_deadline_covers_slow_s3(monkeypatch):
import contextlib
import http.server
import os
import threading
import time
import uuid
import pytest
from messenger.jobs import process_objects
class Slow(http.server.BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header('Content-Length','100')
self.end_headers()
try:
for _ in range(100):
self.wfile.write(b'x');self.wfile.flush();time.sleep(.05)
except (BrokenPipeError,ConnectionResetError): pass
def log_message(self,*args): pass
server=http.server.ThreadingHTTPServer(('127.0.0.1',0),Slow)
thread=threading.Thread(target=server.serve_forever,daemon=True);thread.start()
monkeypatch.delenv('S3_ENDPOINT_FILE',raising=False)
monkeypatch.setenv('S3_ENDPOINT','http://127.0.0.1:'+str(server.server_port))
monkeypatch.setenv('PROCESS_TIMEOUT_SECONDS','2')
row={'id':uuid.uuid4(),'staging_key':'staging/slow','object_key':'originals/slow',
'size_bytes':100,'sha256':hashlib.sha256(b'x'*100).hexdigest(),'content_type':'image/png'}
started=time.monotonic()
try:
with pytest.raises(subprocess.TimeoutExpired): process_objects(__import__("messenger.object_store",fromlist=["ObjectStore"]).ObjectStore(),row)
assert time.monotonic()-started<4
finally:
server.shutdown();server.server_close()