~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
chore: add pre-commit hooks for test and doc coverage (#2167)
LearningCircuitbcd40c7f7307
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yamlindex 435d5662d1..6940910218 100644--- a/.pre-commit-config.yaml+++ b/.pre-commit-config.yaml@@ -172,3 +172,26 @@ repos:files: \.(py|json)$description: "Ensure search engine module_path values use relative imports, notabsolute paths"+ - id: recommend-docs+ name: Documentation Reminder+ entry: .pre-commit-hooks/recommend-docs.py+ language: script+ pass_filenames: false+ always_run: true+ verbose: true+ description: "Gentle reminder to update docs when source files change"+ - id: recommend-tests+ name: Test Coverage Recommendation+ entry: .pre-commit-hooks/recommend-tests.py+ language: script+ pass_filenames: false+ always_run: true+ verbose: true+ description: "Direct recommendation to include tests when source files change"+ - id: require-tests+ name: Require Tests for Substantial Changes+ entry: .pre-commit-hooks/require-tests.py+ language: script+ pass_filenames: false+ always_run: true+ description: "Block commits with substantial new code but no tests"diff --git a/.pre-commit-hooks/_commit_analysis.py b/.pre-commit-hooks/_commit_analysis.pynew file mode 100644index 0000000000..79983b0473--- /dev/null+++ b/.pre-commit-hooks/_commit_analysis.py@@ -0,0 +1,201 @@+"""Shared utility module for pre-commit hooks analyzing staged files."""++import subprocess+from dataclasses import dataclass, field+from pathlib import PurePosixPath+++@dataclass+class StagedFileInfo:+ path: str+ added: int+ removed: int+ is_new: bool+ category: str+++@dataclass+class CommitAnalysis:+ source_files: list[StagedFileInfo] = field(default_factory=list)+ test_files: list[StagedFileInfo] = field(default_factory=list)+ doc_files: list[StagedFileInfo] = field(default_factory=list)++ @property+ def new_source_files(self):+ return [f for f in self.source_files if f.is_new]++ @property+ def total_source_added(self):+ return sum(f.added for f in self.source_files)++ @property+ def has_tests(self):+ return len(self.test_files) > 0++ @property+ def has_docs(self):+ return len(self.doc_files) > 0+++# Directories/patterns excluded from "source" classification+_EXCLUDED_DIRS = {+ "migrations",+ "alembic",+ "config",+ "settings",+ "scripts",+ ".pre-commit-hooks",+ "examples",+ "docs",+}++_EXCLUDED_BASENAMES = {"__init__.py", "conftest.py"}+++def _run_git(args):+ """Run a git command and return stdout lines.++ Returns empty list if git command fails (e.g., not in a git repo).+ """+ result = subprocess.run(+ ["git"] + args,+ capture_output=True,+ text=True,+ )+ if result.returncode != 0:+ return []+ return result.stdout.strip().splitlines() if result.stdout.strip() else []+++def _parse_numstat(lines):+ """Parse git diff --numstat output into {filepath: (added, removed)}."""+ stats = {}+ for line in lines:+ parts = line.split("\t")+ if len(parts) != 3:+ continue+ added_str, removed_str, filepath = parts+ # Binary files show '-' for counts+ added = int(added_str) if added_str != "-" else 0+ removed = int(removed_str) if removed_str != "-" else 0+ stats[filepath] = (added, removed)+ return stats+++def classify_file(path):+ """Classify a file path into a category string.++ Returns one of: source, test, doc, init, conftest, migration, config,+ hook, script, other+ """+ p = PurePosixPath(path)+ basename = p.name+ parts_set = set(p.parts)++ # Doc files+ if p.suffix == ".md":+ return "doc"++ # Non-Python files are "other"+ if p.suffix != ".py":+ return "other"++ # Specific basename exclusions+ if basename == "__init__.py":+ return "init"+ if basename == "conftest.py":+ return "conftest"++ # Test files: under tests/ or matching test_*.py / *_test.py+ if (+ "tests" in parts_set+ or basename.startswith("test_")+ or basename.endswith("_test.py")+ ):+ return "test"++ # Check excluded directory patterns+ for part in p.parts:+ if part.lower() in _EXCLUDED_DIRS:+ return _dir_to_category(part.lower())++ # Source files: under src/+ if len(p.parts) > 0 and p.parts[0] == "src":+ return "source"++ return "other"+++def _dir_to_category(dirname):+ """Map excluded directory names to categories."""+ mapping = {+ "migrations": "migration",+ "alembic": "migration",+ "config": "config",+ "settings": "config",+ "scripts": "script",+ ".pre-commit-hooks": "hook",+ "examples": "other",+ "docs": "doc",+ }+ return mapping.get(dirname, "other")+++def suggest_test_path(source_path):+ """Suggest a test file path for a given source file.++ Example: src/local_deep_research/web/api.py -> tests/web/test_api.py+ """+ p = PurePosixPath(source_path)+ parts = list(p.parts)++ # Strip leading src/ and package name (e.g., src/local_deep_research/)+ if parts and parts[0] == "src":+ parts = parts[1:]+ if parts and not parts[0].startswith("test"):+ parts = parts[1:] # Remove package name like local_deep_research++ # Build test path+ if parts:+ test_name = f"test_{parts[-1]}"+ test_parts = ["tests"] + parts[:-1] + [test_name]+ else:+ test_parts = ["tests", f"test_{p.name}"]++ return str(PurePosixPath(*test_parts))+++def analyze_commit():+ """Analyze staged files and return a CommitAnalysis."""+ # Get list of staged files with their status+ status_lines = _run_git(["diff", "--cached", "--name-status"])+ new_files = set()+ for line in status_lines:+ parts = line.split("\t")+ if len(parts) >= 2 and parts[0].startswith("A"):+ new_files.add(parts[-1])++ # Get line counts+ numstat_lines = _run_git(["diff", "--cached", "--numstat"])+ stats = _parse_numstat(numstat_lines)++ analysis = CommitAnalysis()++ for filepath, (added, removed) in stats.items():+ category = classify_file(filepath)+ info = StagedFileInfo(+ path=filepath,+ added=added,+ removed=removed,+ is_new=filepath in new_files,+ category=category,+ )++ if category == "source":+ analysis.source_files.append(info)+ elif category == "test":+ analysis.test_files.append(info)+ elif category == "doc":+ analysis.doc_files.append(info)++ return analysisdiff --git a/.pre-commit-hooks/recommend-docs.py b/.pre-commit-hooks/recommend-docs.pynew file mode 100755index 0000000000..8b0347c694--- /dev/null+++ b/.pre-commit-hooks/recommend-docs.py@@ -0,0 +1,54 @@+#!/usr/bin/env python3+"""Gentle reminder to update docs when source files change.++Always exits 0 (non-blocking). Prints a suggestion when source files+are staged without any documentation updates.+"""++import sys+from pathlib import Path++# Allow importing sibling module+sys.path.insert(0, str(Path(__file__).resolve().parent))++from _commit_analysis import analyze_commit+++def main():+ analysis = analyze_commit()++ # Silent exit: no source files staged+ if not analysis.source_files:+ return 0++ # Silent exit: docs already included+ if analysis.has_docs:+ return 0++ # Silent exit: trivial change (less than 10 added lines)+ if analysis.total_source_added < 10:+ return 0++ # Print gentle reminder+ print()+ print(" \033[36mDocumentation Reminder\033[0m")+ print(" " + "-" * 40)+ print(+ f" You're changing {len(analysis.source_files)} source file(s) "+ f"with {analysis.total_source_added} new lines"+ )+ print(" but no documentation (.md) files are staged.")+ print()+ print(" Changed source files:")+ for f in analysis.source_files:+ print(f" - {f.path} (+{f.added})")+ print()+ print(" Consider updating README.md or docs/ if this changes")+ print(" public behavior, configuration, or APIs.")+ print()++ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/.pre-commit-hooks/recommend-tests.py b/.pre-commit-hooks/recommend-tests.pynew file mode 100755index 0000000000..6b2a2a8a7f--- /dev/null+++ b/.pre-commit-hooks/recommend-tests.py@@ -0,0 +1,50 @@+#!/usr/bin/env python3+"""Direct recommendation to include tests when source files change.++Always exits 0 (non-blocking). Prints an assertive warning when source+files are staged without any test files.+"""++import sys+from pathlib import Path++# Allow importing sibling module+sys.path.insert(0, str(Path(__file__).resolve().parent))++from _commit_analysis import analyze_commit, suggest_test_path+++def main():+ analysis = analyze_commit()++ # Silent exit: no source files staged+ if not analysis.source_files:+ return 0++ # Silent exit: tests already included+ if analysis.has_tests:+ return 0++ # Print assertive warning+ print()+ print(" \033[33mTest Coverage Recommendation\033[0m")+ print(" " + "-" * 40)+ print(+ f" You're committing {len(analysis.source_files)} source file(s) "+ "with no test files."+ )+ print()+ print(" Source files and suggested tests:")+ for f in analysis.source_files:+ suggested = suggest_test_path(f.path)+ print(f" {f.path} (+{f.added} lines)")+ print(f" -> {suggested}")+ print()+ print(" Adding tests helps catch regressions and documents behavior.")+ print()++ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/.pre-commit-hooks/require-tests.py b/.pre-commit-hooks/require-tests.pynew file mode 100755index 0000000000..ff25c7820e--- /dev/null+++ b/.pre-commit-hooks/require-tests.py@@ -0,0 +1,74 @@+#!/usr/bin/env python3+"""Block commits with substantial new code but no tests.++Exits 1 (blocks commit) when zero test files are staged AND at least one of:+ - A new source file has >50 added lines (real new functionality)+ - >300 total new lines across source files (substantial change)++Otherwise exits 0 silently.+"""++import sys+from pathlib import Path++# Allow importing sibling module+sys.path.insert(0, str(Path(__file__).resolve().parent))++from _commit_analysis import analyze_commit, suggest_test_path++# Thresholds+NEW_FILE_LINE_THRESHOLD = 50+TOTAL_LINES_THRESHOLD = 300+++def main():+ analysis = analyze_commit()++ # Pass: no source files+ if not analysis.source_files:+ return 0++ # Pass: tests are included+ if analysis.has_tests:+ return 0++ # Check blocking conditions+ large_new_files = [+ f+ for f in analysis.new_source_files+ if f.added > NEW_FILE_LINE_THRESHOLD+ ]+ substantial_total = analysis.total_source_added > TOTAL_LINES_THRESHOLD++ if not large_new_files and not substantial_total:+ return 0++ # Block: print reason and suggestions+ print()+ print(" \033[31mTests Required\033[0m")+ print(" " + "=" * 40)++ if large_new_files:+ print()+ print(" New source files with significant code:")+ for f in large_new_files:+ suggested = suggest_test_path(f.path)+ print(f" {f.path} (+{f.added} lines)")+ print(f" -> {suggested}")++ if substantial_total:+ print()+ print(+ f" Total new source lines: {analysis.total_source_added} "+ f"(threshold: {TOTAL_LINES_THRESHOLD})"+ )++ print()+ print(" Please add tests before committing.")+ print()++ return 1+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tests/hooks/__init__.py b/tests/hooks/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/tests/hooks/test_commit_analysis.py b/tests/hooks/test_commit_analysis.pynew file mode 100644index 0000000000..9045aa0899--- /dev/null+++ b/tests/hooks/test_commit_analysis.py@@ -0,0 +1,449 @@+"""+Tests for the _commit_analysis pre-commit hook shared module.++Covers: classify_file, suggest_test_path, _parse_numstat,+CommitAnalysis dataclass, and analyze_commit (with mocked git).+"""++import sys+from pathlib import Path+from unittest.mock import patch+++# Add the pre-commit hooks directory to path+HOOKS_DIR = Path(__file__).parent.parent.parent / ".pre-commit-hooks"+sys.path.insert(0, str(HOOKS_DIR))++from _commit_analysis import ( # noqa: E402+ CommitAnalysis,+ StagedFileInfo,+ _parse_numstat,+ analyze_commit,+ classify_file,+ suggest_test_path,+)+++# =========================================================================+# classify_file tests+# =========================================================================+++class TestClassifyFile:+ """Tests for classify_file path classification."""++ # --- Source files ---++ def test_source_file_under_src(self):+ assert classify_file("src/local_deep_research/web/api.py") == "source"++ def test_source_file_deep_nesting(self):+ assert (+ classify_file(+ "src/local_deep_research/web_search_engines/engines/search_engine_google.py"+ )+ == "source"+ )++ def test_source_file_direct_under_src(self):+ assert classify_file("src/local_deep_research/main.py") == "source"++ # --- Test files ---++ def test_test_file_under_tests_dir(self):+ assert classify_file("tests/web/test_api.py") == "test"++ def test_test_file_by_prefix(self):+ assert classify_file("src/test_something.py") == "test"++ def test_test_file_by_suffix(self):+ assert classify_file("src/something_test.py") == "test"++ def test_test_file_nested_in_tests(self):+ assert classify_file("tests/security/test_url_validator.py") == "test"++ # --- Doc files ---++ def test_markdown_file(self):+ assert classify_file("README.md") == "doc"++ def test_markdown_file_in_docs(self):+ assert classify_file("docs/setup.md") == "doc"++ def test_markdown_file_nested(self):+ assert classify_file("src/local_deep_research/CHANGELOG.md") == "doc"++ # --- Excluded directories ---++ def test_migrations_dir(self):+ assert (+ classify_file("src/local_deep_research/migrations/001.py")+ == "migration"+ )++ def test_alembic_dir(self):+ assert classify_file("alembic/versions/abc123.py") == "migration"++ def test_config_dir(self):+ assert (+ classify_file("src/local_deep_research/config/settings.py")+ == "config"+ )++ def test_settings_dir(self):+ assert classify_file("settings/defaults.py") == "config"++ def test_scripts_dir(self):+ assert classify_file("scripts/dev/restart_server.py") == "script"++ def test_pre_commit_hooks_dir(self):+ assert classify_file(".pre-commit-hooks/check-env-vars.py") == "hook"++ def test_examples_dir(self):+ assert classify_file("examples/basic_usage.py") == "other"++ def test_docs_dir_python_file(self):+ assert classify_file("docs/conf.py") == "doc"++ # --- Special basenames ---++ def test_init_py(self):+ assert classify_file("src/local_deep_research/__init__.py") == "init"++ def test_conftest_py(self):+ assert classify_file("tests/conftest.py") == "conftest"++ # --- Non-Python files ---++ def test_json_file(self):+ assert (+ classify_file(+ "src/local_deep_research/defaults/default_settings.json"+ )+ == "other"+ )++ def test_yaml_file(self):+ assert classify_file(".pre-commit-config.yaml") == "other"++ def test_html_file(self):+ assert (+ classify_file("src/local_deep_research/web/templates/index.html")+ == "other"+ )++ def test_javascript_file(self):+ assert (+ classify_file("src/local_deep_research/web/static/app.js")+ == "other"+ )++ # --- Edge cases ---++ def test_top_level_python_file(self):+ assert classify_file("setup.py") == "other"++ def test_empty_path_components(self):+ """Files not under src/ and not matching other patterns are 'other'."""+ assert classify_file("lib/helper.py") == "other"++ def test_case_insensitive_excluded_dirs(self):+ """Excluded dirs match case-insensitively."""+ assert (+ classify_file("src/local_deep_research/Config/app.py") == "config"+ )++ def test_test_prefix_not_in_tests_dir(self):+ """test_*.py files are classified as test even outside tests/."""+ assert classify_file("src/test_helpers.py") == "test"+++# =========================================================================+# suggest_test_path tests+# =========================================================================+++class TestSuggestTestPath:+ """Tests for suggest_test_path path generation."""++ def test_standard_source_file(self):+ result = suggest_test_path("src/local_deep_research/web/api.py")+ assert result == "tests/web/test_api.py"++ def test_deeply_nested_source(self):+ result = suggest_test_path(+ "src/local_deep_research/web_search_engines/engines/search_engine_google.py"+ )+ assert (+ result+ == "tests/web_search_engines/engines/test_search_engine_google.py"+ )++ def test_direct_under_package(self):+ result = suggest_test_path("src/local_deep_research/main.py")+ assert result == "tests/test_main.py"++ def test_strips_src_prefix(self):+ """Should strip src/ prefix from path."""+ result = suggest_test_path("src/local_deep_research/utils.py")+ assert result.startswith("tests/")+ assert "src" not in result++ def test_adds_test_prefix_to_filename(self):+ """Should add test_ prefix to the filename."""+ result = suggest_test_path("src/local_deep_research/database/models.py")+ assert result.endswith("test_models.py")+++# =========================================================================+# _parse_numstat tests+# =========================================================================+++class TestParseNumstat:+ """Tests for _parse_numstat git output parsing."""++ def test_normal_output(self):+ lines = [+ "10\t5\tsrc/local_deep_research/web/api.py",+ "20\t3\ttests/web/test_api.py",+ ]+ result = _parse_numstat(lines)+ assert result == {+ "src/local_deep_research/web/api.py": (10, 5),+ "tests/web/test_api.py": (20, 3),+ }++ def test_binary_file(self):+ """Binary files show '-' for added/removed counts."""+ lines = ["-\t-\timages/logo.png"]+ result = _parse_numstat(lines)+ assert result == {"images/logo.png": (0, 0)}++ def test_empty_input(self):+ assert _parse_numstat([]) == {}++ def test_malformed_line_skipped(self):+ """Lines with wrong number of fields are skipped."""+ lines = [+ "10\t5\tsrc/api.py",+ "bad line",+ "20\t3\ttests/test_api.py",+ ]+ result = _parse_numstat(lines)+ assert len(result) == 2+ assert "src/api.py" in result+ assert "tests/test_api.py" in result++ def test_zero_counts(self):+ lines = ["0\t0\tempty_file.py"]+ result = _parse_numstat(lines)+ assert result == {"empty_file.py": (0, 0)}++ def test_large_counts(self):+ lines = ["9999\t8888\tbig_file.py"]+ result = _parse_numstat(lines)+ assert result == {"big_file.py": (9999, 8888)}++ def test_filepath_with_spaces(self):+ """Tabs separate fields, so filenames with spaces work."""+ lines = ["5\t2\tpath with spaces/file.py"]+ result = _parse_numstat(lines)+ assert "path with spaces/file.py" in result+++# =========================================================================+# CommitAnalysis dataclass tests+# =========================================================================+++class TestCommitAnalysis:+ """Tests for CommitAnalysis computed properties."""++ def _make_file(+ self,+ path="src/a.py",+ added=10,+ removed=0,+ is_new=False,+ category="source",+ ):+ return StagedFileInfo(+ path=path,+ added=added,+ removed=removed,+ is_new=is_new,+ category=category,+ )++ def test_empty_analysis(self):+ analysis = CommitAnalysis()+ assert analysis.total_source_added == 0+ assert analysis.has_tests is False+ assert analysis.has_docs is False+ assert analysis.new_source_files == []++ def test_total_source_added(self):+ analysis = CommitAnalysis(+ source_files=[+ self._make_file(added=10),+ self._make_file(added=20),+ ]+ )+ assert analysis.total_source_added == 30++ def test_has_tests_true(self):+ analysis = CommitAnalysis(test_files=[self._make_file(category="test")])+ assert analysis.has_tests is True++ def test_has_tests_false(self):+ analysis = CommitAnalysis(source_files=[self._make_file()])+ assert analysis.has_tests is False++ def test_has_docs_true(self):+ analysis = CommitAnalysis(doc_files=[self._make_file(category="doc")])+ assert analysis.has_docs is True++ def test_new_source_files(self):+ analysis = CommitAnalysis(+ source_files=[+ self._make_file(path="a.py", is_new=True),+ self._make_file(path="b.py", is_new=False),+ self._make_file(path="c.py", is_new=True),+ ]+ )+ new = analysis.new_source_files+ assert len(new) == 2+ assert all(f.is_new for f in new)+++# =========================================================================+# analyze_commit integration tests (with mocked git)+# =========================================================================+++class TestAnalyzeCommit:+ """Tests for analyze_commit with mocked git commands."""++ def _mock_run_git(self, name_status_lines, numstat_lines):+ """Create a mock for _run_git returning different output per command."""++ def side_effect(args):+ if "--name-status" in args:+ return name_status_lines+ if "--numstat" in args:+ return numstat_lines+ return []++ return side_effect++ def test_basic_source_and_test_commit(self):+ mock = self._mock_run_git(+ name_status_lines=[+ "M\tsrc/local_deep_research/web/api.py",+ "A\ttests/web/test_api.py",+ ],+ numstat_lines=[+ "15\t3\tsrc/local_deep_research/web/api.py",+ "50\t0\ttests/web/test_api.py",+ ],+ )++ with patch("_commit_analysis._run_git", side_effect=mock):+ analysis = analyze_commit()++ assert len(analysis.source_files) == 1+ assert len(analysis.test_files) == 1+ assert (+ analysis.source_files[0].path+ == "src/local_deep_research/web/api.py"+ )+ assert analysis.source_files[0].is_new is False+ assert analysis.test_files[0].is_new is True+ assert analysis.has_tests is True++ def test_new_file_detection(self):+ mock = self._mock_run_git(+ name_status_lines=["A\tsrc/local_deep_research/new_module.py"],+ numstat_lines=["100\t0\tsrc/local_deep_research/new_module.py"],+ )++ with patch("_commit_analysis._run_git", side_effect=mock):+ analysis = analyze_commit()++ assert len(analysis.source_files) == 1+ assert analysis.source_files[0].is_new is True+ assert analysis.source_files[0].added == 100++ def test_doc_files_classified(self):+ mock = self._mock_run_git(+ name_status_lines=["A\tREADME.md"],+ numstat_lines=["20\t0\tREADME.md"],+ )++ with patch("_commit_analysis._run_git", side_effect=mock):+ analysis = analyze_commit()++ assert len(analysis.doc_files) == 1+ assert analysis.has_docs is True++ def test_excluded_files_not_in_any_list(self):+ """Config, migration, and other excluded files don't appear in analysis lists."""+ mock = self._mock_run_git(+ name_status_lines=[+ "M\tsrc/local_deep_research/config/settings.py",+ "M\t.pre-commit-config.yaml",+ ],+ numstat_lines=[+ "5\t2\tsrc/local_deep_research/config/settings.py",+ "3\t1\t.pre-commit-config.yaml",+ ],+ )++ with patch("_commit_analysis._run_git", side_effect=mock):+ analysis = analyze_commit()++ assert len(analysis.source_files) == 0+ assert len(analysis.test_files) == 0+ assert len(analysis.doc_files) == 0++ def test_empty_commit(self):+ mock = self._mock_run_git(+ name_status_lines=[],+ numstat_lines=[],+ )++ with patch("_commit_analysis._run_git", side_effect=mock):+ analysis = analyze_commit()++ assert len(analysis.source_files) == 0+ assert analysis.total_source_added == 0+ assert analysis.has_tests is False+ assert analysis.has_docs is False++ def test_mixed_commit_with_all_types(self):+ mock = self._mock_run_git(+ name_status_lines=[+ "A\tsrc/local_deep_research/feature.py",+ "A\ttests/test_feature.py",+ "M\tREADME.md",+ "M\tscripts/dev/helper.py",+ ],+ numstat_lines=[+ "80\t0\tsrc/local_deep_research/feature.py",+ "40\t0\ttests/test_feature.py",+ "10\t5\tREADME.md",+ "3\t1\tscripts/dev/helper.py",+ ],+ )++ with patch("_commit_analysis._run_git", side_effect=mock):+ analysis = analyze_commit()++ assert len(analysis.source_files) == 1+ assert len(analysis.test_files) == 1+ assert len(analysis.doc_files) == 1+ assert analysis.total_source_added == 80+ assert analysis.has_tests is True+ assert analysis.has_docs is True+ assert analysis.source_files[0].is_new is True