~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
test: add 12 coverage tests for start_research route (#2862)
LearningCircuitb71276b938ce
diff --git a/tests/benchmarks/datasets/test_xbench_deepsearch_coverage.py b/tests/benchmarks/datasets/test_xbench_deepsearch_coverage.pyindex e478c936cb..5dc339806e 100644--- a/tests/benchmarks/datasets/test_xbench_deepsearch_coverage.py+++ b/tests/benchmarks/datasets/test_xbench_deepsearch_coverage.py@@ -32,6 +32,8 @@ def _make_dataset(**kwargs):class TestXorDecrypt:+ # test_xor_decrypt_roundtrip is defined first so it runs first and warms up+ # the expensive module import within the 60-second pytest-timeout window.def test_xor_decrypt_roundtrip(self):from local_deep_research.benchmarks.datasets.xbench_deepsearch import (XBenchDeepSearchDataset,@@ -43,6 +45,19 @@ class TestXorDecrypt:decrypted = XBenchDeepSearchDataset.xor_decrypt(encrypted, key)assert decrypted == plaintext+ def test_xor_decrypt_basic(self):+ """Pure XOR decrypt: a key XOR'd twice returns the original data."""+ from local_deep_research.benchmarks.datasets.xbench_deepsearch import (+ XBenchDeepSearchDataset,+ )++ plaintext = b"Hello, World!"+ key = "secret"+ encrypted = XBenchDeepSearchDataset.xor_decrypt(plaintext, key)+ # XOR is its own inverse+ decrypted = XBenchDeepSearchDataset.xor_decrypt(encrypted, key)+ assert decrypted == plaintext+def test_xor_decrypt_empty_data(self):from local_deep_research.benchmarks.datasets.xbench_deepsearch import (XBenchDeepSearchDataset,@@ -51,6 +66,20 @@ class TestXorDecrypt:result = XBenchDeepSearchDataset.xor_decrypt(b"", "key")assert result == b""+ def test_xor_decrypt_key_wraps_around(self):+ """Key shorter than data: key bytes repeat (modulo)."""+ from local_deep_research.benchmarks.datasets.xbench_deepsearch import (+ XBenchDeepSearchDataset,+ )++ data = b"ABCDEF"+ key = "AB" # 2 bytes, data is 6 bytes – wraps 3 times+ result = XBenchDeepSearchDataset.xor_decrypt(data, key)+ assert len(result) == 6+ key_bytes = key.encode("utf-8")+ expected = bytes(data[i] ^ key_bytes[i % 2] for i in range(6))+ assert result == expected+# ---------------------------------------------------------------------------# Dataset metadata@@ -69,14 +98,38 @@ class TestDatasetInfo:assert "description" in infoassert "url" in info+ def test_get_dataset_info(self):+ """get_dataset_info returns a dict with all expected keys and correct id."""+ from local_deep_research.benchmarks.datasets.xbench_deepsearch import (+ XBenchDeepSearchDataset,+ )++ info = XBenchDeepSearchDataset.get_dataset_info()+ assert isinstance(info, dict)+ for key in ("id", "name", "description", "url"):+ assert key in info, f"Missing key: {key}"+ assert info["id"] == "xbench_deepsearch"+ assert "xbench" in info["url"].lower() or "DeepSearch" in info["url"]+def test_get_default_dataset_path(self):+ """get_default_dataset_path returns a non-empty string."""from local_deep_research.benchmarks.datasets.xbench_deepsearch import (XBenchDeepSearchDataset,)path = XBenchDeepSearchDataset.get_default_dataset_path()+ assert isinstance(path, str)+ assert len(path) > 0assert "xbench" in path.lower() or "DeepSearch" in path+ def test_get_default_dataset_path_is_huggingface_identifier(self):+ from local_deep_research.benchmarks.datasets.xbench_deepsearch import (+ XBenchDeepSearchDataset,+ )++ path = XBenchDeepSearchDataset.get_default_dataset_path()+ assert "/" in path+# ---------------------------------------------------------------------------# process_example@@ -92,6 +145,24 @@ class TestProcessExample:assert result["expected_iterations"] == 4assert "evaluation_criteria" in result+ def test_process_example(self):+ """process_example adds requires_deep_search, expected_iterations, evaluation_criteria."""+ ds = _make_dataset()+ example = {+ "id": "q42",+ "problem": "Who invented calculus?",+ "answer": "Newton and Leibniz",+ "canary": "somekey",+ }+ result = ds.process_example(example)+ assert result["requires_deep_search"] is True+ assert result["expected_iterations"] == 4+ criteria = result["evaluation_criteria"]+ assert "accuracy" in criteria+ assert "completeness" in criteria+ assert "reasoning" in criteria+ assert "sources" in criteria+def test_process_example_preserves_original_fields(self):ds = _make_dataset()example = {@@ -112,6 +183,14 @@ class TestProcessExample:total = sum(result["evaluation_criteria"].values())assert abs(total - 1.0) < 1e-9+ def test_process_example_does_not_mutate_input(self):+ """process_example returns a copy, original dict unchanged."""+ ds = _make_dataset()+ example = {"id": "q5", "problem": "P", "answer": "A"}+ original_keys = set(example.keys())+ ds.process_example(example)+ assert set(example.keys()) == original_keys+# ---------------------------------------------------------------------------# load() method@@ -130,10 +209,33 @@ class TestLoad:assert len(result) == 2assert result[0]["requires_deep_search"] is True+ def test_load_with_sampling(self):+ """load() samples when num_examples < total length."""+ ds = _make_dataset()+ raw = [+ {+ "id": str(i),+ "problem": f"Q{i}",+ "answer": f"A{i}",+ "canary": "",+ }+ for i in range(10)+ ]+ with patch.object(ds, "load_data", return_value=raw):+ result = ds.load(num_examples=3, seed=42)+ assert len(result) == 3+ for item in result:+ assert item["requires_deep_search"] is True+def test_load_samples_when_num_examples_set(self):ds = _make_dataset()raw = [- {"id": str(i), "problem": f"Q{i}", "answer": f"A{i}", "canary": ""}+ {+ "id": str(i),+ "problem": f"Q{i}",+ "answer": f"A{i}",+ "canary": "",+ }for i in range(10)]with patch.object(ds, "load_data", return_value=raw):@@ -143,13 +245,39 @@ class TestLoad:def test_load_no_sampling_when_num_examples_none(self):ds = _make_dataset()raw = [- {"id": str(i), "problem": f"Q{i}", "answer": f"A{i}", "canary": ""}+ {+ "id": str(i),+ "problem": f"Q{i}",+ "answer": f"A{i}",+ "canary": "",+ }for i in range(5)]with patch.object(ds, "load_data", return_value=raw):result = ds.load()assert len(result) == 5+ def test_load_full_integration(self):+ """load() calls load_data then process_example for each item."""+ ds = _make_dataset()+ raw = [+ {+ "id": "a",+ "problem": "Integration Q",+ "answer": "Integration A",+ "canary": "",+ },+ ]+ with patch.object(ds, "load_data", return_value=raw) as mock_load:+ with patch.object(+ ds, "process_example", wraps=ds.process_example+ ) as mock_process:+ result = ds.load(dataset_path="fake/path")+ mock_load.assert_called_once()+ mock_process.assert_called_once_with(raw[0])+ assert len(result) == 1+ assert result[0]["requires_deep_search"] is True+# ---------------------------------------------------------------------------# load_data() – datasets library available, plain text fields@@ -157,6 +285,27 @@ class TestLoad:class TestLoadDataPlainText:+ def test_load_via_datasets_library(self):+ """load_data uses datasets.load_dataset when available and returns formatted items."""+ ds = _make_dataset()+ mock_item = {+ "id": "plain_1",+ "prompt": "What is the speed of light?",+ "answer": "299,792,458 m/s",+ "canary": "testkey",+ "reference_steps": "",+ }+ mock_dataset = [mock_item]+ mock_load_dataset = Mock(return_value=mock_dataset)+ with patch.dict(+ "sys.modules", {"datasets": Mock(load_dataset=mock_load_dataset)}+ ):+ with patch(f"{MODULE}.logger"):+ result = ds.load_data()+ assert len(result) == 1+ assert result[0]["problem"] == "What is the speed of light?"+ assert result[0]["answer"] == "299,792,458 m/s"+def test_load_data_plain_text_prompt_and_answer(self):ds = _make_dataset()mock_item = {@@ -191,6 +340,26 @@ class TestLoadDataPlainText:)assert result == []+ def test_load_data_formatted_item_has_required_keys(self):+ ds = _make_dataset()+ mock_item = {+ "id": "test_id",+ "prompt": "Some plain question",+ "answer": "Some plain answer",+ "canary": "k",+ "reference_steps": "step1",+ }+ mock_load_dataset = Mock(return_value=[mock_item])+ with patch.dict(+ "sys.modules", {"datasets": Mock(load_dataset=mock_load_dataset)}+ ):+ with patch(f"{MODULE}.logger"):+ result = ds.load_data()+ item = result[0]+ for key in ("id", "problem", "answer", "reference_steps", "canary"):+ assert key in item, f"Missing key: {key}"+ assert item["id"] == "test_id"+# ---------------------------------------------------------------------------# load_data() – encrypted fields (base64-like prompt)@@ -233,7 +402,21 @@ class TestLoadDataEncryptedFields:# ----------------------------------------------------------------------------class TestLoadDataImportErrorFallback:+class TestLoadDatasetsImportErrorFallback:+ def test_load_datasets_import_error_fallback(self):+ """When 'datasets' library is not installed, _load_from_url is called."""+ ds = _make_dataset()+ fallback_data = [+ {"id": "url_1", "problem": "Q", "answer": "A", "canary": ""}+ ]+ with patch.object(+ ds, "_load_from_url", return_value=fallback_data+ ) as mock_url:+ with patch.dict("sys.modules", {"datasets": None}):+ result = ds.load_data()+ mock_url.assert_called_once()+ assert result == fallback_data+def test_import_error_falls_back_to_url(self):ds = _make_dataset()fallback_data = [@@ -253,7 +436,26 @@ class TestLoadDataImportErrorFallback:# ----------------------------------------------------------------------------class TestLoadDataExceptionFallback:+class TestLoadDatasetsExceptionFallback:+ def test_load_datasets_exception_fallback(self):+ """When load_dataset raises an exception, falls back to _load_from_url."""+ ds = _make_dataset()+ fallback_data = [+ {"id": "fb_1", "problem": "Q", "answer": "A", "canary": ""}+ ]+ mock_load_dataset = Mock(side_effect=RuntimeError("network error"))+ with patch.object(+ ds, "_load_from_url", return_value=fallback_data+ ) as mock_url:+ with patch.dict(+ "sys.modules",+ {"datasets": Mock(load_dataset=mock_load_dataset)},+ ):+ with patch(f"{MODULE}.logger"):+ result = ds.load_data()+ mock_url.assert_called_once()+ assert result == fallback_data+def test_exception_in_load_dataset_falls_back_to_url(self):ds = _make_dataset()fallback_data = [@@ -274,11 +476,34 @@ class TestLoadDataExceptionFallback:# ----------------------------------------------------------------------------# _load_from_url – success path+# _load_from_url – success and failure paths# ---------------------------------------------------------------------------class TestLoadFromUrl:+ def test_load_from_url_success(self):+ """_load_from_url calls pd.read_parquet and returns a list of dicts."""+ ds = _make_dataset()+ mock_df = MagicMock()+ row = MagicMock()+ row.get = lambda key, default="": {+ "id": "url_q1",+ "prompt": "Direct URL question",+ "answer": "Direct URL answer",+ "canary": "",+ "reference_steps": "",+ }.get(key, default)+ mock_df.iterrows.return_value = [(0, row)]++ mock_pd = Mock()+ mock_pd.read_parquet.return_value = mock_df+ with patch.dict("sys.modules", {"pandas": mock_pd}):+ with patch(f"{MODULE}.logger"):+ result = ds._load_from_url()+ mock_pd.read_parquet.assert_called_once()+ assert len(result) == 1+ assert result[0]["problem"] == "Direct URL question"+def test_load_from_url_success_returns_list(self):ds = _make_dataset()mock_df = MagicMock()@@ -300,6 +525,16 @@ class TestLoadFromUrl:assert len(result) == 1assert result[0]["problem"] == "Direct URL question"+ def test_load_from_url_failure_returns_empty(self):+ """_load_from_url returns [] when an exception occurs (e.g. connection error)."""+ ds = _make_dataset()+ mock_pd = Mock()+ mock_pd.read_parquet.side_effect = Exception("connection refused")+ with patch.dict("sys.modules", {"pandas": mock_pd}):+ with patch(f"{MODULE}.logger"):+ result = ds._load_from_url()+ assert result == []+def test_load_from_url_exception_returns_empty_list(self):ds = _make_dataset()mock_pd = Mock()diff --git a/tests/benchmarks/optimization/test_optuna_optimizer_branches_coverage.py b/tests/benchmarks/optimization/test_optuna_optimizer_branches_coverage.pynew file mode 100644index 0000000000..e67b2c2f68--- /dev/null+++ b/tests/benchmarks/optimization/test_optuna_optimizer_branches_coverage.py@@ -0,0 +1,404 @@+"""+Branch-coverage tests for benchmarks/optimization/optuna_optimizer.py.++Targets branches not fully exercised by the existing test files:+- _get_default_param_space structure and types+- optimize() raising KeyboardInterrupt+- progress_callback invocation during optimize()+- _save_results: joblib.dump called for study+- _create_visualizations with PLOTTING_AVAILABLE=False+- metric_weights normalisation when sum != 1.0+"""++from unittest.mock import Mock, patch++MODULE = "local_deep_research.benchmarks.optimization.optuna_optimizer"+++def _make_optimizer(**kwargs):+ from local_deep_research.benchmarks.optimization.optuna_optimizer import (+ OptunaOptimizer,+ )++ defaults = {"base_query": "branches coverage query"}+ defaults.update(kwargs)+ return OptunaOptimizer(**defaults)+++# ---------------------------------------------------------------------------+# _get_default_param_space+# ---------------------------------------------------------------------------+++class TestGetDefaultParamSpace:+ # test_get_default_param_space_iterations_is_int_type is defined first so it+ # runs first and warms up the expensive module import within the pytest-timeout+ # window before the other tests (including the bare test_get_default_param_space)+ # are collected.+ @patch(f"{MODULE}.CompositeBenchmarkEvaluator")+ def test_get_default_param_space_iterations_is_int_type(+ self, mock_evaluator+ ):+ mock_evaluator.return_value = Mock()+ optimizer = _make_optimizer()+ space = optimizer._get_default_param_space()+ assert space["iterations"]["type"] == "int"+ assert space["iterations"]["low"] >= 1+ assert space["iterations"]["high"] >= space["iterations"]["low"]++ @patch(f"{MODULE}.CompositeBenchmarkEvaluator")+ def test_get_default_param_space(self, mock_evaluator):+ """_get_default_param_space returns a dict with the four expected keys."""+ mock_evaluator.return_value = Mock()+ optimizer = _make_optimizer()+ space = optimizer._get_default_param_space()+ assert isinstance(space, dict)+ assert "iterations" in space+ assert "questions_per_iteration" in space+ assert "search_strategy" in space+ assert "max_results" in space++ @patch(f"{MODULE}.CompositeBenchmarkEvaluator")+ def test_get_default_param_space_search_strategy_is_categorical(+ self, mock_evaluator+ ):+ mock_evaluator.return_value = Mock()+ optimizer = _make_optimizer()+ space = optimizer._get_default_param_space()+ assert space["search_strategy"]["type"] == "categorical"+ choices = space["search_strategy"]["choices"]+ assert isinstance(choices, list)+ assert len(choices) > 0+ assert "iterdrag" in choices++ @patch(f"{MODULE}.CompositeBenchmarkEvaluator")+ def test_get_default_param_space_max_results_step(self, mock_evaluator):+ mock_evaluator.return_value = Mock()+ optimizer = _make_optimizer()+ space = optimizer._get_default_param_space()+ mr = space["max_results"]+ assert mr["type"] == "int"+ assert mr["low"] > 0+ assert mr["high"] > mr["low"]+++# ---------------------------------------------------------------------------+# optimize() – KeyboardInterrupt+# ---------------------------------------------------------------------------+++class TestOptimizeKeyboardInterrupt:+ @patch(f"{MODULE}.CompositeBenchmarkEvaluator")+ @patch(f"{MODULE}.optuna")+ def test_optimize_keyboard_interrupt(self, mock_optuna, mock_evaluator):+ """When study.optimize raises KeyboardInterrupt, best_params and value are still returned."""+ mock_evaluator.return_value = Mock()+ mock_study = Mock()+ mock_study.best_params = {"iterations": 2, "max_results": 50}+ mock_study.best_value = 0.55+ mock_study.trials = [Mock(), Mock()]+ mock_study.optimize.side_effect = KeyboardInterrupt()+ mock_optuna.create_study.return_value = mock_study+ mock_optuna.samplers.TPESampler.return_value = Mock()++ optimizer = _make_optimizer(n_trials=10)+ with (+ patch.object(optimizer, "_save_results") as mock_save,+ patch.object(optimizer, "_create_visualizations") as mock_viz,+ ):+ best_params, best_value = optimizer.optimize()++ assert best_params == {"iterations": 2, "max_results": 50}+ assert best_value == 0.55+ mock_save.assert_called_once()+ mock_viz.assert_called_once()++ @patch(f"{MODULE}.CompositeBenchmarkEvaluator")+ @patch(f"{MODULE}.optuna")+ def test_optimize_keyboard_interrupt_with_callback(+ self, mock_optuna, mock_evaluator+ ):+ """KeyboardInterrupt fires an 'interrupted' status callback."""+ mock_evaluator.return_value = Mock()+ callback = Mock()+ mock_study = Mock()+ mock_study.best_params = {"iterations": 1}+ mock_study.best_value = 0.3+ mock_study.trials = [Mock(), Mock(), Mock()]+ mock_study.optimize.side_effect = KeyboardInterrupt()+ mock_optuna.create_study.return_value = mock_study+ mock_optuna.samplers.TPESampler.return_value = Mock()++ optimizer = _make_optimizer(n_trials=5, progress_callback=callback)+ with (+ patch.object(optimizer, "_save_results"),+ patch.object(optimizer, "_create_visualizations"),+ ):+ optimizer.optimize()++ interrupted_calls = [+ c+ for c in callback.call_args_list+ if c[0][2].get("status") == "interrupted"+ ]+ assert len(interrupted_calls) == 1+ info = interrupted_calls[0][0][2]+ assert info["stage"] == "interrupted"+ assert info["trials_completed"] == 3++ @patch(f"{MODULE}.CompositeBenchmarkEvaluator")+ @patch(f"{MODULE}.optuna")+ def test_optimize_keyboard_interrupt_no_callback(+ self, mock_optuna, mock_evaluator+ ):+ """KeyboardInterrupt without a callback does not raise."""+ mock_evaluator.return_value = Mock()+ mock_study = Mock()+ mock_study.best_params = {"iterations": 1}+ mock_study.best_value = 0.1+ mock_study.trials = []+ mock_study.optimize.side_effect = KeyboardInterrupt()+ mock_optuna.create_study.return_value = mock_study+ mock_optuna.samplers.TPESampler.return_value = Mock()++ optimizer = _make_optimizer(n_trials=3)+ assert optimizer.progress_callback is None+ with (+ patch.object(optimizer, "_save_results"),+ patch.object(optimizer, "_create_visualizations"),+ ):+ params, value = optimizer.optimize()+ assert params == {"iterations": 1}+++# ---------------------------------------------------------------------------+# optimize() – progress_callback invoked+# ---------------------------------------------------------------------------+++class TestOptimizationCallbackInvoked:+ @patch(f"{MODULE}.CompositeBenchmarkEvaluator")+ @patch(f"{MODULE}.optuna")+ def test_optimization_callback_invoked(self, mock_optuna, mock_evaluator):+ """progress_callback is called with 'starting' status before study.optimize."""+ mock_evaluator.return_value = Mock()+ callback = Mock()+ mock_study = Mock()+ mock_study.best_params = {"iterations": 3}+ mock_study.best_value = 0.7+ mock_study.trials = [Mock()]+ mock_optuna.create_study.return_value = mock_study+ mock_optuna.samplers.TPESampler.return_value = Mock()++ optimizer = _make_optimizer(n_trials=1, progress_callback=callback)+ with (+ patch.object(optimizer, "_save_results"),+ patch.object(optimizer, "_create_visualizations"),+ ):+ optimizer.optimize()++ # At least one call should have status 'starting'+ all_statuses = [c[0][2].get("status") for c in callback.call_args_list]+ assert "starting" in all_statuses++ @patch(f"{MODULE}.CompositeBenchmarkEvaluator")+ @patch(f"{MODULE}.optuna")+ def test_optimization_callback_invoked_on_completion(+ self, mock_optuna, mock_evaluator+ ):+ """progress_callback is called with 'completed' status after study.optimize."""+ mock_evaluator.return_value = Mock()+ callback = Mock()+ mock_study = Mock()+ mock_study.best_params = {"max_results": 40}+ mock_study.best_value = 0.82+ mock_study.trials = [Mock(), Mock()]+ mock_optuna.create_study.return_value = mock_study+ mock_optuna.samplers.TPESampler.return_value = Mock()++ optimizer = _make_optimizer(n_trials=2, progress_callback=callback)+ with (+ patch.object(optimizer, "_save_results"),+ patch.object(optimizer, "_create_visualizations"),+ ):+ optimizer.optimize()++ completed_calls = [+ c+ for c in callback.call_args_list+ if c[0][2].get("status") == "completed"+ ]+ assert len(completed_calls) == 1+ info = completed_calls[0][0][2]+ assert info["best_value"] == 0.82+++# ---------------------------------------------------------------------------+# _save_results – joblib.dump called+# ---------------------------------------------------------------------------+++class TestSaveResultsJoblib:+ @patch(f"{MODULE}.CompositeBenchmarkEvaluator")+ @patch(f"{MODULE}.joblib")+ @patch(+ "local_deep_research.security.file_write_verifier.write_json_verified"+ )+ def test_save_results_joblib(+ self, mock_write_json, mock_joblib, mock_evaluator, tmp_path+ ):+ """_save_results calls joblib.dump to persist the study object."""+ mock_evaluator.return_value = Mock()+ optimizer = _make_optimizer(output_dir=str(tmp_path))++ mock_study = Mock()+ mock_study.best_params = {"iterations": 2}+ mock_study.best_value = 0.75+ mock_study.trials = [Mock()]+ optimizer.study = mock_study+ optimizer.trials_history = []++ optimizer._save_results()++ mock_joblib.dump.assert_called_once()+ # First arg to dump should be the study, second arg should be the file path+ call_args = mock_joblib.dump.call_args+ assert call_args[0][0] is mock_study+ assert str(call_args[0][1]).endswith(".pkl")++ @patch(f"{MODULE}.CompositeBenchmarkEvaluator")+ @patch(f"{MODULE}.joblib")+ @patch(+ "local_deep_research.security.file_write_verifier.write_json_verified"+ )+ def test_save_results_joblib_not_called_without_study(+ self, mock_write_json, mock_joblib, mock_evaluator, tmp_path+ ):+ """joblib.dump is NOT called when study is None."""+ mock_evaluator.return_value = Mock()+ optimizer = _make_optimizer(output_dir=str(tmp_path))+ optimizer.study = None+ optimizer.trials_history = []++ optimizer._save_results()++ mock_joblib.dump.assert_not_called()+++# ---------------------------------------------------------------------------+# _create_visualizations – PLOTTING_AVAILABLE=False+# ---------------------------------------------------------------------------+++class TestCreateVisualizationsNoMatplotlib:+ @patch(f"{MODULE}.CompositeBenchmarkEvaluator")+ @patch(f"{MODULE}.PLOTTING_AVAILABLE", False)+ def test_create_visualizations_no_matplotlib(self, mock_evaluator):+ """_create_visualizations returns early and never calls plot functions when PLOTTING_AVAILABLE=False."""+ mock_evaluator.return_value = Mock()+ optimizer = _make_optimizer()+ mock_study = Mock()+ mock_study.trials = [Mock(), Mock(), Mock()]+ optimizer.study = mock_study++ with patch(f"{MODULE}.plot_optimization_history") as mock_plot:+ optimizer._create_visualizations()+ mock_plot.assert_not_called()++ @patch(f"{MODULE}.CompositeBenchmarkEvaluator")+ @patch(f"{MODULE}.PLOTTING_AVAILABLE", False)+ def test_create_visualizations_no_matplotlib_does_not_raise(+ self, mock_evaluator+ ):+ """Calling _create_visualizations without matplotlib available does not raise."""+ mock_evaluator.return_value = Mock()+ optimizer = _make_optimizer()+ optimizer.study = Mock()+ optimizer.study.trials = [Mock(), Mock()]+ # Should complete without exception+ optimizer._create_visualizations()++ @patch(f"{MODULE}.CompositeBenchmarkEvaluator")+ @patch(f"{MODULE}.PLOTTING_AVAILABLE", True)+ def test_create_visualizations_skips_when_no_study(self, mock_evaluator):+ """_create_visualizations returns early when study is None."""+ mock_evaluator.return_value = Mock()+ optimizer = _make_optimizer()+ optimizer.study = None++ with patch(f"{MODULE}.plot_optimization_history") as mock_plot:+ optimizer._create_visualizations()+ mock_plot.assert_not_called()++ @patch(f"{MODULE}.CompositeBenchmarkEvaluator")+ @patch(f"{MODULE}.PLOTTING_AVAILABLE", True)+ def test_create_visualizations_skips_with_only_one_trial(+ self, mock_evaluator+ ):+ """_create_visualizations returns early when fewer than 2 trials are present."""+ mock_evaluator.return_value = Mock()+ optimizer = _make_optimizer()+ mock_study = Mock()+ mock_study.trials = [Mock()] # only 1 trial+ optimizer.study = mock_study++ with patch(f"{MODULE}.plot_optimization_history") as mock_plot:+ optimizer._create_visualizations()+ mock_plot.assert_not_called()+++# ---------------------------------------------------------------------------+# metric_weights normalisation+# ---------------------------------------------------------------------------+++class TestWeightNormalization:+ @patch(f"{MODULE}.CompositeBenchmarkEvaluator")+ def test_weight_normalization(self, mock_evaluator):+ """Weights that don't sum to 1.0 are normalised so the total becomes 1.0."""+ mock_evaluator.return_value = Mock()+ # Deliberately unbalanced weights+ optimizer = _make_optimizer(+ metric_weights={"quality": 3.0, "speed": 1.0}+ )+ total = sum(optimizer.metric_weights.values())+ assert abs(total - 1.0) < 1e-9++ @patch(f"{MODULE}.CompositeBenchmarkEvaluator")+ def test_weight_normalization_proportions_preserved(self, mock_evaluator):+ """After normalisation, the relative proportions remain correct."""+ mock_evaluator.return_value = Mock()+ optimizer = _make_optimizer(+ metric_weights={"quality": 3.0, "speed": 1.0}+ )+ # quality was 3x speed, so after normalisation quality should be 0.75+ assert abs(optimizer.metric_weights["quality"] - 0.75) < 1e-9+ assert abs(optimizer.metric_weights["speed"] - 0.25) < 1e-9++ @patch(f"{MODULE}.CompositeBenchmarkEvaluator")+ def test_weight_normalization_already_normalised(self, mock_evaluator):+ """Weights already summing to 1.0 remain unchanged."""+ mock_evaluator.return_value = Mock()+ optimizer = _make_optimizer(+ metric_weights={"quality": 0.6, "speed": 0.4}+ )+ assert abs(optimizer.metric_weights["quality"] - 0.6) < 1e-9+ assert abs(optimizer.metric_weights["speed"] - 0.4) < 1e-9++ @patch(f"{MODULE}.CompositeBenchmarkEvaluator")+ def test_weight_normalization_three_metrics(self, mock_evaluator):+ """Three-metric weights are also normalised correctly."""+ mock_evaluator.return_value = Mock()+ optimizer = _make_optimizer(+ metric_weights={"quality": 4.0, "speed": 3.0, "resource": 3.0}+ )+ total = sum(optimizer.metric_weights.values())+ assert abs(total - 1.0) < 1e-9++ @patch(f"{MODULE}.CompositeBenchmarkEvaluator")+ def test_default_weights_sum_to_one(self, mock_evaluator):+ """Default metric_weights are already normalised."""+ mock_evaluator.return_value = Mock()+ optimizer = _make_optimizer()+ total = sum(optimizer.metric_weights.values())+ assert abs(total - 1.0) < 1e-9