From d4345a6f4585eb2034c30ef59ebf9ffa8bb0ddc0 Mon Sep 17 00:00:00 2001 From: codeasier Date: Fri, 17 Apr 2026 20:44:48 +0800 Subject: [PATCH] fix: resolve 7 code quality issues and close test gaps - Remove unused pydantic dependency from pyproject.toml (#15) - Fix bool converter bug: "false" string now returns False instead of True (#12) - Replace silent pass with warnings in template loading (#13) - Use strict=True in zip() to catch column count mismatches early (#16) - Split broad except Exception in CLI use command (#16) - Fix CLAUDE.md template naming mismatch - Add test coverage for bool converter, mapper KeyError, execute_on_all_devices (#17) Closes #12, #13, #14, #15, #16, #17 --- pyproject.toml | 1 - src/pt_snap_cli/cli.py | 7 +++-- src/pt_snap_cli/query/config.py | 2 +- src/pt_snap_cli/query/executor.py | 9 ++++-- src/pt_snap_cli/query/mapper.py | 2 +- src/pt_snap_cli/query/registry.py | 9 +++--- tests/query/test_config.py | 7 +++++ tests/query/test_executor.py | 46 +++++++++++++++++++++++++++++++ tests/query/test_mapper.py | 35 +++++++++++++++++++++++ 9 files changed, 106 insertions(+), 12 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 707aebd..e108a82 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -26,7 +26,6 @@ classifiers = [ dependencies = [ "typer>=0.9.0", - "pydantic>=2.0.0", "pyyaml>=6.0", "jinja2>=3.0.0", ] diff --git a/src/pt_snap_cli/cli.py b/src/pt_snap_cli/cli.py index 2ad1b3a..f141044 100644 --- a/src/pt_snap_cli/cli.py +++ b/src/pt_snap_cli/cli.py @@ -7,7 +7,7 @@ from pt_snap_cli import __version__ from pt_snap_cli.config import ENV_DB_PATH, Config, ContextResolutionError -from pt_snap_cli.context import Context +from pt_snap_cli.context import Context, DatabaseNotFoundError, SchemaVersionError app = typer.Typer( name="pt-snap", @@ -101,9 +101,12 @@ def use_database( typer.echo(f"Available devices: {', '.join(map(str, devices))}") else: typer.echo("No devices found in database.") - except Exception as e: + except (DatabaseNotFoundError, SchemaVersionError) as e: typer.secho(f"Error: {e}", fg=typer.colors.RED) raise typer.Exit(1) from None + except Exception as e: + typer.secho(f"Error: unexpected failure opening database: {e}", fg=typer.colors.RED) + raise typer.Exit(1) from None @app.command("query") diff --git a/src/pt_snap_cli/query/config.py b/src/pt_snap_cli/query/config.py index 1918c69..d2fdfde 100644 --- a/src/pt_snap_cli/query/config.py +++ b/src/pt_snap_cli/query/config.py @@ -41,7 +41,7 @@ def validate(self, value: Any) -> Any: "str": str, "int": int, "float": float, - "bool": lambda x: bool(x) if isinstance(x, str) else x, + "bool": lambda x: x.lower() in ("true", "1", "yes") if isinstance(x, str) else bool(x), } converter = type_converters.get(self.type, str) diff --git a/src/pt_snap_cli/query/executor.py b/src/pt_snap_cli/query/executor.py index 406ca65..8eab31b 100644 --- a/src/pt_snap_cli/query/executor.py +++ b/src/pt_snap_cli/query/executor.py @@ -2,6 +2,7 @@ from __future__ import annotations +import warnings from pathlib import Path from typing import Any @@ -57,8 +58,10 @@ def _load_templates(self) -> None: try: config = QueryConfig.load_yaml(yaml_file) self._configs[yaml_file.stem] = config - except Exception: - pass + except Exception as e: + warnings.warn( + f"Failed to load query template from {yaml_file}: {e}", stacklevel=2 + ) def render( self, @@ -120,7 +123,7 @@ def execute( else: cursor.execute(sql) columns = [desc[0] for desc in cursor.description] - return [dict(zip(columns, row, strict=False)) for row in cursor.fetchall()] + return [dict(zip(columns, row, strict=True)) for row in cursor.fetchall()] except Exception as e: raise QueryExecutionError(f"Query execution failed: {e}") from e diff --git a/src/pt_snap_cli/query/mapper.py b/src/pt_snap_cli/query/mapper.py index a62bb0a..a9f2cf8 100644 --- a/src/pt_snap_cli/query/mapper.py +++ b/src/pt_snap_cli/query/mapper.py @@ -16,7 +16,7 @@ def __init__(self): "int": int, "float": float, "str": str, - "bool": bool, + "bool": lambda x: x.lower() in ("true", "1", "yes") if isinstance(x, str) else bool(x), "hex": lambda x: hex(x) if isinstance(x, int) else x, "datetime": lambda x: x, } diff --git a/src/pt_snap_cli/query/registry.py b/src/pt_snap_cli/query/registry.py index 38f1e26..cd93231 100644 --- a/src/pt_snap_cli/query/registry.py +++ b/src/pt_snap_cli/query/registry.py @@ -2,6 +2,7 @@ from __future__ import annotations +import warnings from collections.abc import Callable from pathlib import Path @@ -266,8 +267,8 @@ def _load_yaml_templates(template_dir: Path | str | None = None) -> None: config = QueryConfig.load_yaml(yaml_file) for _query_name, template in config.queries.items(): _registry.register(template) - except Exception: - pass + except Exception as e: + warnings.warn(f"Failed to load query template from {yaml_file}: {e}", stacklevel=2) def _load_all_templates() -> None: @@ -277,5 +278,5 @@ def _load_all_templates() -> None: try: _load_all_templates() -except Exception: - pass +except Exception as e: + warnings.warn(f"Failed to load query templates: {e}", stacklevel=2) diff --git a/tests/query/test_config.py b/tests/query/test_config.py index d81b494..e464f1e 100644 --- a/tests/query/test_config.py +++ b/tests/query/test_config.py @@ -24,7 +24,14 @@ def test_validate_float(self): def test_validate_bool(self): param = QueryParameter(name="test", type="bool", required=False) assert param.validate("true") is True + assert param.validate("false") is False + assert param.validate("True") is True + assert param.validate("False") is False + assert param.validate("1") is True + assert param.validate("0") is False + assert param.validate("yes") is True assert param.validate(False) is False + assert param.validate(True) is True def test_validate_missing_optional(self): param = QueryParameter(name="test", type="str", required=False, default="default") diff --git a/tests/query/test_executor.py b/tests/query/test_executor.py index d172a18..9b51b6d 100644 --- a/tests/query/test_executor.py +++ b/tests/query/test_executor.py @@ -135,3 +135,49 @@ def test_list_templates(self): executor.register_template(template) assert "test_query" in executor.list_templates() + + def test_execute_on_all_devices(self): + """Test execute_on_all_devices runs template on each device.""" + mock_context = _make_mock_context(device_ids=[0, 1]) + executor = QueryExecutor(mock_context) + executor.register_template( + QueryTemplate( + name="device_test", + description="Test", + query="SELECT {{ device_id }} as dev", + ) + ) + + results = executor.execute_on_all_devices("device_test") + assert 0 in results + assert 1 in results + + def test_execute_on_all_devices_template_not_found(self): + """Test execute_on_all_devices raises for missing template.""" + mock_context = _make_mock_context(device_ids=[0]) + executor = QueryExecutor(mock_context) + + from pt_snap_cli.query.executor import QueryExecutionError + + with pytest.raises(QueryExecutionError, match="Template not found"): + executor.execute_on_all_devices("nonexistent") + + def test_execute_on_all_devices_empty_device_list(self): + """Test execute_on_all_devices with no devices returns empty dict.""" + mock_context = _make_mock_context(device_ids=[]) + executor = QueryExecutor(mock_context) + executor.register_template( + QueryTemplate(name="empty_test", description="Test", query="SELECT 1") + ) + + results = executor.execute_on_all_devices("empty_test") + assert results == {} + + +def _make_mock_context(device_ids: list[int]): + """Create a mock Context with the given device IDs.""" + from unittest.mock import MagicMock + + mock = MagicMock() + mock.device_ids = device_ids + return mock diff --git a/tests/query/test_mapper.py b/tests/query/test_mapper.py index ccd77b4..2aaf4d3 100644 --- a/tests/query/test_mapper.py +++ b/tests/query/test_mapper.py @@ -110,6 +110,41 @@ def __init__(self, data): assert len(models) == 2 assert all(isinstance(m, MockModel) for m in models) + def test_map_to_model_not_registered_raises_keyerror(self): + mapper = ResultMapper() + with pytest.raises(KeyError) as exc_info: + mapper.map_to_model({"id": 1}, "MissingModel") + assert "MissingModel" in str(exc_info.value) + + def test_map_all_to_model_propagates_keyerror(self): + mapper = ResultMapper() + with pytest.raises(KeyError): + mapper.map_all_to_model([{"id": 1}], "MissingModel") + + def test_map_bool_string_values(self): + mapper = ResultMapper() + row = {"flag_true": "true", "flag_false": "false", "flag_1": "1", "flag_0": "0"} + schema = [ + {"column": "flag_true", "type": "bool"}, + {"column": "flag_false", "type": "bool"}, + {"column": "flag_1", "type": "bool"}, + {"column": "flag_0", "type": "bool"}, + ] + + result = mapper.map(row, schema) + assert result["flag_true"] is True + assert result["flag_false"] is False + assert result["flag_1"] is True + assert result["flag_0"] is False + + def test_map_conversion_error_keeps_original_value(self): + mapper = ResultMapper() + row = {"value": "not_an_int"} + schema = [{"column": "value", "type": "int"}] + + result = mapper.map(row, schema) + assert result["value"] == "not_an_int" + class TestModuleFunctions: def test_map_result(self):