File size: 6,462 Bytes
7ff74f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
import importlib.util
import json
from pathlib import Path
import os
import subprocess
import tempfile
import unittest

# 临时仓库夹具不继承调用方的 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)

SPEC = importlib.util.spec_from_file_location('doc_refs', Path(__file__).with_name('doc_refs.py'))
d = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(d)


class DocRefsTests(unittest.TestCase):
    def check(self, files, counts=None):
        with tempfile.TemporaryDirectory() as tmp:
            root = Path(tmp)
            for name, text in files.items():
                (root / name).parent.mkdir(parents=True, exist_ok=True)
                (root / name).write_text(text)
            subprocess.run(['git', 'init', '-q', tmp], check=True)
            subprocess.run(['git', 'add', '.'], cwd=tmp, check=True)
            return [(doc, ref, why) for doc, _, ref, why in d.check(root, counts or {})]

    def test_named_refs_resolve_by_basename_and_line_refs_are_rejected(self):
        bad = self.check({
            'pkg/interp.py': 'def certificate():\n    pass\nclass Reply:\n    pass\n',
            'pkg/README.md': '见 `interp.py(certificate、Reply等)` 和 interp.py(文件尾);外部 render.py(Foo)不核。\n'
                                '旧写法 `interp.py:12`;`interp.py(gone)`。\n',
            'docs/archive/old.md': 'interp.py:3\n'})
        self.assertEqual([(ref, why[:6]) for _, ref, why in bad],
                         [('interp.py:12', '写成了“文件'), ('interp.py(gone)', '名字在文件里')])

    def test_comments_paths_and_counts(self):
        bad = self.check({
            'pkg/interp.py': '"""见 pkg/gone.py 和 runs/X/a.md;共 114 版、12 母题。"""\n# 旧写法 interp.py:3,3 版是局部举例\nx = "pkg/gone.py:9 不是注释"\n',
            'pkg/README.md': '在册 113 版、125 个版本;pkg/interp.py 在。\n旧目录 62 个问法;p2 35/112 版、128×128 版本。\n共 53 个问法。\n现行出题 113 版、现行 102 版、候选 3 版,局部举例也不行。\n'},
            counts={'版': {125, 113, 102, 12}, '母题': {12}, '问法': {54}, '版·现行': {102}, '版·在册': {113}, '版·候选': {12}})
        self.assertEqual([(doc, ref) for doc, ref, _ in bad], [('pkg/README.md', '53问法'), ('pkg/README.md', '113版'), ('pkg/README.md', '3版'), ('pkg/interp.py', 'pkg/gone.py'), ('pkg/interp.py', '114版'), ('pkg/interp.py', 'interp.py:3')])

    def test_named_refs_require_bindings_in_the_correct_scope(self):
        source = ('# gone\nTEXT = "phantom"\nVALUE: int = 1\nLEFT, RIGHT = 2, 3\n'
                  'import os as operating\nfrom pathlib import Path as Location\n'
                  'def real(): pass\nclass C: pass\nclass D:\n    def method(self): pass\n')
        for name in ('gone', 'phantom', 'C.method', 'missing.D.method', 'wrong.real'):
            with self.subTest(name=name):
                bad = self.check({'code.py': source, 'README.md': f'code.py({name})\n'})
                self.assertEqual(len(bad), 1, bad)
                self.assertIn('名字在文件里找不到', bad[0][2])
        names = 'real、C、D.method、VALUE、LEFT、RIGHT、operating、Location、code.real、code.D.method'
        self.assertEqual(self.check({'code.py': source,
                                     'README.md': f'code.py({names})\n'}), [])

    def test_unqualified_refs_accept_bindings_in_any_scope(self):
        source = ('class C:\n    def method(self):\n        self.layout = {}\n'
                  '        local = 1\n        def nested(): pass\n')
        self.assertEqual(self.check({'code.py': source, 'README.md':
            'code.py(method、layout、local、nested、C.method)\n'}), [])

    def test_repository_counts_come_from_catalog(self):
        root = Path(__file__).resolve().parents[2]
        counts = d.catalog_counts(root)
        self.assertEqual(set(counts), {'母题', '子题', '问法', '版', '版·现行', '版·暂停', '版·在册', '版·候选', '版·退役登记'})
        self.assertTrue(all(counts.values()))
        archive = json.loads((root / 'spec/questions/archive/retired-20261109.json').read_text())
        self.assertEqual(counts['版·退役登记'], {len(archive['versions'])})

    def test_retired_registration_uses_archive_scope(self):
        counts = d.catalog_counts(Path(__file__).resolve().parents[2])
        self.assertEqual(self.check({'README.md': '另有退役登记 74 版。\n'}, counts), [])
        # 72 is a valid catalog count, but it omits a record kept only in the archive.
        bad = self.check({'README.md': '另有退役登记 72 版。\n'}, counts)
        self.assertEqual([(doc, ref) for doc, ref, _ in bad], [('README.md', '72版')])

    def test_ambiguous_names_require_an_explicit_path(self):
        bad = self.check({'a/code.py': 'def first(): pass\n',
                          'b/code.py': 'def second(): pass\n',
                          'README.md': 'code.py(first)\na/code.py(first)\n'})
        self.assertEqual(len(bad), 1)
        self.assertIn('不唯一', bad[0][2])

    def test_other_languages_are_explicitly_unsupported(self):
        bad = self.check({'script.sh': 'run() { true; }\n', 'README.md': 'script.sh(run)\n'})
        self.assertEqual(len(bad), 1)
        self.assertIn('不支持', bad[0][2])

    def test_resolution_rejects_escapes_and_deduplicates_internal_symlinks(self):
        with tempfile.TemporaryDirectory() as tmp:
            root = Path(tmp) / 'repo'
            root.mkdir()
            outside = Path(tmp) / 'outside.py'
            outside.write_text('def secret(): pass\n')
            (root / 'alias.py').symlink_to(outside)
            for written in ('../outside.py', str(outside), 'alias.py'):
                with self.subTest(written=written), self.assertRaises(ValueError):
                    d.resolve(root, ['alias.py'], 'README.md', written)
            (root / 'code.py').write_text('VALUE = 1\n')
            (root / 'internal.py').symlink_to('code.py')
            self.assertEqual(d.resolve(root, ['code.py', 'internal.py'], 'README.md', 'internal.py'),
                             [(root / 'code.py').resolve()])


if __name__ == '__main__':
    unittest.main()