|
| 1 | +""" |
| 2 | +Shared test file detection utilities. |
| 3 | +Single source of truth for test file patterns across V2/V3 search. |
| 4 | +""" |
| 5 | +import re |
| 6 | +from typing import List |
| 7 | + |
| 8 | + |
| 9 | +# Regex patterns for test files (consolidated from CodeGraphRanker) |
| 10 | +TEST_PATTERNS = [ |
| 11 | + r'test[s]?[/_]', # test/, tests/, test_ |
| 12 | + r'[/_]test[s]?\.py$', # _test.py, _tests.py |
| 13 | + r'\.test\.[jt]sx?$', # .test.js, .test.ts |
| 14 | + r'\.spec\.[jt]sx?$', # .spec.js, .spec.ts |
| 15 | + r'__tests__', # __tests__/ |
| 16 | + r'conftest\.py$', # pytest config |
| 17 | + r'fixtures?[/_]', # fixtures/ |
| 18 | + r'mock[s]?[/_]', # mocks/ |
| 19 | +] |
| 20 | + |
| 21 | + |
| 22 | +def is_test_file(file_path: str) -> bool: |
| 23 | + """ |
| 24 | + Check if file is a test file using regex patterns. |
| 25 | + |
| 26 | + Args: |
| 27 | + file_path: Path to check (can be relative or absolute) |
| 28 | + |
| 29 | + Returns: |
| 30 | + True if file matches any test pattern |
| 31 | + """ |
| 32 | + if not file_path: |
| 33 | + return False |
| 34 | + file_path_lower = file_path.lower() |
| 35 | + for pattern in TEST_PATTERNS: |
| 36 | + if re.search(pattern, file_path_lower): |
| 37 | + return True |
| 38 | + return False |
| 39 | + |
| 40 | + |
| 41 | +def filter_test_files(results: List[dict], include_tests: bool = False) -> List[dict]: |
| 42 | + """ |
| 43 | + Filter test files from search results. |
| 44 | + |
| 45 | + Args: |
| 46 | + results: List of search result dicts with 'file_path' key |
| 47 | + include_tests: If True, keep test files; if False, filter them out |
| 48 | + |
| 49 | + Returns: |
| 50 | + Filtered results list |
| 51 | + """ |
| 52 | + if include_tests: |
| 53 | + return results |
| 54 | + return [r for r in results if not is_test_file(r.get("file_path", ""))] |
| 55 | + |
| 56 | + |
| 57 | +def has_test_file_in_top_n(results: List[dict], n: int = 3) -> bool: |
| 58 | + """ |
| 59 | + Check if any of the top N results are test files. |
| 60 | + Useful for benchmarking test pollution. |
| 61 | + |
| 62 | + Args: |
| 63 | + results: List of search result dicts |
| 64 | + n: Number of top results to check |
| 65 | + |
| 66 | + Returns: |
| 67 | + True if any top N result is a test file |
| 68 | + """ |
| 69 | + for r in results[:n]: |
| 70 | + if is_test_file(r.get("file_path", "")): |
| 71 | + return True |
| 72 | + return False |
0 commit comments