80 lines
6.1 KiB
Python
80 lines
6.1 KiB
Python
import json, os, pathlib, subprocess, time, hashlib
|
|
s=json.loads(pathlib.Path('/tmp/highload-current-migration-review.json').read_text())
|
|
root=pathlib.Path(s['root']); tmp=pathlib.Path(s['tmp']); project=s['project']
|
|
assert project.startswith('highload-migration-review-')
|
|
base=['docker','compose','--project-name',project,'--project-directory',str(root),'-f',str(root/'compose.yaml'),'-f',str(tmp/'compose.test.yaml')]
|
|
results=[]
|
|
def call(args,label,expected=0,env=None,input=None):
|
|
p=subprocess.run(args,cwd=root,env=env,input=input,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,text=True,timeout=180)
|
|
(tmp/(label+'.log')).write_text(p.stdout)
|
|
if expected is not None and p.returncode!=expected:
|
|
print(label+': unexpected exit '+str(p.returncode),flush=True)
|
|
raise RuntimeError(label+' failed; inspect saved log')
|
|
return p
|
|
def sql(query,label):
|
|
return call(base+['exec','-T','postgres','psql','-X','-v','ON_ERROR_STOP=1','-U','messenger','-d','messenger','-At'],label,input=query+'\n').stdout.strip()
|
|
def check(name,condition):
|
|
results.append({'check':name,'status':'PASS' if condition else 'FAIL'})
|
|
print(name+': '+results[-1]['status'],flush=True)
|
|
if not condition: raise AssertionError(name)
|
|
def records(output):
|
|
rows=[json.loads(x) for x in output.splitlines() if x.strip()]
|
|
password=(tmp/'postgres_password').read_text()
|
|
check('log contents contain neither SQL nor connection secrets',all('statement' not in x for x in rows) and 'CREATE TABLE' not in output and 'postgres://' not in output and password not in output)
|
|
return rows
|
|
try:
|
|
deadline=time.monotonic()+60
|
|
while True:
|
|
p=call(base+['exec','-T','postgres','pg_isready','-U','messenger','-d','messenger'],'postgres-ready',expected=None)
|
|
if p.returncode==0: break
|
|
if time.monotonic()>=deadline: raise RuntimeError('test PostgreSQL not ready')
|
|
time.sleep(.5)
|
|
port=call(base+['port','postgres','5432'],'postgres-port').stdout.strip().rsplit(':',1)[1]
|
|
env=os.environ.copy()
|
|
env['MIGRATE_TEST_DATABASE_URL']='postgres://messenger:'+(tmp/'postgres_password').read_text()+'@127.0.0.1:'+port+'/messenger?sslmode=disable'
|
|
p=call(['go','test','-race','./cmd/migrate','-count=1','-v'],'go-migrate-tests',env=env)
|
|
check('unit and real PostgreSQL migration tests including concurrent runners',p.returncode==0 and 'SKIP' not in p.stdout)
|
|
sql('CREATE TABLE public.chats (marker text);','seed-conflicting-table')
|
|
p=call(base+['up','-d','--no-build','api'],'failed-migration-api-gate',expected=None)
|
|
check('Compose refuses API startup after migration failure',p.returncode!=0)
|
|
migration_id=call(base+['ps','-aq','migrate'],'failed-migration-container').stdout.strip()
|
|
state=json.loads(call(['docker','inspect','--format','{{json .State}}',migration_id],'failed-migration-state').stdout)
|
|
check('failed migrator exits with code 1',state['ExitCode']==1 and not state['Running'])
|
|
rows=records(call(['docker','logs',migration_id],'failed-migration-json').stdout)
|
|
check('failed migration reports only stage SQLSTATE and file/version',len(rows)==1 and rows[0].get('sqlstate')=='42P07' and rows[0].get('version')==1 and rows[0].get('stage')=='apply pending migrations')
|
|
api_id=call(base+['ps','-aq','api'],'blocked-api-container').stdout.strip()
|
|
if api_id:
|
|
api_state=json.loads(call(['docker','inspect','--format','{{json .State}}',api_id],'blocked-api-state').stdout)
|
|
check('API process never started on failed migration',not api_state['Running'] and api_state['StartedAt'].startswith('0001-'))
|
|
else: check('API process never started on failed migration',True)
|
|
check('DDL rolled back when migration failed',sql("SELECT to_regclass('public.users') IS NULL;",'failed-migration-rollback')=='t')
|
|
sql('DROP TABLE public.chats;','remove-test-conflict')
|
|
call(base+['rm','-f','migrate'],'remove-failed-job')
|
|
call(base+['up','-d','--no-build','api'],'successful-startup')
|
|
migration_id=call(base+['ps','-aq','migrate'],'successful-migration-container').stdout.strip()
|
|
rows=records(call(['docker','logs',migration_id],'successful-migration-json').stdout)
|
|
check('container applies both pending migrations with safe per-version logs',[x.get('version') for x in rows if x.get('msg')=='migration applied']==[1,2] and rows[-1].get('applied')==2)
|
|
api_id=call(base+['ps','-aq','api'],'running-api-container').stdout.strip()
|
|
api_state=json.loads(call(['docker','inspect','--format','{{json .State}}',api_id],'running-api-state').stdout)
|
|
check('API starts after successful migration',api_state['Running'])
|
|
sql("INSERT INTO users (username, display_name, password_hash) VALUES ('runtime_fixture', 'Runtime fixture', 'synthetic-test-only-hash');",'insert-runtime-fixture')
|
|
p=call(base+['run','--rm','--no-deps','-T','migrate'],'repeat-migration')
|
|
# Compose creation lines are not application logs.
|
|
rows=records('\n'.join(x for x in p.stdout.splitlines() if x.startswith('{')))
|
|
check('repeat container migration applies no changes',rows[-1].get('applied')==0)
|
|
check('repeat preserves rows and migration history',sql("SELECT (SELECT count(*) FROM users WHERE username='runtime_fixture'), (SELECT count(*) FROM goose_db_version WHERE version_id>0 AND is_applied);",'repeat-counts')=='1|2')
|
|
call(['make','check'],'teacher-contract-check')
|
|
check('teacher offline contract check',True)
|
|
protected=json.loads((tmp/'source-before.json').read_text())
|
|
changed=[name for name,expected in protected.items() if hashlib.sha256((root/name).read_bytes()).hexdigest()!=expected]
|
|
check('no unrelated application or SQL changes during verification',not changed)
|
|
except Exception as e:
|
|
results.append({'check':'runner completion','status':'FAIL','reason':str(e)})
|
|
print('Runtime verification failed: '+str(e),flush=True)
|
|
finally:
|
|
cleanup=call(base+['down','--volumes','--remove-orphans'],'cleanup',expected=None)
|
|
results.append({'check':'cleanup of this disposable project only','status':'PASS' if cleanup.returncode==0 else 'FAIL'})
|
|
(tmp/'summary.json').write_text(json.dumps({'project':project,'results':results,'overall':'PASS' if all(r['status']=='PASS' for r in results) else 'FAIL'},ensure_ascii=False,indent=2))
|
|
print('Overall: '+('PASS' if all(r['status']=='PASS' for r in results) else 'FAIL'),flush=True)
|
|
raise SystemExit(0 if all(r['status']=='PASS' for r in results) else 1)
|