test-selector 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,14 @@
1
+ """test_selector - 覆盖率驱动的精准测试选择器(vllm_ascend / sglang / pytorch 统一架构)。
2
+
3
+ 公共逻辑集中在 test_selector/ 包(diff 解析、噪音过滤、覆盖率选择、CLI 等),
4
+ 仓库差异通过 test_selector.repos.RepoAdapter 注入,保证架构统一、差异按仓库归类。
5
+
6
+ 入口:
7
+ python -m test_selector --repo <vllm_ascend|sglang|pytorch> ...
8
+ """
9
+
10
+ from .repos import AVAILABLE_REPOS, RepoAdapter, get_adapter
11
+ from .test_selector import TestSelector
12
+
13
+ __all__ = ["RepoAdapter", "TestSelector", "get_adapter", "AVAILABLE_REPOS"]
14
+ __version__ = "1.0.0"
@@ -0,0 +1,6 @@
1
+ """python -m test_selector 入口。"""
2
+
3
+ from .cli import main
4
+
5
+ if __name__ == "__main__":
6
+ main()
@@ -0,0 +1,244 @@
1
+ """CodeChangeDetector - 代码变更检测。
2
+
3
+ 功能:
4
+ - 哈希比对扫描范围:整个 source_dir,相对路径基于 source_dir,
5
+ 之后由 TestSelector 的通用路径规范化(adapter.normalize_changed_path)统一剥离
6
+ PRODUCT_PREFIX 或 '{repo_name}/' 前缀
7
+ - diff 文件读取编码:utf-8-sig(兼容带 BOM)
8
+ - diff 前缀过滤:adapter.product_code_prefix
9
+ - 行级解析 / 变更场景排除:diff_parser 公共模块
10
+ """
11
+
12
+ import hashlib
13
+ import json
14
+ from pathlib import Path
15
+
16
+ from . import diff_parser
17
+ from .repos.base import RepoAdapter
18
+
19
+
20
+ class CodeChangeDetector:
21
+ """代码变更检测器"""
22
+
23
+ def __init__(self, source_dir: str, adapter: RepoAdapter):
24
+ """
25
+ Args:
26
+ source_dir: 源代码目录(哈希比对扫描根)
27
+ adapter: 仓库适配器(提供产品代码前缀与哈希扫描根)
28
+ """
29
+ self.source_dir = Path(source_dir)
30
+ self.adapter = adapter
31
+ self.file_hashes = {}
32
+
33
+ def compute_file_hash(self, filepath: str) -> str:
34
+ """计算文件 MD5 哈希"""
35
+ hasher = hashlib.md5()
36
+ try:
37
+ with open(filepath, "rb") as f:
38
+ hasher.update(f.read())
39
+ return hasher.hexdigest()
40
+ except Exception as e:
41
+ print(f" Warning: Error computing file hash: {filepath}: {e}")
42
+ return ""
43
+
44
+ def scan_source_files(self) -> dict[str, str]:
45
+ """扫描源文件,计算哈希(整个 source_dir,相对路径基于 source_dir)"""
46
+ self.file_hashes = {}
47
+ root = self.adapter.hash_scan_root(self.source_dir)
48
+ if not root.exists():
49
+ print(f" Warning: Source directory not found: {root}")
50
+ return self.file_hashes
51
+ for py_file in root.rglob("*.py"):
52
+ rel_path = py_file.relative_to(self.source_dir).as_posix()
53
+ self.file_hashes[rel_path] = self.compute_file_hash(str(py_file))
54
+ return self.file_hashes
55
+
56
+ def detect_changes_by_comparison(self) -> dict[str, set[int]]:
57
+ """通过文件哈希比对检测变更(变更文件返回全部行号)"""
58
+ changed_files = {}
59
+ current_hashes = {}
60
+
61
+ root = self.adapter.hash_scan_root(self.source_dir)
62
+ if not root.exists():
63
+ print(f" Warning: Source directory not found: {root}")
64
+ return changed_files
65
+
66
+ for py_file in root.rglob("*.py"):
67
+ rel_path = py_file.relative_to(self.source_dir).as_posix()
68
+ current_hashes[rel_path] = self.compute_file_hash(str(py_file))
69
+
70
+ baseline_path = self.source_dir / ".file_hashes.json"
71
+ if baseline_path.exists():
72
+ with open(baseline_path) as f:
73
+ old_hashes = json.load(f)
74
+
75
+ for rel_path, current_hash in current_hashes.items():
76
+ old_hash = old_hashes.get(rel_path, "")
77
+ if current_hash != old_hash:
78
+ # 文件有变更,返回全部行号(保守估计)
79
+ changed_files[rel_path] = set(range(1, 10000))
80
+ else:
81
+ changed_files = {rel_path: set(range(1, 10000)) for rel_path in current_hashes}
82
+ with open(baseline_path, "w") as f:
83
+ json.dump(current_hashes, f)
84
+
85
+ return changed_files
86
+
87
+ def parse_git_diff(
88
+ self,
89
+ diff_output: str,
90
+ base_content_getter=None,
91
+ ) -> dict[str, set[int]]:
92
+ """
93
+ 解析 git diff 输出,提取受影响的 base(变更前)行号。
94
+
95
+ Rules:
96
+ - Deleted lines: record the deleted base line itself, nothing more.
97
+ - Pure comment/docstring changes are excluded (needs base content):
98
+ a deletion group where every deleted line is a comment/docstring line
99
+ and the additions are comments or doc prose; an insertion inside a
100
+ docstring or consisting of comment lines only.
101
+ - Pure type annotation changes are excluded in every direction (needs
102
+ base content): inserted, deleted or replaced lines that are all
103
+ simple-name valueless annotations (``x: int``) in a scope where they
104
+ are provably inert - function bodies (never evaluated), plain
105
+ classes (no decorators, no TypedDict/Protocol/Enum/BaseModel/
106
+ NamedTuple base) or module level, unless the annotation expression
107
+ may have runtime side effects (calls, Annotated metadata) and the
108
+ file has no ``from __future__ import annotations``.
109
+ - First-time bindings are excluded for pure insertions (needs base
110
+ content): every added line is an assignment binding simple names
111
+ or self-attributes that occur nowhere in the base file, with inert
112
+ right-hand sides; self-attributes require a function scope whose
113
+ enclosing class has no custom __setattr__ (same-file ancestors only);
114
+ no meaningful line ends in a comma (such lines are call/signature
115
+ arguments, not statements); class-scope insertions follow dataclass
116
+ field-order rules (plain assigns are not fields, annotated fields
117
+ must land at or after the last existing field).
118
+ - Isolated blank-line deletion (neighbours not deleted): treated as a
119
+ one-line insertion -> candidate pair (line above, line below).
120
+ - Pure insertions and blank-deletion pairs are classified via ast of
121
+ the base file (needs base_content_getter):
122
+ 1. modifies an existing function -> record the line above only;
123
+ 2. sits between two function/class definitions -> excluded;
124
+ 3. inserted text belongs to a newly added def/class -> excluded;
125
+ 4. otherwise (module-level statements) -> record the line above only.
126
+ - Without base content (or non-parseable Python) pairs fall back to
127
+ counting both sides, bounded by the hunk's base range.
128
+
129
+ Args:
130
+ diff_output: diff 内容
131
+ base_content_getter: 可选回调(repo-relative-path -> str | None),
132
+ 返回 base 文件内容用于 ast 分类
133
+
134
+ Returns:
135
+ {filepath: {lineno, ...}} - 受影响的 base 行号集合,
136
+ .py 文件且位于 '{product_code_prefix}' 下,前缀已剥离。
137
+ 重命名与删除的文件被排除:它们通过 detect_renames() 在文件级匹配。
138
+ """
139
+ filter_prefix = self.adapter.product_code_prefix
140
+ renamed_files, deleted_files = self.detect_renames(diff_output)
141
+ renamed_new_paths = set(renamed_files.values())
142
+ deleted_paths = set(deleted_files)
143
+
144
+ files, pending, del_groups = diff_parser._parse_diff_base_lines(diff_output)
145
+
146
+ changed_files = {}
147
+ for path, lines in files.items():
148
+ # 重命名/删除的文件走文件级匹配,跳过行级解析
149
+ if path in renamed_new_paths or path in deleted_paths:
150
+ continue
151
+ # 过滤:仅保留产品代码(排除测试文件等)
152
+ if not path.startswith(filter_prefix):
153
+ continue
154
+ if not path.endswith(".py"):
155
+ continue
156
+ # 规范化路径:剥离 '{product_code_prefix}' 前缀
157
+ key = path[len(filter_prefix):]
158
+ changed_files[key] = lines
159
+ pairs = pending.get(path) or []
160
+ groups = del_groups.get(path) or []
161
+ if pairs or groups:
162
+ base_text = base_content_getter(path) if base_content_getter else None
163
+ diff_parser._classify_candidate_pairs(lines, pairs, groups, base_text, path)
164
+
165
+ # 丢弃最终没有受影响代码行的文件(如纯注释变更)
166
+ return {k: v for k, v in changed_files.items() if v}
167
+
168
+ def detect_renames(self, diff_output: str) -> tuple[dict[str, str], list[str]]:
169
+ """
170
+ 检测 git diff 输出中的重命名与删除文件(仅产品代码,under product_code_prefix)。
171
+ 两者处理方式相同:使用 base 路径进行文件级匹配,从行级解析中排除。
172
+
173
+ Args:
174
+ diff_output: diff 内容
175
+
176
+ Returns:
177
+ (rename_mapping, deleted_files)
178
+ - rename_mapping: {old_path: new_path}
179
+ - deleted_files: [path, ...](base 路径)
180
+ """
181
+ prefix = self.adapter.product_code_prefix
182
+ renames = {}
183
+ deleted = []
184
+ current_old_path = None
185
+ current_new_path = None
186
+ header_old_path = None
187
+
188
+ for raw_line in diff_output.split("\n"):
189
+ line = raw_line.rstrip("\r")
190
+
191
+ # 检测重命名标记
192
+ if line.startswith("rename from "):
193
+ current_old_path = line[12:].strip()
194
+ continue
195
+ if line.startswith("rename to "):
196
+ current_new_path = line[10:].strip()
197
+ # 同时拿到新旧路径时记录重命名
198
+ if current_old_path and current_new_path:
199
+ # 去除 a/ 或 b/ 前缀
200
+ old_path = current_old_path[2:] if current_old_path.startswith("a/") else current_old_path
201
+ new_path = current_new_path[2:] if current_new_path.startswith("b/") else current_new_path
202
+ # 仅记录产品代码重命名(under prefix)
203
+ if old_path.startswith(prefix):
204
+ renames[old_path] = new_path
205
+ current_old_path = None
206
+ current_new_path = None
207
+ continue
208
+
209
+ # 通过 '--- a/path' + '+++ /dev/null' 检测删除文件
210
+ if line.startswith("--- "):
211
+ header_old_path = line[4:].strip()
212
+ if header_old_path.startswith("a/"):
213
+ header_old_path = header_old_path[2:]
214
+ elif line.startswith("+++ "):
215
+ if line[4:].strip() == "/dev/null" and header_old_path and header_old_path.startswith(prefix):
216
+ deleted.append(header_old_path)
217
+ header_old_path = None
218
+
219
+ return renames, deleted
220
+
221
+ def parse_pr_diff_file(
222
+ self, diff_file_path: str, base_content_getter=None
223
+ ) -> tuple[dict[str, set[int]], dict[str, str], list[str]]:
224
+ """
225
+ 从 PR diff 文件解析变更行号、重命名与删除文件。
226
+
227
+ Args:
228
+ diff_file_path: diff 文件路径
229
+ base_content_getter: 可选回调(repo-relative-path -> str | None),
230
+ 返回 base 文件内容用于 ast 分类
231
+
232
+ Returns:
233
+ (changed_files_with_lines, rename_mapping, deleted_files)
234
+ """
235
+ try:
236
+ # 读取编码使用 utf-8-sig,兼容带 BOM 的 diff 文件
237
+ with open(diff_file_path, encoding="utf-8-sig") as f:
238
+ diff_content = f.read()
239
+ changed_files = self.parse_git_diff(diff_content, base_content_getter=base_content_getter)
240
+ renames, deleted_files = self.detect_renames(diff_content)
241
+ return changed_files, renames, deleted_files
242
+ except Exception as e:
243
+ print(f"Warning: Failed to read diff file: {e}")
244
+ return {}, {}, []
test_selector/cli.py ADDED
@@ -0,0 +1,334 @@
1
+ """统一 CLI 入口。
2
+
3
+ 功能:
4
+ - 路径解析/输出位置:相对路径基于仓库根目录,绝对路径保持原样
5
+ - CLI 参数:adapter 提供默认值,参数统一(--repo 选择仓库适配器)
6
+ - 粒度开关:--enable/--disable-line-match、--enable/--disable-function-match,disable 优先
7
+ - 全量测试触发:adapter.has_full_suite_changes(如 vllm 的 csrc 检查)
8
+ - 测试文件提取:pr_detector 公共模块(逐行解析 + adapter.is_test_file)
9
+ - PR 拉取:github / gitcode 公共模块
10
+
11
+ 用法:
12
+ python -m test_selector --repo vllm_ascend --github-pr owner/repo#123
13
+ python -m test_selector --repo pytorch --github-pr pytorch/pytorch#123 # 上游 pytorch/pytorch
14
+ python -m test_selector --repo torch_npu --gitcode-pr Ascend/pytorch#123 # Ascend/pytorch(torch_npu 本体,GitCode)
15
+ python -m test_selector --repo sglang --build-map --coverage-dir coverage
16
+ """
17
+
18
+ import argparse
19
+ from pathlib import Path
20
+
21
+ from . import github, gitcode, pr_detector
22
+ from .change_detector import CodeChangeDetector
23
+ from .coverage_selector import CoverageSelector
24
+ from .repos import AVAILABLE_REPOS, get_adapter
25
+ from .test_selector import TestSelector
26
+
27
+ #: 仓库根目录(test_selector 包的上级):相对路径基准 + 输出文件位置
28
+ BASE_DIR = Path(__file__).resolve().parent.parent
29
+
30
+
31
+ def _resolve_abs(base: Path, p: str) -> Path:
32
+ """相对路径基于 base 解析,绝对路径保持原样。"""
33
+ path = Path(p)
34
+ return path if path.is_absolute() else base / path
35
+
36
+
37
+ def build_parser(adapter, default_repo: str) -> argparse.ArgumentParser:
38
+ """构建命令行解析器,参数默认值由仓库适配器提供(cli_defaults)。"""
39
+ defaults = adapter.cli_defaults()
40
+ parser = argparse.ArgumentParser(
41
+ description="Coverage-based precision test selector (line, function, file granularity)"
42
+ )
43
+ parser.add_argument(
44
+ "--repo", "-r",
45
+ default=default_repo,
46
+ choices=list(AVAILABLE_REPOS),
47
+ help=f"Repository adapter to use (default: {default_repo})",
48
+ )
49
+ parser.add_argument("--github-pr", "-pr", help="GitHub PR, format: owner/repo#pr_number")
50
+ parser.add_argument("--gitcode-pr", help="GitCode PR, format: owner/repo#pr_number")
51
+ parser.add_argument(
52
+ "--source-dir", "-s", default=defaults["source_dir"], help=f"Source code directory (default: {defaults['source_dir']})"
53
+ )
54
+ parser.add_argument(
55
+ "--map-file", "-m", default=defaults["map_file"], help=f"Test case map file (default: {defaults['map_file']})"
56
+ )
57
+ parser.add_argument(
58
+ "--coverage-dir", "-c", default=defaults["coverage_dir"], help=f"Coverage data directory (default: {defaults['coverage_dir']})"
59
+ )
60
+ parser.add_argument("--build-map", "-b", action="store_true", help="Rebuild test case mapping")
61
+ parser.add_argument(
62
+ "--min-affected", "-a", type=int, default=defaults["min_affected"],
63
+ help=f"Minimum affected lines threshold (default: {defaults['min_affected']})",
64
+ )
65
+ parser.add_argument(
66
+ "--dedup",
67
+ action="store_true",
68
+ default=defaults["dedup"],
69
+ help="Enable deduplication (keep only one test for same covered lines, default off)",
70
+ )
71
+ parser.add_argument(
72
+ "--enable-line-match",
73
+ action="store_true",
74
+ default=defaults["enable_line_match"],
75
+ help="Enable line-level matching (default from adapter)",
76
+ )
77
+ parser.add_argument("--disable-line-match", action="store_true", help="Disable line-level matching")
78
+ parser.add_argument(
79
+ "--enable-function-match",
80
+ action="store_true",
81
+ default=defaults["enable_function_match"],
82
+ help="Enable function-level matching (default from adapter)",
83
+ )
84
+ parser.add_argument("--disable-function-match", action="store_true", help="Disable function-level matching")
85
+ parser.add_argument(
86
+ "--skip-imports",
87
+ action="store_true",
88
+ default=defaults["skip_imports"],
89
+ help="Skip import statement lines (only effective for function-level matching, default off)",
90
+ )
91
+ parser.add_argument(
92
+ "--new-tests-output",
93
+ help="Write the new test files extracted from the PR diff to this file (one per line, for the append-table workflow)",
94
+ )
95
+ parser.add_argument(
96
+ "--output", "-o",
97
+ default=None,
98
+ help="Output file path for the recommended test list (default: <package-parent>/recommended_pytest_paths.txt)",
99
+ )
100
+ return parser
101
+
102
+
103
+ def main(argv=None, default_repo: str = "vllm_ascend") -> None:
104
+ """统一 CLI 主入口。
105
+
106
+ Args:
107
+ argv: 命令行参数列表(None 时使用 sys.argv[1:])
108
+ default_repo: 默认仓库适配器(薄入口可注入,如 sglang 入口默认 'sglang')
109
+ """
110
+ # 第一阶段:仅解析 --repo 以确定仓库适配器(其余参数默认值依赖 adapter)
111
+ pre_parser = argparse.ArgumentParser(add_help=False)
112
+ pre_parser.add_argument("--repo", "-r", default=default_repo, choices=list(AVAILABLE_REPOS))
113
+ pre_args, _ = pre_parser.parse_known_args(argv)
114
+
115
+ adapter = get_adapter(pre_args.repo)
116
+
117
+ # 第二阶段:完整解析,默认值来自 adapter.cli_defaults()
118
+ args = build_parser(adapter, default_repo).parse_args(argv)
119
+
120
+ # 粒度开关:disable 优先
121
+ if args.disable_line_match:
122
+ args.enable_line_match = False
123
+ if args.disable_function_match:
124
+ args.enable_function_match = False
125
+
126
+ # PR 源互斥校验(gitcode 与 github 只能指定其一)
127
+ if args.github_pr and args.gitcode_pr:
128
+ print("Error: --github-pr and --gitcode-pr are mutually exclusive, please specify only one")
129
+ exit(1)
130
+
131
+ # 相对路径基于仓库根目录解析,绝对路径保持原样
132
+ coverage_dir = _resolve_abs(BASE_DIR, args.coverage_dir) if args.coverage_dir else None
133
+ source_dir = _resolve_abs(BASE_DIR, args.source_dir)
134
+ map_file = _resolve_abs(BASE_DIR, args.map_file)
135
+
136
+ # 1. Build or load test case mapping
137
+ selector = CoverageSelector(str(coverage_dir) if coverage_dir else None, str(source_dir), adapter)
138
+
139
+ if args.build_map or not map_file.exists():
140
+ # Coverage data dir is required only when building the map
141
+ if not coverage_dir:
142
+ print("Error: --coverage-dir is required when building the test case map (no map file found)")
143
+ exit(1)
144
+ print("\n=== Building Test Case Mapping ===")
145
+ selector.build_test_case_map()
146
+ selector.save_map(str(map_file))
147
+ else:
148
+ print("\n=== Loading Test Case Mapping ===")
149
+ selector.load_map(str(map_file))
150
+
151
+ # If only need to generate map file, exit directly
152
+ if args.build_map and not args.github_pr and not args.gitcode_pr:
153
+ print("\n=== Map file generated, done ===")
154
+ return
155
+
156
+ # 2. Parse code changes
157
+ print("\n=== Parsing Code Changes ===")
158
+ change_detector = CodeChangeDetector(str(source_dir), adapter)
159
+
160
+ diff_file = None
161
+ base_content_getter = None
162
+ changed_files_with_lines: dict[str, set[int]] = {}
163
+ if args.github_pr:
164
+ # Fetch changes from GitHub PR
165
+ diff_file, base_content_getter = github.fetch_pr_diff(args.github_pr)
166
+ elif args.gitcode_pr:
167
+ # Fetch changes from GitCode PR(拼接后的 diff 格式与 GitHub 一致,下游处理复用公共逻辑)
168
+ diff_file, base_content_getter = gitcode.fetch_pr_diff(args.gitcode_pr)
169
+ else:
170
+ # Get from file comparison (default)
171
+ change_detector.scan_source_files()
172
+ changed_files_with_lines = change_detector.detect_changes_by_comparison()
173
+ print(f"Detected {len(changed_files_with_lines)} changed files")
174
+
175
+ # ===== Action 1: Extract new/deleted test files & full-suite changes =====
176
+ has_full_suite = False
177
+ new_test_files: list[str] = []
178
+ deleted_test_files: list[str] = []
179
+ if diff_file:
180
+ # 读取编码使用 utf-8-sig,兼容带 BOM 的 diff 文件
181
+ with open(diff_file, encoding="utf-8-sig") as f:
182
+ diff_content = f.read()
183
+ new_test_files = pr_detector.get_test_files_from_pr_diff(diff_content, adapter)
184
+ deleted_test_files = pr_detector.get_deleted_test_files_from_pr(diff_content, adapter)
185
+ has_full_suite = pr_detector.has_full_suite_changes(diff_content, adapter)
186
+
187
+ # ===== Action 2: Detect Python product code changes -> Precision matching =====
188
+ selected: list[tuple[str, dict, int]] = []
189
+ expand_reason = ""
190
+
191
+ if has_full_suite:
192
+ # 全量触发变更(如 vllm 的 csrc 目录),由 adapter 判断
193
+ print("\n=== Full-Suite Changes Detected - Running Full Test Suite ===")
194
+ else:
195
+ renames: dict[str, str] = {}
196
+ deleted_files: list[str] = []
197
+ if diff_file:
198
+ changed_files_with_lines, renames, deleted_files = change_detector.parse_pr_diff_file(
199
+ diff_file, base_content_getter=base_content_getter
200
+ )
201
+ print(f"Parsed {len(changed_files_with_lines)} changed files:")
202
+ for file_path, line_set in changed_files_with_lines.items():
203
+ print(f" {adapter.repo_name}/{file_path}: {TestSelector._format_line_range(list(line_set))}")
204
+
205
+ # detect_renames already filters to product code prefix only
206
+ if renames:
207
+ print(f"\n=== Detected {len(renames)} Product Code Renamed File(s) - Using File-Level Matching ===")
208
+ for old_path, new_path in renames.items():
209
+ print(f" {old_path} -> {new_path}")
210
+
211
+ if deleted_files:
212
+ print(
213
+ f"\n=== Detected {len(deleted_files)} Product Code Deleted File(s) - Using File-Level Matching ==="
214
+ )
215
+ for path in deleted_files:
216
+ print(f" {path}")
217
+
218
+ if changed_files_with_lines or renames or deleted_files:
219
+ # Select test cases by precision matching
220
+ print("\n=== Selecting Affected Test Cases ===")
221
+ test_selector = TestSelector(selector.test_case_map, adapter)
222
+
223
+ # Renamed/deleted files are already excluded from changed_files by
224
+ # parse_git_diff; they are matched at file level below
225
+ normal_files = changed_files_with_lines
226
+
227
+ # Process normal files with precision matching
228
+ if normal_files:
229
+ selected, expand_reason = test_selector.select_tests(
230
+ normal_files,
231
+ min_affected_lines=args.min_affected,
232
+ source_dir=str(source_dir),
233
+ enable_line_match=args.enable_line_match,
234
+ enable_function_match=args.enable_function_match,
235
+ enable_file_match=False, # File-level matching reserved for renamed/deleted files only
236
+ enable_skip_imports=args.skip_imports,
237
+ enable_dedup=args.dedup,
238
+ )
239
+
240
+ # Process renamed/deleted files: file-level matching with the base path
241
+ file_level_paths = [(p, f"{p} -> {n}") for p, n in renames.items()]
242
+ file_level_paths += [(p, p) for p in deleted_files]
243
+ for path, label in file_level_paths:
244
+ fl_selected, fl_expand = test_selector.select_tests(
245
+ {path: set()},
246
+ min_affected_lines=args.min_affected,
247
+ source_dir=str(source_dir),
248
+ enable_line_match=False, # Disable line match for file-level matching
249
+ enable_function_match=False, # Disable function match for file-level matching
250
+ enable_file_match=True, # Enable file match for renamed/deleted files
251
+ enable_skip_imports=args.skip_imports,
252
+ enable_dedup=args.dedup,
253
+ )
254
+ selected.extend(fl_selected)
255
+ expand_reason += fl_expand
256
+ # Print file-level matched test cases (even when empty, for diagnosis)
257
+ print(f"\n=== File-Level Matched Tests for {label} ===")
258
+ if fl_selected:
259
+ for test_name, _, _ in fl_selected:
260
+ print(f" {test_name}")
261
+ else:
262
+ print(" (0 tests matched: no coverage data for this path in test_case_map)")
263
+
264
+ # Deduplicate
265
+ seen = set()
266
+ deduped = []
267
+ for item in selected:
268
+ if item[0] not in seen:
269
+ seen.add(item[0])
270
+ deduped.append(item)
271
+ selected = deduped
272
+
273
+ test_selector.print_selection(
274
+ selected, changed_files_with_lines, min_affected_lines=args.min_affected, expand_reason=expand_reason
275
+ )
276
+ else:
277
+ print("\n=== No product source code changes found ===")
278
+
279
+ # ===== Merge results =====
280
+ # Base set: full suite for full-suite changes, otherwise use precision results
281
+ if has_full_suite:
282
+ base_selected = [(test_name, {}, 0) for test_name in selector.test_case_map]
283
+ print(f"\n=== Full Test Suite: {len(base_selected)} tests ===")
284
+ else:
285
+ base_selected = selected
286
+
287
+ # Add new test files
288
+ existing_test_names = {s[0] for s in base_selected}
289
+ for test_name in new_test_files:
290
+ if test_name not in existing_test_names:
291
+ base_selected.append((test_name, {}, 0))
292
+ existing_test_names.add(test_name)
293
+
294
+ if new_test_files:
295
+ print(f"\n=== New Test Files Added: {len(new_test_files)} ===")
296
+ print(f" {new_test_files}")
297
+
298
+ # Remove deleted test files
299
+ if deleted_test_files:
300
+ print(f"\n=== Deleted Test Files Removed: {len(deleted_test_files)} ===")
301
+ print(f" {deleted_test_files}")
302
+ deleted_set = set(deleted_test_files)
303
+ base_selected = [
304
+ (name, detail, count)
305
+ for name, detail, count in base_selected
306
+ if name not in deleted_set and not any(name.startswith(d) for d in deleted_set)
307
+ ]
308
+
309
+ # ===== Output results =====
310
+ test_names = [s[0] for s in base_selected]
311
+ if test_names:
312
+ print(f"\n=== Recommended Test Cases ({len(test_names)} tests) ===")
313
+ print(test_names)
314
+ else:
315
+ print("\n=== No Test Cases Recommended ===")
316
+
317
+ # Always write output file (even if empty); --output wins, default is next to the repo root
318
+ output_file = Path(args.output) if args.output else BASE_DIR / "recommended_pytest_paths.txt"
319
+ with open(output_file, "w", encoding="utf-8") as f:
320
+ for test_name in test_names:
321
+ f.write(test_name + "\n")
322
+ print(f"\nResults saved to: {output_file}")
323
+
324
+ # Write new test files to a separate file when requested (append-table workflow)
325
+ if args.new_tests_output:
326
+ new_tests_path = _resolve_abs(BASE_DIR, args.new_tests_output)
327
+ with open(new_tests_path, "w", encoding="utf-8") as f:
328
+ for test_name in new_test_files:
329
+ f.write(test_name + "\n")
330
+ print(f"New test files ({len(new_test_files)}) saved to: {new_tests_path}")
331
+
332
+
333
+ if __name__ == "__main__":
334
+ main()