diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..89c16b9 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,70 @@ +name: Release + +on: + push: + tags: ["v*"] + +jobs: + build: + name: Build distribution + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-python@v5 + with: + python-version: "3.13" + + - name: Install build tool + run: pip install build + + - name: Build sdist and wheel + run: python -m build + + - name: Verify tag matches package version + run: | + TAG=${GITHUB_REF#refs/tags/v} + PKG_VERSION=$(python -c "import tomllib; print(tomllib.load(open('pyproject.toml','rb'))['project']['version'])") + if [ "$TAG" != "$PKG_VERSION" ]; then + echo "::error::Tag v$TAG does not match pyproject.toml version $PKG_VERSION" + exit 1 + fi + + - name: Verify package installs and runs + run: | + pip install dist/*.whl + pt-snap --version + + - name: Upload build artifacts + uses: actions/upload-artifact@v4 + with: + name: dist + path: dist/ + retention-days: 90 + + publish: + name: Publish to PyPI + needs: build + runs-on: ubuntu-latest + permissions: + id-token: write + environment: + name: pypi + url: https://pypi.org/project/pt-snap-cli/ + steps: + - name: Download build artifacts + uses: actions/download-artifact@v4 + with: + name: dist + path: dist/ + + - name: Publish to PyPI + uses: pypa/gh-action-pypi-publish@release/v1 + # Uses Trusted Publisher (OIDC) by default - no API token needed. + # To publish to TestPyPI instead, uncomment: + # with: + # repository-url: https://test.pypi.org/legacy/ + + # Alternative: token-based publishing (if OIDC not configured) + # with: + # password: ${{ secrets.PYPI_API_TOKEN }} diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 0000000..46647d6 --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,66 @@ +name: Test + +on: + push: + branches: [main] + pull_request: + branches: [main] + +concurrency: + group: test-${{ github.ref }} + cancel-in-progress: true + +jobs: + lint: + name: Lint & Format + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-python@v5 + with: + python-version: "3.13" + + - name: Install dependencies + run: pip install -e .[dev] + + - name: Ruff lint check + run: ruff check . + + - name: Black format check + run: black --check . + + test: + name: Test (Python ${{ matrix.python-version }}) + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + python-version: ["3.10", "3.11", "3.12", "3.13"] + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python-version }} + + - uses: actions/cache@v4 + with: + path: ~/.cache/pip + key: pip-${{ runner.os }}-${{ matrix.python-version }}-${{ hashFiles('pyproject.toml') }} + restore-keys: | + pip-${{ runner.os }}-${{ matrix.python-version }}- + + - name: Install dependencies + run: pip install -e .[dev] + + - name: Run tests with coverage + run: pytest --cov --cov-report=xml --cov-report=term-missing + + - name: Upload coverage report + uses: actions/upload-artifact@v4 + if: matrix.python-version == '3.13' && always() + with: + name: coverage-report + path: coverage.xml + retention-days: 30 diff --git a/pt_snap_cli/cli.py b/pt_snap_cli/cli.py index af6796a..777760b 100644 --- a/pt_snap_cli/cli.py +++ b/pt_snap_cli/cli.py @@ -37,8 +37,12 @@ def main( @app.command("use") def use_database( db_path: Annotated[Path | None, typer.Argument(help="Path to SQLite database file")] = None, - session: Annotated[bool, typer.Option("--session", help="Print a shell export for this session only")] = False, - global_context: Annotated[bool, typer.Option("--global", help="Store the database in legacy global config")] = False, + session: Annotated[ + bool, typer.Option("--session", help="Print a shell export for this session only") + ] = False, + global_context: Annotated[ + bool, typer.Option("--global", help="Store the database in legacy global config") + ] = False, ) -> None: """Set the current analysis database. @@ -104,12 +108,24 @@ def use_database( @app.command("query") def query_database( - db_path: Annotated[Path | None, typer.Argument(help="Path to database file (optional if configured)")] = None, - template_use: Annotated[str | None, typer.Option("--template-use", help="Query template name to execute")] = None, + db_path: Annotated[ + Path | None, typer.Argument(help="Path to database file (optional if configured)") + ] = None, + template_use: Annotated[ + str | None, typer.Option("--template-use", help="Query template name to execute") + ] = None, params: Annotated[str | None, typer.Option(help="Query parameters as JSON string")] = None, device: Annotated[int | None, typer.Option(help="Device ID to query")] = None, - list_templates: Annotated[bool, typer.Option("--list", help="List all available query templates")] = False, - template_info: Annotated[str | None, typer.Option("--template-info", help="Show detailed information about a template (including parameters and output schema)")] = None, + list_templates: Annotated[ + bool, typer.Option("--list", help="List all available query templates") + ] = False, + template_info: Annotated[ + str | None, + typer.Option( + "--template-info", + help="Show detailed information about a template (including parameters and output schema)", + ), + ] = None, ) -> None: """Execute queries on the memory snapshot database. @@ -150,19 +166,26 @@ def query_database( typer.echo() typer.echo("Parameters:") - if info['parameters']: - for param_name, param_details in info['parameters'].items(): - required_str = " (required)" if param_details['required'] else " (optional)" - default_str = f" [default: {param_details['default']}]" if param_details['default'] is not None else "" - typer.secho(f" {param_name}: {param_details['type']}{required_str}{default_str}", fg=typer.colors.YELLOW) + if info["parameters"]: + for param_name, param_details in info["parameters"].items(): + required_str = " (required)" if param_details["required"] else " (optional)" + default_str = ( + f" [default: {param_details['default']}]" + if param_details["default"] is not None + else "" + ) + typer.secho( + f" {param_name}: {param_details['type']}{required_str}{default_str}", + fg=typer.colors.YELLOW, + ) typer.echo(f" {param_details['description']}") else: typer.echo(" None") typer.echo() typer.echo("Output Schema:") - if info['output_schema']: - for col in info['output_schema']: + if info["output_schema"]: + for col in info["output_schema"]: typer.echo(f" {col['column']}: {col['type']}") else: typer.echo(" Dynamic (depends on query)") @@ -170,28 +193,44 @@ def query_database( typer.echo("Example Usage:") example_params = {} - for param_name, param_details in info['parameters'].items(): - if param_details['type'] == 'int': - example_params[param_name] = param_details['default'] if param_details['default'] is not None else 0 - elif param_details['type'] == 'float': - example_params[param_name] = param_details['default'] if param_details['default'] is not None else 0.0 - elif param_details['type'] == 'str': - example_params[param_name] = param_details['default'] if param_details['default'] is not None else "example" - elif param_details['type'] == 'bool': + for param_name, param_details in info["parameters"].items(): + if param_details["type"] == "int": + example_params[param_name] = ( + param_details["default"] if param_details["default"] is not None else 0 + ) + elif param_details["type"] == "float": + example_params[param_name] = ( + param_details["default"] if param_details["default"] is not None else 0.0 + ) + elif param_details["type"] == "str": + example_params[param_name] = ( + param_details["default"] + if param_details["default"] is not None + else "example" + ) + elif param_details["type"] == "bool": example_params[param_name] = True if example_params: import json + params_str = json.dumps(example_params) - typer.echo(f" pt-snap query {db_path or ''} --template-use {info['name']} --params '{params_str}'") + typer.echo( + f" pt-snap query {db_path or ''} --template-use {info['name']} --params '{params_str}'" + ) else: - typer.echo(f" pt-snap query {db_path or ''} --template-use {info['name']}") + typer.echo( + f" pt-snap query {db_path or ''} --template-use {info['name']}" + ) else: typer.secho(f"Error: Template '{template_info}' not found", fg=typer.colors.RED) raise typer.Exit() if not template_use: - typer.secho("Error: --template-use is required when not using --list or --template-info", fg=typer.colors.RED) + typer.secho( + "Error: --template-use is required when not using --list or --template-info", + fg=typer.colors.RED, + ) raise typer.Exit(1) config = Config() @@ -207,7 +246,9 @@ def query_database( "Error: No database path specified and no database configured.", fg=typer.colors.RED, ) - typer.echo("Use 'pt-snap use ' to set a project database, or provide db_path argument.") + typer.echo( + "Use 'pt-snap use ' to set a project database, or provide db_path argument." + ) raise typer.Exit(1) if not db_path.exists(): typer.secho( @@ -216,7 +257,9 @@ def query_database( ) if resolved.context_file: typer.echo(f"Context file: {resolved.context_file}") - typer.echo("Use 'pt-snap use ' to set a new project database, or provide db_path argument.") + typer.echo( + "Use 'pt-snap use ' to set a new project database, or provide db_path argument." + ) raise typer.Exit(1) try: @@ -239,7 +282,9 @@ def query_database( typer.echo("No devices found in database.") raise typer.Exit() default_device = device_ids[0] - results = executor.execute_template(template_use, query_params, device_id=default_device) + results = executor.execute_template( + template_use, query_params, device_id=default_device + ) if results: typer.echo(f"Found {len(results)} results:") diff --git a/pt_snap_cli/config.py b/pt_snap_cli/config.py index b85b19f..4c4ad72 100644 --- a/pt_snap_cli/config.py +++ b/pt_snap_cli/config.py @@ -149,9 +149,7 @@ def get_project_db_path(self, start_dir: Path | None = None) -> tuple[Path, Path with open(context_file) as f: data = json.load(f) except (json.JSONDecodeError, OSError) as exc: - raise ContextResolutionError( - f"Invalid project context file: {context_file}" - ) from exc + raise ContextResolutionError(f"Invalid project context file: {context_file}") from exc db_path = data.get(CURRENT_DB_KEY) if not db_path: diff --git a/pt_snap_cli/query/executor.py b/pt_snap_cli/query/executor.py index 1f122b8..406ca65 100644 --- a/pt_snap_cli/query/executor.py +++ b/pt_snap_cli/query/executor.py @@ -91,13 +91,9 @@ def render( jinja_template = self._env.from_string(template.query) return jinja_template.render(render_context) except TemplateSyntaxError as e: - raise TemplateRenderError( - f"Template syntax error in '{template.name}': {e}" - ) from e + raise TemplateRenderError(f"Template syntax error in '{template.name}': {e}") from e except Exception as e: - raise TemplateRenderError( - f"Failed to render template '{template.name}': {e}" - ) from e + raise TemplateRenderError(f"Failed to render template '{template.name}': {e}") from e def execute( self, @@ -124,9 +120,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=False)) for row in cursor.fetchall()] except Exception as e: raise QueryExecutionError(f"Query execution failed: {e}") from e @@ -186,9 +180,7 @@ def execute_on_all_devices( results = {} for device_id in self._context.device_ids: try: - results[device_id] = self.execute_template( - name, params, device_id, config_name - ) + results[device_id] = self.execute_template(name, params, device_id, config_name) except QueryExecutionError: results[device_id] = [] diff --git a/pt_snap_cli/query/mapper.py b/pt_snap_cli/query/mapper.py index 5253ca6..a62bb0a 100644 --- a/pt_snap_cli/query/mapper.py +++ b/pt_snap_cli/query/mapper.py @@ -22,9 +22,7 @@ def __init__(self): } self._model_factories: dict[str, Callable[[dict], Any]] = {} - def register_type_converter( - self, type_name: str, converter: Callable[[Any], Any] - ) -> None: + def register_type_converter(self, type_name: str, converter: Callable[[Any], Any]) -> None: """Register a type converter. Args: @@ -33,9 +31,7 @@ def register_type_converter( """ self._type_converters[type_name] = converter - def register_model_factory( - self, model_name: str, factory: Callable[[dict], Any] - ) -> None: + def register_model_factory(self, model_name: str, factory: Callable[[dict], Any]) -> None: """Register a model factory. Args: diff --git a/pt_snap_cli/query/registry.py b/pt_snap_cli/query/registry.py index 078eb1e..918fea3 100644 --- a/pt_snap_cli/query/registry.py +++ b/pt_snap_cli/query/registry.py @@ -80,15 +80,17 @@ def list_queries_with_details(self) -> list[dict[str, str]]: """ details = [] all_names = set(self._queries.keys()) | set(self._factories.keys()) - + for name in sorted(all_names): template = self.get(name) if template: - details.append({ - "name": name, - "description": template.description, - }) - + details.append( + { + "name": name, + "description": template.description, + } + ) + return details def unregister(self, name: str) -> bool: @@ -146,7 +148,7 @@ def get_template_info(name: str) -> dict | None: template = _registry.get(name) if not template: return None - + return { "name": template.name, "description": template.description, @@ -185,7 +187,7 @@ def list_queries_with_details() -> list[dict[str, str]]: def _load_yaml_templates(template_dir: Path | str | None = None) -> None: """Load all YAML templates from the template directory. - + Args: template_dir: Path to template directory. Defaults to package templates dir. """ @@ -193,14 +195,14 @@ def _load_yaml_templates(template_dir: Path | str | None = None) -> None: template_dir = Path(__file__).parent / "templates" else: template_dir = Path(template_dir) - + if not template_dir.exists(): return - + for yaml_file in template_dir.glob("*.yaml"): try: config = QueryConfig.load_yaml(yaml_file) - for query_name, template in config.queries.items(): + for _query_name, template in config.queries.items(): _registry.register(template) except Exception: pass diff --git a/pyproject.toml b/pyproject.toml index 60c33e6..8d3e7ea 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -31,12 +31,18 @@ dependencies = [ "jinja2>=3.0.0", ] +[project.urls] +Homepage = "https://github.com/codeasier/pt-snap-cli" +Repository = "https://github.com/codeasier/pt-snap-cli" +Issues = "https://github.com/codeasier/pt-snap-cli/issues" + [project.optional-dependencies] dev = [ "pytest>=7.0.0", "pytest-cov>=4.0.0", "black>=23.0.0", "ruff>=0.0.280", + "build>=1.0.0", ] rag = [ "chromadb>=0.4.0", @@ -69,4 +75,22 @@ ignore = ["E501"] testpaths = ["tests"] python_files = ["test_*.py"] python_functions = ["test_*"] -addopts = "-v --tb=short" \ No newline at end of file +addopts = "-v --tb=short" + +[tool.coverage.run] +source = ["pt_snap_cli"] +branch = true +omit = ["*/tests/*", "*/__pycache__/*"] + +[tool.coverage.report] +show_missing = true +skip_empty = true +exclude_lines = [ + "pragma: no cover", + "if __name__ == .__main__.", + "if TYPE_CHECKING:", +] +fail_under = 0 + +[tool.coverage.xml] +output = "coverage.xml" \ No newline at end of file diff --git a/tests/test_cli.py b/tests/test_cli.py index ad97477..dd6e491 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -53,15 +53,21 @@ def create_sample_db(db_path: Path, size: int = 1024) -> Path: """) # Insert sample data - conn.execute(""" + conn.execute( + """ INSERT INTO trace_entry_0 (action, device_id, size, timestamp) VALUES ('malloc', 0, ?, 1.0) - """, (size,)) + """, + (size,), + ) - conn.execute(""" + conn.execute( + """ INSERT INTO blocks_0 (device_id, address, size, start_time, end_time) VALUES (0, 1000, ?, 1.0, 2.0) - """, (size,)) + """, + (size,), + ) conn.commit() conn.close() @@ -88,7 +94,7 @@ def mock_home(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): """Mock Path.home to use tmp_path.""" monkeypatch.chdir(tmp_path) monkeypatch.delenv("PT_SNAP_DB_PATH", raising=False) - with patch.object(Path, 'home', return_value=tmp_path): + with patch.object(Path, "home", return_value=tmp_path): yield @@ -227,41 +233,43 @@ def test_template_info_with_complex_parameters(self, sample_db: Path) -> None: type="int", default=42, required=False, - description="Integer parameter" + description="Integer parameter", ), "float_param": QueryParameter( name="float_param", type="float", default=3.14, required=False, - description="Float parameter" + description="Float parameter", ), "str_param": QueryParameter( name="str_param", type="str", default="default_value", required=False, - description="String parameter" + description="String parameter", ), "bool_param": QueryParameter( name="bool_param", type="bool", default=True, required=False, - description="Boolean parameter" + description="Boolean parameter", ), "required_param": QueryParameter( name="required_param", type="int", default=None, required=True, - description="Required parameter" - ) - } + description="Required parameter", + ), + }, ) register_query(template) - result = runner.invoke(app, ["query", str(sample_db), "--template-info", "complex_template"]) + result = runner.invoke( + app, ["query", str(sample_db), "--template-info", "complex_template"] + ) assert result.exit_code == 0 assert "Template: complex_template" in result.stdout assert "int_param" in result.stdout @@ -278,11 +286,13 @@ def test_template_info_without_parameters(self, sample_db: Path) -> None: template = QueryTemplate( name="no_param_template", description="Template without parameters", - query="SELECT COUNT(*) FROM blocks" + query="SELECT COUNT(*) FROM blocks", ) register_query(template) - result = runner.invoke(app, ["query", str(sample_db), "--template-info", "no_param_template"]) + result = runner.invoke( + app, ["query", str(sample_db), "--template-info", "no_param_template"] + ) assert result.exit_code == 0 assert "Parameters:" in result.stdout assert "None" in result.stdout @@ -292,11 +302,13 @@ def test_template_info_without_output_schema(self, sample_db: Path) -> None: template = QueryTemplate( name="no_schema_template", description="Template without output schema", - query="SELECT * FROM blocks" + query="SELECT * FROM blocks", ) register_query(template) - result = runner.invoke(app, ["query", str(sample_db), "--template-info", "no_schema_template"]) + result = runner.invoke( + app, ["query", str(sample_db), "--template-info", "no_schema_template"] + ) assert result.exit_code == 0 assert "Output Schema:" in result.stdout assert "Dynamic" in result.stdout @@ -414,7 +426,9 @@ class TestQueryCommand: def test_query_list_templates(self, sample_db: Path) -> None: """Test 'query --list' command lists templates.""" - register_query(QueryTemplate(name="test_template", description="Test query", query="SELECT 1")) + register_query( + QueryTemplate(name="test_template", description="Test query", query="SELECT 1") + ) result = runner.invoke(app, ["query", str(sample_db), "--list"]) assert result.exit_code == 0 @@ -425,7 +439,10 @@ def test_query_list_no_templates(self, sample_db: Path) -> None: """Test 'query --list' when no templates registered.""" result = runner.invoke(app, ["query", str(sample_db), "--list"]) assert result.exit_code == 0 - assert "No query templates available" in result.stdout or "Available query templates" in result.stdout + assert ( + "No query templates available" in result.stdout + or "Available query templates" in result.stdout + ) def test_query_template_info(self, sample_db: Path) -> None: """Test 'query --template-info' command.""" @@ -437,17 +454,10 @@ def test_query_template_info(self, sample_db: Path) -> None: query="SELECT * FROM blocks", parameters={ "device_id": QueryParameter( - name="device_id", - type="int", - default=0, - required=False, - description="Device ID" + name="device_id", type="int", default=0, required=False, description="Device ID" ) }, - output_schema=[ - {"column": "id", "type": "int"}, - {"column": "size", "type": "int"} - ] + output_schema=[{"column": "id", "type": "int"}, {"column": "size", "type": "int"}], ) register_query(template) @@ -469,7 +479,11 @@ def test_query_uses_project_context(self, sample_db: Path) -> None: context_dir = Path.cwd() / ".pt-snap" context_dir.mkdir() (context_dir / "context.json").write_text(json.dumps({"current_db_path": str(sample_db)})) - register_query(QueryTemplate(name="size_query", description="Test", query="SELECT size FROM trace_entry_0")) + register_query( + QueryTemplate( + name="size_query", description="Test", query="SELECT size FROM trace_entry_0" + ) + ) result = runner.invoke(app, ["query", "--template-use", "size_query"]) @@ -488,7 +502,11 @@ def test_query_env_overrides_project_context( context_dir.mkdir() (context_dir / "context.json").write_text(json.dumps({"current_db_path": str(sample_db)})) monkeypatch.setenv("PT_SNAP_DB_PATH", str(env_db)) - register_query(QueryTemplate(name="size_query", description="Test", query="SELECT size FROM trace_entry_0")) + register_query( + QueryTemplate( + name="size_query", description="Test", query="SELECT size FROM trace_entry_0" + ) + ) result = runner.invoke(app, ["query", "--template-use", "size_query"]) @@ -508,7 +526,11 @@ def test_query_explicit_path_overrides_env_and_project( context_dir.mkdir() (context_dir / "context.json").write_text(json.dumps({"current_db_path": str(sample_db)})) monkeypatch.setenv("PT_SNAP_DB_PATH", str(env_db)) - register_query(QueryTemplate(name="size_query", description="Test", query="SELECT size FROM trace_entry_0")) + register_query( + QueryTemplate( + name="size_query", description="Test", query="SELECT size FROM trace_entry_0" + ) + ) result = runner.invoke(app, ["query", str(explicit_db), "--template-use", "size_query"]) @@ -521,11 +543,13 @@ def test_query_with_device(self, sample_db: Path) -> None: name="device_query", description="Query with device", query="SELECT * FROM blocks_0 WHERE device_id = ?", - devices=[0] + devices=[0], ) register_query(template) - result = runner.invoke(app, ["query", str(sample_db), "--template-use", "device_query", "--device", "0"]) + result = runner.invoke( + app, ["query", str(sample_db), "--template-use", "device_query", "--device", "0"] + ) # The test might fail due to executor issues, but we're testing CLI flow assert result.exit_code in [0, 1] @@ -535,11 +559,21 @@ def test_query_with_params(self, sample_db: Path) -> None: name="param_query", description="Query with params", query="SELECT * FROM trace_entry_0 WHERE device_id = ?", - devices=[0] + devices=[0], ) register_query(template) - result = runner.invoke(app, ["query", str(sample_db), "--template-use", "param_query", "--params", '{"device_id": 0}']) + result = runner.invoke( + app, + [ + "query", + str(sample_db), + "--template-use", + "param_query", + "--params", + '{"device_id": 0}', + ], + ) # The test might fail due to executor issues, but we're testing CLI flow assert result.exit_code in [0, 1] @@ -547,6 +581,8 @@ def test_query_invalid_json_params(self, sample_db: Path) -> None: """Test 'query' command with invalid JSON params.""" register_query(QueryTemplate(name="test", description="Test", query="SELECT 1")) - result = runner.invoke(app, ["query", str(sample_db), "--template-use", "test", "--params", "invalid json"]) + result = runner.invoke( + app, ["query", str(sample_db), "--template-use", "test", "--params", "invalid json"] + ) assert result.exit_code == 1 assert "Error" in result.stdout diff --git a/tests/test_config.py b/tests/test_config.py index 10b5c5d..fbfc44e 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -138,10 +138,9 @@ def test_config_load_from_file(self, tmp_path: Path) -> None: db_path = tmp_path / "existing.db" db_path.touch() - config_file.write_text(json.dumps({ - "current_db_path": str(db_path), - "other_key": "other_value" - })) + config_file.write_text( + json.dumps({"current_db_path": str(db_path), "other_key": "other_value"}) + ) config = Config() assert config.current_db_path == db_path.resolve() diff --git a/tests/test_query_builder.py b/tests/test_query_builder.py index 7425b99..0cb3d87 100644 --- a/tests/test_query_builder.py +++ b/tests/test_query_builder.py @@ -15,21 +15,13 @@ def test_basic_select(self): def test_select_specific_columns(self): builder = QueryBuilder() - sql, params = ( - builder.from_table("trace_entry_0") - .columns("id", "address", "size") - .build() - ) + sql, params = builder.from_table("trace_entry_0").columns("id", "address", "size").build() assert sql == "SELECT id, address, size FROM trace_entry_0" assert params == [] def test_where_clause(self): builder = QueryBuilder() - sql, params = ( - builder.from_table("trace_entry_0") - .where(Equal("status", "active")) - .build() - ) + sql, params = builder.from_table("trace_entry_0").where(Equal("status", "active")).build() assert "WHERE" in sql assert "(status = ?)" in sql assert params == ["active"] @@ -50,11 +42,7 @@ def test_multiple_where_clauses(self): def test_order_by(self): builder = QueryBuilder() - sql, params = ( - builder.from_table("trace_entry_0") - .order_by("size", descending=True) - .build() - ) + sql, params = builder.from_table("trace_entry_0").order_by("size", descending=True).build() assert "ORDER BY size DESC" in sql def test_order_by_multiple(self): @@ -69,30 +57,17 @@ def test_order_by_multiple(self): def test_group_by(self): builder = QueryBuilder() - sql, params = ( - builder.from_table("trace_entry_0") - .group_by("eventType") - .build() - ) + sql, params = builder.from_table("trace_entry_0").group_by("eventType").build() assert "GROUP BY eventType" in sql def test_limit(self): builder = QueryBuilder() - sql, params = ( - builder.from_table("trace_entry_0") - .limit(100) - .build() - ) + sql, params = builder.from_table("trace_entry_0").limit(100).build() assert "LIMIT 100" in sql def test_offset(self): builder = QueryBuilder() - sql, params = ( - builder.from_table("trace_entry_0") - .limit(100) - .offset(50) - .build() - ) + sql, params = builder.from_table("trace_entry_0").limit(100).offset(50).build() assert "LIMIT 100" in sql assert "OFFSET 50" in sql @@ -128,27 +103,25 @@ def test_reset(self): def test_in_condition(self): builder = QueryBuilder() sql, params = ( - builder.from_table("trace_entry_0") - .where(In("eventType", ["alloc", "free"])) - .build() + builder.from_table("trace_entry_0").where(In("eventType", ["alloc", "free"])).build() ) assert "eventType IN (?, ?)" in sql assert params == ["alloc", "free"] def test_combined_conditions(self): builder = QueryBuilder() - cond = And([ - Equal("status", "active"), - Or([ - Equal("type", "malloc"), - Equal("type", "cudaMalloc"), - ]), - ]) - sql, params = ( - builder.from_table("trace_entry_0") - .where(cond) - .build() + cond = And( + [ + Equal("status", "active"), + Or( + [ + Equal("type", "malloc"), + Equal("type", "cudaMalloc"), + ] + ), + ] ) + sql, params = builder.from_table("trace_entry_0").where(cond).build() assert "WHERE" in sql assert "AND" in sql assert "OR" in sql diff --git a/tests/test_query_condition.py b/tests/test_query_condition.py index e5a10d3..e1822e6 100644 --- a/tests/test_query_condition.py +++ b/tests/test_query_condition.py @@ -1,6 +1,5 @@ """Tests for query condition classes.""" - from pt_snap_cli.query.condition import ( And, Equal, @@ -236,34 +235,6 @@ def test_or_combination(self): assert params == ["%kernel%", "%user%"] -class TestIn: - def test_to_sql_single_value(self): - cond = In("status", ["active"]) - sql, params = cond.to_sql() - assert sql == "status IN (?)" - assert params == ["active"] - - def test_to_sql_multiple_values(self): - cond = In("status", ["active", "pending", "running"]) - sql, params = cond.to_sql() - assert sql == "status IN (?, ?, ?)" - assert params == ["active", "pending", "running"] - - def test_to_sql_int_values(self): - cond = In("device_id", [0, 1, 2]) - sql, params = cond.to_sql() - assert sql == "device_id IN (?, ?, ?)" - assert params == [0, 1, 2] - - -class TestLike: - def test_to_sql(self): - cond = Like("name", "%kernel%") - sql, params = cond.to_sql() - assert sql == "name LIKE ?" - assert params == ["%kernel%"] - - class TestAnd: def test_empty_conditions(self): cond = And([]) @@ -278,11 +249,13 @@ def test_single_condition(self): assert params == [1] def test_multiple_conditions(self): - cond = And([ - Equal("a", 1), - GreaterThan("b", 2), - LessThan("c", 3), - ]) + cond = And( + [ + Equal("a", 1), + GreaterThan("b", 2), + LessThan("c", 3), + ] + ) sql, params = cond.to_sql() assert "(a = ?)" in sql assert "(b > ?)" in sql @@ -306,10 +279,12 @@ def test_empty_conditions(self): assert params == [] def test_multiple_conditions(self): - cond = Or([ - Equal("status", "active"), - Equal("status", "pending"), - ]) + cond = Or( + [ + Equal("status", "active"), + Equal("status", "pending"), + ] + ) sql, params = cond.to_sql() assert "(status = ?)" in sql assert "OR" in sql @@ -337,14 +312,18 @@ def test_and_or_mixed(self): assert params == [1, 2, 3] def test_complex_nested(self): - inner_and = And([ - Equal("status", "active"), - GreaterThan("size", 100), - ]) - inner_or = Or([ - Equal("type", "malloc"), - Equal("type", "cudaMalloc"), - ]) + inner_and = And( + [ + Equal("status", "active"), + GreaterThan("size", 100), + ] + ) + inner_or = Or( + [ + Equal("type", "malloc"), + Equal("type", "cudaMalloc"), + ] + ) combined = inner_and & inner_or sql, params = combined.to_sql() diff --git a/tests/test_query_config.py b/tests/test_query_config.py index 6a1df5e..35771ba 100644 --- a/tests/test_query_config.py +++ b/tests/test_query_config.py @@ -73,9 +73,7 @@ def test_validate_params(self): name="test", parameters={ "min_size": QueryParameter(name="min_size", type="int", default=0), - "required_param": QueryParameter( - name="required_param", type="str", required=True - ), + "required_param": QueryParameter(name="required_param", type="str", required=True), }, ) params = {"required_param": "value", "min_size": "100"} @@ -87,9 +85,7 @@ def test_validate_params_missing_required(self): template = QueryTemplate( name="test", parameters={ - "required_param": QueryParameter( - name="required_param", type="str", required=True - ), + "required_param": QueryParameter(name="required_param", type="str", required=True), }, ) with pytest.raises(ValueError): diff --git a/tests/test_query_mapper.py b/tests/test_query_mapper.py index 2188078..ccd77b4 100644 --- a/tests/test_query_mapper.py +++ b/tests/test_query_mapper.py @@ -129,6 +129,7 @@ def test_map_results(self): def test_register_type_converter(self): from pt_snap_cli.query.mapper import _default_mapper + register_type_converter("test_type", str.upper) row = {"value": "hello"} @@ -139,6 +140,7 @@ def test_register_type_converter(self): def test_register_model_factory(self): from pt_snap_cli.query.mapper import _default_mapper + class TestModel: def __init__(self, data): self.value = data["value"] diff --git a/tests/test_query_registry.py b/tests/test_query_registry.py index 1397902..c514620 100644 --- a/tests/test_query_registry.py +++ b/tests/test_query_registry.py @@ -1,14 +1,13 @@ """Tests for query registry.""" - -from pt_snap_cli.query.config import QueryTemplate, QueryParameter +from pt_snap_cli.query.config import QueryParameter, QueryTemplate from pt_snap_cli.query.registry import ( QueryRegistry, get_query, + get_template_info, list_queries, list_queries_with_details, register_query, - get_template_info, ) @@ -81,21 +80,17 @@ def test_list_queries_function(self): def test_list_queries_with_details(self): template1 = QueryTemplate( - name="detailed_query1", - description="First detailed query", - query="SELECT 1" + name="detailed_query1", description="First detailed query", query="SELECT 1" ) template2 = QueryTemplate( - name="detailed_query2", - description="Second detailed query", - query="SELECT 2" + name="detailed_query2", description="Second detailed query", query="SELECT 2" ) register_query(template1) register_query(template2) details = list_queries_with_details() assert len(details) >= 2 - + found_q1 = False found_q2 = False for detail in details: @@ -105,7 +100,7 @@ def test_list_queries_with_details(self): elif detail["name"] == "detailed_query2": assert detail["description"] == "Second detailed query" found_q2 = True - + assert found_q1 and found_q2 def test_get_template_info(self): @@ -120,20 +115,20 @@ def test_get_template_info(self): type="int", default=0, required=False, - description="Device ID to filter" + description="Device ID to filter", ), "min_size": QueryParameter( name="min_size", type="int", default=None, required=True, - description="Minimum block size" - ) + description="Minimum block size", + ), }, output_schema=[ {"column": "block_id", "type": "int"}, - {"column": "size", "type": "int"} - ] + {"column": "size", "type": "int"}, + ], ) register_query(template) @@ -159,7 +154,7 @@ def test_get_template_info_without_parameters(self): template = QueryTemplate( name="simple_query", description="Simple query without parameters", - query="SELECT COUNT(*) FROM blocks" + query="SELECT COUNT(*) FROM blocks", ) register_query(template) @@ -176,7 +171,7 @@ def test_registry_singleton(self): def test_registry_reset(self): register_query(QueryTemplate(name="test", query="SELECT 1")) assert get_query("test") is not None - + QueryRegistry.reset() new_registry = QueryRegistry() assert new_registry.get("test") is None