forked from mtusi2026/mtusi2026lab5
62 lines
2.6 KiB
Python
62 lines
2.6 KiB
Python
"""Fast isolated tests for reconciliation safety; run in application image."""
|
|
import uuid
|
|
from datetime import datetime, timezone, timedelta
|
|
from .reconcile import reconcile
|
|
from .attachments import BUCKET
|
|
|
|
NOW = datetime.now(timezone.utc)
|
|
|
|
class FakeConn:
|
|
def __init__(self, rows): self.rows=rows
|
|
def __enter__(self): return self
|
|
def __exit__(self,*a): return False
|
|
def execute(self, sql, args=None):
|
|
self.sql=sql
|
|
self.args=args
|
|
return self
|
|
def fetchall(self): return self.rows
|
|
def fetchone(self):
|
|
key=self.args[0]
|
|
return {'id': 1} if any(key in (row['object_key'],row['backup_key']) for row in self.rows) else None
|
|
|
|
class FakeS3:
|
|
def __init__(self,objects): self.objects=objects
|
|
def get_paginator(self,op): return self
|
|
def paginate(self,**kwargs):
|
|
yield {'Contents':[{'Key':k,'LastModified':t} for k,t in self.objects.items()]}
|
|
def head_object(self,**kw):
|
|
if kw['Key'] not in self.objects:
|
|
from botocore.exceptions import ClientError
|
|
raise ClientError({'Error':{'Code':'404'}},'HeadObject')
|
|
def copy_object(self,**kw):
|
|
assert kw['CopySource']['Key'] in self.objects
|
|
self.objects[kw['Key']]=NOW
|
|
def delete_object(self,**kw):
|
|
self.objects.pop(kw['Key'],None)
|
|
|
|
|
|
def test():
|
|
i=str(uuid.uuid4())
|
|
primary=f'attachments/{i}/original';backup=f'recovery/{i}/original'
|
|
young=f'attachments/{uuid.uuid4()}/original'
|
|
old=f'attachments/{uuid.uuid4()}/original'
|
|
rows=[{'id':i,'object_key':primary,'backup_key':backup,'status':'ready'}]
|
|
fake=FakeS3({backup: NOW-timedelta(days=1),young:NOW-timedelta(seconds=10),old:NOW-timedelta(days=1)})
|
|
kwargs={'now':NOW,'client':fake,'connect':lambda:FakeConn(rows)}
|
|
first=reconcile(apply=False,**kwargs)
|
|
assert first['missing_primary_repairable']==[i]
|
|
assert old in first['orphan_keys'] and young in first['orphan_keys_young']
|
|
assert primary not in fake.objects and old in fake.objects, 'Dry run mutated objects'
|
|
second=reconcile(apply=True,**kwargs)
|
|
assert primary in fake.objects and old not in fake.objects and young in fake.objects
|
|
assert any(x['action']=='restore' for x in second['actions'])
|
|
third=reconcile(apply=True,**kwargs)
|
|
assert not third['actions'], 'Re-run unexpectedly mutated objects'
|
|
assert rows[0]['object_key']==primary, 'Metadata destroyed'
|
|
try: reconcile(apply=True, grace_seconds=0, **kwargs)
|
|
except ValueError: pass
|
|
else: raise AssertionError('Unsafe zero-grace apply accepted')
|
|
print('PASS: dry-run, orphan grace, recover primary from backup, apply idempotence')
|
|
|
|
if __name__ == '__main__': test()
|