PlotDirector/Tools/Deployment/test_retention.py

225 lines
13 KiB
Python

import contextlib
import importlib.util
import io
import json
import os
from pathlib import Path
import tempfile
import time
import unittest
from unittest.mock import patch
from types import SimpleNamespace
spec=importlib.util.spec_from_file_location('retention',Path(__file__).with_name('retention.py'))
r=importlib.util.module_from_spec(spec);spec.loader.exec_module(r)
class RetentionTests(unittest.TestCase):
def artifact(self,root,name='publish'):
p=Path(root)/name;p.mkdir(parents=True)
(p/'PlotLine.dll').write_bytes(b'MZcompiled fixture')
(p/'PlotLine.runtimeconfig.json').write_text('{"runtimeOptions":{}}')
(p/'PlotLine.deps.json').write_text('{"targets":{}}')
return p
def receipt(self,name,index,status='activated'):
return {'status':status,'completed_utc':f'2026-11-30T10:00:{index:02d}+00:00','release':{'id':name}}
def test_active_and_three_distinct_successful_previous(self):
receipts=[self.receipt(name,i) for i,name in enumerate(['active','old','one','two','two','three'])]
receipts.append(self.receipt('failed',9,'failed'))
keep,successful=r.success_keep(receipts,'active')
self.assertEqual(keep,{'active','one','two','three'});self.assertNotIn('failed',successful)
def test_receipt_order_uses_instants_not_offset_string_order(self):
receipts=[self.receipt('one',1),self.receipt('two',2),self.receipt('three',3),self.receipt('four',4)]
receipts[0]['completed_utc']='2026-11-30T11:00:00+02:00'
self.assertEqual(r.success_keep(receipts,'active')[0],{'active','two','three','four'})
def test_source_and_repository_preserved(self):
for name in ['source-tracked.patch','source.cs','.git','acceptance']:
with self.subTest(name=name),tempfile.TemporaryDirectory() as d:
p=self.artifact(d);(p/name).touch();self.assertIsNotNone(r.inspect(p))
def test_unknown_files_preserved(self):
with tempfile.TemporaryDirectory() as d:
p=self.artifact(d);(p/'important.txt').touch();self.assertIsNotNone(r.inspect(p))
def test_case_insensitive_nested_evidence_and_sources_preserved(self):
for name in ['Evidence','Acceptance','SOURCE.CS','CHANGES.PATCH','schema.sql','view.cshtml','Uploads']:
with self.subTest(name=name),tempfile.TemporaryDirectory() as d:
p=self.artifact(d);(p/'Data').mkdir();(p/'Data'/name).touch()
self.assertIsNotNone(r.inspect(p))
def test_named_restore_package_preserved(self):
with tempfile.TemporaryDirectory() as d:
self.assertIsNotNone(r.inspect(self.artifact(d,'restore-candidate')))
def test_symlinks_not_followed(self):
with tempfile.TemporaryDirectory() as d:
p=self.artifact(d);(p/'Data').symlink_to('/etc');self.assertIsNotNone(r.inspect(p))
def test_symlinked_ancestor_preserved(self):
with tempfile.TemporaryDirectory() as d:
root=Path(d);p=self.artifact(root/'physical');(root/'alias').symlink_to(root/'physical')
self.assertIsNotNone(r.inspect(root/'alias'/p.name))
def test_publish_under_a_repository_is_preserved(self):
with tempfile.TemporaryDirectory() as d:
root=Path(d);(root/'.git').mkdir();p=self.artifact(root/'output')
self.assertIsNotNone(r.inspect(p))
def test_bind_mount_root_or_descendant_preserved_even_on_same_device(self):
with tempfile.TemporaryDirectory() as d:
p=self.artifact(d);(p/'Data').mkdir()
for mounted in [p,p/'Data',p/'PlotLine.dll']:
with self.subTest(mounted=mounted),patch.object(r,'mount_points',return_value={mounted}),patch.object(r.os.path,'ismount',return_value=False):
self.assertEqual(r.inspect(p),'mount boundary')
def test_bound_runtime_links_allowed_but_retain_marker_wins(self):
with tempfile.TemporaryDirectory() as d:
root=Path(d);shared=root/'shared';shared.mkdir();(shared/'data').mkdir()
p=self.artifact(root);(p/'App_Data').symlink_to(shared/'data')
with patch.object(r,'ROOT',root):
self.assertIsNone(r.inspect(p,bound=True))
(p/'.retain').symlink_to(shared/'data');self.assertIsNotNone(r.inspect(p,bound=True))
def test_recent_and_abandoned_outputs_use_all_descendant_times(self):
with tempfile.TemporaryDirectory() as d:
p=self.artifact(d);self.assertIsNone(r.inspect(p));self.assertIsNotNone(r.inspect(p,age=172800))
old=time.time()-200000
for f in [p,*p.iterdir()]:os.utime(f,(old,old))
self.assertIsNone(r.inspect(p,age=172800))
(p/'PlotLine.dll').touch();self.assertIsNotNone(r.inspect(p,age=172800))
def test_corrupt_or_incomplete_snapshots_do_not_count_as_valid(self):
with tempfile.TemporaryDirectory() as d:
p=self.artifact(d);self.assertTrue(r.valid_snapshot(p))
(p/'PlotLine.runtimeconfig.json').write_text('broken')
self.assertFalse(r.valid_snapshot(p));self.assertIsNotNone(r.inspect(p))
def test_snapshot_metadata_links_and_special_files_are_not_read(self):
for kind in ('link','fifo'):
with self.subTest(kind=kind),tempfile.TemporaryDirectory() as d:
p=self.artifact(d);meta=p/'PlotLine.runtimeconfig.json';meta.unlink()
if kind=='link':meta.symlink_to(p/'PlotLine.deps.json')
else:os.mkfifo(meta)
self.assertFalse(r.valid_snapshot(p))
self.assertIsNotNone(r.inspect(p))
def test_references_protect_ancestors_and_descendants(self):
p=Path('/releases/active');self.assertTrue(r.overlaps(p,p/'app/PlotLine.dll'))
self.assertTrue(r.overlaps(p,p.parent));self.assertFalse(r.overlaps(p,Path('/releases/active-old')))
@contextlib.contextmanager
def layout(self):
with tempfile.TemporaryDirectory() as d,contextlib.ExitStack() as stack:
base=Path(d);root=base/'runtime';legacy=base/'legacy';temporary=base/'tmp';builds=base/'builds'
for p in [root/'releases',root/'deployment-receipts',legacy/'releases',temporary,builds]:p.mkdir(parents=True,exist_ok=True)
for i,name in enumerate(['old','one','two','three','active']):
self.artifact(root/'releases'/name,'app')
(root/'releases'/name/'manifest.json').write_text('{"preserve":"metadata"}')
(root/'deployment-receipts'/(name+'.json')).write_text(json.dumps(self.receipt(name,i)))
(root/'deployment.lock').touch()
(root/'current').symlink_to(root/'releases/active/app')
(root/'active-deployment.json').write_text('{"release":"active"}')
for key,value in dict(ROOT=root,LEGACY=legacy,TEMPORARY=temporary,BUILDS=builds).items():stack.enter_context(patch.object(r,key,value))
for key in ('read_pins','registered_worktrees','process_refs'):stack.enter_context(patch.object(r,key,return_value=[]))
stack.enter_context(patch.object(r,'preflight'))
stack.enter_context(patch.object(r.socket,'gethostname',return_value='atlas'))
stack.enter_context(patch.object(r.os,'geteuid',return_value=0))
yield root,legacy,temporary,builds
def test_plan_preserves_active_three_previous_unknown_and_pinned_releases(self):
with self.layout() as (root,legacy,*_):
unknown=self.artifact(root/'releases'/'no-receipt','app')
candidates,retained,active=r.plan()
self.assertEqual(candidates,[(str(root/'releases/old/app'),'manifest-release-payload')])
self.assertTrue(unknown.exists());self.assertEqual(active,root/'releases/active/app')
with patch.object(r,'read_pins',return_value=[root/'releases/old']):self.assertEqual(r.plan()[0],[])
def test_plan_rejects_marker_mismatch(self):
with self.layout() as (root,*_):
(root/'active-deployment.json').write_text('{"release":"different"}')
with self.assertRaises(RuntimeError):r.plan()
def test_three_newest_valid_snapshots_preserved_and_archived_links_never_pruned(self):
with self.layout() as (_,legacy,*_):
snapshots=[self.artifact(legacy,'current-before-'+str(i)) for i in range(5)]
for i,p in enumerate(snapshots):os.utime(p,(100+i,100+i))
(snapshots[-1]/'PlotLine.runtimeconfig.json').write_text('broken')
link=legacy/'current-before-archive';link.symlink_to(snapshots[2])
candidates,retained,_=r.plan()
self.assertNotIn(str(link),[p for p,c in candidates])
self.assertNotIn(str(snapshots[-1]),[p for p,c in candidates])
valid_kept=[p for p,reason in retained if reason=='three latest valid installation snapshots']
self.assertEqual(len(valid_kept),3)
def test_dry_run_changes_nothing_and_apply_only_removes_payload(self):
with self.layout() as (root,*_),contextlib.redirect_stdout(io.StringIO()):
app=root/'releases/old/app';r.run();self.assertTrue(app.exists())
r.run(apply=True);self.assertFalse(app.exists())
self.assertTrue((root/'releases/old/manifest.json').exists())
self.assertTrue((root/'releases/active/app').exists())
r.run(apply=True) # idempotent
def test_source_or_pin_added_after_plan_is_preserved(self):
for kind in ('source','pin','process','mount'):
with self.subTest(kind=kind),self.layout() as (root,*_),contextlib.redirect_stdout(io.StringIO()):
original=r.plan
app=root/'releases/old/app'
def changed():
result=original()
if kind=='source':(app/'source.patch').write_text('keep')
elif kind=='pin':(app.parent/'.retain').touch()
elif kind=='process':r.process_refs.return_value=[app/'PlotLine.dll']
elif kind=='mount':r.mount_points=lambda:{app}
return result
# Keep mount patches scoped independently of the other fixture cases.
with patch.object(r,'mount_points',wraps=r.mount_points),patch.object(r,'plan',side_effect=changed):r.run(apply=True)
self.assertTrue(app.exists())
def test_scope_refuses_production_or_substituted_paths(self):
with self.layout() as (root,legacy,tmp,builds):
self.assertFalse(r.candidate_scope(Path('/srv/plotdirector/releases/old/app'),'manifest-release-payload'))
self.assertFalse(r.candidate_scope(root/'current','legacy-release'))
self.assertFalse(r.candidate_scope(tmp/'unrelated','temporary-publish'))
self.assertTrue(r.candidate_scope(builds/'known','build-package'))
def test_substituted_parent_cannot_redirect_removal(self):
with tempfile.TemporaryDirectory() as d:
base=Path(d);parent=base/'parent';app=self.artifact(parent);outside=self.artifact(base/'outside')
original=r.directory_fd
@contextlib.contextmanager
def substituted(path):
parent.rename(base/'saved');parent.symlink_to(outside.parent)
with original(path) as fd:yield fd
with patch.object(r,'directory_fd',substituted),self.assertRaises(OSError):r.remove_candidate(app)
self.assertTrue(outside.exists());self.assertTrue((base/'saved'/app.name).exists())
def test_pin_configuration_rejects_untrusted_ownership_and_relative_paths(self):
with tempfile.TemporaryDirectory() as d:
p=Path(d)/'pins.json';p.write_text('{"paths":["relative"]}')
# Root trust is checked before the content is used, independently of tests' uid.
with patch.object(r,'PINS',p),self.assertRaises(RuntimeError):r.read_pins()
trusted=SimpleNamespace(st_uid=0,st_mode=0o100600)
with patch.object(r,'PINS',p),patch.object(Path,'lstat',return_value=trusted),patch.object(Path,'is_symlink',return_value=False):
with self.assertRaisesRegex(RuntimeError,'exact absolute'):r.read_pins()
p.write_text('{"paths":["/srv/tmp/protected"]}')
self.assertIn(Path('/srv/tmp/protected'),r.read_pins())
def test_git_worktrees_use_fixed_isolated_metadata_reader(self):
trusted=SimpleNamespace(st_uid=0,st_mode=0o100644)
with patch.object(Path,'lstat',return_value=trusted),patch.object(Path,'is_symlink',return_value=False),patch.object(r.subprocess,'check_output',return_value='worktree /input\0HEAD hash\0\0worktree /srv/tmp/keep me\0') as command:
self.assertEqual(r.registered_worktrees(),[r.REPOSITORY,Path('/srv/tmp/keep me')])
args=command.call_args.args[0]
self.assertEqual(args[:3],['/usr/bin/python3','-I','-c'])
self.assertIn("'worktree','list','--porcelain','-z'",args[3])
def test_other_host_or_non_root_refused_before_planning(self):
for host,uid in [('web1',0),('atlas',1000)]:
with patch.object(r.socket,'gethostname',return_value=host),patch.object(r.os,'geteuid',return_value=uid),patch.object(r,'plan') as plan:
with self.assertRaises(RuntimeError):r.run(True)
plan.assert_not_called()
if __name__=='__main__':unittest.main()