"""Deletion guards exercised against a small independent Git repository.""" import contextlib import io import json from pathlib import Path import shutil import subprocess import tempfile import unittest from unittest.mock import patch import os from tools.workspace import reachability as r # 临时仓库夹具不继承调用方的 Git 环境:带着 GIT_DIR 跑,init/commit 会落到调用方的仓库 for _k in ('GIT_DIR', 'GIT_WORK_TREE', 'GIT_INDEX_FILE', 'GIT_COMMON_DIR', 'GIT_OBJECT_DIRECTORY'): os.environ.pop(_k, None) class ReachabilityTests(unittest.TestCase): def setUp(self): self.temp = tempfile.TemporaryDirectory() self.addCleanup(self.temp.cleanup) self.root = Path(self.temp.name) subprocess.run(['git', 'init', '-q', str(self.root)], check=True) files = {'np/__init__.py': '', 'np/main.py': 'def run():\n from . import x\n', 'np/x.py': 'from pathlib import Path\nPath("shared.json").write_text("{}")\n', 'np/reader.py': 'from pathlib import Path\nPath("shared.json").read_text()\n', 'tests/test_x.py': 'from np import x\ndef test_x():\n assert x\n', 'tests/test_mixed.py': 'from np import x, reader\ndef test_x():\n assert x\n import np.main\ndef test_reader():\n assert reader\n', 'np/hash.py': 'import hashlib\nfrom pathlib import Path\nhashlib.sha256(Path("np/x.py").read_bytes())\n'} for f, source in files.items(): self.write(f, source) self.write('tools/workspace/entrypoints.json', json.dumps({'schema': 1, 'modules': ['np.main', 'np.reader'], 'files': ['np/hash.py']})) self.keep([]) def write(self, f, text): p = self.root / f p.parent.mkdir(parents=True, exist_ok=True) p.write_text(text) def keep(self, patterns): self.write('tools/workspace/keep.json', json.dumps({'schema': 1, 'keep': [dict(pattern=p, cluster='keep', reason='fixture', ask='-') for p in patterns]})) def test_tests_for_takes_callers_tests(self): self.write('np/lib.py', 'def f():\n return 1\n\n\ndef g():\n return 2\n') self.write('np/use.py', 'from .lib import f\ndef h():\n return f()\n') self.write('np/other.py', 'def k():\n return 3\n') for name, source in [('f', 'from np.lib import f\nf()\n'), ('use', 'from np.use import h\nh()\n'), ('g', 'from np.lib import g\ng()\n'), ('other', 'from np.other import k\nk()\n')]: self.write(f'tests/test_{name}.py', source) subprocess.run(['git', '-C', str(self.root), 'add', '-A'], check=True) subprocess.run(['git', '-C', str(self.root), '-c', 'user.name=t', '-c', 'user.email=t@t', 'commit', '-qm', 'x'], check=True) self.write('np/lib.py', 'def f():\n return 10\n\n\ndef g():\n return 2\n') rc, out = self.run_command('tests-for', '--base', 'HEAD') self.assertEqual((rc, out['changed'], out['callers']), (0, ['np.lib.f'], ['np.use.h'])) self.assertEqual(out['tests'], ['tests/test_f.py', 'tests/test_use.py']) # g、k 不调 f,它们的测试不跑 def run_command(self, command, *args): output = io.StringIO() with contextlib.redirect_stdout(output), contextlib.redirect_stderr(output): rc = r.main([command, *args, '--root', str(self.root), '--json']) return rc, json.loads(output.getvalue()) def test_check_and_function_import(self): rc, data = self.run_command('check') self.assertEqual(rc, 0) self.assertEqual(data['reachable'], 5) self.assertIn('np.x', r.Repository(self.root).reach) def test_export_without_git_walks_files(self): shutil.rmtree(self.root / '.git') rc, data = self.run_command('check') self.assertEqual(rc, 0) self.assertEqual(data['reachable'], 5) self.assertEqual(self.run_command('paths', 'np.x')[0], 1) def test_git_and_export_share_controlled_enumeration_and_prune_data(self): for rel in ('assets/bulk/bad.py', 'runs/bad.py', 'np/node_modules/bad.py'): self.write(rel, 'not valid Python!') self.write('np/ignored.py', '') self.write('.gitignore', 'np/ignored.py\n') real_scandir = os.scandir def guarded(path): self.assertNotIn(Path(path), {self.root / 'assets/bulk', self.root / 'runs', self.root / 'np/node_modules'}) return real_scandir(path) with patch('os.scandir', side_effect=guarded): before = r.Repository(self.root).files self.assertIn('np/ignored.py', before) self.assertNotIn('runs/bad.py', before) # Keep .git intact: absence can be simulated without removing any # repository contents while using the same source tree. git = self.root / '.git' git.rename(self.root / '.git-hidden') try: self.assertEqual(r.Repository(self.root).files, before) finally: (self.root / '.git-hidden').rename(git) def test_unreachable_fails_then_keep_passes(self): self.write('np/orphan.py', '') rc, data = self.run_command('check') self.assertEqual(rc, 1) self.assertEqual(data['missing'], ['np.orphan']) self.keep(['np.orphan']) self.assertEqual(self.run_command('check')[0], 0) def test_stale_keep_fails(self): self.keep(['np.absent']) rc, data = self.run_command('check') self.assertEqual(rc, 1) self.assertEqual(data['stale'], ['np.absent']) def test_closure_importers_mixed_units_and_coverage(self): rc, data = self.run_command('closure', 'np.x') self.assertEqual(rc, 1) self.assertIn(('np/main.py', 2), [(x['file'], x['line']) for x in data['importers']]) mixed = next(x for x in data['tests'] if x['category'] == 'mixed') self.assertEqual([x['name'] for x in mixed['affected']], ['test_x']) self.assertEqual(data['lost'], [dict(module='np.main', before=1, after=0)]) self.assertIn('all', [x['category'] for x in data['tests']]) self.assertEqual(self.run_command('closure', 'np.hash')[0], 0) def test_paths_hash_and_no_match_control(self): rc, data = self.run_command('paths', 'np.x') self.assertEqual(rc, 1) self.assertTrue(any(x.startswith('np/hash.py:3:') for x in data['hits'])) self.write('tools/evaluation/unused.py', '') self.assertEqual(self.run_command('paths', 'tools.evaluation.unused')[0], 0) def test_products_write_read_and_direction(self): rc, data = self.run_command('products', 'np.x') self.assertEqual(rc, 1) self.assertEqual(data['pairs'], [['shared.json', 'np/x.py:2', 'np/reader.py:2']]) self.assertEqual(self.run_command('products', 'np.reader')[0], 0) def test_product_paths_keep_directories_and_normalize_equivalent_paths(self): self.write('np/x.py', 'from pathlib import Path\nPath("left/data.json").write_text("{}")\n') self.write('np/reader.py', 'from pathlib import Path\nPath("right/data.json").read_text()\n') self.assertEqual(self.run_command('products', 'np.x')[0], 0) self.write('np/reader.py', 'from pathlib import Path\n(Path("left") / "sub/../data.json").read_text()\n') rc, data = self.run_command('products', 'np.x') self.assertEqual(rc, 1) self.assertEqual(data['pairs'][0][0], 'left/data.json') def test_branch_loop_with_and_try_bindings_reach_later_writes(self): sources = ( 'if condition:\n path = Path("out/data.json")\nelse:\n path = Path("out/./data.json")\n', 'path = Path("old.json")\nfor folder in ["out"]:\n path = Path(folder) / "data.json"\n', 'with Path("source.txt").open() as handle:\n path = Path("out/data.json")\n', 'path = Path("old.json")\ntry:\n path = Path("out/data.json")\nexcept OSError:\n path = Path("else.json")\n', 'try:\n path = Path("old.json")\nfinally:\n path = Path("out/data.json")\n', ) self.write('np/reader.py', 'from pathlib import Path\nPath("out/data.json").read_text()\n') for source in sources: with self.subTest(source=source): self.write('np/x.py', 'from pathlib import Path\n' + source + 'path.write_text("{}")\n') rc, data = self.run_command('products', 'np.x') self.assertEqual(rc, 1, data) self.assertIn('out/data.json', [row[0] for row in data['pairs']]) self.write('np/x.py', 'from pathlib import Path\npath = Path("outer.json")\n' 'def helper():\n path = Path("out/data.json")\npath.write_text("{}")\n') self.assertEqual(self.run_command('products', 'np.x')[0], 0) def test_with_suffix_replaces_instead_of_retaining_old_suffix(self): self.write('np/x.py', 'from pathlib import Path\nPath("out/data.json").with_suffix(".npz").write_bytes(b"")\n') self.write('np/reader.py', 'from pathlib import Path\nPath("out/data.json").read_text()\n') self.assertEqual(self.run_command('products', 'np.x')[0], 0) self.write('np/reader.py', 'from pathlib import Path\nPath("out/data.npz").read_bytes()\n') rc, data = self.run_command('products', 'np.x') self.assertEqual(rc, 1) self.assertEqual([row[0] for row in data['pairs']], ['out/data.npz']) def test_unknown_or_invalid_suffix_and_partial_branches_block_deletion(self): for source in ('path = Path("out/data.json").with_suffix(dynamic())\n', 'path = Path("out/data.json").with_suffix("npz")\n', 'if condition:\n path = Path("out/data.json")\n', 'path = Path("out/data.json") if condition else dynamic()\n'): with self.subTest(source=source): self.write('np/x.py', 'from pathlib import Path\n' + source + 'path.write_text("{}")\n') rc, data = self.run_command('products', 'np.x') self.assertEqual(rc, 1, data) self.assertEqual(len(data['unresolved_writes']), 1, data) def test_dynamic_alias_relative_and_parent(self): self.write('np/main.py', 'import importlib\nimportlib.import_module("np.x")\n__import__("np.reader")\n') self.assertEqual(self.run_command('check')[0], 0) self.write('np/main.py', 'import x\nimport np.reader\n') self.assertEqual(self.run_command('check')[0], 0) def baseline(self, *names): self.write(r.BASELINE, '名\t档\t理由\t清理步骤\n' + ''.join(f'{n}\tzero\tfixture\t-\n' for n in names)) def test_check_dead_new_baseline_stale(self): self.baseline() rc, data = self.run_command('check-dead') self.assertEqual((rc, data['new']), (1, ['np/main.py:1 np.main.run zero'])) self.baseline('np.main.run') self.assertEqual(self.run_command('check-dead')[0], 0) self.write('np/main.py', 'from . import x\n') rc, data = self.run_command('check-dead') self.assertEqual((rc, data['stale']), (1, ['np.main.run'])) def test_check_dead_base_only_shrinks(self): self.baseline('np.main.run') git = ['git', '-C', str(self.root), '-c', 'user.name=t', '-c', 'user.email=t@t'] subprocess.run(git + ['add', '-A'], check=True) subprocess.run(git + ['commit', '-qm', 'base'], check=True) self.write('np/main.py', 'def run():\n from . import x\ndef extra():\n pass\n') self.baseline('np.main.run', 'np.main.extra') rc, data = self.run_command('check-dead', '--base', 'HEAD') self.assertEqual((rc, data['new'], data['added']), (1, [], ['np.main.extra'])) self.assertEqual(self.run_command('check-dead', '--base', 'HEAD~0^{tree}')[0], 2) def test_check_dead_base_without_baseline_is_first_introduction(self): git = ['git', '-C', str(self.root), '-c', 'user.name=t', '-c', 'user.email=t@t'] subprocess.run(git + ['add', '-A'], check=True) subprocess.run(git + ['commit', '-qm', 'before baseline'], check=True) self.baseline('np.main.run') rc, data = self.run_command('check-dead', '--base', 'HEAD') self.assertEqual((rc, data['added']), (0, [])) self.assertEqual(self.run_command('check-dead', '--base', 'no-such-rev')[0], 2) def test_registered_plugins_and_framework_callbacks_are_used(self): self.write('np/main.py', 'def run():\n from . import x, reg, parse\nrun()\n') self.write('np/reg.py', 'import importlib\nfrom pathlib import Path\ndef method(name):\n return lambda f: f\n' 'for p in Path(__file__).parent.glob("plug_*.py"):\n importlib.import_module("np." + p.stem)\n') self.write('np/plug_a.py', 'from .reg import method\n@method("a")\ndef a():\n pass\n') self.write('np/parse.py', 'from html.parser import HTMLParser\nclass P(HTMLParser):\n def handle_data(self, data):\n pass\n def unused(self):\n pass\nP()\n') self.assertEqual(self.run_command('check')[0], 0) rows = {x['name']: x['bucket'] for x in self.run_command('functions')[1]['rows']} self.assertEqual([rows['np.plug_a.a'], rows['np.parse.P.handle_data'], rows['np.parse.P.unused']], ['used-live', 'used-live', 'zero']) def test_invalid_selection_and_parse_fail_closed(self): self.assertEqual(self.run_command('closure', 'np.absent')[0], 2) self.write('np/x.py', 'this is not python!') self.assertEqual(self.run_command('check')[0], 2) class RepositoryTests(unittest.TestCase): def test_repository(self): with contextlib.redirect_stdout(io.StringIO()): self.assertEqual(r.main(['check']), 0) self.assertEqual(r.main(['check-dead']), 0) if __name__ == '__main__': unittest.main()