Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ classifiers = [

dependencies = [
"typer>=0.9.0",
"pydantic>=2.0.0",
"pyyaml>=6.0",
"jinja2>=3.0.0",
]
Expand Down
7 changes: 5 additions & 2 deletions src/pt_snap_cli/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -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")
Expand Down
2 changes: 1 addition & 1 deletion src/pt_snap_cli/query/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
9 changes: 6 additions & 3 deletions src/pt_snap_cli/query/executor.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

from __future__ import annotations

import warnings
from pathlib import Path
from typing import Any

Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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

Expand Down
2 changes: 1 addition & 1 deletion src/pt_snap_cli/query/mapper.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
}
Expand Down
9 changes: 5 additions & 4 deletions src/pt_snap_cli/query/registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

from __future__ import annotations

import warnings
from collections.abc import Callable
from pathlib import Path

Expand Down Expand Up @@ -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:
Expand All @@ -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)
7 changes: 7 additions & 0 deletions tests/query/test_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
46 changes: 46 additions & 0 deletions tests/query/test_executor.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
35 changes: 35 additions & 0 deletions tests/query/test_mapper.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
Loading