~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
added pytest-mock to dev dependencies, tests get/set
ScottVR877a1c71000e
diff --git a/pdm.lock b/pdm.lockindex 9f0d026d48..15dc278a88 100644--- a/pdm.lock+++ b/pdm.lock@@ -5,7 +5,7 @@groups = ["default", "dev"]strategy = ["inherit_metadata"]lock_version = "4.5.0"-content_hash = "sha256:cabfc4a2a630702180a8c62762cc34221b2d65824c021b3420794ea7d5048684"+content_hash = "sha256:c1c44fe161278b7000b789d082a9e1d37817d7598d1df5d775c02782d422c2f3"[[metadata.targets]]requires_python = ">=3.10"@@ -1526,6 +1526,17 @@ files = [{file = "importlib_resources-6.5.2.tar.gz", hash = "sha256:185f87adef5bcc288449d98fb4fba07cea78bc036455dd44c5fc4a2fe78fed2c"},]+[[package]]+name = "iniconfig"+version = "2.1.0"+requires_python = ">=3.8"+summary = "brain-dead simple config-ini parsing"+groups = ["dev"]+files = [+ {file = "iniconfig-2.1.0-py3-none-any.whl", hash = "sha256:9deba5723312380e77435581c6bf4935c94cbfab9b1ed33ef8d238ea168eb760"},+ {file = "iniconfig-2.1.0.tar.gz", hash = "sha256:3abbd2e30b36733fee78f9c7f7308f2d0050e88f0087fd25c2645f63c773e1c7"},+]+[[package]]name = "ipykernel"version = "6.29.5"@@ -3504,6 +3515,17 @@ files = [{file = "plotly-6.1.0.tar.gz", hash = "sha256:f13f497ccc2d97f06f771a30b27fab0cbd220f2975865f4ecbc75057135521de"},]+[[package]]+name = "pluggy"+version = "1.6.0"+requires_python = ">=3.9"+summary = "plugin and hook calling mechanisms for python"+groups = ["dev"]+files = [+ {file = "pluggy-1.6.0-py3-none-any.whl", hash = "sha256:e920276dd6813095e9377c0bc5566d94c932c33b27a3e3945d8389c374dd4746"},+ {file = "pluggy-1.6.0.tar.gz", hash = "sha256:7dcc130b76258d33b90f61b658791dede3486c3e6bfb003ee5c9bfb396dd22f3"},+]+[[package]]name = "pre-commit"version = "4.2.0"@@ -3921,6 +3943,39 @@ files = [{file = "pypdfium2-4.30.1.tar.gz", hash = "sha256:5f5c7c6d03598e107d974f66b220a49436aceb191da34cda5f692be098a814ce"},]+[[package]]+name = "pytest"+version = "8.3.5"+requires_python = ">=3.8"+summary = "pytest: simple powerful testing with Python"+groups = ["dev"]+dependencies = [+ "colorama; sys_platform == \"win32\"",+ "exceptiongroup>=1.0.0rc8; python_version < \"3.11\"",+ "iniconfig",+ "packaging",+ "pluggy<2,>=1.5",+ "tomli>=1; python_version < \"3.11\"",+]+files = [+ {file = "pytest-8.3.5-py3-none-any.whl", hash = "sha256:c69214aa47deac29fad6c2a4f590b9c4a9fdb16a403176fe154b79c0b4d4d820"},+ {file = "pytest-8.3.5.tar.gz", hash = "sha256:f4efe70cc14e511565ac476b57c279e12a855b11f48f212af1080ef2263d3845"},+]++[[package]]+name = "pytest-mock"+version = "3.14.0"+requires_python = ">=3.8"+summary = "Thin-wrapper around the mock package for easier use with pytest"+groups = ["dev"]+dependencies = [+ "pytest>=6.2.5",+]+files = [+ {file = "pytest-mock-3.14.0.tar.gz", hash = "sha256:2719255a1efeceadbc056d6bf3df3d1c5015530fb40cf347c0f9afac88410bd0"},+ {file = "pytest_mock-3.14.0-py3-none-any.whl", hash = "sha256:0b72c38033392a5f4621342fe11e9219ac11ec9d375f8e2a0c164539e0d70f6f"},+]+[[package]]name = "python-dateutil"version = "2.9.0.post0"diff --git a/pyproject.toml b/pyproject.tomlindex ae3ba42c30..ce50339ddb 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -99,4 +99,5 @@ dev = ["cookiecutter>=2.6.0","pandas>=2.2.3","optuna>=4.3.0",+ "pytest-mock>=3.14.0",]diff --git a/run_tests.py b/run_tests.pynew file mode 100644index 0000000000..d5459a0f70--- /dev/null+++ b/run_tests.py@@ -0,0 +1,47 @@+#!/usr/bin/env python3+"""+Run tests for Local Deep Research.++This script runs pytest with appropriate configuration for the project.+"""++import os+import subprocess+import sys+from pathlib import Path+++def main():+ """Run the test suite with appropriate settings."""+ # Get the project root directory+ project_root = Path(__file__).parent.absolute()++ # Ensure PYTHONPATH includes the project root for proper imports+ os.environ["PYTHONPATH"] = str(project_root)++ # Configure pytest arguments+ pytest_args = [+ "pytest", # Call pytest+ "--verbose", # Verbose output+ "--color=yes", # Force colored output+ "--cov=src", # Measure coverage for src directory+ "--cov-report=term", # Report coverage in terminal+ "--cov-report=html:coverage_html", # Also generate HTML report+ "--cov-config=.coveragerc", # Use the coverage configuration file+ ]++ # Add any command line arguments passed to this script+ pytest_args.extend(sys.argv[1:])++ # Print the command being run+ print(f"Running: {' '.join(pytest_args)}")++ # Run pytest and capture the return code+ result = subprocess.run(pytest_args)++ # Return the pytest exit code+ return result.returncode+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tests/TESTING_PROPOSAL.md b/tests/TESTING_PROPOSAL.mdnew file mode 100644index 0000000000..8e1f1413e3--- /dev/null+++ b/tests/TESTING_PROPOSAL.md@@ -0,0 +1,294 @@+# Local Deep Research - Test Suite++This directory contains the test suite for the Local Deep Research project. The tests are organized into unit tests, integration tests, and search engine-specific tests.++## Tests Structure++```+tests/+├── conftest.py # Common test fixtures+├── run_tests.py # Test runner with coverage reporting+├── README.md # Test documentation+├── unit/ # Unit tests+│ ├── test_citation.py # Tests for citation handling+│ ├── test_config.py # Tests for configuration management+│ ├── test_report.py # Tests for report generation+│ └── test_search_system.py # Tests for search system+├── integration/ # Integration tests+│ └── test_db_ops.py # Database operation tests (placeholder)+└── search_engines/ # Search engine specific tests+ └── test_wikipedia.py # Wikipedia search engine tests+```+## Current Coverage++| Component | Coverage | Notes |+|-----------|----------|-------|+| Citation Handler | High | Comprehensive tests for all methods |+| Search System | High | Tests strategy selection and core functionality |+| Report Generator | High | Tests structure determination and report formatting |+| Configuration | High | Tests loading, env vars, and defaults |+| Wikipedia Search | High | Tests API interaction and result processing |+| Database Operations | Low | Database tests outlined but need implementation |+| Other Search Engines | Low | Only Wikipedia has tests so far |+| Web Interface | None | Web interface tests not yet implemented |++## Initial Test Files Created 2025/04/13++1. **test_citation.py**: Tests the citation handler functionality, including document creation from search results, source formatting, and citation analysis.++2. **test_search_system.py**: Tests the advanced search system, including strategy selection, callback handling, and search execution.++3. **test_report_generator.py**: Tests report generation, including structure determination, content research, and final formatting.++4. **test_config.py**: Tests configuration loading, environment variable overrides, and default settings creation.++5. **test_wikipedia.py**: Tests the Wikipedia search engine, including API interaction, error handling, and result processing.++6. **conftest.py**: Provides common fixtures used across different test files, including mock LLMs, search engines, and database connections.++## Running the Test Suite++### Prerequisites++Before running the tests, ensure you have the required test dependencies:++```bash+pip install pytest pytest-cov+```++### Using the Test Runner++The easiest way to run tests is to use the provided `run_tests.py` script:++The included `run_tests.py` script provides an easy way to run the tests with coverage reporting:++```bash+# Run all tests with coverage reporting+python run_tests.py++# Generate HTML coverage report+python run_tests.py --html++# Run specific test file or directory+python run_tests.py --path tests/unit/test_citation.py+```+++### Using pytest Directly++You can also run the tests using pytest directly:++```bash+# Run all tests+pytest tests/++# Run with coverage+pytest --cov=local_deep_research tests/++# Run specific test file+pytest tests/unit/test_citation.py++# Run with verbose output+pytest -v tests/+```++## Adding New Tests++When adding new tests:++1. Follow the existing structure and naming conventions+2. Place tests in the appropriate directory:+ - `unit/` for isolated component tests+ - `integration/` for tests that involve multiple components+ - `search_engines/` for search engine specific tests+3. Use fixtures from `conftest.py` when possible+4. Follow the naming convention: `test_*.py` for test files and `test_*` for test functions+5. Make sure to add appropriate mocks for external dependencies+6. Include docstrings explaining what each test verifies++## Test Coverage++To generate a coverage report:++```+pytest --cov=local_deep_research [--cov-report=html] tests/+```++After generating an HTML report, open `htmlcov/index.html` in your browser to view the detailed coverage information.++## Continuous Integration++It is important that:+- Tests run on each pull request+- Coverage reports are generated+- Test failures block merges to main branches++For full release readiness:++1. **GitHub Actions Workflow**: Set up automated testing on push/PR+2. **Coverage Requirements**: Enforce minimum coverage percentages (suggest 80%)+3. **Branch Protection**: Require passing tests before merging+4. **Dependency Checking**: Add automated vulnerability scanning++## Troubleshooting++If you encounter issues with the test suite:++1. Ensure all dependencies are installed+2. Check that you're running from the project root directory+3. Verify that test fixtures are properly set up+4. For tests requiring environment variables, make sure they're properly defined++## Mocking Strategy++Many tests rely on mocked dependencies to avoid external API calls or complex setups. Key points:++1. External API calls are always mocked+2. Database connections use in-memory SQLite or temporary files+3. File operations use temporary directories+4. LLM interactions are mocked with predefined responses++## Adding to Test Coverage++Priority areas for additional test coverage:++1. Integration tests for web interface+2. Additional search engine tests+3. Performance tests for long-running operations+4. Edge case handling in report generation+5. Error recovery scenarios++### ADD'L:++This should be a solid foundation for ensuring the reliability of Local Deep Research.+While there are still gaps to address, the core functionality is covered and this provides patterns for extending coverage to other areas.++I recommend continuing to expand the test suite, particularly for database operations, web interfaces, and additional search engines, to achieve comprehensive coverage before final release.The two files currently in the tests/ directory are more like utility scripts than software tests.++I propose LDR make use of the all-but-standard (technically unittest is in the python standard lib) `pytest` for a structured testing framework.++As I said in the chat, LDR has 0% "code coverage".++Since there is already much code and no test harness, I propose a strategy (this is off the cuff; discord on my phone and laptop typing this out right now so you'll all have something to read when you get online.)++# Areas to test, loosely in an order++## core++- searching implementation+- report generation+- citations+- LLM integrations++## conf+- loading+- validation+- env+- defaults++## search+- each+- search+- engine+- needs+- tests+- oh, and tests for filtering too++## web interface+- API endpoints+- frontend functionality++## DB+- CRUD+- and we'll use the migration test that exists now if that's what it does. I only glanced.++# Test implementation++Would look something like this:+```+tests/+├── conftest.py # Shared pytest fixtures+├── unit/ # Unit tests+│ ├── test_citation.py # Test citation handling+│ ├── test_config.py # Test configuration loading+│ ├── test_llm.py # Test LLM integration+│ ├── test_report.py # Test report generation+│ └── test_search.py # Test search functionality+├── integration/ # Integration tests+│ ├── test_db_ops.py # Test database operations+...+```++# Example++This is what a pytest test looks like:++``` python+import pytest+from unittest.mock import MagicMock, patch+import sys+from pathlib import Path++# Handle import paths for testing+sys.path.append(str(Path(__file__).parent.parent.parent))+from local_deep_research.citation_handler import CitationHandler+from langchain_core.documents import Document+++def citation_handler():+ """Create a citation handler with a mocked LLM for testing."""+ mock_llm = MagicMock()+ mock_llm.invoke.return_value = MagicMock(content="Mocked analysis with citation [1]")+ return CitationHandler(mock_llm)+++def sample_search_results():+ """Sample search results for testing."""+ return [+ {+ "title": "Test Result 1",+ "link": "https://example.com/1",+ "snippet": "This is the first test result snippet."+ },+ {+ "title": "Test Result 2",+ "link": "https://example.com/2",+ "full_content": "This is the full content of the second test result."+ }+ ]+++def test_create_documents_empty(citation_handler):+ """Test document creation with empty search results."""+ documents = citation_handler._create_documents([])+ assert len(documents) == 0+++def test_create_documents_string(citation_handler):+ """Test document creation with string input (error case)."""+ documents = citation_handler._create_documents("not a list")+ assert len(documents) == 0+++def test_create_documents(citation_handler, sample_search_results):+ """Test document creation with valid search results."""+ documents = citation_handler._create_documents(sample_search_results)++ # Check if the correct number of documents was created+ assert len(documents) == 2++ # Check first document+ assert documents[0].metadata["title"] == "Test Result 1"+ assert documents[0].metadata["source"] == "https://example.com/1"+ assert documents[0].metadata["index"] == 1+ assert documents[0].page_content == "This is the first test result snippet."++ # Check second document - should use full_content instead of snippet+...+```++There would be files like this for all the areas I mentioned and others.++## Else?\ No newline at end of filediff --git a/tests/test_settings_manager.py b/tests/test_settings_manager.pyindex 6895fd4249..f187e3eb13 100644--- a/tests/test_settings_manager.py+++ b/tests/test_settings_manager.py@@ -2,11 +2,12 @@ import osimport pytestimport sysfrom pathlib import Path+from sqlalchemy.exc import SQLAlchemyError# Add the src directory to the path before importing project modulessys.path.append(str(Path(__file__).parent.parent))-from src.local_deep_research.web.services.settings_manager import check_env_setting+from src.local_deep_research.web.services.settings_manager import check_env_setting, SettingsManager, Setting, SettingTypedef test_check_env_setting_exists(monkeypatch):monkeypatch.setenv("LDR_APP_VERSION", "1.0.0")@@ -16,4 +17,82 @@ def test_check_env_setting_not_exists():# Ensure the environment variable is not setif "LDR_APP_VERSION" in os.environ:del os.environ["LDR_APP_VERSION"]- assert check_env_setting("app.version") is None\ No newline at end of file+ assert check_env_setting("app.version") is None++def test_get_setting_from_db(mocker):+ mock_db_session = mocker.MagicMock()+ mock_setting = Setting(key="app.version", value="1.0.0")+ # Use mocker.patch.object for patching instances+ mock_db_session.query.return_value.filter.return_value.all.return_value = [mock_setting]++ settings_manager = SettingsManager(db_session=mock_db_session)+ assert settings_manager.get_setting("app.version") == "1.0.0"++def test_get_setting_from_env(mocker, monkeypatch):+ mock_db_session = mocker.MagicMock()+ monkeypatch.setenv("LDR_APP_VERSION", "2.0.0")+ # Ensure DB query returns nothing to verify environment variable is prioritized+ mock_db_session.query.return_value.filter.return_value.all.return_value = []++ settings_manager = SettingsManager(db_session=mock_db_session)+ assert settings_manager.get_setting("app.version") == "2.0.0"++def test_get_setting_default(mocker):+ mock_db_session = mocker.MagicMock()+ # Ensure DB query returns nothing+ mock_db_session.query.return_value.filter.return_value.all.return_value = []++ settings_manager = SettingsManager(db_session=mock_db_session)+ assert settings_manager.get_setting("non_existent_setting", default="default_value") == "default_value"++# The mocker fixture is automatically available+def test_set_setting_update_existing(mocker):+ mock_db_session = mocker.MagicMock()+ mock_setting = Setting(key="app.version", value="1.0.0")+ mock_db_session.query.return_value.filter.return_value.first.return_value = mock_setting+ mocker.patch("src.local_deep_research.web.services.settings_manager.func.now") # Patching the func.now call++ settings_manager = SettingsManager(db_session=mock_db_session)+ result = settings_manager.set_setting("app.version", "2.0.0")++ assert result is True+ assert mock_setting.value == "2.0.0"+ mock_db_session.commit.assert_called_once()+ mock_db_session.rollback.assert_not_called()++def test_set_setting_create_new(mocker):+ mock_db_session = mocker.MagicMock()+ mock_db_session.query.return_value.filter.return_value.first.return_value = None+ mocker.patch("src.local_deep_research.web.services.settings_manager.func.now") # Patching the func.now call++ settings_manager = SettingsManager(db_session=mock_db_session)+ result = settings_manager.set_setting("new.setting", "new_value")++ assert result is True+ mock_db_session.add.assert_called_once()+ new_setting = mock_db_session.add.call_args[0][0]+ assert isinstance(new_setting, Setting)+ assert new_setting.key == "new.setting"+ assert new_setting.value == "new_value"+ assert new_setting.type == SettingType.APP # Assuming 'app' type for this key+ mock_db_session.commit.assert_called_once()+ mock_db_session.rollback.assert_not_called()++def test_set_setting_db_error(mocker):+ mock_db_session = mocker.MagicMock()+ # Set the side_effect to an instance of SQLAlchemyError+ mock_db_session.query.return_value.filter.return_value.first.side_effect = SQLAlchemyError("Simulated DB Error")++ # Mock the logger to check if error is logged+ mock_logger = mocker.patch("src.local_deep_research.web.services.settings_manager.logger")++ settings_manager = SettingsManager(db_session=mock_db_session)+ result = settings_manager.set_setting("app.version", "2.0.0")++ # Assert that the method returned False+ assert result is False++ mock_db_session.rollback.assert_called_once()+ mock_db_session.commit.assert_not_called()+ mock_logger.error.assert_called_once()+ # mock_logger.error.assert_called_once_with("Error setting value for app.version: Simulated DB Error")