diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 83b3fa1..5891694 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -97,7 +97,7 @@ so no DataMasque server is required. ### Integration tests `tests/integration/` hits a real DataMasque instance to catch the bugs unit tests can't — -ruleset namespace collisions, +a database and a file ruleset sharing a name, delete targeting, server-state resolution, and the full `run start → retry → logs --follow` lifecycle. diff --git a/README.md b/README.md index 8934bfe..f28ccf1 100644 --- a/README.md +++ b/README.md @@ -108,6 +108,28 @@ For instances with self-signed or expired TLS certificates pass `--insecure` to `dm auth login` to persist the toggle on the profile, or set `DATAMASQUE_VERIFY_SSL=false` to skip verification per call. +## Projects + +Every connection, ruleset, library, discovery config, seed, file and table reference belongs to one project. +This CLI needs a DataMasque version with projects (v3.26.22.0 or later); use an earlier CLI release with older versions. + +- `--project` takes a project name (any case) or its numeric ID. +- List commands show each resource's project, and `--project` lists only that project's resources + (plus the built-in seeds, for `dm seeds list`). +- Create, upload and validate commands put the resource in the `--project` project. + Without `--project`, a create updates the resource of that name in the one project that has it + (for rulesets and discovery configs, the one of the same type). + Otherwise they use the instance's only project, and fail asking for one when there are several. +- Get, update and delete commands find a resource by name in any project. + When the name exists in more than one project they fail asking for `--project`. + +```console +dm rulesets list --project Finance +dm rulesets create --name customers --file rules.yaml --type database --project Finance +dm seeds upload names.csv --project Finance +dm run start -c finance_db -r customers --project Finance +``` + ## Commands ### Authentication @@ -148,9 +170,11 @@ dm rulesets generate --file request.json # Generate from schema dm rulesets generate --file req.json -o out.yaml # Generate to file dm rulesets validate --file rules.yaml --type database|file # Validate against server (YAML under 60 KiB) dm rulesets status # Validation status; poll after creating YAML of 60 KiB+ -dm rulesets export-bundle -o bundle.zip # Export rulesets + libraries + seeds +dm rulesets export-bundle -o bundle.zip # Export rulesets + libraries, by project +dm rulesets export-bundle -o bundle.zip --include-seed-files # Also bundle the custom seed files they use dm rulesets import-bundle --file bundle.zip # Import a previously exported bundle dm rulesets import-bundle -f bundle.zip --overwrite-rulesets --overwrite-libraries # Replace existing entries +dm rulesets import-bundle -f bundle.zip --fallback-project # Project for items filed under none ``` ### Ruleset libraries @@ -160,11 +184,11 @@ dm libraries list # List all libraries dm libraries get # Show library details dm libraries get --yaml # Print raw YAML only dm libraries create --name --file lib.yaml # Create/update from file -dm libraries create --name --file lib.yaml --namespace pii # With namespace +dm libraries create --name --file lib.yaml --project pii # In a given project dm libraries delete # Delete a library dm libraries validate # Re-validate against current server schema dm libraries status # Validation status; poll after creating YAML of 60 KiB+ -dm libraries usage # Show rulesets using it +dm libraries usage # Show rulesets using it, with their projects ``` ### Table references @@ -180,6 +204,34 @@ dm table-references update --delimiter ';' --null-string NULL # Any CS dm table-references delete # Delete a table reference ``` +### Projects + +```console +dm projects list # id, name, description, created +dm projects list --include-deleted # Adds deleted projects, with a deleted column +dm projects get # Show a project's details +dm projects create --name --description "" +dm projects update --name # Rename; --description changes the description +dm projects delete --to # Move every resource to the --to project, then delete +dm projects delete --to --check # Only list what would stop the delete +``` + +Creating, renaming and deleting projects needs an admin user. +Renaming makes rulesets and configurations that import one of the project's libraries by the old project name invalid. + +### Moving resources + +```console +dm resources move --project Finance --to Archive # Every resource in Finance +dm resources move customers orders --type rulesets --to Archive # Rulesets with these exact names, from any project +dm resources move --search payroll --to HR --check # Only list the matches and what would stop them moving +``` + +Resources move with their files and runs. `--project`, `--type`, `--search` and names combine; pass at least one. +All of the resources move, or none do. A resource that clashes with the destination (same name, or a file in the way) +stops the move, and the command exits with the `conflict` code, listing each one. A resource already in the +destination stays there, and the others move. + ### In-flight masking The IFM service runs alongside the admin server, @@ -260,11 +312,11 @@ The same library can be imported by both database and file discovery configs. ```console dm discover libraries list -dm discover libraries get [--namespace org] [--yaml] -dm discover libraries create --name --namespace org -f lib.yaml -dm discover libraries delete [--namespace org] [--force] # --force if imported by configs -dm discover libraries validate -f lib.yaml -dm discover libraries status [--namespace org] +dm discover libraries get [--project org] [--yaml] +dm discover libraries create --name --project org -f lib.yaml +dm discover libraries delete [--project org] [--force] # --force if imported by configs +dm discover libraries validate -f lib.yaml [--project org] +dm discover libraries status [--project org] ``` ### Seeds diff --git a/claude-skills/datamasque-cli/skills/datamasque-cli/SKILL.md b/claude-skills/datamasque-cli/skills/datamasque-cli/SKILL.md index 15e00d6..6495103 100644 --- a/claude-skills/datamasque-cli/skills/datamasque-cli/SKILL.md +++ b/claude-skills/datamasque-cli/skills/datamasque-cli/SKILL.md @@ -54,12 +54,26 @@ Pass repeated `--options key=value` for server-side knobs ## Idioms and gotchas -- **Ruleset namespaces.** `database` and `file` rulesets share a name - namespace, so `customers` can exist in both. `dm run start` reads the +- **Database and file rulesets.** A `database` and a `file` ruleset can + share a name, so `customers` can exist as both. `dm run start` reads the source connection's type and picks the matching ruleset automatically. For `get` / `create` / `delete`, pass `--type database|file` only when two rows share the name and you need to disambiguate. +- **Projects.** Every resource belongs to one project, and names are unique + per project (per project and type for rulesets and discovery configs). Lists show each resource's project, and `--project ` + narrows a list to one project. A create with no `--project` updates the + resource of that name in the one project that has it (same type, for + rulesets and discovery configs). Otherwise a create or upload with no + `--project` goes into the instance's only project, and fails with + `ambiguous` when there are several. A get or delete fails with `ambiguous` when the name + exists in two projects; pass `--project` to pick one. + `dm projects` creates, renames and deletes projects (delete needs `--to`, the + project that takes its resources). `dm resources move --to ` moves + resources selected by `--project`, `--type`, `--search` or exact names; it + moves nothing and exits `conflict` when any of them clashes with the + destination. Add `--check` to only preview. + - **File masking needs a destination.** Database masking is in-place; file masking writes through to a destination connection and fails with `invalid_input` without `--destination`. diff --git a/claude-skills/ruleset-builder/skills/ruleset-builder/SKILL.md b/claude-skills/ruleset-builder/skills/ruleset-builder/SKILL.md index 7f56bce..23ac241 100644 --- a/claude-skills/ruleset-builder/skills/ruleset-builder/SKILL.md +++ b/claude-skills/ruleset-builder/skills/ruleset-builder/SKILL.md @@ -97,7 +97,7 @@ masks: ### Output format -`Global/RuleLib` below is a placeholder for `/` — substitute the operator's real values, and create the library with `dm libraries create` before running the ruleset. +`Global/RuleLib` below is a placeholder for `/` — substitute the operator's real values, and create the library with `dm libraries create` before running the ruleset. ```yaml version: '1.0' diff --git a/claude-skills/ruleset-builder/skills/ruleset-builder/references/ruleset-libraries-guide.md b/claude-skills/ruleset-builder/skills/ruleset-builder/references/ruleset-libraries-guide.md index b845b5e..99342ea 100644 --- a/claude-skills/ruleset-builder/skills/ruleset-builder/references/ruleset-libraries-guide.md +++ b/claude-skills/ruleset-builder/skills/ruleset-builder/references/ruleset-libraries-guide.md @@ -8,10 +8,10 @@ Define masking logic once, reuse it everywhere. ```bash dm libraries list # List all libraries -dm libraries get [--namespace ] [--yaml] # Show details or YAML -dm libraries create --name --file lib.yml [--namespace ] -dm libraries delete [--namespace ] [--force] -dm libraries usage [--namespace ] # Which rulesets use it +dm libraries get [--project

] [--yaml] # Show details or YAML +dm libraries create --name --file lib.yml [--project

] +dm libraries delete [--project

] [--force] +dm libraries usage [--project

] # Which rulesets use it ``` ## Library Structure @@ -78,8 +78,8 @@ other: Rulesets reference library content using `$ref`: ``` -$ref: "/#

/" -$ref: "#
/" # No namespace +$ref: "/#
/" +$ref: "#
/" # The ruleset's own project $ref: "#
//" # Nested access $ref: "#
/0" # Array index ``` diff --git a/claude-skills/ruleset-builder/skills/ruleset-builder/references/ruleset-yaml-reference.md b/claude-skills/ruleset-builder/skills/ruleset-builder/references/ruleset-yaml-reference.md index c7f20af..0f29528 100644 --- a/claude-skills/ruleset-builder/skills/ruleset-builder/references/ruleset-yaml-reference.md +++ b/claude-skills/ruleset-builder/skills/ruleset-builder/references/ruleset-yaml-reference.md @@ -187,12 +187,12 @@ See `ruleset-libraries-guide.md` for full details. ```yaml imports: - - namespace/library_name + - project/library_name tasks: - type: mask_table table: users key: id rules: - - $ref: "namespace/library_name#database_rules/email_rule" + - $ref: "project/library_name#database_rules/email_rule" ``` diff --git a/pyproject.toml b/pyproject.toml index 79ae0d5..fae18c5 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -13,7 +13,7 @@ dependencies = [ "typer>=0.16.0,<1", "rich>=13.8", "tomli-w>=1.0.0,<2", - "datamasque-python>=1.2.5,<2", + "datamasque-python>=1.6.0,<2", "pydantic>=2.5,<3", ] classifiers = [ diff --git a/src/datamasque_cli/client.py b/src/datamasque_cli/client.py index adab959..6aba6ba 100644 --- a/src/datamasque_cli/client.py +++ b/src/datamasque_cli/client.py @@ -16,6 +16,7 @@ from datamasque_cli.config import Config, Profile, load_config from datamasque_cli.errors import ErrorCode, abort +from datamasque_cli.projects import filter_by_project, require_single_or_abort, resolve_optional_project ENV_URL = "DATAMASQUE_URL" ENV_USERNAME = "DATAMASQUE_USERNAME" @@ -215,10 +216,24 @@ def get_ifm_client(profile_name: str | None = None) -> DataMasqueIfmClient: return client -def resolve_connection(client: DataMasqueClient, name_or_id: str) -> ConnectionConfig: - """Resolve a connection by name or ID via the connection listing, aborting when not found.""" +def resolve_connection(client: DataMasqueClient, name_or_id: str, project: str | None = None) -> ConnectionConfig: + """ + Resolve a connection by name, in the project `--project` names if given, else by ID. + + Aborts when nothing matches, or when the name matches connections in more than one project. + """ connections = client.list_connections() - match = next((c for c in connections if c.name == name_or_id or str(c.id) == name_or_id), None) - if match is None: - abort(f"Connection '{name_or_id}' not found.", code=ErrorCode.NOT_FOUND) - return match + by_name = filter_by_project( + [c for c in connections if c.name == name_or_id], resolve_optional_project(client, project) + ) + if not by_name: + by_id = next((c for c in connections if str(c.id) == name_or_id), None) + if by_id is not None: + return by_id + return require_single_or_abort( + client, + by_name, + f"Connection '{name_or_id}'", + describe=lambda c: f"id={c.id}", + hint="Pass --project, or the connection's id, to disambiguate.", + ) diff --git a/src/datamasque_cli/commands/connections.py b/src/datamasque_cli/commands/connections.py index a9b5506..4291035 100644 --- a/src/datamasque_cli/commands/connections.py +++ b/src/datamasque_cli/commands/connections.py @@ -23,9 +23,18 @@ from pydantic import ValidationError from datamasque_cli.client import get_client, resolve_connection -from datamasque_cli.errors import ErrorCode, abort, abort_api_error, confirm_or_abort +from datamasque_cli.errors import ErrorCode, abort, abort_api_error, confirm_or_abort, require_id_or_abort from datamasque_cli.fileio import read_json_object_or_abort from datamasque_cli.output import print_success, redact_sensitive_fields, render_output +from datamasque_cli.projects import ( + PROJECT_OPTION_HELP, + filter_by_project, + get_project_names_by_reference, + get_same_name_project_help, + project_label, + resolve_create_project, + resolve_optional_project, +) class ConnectionType(StrEnum): @@ -92,18 +101,21 @@ def _parse_connection_type(raw: str) -> ConnectionType: @app.command("list") def list_connections( + project: str | None = typer.Option(None, "--project", help=PROJECT_OPTION_HELP), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), is_json: bool = typer.Option(False, "--json", help="Output as JSON"), ) -> None: - """List all configured connections.""" + """List all configured connections, or those in one project.""" client = get_client(profile) - connections = client.list_connections() + connections = filter_by_project(client.list_connections(), resolve_optional_project(client, project)) + names = get_project_names_by_reference(client) data = [] for conn in connections: class_name = type(conn).__name__ entry: dict[str, object] = { "id": conn.id, + "project": project_label(names, conn.project), "name": conn.name, "type": class_name.replace("ConnectionConfig", "").replace("Config", ""), "role": _format_role(conn), @@ -113,26 +125,24 @@ def list_connections( render_output( data, is_json=is_json, - columns=["id", "name", "type", "role"], + columns=["id", "project", "name", "type", "role"], title="Connections", ) @app.command("get") def get_connection( - name: str = typer.Argument(help="Connection name"), + name: str = typer.Argument(help="Connection name or ID"), + project: str | None = typer.Option(None, "--project", help=get_same_name_project_help("connections")), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), is_json: bool = typer.Option(False, "--json", help="Output as JSON"), ) -> None: """Show details for a specific connection.""" client = get_client(profile) - connections = client.list_connections() - - match = next((c for c in connections if c.name == name), None) - if match is None: - abort(f"Connection '{name}' not found.", code=ErrorCode.NOT_FOUND) + match = resolve_connection(client, name, project) data = redact_sensitive_fields(match.model_dump()) + data["project"] = project_label(get_project_names_by_reference(client), match.project) render_output(data, is_json=is_json, title=f"Connection: {name}") @@ -154,6 +164,7 @@ def create_connection( is_source: bool = typer.Option(False, "--source", help="Is a file mask source"), is_destination: bool = typer.Option(False, "--destination", help="Is a file mask destination"), bucket: str | None = typer.Option(None, help="S3 bucket name"), + project: str | None = typer.Option(None, "--project", help=PROJECT_OPTION_HELP), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), ) -> None: """Create or update a connection. @@ -178,9 +189,8 @@ def create_connection( dm connections create --file databricks.json """ client = get_client(profile) - if file is not None: - _create_from_file(client, file) + _create_from_file(client, file, project) return if name is None or conn_type is None: @@ -201,13 +211,14 @@ def create_connection( is_destination=is_destination, bucket=bucket, ) + config.project = resolve_create_project(client, project, [c for c in client.list_connections() if c.name == name]) client.create_or_update_connection(config) print_success(f"Connection '{name}' created/updated.") -def _create_from_file(client: DataMasqueClient, file: Path) -> None: - """Create a connection from a JSON file.""" +def _create_from_file(client: DataMasqueClient, file: Path, project: str | None) -> None: + """Create a connection from a JSON file, in the project `--project` names when given.""" data = read_json_object_or_abort(file) raw_type = data.pop("type", "database") if not isinstance(raw_type, str): @@ -223,6 +234,9 @@ def _create_from_file(client: DataMasqueClient, file: Path) -> None: config = klass(**data) except ValidationError as exc: abort(f"{file} does not match the expected format: {exc}", code=ErrorCode.INVALID_INPUT) + config.project = resolve_create_project( + client, project, [c for c in client.list_connections() if c.name == config.name] + ) client.create_or_update_connection(config) print_success(f"Connection '{config.name}' created/updated.") @@ -293,6 +307,7 @@ def _build_connection_config( @app.command("test") def test_connection( name: str = typer.Argument(help="Connection name or ID to test"), + project: str | None = typer.Option(None, "--project", help=get_same_name_project_help("connections")), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), ) -> None: """Verify a connection can reach its target. @@ -302,7 +317,7 @@ def test_connection( success, a warning, or a hard failure. """ client = get_client(profile) - match = resolve_connection(client, name) + match = resolve_connection(client, name, project) try: response = client.make_request("POST", f"/api/connections/{match.id}/test/", data={}) @@ -320,6 +335,7 @@ def test_connection( @app.command("update") def update_connection( name: str = typer.Argument(help="Connection name or ID to update"), + project: str | None = typer.Option(None, "--project", help=get_same_name_project_help("connections")), host: str | None = typer.Option(None, help="New database host"), port: str | None = typer.Option(None, help="New database port"), database: str | None = typer.Option(None, help="New database name"), @@ -335,7 +351,7 @@ def update_connection( references it stays intact. Pass only the fields that should change. """ client = get_client(profile) - match = resolve_connection(client, name) + match = resolve_connection(client, name, project) updates: dict[str, object] = { key: value @@ -364,17 +380,17 @@ def update_connection( @app.command("delete") def delete_connection( - name: str = typer.Argument(help="Connection name to delete"), + name: str = typer.Argument(help="Connection name or ID to delete"), + project: str | None = typer.Option(None, "--project", help=get_same_name_project_help("connections")), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), is_confirmed: bool = typer.Option(False, "--yes", "-y", help="Skip confirmation"), ) -> None: """Delete a connection by name.""" client = get_client(profile) - if not any(c.name == name for c in client.list_connections()): - abort(f"Connection '{name}' not found.", code=ErrorCode.NOT_FOUND) + match = resolve_connection(client, name, project) if not is_confirmed: confirm_or_abort(f"Delete connection '{name}'?") - client.delete_connection_by_name_if_exists(name) + client.delete_connection_by_id_if_exists(require_id_or_abort(match.id, f"connection '{name}'")) print_success(f"Connection '{name}' deleted.") diff --git a/src/datamasque_cli/commands/discovery.py b/src/datamasque_cli/commands/discovery.py index 4094d03..61beb36 100644 --- a/src/datamasque_cli/commands/discovery.py +++ b/src/datamasque_cli/commands/discovery.py @@ -34,6 +34,12 @@ ) from datamasque_cli.fileio import write_bytes_or_abort, write_text_or_abort from datamasque_cli.output import print_info, print_json, print_success, render_output, should_emit_json +from datamasque_cli.projects import ( + filter_by_project, + get_named_resources_project_help, + require_single_or_abort, + resolve_optional_project, +) app = typer.Typer(help="Data discovery operations.", no_args_is_help=True) app.add_typer(discovery_configs.app, name="configs") @@ -80,20 +86,22 @@ def _write_or_echo(content: str, output: Path | None, success_label: str) -> Non def _resolve_discovery_config_id( - client: DataMasqueClient, name: str, expected_type: DiscoveryConfigType + client: DataMasqueClient, name: str, expected_type: DiscoveryConfigType, project: str | None ) -> DiscoveryConfigId: """Resolve a discovery config name to its UUID, requiring it to be of `expected_type`. - Config names are unique per type, so name plus type identifies at most one config. + Config names are unique per type within a project, so name, type and project identify at most one config. """ - match = client.get_discovery_config_by_name(name, expected_type) - if match is not None: + named_configs = filter_by_project( + [c for c in client.list_discovery_configs() if c.name == name], resolve_optional_project(client, project) + ) + configs_of_type = [c for c in named_configs if c.config_type is expected_type] + if configs_of_type: + match = require_single_or_abort(client, configs_of_type, f"Discovery config '{name}'") return require_id_or_abort(match.id, f"discovery config '{name}'") - other_type = ( - DiscoveryConfigType.file if expected_type is DiscoveryConfigType.database else DiscoveryConfigType.database - ) - if client.get_discovery_config_by_name(name, other_type) is not None: + if named_configs: + other_type = named_configs[0].config_type abort( f"Discovery config '{name}' exists as {other_type.value}, " f"but {expected_type.value} discovery needs a {expected_type.value} config.", @@ -108,6 +116,9 @@ def schema_discovery( config: str | None = typer.Option( None, "--config", "-c", help="Run with a saved database discovery config (configurable discovery)" ), + project: str | None = typer.Option( + None, "--project", help=get_named_resources_project_help("connection and config") + ), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), is_json: bool = typer.Option(False, "--json", help="Output as JSON"), ) -> None: @@ -118,11 +129,11 @@ def schema_discovery( (poll with `dm run status `). """ client = get_client(profile) - conn_id = str(resolve_connection(client, connection).id) + conn_id = str(resolve_connection(client, connection, project).id) try: if config is not None: - config_id = _resolve_discovery_config_id(client, config, DiscoveryConfigType.database) + config_id = _resolve_discovery_config_id(client, config, DiscoveryConfigType.database, project) from_config = SchemaDiscoveryFromConfigRequest(connection=ConnectionId(conn_id), discovery_config=config_id) run_id = client.start_schema_discovery_run_from_config(from_config) config_source = f"config '{config}'" @@ -151,6 +162,9 @@ def start_file_discovery( config: str | None = typer.Option( None, "--config", "-c", help="Run with a saved file discovery config (configurable discovery)" ), + project: str | None = typer.Option( + None, "--project", help=get_named_resources_project_help("connection and config") + ), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), is_json: bool = typer.Option(False, "--json", help="Output as JSON"), ) -> None: @@ -160,11 +174,11 @@ def start_file_discovery( (poll with `dm run status `). """ client = get_client(profile) - conn_id = str(resolve_connection(client, connection).id) + conn_id = str(resolve_connection(client, connection, project).id) try: if config is not None: - config_id = _resolve_discovery_config_id(client, config, DiscoveryConfigType.file) + config_id = _resolve_discovery_config_id(client, config, DiscoveryConfigType.file, project) from_config = FileDataDiscoveryFromConfigRequest( connection=ConnectionId(conn_id), discovery_config=config_id ) diff --git a/src/datamasque_cli/commands/discovery_config_libraries.py b/src/datamasque_cli/commands/discovery_config_libraries.py index b486622..4c6b8de 100644 --- a/src/datamasque_cli/commands/discovery_config_libraries.py +++ b/src/datamasque_cli/commands/discovery_config_libraries.py @@ -6,36 +6,53 @@ from pathlib import Path import typer +from datamasque.client import DataMasqueClient from datamasque.client.exceptions import DataMasqueApiError from datamasque.client.models.discovery_config_library import DiscoveryConfigLibrary from datamasque.client.models.status import ValidationErrorDetails from datamasque_cli.client import get_client -from datamasque_cli.errors import ErrorCode, abort, abort_api_error, abort_if_invalid, confirm_or_abort +from datamasque_cli.errors import abort_api_error, abort_if_invalid, confirm_or_abort from datamasque_cli.fileio import read_text_or_abort from datamasque_cli.output import print_success, print_warning, render_output +from datamasque_cli.projects import ( + PROJECT_OPTION_HELP, + PROJECT_VALIDATE_HELP, + filter_by_project, + get_project_names_by_reference, + project_label, + require_single_or_abort, + resolve_create_project, + resolve_optional_project, + resolve_target_project, +) app = typer.Typer(help="Manage discovery config libraries (configurable discovery).", no_args_is_help=True) -def _format_library_label(name: str, namespace: str) -> str: - """Render a library's display label as `namespace/name`, or bare `name` in the default namespace.""" - return f"{namespace}/{name}" if namespace else name +def _find_library(client: DataMasqueClient, name: str, project: str | None) -> DiscoveryConfigLibrary: + """Return the library named `name`, with its YAML, in `project` or in the one project that has it.""" + matches = [lib for lib in client.list_discovery_config_libraries() if lib.name == name] + matches = filter_by_project(matches, resolve_optional_project(client, project)) + found = require_single_or_abort(client, matches, f"Discovery config library '{name}'") + return client.get_discovery_config_library(found.id) @app.command("list") def list_libraries( + project: str | None = typer.Option(None, "--project", help=PROJECT_OPTION_HELP), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), is_json: bool = typer.Option(False, "--json", help="Output as JSON"), ) -> None: - """List all discovery config libraries.""" + """List all discovery config libraries, or those in one project.""" client = get_client(profile) - libraries = client.list_discovery_config_libraries() + libraries = filter_by_project(client.list_discovery_config_libraries(), resolve_optional_project(client, project)) + names = get_project_names_by_reference(client) data = [ { "id": lib.id, - "namespace": lib.namespace or "", + "project": project_label(names, lib.project), "name": lib.name, "valid": lib.is_valid.value if lib.is_valid else "unknown", "used_by": lib.usage_count, @@ -46,7 +63,7 @@ def list_libraries( render_output( data, is_json=is_json, - columns=["id", "namespace", "name", "valid", "used_by"], + columns=["id", "project", "name", "valid", "used_by"], title="Discovery Config Libraries", ) @@ -54,20 +71,14 @@ def list_libraries( @app.command("get") def get_library( name: str = typer.Argument(help="Library name"), - namespace: str = typer.Option("", "--namespace", "-n", help="Library namespace"), + project: str | None = typer.Option(None, "--project", help=PROJECT_OPTION_HELP), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), is_yaml: bool = typer.Option(False, "--yaml", help="Output raw YAML content only"), is_json: bool = typer.Option(False, "--json", help="Output as JSON"), ) -> None: """Show a discovery config library's details or YAML content.""" client = get_client(profile) - lib = client.get_discovery_config_library_by_name(name, namespace) - - if lib is None: - abort( - f"Discovery config library '{_format_library_label(name, namespace)}' not found.", - code=ErrorCode.NOT_FOUND, - ) + lib = _find_library(client, name, project) if is_yaml: typer.echo(lib.yaml) @@ -75,7 +86,7 @@ def get_library( data: dict[str, object] = { "id": lib.id, - "namespace": lib.namespace, + "project": project_label(get_project_names_by_reference(client), lib.project), "name": lib.name, "valid": lib.is_valid.value if lib.is_valid else "unknown", "used_by": lib.usage_count, @@ -89,22 +100,25 @@ def get_library( def create_library( name: str = typer.Option(..., help="Library name"), file: Path = typer.Option(..., "--file", "-f", help="Path to YAML library file", exists=True, readable=True), - namespace: str = typer.Option("", "--namespace", "-n", help="Library namespace"), + project: str | None = typer.Option(None, "--project", help=PROJECT_OPTION_HELP), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), ) -> None: """Create or update a discovery config library from a YAML file.""" yaml_content = read_text_or_abort(file) client = get_client(profile) - library = DiscoveryConfigLibrary(name=name, namespace=namespace, yaml=yaml_content) + existing = [lib for lib in client.list_discovery_config_libraries() if lib.name == name] + library = DiscoveryConfigLibrary( + name=name, project=resolve_create_project(client, project, existing), yaml=yaml_content + ) client.create_or_update_discovery_config_library(library) - print_success(f"Discovery config library '{_format_library_label(name, namespace)}' created/updated.") + print_success(f"Discovery config library '{name}' created/updated.") @app.command("delete") def delete_library( name: str = typer.Argument(help="Library name to delete"), - namespace: str = typer.Option("", "--namespace", "-n", help="Library namespace"), + project: str | None = typer.Option(None, "--project", help=PROJECT_OPTION_HELP), force: bool = typer.Option(False, "--force", help="Force delete even if imported by discovery configs"), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), is_confirmed: bool = typer.Option(False, "--yes", "-y", help="Skip confirmation"), @@ -114,42 +128,42 @@ def delete_library( If the library is imported by any discovery configs, the server rejects the delete unless --force is passed. """ - label = _format_library_label(name, namespace) client = get_client(profile) - if client.get_discovery_config_library_by_name(name, namespace) is None: - abort(f"Discovery config library '{label}' not found.", code=ErrorCode.NOT_FOUND) + lib = _find_library(client, name, project) if not is_confirmed: - confirm_or_abort(f"Delete discovery config library '{label}'?") + confirm_or_abort(f"Delete discovery config library '{name}'?") try: - client.delete_discovery_config_library_by_name_if_exists(name, namespace, force=force) + client.delete_discovery_config_library_by_id_if_exists(lib.id, force=force) except DataMasqueApiError as exc: abort_api_error( - f"Failed to delete discovery config library '{label}'", + f"Failed to delete discovery config library '{name}'", exc, conflict_hint="Re-run with --force to delete it and mark the dependent configs invalid.", ) - print_success(f"Discovery config library '{label}' deleted.") + print_success(f"Discovery config library '{name}' deleted.") @app.command("validate") def validate_library( file: Path = typer.Option(..., "--file", "-f", help="Path to YAML library file", exists=True, readable=True), + project: str | None = typer.Option(None, "--project", help=PROJECT_VALIDATE_HELP), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), ) -> None: """Validate a discovery config library YAML file against the DataMasque server. - Creates a temporary library to trigger server-side validation, + Creates a temporary library in the project to trigger server-side validation, then deletes it. Reports any validation errors. """ yaml_content = read_text_or_abort(file) temp_name = f"__dm_cli_validate_{uuid.uuid4().hex}" client = get_client(profile) - library = DiscoveryConfigLibrary(name=temp_name, yaml=yaml_content) + target = resolve_target_project(client, project) + library = DiscoveryConfigLibrary(name=temp_name, project=target.reference, yaml=yaml_content) try: created = client.create_discovery_config_library(library) @@ -173,23 +187,17 @@ def validate_library( @app.command("status") def show_library_status( name: str = typer.Argument(help="Library name"), - namespace: str = typer.Option("", "--namespace", "-n", help="Library namespace"), + project: str | None = typer.Option(None, "--project", help=PROJECT_OPTION_HELP), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), is_json: bool = typer.Option(False, "--json", help="Output as JSON"), ) -> None: """Show a discovery config library's validation status.""" client = get_client(profile) - lib = client.get_discovery_config_library_by_name(name, namespace) - - if lib is None: - abort( - f"Discovery config library '{_format_library_label(name, namespace)}' not found.", - code=ErrorCode.NOT_FOUND, - ) + lib = _find_library(client, name, project) status = lib.is_valid.value if lib.is_valid else "unknown" data: dict[str, object] = { - "namespace": lib.namespace, + "project": project_label(get_project_names_by_reference(client), lib.project), "name": lib.name, "status": status, "validation_error": lib.validation_error, diff --git a/src/datamasque_cli/commands/discovery_configs.py b/src/datamasque_cli/commands/discovery_configs.py index 98256bd..55d0c4b 100644 --- a/src/datamasque_cli/commands/discovery_configs.py +++ b/src/datamasque_cli/commands/discovery_configs.py @@ -26,6 +26,17 @@ write_text_or_abort, ) from datamasque_cli.output import print_info, print_success, print_warning, render_output +from datamasque_cli.projects import ( + PROJECT_OPTION_HELP, + PROJECT_VALIDATE_HELP, + filter_by_project, + get_project_names_by_reference, + get_same_name_project_help, + project_label, + resolve_create_project, + resolve_optional_project, + resolve_target_project, +) app = typer.Typer(help="Manage discovery configs (configurable discovery).", no_args_is_help=True) @@ -34,24 +45,30 @@ def _find_by_name( client: DataMasqueClient, name: str, config_type: DiscoveryConfigType | None = None, + project: str | None = None, ) -> list[DiscoveryConfig]: - """Return all discovery configs matching `name`, optionally narrowed by `config_type`.""" + """Return all discovery configs matching `name`, optionally narrowed by `config_type` and `--project`.""" matches = [c for c in client.list_discovery_configs() if c.name == name] if config_type is not None: matches = [c for c in matches if c.config_type is config_type] - return matches + return filter_by_project(matches, resolve_optional_project(client, project)) -def _require_single_matched_config_or_abort(matched_configs: list[DiscoveryConfig], name: str) -> DiscoveryConfig: - """Return the single discovery config matching `name`, or abort asking for `--type`.""" +def _require_single_matched_config_or_abort( + client: DataMasqueClient, matched_configs: list[DiscoveryConfig], name: str +) -> DiscoveryConfig: + """Return the single discovery config matching `name`, or abort asking for `--type` or `--project`.""" if not matched_configs: abort(f"Discovery config '{name}' not found.", code=ErrorCode.NOT_FOUND) if len(matched_configs) > 1: - options = "\n ".join(f"id={c.id} type={c.config_type.value}" for c in matched_configs) + names = get_project_names_by_reference(client) + options = "\n ".join( + f"id={c.id} type={c.config_type.value} project={project_label(names, c.project)}" for c in matched_configs + ) abort( f"Multiple discovery configs named '{name}':\n {options}", code=ErrorCode.AMBIGUOUS, - hint="Pass --type database|file to disambiguate.", + hint="Pass --type database|file or --project to disambiguate.", ) return matched_configs[0] @@ -61,12 +78,14 @@ def list_configs( config_type: DiscoveryConfigType | None = typer.Option( None, "--type", "-t", help="Filter by type: database or file" ), + project: str | None = typer.Option(None, "--project", help=PROJECT_OPTION_HELP), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), is_json: bool = typer.Option(False, "--json", help="Output as JSON"), ) -> None: - """List all discovery configs.""" + """List all discovery configs, or those in one project.""" client = get_client(profile) - configs = client.list_discovery_configs() + configs = filter_by_project(client.list_discovery_configs(), resolve_optional_project(client, project)) + names = get_project_names_by_reference(client) if config_type is not None: configs = [c for c in configs if c.config_type is config_type] @@ -74,6 +93,7 @@ def list_configs( data = [ { "id": c.id, + "project": project_label(names, c.project), "name": c.name, "type": c.config_type.value, "valid": c.is_valid.value if c.is_valid else "unknown", @@ -81,7 +101,7 @@ def list_configs( for c in configs ] - render_output(data, is_json=is_json, columns=["id", "name", "type", "valid"], title="Discovery Configs") + render_output(data, is_json=is_json, columns=["id", "project", "name", "type", "valid"], title="Discovery Configs") @app.command("get") @@ -90,13 +110,14 @@ def get_config( config_type: DiscoveryConfigType | None = typer.Option( None, "--type", "-t", help="Required when two configs share a name" ), + project: str | None = typer.Option(None, "--project", help=get_same_name_project_help("configs")), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), is_yaml: bool = typer.Option(False, "--yaml", help="Output raw YAML content only"), is_json: bool = typer.Option(False, "--json", help="Output as JSON"), ) -> None: """Show a discovery config's details or YAML content.""" client = get_client(profile) - match = _require_single_matched_config_or_abort(_find_by_name(client, name, config_type), name) + match = _require_single_matched_config_or_abort(client, _find_by_name(client, name, config_type, project), name) config_id = require_id_or_abort(match.id, f"discovery config '{name}'") full = client.get_discovery_config(config_id) @@ -107,6 +128,7 @@ def get_config( data: dict[str, object] = { "id": full.id, + "project": project_label(get_project_names_by_reference(client), full.project), "name": full.name, "type": full.config_type.value, "valid": full.is_valid.value if full.is_valid else "unknown", @@ -151,6 +173,7 @@ def create_config( "Required when the config does not yet exist; defaults to the existing type on updates." ), ), + project: str | None = typer.Option(None, "--project", help=PROJECT_OPTION_HELP), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), ) -> None: """Create or update a discovery config from a YAML file. @@ -159,7 +182,7 @@ def create_config( type from; an update defaults to whatever the existing row is stored as. """ client = get_client(profile) - existing = _find_by_name(client, name) + existing = _find_by_name(client, name, project=project) if config_type is not None: resolved_type = config_type @@ -173,16 +196,22 @@ def create_config( hint="Pass --type database|file to create a new one.", ) else: - options = ", ".join(c.config_type.value for c in existing) + names = get_project_names_by_reference(client) + options = ", ".join(f"{c.config_type.value} in {project_label(names, c.project)}" for c in existing) abort( f"Multiple discovery configs named '{name}' ({options}).", code=ErrorCode.AMBIGUOUS, - hint="Pass --type database|file to pick which one to update.", + hint="Pass --type database|file or --project to pick which one to update.", ) yaml_content = read_text_or_abort(file) - config = DiscoveryConfig(name=name, yaml=yaml_content, config_type=resolved_type) + config = DiscoveryConfig( + name=name, + yaml=yaml_content, + config_type=resolved_type, + project=resolve_create_project(client, project, [c for c in existing if c.config_type is resolved_type]), + ) client.create_or_update_discovery_config(config) print_success(f"Discovery config '{name}' ({resolved_type.value}) created/updated.") @@ -193,12 +222,13 @@ def delete_config( config_type: DiscoveryConfigType | None = typer.Option( None, "--type", "-t", help="Required when two configs share a name" ), + project: str | None = typer.Option(None, "--project", help=get_same_name_project_help("configs")), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), is_confirmed: bool = typer.Option(False, "--yes", "-y", help="Skip confirmation"), ) -> None: """Delete a discovery config by name.""" client = get_client(profile) - match = _require_single_matched_config_or_abort(_find_by_name(client, name, config_type), name) + match = _require_single_matched_config_or_abort(client, _find_by_name(client, name, config_type, project), name) config_id = require_id_or_abort(match.id, f"discovery config '{name}'") if not is_confirmed: @@ -212,11 +242,12 @@ def delete_config( def validate_config( file: Path = typer.Option(..., "--file", "-f", help="Path to YAML config file", exists=True, readable=True), config_type: DiscoveryConfigType = typer.Option(..., "--type", "-t", help="Config type: database or file"), + project: str | None = typer.Option(None, "--project", help=PROJECT_VALIDATE_HELP), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), ) -> None: """Validate a discovery config YAML file against the DataMasque server. - Creates a temporary config to trigger server-side validation, + Creates a temporary config in the project to trigger server-side validation, then deletes it. Reports any validation errors. Note that configs over 60 KiB validate asynchronously and cannot be validated here. @@ -231,7 +262,8 @@ def validate_config( temp_name = f"__dm_cli_validate_{uuid.uuid4().hex}" client = get_client(profile) - config = DiscoveryConfig(name=temp_name, yaml=yaml_content, config_type=config_type) + target = resolve_target_project(client, project) + config = DiscoveryConfig(name=temp_name, yaml=yaml_content, config_type=config_type, project=target.reference) try: created = client.create_discovery_config(config) @@ -260,15 +292,17 @@ def show_config_status( config_type: DiscoveryConfigType | None = typer.Option( None, "--type", "-t", help="Required when two configs share a name" ), + project: str | None = typer.Option(None, "--project", help=get_same_name_project_help("configs")), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), is_json: bool = typer.Option(False, "--json", help="Output as JSON"), ) -> None: """Show a discovery config's validation status.""" client = get_client(profile) - match = _require_single_matched_config_or_abort(_find_by_name(client, name, config_type), name) + match = _require_single_matched_config_or_abort(client, _find_by_name(client, name, config_type, project), name) status = match.is_valid.value if match.is_valid else "unknown" data: dict[str, object] = { + "project": project_label(get_project_names_by_reference(client), match.project), "name": match.name, "type": match.config_type.value, "status": status, diff --git a/src/datamasque_cli/commands/files.py b/src/datamasque_cli/commands/files.py index 03bbd10..6d29485 100644 --- a/src/datamasque_cli/commands/files.py +++ b/src/datamasque_cli/commands/files.py @@ -8,8 +8,19 @@ from datamasque.client.models.files import DataMasqueFile, SnowflakeKeyFile from datamasque_cli.client import get_client -from datamasque_cli.errors import ErrorCode, abort, confirm_or_abort +from datamasque_cli.errors import confirm_or_abort from datamasque_cli.output import print_success, render_output +from datamasque_cli.projects import ( + PROJECT_OPTION_HELP, + PROJECT_UPLOAD_HELP, + filter_by_project, + get_project_names_by_reference, + get_same_name_project_help, + project_label, + require_single_or_abort, + resolve_optional_project, + resolve_target_project, +) app = typer.Typer(help="Manage uploaded files (Oracle wallets, Snowflake keys).", no_args_is_help=True) @@ -30,22 +41,26 @@ def _resolve_file_type(type_name: str) -> type[DataMasqueFile]: @app.command("list") def list_files( file_type: str = typer.Argument(help="File type: snowflake-key"), + project: str | None = typer.Option(None, "--project", help=PROJECT_OPTION_HELP), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), is_json: bool = typer.Option(False, "--json", help="Output as JSON"), ) -> None: - """List uploaded files of a given type.""" + """List uploaded files of a given type, or those in one project.""" klass = _resolve_file_type(file_type) client = get_client(profile) - files = client.list_files_of_type(klass) + target = resolve_optional_project(client, project) + files = client.list_files_of_type(klass, project=target.id if target else None) + names = get_project_names_by_reference(client) - data = [{"id": f.id, "name": f.name} for f in files] - render_output(data, is_json=is_json, columns=["id", "name"], title=f"Files ({file_type})") + data = [{"id": f.id, "project": project_label(names, f.project), "name": f.name} for f in files] + render_output(data, is_json=is_json, columns=["id", "project", "name"], title=f"Files ({file_type})") @app.command("delete") def delete_file( file_type: str = typer.Argument(help="File type: snowflake-key"), name: str = typer.Argument(help="File name"), + project: str | None = typer.Option(None, "--project", help=get_same_name_project_help("files")), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), is_confirmed: bool = typer.Option(False, "--yes", "-y", help="Skip confirmation"), ) -> None: @@ -53,9 +68,12 @@ def delete_file( klass = _resolve_file_type(file_type) client = get_client(profile) - match = client.get_file_of_type_by_name(klass, name) - if match is None: - abort(f"File '{name}' ({file_type}) not found.", code=ErrorCode.NOT_FOUND) + named_files = [f for f in client.list_files_of_type(klass) if f.name == name] + match = require_single_or_abort( + client, + filter_by_project(named_files, resolve_optional_project(client, project)), + f"File '{name}' ({file_type})", + ) if not is_confirmed: confirm_or_abort(f"Delete file '{name}' ({file_type})?") @@ -69,10 +87,12 @@ def upload_file( file_type: str = typer.Argument(help="File type: snowflake-key"), file: Path = typer.Option(..., "--file", "-f", help="Path to file", exists=True, readable=True), name: str = typer.Option(..., help="Name for the uploaded file"), + project: str | None = typer.Option(None, "--project", help=PROJECT_UPLOAD_HELP), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), ) -> None: """Upload a file.""" klass = _resolve_file_type(file_type) client = get_client(profile) - client.upload_file(klass, name, file) + target = resolve_target_project(client, project) + client.upload_file(klass, name, file, project=target.id) print_success(f"File '{name}' uploaded as {file_type}.") diff --git a/src/datamasque_cli/commands/projects.py b/src/datamasque_cli/commands/projects.py new file mode 100644 index 0000000..a20e59e --- /dev/null +++ b/src/datamasque_cli/commands/projects.py @@ -0,0 +1,158 @@ +"""Project management commands.""" + +from __future__ import annotations + +import typer +from datamasque.client import DataMasqueClient +from datamasque.client.exceptions import DataMasqueApiError, ProjectDeleteConflictError +from datamasque.client.models.project import Project, ProjectCreateRequest, ProjectUpdateRequest + +from datamasque_cli.client import get_client +from datamasque_cli.errors import ErrorCode, abort, abort_api_error, confirm_or_abort +from datamasque_cli.output import print_success, render_output +from datamasque_cli.projects import PROJECT_OPTION_HELP, find_named_project, get_named_project, resolve_project + +app = typer.Typer(help="Manage projects.", no_args_is_help=True) + +DELETE_CONFLICT_MESSAGE = "The project's resources cannot move to the destination project" + + +def _build_project_row(project: Project) -> dict[str, object]: + return { + "id": project.id, + "name": project.name, + "description": project.description, + "created": project.created, + } + + +def _find_project_for_get(client: DataMasqueClient, name_or_id: str) -> tuple[Project, bool]: + """ + Return the project `name_or_id` names, and whether it is deleted. + + A name resolves among the active projects only, because a deleted project can share an active project's name. + An id that no active project has also finds a deleted project, as `list --include-deleted` shows it. + """ + active = client.list_projects() + found = find_named_project(active, name_or_id) + if found is not None: + return found, False + + deleted = next( + (project for project in client.list_projects(include_archived=True) if str(project.id) == name_or_id), None + ) + if deleted is None: + abort(f"Project '{name_or_id}' not found.", code=ErrorCode.NOT_FOUND) + return deleted, True + + +@app.command("list") +def list_projects( + is_deleted_included: bool = typer.Option(False, "--include-deleted", help="Also list deleted projects"), + profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), + is_json: bool = typer.Option(False, "--json", help="Output as JSON"), +) -> None: + """List the active projects, or every project with --include-deleted.""" + client = get_client(profile) + columns = ["id", "name", "description", "created"] + if not is_deleted_included: + data = [_build_project_row(project) for project in client.list_projects()] + render_output(data, is_json=is_json, columns=columns, title="Projects") + return + + active_ids = {project.id for project in client.list_projects()} + data = [ + {**_build_project_row(project), "deleted": project.id not in active_ids} + for project in client.list_projects(include_archived=True) + ] + render_output(data, is_json=is_json, columns=[*columns, "deleted"], title="Projects") + + +@app.command("get") +def get_project( + project: str = typer.Argument(help=PROJECT_OPTION_HELP), + profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), + is_json: bool = typer.Option(False, "--json", help="Output as JSON"), +) -> None: + """Show a project's details, or a deleted project's by its id.""" + client = get_client(profile) + found, is_deleted = _find_project_for_get(client, project) + data = {**_build_project_row(found), "updated": found.updated, "deleted": is_deleted} + render_output(data, is_json=is_json, title=f"Project: {found.name}") + + +@app.command("create") +def create_project( + name: str = typer.Option(..., help="Project name"), + description: str = typer.Option("", help="Project description"), + profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), +) -> None: + """Create a project.""" + client = get_client(profile) + try: + created = client.create_project(ProjectCreateRequest(name=name, description=description)) + except DataMasqueApiError as exc: + abort_api_error(f"Failed to create project '{name}'", exc) + print_success(f"Project '{created.name}' created (id {created.id}).") + + +@app.command("update") +def update_project( + project: str = typer.Argument(help=PROJECT_OPTION_HELP), + new_name: str | None = typer.Option(None, "--name", help="New project name"), + description: str | None = typer.Option(None, help="New project description"), + profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), +) -> None: + """ + Rename a project or change its description. + + Renaming moves the project's seed and credential files. + Rulesets and configurations that import one of its libraries by the old project name become invalid, + and seed and table references that name the old project are not changed. + """ + if new_name is None and description is None: + abort("Nothing to update.", code=ErrorCode.INVALID_INPUT, hint="Pass --name, --description or both.") + + client = get_client(profile) + found = resolve_project(client, project) + try: + updated = client.update_project(found, ProjectUpdateRequest(name=new_name, description=description)) + except DataMasqueApiError as exc: + abort_api_error(f"Failed to update project '{found.name}'", exc) + print_success(f"Project '{updated.name}' updated.") + + +@app.command("delete") +def delete_project( + project: str = typer.Argument(help=PROJECT_OPTION_HELP), + destination: str = typer.Option(..., "--to", help="Project to move the resources to: name or id"), + is_check_only: bool = typer.Option(False, "--check", help="Only list what would stop the delete"), + profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), + is_confirmed: bool = typer.Option(False, "--yes", "-y", help="Skip confirmation"), +) -> None: + """Delete a project, after moving all of its resources to another project.""" + client = get_client(profile) + projects = client.list_projects() + found = get_named_project(projects, project) + target = get_named_project(projects, destination) + + if is_check_only: + try: + conflicts = client.get_project_delete_conflicts(found, target) + except DataMasqueApiError as exc: + abort_api_error(f"Failed to check project '{found.name}'", exc) + if conflicts: + abort(DELETE_CONFLICT_MESSAGE, code=ErrorCode.CONFLICT, details=[c.detail for c in conflicts]) + print_success(f"Project '{found.name}' can be deleted, moving its resources to '{target.name}'.") + return + + if not is_confirmed: + confirm_or_abort(f"Delete project '{found.name}' and move its resources to '{target.name}'?") + + try: + client.delete_project(found, target) + except ProjectDeleteConflictError as exc: + abort(DELETE_CONFLICT_MESSAGE, code=ErrorCode.CONFLICT, details=[c.detail for c in exc.conflicts]) + except DataMasqueApiError as exc: + abort_api_error(f"Failed to delete project '{found.name}'", exc) + print_success(f"Project '{found.name}' deleted; its resources moved to '{target.name}'.") diff --git a/src/datamasque_cli/commands/resources.py b/src/datamasque_cli/commands/resources.py new file mode 100644 index 0000000..7c5f225 --- /dev/null +++ b/src/datamasque_cli/commands/resources.py @@ -0,0 +1,151 @@ +"""Commands that act on resources of any type.""" + +from __future__ import annotations + +import typer +from datamasque.client import DataMasqueClient +from datamasque.client.exceptions import DataMasqueApiError, ResourceMoveConflictError +from datamasque.client.models.project import Project +from datamasque.client.models.resource import Resource, ResourceMoveConflict +from datamasque.client.models.resource_type import ResourceTypeName + +from datamasque_cli.client import get_client +from datamasque_cli.errors import ErrorCode, abort, abort_api_error, confirm_or_abort +from datamasque_cli.output import print_success, render_output +from datamasque_cli.projects import PROJECT_OPTION_HELP, get_named_project, project_label + +app = typer.Typer(help="Work with resources of every type.", no_args_is_help=True) + +MOVE_CHECK_CONFLICT_MESSAGE = "No resources would move" + + +def _describe_resource_count(count: int) -> str: + return f"{count} resource" if count == 1 else f"{count} resources" + + +def _get_conflict_details(conflicts: list[ResourceMoveConflict]) -> list[str]: + """Return each conflict's detail once, in order, since resources that clash the same way share a detail.""" + return list(dict.fromkeys(conflict.detail for conflict in conflicts)) + + +def _get_resources_to_move( + client: DataMasqueClient, + *, + names: list[str], + sources: list[Project] | None, + type_names: list[ResourceTypeName] | None, + search: str | None, + destination: Project, +) -> dict[ResourceTypeName, list[Resource]]: + """ + Return the resources the filters select, by type, leaving out those already in the destination. + + Built-in seeds belong to no project and cannot move, so they are left out too. + Aborts with not-found when a name matches none of the resources the other filters select. + """ + listed_resources = client.list_resources(projects=sources, types=type_names, search=search) + listed_names = {resource.name for resources in listed_resources.values() for resource in resources} + if unmatched_names := [name for name in dict.fromkeys(names) if name not in listed_names]: + abort( + f"No resources named {', '.join(repr(name) for name in unmatched_names)}.", + code=ErrorCode.NOT_FOUND, + hint="Check the names, and that --project, --type and --search select them.", + ) + selected_resources = { + type_name: [ + resource + for resource in resources + if resource.project not in (None, destination.reference) and (not names or resource.name in names) + ] + for type_name, resources in listed_resources.items() + } + return {type_name: resources for type_name, resources in selected_resources.items() if resources} + + +@app.command("move") +def move_resources( + names: list[str] | None = typer.Argument( + None, help="Exact names of the resources to move, of any type unless --type is given; omit to move every match" + ), + destination: str = typer.Option(..., "--to", help="Project to move the resources to: name or id"), + sources: list[str] | None = typer.Option( + None, "--project", help=f"Move from this project only. {PROJECT_OPTION_HELP}; repeatable" + ), + type_names: list[ResourceTypeName] | None = typer.Option(None, "--type", help="Move this type only; repeatable"), + search: str | None = typer.Option(None, help="Move resources whose name contains every word of this, any case"), + is_check_only: bool = typer.Option( + False, "--check", help="Only list the resources and what would stop them moving" + ), + profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), + is_confirmed: bool = typer.Option(False, "--yes", "-y", help="Skip confirmation"), + is_json: bool = typer.Option(False, "--json", help="Output as JSON"), +) -> None: + """ + Move resources to another project, with their files and runs. + + Select them by project, type, a name search or exact names; the filters combine. + All of them move, or none do: a resource that clashes with the destination stops the move. + A resource already in the destination stays there, and the others move. + Rulesets and configurations whose library imports resolve differently after the move become invalid. + """ + if not (names or sources or type_names or search): + abort( + "Select the resources to move.", + code=ErrorCode.INVALID_INPUT, + hint="Pass resource names, --project, --type or --search.", + ) + + client = get_client(profile) + projects = client.list_projects() + target = get_named_project(projects, destination) + resources_to_move = _get_resources_to_move( + client, + names=names or [], + sources=[get_named_project(projects, source) for source in sources] if sources else None, + type_names=type_names, + search=search, + destination=target, + ) + if not resources_to_move: + abort(f"No resources to move to '{target.name}'.", code=ErrorCode.NOT_FOUND) + + # The selection leaves out resources in no project, and a deleted project has no resources left. + project_names_by_reference = {project.reference: project.name for project in projects} + rows = [ + { + "type": type_name.value, + "name": resource.name, + "project": project_label(project_names_by_reference, resource.project), + } + for type_name, resources in resources_to_move.items() + for resource in resources + ] + render_output( + rows, is_json=is_json, columns=["type", "name", "project"], title=f"Resources to move to {target.name}" + ) + + if is_check_only: + try: + conflicts = client.get_resource_move_conflicts(resources_to_move, target) + except DataMasqueApiError as exc: + abort_api_error("Failed to check the move", exc) + if conflicts: + abort(MOVE_CHECK_CONFLICT_MESSAGE, code=ErrorCode.CONFLICT, details=_get_conflict_details(conflicts)) + print_success(f"All {_describe_resource_count(len(rows))} can move to '{target.name}'.") + return + + if not is_confirmed: + confirm_or_abort(f"Move {_describe_resource_count(len(rows))} to '{target.name}'?") + + try: + result = client.move_resources(resources_to_move, target) + except ResourceMoveConflictError as exc: + abort( + f"No resources moved to '{target.name}'", + code=ErrorCode.CONFLICT, + details=_get_conflict_details(exc.conflicts), + ) + except DataMasqueApiError as exc: + abort_api_error(f"Failed to move resources to '{target.name}'", exc) + + print_success(f"Moved {_describe_resource_count(result.moved)} to '{target.name}'.") diff --git a/src/datamasque_cli/commands/ruleset_libraries.py b/src/datamasque_cli/commands/ruleset_libraries.py index d43190b..a8ff74d 100644 --- a/src/datamasque_cli/commands/ruleset_libraries.py +++ b/src/datamasque_cli/commands/ruleset_libraries.py @@ -5,55 +5,71 @@ from pathlib import Path import typer +from datamasque.client import DataMasqueClient from datamasque.client.exceptions import DataMasqueApiError from datamasque.client.models.ruleset_library import RulesetLibrary from datamasque.client.models.status import ValidationStatus from datamasque_cli.client import get_client -from datamasque_cli.errors import ErrorCode, abort, abort_api_error, abort_if_invalid, confirm_or_abort +from datamasque_cli.errors import abort_api_error, abort_if_invalid, confirm_or_abort from datamasque_cli.fileio import read_text_or_abort from datamasque_cli.output import print_info, print_success, render_output, should_emit_json +from datamasque_cli.projects import ( + PROJECT_OPTION_HELP, + filter_by_project, + get_project_names_by_reference, + project_label, + require_single_or_abort, + resolve_create_project, + resolve_optional_project, +) app = typer.Typer(help="Manage ruleset libraries.", no_args_is_help=True) +def _find_library(client: DataMasqueClient, name: str, project: str | None) -> RulesetLibrary: + """Return the library named `name`, with its YAML, in `project` or in the one project that has it.""" + matches = [lib for lib in client.list_ruleset_libraries() if lib.name == name] + matches = filter_by_project(matches, resolve_optional_project(client, project)) + found = require_single_or_abort(client, matches, f"Library '{name}'") + return client.get_ruleset_library(found.id) + + @app.command("list") def list_libraries( + project: str | None = typer.Option(None, "--project", help=PROJECT_OPTION_HELP), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), is_json: bool = typer.Option(False, "--json", help="Output as JSON"), ) -> None: - """List all ruleset libraries.""" + """List all ruleset libraries, or those in one project.""" client = get_client(profile) - libraries = client.list_ruleset_libraries() + libraries = filter_by_project(client.list_ruleset_libraries(), resolve_optional_project(client, project)) + names = get_project_names_by_reference(client) data = [ { "id": lib.id, - "namespace": lib.namespace or "", + "project": project_label(names, lib.project), "name": lib.name, "valid": lib.is_valid.value if lib.is_valid else "unknown", } for lib in libraries ] - render_output(data, is_json=is_json, columns=["id", "namespace", "name", "valid"], title="Ruleset Libraries") + render_output(data, is_json=is_json, columns=["id", "project", "name", "valid"], title="Ruleset Libraries") @app.command("get") def get_library( name: str = typer.Argument(help="Library name"), - namespace: str = typer.Option("", "--namespace", "-n", help="Library namespace"), + project: str | None = typer.Option(None, "--project", help=PROJECT_OPTION_HELP), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), is_yaml: bool = typer.Option(False, "--yaml", help="Output raw YAML content only"), is_json: bool = typer.Option(False, "--json", help="Output as JSON"), ) -> None: """Show a library's details or YAML content.""" client = get_client(profile) - lib = client.get_ruleset_library_by_name(name, namespace) - - if lib is None: - label = f"{namespace}/{name}" if namespace else name - abort(f"Library '{label}' not found.", code=ErrorCode.NOT_FOUND) + lib = _find_library(client, name, project) if is_yaml: typer.echo(lib.yaml) @@ -61,7 +77,7 @@ def get_library( data: dict[str, object] = { "id": lib.id, - "namespace": lib.namespace, + "project": project_label(get_project_names_by_reference(client), lib.project), "name": lib.name, "valid": lib.is_valid.value if lib.is_valid else "unknown", "created": lib.created, @@ -74,14 +90,15 @@ def get_library( def create_library( name: str = typer.Option(..., help="Library name"), file: Path = typer.Option(..., "--file", "-f", help="Path to YAML library file", exists=True, readable=True), - namespace: str = typer.Option("", "--namespace", "-n", help="Library namespace"), + project: str | None = typer.Option(None, "--project", help=PROJECT_OPTION_HELP), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), ) -> None: """Create or update a ruleset library from a YAML file.""" yaml_content = read_text_or_abort(file) client = get_client(profile) - library = RulesetLibrary(name=name, namespace=namespace, yaml=yaml_content) + existing = [lib for lib in client.list_ruleset_libraries() if lib.name == name] + library = RulesetLibrary(name=name, project=resolve_create_project(client, project, existing), yaml=yaml_content) client.create_or_update_ruleset_library(library) print_success(f"Library '{name}' created/updated.") @@ -89,80 +106,70 @@ def create_library( @app.command("delete") def delete_library( name: str = typer.Argument(help="Library name to delete"), - namespace: str = typer.Option("", "--namespace", "-n", help="Library namespace"), + project: str | None = typer.Option(None, "--project", help=PROJECT_OPTION_HELP), force: bool = typer.Option(False, "--force", help="Force delete even if imported by rulesets"), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), is_confirmed: bool = typer.Option(False, "--yes", "-y", help="Skip confirmation"), ) -> None: """Delete a ruleset library by name.""" - label = f"{namespace}/{name}" if namespace else name client = get_client(profile) - if client.get_ruleset_library_by_name(name, namespace) is None: - abort(f"Library '{label}' not found.", code=ErrorCode.NOT_FOUND) + lib = _find_library(client, name, project) if not is_confirmed: - confirm_or_abort(f"Delete library '{label}'?") + confirm_or_abort(f"Delete library '{name}'?") try: - client.delete_ruleset_library_by_name_if_exists(name, namespace, force=force) + client.delete_ruleset_library_by_id_if_exists(lib.id, force=force) except DataMasqueApiError as exc: abort_api_error( - f"Failed to delete library '{label}'", + f"Failed to delete library '{name}'", exc, conflict_hint="Re-run with --force to delete it and flag the dependent rulesets for revalidation.", ) - print_success(f"Library '{label}' deleted.") + print_success(f"Library '{name}' deleted.") @app.command("validate") def validate_library( name: str = typer.Argument(help="Library name"), - namespace: str = typer.Option("", "--namespace", "-n", help="Library namespace"), + project: str | None = typer.Option(None, "--project", help=PROJECT_OPTION_HELP), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), ) -> None: """Re-validate a ruleset library against the current server schema. Triggers a server-side validation pass on an existing library and reports the result. """ - label = f"{namespace}/{name}" if namespace else name client = get_client(profile) - lib = client.get_ruleset_library_by_name(name, namespace) - - if lib is None: - abort(f"Library '{label}' not found.", code=ErrorCode.NOT_FOUND) + lib = _find_library(client, name, project) try: validated = client.validate_ruleset_library(lib.id) except DataMasqueApiError as exc: - abort_api_error(f"Failed to validate library '{label}'", exc) - abort_if_invalid(f"Library '{label}'", validated.is_valid, validated.validation_errors) + abort_api_error(f"Failed to validate library '{name}'", exc) + abort_if_invalid(f"Library '{name}'", validated.is_valid, validated.validation_errors) status = validated.is_valid.value if validated.is_valid else "unknown" - print_success(f"Library '{label}' validation status: {status}") + print_success(f"Library '{name}' validation status: {status}") @app.command("status") def show_library_status( name: str = typer.Argument(help="Library name"), - namespace: str = typer.Option("", "--namespace", "-n", help="Library namespace"), + project: str | None = typer.Option(None, "--project", help=PROJECT_OPTION_HELP), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), is_json: bool = typer.Option(False, "--json", help="Output as JSON"), ) -> None: """Show a ruleset library's validation status.""" client = get_client(profile) - lib = client.get_ruleset_library_by_name(name, namespace) - - if lib is None: - label = f"{namespace}/{name}" if namespace else name - abort(f"Library '{label}' not found.", code=ErrorCode.NOT_FOUND) + lib = _find_library(client, name, project) status = lib.is_valid.value if lib.is_valid else "unknown" errors = lib.validation_errors or [] data: dict[str, object] = { - "namespace": lib.namespace, + "project": project_label(get_project_names_by_reference(client), lib.project), "name": lib.name, "status": status, } @@ -179,27 +186,25 @@ def show_library_status( @app.command("usage") def library_usage( name: str = typer.Argument(help="Library name"), - namespace: str = typer.Option("", "--namespace", "-n", help="Library namespace"), + project: str | None = typer.Option(None, "--project", help=PROJECT_OPTION_HELP), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), is_json: bool = typer.Option(False, "--json", help="Output as JSON"), ) -> None: """Show which rulesets import a given library.""" client = get_client(profile) - lib = client.get_ruleset_library_by_name(name, namespace) - - if lib is None: - label = f"{namespace}/{name}" if namespace else name - abort(f"Library '{label}' not found.", code=ErrorCode.NOT_FOUND) + lib = _find_library(client, name, project) rulesets = client.list_rulesets_using_library(lib.id) + names = get_project_names_by_reference(client) data = [ { "id": rs.id, + "project": project_label(names, rs.project), "name": rs.name, "type": rs.ruleset_type.value, } for rs in rulesets ] - render_output(data, is_json=is_json, columns=["id", "name", "type"], title=f"Rulesets using '{name}'") + render_output(data, is_json=is_json, columns=["id", "project", "name", "type"], title=f"Rulesets using '{name}'") diff --git a/src/datamasque_cli/commands/rulesets.py b/src/datamasque_cli/commands/rulesets.py index 42b50a4..5e87e67 100644 --- a/src/datamasque_cli/commands/rulesets.py +++ b/src/datamasque_cli/commands/rulesets.py @@ -7,7 +7,6 @@ import typer from datamasque.client import DataMasqueClient -from datamasque.client.base import UploadFile from datamasque.client.exceptions import DataMasqueApiError from datamasque.client.models.discovery import FileRulesetGenerationRequest, RulesetGenerationRequest from datamasque.client.models.ruleset import Ruleset, RulesetType @@ -31,6 +30,18 @@ write_text_or_abort, ) from datamasque_cli.output import print_info, print_success, print_warning, render_output, should_emit_json +from datamasque_cli.projects import ( + PROJECT_OPTION_HELP, + PROJECT_VALIDATE_HELP, + filter_by_project, + get_project_names_by_reference, + get_same_name_project_help, + project_label, + resolve_create_project, + resolve_optional_project, + resolve_project, + resolve_target_project, +) app = typer.Typer(help="Manage masking rulesets.", no_args_is_help=True) @@ -39,24 +50,31 @@ def _find_by_name( client: DataMasqueClient, name: str, mask_type: RulesetType | None = None, + project: str | None = None, ) -> list[Ruleset]: - """Return all rulesets matching `name`, optionally narrowed by `mask_type`.""" + """Return all rulesets matching `name`, optionally narrowed by `mask_type` and by the project `--project` names.""" matches = [rs for rs in client.list_rulesets() if rs.name == name] if mask_type is not None: matches = [rs for rs in matches if rs.ruleset_type == mask_type] - return matches + return filter_by_project(matches, resolve_optional_project(client, project)) -def _require_single_matched_ruleset_or_abort(matched_rulesets: list[Ruleset], name: str) -> Ruleset: - """Return the single ruleset matching `name`, or abort asking for `--type`.""" +def _require_single_matched_ruleset_or_abort( + client: DataMasqueClient, matched_rulesets: list[Ruleset], name: str +) -> Ruleset: + """Return the single ruleset matching `name`, or abort asking for `--type` or `--project`.""" if not matched_rulesets: abort(f"Ruleset '{name}' not found.", code=ErrorCode.NOT_FOUND) if len(matched_rulesets) > 1: - options = "\n ".join(f"id={rs.id} type={rs.ruleset_type.value}" for rs in matched_rulesets) + names = get_project_names_by_reference(client) + options = "\n ".join( + f"id={rs.id} type={rs.ruleset_type.value} project={project_label(names, rs.project)}" + for rs in matched_rulesets + ) abort( f"Multiple rulesets named '{name}':\n {options}", code=ErrorCode.AMBIGUOUS, - hint="Pass --type database|file to disambiguate.", + hint="Pass --type database|file or --project to disambiguate.", ) return matched_rulesets[0] @@ -64,26 +82,29 @@ def _require_single_matched_ruleset_or_abort(matched_rulesets: list[Ruleset], na @app.command("list") def list_rulesets( ruleset_type: RulesetType | None = typer.Option(None, "--type", "-t", help="Filter by type: database or file"), + project: str | None = typer.Option(None, "--project", help=PROJECT_OPTION_HELP), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), is_json: bool = typer.Option(False, "--json", help="Output as JSON"), ) -> None: - """List all rulesets.""" + """List all rulesets, or those in one project.""" client = get_client(profile) - rulesets = client.list_rulesets() + rulesets = filter_by_project(client.list_rulesets(), resolve_optional_project(client, project)) if ruleset_type is not None: rulesets = [rs for rs in rulesets if rs.ruleset_type == ruleset_type] + names = get_project_names_by_reference(client) data = [ { "id": rs.id, + "project": project_label(names, rs.project), "name": rs.name, "type": rs.ruleset_type.value, } for rs in rulesets ] - render_output(data, is_json=is_json, columns=["id", "name", "type"], title="Rulesets") + render_output(data, is_json=is_json, columns=["id", "project", "name", "type"], title="Rulesets") @app.command("get") @@ -92,13 +113,14 @@ def get_ruleset( ruleset_type: RulesetType | None = typer.Option( None, "--type", "-t", help="Required when two rulesets share a name" ), + project: str | None = typer.Option(None, "--project", help=get_same_name_project_help("rulesets")), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), is_yaml: bool = typer.Option(False, "--yaml", help="Output raw YAML content only"), is_json: bool = typer.Option(False, "--json", help="Output as JSON"), ) -> None: """Show a ruleset's details or YAML content.""" client = get_client(profile) - match = _require_single_matched_ruleset_or_abort(_find_by_name(client, name, ruleset_type), name) + match = _require_single_matched_ruleset_or_abort(client, _find_by_name(client, name, ruleset_type, project), name) # `list_rulesets` omits the YAML body for performance; fetch the single ruleset # to populate `yaml` via the Ruleset pydantic model's `config_yaml` alias. @@ -111,6 +133,7 @@ def get_ruleset( data: dict[str, object] = { "id": full.id, + "project": project_label(get_project_names_by_reference(client), full.project), "name": full.name, "type": full.ruleset_type.value, "yaml": full.yaml, @@ -131,16 +154,17 @@ def create_ruleset( "Required when the ruleset does not yet exist; defaults to the existing type on updates." ), ), + project: str | None = typer.Option(None, "--project", help=PROJECT_OPTION_HELP), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), ) -> None: """Create or update a ruleset from a YAML file. - Read the server first to decide which namespace the upload belongs in. A + Read the server first to decide which type the upload has. A brand-new ruleset needs --type because there is no stored row to copy the type from; an update defaults to whatever the existing row is stored as. """ client = get_client(profile) - existing = _find_by_name(client, name) + existing = _find_by_name(client, name, project=project) if ruleset_type is not None: rs_type = ruleset_type @@ -154,15 +178,21 @@ def create_ruleset( hint="Pass --type database|file to create a new one.", ) else: - options = ", ".join(r.ruleset_type.value for r in existing) + names = get_project_names_by_reference(client) + options = ", ".join(f"{r.ruleset_type.value} in {project_label(names, r.project)}" for r in existing) abort( f"Multiple rulesets named '{name}' ({options}).", code=ErrorCode.AMBIGUOUS, - hint="Pass --type database|file to pick which one to update.", + hint="Pass --type database|file or --project to pick which one to update.", ) yaml_content = read_text_or_abort(file) - ruleset = Ruleset(name=name, yaml=yaml_content, ruleset_type=rs_type) + ruleset = Ruleset( + name=name, + yaml=yaml_content, + ruleset_type=rs_type, + project=resolve_create_project(client, project, [r for r in existing if r.ruleset_type is rs_type]), + ) client.create_or_update_ruleset(ruleset) print_success(f"Ruleset '{name}' ({rs_type.value}) created/updated.") @@ -173,12 +203,13 @@ def delete_ruleset( ruleset_type: RulesetType | None = typer.Option( None, "--type", "-t", help="Required when two rulesets share a name" ), + project: str | None = typer.Option(None, "--project", help=get_same_name_project_help("rulesets")), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), is_confirmed: bool = typer.Option(False, "--yes", "-y", help="Skip confirmation"), ) -> None: """Delete a ruleset by name.""" client = get_client(profile) - match = _require_single_matched_ruleset_or_abort(_find_by_name(client, name, ruleset_type), name) + match = _require_single_matched_ruleset_or_abort(client, _find_by_name(client, name, ruleset_type, project), name) ruleset_id = require_id_or_abort(match.id, f"ruleset '{name}'") if not is_confirmed: @@ -197,11 +228,12 @@ def validate_ruleset( "-t", help="Ruleset type: database or file", ), + project: str | None = typer.Option(None, "--project", help=PROJECT_VALIDATE_HELP), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), ) -> None: """Validate a ruleset YAML file against the DataMasque server. - Creates a temporary ruleset to trigger server-side validation, + Creates a temporary ruleset in the project to trigger server-side validation, then deletes it. Reports any validation errors. Note that rulesets over 60 KiB validate asynchronously and cannot be validated here. @@ -217,7 +249,8 @@ def validate_ruleset( temp_name = f"__dm_cli_validate_{uuid.uuid4().hex}" client = get_client(profile) - ruleset = Ruleset(name=temp_name, yaml=yaml_content, ruleset_type=ruleset_type) + target = resolve_target_project(client, project) + ruleset = Ruleset(name=temp_name, yaml=yaml_content, ruleset_type=ruleset_type, project=target.reference) try: created = client.create_or_update_ruleset(ruleset) @@ -241,17 +274,24 @@ def validate_ruleset( @app.command("export-bundle") def export_bundle( output_path: Path = typer.Option("datamasque-bundle.zip", "--output", "-o", help="Where to save the ZIP bundle"), + is_including_seed_files: bool = typer.Option( + False, "--include-seed-files", help="Also bundle the custom seed files the rulesets and libraries use" + ), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), ) -> None: - """Export rulesets, ruleset libraries, and any referenced seed files as a ZIP bundle. + """ + Export every ruleset and ruleset library as a ZIP bundle, with their seed files on request. - Bundles only rulesets + libraries + optional seed files — not connections, - users, licences, or instance settings. + Bundles only rulesets, libraries and, with `--include-seed-files`, the custom seed files they use, + not connections, users, licences or instance settings. + Each item is filed under its project. """ client = get_client(profile) - # `export_configuration` is not yet wrapped in datamasque-python; hit the endpoint directly. - response = client.make_request("GET", "/api/export/v1/") - write_bytes_or_abort(output_path, response.content) + try: + bundle = client.export_bundle(include_seed_files=is_including_seed_files) + except DataMasqueApiError as exc: + abort_api_error("Failed to export the bundle", exc) + write_bytes_or_abort(output_path, bundle) print_success(f"Bundle exported to {output_path}") @@ -267,49 +307,47 @@ def import_bundle( overwrite_seeds: bool = typer.Option( False, "--overwrite-seeds", help="Overwrite seed files that already exist with the same name" ), + fallback_project: str | None = typer.Option( + None, + "--fallback-project", + help=f"{PROJECT_OPTION_HELP} for the items the bundle files under no project. " + "Defaults to the server's default project.", + ), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), is_confirmed: bool = typer.Option(False, "--yes", "-y", help="Skip confirmation"), ) -> None: - """Import rulesets, ruleset libraries, and seed files from a ZIP bundle. + """ + Import rulesets, ruleset libraries, and seed files from a ZIP bundle. - Bundle must have been produced by `dm rulesets export-bundle` or the - server's `/api/export/v1/` endpoint. By default, duplicates are skipped; - pass `--overwrite-*` flags to replace existing entries. + Bundle must have been produced by `dm rulesets export-bundle` or the server's export endpoint. + Each item goes into the project the bundle files it under; + items under no project, such as those in an older bundle, go into `--fallback-project`. + By default, duplicates are skipped; pass `--overwrite-*` flags to replace existing entries. """ if not is_confirmed: confirm_or_abort("This will modify rulesets, libraries, and seed files. Continue?") client = get_client(profile) - # `/api/import/v1/` expects a multipart `zip_archive` upload plus three - # optional boolean overwrite flags; `import_configuration` is not yet - # wrapped in datamasque-python, so we call `make_request` directly. - with file.open("rb") as zip_content: - response = client.make_request( - "POST", - "/api/import/v1/", - data={ - "overwrite_rulesets": str(overwrite_rulesets).lower(), - "overwrite_libraries": str(overwrite_libraries).lower(), - "overwrite_seed_files": str(overwrite_seeds).lower(), - }, - files=[ - UploadFile( - field_name="zip_archive", - filename=file.name, - content=zip_content, - content_type="application/zip", - ), - ], + fallback = resolve_project(client, fallback_project) if fallback_project is not None else None + try: + result = client.import_bundle( + file, + overwrite_rulesets=overwrite_rulesets, + overwrite_libraries=overwrite_libraries, + overwrite_seed_files=overwrite_seeds, + fallback_project=fallback, ) + except DataMasqueApiError as exc: + abort_api_error("Failed to import the bundle", exc) print_success("Bundle imported successfully.") - if response.content: - try: - summary = response.json() - except ValueError: - return - if isinstance(summary, dict): - render_output(summary, is_json=False, title="Import summary") + if result.fallback_project is not None: + print_info(f"Items the bundle files under no project went into project '{result.fallback_project}'.") + render_output( + result.model_dump(mode="json", exclude={"is_deprecated_bundle"}, exclude_none=True), + is_json=False, + title="Import summary", + ) @app.command("status") @@ -318,16 +356,18 @@ def show_ruleset_status( ruleset_type: RulesetType | None = typer.Option( None, "--type", "-t", help="Required when two rulesets share a name" ), + project: str | None = typer.Option(None, "--project", help=get_same_name_project_help("rulesets")), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), is_json: bool = typer.Option(False, "--json", help="Output as JSON"), ) -> None: """Show a ruleset's validation status.""" client = get_client(profile) - match = _require_single_matched_ruleset_or_abort(_find_by_name(client, name, ruleset_type), name) + match = _require_single_matched_ruleset_or_abort(client, _find_by_name(client, name, ruleset_type, project), name) status = match.is_valid.value if match.is_valid else "unknown" errors = match.validation_errors or [] data: dict[str, object] = { + "project": project_label(get_project_names_by_reference(client), match.project), "name": match.name, "type": match.ruleset_type.value, "status": status, diff --git a/src/datamasque_cli/commands/runs.py b/src/datamasque_cli/commands/runs.py index 56304c5..098cf87 100644 --- a/src/datamasque_cli/commands/runs.py +++ b/src/datamasque_cli/commands/runs.py @@ -11,10 +11,9 @@ import typer from datamasque.client import DataMasqueClient, RunId from datamasque.client.exceptions import DataMasqueApiError, InvalidLibraryError, RunNotCancellableError -from datamasque.client.models.connection import ConnectionConfig from datamasque.client.models.runs import MaskingRunOptions, MaskingRunRequest, RunInfo -from datamasque_cli.client import get_client +from datamasque_cli.client import get_client, resolve_connection from datamasque_cli.errors import ErrorCode, abort, abort_api_error, abort_if_not_found from datamasque_cli.fileio import write_text_or_abort from datamasque_cli.output import ( @@ -27,18 +26,27 @@ stdout_console, style_status, ) +from datamasque_cli.projects import ( + PROJECT_OPTION_HELP, + filter_by_project, + get_named_resources_project_help, + get_project_names_by_reference, + project_label, + resolve_optional_project, +) app = typer.Typer(help="Manage masking runs.", no_args_is_help=True) _POLL_INTERVAL_SECONDS = 5 -def _format_run_info(run: RunInfo, *, is_styled: bool = False) -> dict[str, object]: - """Extract the fields most useful for display from a `RunInfo`.""" +def _format_run_info(run: RunInfo, names: dict[str, str], *, is_styled: bool = False) -> dict[str, object]: + """Extract the fields most useful for display from a `RunInfo`, naming its project from `names`.""" status = run.status.value destination = run.destination_connection.name if run.destination_connection else None return { "id": run.id, + "project": project_label(names, run.project), "status": style_status(status) if is_styled else status, "ruleset": run.ruleset_name, "source": run.source_connection.name, @@ -47,11 +55,15 @@ def _format_run_info(run: RunInfo, *, is_styled: bool = False) -> dict[str, obje } -def _format_run_dict(run_data: dict[str, object], *, is_styled: bool = False) -> dict[str, object]: +def _format_run_dict( + run_data: dict[str, object], names: dict[str, str], *, is_styled: bool = False +) -> dict[str, object]: """Extract display fields from a raw run list-response dict (not yet modelled in dm-python 1.0.0).""" status = str(run_data.get("status") or run_data.get("run_status") or "") + project = run_data.get("project") return { "id": run_data.get("id"), + "project": project_label(names, project if isinstance(project, str) else None), "status": style_status(status) if is_styled else status, "ruleset": run_data.get("ruleset_name"), "source": run_data.get("source_connection_name"), @@ -89,36 +101,20 @@ def _get_run_log_or_abort(client: DataMasqueClient, run_id: int) -> str: return log -def _resolve_connection(client: DataMasqueClient, name_or_id: str) -> ConnectionConfig: - """Return the connection matching `name_or_id`, preferring name.""" - connections = client.list_connections() - - match = next((c for c in connections if c.name == name_or_id), None) - if match is not None: - return match - - match = next((c for c in connections if str(c.id) == name_or_id), None) - if match is not None: - return match - - available = ", ".join(c.name for c in connections) - abort(f"Connection '{name_or_id}' not found.", code=ErrorCode.NOT_FOUND, hint=f"Available: {available}") - - -def _resolve_connection_id(client: DataMasqueClient, name_or_id: str) -> str: - """Resolve a connection name to its UUID. Pass through if already a UUID.""" - return str(_resolve_connection(client, name_or_id).id) - - -def _resolve_ruleset_id(client: DataMasqueClient, name_or_id: str, mask_type: str | None = None) -> str: +def _resolve_ruleset_id( + client: DataMasqueClient, name_or_id: str, mask_type: str | None = None, project: str | None = None +) -> str: """Resolve a ruleset name to its UUID. `mask_type` is the source connection's type when called from `run start`. - Providing it narrows the lookup to the matching namespace, which is what + Providing it narrows the lookup to the matching type, which is what disambiguates same-named rulesets across the database/file split. + `project` narrows it to the project `--project` names. """ rulesets = client.list_rulesets() - by_name = [r for r in rulesets if r.name == name_or_id] + by_name = filter_by_project( + [r for r in rulesets if r.name == name_or_id], resolve_optional_project(client, project) + ) if mask_type is not None: by_name_and_type = [r for r in by_name if r.ruleset_type.value == mask_type] @@ -135,11 +131,12 @@ def _resolve_ruleset_id(client: DataMasqueClient, name_or_id: str, mask_type: st if len(by_name) == 1: return str(by_name[0].id) if len(by_name) > 1: - options = ", ".join(f"{r.ruleset_type.value}:{r.id}" for r in by_name) + names = get_project_names_by_reference(client) + options = ", ".join(f"{r.ruleset_type.value}:{project_label(names, r.project)}:{r.id}" for r in by_name) abort( f"Multiple rulesets named '{name_or_id}' ({options}).", code=ErrorCode.AMBIGUOUS, - hint="Pass a UUID instead, or rename one of them.", + hint="Pass --project or a UUID instead, or rename one of them.", ) by_id = next((r for r in rulesets if str(r.id) == name_or_id), None) @@ -197,14 +194,17 @@ def start_run( is_background: bool = typer.Option( False, "--background", "-b", help="Return immediately without waiting for completion" ), + project: str | None = typer.Option( + None, "--project", help=get_named_resources_project_help("ruleset and connections") + ), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), is_json: bool = typer.Option(False, "--json", help="Output as JSON"), ) -> None: """Start a new masking run.""" client = get_client(profile) - source = _resolve_connection(client, connection) - ruleset_id = _resolve_ruleset_id(client, ruleset, mask_type=source.mask_type) + source = resolve_connection(client, connection, project) + ruleset_id = _resolve_ruleset_id(client, ruleset, mask_type=source.mask_type, project=project) # Without `destination_connection` in the payload the server defaults # `mask_type` to `database`, so a file source produces a confusing @@ -221,7 +221,7 @@ def start_run( destination_id: str | None = None if destination is not None: - dest = _resolve_connection(client, destination) + dest = resolve_connection(client, destination, project) if dest.mask_type != source.mask_type: abort( f"Connection type mismatch: source '{source.name}' is {source.mask_type} " @@ -261,13 +261,18 @@ def run_status( # Skip rich styling tags when output will be JSON — otherwise they'd appear # as literal "[status.finished]finished[/status.finished]" in the dump. is_styled = not should_emit_json(is_json) - render_output(_format_run_info(run, is_styled=is_styled), is_json=is_json, title=f"Run {run_id}") + render_output( + _format_run_info(run, get_project_names_by_reference(client), is_styled=is_styled), + is_json=is_json, + title=f"Run {run_id}", + ) @app.command("list") def list_runs( status_filter: str | None = typer.Option(None, "--status", "-s", help="Filter by status"), limit: int = typer.Option(20, "--limit", "-l", help="Maximum number of runs to show"), + project: str | None = typer.Option(None, "--project", help=PROJECT_OPTION_HELP), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), is_json: bool = typer.Option(False, "--json", help="Output as JSON"), ) -> None: @@ -280,6 +285,10 @@ def list_runs( # `list_runs` is not yet wrapped in datamasque-python; hit the endpoint directly. params = [] + target = resolve_optional_project(client, project) + if target is not None: + # Filtered on the server, so `--limit` counts only this project's runs. + params.append(f"project={target.id}") if status_filter is not None: params.append(f"run_status={status_filter}") if limit is not None: @@ -299,12 +308,13 @@ def list_runs( else: runs = body is_styled = not should_emit_json(is_json) - data = [_format_run_dict(r, is_styled=is_styled) for r in runs] + names = get_project_names_by_reference(client) + data = [_format_run_dict(r, names, is_styled=is_styled) for r in runs] render_output( data, is_json=is_json, - columns=["id", "status", "ruleset", "source", "destination", "created"], + columns=["id", "project", "status", "ruleset", "source", "destination", "created"], title="Masking Runs", ) @@ -500,7 +510,7 @@ def _wait_for_run( duration = _format_duration(int(elapsed)) if should_emit_json(is_json): - print_json(_format_run_info(run)) + print_json(_format_run_info(run, get_project_names_by_reference(client))) status = run.status summary_parts = [f"Run {run_id} {status.value} in {duration}"] diff --git a/src/datamasque_cli/commands/seeds.py b/src/datamasque_cli/commands/seeds.py index 3f07b59..5f0a639 100644 --- a/src/datamasque_cli/commands/seeds.py +++ b/src/datamasque_cli/commands/seeds.py @@ -8,47 +8,65 @@ from datamasque.client.models.files import SeedFile from datamasque_cli.client import get_client -from datamasque_cli.errors import ErrorCode, abort, confirm_or_abort +from datamasque_cli.errors import confirm_or_abort from datamasque_cli.output import print_success, render_output +from datamasque_cli.projects import ( + PROJECT_OPTION_HELP, + PROJECT_UPLOAD_HELP, + filter_by_project, + get_project_names_by_reference, + get_same_name_project_help, + project_label, + require_single_or_abort, + resolve_optional_project, + resolve_target_project, +) app = typer.Typer(help="Manage seed files.", no_args_is_help=True) @app.command("list") def list_seeds( + project: str | None = typer.Option(None, "--project", help=f"{PROJECT_OPTION_HELP}; also lists the built-in seeds"), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), is_json: bool = typer.Option(False, "--json", help="Output as JSON"), ) -> None: - """List all seed files.""" + """List all seed files, or those in one project plus the built-in seeds.""" client = get_client(profile) - seeds = client.list_files_of_type(SeedFile) + target = resolve_optional_project(client, project) + seeds = client.list_files_of_type(SeedFile, project=target.id if target else None) + names = get_project_names_by_reference(client) - data = [{"id": s.id, "name": s.name} for s in seeds] - render_output(data, is_json=is_json, columns=["id", "name"], title="Seed Files") + data = [{"id": s.id, "project": project_label(names, s.project), "name": s.name} for s in seeds] + render_output(data, is_json=is_json, columns=["id", "project", "name"], title="Seed Files") @app.command("upload") def upload_seed( file: Path = typer.Argument(help="Path to seed file", exists=True, readable=True), + project: str | None = typer.Option(None, "--project", help=PROJECT_UPLOAD_HELP), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), ) -> None: """Upload a seed file.""" client = get_client(profile) - client.upload_file(SeedFile, file.name, file) + target = resolve_target_project(client, project) + client.upload_file(SeedFile, file.name, file, project=target.id) print_success(f"Seed file '{file.name}' uploaded.") @app.command("delete") def delete_seed( filename: str = typer.Argument(help="Seed filename to delete"), + project: str | None = typer.Option(None, "--project", help=get_same_name_project_help("seeds")), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), is_confirmed: bool = typer.Option(False, "--yes", "-y", help="Skip confirmation"), ) -> None: """Delete a seed file by filename.""" client = get_client(profile) - match = client.get_file_of_type_by_name(SeedFile, filename) - if match is None: - abort(f"Seed file '{filename}' not found.", code=ErrorCode.NOT_FOUND) + named_seeds = [seed for seed in client.list_files_of_type(SeedFile) if seed.name == filename] + match = require_single_or_abort( + client, filter_by_project(named_seeds, resolve_optional_project(client, project)), f"Seed file '{filename}'" + ) if not is_confirmed: confirm_or_abort(f"Delete seed file '{filename}'?") diff --git a/src/datamasque_cli/commands/system.py b/src/datamasque_cli/commands/system.py index 5eb527c..f0c7fc6 100644 --- a/src/datamasque_cli/commands/system.py +++ b/src/datamasque_cli/commands/system.py @@ -78,7 +78,7 @@ def export_config( ) -> None: """Deprecated alias for `dm rulesets export-bundle`.""" print_warning("`dm system export` is deprecated; use `dm rulesets export-bundle` instead.") - export_bundle(output_path=output_path, profile=profile) + export_bundle(output_path=output_path, is_including_seed_files=False, profile=profile) @app.command("import", hidden=True, deprecated=True) @@ -94,6 +94,7 @@ def import_config( overwrite_rulesets=False, overwrite_libraries=False, overwrite_seeds=False, + fallback_project=None, profile=profile, is_confirmed=is_confirmed, ) diff --git a/src/datamasque_cli/commands/table_references.py b/src/datamasque_cli/commands/table_references.py index be4836a..05061af 100644 --- a/src/datamasque_cli/commands/table_references.py +++ b/src/datamasque_cli/commands/table_references.py @@ -12,9 +12,19 @@ from datamasque.client.models.table_reference import TableReference, TableReferenceFormat, TableReferenceOptions from datamasque_cli.client import get_client, resolve_connection -from datamasque_cli.errors import ErrorCode, abort, abort_api_error, confirm_or_abort +from datamasque_cli.errors import ErrorCode, abort, abort_api_error, confirm_or_abort, require_id_or_abort from datamasque_cli.fileio import read_model_or_abort from datamasque_cli.output import print_success, render_output +from datamasque_cli.projects import ( + PROJECT_OPTION_HELP, + filter_by_project, + get_project_names_by_reference, + get_same_name_project_help, + project_label, + require_single_or_abort, + resolve_create_project, + resolve_optional_project, +) app = typer.Typer( help=( @@ -56,28 +66,31 @@ def _list_or_abort(client: DataMasqueClient) -> list[TableReference]: abort_api_error("Failed to list table references", exc) -def _get_or_abort(client: DataMasqueClient, name: str) -> TableReference | None: - """Return the table reference named `name`, or `None`, or abort with the reason the lookup failed.""" - try: - reference: TableReference | None = client.get_table_reference_by_name(name) - return reference - except DataMasqueApiError as exc: - _abort_if_unsupported(exc) - abort_api_error(f"Failed to look up table reference '{name}'", exc) +def _get_or_abort(client: DataMasqueClient, name: str, project: str | None) -> TableReference: + """Return the table reference named `name`, in `project` or in the one project that has it, else abort.""" + named_references = [ref for ref in _list_or_abort(client) if ref.name == name] + return require_single_or_abort( + client, + filter_by_project(named_references, resolve_optional_project(client, project)), + f"Table reference '{name}'", + ) @app.command("list") def list_references( + project: str | None = typer.Option(None, "--project", help=PROJECT_OPTION_HELP), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), is_json: bool = typer.Option(False, "--json", help="Output as JSON"), ) -> None: - """List all table references.""" + """List all table references, or those in one project.""" client = get_client(profile) - references = _list_or_abort(client) + references = filter_by_project(_list_or_abort(client), resolve_optional_project(client, project)) + names = get_project_names_by_reference(client) data = [ { "id": ref.id, + "project": project_label(names, ref.project), "name": ref.name, "connection": ref.connection_id, "source": ref.source, @@ -85,24 +98,26 @@ def list_references( for ref in references ] - render_output(data, is_json=is_json, columns=["id", "name", "connection", "source"], title="Table References") + render_output( + data, is_json=is_json, columns=["id", "project", "name", "connection", "source"], title="Table References" + ) @app.command("get") def get_reference( name: str = typer.Argument(help="Table reference name"), + project: str | None = typer.Option(None, "--project", help=get_same_name_project_help("references")), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), is_json: bool = typer.Option(False, "--json", help="Output as JSON"), ) -> None: """Show details for a specific table reference.""" client = get_client(profile) - reference = _get_or_abort(client, name) - if reference is None: - abort(f"Table reference '{name}' not found.", code=ErrorCode.NOT_FOUND) + reference = _get_or_abort(client, name, project) options = reference.options data: dict[str, object] = { "id": reference.id, + "project": project_label(get_project_names_by_reference(client), reference.project), "name": reference.name, "connection": reference.connection_id, "source": reference.source, @@ -117,9 +132,22 @@ def get_reference( render_output(data, is_json=is_json, title=f"Table Reference: {name}") -def _resolve_connection_id(client: DataMasqueClient, name_or_id: str) -> ConnectionId: - """Resolve a `--connection` value (name or ID) to a connection ID.""" - return resolve_connection(client, name_or_id).id +def _resolve_connection_id( + client: DataMasqueClient, name_or_id: str, project: str | None, reference_project: str | None +) -> ConnectionId: + """ + Resolve a `--connection` value (name or ID), narrowed by `--project`, to a connection ID. + + Without `--project`, a connection of that name in the reference's own project is used, + so a name that other projects share needs no `--project`. Otherwise every project is searched. + """ + if project is None: + own_project_connections = [ + c for c in client.list_connections() if c.name == name_or_id and c.project == reference_project + ] + if own_project_connections: + return own_project_connections[0].id + return resolve_connection(client, name_or_id, project).id def _option_overrides( @@ -155,6 +183,9 @@ def create_reference( encoding: str | None = typer.Option(None, help=f"CSV encoding {_CSV_OPTION_HELP}"), quotechar: str | None = typer.Option(None, help=f"CSV quote character {_CSV_OPTION_HELP}"), null_string: str | None = typer.Option(None, help=f"String read as null {_CSV_OPTION_HELP}"), + project: str | None = typer.Option( + None, "--project", help="Project for the reference, also used to find --connection by name" + ), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), ) -> None: """Create or update a table reference. @@ -186,39 +217,37 @@ def create_reference( "--file cannot be combined with --name/--connection/--source/--format/CSV-option flags.", code=ErrorCode.INVALID_INPUT, ) - _create_from_file(client, file) + _create_from_file(client, file, project) return if name is None or connection is None or source is None: abort("Provide either --file or all of --name, --connection, and --source.", code=ErrorCode.INVALID_INPUT) overrides = _option_overrides(file_format, delimiter, encoding, quotechar, null_string) + existing = [ref for ref in _list_or_abort(client) if ref.name == name] + reference_project = resolve_create_project(client, project, existing) reference = TableReference( name=name, - connection=_resolve_connection_id(client, connection), + connection=_resolve_connection_id(client, connection, project, reference_project), source=source, options=TableReferenceOptions(**overrides) if overrides else None, + project=reference_project, ) _create_or_update(client, reference) print_success(f"Table reference '{name}' created/updated.") -def _create_from_file(client: DataMasqueClient, file: Path) -> None: - """Create a table reference from a JSON file.""" +def _create_from_file(client: DataMasqueClient, file: Path, project: str | None) -> None: + """Create a table reference from a JSON file, in the project `--project` names when given.""" reference = read_model_or_abort(file, TableReference) + existing = [ref for ref in _list_or_abort(client) if ref.name == reference.name] + reference.project = resolve_create_project(client, project, existing) _create_or_update(client, reference) print_success(f"Table reference '{reference.name}' created/updated.") def _create_or_update(client: DataMasqueClient, reference: TableReference) -> None: - """Create or update `reference`, distinguishing an unsupported server from any other failure. - - `create_or_update_table_reference` itself makes two requests (a GET to look up an existing - reference by name, then a POST or PUT), so probe support with `_get_or_abort` first and let - a 404 from the create/update call surface as a plain API error instead of being misread as - "not supported". - """ - _get_or_abort(client, reference.name) + """Create or update `reference`.""" try: client.create_or_update_table_reference(reference) except DataMasqueApiError as exc: @@ -235,6 +264,7 @@ def update_reference( encoding: str | None = typer.Option(None, help=f"New CSV encoding {_CSV_OPTION_HELP}"), quotechar: str | None = typer.Option(None, help=f"New CSV quote character {_CSV_OPTION_HELP}"), null_string: str | None = typer.Option(None, help=f"New null-string value {_CSV_OPTION_HELP}"), + project: str | None = typer.Option(None, "--project", help=get_same_name_project_help("references")), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), ) -> None: """Update selected fields on an existing table reference, preserving its ID.""" @@ -243,12 +273,10 @@ def update_reference( abort("Pass at least one field to update (e.g. --source, --format).", code=ErrorCode.INVALID_INPUT) client = get_client(profile) - reference = _get_or_abort(client, name) - if reference is None: - abort(f"Table reference '{name}' not found.", code=ErrorCode.NOT_FOUND) + reference = _get_or_abort(client, name, project) if connection is not None: - reference.connection = _resolve_connection_id(client, connection) + reference.connection = _resolve_connection_id(client, connection, project, reference.project) if source is not None: reference.source = source if overrides: @@ -268,20 +296,19 @@ def update_reference( @app.command("delete") def delete_reference( name: str = typer.Argument(help="Table reference name to delete"), + project: str | None = typer.Option(None, "--project", help=get_same_name_project_help("references")), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), is_confirmed: bool = typer.Option(False, "--yes", "-y", help="Skip confirmation"), ) -> None: """Delete a table reference by name.""" client = get_client(profile) - reference = _get_or_abort(client, name) - if reference is None: - abort(f"Table reference '{name}' not found.", code=ErrorCode.NOT_FOUND) + reference = _get_or_abort(client, name, project) if not is_confirmed: confirm_or_abort(f"Delete table reference '{name}'?") try: - client.delete_table_reference_by_name_if_exists(name) + client.delete_table_reference_by_id_if_exists(require_id_or_abort(reference.id, f"table reference '{name}'")) except DataMasqueApiError as exc: abort_api_error(f"Failed to delete table reference '{name}'", exc) print_success(f"Table reference '{name}' deleted.") diff --git a/src/datamasque_cli/main.py b/src/datamasque_cli/main.py index 3545039..ea0ce77 100644 --- a/src/datamasque_cli/main.py +++ b/src/datamasque_cli/main.py @@ -27,6 +27,8 @@ discovery, files, ifm, + projects, + resources, ruleset_libraries, rulesets, runs, @@ -65,6 +67,8 @@ app.add_typer(ruleset_libraries.app, name="libraries") app.add_typer(ifm.app, name="ifm") app.add_typer(table_references.app, name="table-references") +app.add_typer(projects.app, name="projects") +app.add_typer(resources.app, name="resources") @app.command() diff --git a/src/datamasque_cli/projects.py b/src/datamasque_cli/projects.py new file mode 100644 index 0000000..9132cd0 --- /dev/null +++ b/src/datamasque_cli/projects.py @@ -0,0 +1,152 @@ +"""Resolve `--project` and name each resource's project in output.""" + +from __future__ import annotations + +from collections.abc import Callable, Sequence +from typing import Protocol, TypeVar + +from datamasque.client import DataMasqueClient +from datamasque.client.models.project import Project + +from datamasque_cli.errors import ErrorCode, abort + +PROJECT_OPTION_HELP = "Project name or id" + + +def get_same_name_project_help(resources: str) -> str: + """Return the `--project` help for a command that finds `resources` by a name more than one project can hold.""" + return f"{PROJECT_OPTION_HELP}; required when {resources} in two projects share a name" + + +def get_only_project_help(action: str) -> str: + """Return the `--project` help for a command that `action`s into one project, the only one when omitted.""" + return f"Project to {action}; required when the instance has more than one" + + +def get_named_resources_project_help(resources: str) -> str: + """Return the `--project` help for a command that finds several `resources` by names more than one project can hold.""" + return f"Project of the {resources}, when their names exist in more than one" + + +PROJECT_UPLOAD_HELP = get_only_project_help("upload to") +PROJECT_VALIDATE_HELP = get_only_project_help("validate in") + + +class ProjectScoped(Protocol): + """A resource that records its project as an `-` reference.""" + + @property + def project(self) -> str | None: ... + + +ScopedT = TypeVar("ScopedT", bound=ProjectScoped) + + +def find_named_project(projects: Sequence[Project], name_or_id: str) -> Project | None: + """Return the project in `projects` named `name_or_id`, ignoring case, or with that numeric id, else `None`.""" + match = next((p for p in projects if p.name.casefold() == name_or_id.casefold()), None) + if match is None and name_or_id.isdigit(): + match = next((p for p in projects if p.id == int(name_or_id)), None) + return match + + +def get_named_project(projects: Sequence[Project], name_or_id: str) -> Project: + """Return the project in `projects` named `name_or_id`, ignoring case, or with that numeric id.""" + match = find_named_project(projects, name_or_id) + if match is None: + abort(f"Project '{name_or_id}' not found.", code=ErrorCode.NOT_FOUND) + return match + + +def resolve_project(client: DataMasqueClient, name_or_id: str) -> Project: + """Return the active project named `name_or_id`, ignoring case, or with that numeric id.""" + return get_named_project(client.list_projects(), name_or_id) + + +def resolve_optional_project(client: DataMasqueClient, name_or_id: str | None) -> Project | None: + """Return the project `name_or_id` names, or `None` when no `--project` was given.""" + return None if name_or_id is None else resolve_project(client, name_or_id) + + +def resolve_target_project(client: DataMasqueClient, name_or_id: str | None) -> Project: + """ + Return the project to put a new resource in: the one `--project` names, else the only active project. + + Aborts when no `--project` was given and the instance has more than one active project, + as the server does for a create that names no project. + """ + if name_or_id is not None: + return resolve_project(client, name_or_id) + projects = client.list_projects() + if len(projects) == 1: + return projects[0] + abort( + f"The instance has {len(projects)} active projects.", + code=ErrorCode.AMBIGUOUS, + hint="Pass --project to choose one.", + ) + + +def resolve_create_project(client: DataMasqueClient, name_or_id: str | None, existing: Sequence[ProjectScoped]) -> str: + """ + Return the `-` reference of the project a create-or-update writes to. + + That is the project `--project` names; else the one project that already has a resource of that name, so an + update needs no `--project`; else the instance's only active project. + """ + references = {item.project for item in existing} + if name_or_id is None and len(references) == 1: + (reference,) = references + if reference is not None: + return reference + target: str = resolve_target_project(client, name_or_id).reference + return target + + +def get_project_names_by_reference(client: DataMasqueClient) -> dict[str, str]: + """Map each project's `-` reference to its name, archived projects included.""" + return {p.reference: p.name for p in client.list_projects(include_archived=True)} + + +def project_label(names: dict[str, str], reference: str | None) -> str: + """Name the project `reference` points at, or "" for a resource in no project, such as a built-in seed.""" + if reference is None: + return "" + return names.get(reference, reference) + + +def filter_by_project(items: Sequence[ScopedT], project: Project | None) -> list[ScopedT]: + """Keep the items in `project`, or all of them when `project` is `None`.""" + if project is None: + return list(items) + return [item for item in items if item.project == project.reference] + + +def require_single_or_abort( + client: DataMasqueClient, + matches: Sequence[ScopedT], + label: str, + *, + describe: Callable[[ScopedT], str] | None = None, + hint: str = "Pass --project to disambiguate.", +) -> ScopedT: + """ + Return the one resource in `matches`, or abort when there is none or several. + + Several matches means the name exists in more than one project, so the hint asks for `--project`. + `describe` adds a per-match detail, such as the id, to the list the error shows. + """ + if not matches: + abort(f"{label} not found.", code=ErrorCode.NOT_FOUND) + if len(matches) > 1: + names = get_project_names_by_reference(client) + options = "\n ".join( + f"project={project_label(names, item.project)}" + (f" {describe(item)}" if describe else "") + for item in matches + ) + abort( + f"{label} exists in more than one project:\n {options}", + code=ErrorCode.AMBIGUOUS, + hint=hint, + ) + return matches[0] diff --git a/tests/commands/test_connections.py b/tests/commands/test_connections.py index cf92a84..10a242b 100644 --- a/tests/commands/test_connections.py +++ b/tests/commands/test_connections.py @@ -17,6 +17,7 @@ from datamasque_cli.commands.connections import _format_role from datamasque_cli.errors import ExitCode from datamasque_cli.main import app +from tests.conftest import with_projects MODULE = "datamasque_cli.commands.connections" @@ -58,7 +59,7 @@ def test_format_role_for_database_connections_is_always_source() -> None: @patch(f"{MODULE}.get_client") def test_list_connections_includes_role_column(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.list_connections.return_value = [ MountedShareConnectionConfig( @@ -82,7 +83,7 @@ def test_list_connections_includes_role_column(mock_get_client: MagicMock, runne @patch(f"{MODULE}.get_client") def test_create_connection_database(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client result = runner.invoke( @@ -114,7 +115,7 @@ def test_create_connection_database(mock_get_client: MagicMock, runner: CliRunne @patch(f"{MODULE}.get_client") def test_create_connection_mounted_share(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client result = runner.invoke( @@ -144,7 +145,7 @@ def test_create_connection_missing_name_aborts(mock_get_client: MagicMock, runne @patch(f"{MODULE}.get_client") def test_create_connection_from_json_file(mock_get_client: MagicMock, runner: CliRunner, tmp_path: MagicMock) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client conn_file = tmp_path / "conn.json" @@ -173,7 +174,7 @@ def test_create_connection_from_json_file_invalid_schema_aborts( mock_get_client: MagicMock, runner: CliRunner, tmp_path: MagicMock ) -> None: """Valid JSON that doesn't match the connection type's schema aborts cleanly instead of raising.""" - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client conn_file = tmp_path / "conn.json" @@ -191,7 +192,7 @@ def test_create_connection_from_json_file_invalid_schema_aborts( def test_create_databricks_connection_from_json_file( mock_get_client: MagicMock, runner: CliRunner, tmp_path: MagicMock ) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client conn_file = tmp_path / "dbx.json" @@ -220,7 +221,7 @@ def test_create_databricks_connection_from_json_file( def test_create_mongodb_connection_from_json_file( mock_get_client: MagicMock, runner: CliRunner, tmp_path: MagicMock ) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client conn_file = tmp_path / "mongo.json" @@ -253,7 +254,7 @@ def test_delete_connection_confirmed(mock_get_client: MagicMock, mock_client: Ma mock_get_client.return_value = mock_client runner.invoke(app, ["connections", "delete", "my_conn", "--yes"]) - mock_client.delete_connection_by_name_if_exists.assert_called_once_with("my_conn") + mock_client.delete_connection_by_id_if_exists.assert_called_once_with(1) @patch(f"{MODULE}.get_client") @@ -261,7 +262,7 @@ def test_delete_connection_declined(mock_get_client: MagicMock, mock_client: Mag mock_get_client.return_value = mock_client runner.invoke(app, ["connections", "delete", "my_conn"], input="n\n") - mock_client.delete_connection_by_name_if_exists.assert_not_called() + mock_client.delete_connection_by_id_if_exists.assert_not_called() @patch(f"{MODULE}.get_client") @@ -273,7 +274,7 @@ def test_delete_connection_aborts_when_missing( result = runner.invoke(app, ["connections", "delete", "no_such_conn", "--yes"]) assert result.exit_code == ExitCode.NOT_FOUND - mock_client.delete_connection_by_name_if_exists.assert_not_called() + mock_client.delete_connection_by_id_if_exists.assert_not_called() # -- test (reachability check) -------------------------------------------- @@ -369,7 +370,7 @@ def test_update_connection_aborts_when_missing( @patch(f"{MODULE}.get_client") def test_get_connection_redacts_password(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.list_connections.return_value = [ DatabaseConnectionConfig( diff --git a/tests/commands/test_discovery.py b/tests/commands/test_discovery.py index d6f8cc3..fff83c4 100644 --- a/tests/commands/test_discovery.py +++ b/tests/commands/test_discovery.py @@ -1,7 +1,6 @@ from __future__ import annotations import json -from collections.abc import Callable from pathlib import Path from types import SimpleNamespace from unittest.mock import MagicMock, patch @@ -33,6 +32,7 @@ from datamasque_cli.errors import ExitCode from datamasque_cli.main import app +from tests.conftest import DEFAULT_PROJECT_REFERENCE, with_projects MODULE = "datamasque_cli.commands.discovery" @@ -57,7 +57,7 @@ def _make_numeric_preview() -> NumericPreview: @patch(f"{MODULE}.get_client") def test_sdd_report_writes_to_output_file(mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.get_sdd_report.return_value = "col1,col2\na,b\n" @@ -70,7 +70,7 @@ def test_sdd_report_writes_to_output_file(mock_get_client: MagicMock, runner: Cl @patch(f"{MODULE}.get_client") def test_sdd_report_echoes_to_stdout_without_output(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.get_sdd_report.return_value = "col1,col2\na,b\n" @@ -82,7 +82,7 @@ def test_sdd_report_echoes_to_stdout_without_output(mock_get_client: MagicMock, @patch(f"{MODULE}.get_client") def test_db_report_writes_csv_to_output_file(mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.get_db_discovery_result_report.return_value = "header\nrow1\n" @@ -95,7 +95,7 @@ def test_db_report_writes_csv_to_output_file(mock_get_client: MagicMock, runner: @patch(f"{MODULE}.get_client") def test_db_report_writes_zip_when_split(mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client zip_bytes = b"PK\x03\x04 fake zip bytes" client.get_db_discovery_result_report.return_value = zip_bytes @@ -110,7 +110,7 @@ def test_db_report_writes_zip_when_split(mock_get_client: MagicMock, runner: Cli @patch(f"{MODULE}.get_client") def test_db_report_split_without_output_aborts(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.get_db_discovery_result_report.return_value = b"PK\x03\x04 fake zip bytes" @@ -138,7 +138,7 @@ def _make_file_report() -> list[FileDiscoveryResult]: @patch(f"{MODULE}.get_client") def test_file_report_writes_json_to_output(mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.get_file_data_discovery_report.return_value = _make_file_report() @@ -152,7 +152,7 @@ def test_file_report_writes_json_to_output(mock_get_client: MagicMock, runner: C @patch(f"{MODULE}.get_client") def test_file_report_table_lists_locators(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.get_file_data_discovery_report.return_value = _make_file_report() @@ -182,7 +182,7 @@ def test_file_report_table_lists_locators(mock_get_client: MagicMock, runner: Cl def _client_missing_output(client_method: str, status: int, detail: str) -> MagicMock: - client = MagicMock() + client = with_projects(MagicMock()) response = MagicMock(status_code=status) response.json.return_value = {"detail": detail} getattr(client, client_method).side_effect = DataMasqueApiError(f"{status}", response=response) @@ -262,7 +262,7 @@ def test_output_missing_for_unknown_run_is_not_found( @patch(f"{MODULE}.get_client") def test_unexpected_api_error_is_not_swallowed(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client response = MagicMock(status_code=500) response.json.return_value = {"detail": "Report generation crashed."} @@ -280,10 +280,10 @@ def test_unexpected_api_error_is_not_swallowed(mock_get_client: MagicMock, runne @patch(f"{MODULE}.get_client") def test_schema_starts_discovery_run_and_points_at_results(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.list_connections.return_value = [ - SimpleNamespace(id="abc-123", name="my_db", mask_type="database"), + SimpleNamespace(id="abc-123", name="my_db", mask_type="database", project=DEFAULT_PROJECT_REFERENCE), ] client.start_schema_discovery_run.return_value = 99 @@ -298,9 +298,11 @@ def test_schema_starts_discovery_run_and_points_at_results(mock_get_client: Magi @patch(f"{MODULE}.get_client") def test_schema_emits_run_id_as_json(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client - client.list_connections.return_value = [SimpleNamespace(id="abc-123", name="my_db", mask_type="database")] + client.list_connections.return_value = [ + SimpleNamespace(id="abc-123", name="my_db", mask_type="database", project=DEFAULT_PROJECT_REFERENCE) + ] client.start_schema_discovery_run.return_value = 99 result = runner.invoke(app, ["discover", "schema", "my_db", "--json"]) @@ -311,9 +313,11 @@ def test_schema_emits_run_id_as_json(mock_get_client: MagicMock, runner: CliRunn @patch(f"{MODULE}.get_client") def test_file_start_failure_reports_server_detail(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client - client.list_connections.return_value = [SimpleNamespace(id="fs-1", name="my_files", mask_type="file")] + client.list_connections.return_value = [ + SimpleNamespace(id="fs-1", name="my_files", mask_type="file", project=DEFAULT_PROJECT_REFERENCE) + ] response = MagicMock(status_code=400) response.json.return_value = {"detail": "Simultaneous runs on the same connection are not allowed."} client.start_file_data_discovery_run.side_effect = DataMasqueApiError("boom", response=response) @@ -327,7 +331,7 @@ def test_file_start_failure_reports_server_detail(mock_get_client: MagicMock, ru @patch(f"{MODULE}.get_client") def test_schema_results_lists_with_flattened_rows(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.list_schema_discovery_results.return_value = [ SimpleNamespace( @@ -371,7 +375,7 @@ def test_schema_results_lists_with_flattened_rows(mock_get_client: MagicMock, ru @patch(f"{MODULE}.get_client") def test_schema_results_skips_unlabelled_matches(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.list_schema_discovery_results.return_value = [ SimpleNamespace( @@ -413,7 +417,7 @@ def test_schema_results_skips_unlabelled_matches(mock_get_client: MagicMock, run @patch(f"{MODULE}.get_client") def test_schema_results_includes_safe_data_preview_in_json(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.list_schema_discovery_results.return_value = [ SimpleNamespace( @@ -447,7 +451,7 @@ def test_schema_results_includes_safe_data_preview_in_json(mock_get_client: Magi def test_schema_results_hints_at_json_only_when_safe_data_preview_present( mock_get_client: MagicMock, runner: CliRunner, has_safe_data_preview: bool ) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.list_schema_discovery_results.return_value = [ SimpleNamespace( @@ -474,24 +478,25 @@ def test_schema_results_hints_at_json_only_when_safe_data_preview_present( # -- configurable-discovery run triggers ---------------------------------- -def _fake_config_lookup(**ids_by_type: str) -> Callable[[str, DiscoveryConfigType], SimpleNamespace | None]: - """Return a `get_discovery_config_by_name` side effect that knows only the given types.""" - - def lookup(name: str, config_type: DiscoveryConfigType) -> SimpleNamespace | None: - config_id = ids_by_type.get(config_type.value) - if config_id is None: - return None - return SimpleNamespace(id=config_id, name=name, config_type=config_type) - - return lookup +def _saved_configs(**ids_by_type: str) -> list[SimpleNamespace]: + """Return a `list_discovery_configs` result holding, under each test config name, only the given types.""" + return [ + SimpleNamespace( + id=config_id, name=name, config_type=DiscoveryConfigType(type_), project=DEFAULT_PROJECT_REFERENCE + ) + for type_, config_id in ids_by_type.items() + for name in ("emp", "docs") + ] @patch(f"{MODULE}.get_client") def test_schema_with_config_runs_from_saved_config(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client - client.list_connections.return_value = [SimpleNamespace(id="abc-123", name="my_db", mask_type="database")] - client.get_discovery_config_by_name.side_effect = _fake_config_lookup(database="cfg-1") + client.list_connections.return_value = [ + SimpleNamespace(id="abc-123", name="my_db", mask_type="database", project=DEFAULT_PROJECT_REFERENCE) + ] + client.list_discovery_configs.return_value = _saved_configs(database="cfg-1") client.start_schema_discovery_run_from_config.return_value = 77 result = runner.invoke(app, ["discover", "schema", "my_db", "--config", "emp"]) @@ -507,10 +512,12 @@ def test_schema_with_config_runs_from_saved_config(mock_get_client: MagicMock, r @patch(f"{MODULE}.get_client") def test_schema_config_wrong_type_aborts(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client - client.list_connections.return_value = [SimpleNamespace(id="abc-123", name="my_db", mask_type="database")] - client.get_discovery_config_by_name.side_effect = _fake_config_lookup(file="cfg-2") + client.list_connections.return_value = [ + SimpleNamespace(id="abc-123", name="my_db", mask_type="database", project=DEFAULT_PROJECT_REFERENCE) + ] + client.list_discovery_configs.return_value = _saved_configs(file="cfg-2") result = runner.invoke(app, ["discover", "schema", "my_db", "--config", "docs"]) @@ -522,10 +529,12 @@ def test_schema_config_wrong_type_aborts(mock_get_client: MagicMock, runner: Cli @patch(f"{MODULE}.get_client") def test_schema_config_not_found_aborts(mock_get_client: MagicMock, runner: CliRunner) -> None: """Neither type holds the name, so this is not-found rather than a type mismatch.""" - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client - client.list_connections.return_value = [SimpleNamespace(id="abc-123", name="my_db", mask_type="database")] - client.get_discovery_config_by_name.side_effect = _fake_config_lookup() + client.list_connections.return_value = [ + SimpleNamespace(id="abc-123", name="my_db", mask_type="database", project=DEFAULT_PROJECT_REFERENCE) + ] + client.list_discovery_configs.return_value = _saved_configs() result = runner.invoke(app, ["discover", "schema", "my_db", "--config", "nope"]) @@ -535,9 +544,11 @@ def test_schema_config_not_found_aborts(mock_get_client: MagicMock, runner: CliR @patch(f"{MODULE}.get_client") def test_file_without_config_runs_keyword_discovery(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client - client.list_connections.return_value = [SimpleNamespace(id="fs-1", name="my_files", mask_type="file")] + client.list_connections.return_value = [ + SimpleNamespace(id="fs-1", name="my_files", mask_type="file", project=DEFAULT_PROJECT_REFERENCE) + ] client.start_file_data_discovery_run.return_value = 88 result = runner.invoke(app, ["discover", "file", "my_files"]) @@ -552,10 +563,12 @@ def test_file_without_config_runs_keyword_discovery(mock_get_client: MagicMock, @patch(f"{MODULE}.get_client") def test_file_with_config_runs_from_saved_config(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client - client.list_connections.return_value = [SimpleNamespace(id="fs-1", name="my_files", mask_type="file")] - client.get_discovery_config_by_name.side_effect = _fake_config_lookup(file="cfg-3") + client.list_connections.return_value = [ + SimpleNamespace(id="fs-1", name="my_files", mask_type="file", project=DEFAULT_PROJECT_REFERENCE) + ] + client.list_discovery_configs.return_value = _saved_configs(file="cfg-3") client.start_file_data_discovery_run_from_config.return_value = 89 result = runner.invoke(app, ["discover", "file", "my_files", "--config", "docs"]) @@ -570,13 +583,13 @@ def test_file_with_config_runs_from_saved_config(mock_get_client: MagicMock, run _CONFIG_RUN_STARTS = [ ( ["discover", "schema", "my_db", "--config", "emp"], - SimpleNamespace(id="abc-123", name="my_db", mask_type="database"), + SimpleNamespace(id="abc-123", name="my_db", mask_type="database", project=DEFAULT_PROJECT_REFERENCE), {"database": "cfg-1"}, "start_schema_discovery_run_from_config", ), ( ["discover", "file", "my_files", "--config", "docs"], - SimpleNamespace(id="fs-1", name="my_files", mask_type="file"), + SimpleNamespace(id="fs-1", name="my_files", mask_type="file", project=DEFAULT_PROJECT_REFERENCE), {"file": "cfg-3"}, "start_file_data_discovery_run_from_config", ), @@ -602,10 +615,10 @@ def test_config_run_start_error_keeps_its_own_code( config_ids: dict[str, str], start_method: str, ) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.list_connections.return_value = [connection] - client.get_discovery_config_by_name.side_effect = _fake_config_lookup(**config_ids) + client.list_discovery_configs.return_value = _saved_configs(**config_ids) getattr(client, start_method).side_effect = error( "run failed to start: the config is unusable", response=MagicMock(status_code=400) ) @@ -618,9 +631,11 @@ def test_config_run_start_error_keeps_its_own_code( @patch(f"{MODULE}.get_client") def test_file_emits_run_id_as_json(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client - client.list_connections.return_value = [SimpleNamespace(id="fs-1", name="my_files", mask_type="file")] + client.list_connections.return_value = [ + SimpleNamespace(id="fs-1", name="my_files", mask_type="file", project=DEFAULT_PROJECT_REFERENCE) + ] client.start_file_data_discovery_run.return_value = 88 result = runner.invoke(app, ["discover", "file", "my_files", "--json"]) @@ -631,7 +646,7 @@ def test_file_emits_run_id_as_json(mock_get_client: MagicMock, runner: CliRunner @patch(f"{MODULE}.get_client") def test_config_snapshot_writes_to_output(mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.get_discovery_run_config_snapshot_yaml.return_value = "# provenance\nlabels: []\n" diff --git a/tests/commands/test_discovery_config_libraries.py b/tests/commands/test_discovery_config_libraries.py index f92add3..3556246 100644 --- a/tests/commands/test_discovery_config_libraries.py +++ b/tests/commands/test_discovery_config_libraries.py @@ -13,13 +13,14 @@ from datamasque_cli.errors import ExitCode from datamasque_cli.main import app +from tests.conftest import DEFAULT_PROJECT_REFERENCE, make_project, with_projects MODULE = "datamasque_cli.commands.discovery_config_libraries" def _make_library( name: str, - namespace: str = "", + project: str = DEFAULT_PROJECT_REFERENCE, library_id: str = "lib-uuid", is_valid: ValidationStatus | None = ValidationStatus.valid, usage_count: int = 0, @@ -30,7 +31,7 @@ def _make_library( return SimpleNamespace( id=library_id, name=name, - namespace=namespace, + project=project, is_valid=is_valid, validation_error=validation_error, usage_count=usage_count, @@ -40,78 +41,142 @@ def _make_library( ) +ORG = make_project(2, "Org") +ORG_REFERENCE = ORG.reference + + +def _given_libraries(client: MagicMock, *libraries: SimpleNamespace) -> None: + """Make the mock serve `libraries` from the listing and, by id, with their YAML, in `Default` and `Org`.""" + with_projects(client, make_project(), ORG) + client.list_discovery_config_libraries.return_value = list(libraries) + client.get_discovery_config_library.side_effect = lambda library_id: next( + lib for lib in libraries if lib.id == library_id + ) + + @patch(f"{MODULE}.get_client") -def test_list_shows_namespace_and_usage(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() +def test_list_shows_project_and_usage(mock_get_client: MagicMock, runner: CliRunner) -> None: + client = with_projects(MagicMock()) mock_get_client.return_value = client - client.list_discovery_config_libraries.return_value = [ - _make_library("finance", namespace="org", usage_count=3), - ] + _given_libraries(client, _make_library("finance", project=ORG_REFERENCE, usage_count=3)) result = runner.invoke(app, ["discover", "libraries", "list", "--json"]) assert result.exit_code == 0 - assert '"finance"' in result.stdout - assert '"org"' in result.stdout - assert '"used_by": 3' in result.stdout + assert json.loads(result.stdout) == [ + {"id": "lib-uuid", "project": "Org", "name": "finance", "valid": "valid", "used_by": 3} + ] + + +@patch(f"{MODULE}.get_client") +def test_list_project_keeps_only_that_projects_libraries(mock_get_client: MagicMock, runner: CliRunner) -> None: + client = with_projects(MagicMock()) + mock_get_client.return_value = client + _given_libraries( + client, + _make_library("finance", library_id="default-lib"), + _make_library("payroll", project=ORG_REFERENCE, library_id="org-lib"), + ) + + result = runner.invoke(app, ["discover", "libraries", "list", "--project", "org", "--json"]) + + assert result.exit_code == 0 + assert json.loads(result.stdout) == [ + {"id": "org-lib", "project": "Org", "name": "payroll", "valid": "valid", "used_by": 0} + ] @patch(f"{MODULE}.get_client") -def test_get_yaml_fetches_full_library(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() +def test_get_yaml_fetches_the_named_projects_library(mock_get_client: MagicMock, runner: CliRunner) -> None: + client = with_projects(MagicMock()) mock_get_client.return_value = client - client.get_discovery_config_library_by_name.return_value = _make_library( - "finance", namespace="org", yaml="labels: []\n" + _given_libraries( + client, + _make_library("finance", library_id="default-lib", yaml="default: []\n"), + _make_library("finance", project=ORG_REFERENCE, library_id="org-lib", yaml="labels: []\n"), ) - result = runner.invoke(app, ["discover", "libraries", "get", "finance", "--namespace", "org", "--yaml"]) + result = runner.invoke(app, ["discover", "libraries", "get", "finance", "--project", "Org", "--yaml"]) assert result.exit_code == 0 assert "labels: []" in result.stdout - client.get_discovery_config_library_by_name.assert_called_once_with("finance", "org") + client.get_discovery_config_library.assert_called_once_with("org-lib") + + +@patch(f"{MODULE}.get_client") +def test_get_name_in_two_projects_asks_for_the_project(mock_get_client: MagicMock, runner: CliRunner) -> None: + client = with_projects(MagicMock()) + mock_get_client.return_value = client + _given_libraries( + client, + _make_library("finance", library_id="default-lib"), + _make_library("finance", project=ORG_REFERENCE, library_id="org-lib"), + ) + + result = runner.invoke(app, ["discover", "libraries", "get", "finance"]) + + assert result.exit_code == ExitCode.AMBIGUOUS + assert result.stderr == ( + "Error: Discovery config library 'finance' exists in more than one project:\n" + " project=Default\n" + " project=Org\n" + "Hint: Pass --project to disambiguate.\n" + ) + client.get_discovery_config_library.assert_not_called() @patch(f"{MODULE}.get_client") -def test_get_namespace_scopes_lookup(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() +def test_get_unknown_name_is_not_found(mock_get_client: MagicMock, runner: CliRunner) -> None: + client = with_projects(MagicMock()) mock_get_client.return_value = client - client.get_discovery_config_library_by_name.return_value = None + _given_libraries(client) result = runner.invoke(app, ["discover", "libraries", "get", "finance"]) assert result.exit_code == ExitCode.NOT_FOUND - client.get_discovery_config_library_by_name.assert_called_once_with("finance", "") + + +@patch(f"{MODULE}.get_client") +def test_get_unknown_project_is_not_found(mock_get_client: MagicMock, runner: CliRunner) -> None: + client = with_projects(MagicMock()) + mock_get_client.return_value = client + _given_libraries(client, _make_library("finance")) + + result = runner.invoke(app, ["discover", "libraries", "get", "finance", "--project", "nope"]) + + assert result.exit_code == ExitCode.NOT_FOUND + assert result.stderr == "Error: Project 'nope' not found.\n" @patch(f"{MODULE}.get_client") def test_create_posts_library(mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path) -> None: - client = MagicMock() + client = with_projects(MagicMock(), make_project(), ORG) mock_get_client.return_value = client lib = tmp_path / "lib.yaml" lib.write_text("labels: []\n") result = runner.invoke( app, - ["discover", "libraries", "create", "--name", "finance", "-n", "org", "-f", str(lib)], + ["discover", "libraries", "create", "--name", "finance", "--project", "Org", "-f", str(lib)], ) assert result.exit_code == 0 client.create_or_update_discovery_config_library.assert_called_once() created = client.create_or_update_discovery_config_library.call_args.args[0] assert created.name == "finance" - assert created.namespace == "org" + assert created.project == ORG_REFERENCE @patch(f"{MODULE}.get_client") def test_delete_force_passes_through(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client - client.get_discovery_config_library_by_name.return_value = _make_library("finance", namespace="org") + _given_libraries(client, _make_library("finance", project=ORG_REFERENCE, library_id="org-lib")) - result = runner.invoke(app, ["discover", "libraries", "delete", "finance", "-n", "org", "--force", "--yes"]) + result = runner.invoke(app, ["discover", "libraries", "delete", "finance", "--project", "Org", "--force", "--yes"]) assert result.exit_code == 0 - client.delete_discovery_config_library_by_name_if_exists.assert_called_once_with("finance", "org", force=True) + client.delete_discovery_config_library_by_id_if_exists.assert_called_once_with("org-lib", force=True) @patch(f"{MODULE}.get_client") @@ -122,16 +187,16 @@ def test_delete_in_use_reports_server_reason(mock_get_client: MagicMock, runner: its `detail` names the count. Without handling, the raised `DataMasqueApiError` escapes as an unhandled exception and the user only sees a stack trace. """ - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client - client.get_discovery_config_library_by_name.return_value = _make_library("finance") + _given_libraries(client, _make_library("finance")) response = MagicMock() response.status_code = HTTPStatus.CONFLICT response.json.return_value = { "detail": 'Cannot delete library "finance": used by 2 active config(s)', "configs": [{"id": "cfg-1", "name": "employees"}], } - client.delete_discovery_config_library_by_name_if_exists.side_effect = DataMasqueApiError( + client.delete_discovery_config_library_by_id_if_exists.side_effect = DataMasqueApiError( "API request to https://dm/api/discovery/config-libraries/lib-uuid/ failed with status 409", response=response, ) @@ -146,13 +211,13 @@ def test_delete_in_use_reports_server_reason(mock_get_client: MagicMock, runner: @patch(f"{MODULE}.get_client") def test_delete_other_api_error_is_generic_failure(mock_get_client: MagicMock, runner: CliRunner) -> None: """Non-409 API failures still abort cleanly rather than raising.""" - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client - client.get_discovery_config_library_by_name.return_value = _make_library("finance") + _given_libraries(client, _make_library("finance")) response = MagicMock() response.status_code = HTTPStatus.INTERNAL_SERVER_ERROR response.json.side_effect = ValueError("no body") - client.delete_discovery_config_library_by_name_if_exists.side_effect = DataMasqueApiError( + client.delete_discovery_config_library_by_id_if_exists.side_effect = DataMasqueApiError( "API request failed with status 500", response=response ) @@ -164,14 +229,14 @@ def test_delete_other_api_error_is_generic_failure(mock_get_client: MagicMock, r @patch(f"{MODULE}.get_client") def test_delete_missing_is_not_found(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client - client.get_discovery_config_library_by_name.return_value = None + _given_libraries(client) result = runner.invoke(app, ["discover", "libraries", "delete", "finance", "--yes"]) assert result.exit_code == ExitCode.NOT_FOUND - client.delete_discovery_config_library_by_name_if_exists.assert_not_called() + client.delete_discovery_config_library_by_id_if_exists.assert_not_called() @patch(f"{MODULE}.get_client") @@ -189,7 +254,7 @@ def test_validate_empty_file_aborts_before_any_request( @patch(f"{MODULE}.get_client") def test_validate_reports_valid(mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.create_discovery_config_library.return_value = _make_library("finance", is_valid=ValidationStatus.valid) lib = tmp_path / "lib.yaml" @@ -209,7 +274,7 @@ def test_validate_reports_valid(mock_get_client: MagicMock, runner: CliRunner, t def test_validate_rejected_create_aborts_without_delete( mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path ) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client response = MagicMock() response.status_code = HTTPStatus.BAD_REQUEST @@ -229,7 +294,7 @@ def test_validate_rejected_create_aborts_without_delete( @patch(f"{MODULE}.get_client") def test_validate_invalid_exits_4(mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.create_discovery_config_library.return_value = _make_library( "finance", is_valid=ValidationStatus.invalid, validation_error="duplicate label 'email'" @@ -249,7 +314,7 @@ def test_validate_puts_the_reason_in_the_agent_envelope( mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: monkeypatch.setenv("DM_OUTPUT", "json") - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.create_discovery_config_library.return_value = _make_library( "finance", is_valid=ValidationStatus.invalid, validation_error="duplicate label 'email'" @@ -269,7 +334,7 @@ def test_validate_puts_the_reason_in_the_agent_envelope( def test_validate_warns_when_temp_library_cleanup_fails( mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path ) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.create_discovery_config_library.return_value = _make_library("finance", is_valid=ValidationStatus.valid) client.delete_discovery_config_library_by_id_if_exists.side_effect = DataMasqueApiError( @@ -299,11 +364,9 @@ def test_status_reports_state( is_valid: ValidationStatus, validation_error: str | None, ) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client - client.get_discovery_config_library_by_name.return_value = _make_library( - "finance", is_valid=is_valid, validation_error=validation_error - ) + _given_libraries(client, _make_library("finance", is_valid=is_valid, validation_error=validation_error)) result = runner.invoke(app, ["discover", "libraries", "status", "finance", "--json"]) diff --git a/tests/commands/test_discovery_configs.py b/tests/commands/test_discovery_configs.py index e79f497..0e85b71 100644 --- a/tests/commands/test_discovery_configs.py +++ b/tests/commands/test_discovery_configs.py @@ -14,6 +14,7 @@ from datamasque_cli.errors import ExitCode from datamasque_cli.main import app +from tests.conftest import DEFAULT_PROJECT_REFERENCE, make_project, with_projects MODULE = "datamasque_cli.commands.discovery_configs" @@ -28,6 +29,7 @@ def _make_discovery_config( ) -> SimpleNamespace: """A discovery config as the server returns it, carrying its validation status.""" return SimpleNamespace( + project=DEFAULT_PROJECT_REFERENCE, id=config_id, name=name, config_type=config_type, @@ -51,7 +53,7 @@ def test_unknown_type_is_rejected_before_any_request(mock_get_client: MagicMock, @patch(f"{MODULE}.get_client") def test_list_filters_by_type(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.list_discovery_configs.return_value = [ _make_discovery_config("emp", DiscoveryConfigType.database), @@ -67,7 +69,7 @@ def test_list_filters_by_type(mock_get_client: MagicMock, runner: CliRunner) -> @patch(f"{MODULE}.get_client") def test_get_yaml_fetches_full_config(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.list_discovery_configs.return_value = [_make_discovery_config("emp")] client.get_discovery_config.return_value = _make_discovery_config("emp", yaml="labels: []\n") @@ -81,7 +83,7 @@ def test_get_yaml_fetches_full_config(mock_get_client: MagicMock, runner: CliRun @patch(f"{MODULE}.get_client") def test_get_ambiguous_name_aborts(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.list_discovery_configs.return_value = [ _make_discovery_config("shared", DiscoveryConfigType.database, config_id="a"), @@ -96,7 +98,7 @@ def test_get_ambiguous_name_aborts(mock_get_client: MagicMock, runner: CliRunner @patch(f"{MODULE}.get_client") def test_get_ambiguous_resolved_by_type(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.list_discovery_configs.return_value = [ _make_discovery_config("shared", DiscoveryConfigType.database, config_id="a"), @@ -112,7 +114,7 @@ def test_get_ambiguous_resolved_by_type(mock_get_client: MagicMock, runner: CliR @patch(f"{MODULE}.get_client") def test_defaults_requests_typed_default(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.make_request.return_value = SimpleNamespace(content=b"labels: []\n") @@ -127,7 +129,7 @@ def test_defaults_requests_typed_default(mock_get_client: MagicMock, runner: Cli @patch(f"{MODULE}.get_client") def test_create_new_requires_type(mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.list_discovery_configs.return_value = [] cfg = tmp_path / "cfg.yaml" @@ -146,7 +148,7 @@ def test_create_new_requires_type(mock_get_client: MagicMock, runner: CliRunner, @patch(f"{MODULE}.get_client") def test_create_update_defaults_to_existing_type(mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.list_discovery_configs.return_value = [_make_discovery_config("emp", DiscoveryConfigType.database)] cfg = tmp_path / "cfg.yaml" @@ -158,9 +160,30 @@ def test_create_update_defaults_to_existing_type(mock_get_client: MagicMock, run client.create_or_update_discovery_config.assert_called_once() +@patch(f"{MODULE}.get_client") +def test_create_of_a_new_type_ignores_the_other_types_project( + mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path +) -> None: + client = with_projects(MagicMock(), make_project(1, "Default"), make_project(2, "Finance")) + mock_get_client.return_value = client + file_config = _make_discovery_config("emp", DiscoveryConfigType.file) + file_config.project = "2-finance" + client.list_discovery_configs.return_value = [file_config] + cfg = tmp_path / "cfg.yaml" + cfg.write_text("labels: []\n") + + result = runner.invoke( + app, ["discover", "configs", "create", "--name", "emp", "-f", str(cfg), "--type", "database"] + ) + + assert result.exit_code == ExitCode.AMBIGUOUS + assert result.stderr == "Error: The instance has 2 active projects.\nHint: Pass --project to choose one.\n" + client.create_or_update_discovery_config.assert_not_called() + + @patch(f"{MODULE}.get_client") def test_delete_proceeds_when_present(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.list_discovery_configs.return_value = [_make_discovery_config("emp")] @@ -172,7 +195,7 @@ def test_delete_proceeds_when_present(mock_get_client: MagicMock, runner: CliRun @patch(f"{MODULE}.get_client") def test_delete_aborts_when_missing(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.list_discovery_configs.return_value = [] @@ -184,7 +207,7 @@ def test_delete_aborts_when_missing(mock_get_client: MagicMock, runner: CliRunne @patch(f"{MODULE}.get_client") def test_validate_reports_valid(mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.create_discovery_config.return_value = _make_discovery_config("emp", is_valid=ValidationStatus.valid) cfg = tmp_path / "cfg.yaml" @@ -203,7 +226,7 @@ def test_validate_reports_valid(mock_get_client: MagicMock, runner: CliRunner, t @patch(f"{MODULE}.get_client") def test_validate_invalid_exits_4(mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.create_discovery_config.return_value = _make_discovery_config( "emp", is_valid=ValidationStatus.invalid, validation_error="unknown label 'foo'" @@ -223,7 +246,7 @@ def test_validate_puts_the_reason_in_the_agent_envelope( mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: monkeypatch.setenv("DM_OUTPUT", "json") - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.create_discovery_config.return_value = _make_discovery_config( "emp", is_valid=ValidationStatus.invalid, validation_error="unknown label 'foo'" @@ -243,7 +266,7 @@ def test_validate_puts_the_reason_in_the_agent_envelope( def test_validate_rejected_create_aborts_without_delete( mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path ) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client response = MagicMock() response.status_code = HTTPStatus.BAD_REQUEST @@ -265,7 +288,7 @@ def test_validate_rejected_create_aborts_without_delete( def test_validate_warns_when_temp_config_cleanup_fails( mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path ) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.create_discovery_config.return_value = _make_discovery_config("emp", is_valid=ValidationStatus.valid) client.delete_discovery_config_by_id_if_exists.side_effect = DataMasqueApiError("boom", response=MagicMock()) @@ -322,7 +345,7 @@ def test_status_reports_state( is_valid: ValidationStatus, validation_error: str | None, ) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.list_discovery_configs.return_value = [ _make_discovery_config("emp", is_valid=is_valid, validation_error=validation_error) diff --git a/tests/commands/test_files.py b/tests/commands/test_files.py index cdfd7d5..65b58df 100644 --- a/tests/commands/test_files.py +++ b/tests/commands/test_files.py @@ -8,16 +8,19 @@ from datamasque_cli.errors import ExitCode from datamasque_cli.main import app +from tests.conftest import DEFAULT_PROJECT_REFERENCE, with_projects MODULE = "datamasque_cli.commands.files" @patch(f"{MODULE}.get_client") def test_delete_file_proceeds_when_present(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client - match = SnowflakeKeyFile(id="abc", name="mykey", created_date=datetime.now(tz=UTC)) - client.get_file_of_type_by_name.return_value = match + match = SnowflakeKeyFile( + id="abc", name="mykey", created_date=datetime.now(tz=UTC), project=DEFAULT_PROJECT_REFERENCE + ) + client.list_files_of_type.return_value = [match] result = runner.invoke(app, ["files", "delete", "snowflake-key", "mykey", "--yes"]) @@ -27,9 +30,9 @@ def test_delete_file_proceeds_when_present(mock_get_client: MagicMock, runner: C @patch(f"{MODULE}.get_client") def test_delete_file_aborts_when_missing(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client - client.get_file_of_type_by_name.return_value = None + client.list_files_of_type.return_value = [] result = runner.invoke(app, ["files", "delete", "snowflake-key", "nope", "--yes"]) diff --git a/tests/commands/test_project_options.py b/tests/commands/test_project_options.py new file mode 100644 index 0000000..704c4eb --- /dev/null +++ b/tests/commands/test_project_options.py @@ -0,0 +1,409 @@ +"""`--project` on list and create commands, and the project in their output.""" + +from __future__ import annotations + +import json +from datetime import UTC, datetime +from pathlib import Path +from types import SimpleNamespace +from unittest.mock import MagicMock, patch + +from datamasque.client.models.discovery_config import DiscoveryConfigType +from datamasque.client.models.files import SeedFile, SnowflakeKeyFile +from datamasque.client.models.ruleset import RulesetType +from typer.testing import CliRunner + +from datamasque_cli.errors import ExitCode +from datamasque_cli.main import app +from tests.conftest import make_api_response, make_project, with_projects + +DEFAULT = make_project(1, "Default") +FINANCE = make_project(2, "Finance") + + +def _client() -> MagicMock: + return with_projects(MagicMock(), DEFAULT, FINANCE) + + +def _ruleset(id_: int | str, name: str, project: str) -> SimpleNamespace: + return SimpleNamespace(id=id_, name=name, ruleset_type=RulesetType.database, yaml="", project=project) + + +@patch("datamasque_cli.commands.rulesets.get_client") +def test_rulesets_list_names_the_project(mock_get_client: MagicMock, runner: CliRunner) -> None: + client = _client() + mock_get_client.return_value = client + client.list_rulesets.return_value = [_ruleset(1, "customers", FINANCE.reference)] + + result = runner.invoke(app, ["rulesets", "list", "--json"]) + + assert result.exit_code == 0 + assert json.loads(result.stdout) == [{"id": 1, "project": "Finance", "name": "customers", "type": "database"}] + + +@patch("datamasque_cli.commands.rulesets.get_client") +def test_rulesets_list_project_keeps_only_that_projects_rulesets(mock_get_client: MagicMock, runner: CliRunner) -> None: + client = _client() + mock_get_client.return_value = client + client.list_rulesets.return_value = [ + _ruleset(1, "customers", DEFAULT.reference), + _ruleset(2, "payroll", FINANCE.reference), + ] + + result = runner.invoke(app, ["rulesets", "list", "--project", "finance", "--json"]) + + assert result.exit_code == 0 + assert [row["name"] for row in json.loads(result.stdout)] == ["payroll"] + + +@patch("datamasque_cli.commands.rulesets.get_client") +def test_rulesets_create_sends_the_project(mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path) -> None: + client = _client() + mock_get_client.return_value = client + client.list_rulesets.return_value = [] + ruleset_file = tmp_path / "rules.yaml" + ruleset_file.write_text("version: '1.0'\ntasks: []\n") + + result = runner.invoke( + app, + [ + "rulesets", + "create", + "--name", + "customers", + "--type", + "database", + "-f", + str(ruleset_file), + "--project", + "Finance", + ], + ) + + assert result.exit_code == 0 + assert client.create_or_update_ruleset.call_args.args[0].project == FINANCE.reference + + +@patch("datamasque_cli.commands.rulesets.get_client") +def test_rulesets_create_updates_where_the_name_already_is( + mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path +) -> None: + client = _client() + mock_get_client.return_value = client + client.list_rulesets.return_value = [_ruleset(1, "customers", FINANCE.reference)] + ruleset_file = tmp_path / "rules.yaml" + ruleset_file.write_text("version: '1.0'\ntasks: []\n") + + result = runner.invoke(app, ["rulesets", "create", "--name", "customers", "-f", str(ruleset_file)]) + + assert result.exit_code == 0 + assert client.create_or_update_ruleset.call_args.args[0].project == FINANCE.reference + + +@patch("datamasque_cli.commands.rulesets.get_client") +def test_rulesets_create_new_name_needs_a_project_once_there_are_two( + mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path +) -> None: + client = _client() + mock_get_client.return_value = client + client.list_rulesets.return_value = [] + ruleset_file = tmp_path / "rules.yaml" + ruleset_file.write_text("version: '1.0'\ntasks: []\n") + + result = runner.invoke( + app, ["rulesets", "create", "--name", "customers", "--type", "database", "-f", str(ruleset_file)] + ) + + assert result.exit_code == ExitCode.AMBIGUOUS + assert result.stderr == "Error: The instance has 2 active projects.\nHint: Pass --project to choose one.\n" + client.create_or_update_ruleset.assert_not_called() + + +@patch("datamasque_cli.commands.rulesets.get_client") +def test_rulesets_get_name_in_two_projects_asks_for_the_project(mock_get_client: MagicMock, runner: CliRunner) -> None: + client = _client() + mock_get_client.return_value = client + client.list_rulesets.return_value = [ + _ruleset(1, "customers", DEFAULT.reference), + _ruleset(2, "customers", FINANCE.reference), + ] + + result = runner.invoke(app, ["rulesets", "get", "customers"]) + + assert result.exit_code == ExitCode.AMBIGUOUS + assert result.stderr == ( + "Error: Multiple rulesets named 'customers':\n" + " id=1 type=database project=Default\n" + " id=2 type=database project=Finance\n" + "Hint: Pass --type database|file or --project to disambiguate.\n" + ) + + +@patch("datamasque_cli.commands.rulesets.get_client") +def test_rulesets_get_project_picks_between_same_named_rulesets(mock_get_client: MagicMock, runner: CliRunner) -> None: + client = _client() + mock_get_client.return_value = client + client.list_rulesets.return_value = [ + _ruleset("rs-1", "customers", DEFAULT.reference), + _ruleset("rs-2", "customers", FINANCE.reference), + ] + client.make_request.return_value = make_api_response( + {"id": "rs-2", "name": "customers", "mask_type": "database", "config_yaml": "x", "project": FINANCE.reference} + ) + + result = runner.invoke(app, ["rulesets", "get", "customers", "--project", "Finance", "--json"]) + + assert result.exit_code == 0 + client.make_request.assert_called_once_with("GET", "/api/rulesets/rs-2/") + assert json.loads(result.stdout)["project"] == "Finance" + + +@patch("datamasque_cli.commands.connections.get_client") +def test_connections_create_sends_the_project(mock_get_client: MagicMock, runner: CliRunner) -> None: + client = _client() + mock_get_client.return_value = client + + result = runner.invoke( + app, + [ + "connections", + "create", + "--name", + "share", + "--type", + "mounted_share", + "--base-dir", + "in", + "--source", + "--project", + "Finance", + ], + ) + + assert result.exit_code == 0 + assert client.create_or_update_connection.call_args.args[0].project == FINANCE.reference + + +@patch("datamasque_cli.commands.connections.get_client") +def test_connections_list_names_the_project(mock_get_client: MagicMock, runner: CliRunner) -> None: + client = _client() + mock_get_client.return_value = client + client.list_connections.return_value = [ + SimpleNamespace(id=1, name="db", project=FINANCE.reference, is_file_mask_source=False) + ] + + result = runner.invoke(app, ["connections", "list", "--json"]) + + assert result.exit_code == 0 + assert json.loads(result.stdout)[0]["project"] == "Finance" + + +@patch("datamasque_cli.commands.seeds.get_client") +def test_seeds_upload_needs_a_project_once_there_are_two( + mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path +) -> None: + client = _client() + mock_get_client.return_value = client + seed = tmp_path / "names.csv" + seed.write_text("name\nann\n") + + result = runner.invoke(app, ["seeds", "upload", str(seed)]) + + assert result.exit_code == ExitCode.AMBIGUOUS + assert result.stderr == "Error: The instance has 2 active projects.\nHint: Pass --project to choose one.\n" + client.upload_file.assert_not_called() + + +@patch("datamasque_cli.commands.seeds.get_client") +def test_seeds_upload_goes_to_the_named_project(mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path) -> None: + client = _client() + mock_get_client.return_value = client + seed = tmp_path / "names.csv" + seed.write_text("name\nann\n") + + result = runner.invoke(app, ["seeds", "upload", str(seed), "--project", "Finance"]) + + assert result.exit_code == 0 + client.upload_file.assert_called_once_with(SeedFile, "names.csv", seed, project=FINANCE.id) + + +@patch("datamasque_cli.commands.seeds.get_client") +def test_seeds_list_project_asks_the_server_and_names_built_ins_blank( + mock_get_client: MagicMock, runner: CliRunner +) -> None: + client = _client() + mock_get_client.return_value = client + stamp = datetime.now(tz=UTC) + client.list_files_of_type.return_value = [ + SeedFile(id="a", name="names.csv", created_date=stamp, project=FINANCE.reference), + SeedFile(id="b", name="DataMasque_first_names.csv", created_date=stamp, project=None), + ] + + result = runner.invoke(app, ["seeds", "list", "--project", "Finance", "--json"]) + + assert result.exit_code == 0 + client.list_files_of_type.assert_called_once_with(SeedFile, project=FINANCE.id) + assert [row["project"] for row in json.loads(result.stdout)] == ["Finance", ""] + + +@patch("datamasque_cli.commands.runs.get_client") +def test_runs_list_project_is_filtered_on_the_server(mock_get_client: MagicMock, runner: CliRunner) -> None: + client = _client() + mock_get_client.return_value = client + client.make_request.return_value = make_api_response( + {"results": [{"id": 7, "run_status": "finished", "project": FINANCE.reference}]} + ) + + result = runner.invoke(app, ["run", "list", "--project", "Finance", "--json"]) + + assert result.exit_code == 0 + client.make_request.assert_called_once_with("GET", "/api/runs/?project=2&limit=20") + assert json.loads(result.stdout)[0]["project"] == "Finance" + + +@patch("datamasque_cli.commands.table_references.get_client") +def test_table_references_create_sends_the_project(mock_get_client: MagicMock, runner: CliRunner) -> None: + client = _client() + mock_get_client.return_value = client + client.list_table_references.return_value = [] + client.list_connections.return_value = [SimpleNamespace(id="conn-1", name="input", project=FINANCE.reference)] + + result = runner.invoke( + app, + [ + "table-references", + "create", + "--name", + "ids", + "--connection", + "input", + "--source", + "a.csv", + "--project", + "Finance", + ], + ) + + assert result.exit_code == 0 + assert client.create_or_update_table_reference.call_args.args[0].project == FINANCE.reference + + +@patch("datamasque_cli.commands.connections.get_client") +def test_connections_list_project_keeps_only_that_projects_connections( + mock_get_client: MagicMock, runner: CliRunner +) -> None: + client = _client() + mock_get_client.return_value = client + client.list_connections.return_value = [ + SimpleNamespace(id=1, name="db", project=DEFAULT.reference, is_file_mask_source=False), + SimpleNamespace(id=2, name="warehouse", project=FINANCE.reference, is_file_mask_source=False), + ] + + result = runner.invoke(app, ["connections", "list", "--project", "Finance", "--json"]) + + assert result.exit_code == 0 + assert [row["name"] for row in json.loads(result.stdout)] == ["warehouse"] + + +def _discovery_config(id_: str, name: str, project: str) -> SimpleNamespace: + return SimpleNamespace( + id=id_, name=name, config_type=DiscoveryConfigType.database, is_valid=None, yaml="", project=project + ) + + +@patch("datamasque_cli.commands.discovery_configs.get_client") +def test_discovery_configs_list_names_the_project_and_keeps_only_that_projects_configs( + mock_get_client: MagicMock, runner: CliRunner +) -> None: + client = _client() + mock_get_client.return_value = client + client.list_discovery_configs.return_value = [ + _discovery_config("c-1", "pii", DEFAULT.reference), + _discovery_config("c-2", "payroll", FINANCE.reference), + ] + + result = runner.invoke(app, ["discover", "configs", "list", "--project", "Finance", "--json"]) + + assert result.exit_code == 0 + assert [(row["name"], row["project"]) for row in json.loads(result.stdout)] == [("payroll", "Finance")] + + +@patch("datamasque_cli.commands.discovery_configs.get_client") +def test_discovery_configs_create_sends_the_project( + mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path +) -> None: + client = _client() + mock_get_client.return_value = client + client.list_discovery_configs.return_value = [] + config_file = tmp_path / "config.yaml" + config_file.write_text("labels: []\n") + + result = runner.invoke( + app, + [ + "discover", + "configs", + "create", + "--name", + "payroll", + "--type", + "database", + "-f", + str(config_file), + "--project", + "Finance", + ], + ) + + assert result.exit_code == 0 + assert client.create_or_update_discovery_config.call_args.args[0].project == FINANCE.reference + + +@patch("datamasque_cli.commands.files.get_client") +def test_files_list_project_asks_the_server_and_names_the_project( + mock_get_client: MagicMock, runner: CliRunner +) -> None: + client = _client() + mock_get_client.return_value = client + stamp = datetime.now(tz=UTC) + client.list_files_of_type.return_value = [ + SnowflakeKeyFile(id="k", name="key.p8", created_date=stamp, project=FINANCE.reference) + ] + + result = runner.invoke(app, ["files", "list", "snowflake-key", "--project", "Finance", "--json"]) + + assert result.exit_code == 0 + client.list_files_of_type.assert_called_once_with(SnowflakeKeyFile, project=FINANCE.id) + assert json.loads(result.stdout) == [{"id": "k", "project": "Finance", "name": "key.p8"}] + + +@patch("datamasque_cli.commands.files.get_client") +def test_files_upload_goes_to_the_named_project(mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path) -> None: + client = _client() + mock_get_client.return_value = client + key = tmp_path / "key.p8" + key.write_text("-----BEGIN PRIVATE KEY-----\n") + + result = runner.invoke( + app, ["files", "upload", "snowflake-key", "-f", str(key), "--name", "key.p8", "--project", "Finance"] + ) + + assert result.exit_code == 0 + client.upload_file.assert_called_once_with(SnowflakeKeyFile, "key.p8", key, project=FINANCE.id) + + +@patch("datamasque_cli.commands.table_references.get_client") +def test_table_references_list_project_keeps_only_that_projects_references( + mock_get_client: MagicMock, runner: CliRunner +) -> None: + client = _client() + mock_get_client.return_value = client + client.list_table_references.return_value = [ + SimpleNamespace(id="t-1", name="ids", connection_id="c", source="a.csv", project=DEFAULT.reference), + SimpleNamespace(id="t-2", name="codes", connection_id="c", source="b.csv", project=FINANCE.reference), + ] + + result = runner.invoke(app, ["table-references", "list", "--project", "Finance", "--json"]) + + assert result.exit_code == 0 + assert [(row["name"], row["project"]) for row in json.loads(result.stdout)] == [("codes", "Finance")] diff --git a/tests/commands/test_projects.py b/tests/commands/test_projects.py new file mode 100644 index 0000000..50a66de --- /dev/null +++ b/tests/commands/test_projects.py @@ -0,0 +1,223 @@ +from __future__ import annotations + +import json +from collections.abc import Iterator +from http import HTTPStatus +from unittest.mock import MagicMock, patch + +import pytest +from datamasque.client.exceptions import DataMasqueApiError, ProjectDeleteConflictError +from datamasque.client.models.project import ( + Project, + ProjectCreateRequest, + ProjectDeleteConflict, + ProjectDeleteConflictReason, + ProjectUpdateRequest, +) +from typer.testing import CliRunner + +from datamasque_cli.errors import ExitCode +from datamasque_cli.main import app +from tests.conftest import make_api_response, make_project, with_projects + +MODULE = "datamasque_cli.commands.projects" + +DEFAULT = make_project(1, "Default") +FINANCE = make_project(2, "Finance") +OLD = make_project(3, "Old") + +NAME_CLASH = ProjectDeleteConflict( + reason=ProjectDeleteConflictReason.name_in_use, + detail='Ruleset "customers" exists.', +) + +CONFLICT_ERROR = ( + 'Error: The project\'s resources cannot move to the destination project:\n Ruleset "customers" exists.\n' +) + + +def _api_error(status: HTTPStatus, detail: str) -> DataMasqueApiError: + response = make_api_response({"detail": detail}, is_ok=False) + response.status_code = status + return DataMasqueApiError(detail, response=response) + + +def _with_deleted_projects(client: MagicMock, *deleted: Project) -> None: + """Make `list_projects` return `Default` and `Finance`, and the `deleted` projects first when they are included.""" + client.list_projects.side_effect = lambda include_archived=False: ( + [*deleted, DEFAULT, FINANCE] if include_archived else [DEFAULT, FINANCE] + ) + + +@pytest.fixture() +def client() -> Iterator[MagicMock]: + client = with_projects(MagicMock(), DEFAULT, FINANCE) + with patch(f"{MODULE}.get_client", return_value=client): + yield client + + +def test_list_shows_the_active_projects(client: MagicMock, runner: CliRunner) -> None: + result = runner.invoke(app, ["projects", "list", "--json"]) + + assert result.exit_code == 0 + assert [(p["id"], p["name"]) for p in json.loads(result.stdout)] == [(1, "Default"), (2, "Finance")] + client.list_projects.assert_called_once_with() + + +def test_list_include_deleted_marks_the_deleted_projects(client: MagicMock, runner: CliRunner) -> None: + _with_deleted_projects(client, OLD) + + result = runner.invoke(app, ["projects", "list", "--include-deleted", "--json"]) + + assert result.exit_code == 0 + assert [(p["name"], p["deleted"]) for p in json.loads(result.stdout)] == [ + ("Old", True), + ("Default", False), + ("Finance", False), + ] + + +@pytest.mark.parametrize("given", ["finance", "2"]) +def test_get_finds_a_project_by_name_in_any_case_or_by_id(client: MagicMock, runner: CliRunner, given: str) -> None: + result = runner.invoke(app, ["projects", "get", given, "--json"]) + + assert result.exit_code == 0 + found = json.loads(result.stdout) + assert (found["name"], found["deleted"]) == ("Finance", False) + + +def test_get_finds_a_deleted_project_by_id(client: MagicMock, runner: CliRunner) -> None: + _with_deleted_projects(client, OLD) + + result = runner.invoke(app, ["projects", "get", "3", "--json"]) + + assert result.exit_code == 0 + found = json.loads(result.stdout) + assert (found["id"], found["name"], found["deleted"]) == (3, "Old", True) + + +def test_get_by_name_finds_the_active_project_not_a_deleted_one_of_that_name( + client: MagicMock, runner: CliRunner +) -> None: + _with_deleted_projects(client, make_project(4, "Finance")) + + result = runner.invoke(app, ["projects", "get", "finance", "--json"]) + + assert result.exit_code == 0 + found = json.loads(result.stdout) + assert (found["id"], found["deleted"]) == (2, False) + + +def test_get_of_an_unknown_id_is_not_found(client: MagicMock, runner: CliRunner) -> None: + _with_deleted_projects(client, OLD) + + result = runner.invoke(app, ["projects", "get", "99"]) + + assert result.exit_code == ExitCode.NOT_FOUND + assert result.stderr == "Error: Project '99' not found.\n" + + +def test_get_of_an_unknown_project_is_not_found(client: MagicMock, runner: CliRunner) -> None: + result = runner.invoke(app, ["projects", "get", "nope"]) + + assert result.exit_code == ExitCode.NOT_FOUND + assert result.stderr == "Error: Project 'nope' not found.\n" + + +def test_create_sends_the_name_and_description(client: MagicMock, runner: CliRunner) -> None: + client.create_project.return_value = make_project(4, "Sales") + + result = runner.invoke(app, ["projects", "create", "--name", "Sales", "--description", "Sales team"]) + + assert result.exit_code == 0 + client.create_project.assert_called_once_with(ProjectCreateRequest(name="Sales", description="Sales team")) + + +def test_create_rejected_by_the_server_shows_its_reason(client: MagicMock, runner: CliRunner) -> None: + client.create_project.side_effect = _api_error(HTTPStatus.BAD_REQUEST, "Name in use.") + + result = runner.invoke(app, ["projects", "create", "--name", "finance"]) + + assert result.exit_code == ExitCode.INVALID_INPUT + assert result.stderr == "Error: Failed to create project 'finance': Name in use.\n" + + +@pytest.mark.parametrize( + ("options", "request_sent"), + [ + (["--name", "Accounts"], ProjectUpdateRequest(name="Accounts")), + (["--description", "Accounts team"], ProjectUpdateRequest(description="Accounts team")), + ], + ids=["name", "description"], +) +def test_update_sends_only_the_fields_given( + client: MagicMock, runner: CliRunner, options: list[str], request_sent: ProjectUpdateRequest +) -> None: + client.update_project.return_value = FINANCE + + result = runner.invoke(app, ["projects", "update", "finance", *options]) + + assert result.exit_code == 0 + client.update_project.assert_called_once_with(FINANCE, request_sent) + + +def test_update_with_nothing_to_change_is_rejected_without_a_request(client: MagicMock, runner: CliRunner) -> None: + result = runner.invoke(app, ["projects", "update", "finance"]) + + assert result.exit_code == ExitCode.INVALID_INPUT + assert result.stderr == "Error: Nothing to update.\nHint: Pass --name, --description or both.\n" + client.update_project.assert_not_called() + + +def test_delete_moves_the_resources_to_the_destination(client: MagicMock, runner: CliRunner) -> None: + result = runner.invoke(app, ["projects", "delete", "finance", "--to", "default", "--yes"]) + + assert result.exit_code == 0 + client.delete_project.assert_called_once_with(FINANCE, DEFAULT) + client.get_project_delete_conflicts.assert_not_called() + client.list_projects.assert_called_once_with() + + +def test_delete_refused_by_a_conflict_lists_it(client: MagicMock, runner: CliRunner) -> None: + response = make_api_response({}, is_ok=False) + response.status_code = HTTPStatus.CONFLICT + client.delete_project.side_effect = ProjectDeleteConflictError( + "conflict", response=response, conflicts=[NAME_CLASH] + ) + + result = runner.invoke(app, ["projects", "delete", "finance", "--to", "default", "--yes"]) + + assert result.exit_code == ExitCode.CONFLICT + assert result.stderr == CONFLICT_ERROR + + +def test_delete_declined_at_the_prompt_deletes_nothing(client: MagicMock, runner: CliRunner) -> None: + result = runner.invoke(app, ["projects", "delete", "finance", "--to", "default"], input="n\n") + + assert result.exit_code == ExitCode.CANCELLED + client.delete_project.assert_not_called() + + +@pytest.mark.parametrize( + ("conflicts", "exit_code", "stderr"), + [ + ([], 0, "Project 'Finance' can be deleted, moving its resources to 'Default'.\n"), + ([NAME_CLASH], ExitCode.CONFLICT, CONFLICT_ERROR), + ], + ids=["no-conflicts", "conflict"], +) +def test_delete_check_reports_the_conflicts_without_deleting( + client: MagicMock, + runner: CliRunner, + conflicts: list[ProjectDeleteConflict], + exit_code: int, + stderr: str, +) -> None: + client.get_project_delete_conflicts.return_value = conflicts + + result = runner.invoke(app, ["projects", "delete", "finance", "--to", "default", "--check"]) + + assert result.exit_code == exit_code + assert result.stderr == stderr + client.get_project_delete_conflicts.assert_called_once_with(FINANCE, DEFAULT) + client.delete_project.assert_not_called() diff --git a/tests/commands/test_resources.py b/tests/commands/test_resources.py new file mode 100644 index 0000000..e4e9e61 --- /dev/null +++ b/tests/commands/test_resources.py @@ -0,0 +1,183 @@ +from __future__ import annotations + +from collections.abc import Iterator +from unittest.mock import MagicMock, patch + +import pytest +from datamasque.client.exceptions import ResourceMoveConflictError +from datamasque.client.models.resource import ( + Resource, + ResourceMoveConflict, + ResourceMoveConflictReason, + ResourceMoveResult, +) +from datamasque.client.models.resource_type import ResourceTypeName +from typer.testing import CliRunner + +from datamasque_cli.errors import ExitCode +from datamasque_cli.main import app +from tests.conftest import make_project, with_projects + +MODULE = "datamasque_cli.commands.resources" + +DEFAULT = make_project(1, "Default") +FINANCE = make_project(2, "Finance") + +CUSTOMERS = Resource(id="r1", name="customers", project=FINANCE.reference) +ORDERS = Resource(id="r2", name="orders", project=FINANCE.reference) +ALREADY_THERE = Resource(id="r3", name="customers", project=DEFAULT.reference) +BUILT_IN_SEED = Resource(id="s1", name="first_names.csv", project=None) + +CUSTOMERS_CLASH = ResourceMoveConflict( + reason=ResourceMoveConflictReason.name_in_use, + detail='Ruleset "customers" exists.', + type=ResourceTypeName.rulesets, + id="r1", + name="customers", +) + + +@pytest.fixture() +def client() -> Iterator[MagicMock]: + client = with_projects(MagicMock(), DEFAULT, FINANCE) + client.list_resources.return_value = { + ResourceTypeName.rulesets: [CUSTOMERS, ORDERS, ALREADY_THERE], + ResourceTypeName.seeds: [BUILT_IN_SEED], + } + client.move_resources.return_value = ResourceMoveResult(moved=2) + with patch(f"{MODULE}.get_client", return_value=client): + yield client + + +def test_move_project_sends_its_resources_and_filters(client: MagicMock, runner: CliRunner) -> None: + result = runner.invoke( + app, + [ + "resources", + "move", + "--project", + "finance", + "--type", + "rulesets", + "--search", + "cust", + "--to", + "default", + "-y", + ], + ) + + assert result.exit_code == 0 + client.list_projects.assert_called_once_with() + client.list_resources.assert_called_once_with(projects=[FINANCE], types=[ResourceTypeName.rulesets], search="cust") + client.move_resources.assert_called_once_with({ResourceTypeName.rulesets: [CUSTOMERS, ORDERS]}, DEFAULT) + + +def test_move_names_select_exact_names_only(client: MagicMock, runner: CliRunner) -> None: + client.list_resources.return_value = { + ResourceTypeName.rulesets: [CUSTOMERS, Resource(id="r4", name="customers_v2", project=FINANCE.reference)], + } + + result = runner.invoke(app, ["resources", "move", "customers", "--to", "default", "-y"]) + + assert result.exit_code == 0 + client.move_resources.assert_called_once_with({ResourceTypeName.rulesets: [CUSTOMERS]}, DEFAULT) + + +def test_move_with_a_name_that_matches_nothing_moves_nothing_and_is_not_found( + client: MagicMock, runner: CliRunner +) -> None: + result = runner.invoke(app, ["resources", "move", "customers", "typo", "other", "--to", "default", "-y"]) + + assert result.exit_code == ExitCode.NOT_FOUND + assert result.stderr == ( + "Error: No resources named 'typo', 'other'.\n" + "Hint: Check the names, and that --project, --type and --search select them.\n" + ) + client.move_resources.assert_not_called() + + +def test_move_name_of_a_resource_that_cannot_move_is_not_reported_missing(client: MagicMock, runner: CliRunner) -> None: + result = runner.invoke(app, ["resources", "move", "first_names.csv", "--to", "default", "-y"]) + + assert result.exit_code == ExitCode.NOT_FOUND + assert result.stderr == "Error: No resources to move to 'Default'.\n" + + +def test_move_without_any_selection_is_rejected_without_a_request(client: MagicMock, runner: CliRunner) -> None: + result = runner.invoke(app, ["resources", "move", "--to", "default", "-y"]) + + assert result.exit_code == ExitCode.INVALID_INPUT + assert result.stderr == ( + "Error: Select the resources to move.\nHint: Pass resource names, --project, --type or --search.\n" + ) + client.list_resources.assert_not_called() + + +def test_move_with_nothing_outside_the_destination_is_not_found(client: MagicMock, runner: CliRunner) -> None: + client.list_resources.return_value = { + ResourceTypeName.rulesets: [ALREADY_THERE], + ResourceTypeName.seeds: [BUILT_IN_SEED], + } + + result = runner.invoke(app, ["resources", "move", "--search", "c", "--to", "default", "-y"]) + + assert result.exit_code == ExitCode.NOT_FOUND + assert result.stderr == "Error: No resources to move to 'Default'.\n" + client.move_resources.assert_not_called() + + +def test_move_with_a_conflict_says_none_moved_and_names_it(client: MagicMock, runner: CliRunner) -> None: + response = MagicMock(status_code=409) + client.move_resources.side_effect = ResourceMoveConflictError( + "No resources moved.", response=response, conflicts=[CUSTOMERS_CLASH] + ) + + result = runner.invoke(app, ["resources", "move", "--project", "finance", "--to", "default", "-y"]) + + assert result.exit_code == ExitCode.CONFLICT + assert result.stderr == "Error: No resources moved to 'Default':\n Ruleset \"customers\" exists.\n" + + +def test_move_lists_a_detail_shared_by_several_conflicts_once(client: MagicMock, runner: CliRunner) -> None: + orders_clash = CUSTOMERS_CLASH.model_copy(update={"id": "r2", "name": "orders"}) + client.get_resource_move_conflicts.return_value = [CUSTOMERS_CLASH, orders_clash] + + result = runner.invoke(app, ["resources", "move", "--project", "finance", "--to", "default", "--check"]) + + assert result.exit_code == ExitCode.CONFLICT + assert result.stderr == 'Error: No resources would move:\n Ruleset "customers" exists.\n' + + +def test_move_declined_at_the_prompt_moves_nothing(client: MagicMock, runner: CliRunner) -> None: + result = runner.invoke(app, ["resources", "move", "--project", "finance", "--to", "default"], input="n\n") + + assert result.exit_code == ExitCode.CANCELLED + client.move_resources.assert_not_called() + + +@pytest.mark.parametrize( + ("conflicts", "exit_code", "stderr"), + [ + ([], 0, "All 2 resources can move to 'Default'.\n"), + ( + [CUSTOMERS_CLASH], + ExitCode.CONFLICT, + 'Error: No resources would move:\n Ruleset "customers" exists.\n', + ), + ], + ids=["no-conflicts", "conflict"], +) +def test_move_check_reports_the_conflicts_without_moving( + client: MagicMock, runner: CliRunner, conflicts: list[ResourceMoveConflict], exit_code: int, stderr: str +) -> None: + client.get_resource_move_conflicts.return_value = conflicts + + result = runner.invoke(app, ["resources", "move", "--project", "finance", "--to", "default", "--check"]) + + assert result.exit_code == exit_code + assert result.stderr == stderr + client.get_resource_move_conflicts.assert_called_once_with( + {ResourceTypeName.rulesets: [CUSTOMERS, ORDERS]}, DEFAULT + ) + client.move_resources.assert_not_called() diff --git a/tests/commands/test_ruleset_libraries.py b/tests/commands/test_ruleset_libraries.py index 78635e8..44df5d7 100644 --- a/tests/commands/test_ruleset_libraries.py +++ b/tests/commands/test_ruleset_libraries.py @@ -2,37 +2,153 @@ import json from http import HTTPStatus +from pathlib import Path from types import SimpleNamespace from unittest.mock import MagicMock, patch import pytest from datamasque.client.exceptions import DataMasqueApiError +from datamasque.client.models.ruleset import RulesetType from datamasque.client.models.status import ValidationErrorDetails, ValidationStatus from typer.testing import CliRunner from datamasque_cli.errors import ExitCode from datamasque_cli.main import app +from tests.conftest import DEFAULT_PROJECT_REFERENCE, make_project, with_projects MODULE = "datamasque_cli.commands.ruleset_libraries" def _make_ruleset_library( name: str, - namespace: str = "", + project: str = DEFAULT_PROJECT_REFERENCE, library_id: str = "lib-uuid", is_valid: ValidationStatus | None = None, validation_errors: list[ValidationErrorDetails] | None = None, + yaml: str = "", ) -> SimpleNamespace: """A ruleset library as the server returns it, carrying its validation status.""" return SimpleNamespace( id=library_id, name=name, - namespace=namespace, + project=project, is_valid=is_valid, validation_errors=validation_errors or [], + yaml=yaml, + created=None, + modified=None, ) +ORG = make_project(2, "Org") +ORG_REFERENCE = ORG.reference + + +def _given_libraries(client: MagicMock, *libraries: SimpleNamespace) -> None: + """Make the mock serve `libraries` from the listing and, by id, with their YAML, in `Default` and `Org`.""" + with_projects(client, make_project(), ORG) + client.list_ruleset_libraries.return_value = list(libraries) + client.get_ruleset_library.side_effect = lambda library_id: next(lib for lib in libraries if lib.id == library_id) + + +@patch(f"{MODULE}.get_client") +def test_list_project_keeps_only_that_projects_libraries(mock_get_client: MagicMock, runner: CliRunner) -> None: + client = MagicMock() + mock_get_client.return_value = client + _given_libraries( + client, + _make_ruleset_library("finance", library_id="default-lib"), + _make_ruleset_library("payroll", project=ORG_REFERENCE, library_id="org-lib"), + ) + + result = runner.invoke(app, ["libraries", "list", "--project", "org", "--json"]) + + assert result.exit_code == 0 + assert [lib["name"] for lib in json.loads(result.stdout)] == ["payroll"] + + +@patch(f"{MODULE}.get_client") +def test_list_names_the_project(mock_get_client: MagicMock, runner: CliRunner) -> None: + client = MagicMock() + mock_get_client.return_value = client + _given_libraries(client, _make_ruleset_library("payroll", project=ORG_REFERENCE, library_id="org-lib")) + + result = runner.invoke(app, ["libraries", "list", "--json"]) + + assert result.exit_code == 0 + assert json.loads(result.stdout) == [{"id": "org-lib", "project": "Org", "name": "payroll", "valid": "unknown"}] + + +@patch(f"{MODULE}.get_client") +def test_usage_names_each_rulesets_project(mock_get_client: MagicMock, runner: CliRunner) -> None: + client = MagicMock() + mock_get_client.return_value = client + _given_libraries(client, _make_ruleset_library("finance", library_id="lib-1")) + client.list_rulesets_using_library.return_value = [ + SimpleNamespace(id="rs-1", name="customers", ruleset_type=RulesetType.database, project=ORG_REFERENCE) + ] + + result = runner.invoke(app, ["libraries", "usage", "finance", "--json"]) + + assert result.exit_code == 0 + assert json.loads(result.stdout) == [{"id": "rs-1", "project": "Org", "name": "customers", "type": "database"}] + + +@patch(f"{MODULE}.get_client") +def test_get_yaml_fetches_the_named_projects_library(mock_get_client: MagicMock, runner: CliRunner) -> None: + client = MagicMock() + mock_get_client.return_value = client + _given_libraries( + client, + _make_ruleset_library("finance", library_id="default-lib", yaml="default: []\n"), + _make_ruleset_library("finance", project=ORG_REFERENCE, library_id="org-lib", yaml="org: []\n"), + ) + + result = runner.invoke(app, ["libraries", "get", "finance", "--project", "Org", "--yaml"]) + + assert result.exit_code == 0 + assert result.stdout == "org: []\n\n" + client.get_ruleset_library.assert_called_once_with("org-lib") + + +@patch(f"{MODULE}.get_client") +def test_get_name_in_two_projects_asks_for_the_project(mock_get_client: MagicMock, runner: CliRunner) -> None: + client = MagicMock() + mock_get_client.return_value = client + _given_libraries( + client, + _make_ruleset_library("finance", library_id="default-lib"), + _make_ruleset_library("finance", project=ORG_REFERENCE, library_id="org-lib"), + ) + + result = runner.invoke(app, ["libraries", "get", "finance"]) + + assert result.exit_code == ExitCode.AMBIGUOUS + assert result.stderr == ( + "Error: Library 'finance' exists in more than one project:\n" + " project=Default\n" + " project=Org\n" + "Hint: Pass --project to disambiguate.\n" + ) + client.get_ruleset_library.assert_not_called() + + +@patch(f"{MODULE}.get_client") +def test_create_sends_the_named_project(mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path) -> None: + client = MagicMock() + mock_get_client.return_value = client + _given_libraries(client) + lib = tmp_path / "lib.yaml" + lib.write_text("version: '1.0'\n") + + result = runner.invoke(app, ["libraries", "create", "--name", "finance", "--project", "Org", "-f", str(lib)]) + + assert result.exit_code == 0 + created = client.create_or_update_ruleset_library.call_args.args[0] + assert created.name == "finance" + assert created.project == ORG_REFERENCE + + @patch(f"{MODULE}.get_client") def test_delete_in_use_reports_server_reason(mock_get_client: MagicMock, runner: CliRunner) -> None: """A 409 must surface the server's explanation, not a traceback. @@ -43,14 +159,14 @@ def test_delete_in_use_reports_server_reason(mock_get_client: MagicMock, runner: """ client = MagicMock() mock_get_client.return_value = client - client.get_ruleset_library_by_name.return_value = _make_ruleset_library("lib") + _given_libraries(client, _make_ruleset_library("lib")) response = MagicMock() response.status_code = HTTPStatus.CONFLICT response.json.return_value = { "detail": 'Cannot delete library "lib": used by 3 active ruleset(s)', "rulesets": [{"id": "rs-1", "name": "customers"}], } - client.delete_ruleset_library_by_name_if_exists.side_effect = DataMasqueApiError( + client.delete_ruleset_library_by_id_if_exists.side_effect = DataMasqueApiError( "API request to https://dm/api/ruleset-libraries/lib-uuid/ failed with status 409", response=response ) @@ -65,31 +181,31 @@ def test_delete_in_use_reports_server_reason(mock_get_client: MagicMock, runner: def test_delete_library_aborts_when_missing(mock_get_client: MagicMock, runner: CliRunner) -> None: client = MagicMock() mock_get_client.return_value = client - client.get_ruleset_library_by_name.return_value = None + _given_libraries(client) result = runner.invoke(app, ["libraries", "delete", "nope", "--yes"]) assert result.exit_code == ExitCode.NOT_FOUND - client.delete_ruleset_library_by_name_if_exists.assert_not_called() + client.delete_ruleset_library_by_id_if_exists.assert_not_called() @patch(f"{MODULE}.get_client") def test_delete_library_proceeds_when_present(mock_get_client: MagicMock, runner: CliRunner) -> None: client = MagicMock() mock_get_client.return_value = client - client.get_ruleset_library_by_name.return_value = SimpleNamespace(id=1, name="lib", namespace="") + _given_libraries(client, SimpleNamespace(id=1, name="lib", project=DEFAULT_PROJECT_REFERENCE)) result = runner.invoke(app, ["libraries", "delete", "lib", "--yes"]) assert result.exit_code == 0 - client.delete_ruleset_library_by_name_if_exists.assert_called_once_with("lib", "", force=False) + client.delete_ruleset_library_by_id_if_exists.assert_called_once_with(1, force=False) @patch(f"{MODULE}.get_client") def test_validate_library_reports_status(mock_get_client: MagicMock, runner: CliRunner) -> None: client = MagicMock() mock_get_client.return_value = client - client.get_ruleset_library_by_name.return_value = _make_ruleset_library("my-lib") + _given_libraries(client, _make_ruleset_library("my-lib")) client.validate_ruleset_library.return_value = _make_ruleset_library("my-lib", is_valid=ValidationStatus.valid) result = runner.invoke(app, ["libraries", "validate", "my-lib"]) @@ -103,7 +219,7 @@ def test_validate_library_reports_status(mock_get_client: MagicMock, runner: Cli def test_validate_library_aborts_when_missing(mock_get_client: MagicMock, runner: CliRunner) -> None: client = MagicMock() mock_get_client.return_value = client - client.get_ruleset_library_by_name.return_value = None + _given_libraries(client) result = runner.invoke(app, ["libraries", "validate", "missing"]) @@ -115,7 +231,7 @@ def test_validate_library_aborts_when_missing(mock_get_client: MagicMock, runner def test_validate_library_invalid_prints_errors_and_exits_4(mock_get_client: MagicMock, runner: CliRunner) -> None: client = MagicMock() mock_get_client.return_value = client - client.get_ruleset_library_by_name.return_value = _make_ruleset_library("my-lib") + _given_libraries(client, _make_ruleset_library("my-lib")) client.validate_ruleset_library.return_value = _make_ruleset_library( "my-lib", is_valid=ValidationStatus.invalid, @@ -140,7 +256,7 @@ def test_validate_library_puts_every_reason_in_the_agent_envelope( monkeypatch.setenv("DM_OUTPUT", "json") client = MagicMock() mock_get_client.return_value = client - client.get_ruleset_library_by_name.return_value = _make_ruleset_library("my-lib") + _given_libraries(client, _make_ruleset_library("my-lib")) client.validate_ruleset_library.return_value = _make_ruleset_library( "my-lib", is_valid=ValidationStatus.invalid, @@ -164,7 +280,7 @@ def test_validate_library_puts_every_reason_in_the_agent_envelope( def test_validate_library_nonterminal_status_passes_through(mock_get_client: MagicMock, runner: CliRunner) -> None: client = MagicMock() mock_get_client.return_value = client - client.get_ruleset_library_by_name.return_value = _make_ruleset_library("my-lib") + _given_libraries(client, _make_ruleset_library("my-lib")) client.validate_ruleset_library.return_value = _make_ruleset_library( "my-lib", is_valid=ValidationStatus.in_progress ) @@ -195,9 +311,7 @@ def test_status_reports_state( ) -> None: client = MagicMock() mock_get_client.return_value = client - client.get_ruleset_library_by_name.return_value = _make_ruleset_library( - "lib", is_valid=is_valid, validation_errors=errors - ) + _given_libraries(client, _make_ruleset_library("lib", is_valid=is_valid, validation_errors=errors)) result = runner.invoke(app, ["libraries", "status", "lib", "--json"]) diff --git a/tests/commands/test_rulesets.py b/tests/commands/test_rulesets.py index 8970ec3..b4feab8 100644 --- a/tests/commands/test_rulesets.py +++ b/tests/commands/test_rulesets.py @@ -7,18 +7,20 @@ import pytest from datamasque.client.exceptions import DataMasqueApiError +from datamasque.client.models.bundle import BundleImportResult from datamasque.client.models.ruleset import RulesetType from datamasque.client.models.status import ValidationErrorDetails, ValidationStatus from typer.testing import CliRunner from datamasque_cli.errors import ExitCode from datamasque_cli.main import app +from tests.conftest import DEFAULT_PROJECT_REFERENCE, make_project, with_projects MODULE = "datamasque_cli.commands.rulesets" def _ruleset(id_: int, name: str, rs_type: RulesetType) -> SimpleNamespace: - return SimpleNamespace(id=id_, name=name, ruleset_type=rs_type, yaml="") + return SimpleNamespace(id=id_, name=name, ruleset_type=rs_type, yaml="", project=DEFAULT_PROJECT_REFERENCE) def _make_ruleset_with_status( @@ -28,6 +30,7 @@ def _make_ruleset_with_status( ) -> SimpleNamespace: """A ruleset as the server returns it, carrying its validation status.""" return SimpleNamespace( + project=DEFAULT_PROJECT_REFERENCE, id=id_, name="demo", ruleset_type=RulesetType.database, @@ -52,7 +55,7 @@ def test_unknown_type_is_rejected_before_any_request(mock_get_client: MagicMock, def test_create_requires_type_when_ruleset_is_new( mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path ) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.list_rulesets.return_value = [] @@ -67,7 +70,7 @@ def test_create_requires_type_when_ruleset_is_new( @patch(f"{MODULE}.get_client") def test_create_uses_existing_type_on_update(mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.list_rulesets.return_value = [_ruleset(1, "demo", RulesetType.file)] @@ -82,10 +85,10 @@ def test_create_uses_existing_type_on_update(mock_get_client: MagicMock, runner: @patch(f"{MODULE}.get_client") -def test_create_requires_type_when_both_namespaces_hold_same_name( +def test_create_requires_type_when_database_and_file_rulesets_share_a_name( mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path ) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.list_rulesets.return_value = [ _ruleset(1, "demo", RulesetType.database), @@ -105,7 +108,7 @@ def test_create_requires_type_when_both_namespaces_hold_same_name( def test_create_honours_explicit_type_for_new_ruleset( mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path ) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.list_rulesets.return_value = [] @@ -126,7 +129,7 @@ def test_create_honours_explicit_type_for_new_ruleset( def test_create_explicit_type_overrides_existing_type( mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path ) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.list_rulesets.return_value = [_ruleset(1, "demo", RulesetType.database)] @@ -143,12 +146,35 @@ def test_create_explicit_type_overrides_existing_type( assert args[0].ruleset_type == RulesetType.file +@patch(f"{MODULE}.get_client") +def test_create_of_a_new_type_ignores_the_other_types_project( + mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path +) -> None: + client = with_projects(MagicMock(), make_project(1, "Default"), make_project(2, "Finance")) + mock_get_client.return_value = client + file_ruleset = _ruleset(1, "demo", RulesetType.file) + file_ruleset.project = "2-finance" + client.list_rulesets.return_value = [file_ruleset] + + yaml_file = tmp_path / "rs.yaml" + yaml_file.write_text("tasks: []\n") + + result = runner.invoke( + app, + ["rulesets", "create", "--name", "demo", "--file", str(yaml_file), "--type", "database"], + ) + + assert result.exit_code == ExitCode.AMBIGUOUS + assert result.stderr == "Error: The instance has 2 active projects.\nHint: Pass --project to choose one.\n" + client.create_or_update_ruleset.assert_not_called() + + # -- get / delete disambiguation ------------------------------------------ @patch(f"{MODULE}.get_client") def test_get_aborts_when_multiple_same_name_without_type(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.list_rulesets.return_value = [ _ruleset(1, "demo", RulesetType.database), @@ -161,7 +187,7 @@ def test_get_aborts_when_multiple_same_name_without_type(mock_get_client: MagicM @patch(f"{MODULE}.get_client") def test_get_disambiguates_with_type_flag(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.list_rulesets.return_value = [ _ruleset(1, "demo", RulesetType.database), @@ -184,7 +210,7 @@ def test_get_disambiguates_with_type_flag(mock_get_client: MagicMock, runner: Cl @patch(f"{MODULE}.get_client") def test_delete_only_removes_matched_type(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.list_rulesets.return_value = [ _ruleset(1, "demo", RulesetType.database), @@ -200,7 +226,7 @@ def test_delete_only_removes_matched_type(mock_get_client: MagicMock, runner: Cl @patch(f"{MODULE}.get_client") def test_delete_aborts_when_ambiguous(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.list_rulesets.return_value = [ _ruleset(1, "demo", RulesetType.database), @@ -215,7 +241,7 @@ def test_delete_aborts_when_ambiguous(mock_get_client: MagicMock, runner: CliRun @patch(f"{MODULE}.get_client") def test_delete_aborts_when_missing(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.list_rulesets.return_value = [] @@ -230,7 +256,7 @@ def test_delete_aborts_when_missing(mock_get_client: MagicMock, runner: CliRunne @patch(f"{MODULE}.get_client") def test_list_filters_by_type(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.list_rulesets.return_value = [ _ruleset(1, "a", RulesetType.database), @@ -249,7 +275,7 @@ def test_list_filters_by_type(mock_get_client: MagicMock, runner: CliRunner) -> @patch(f"{MODULE}.get_client") def test_validate_requires_type_flag(mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client yaml_file = tmp_path / "rs.yaml" @@ -265,7 +291,7 @@ def test_validate_requires_type_flag(mock_get_client: MagicMock, runner: CliRunn def test_validate_uses_unique_temp_name_and_cleans_by_id( mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path ) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.create_or_update_ruleset.return_value = _make_ruleset_with_status(ValidationStatus.valid) @@ -289,7 +315,7 @@ def test_validate_cleans_up_when_print_success_interrupted( tmp_path: Path, ) -> None: """`try/finally` guarantees the temp ruleset is deleted even if a later step raises.""" - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.create_or_update_ruleset.return_value = _make_ruleset_with_status(ValidationStatus.valid) @@ -303,7 +329,7 @@ def test_validate_cleans_up_when_print_success_interrupted( @patch(f"{MODULE}.get_client") def test_validate_warns_when_cleanup_fails(mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.create_or_update_ruleset.return_value = _make_ruleset_with_status(ValidationStatus.valid) client.delete_ruleset_by_id_if_exists.side_effect = DataMasqueApiError("boom", response=MagicMock()) @@ -321,7 +347,7 @@ def test_validate_warns_when_cleanup_fails(mock_get_client: MagicMock, runner: C def test_validate_sync_invalid_prints_errors_and_cleans_up( mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path ) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.create_or_update_ruleset.return_value = _make_ruleset_with_status( ValidationStatus.invalid, @@ -348,7 +374,7 @@ def test_validate_puts_every_reason_in_the_agent_envelope( mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: monkeypatch.setenv("DM_OUTPUT", "json") - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.create_or_update_ruleset.return_value = _make_ruleset_with_status( ValidationStatus.invalid, @@ -371,7 +397,7 @@ def test_validate_puts_every_reason_in_the_agent_envelope( def test_validate_nonterminal_status_reports_valid( mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path, initial_status: ValidationStatus | None ) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.create_or_update_ruleset.return_value = _make_ruleset_with_status(initial_status) @@ -387,25 +413,40 @@ def test_validate_nonterminal_status_reports_valid( # -- export-bundle / import-bundle ---------------------------------------- +def _make_bundle_import_result(*, fallback_project: str | None = None) -> BundleImportResult: + """Return an import result for a bundle with no items, whose items under no project went into `fallback_project`.""" + return BundleImportResult.model_validate( + { + "rulesets": {"metadata": {"processed": 0, "created": 0, "restored": 0, "error": 0}, "data": []}, + "fallback_project": fallback_project, + } + ) + + +@pytest.mark.parametrize(("seed_flags", "is_including_seed_files"), [([], False), (["--include-seed-files"], True)]) @patch(f"{MODULE}.get_client") -def test_export_bundle_writes_binary_zip(mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path) -> None: - client = MagicMock() +def test_export_bundle_writes_the_zip_with_seed_files_only_on_request( + mock_get_client: MagicMock, + runner: CliRunner, + tmp_path: Path, + seed_flags: list[str], + is_including_seed_files: bool, +) -> None: + client = with_projects(MagicMock()) mock_get_client.return_value = client - mock_response = MagicMock() - mock_response.content = b"PK\x03\x04fake-zip-bytes" - client.make_request.return_value = mock_response + client.export_bundle.return_value = b"PK\x03\x04fake-zip-bytes" output = tmp_path / "bundle.zip" - result = runner.invoke(app, ["rulesets", "export-bundle", "--output", str(output)]) + result = runner.invoke(app, ["rulesets", "export-bundle", "--output", str(output), *seed_flags]) assert result.exit_code == 0 assert output.read_bytes() == b"PK\x03\x04fake-zip-bytes" - client.make_request.assert_called_once_with("GET", "/api/export/v1/") + client.export_bundle.assert_called_once_with(include_seed_files=is_including_seed_files) @patch(f"{MODULE}.get_client") def test_import_bundle_requires_confirmation(mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client bundle = tmp_path / "bundle.zip" @@ -414,55 +455,94 @@ def test_import_bundle_requires_confirmation(mock_get_client: MagicMock, runner: result = runner.invoke(app, ["rulesets", "import-bundle", "--file", str(bundle)], input="n\n") assert result.exit_code == ExitCode.CANCELLED - client.make_request.assert_not_called() + client.import_bundle.assert_not_called() @patch(f"{MODULE}.get_client") -def test_import_bundle_uploads_zip_archive_as_multipart( +def test_import_bundle_passes_the_file_and_overwrite_options( mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path ) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client - mock_response = MagicMock() - mock_response.content = b"" - client.make_request.return_value = mock_response + client.import_bundle.return_value = _make_bundle_import_result() bundle = tmp_path / "my-bundle.zip" bundle.write_bytes(b"PK\x03\x04zip-bytes") + result = runner.invoke(app, ["rulesets", "import-bundle", "--file", str(bundle), "--overwrite-rulesets", "--yes"]) + + assert result.exit_code == 0 + client.import_bundle.assert_called_once_with( + bundle, + overwrite_rulesets=True, + overwrite_libraries=False, + overwrite_seed_files=False, + fallback_project=None, + ) + + +@patch(f"{MODULE}.get_client") +def test_import_bundle_sends_the_fallback_project( + mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path +) -> None: + bank = make_project(project_id=7, name="Bank") + client = with_projects(MagicMock(), make_project(), bank) + mock_get_client.return_value = client + client.import_bundle.return_value = _make_bundle_import_result() + + bundle = tmp_path / "bundle.zip" + bundle.write_bytes(b"PK\x03\x04") + result = runner.invoke( - app, - [ - "rulesets", - "import-bundle", - "--file", - str(bundle), - "--overwrite-rulesets", - "--yes", - ], + app, ["rulesets", "import-bundle", "--file", str(bundle), "--fallback-project", "bank", "--yes"] ) assert result.exit_code == 0 - (call,) = client.make_request.call_args_list - assert call.args == ("POST", "/api/import/v1/") - assert call.kwargs["data"] == { - "overwrite_rulesets": "true", - "overwrite_libraries": "false", - "overwrite_seed_files": "false", - } - (upload,) = call.kwargs["files"] - assert upload.field_name == "zip_archive" - assert upload.filename == "my-bundle.zip" - assert upload.content_type == "application/zip" + assert client.import_bundle.call_args.kwargs["fallback_project"] == bank + + +@patch(f"{MODULE}.get_client") +def test_import_bundle_rejects_an_unknown_fallback_project( + mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path +) -> None: + client = with_projects(MagicMock()) + mock_get_client.return_value = client + + bundle = tmp_path / "bundle.zip" + bundle.write_bytes(b"PK\x03\x04") + + result = runner.invoke( + app, ["rulesets", "import-bundle", "--file", str(bundle), "--fallback-project", "nope", "--yes"] + ) + + assert result.exit_code == ExitCode.NOT_FOUND + client.import_bundle.assert_not_called() + + +@patch(f"{MODULE}.get_client") +def test_import_bundle_names_the_project_that_took_items_under_no_project( + mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path +) -> None: + client = with_projects(MagicMock()) + mock_get_client.return_value = client + client.import_bundle.return_value = _make_bundle_import_result(fallback_project="Bank") + + bundle = tmp_path / "bundle.zip" + bundle.write_bytes(b"PK\x03\x04") + + result = runner.invoke(app, ["rulesets", "import-bundle", "--file", str(bundle), "--yes"]) + + assert result.exit_code == 0 + assert " ".join(result.stderr.split()) == ( + "Bundle imported successfully. Items the bundle files under no project went into project 'Bank'." + ) @patch(f"{MODULE}.get_client") def test_system_export_alias_warns_and_delegates(mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client - mock_response = MagicMock() - mock_response.content = b"zip-body" - client.make_request.return_value = mock_response + client.export_bundle.return_value = b"zip-body" output = tmp_path / "export.zip" result = runner.invoke(app, ["system", "export", "--output", str(output)]) @@ -509,7 +589,7 @@ def test_status_reports_state( is_valid: ValidationStatus, errors: list[ValidationErrorDetails], ) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.list_rulesets.return_value = [_make_ruleset_with_status(is_valid, errors)] diff --git a/tests/commands/test_runs.py b/tests/commands/test_runs.py index 6fa8a0c..aea6883 100644 --- a/tests/commands/test_runs.py +++ b/tests/commands/test_runs.py @@ -19,12 +19,11 @@ _format_run_info, _parse_options, _print_pretty_logs, - _resolve_connection, - _resolve_connection_id, _resolve_ruleset_id, ) from datamasque_cli.errors import ExitCode from datamasque_cli.main import app +from tests.conftest import DEFAULT_PROJECT_REFERENCE, with_projects MODULE = "datamasque_cli.commands.runs" @@ -38,6 +37,7 @@ def _run_info(**overrides: Any) -> RunInfo: "source_connection": "src-uuid", "source_connection_name": "my_src", "ruleset_name": "demo", + "project": DEFAULT_PROJECT_REFERENCE, } data.update(overrides) return RunInfo.model_validate(data) @@ -47,35 +47,22 @@ def _run_info(**overrides: Any) -> RunInfo: def test_format_run_info_uses_nested_connection_name() -> None: - result = _format_run_info(_run_info()) + result = _format_run_info(_run_info(), {DEFAULT_PROJECT_REFERENCE: "Default"}) assert result["status"] == "finished" assert result["source"] == "my_src" def test_format_run_dict_prefers_status_over_run_status() -> None: - result = _format_run_dict({"id": 1, "status": "finished", "run_status": "queued"}) + result = _format_run_dict({"id": 1, "status": "finished", "run_status": "queued"}, {}) assert result["status"] == "finished" def test_format_run_dict_falls_back_to_run_status() -> None: - result = _format_run_dict({"id": 1, "run_status": "running"}) + result = _format_run_dict({"id": 1, "run_status": "running"}, {}) assert result["status"] == "running" -# -- _resolve_connection_id / _resolve_ruleset_id -------------------------- - - -def test_resolve_connection_id_by_name(mock_client: MagicMock) -> None: - assert _resolve_connection_id(mock_client, "my_conn") == "1" - - -def test_resolve_connection_id_by_id(mock_client: MagicMock) -> None: - assert _resolve_connection_id(mock_client, "2") == "2" - - -def test_resolve_connection_id_not_found(mock_client: MagicMock) -> None: - with pytest.raises(SystemExit): - _resolve_connection_id(mock_client, "nonexistent") +# -- _resolve_ruleset_id -------------------------------------------------- def test_resolve_ruleset_id_by_name(mock_client: MagicMock) -> None: @@ -88,40 +75,34 @@ def test_resolve_ruleset_id_not_found(mock_client: MagicMock) -> None: def test_resolve_ruleset_id_prefers_matching_mask_type() -> None: - client = MagicMock() + client = with_projects(MagicMock()) client.list_rulesets.return_value = [ - SimpleNamespace(id=1, name="demo", ruleset_type=RulesetType.database), - SimpleNamespace(id=2, name="demo", ruleset_type=RulesetType.file), + SimpleNamespace(id=1, name="demo", ruleset_type=RulesetType.database, project=DEFAULT_PROJECT_REFERENCE), + SimpleNamespace(id=2, name="demo", ruleset_type=RulesetType.file, project=DEFAULT_PROJECT_REFERENCE), ] assert _resolve_ruleset_id(client, "demo", mask_type="file") == "2" assert _resolve_ruleset_id(client, "demo", mask_type="database") == "1" def test_resolve_ruleset_id_aborts_when_type_missing() -> None: - client = MagicMock() + client = with_projects(MagicMock()) client.list_rulesets.return_value = [ - SimpleNamespace(id=1, name="demo", ruleset_type=RulesetType.database), + SimpleNamespace(id=1, name="demo", ruleset_type=RulesetType.database, project=DEFAULT_PROJECT_REFERENCE), ] with pytest.raises(SystemExit): _resolve_ruleset_id(client, "demo", mask_type="file") def test_resolve_ruleset_id_ambiguous_without_type() -> None: - client = MagicMock() + client = with_projects(MagicMock()) client.list_rulesets.return_value = [ - SimpleNamespace(id=1, name="demo", ruleset_type=RulesetType.database), - SimpleNamespace(id=2, name="demo", ruleset_type=RulesetType.file), + SimpleNamespace(id=1, name="demo", ruleset_type=RulesetType.database, project=DEFAULT_PROJECT_REFERENCE), + SimpleNamespace(id=2, name="demo", ruleset_type=RulesetType.file, project=DEFAULT_PROJECT_REFERENCE), ] with pytest.raises(SystemExit): _resolve_ruleset_id(client, "demo") -def test_resolve_connection_returns_name_and_type(mock_client: MagicMock) -> None: - conn = _resolve_connection(mock_client, "my_conn") - assert conn.name == "my_conn" - assert conn.mask_type == "database" - - # -- start_run (behaviour, not wiring) ------------------------------------ @@ -162,15 +143,15 @@ def test_start_run_uses_connection_name_for_run_label( @patch(f"{MODULE}.get_client") def test_start_run_passes_connection_type_to_ruleset_resolver(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.list_connections.return_value = [ - SimpleNamespace(id=1, name="files_in", mask_type="file"), - SimpleNamespace(id=2, name="files_out", mask_type="file"), + SimpleNamespace(id=1, name="files_in", mask_type="file", project=DEFAULT_PROJECT_REFERENCE), + SimpleNamespace(id=2, name="files_out", mask_type="file", project=DEFAULT_PROJECT_REFERENCE), ] client.list_rulesets.return_value = [ - SimpleNamespace(id=10, name="demo", ruleset_type=RulesetType.database), - SimpleNamespace(id=20, name="demo", ruleset_type=RulesetType.file), + SimpleNamespace(id=10, name="demo", ruleset_type=RulesetType.database, project=DEFAULT_PROJECT_REFERENCE), + SimpleNamespace(id=20, name="demo", ruleset_type=RulesetType.file, project=DEFAULT_PROJECT_REFERENCE), ] client.start_masking_run.return_value = RunId(42) client.get_run_info.return_value = _run_info(id=42, status="finished", mask_type="file") @@ -184,14 +165,14 @@ def test_start_run_passes_connection_type_to_ruleset_resolver(mock_get_client: M @patch(f"{MODULE}.get_client") def test_start_run_aborts_on_destination_type_mismatch(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.list_connections.return_value = [ - SimpleNamespace(id=1, name="db_src", mask_type="database"), - SimpleNamespace(id=2, name="files_dst", mask_type="file"), + SimpleNamespace(id=1, name="db_src", mask_type="database", project=DEFAULT_PROJECT_REFERENCE), + SimpleNamespace(id=2, name="files_dst", mask_type="file", project=DEFAULT_PROJECT_REFERENCE), ] client.list_rulesets.return_value = [ - SimpleNamespace(id=10, name="demo", ruleset_type=RulesetType.database), + SimpleNamespace(id=10, name="demo", ruleset_type=RulesetType.database, project=DEFAULT_PROJECT_REFERENCE), ] result = runner.invoke(app, ["run", "start", "-c", "db_src", "-r", "demo", "-d", "files_dst"]) @@ -276,13 +257,13 @@ def test_start_run_passes_parsed_options_into_payload( @patch(f"{MODULE}.get_client") def test_start_run_aborts_when_file_source_has_no_destination(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.list_connections.return_value = [ - SimpleNamespace(id=1, name="files_src", mask_type="file"), + SimpleNamespace(id=1, name="files_src", mask_type="file", project=DEFAULT_PROJECT_REFERENCE), ] client.list_rulesets.return_value = [ - SimpleNamespace(id=10, name="demo", ruleset_type=RulesetType.file), + SimpleNamespace(id=10, name="demo", ruleset_type=RulesetType.file, project=DEFAULT_PROJECT_REFERENCE), ] result = runner.invoke(app, ["run", "start", "-c", "files_src", "-r", "demo"]) @@ -299,10 +280,11 @@ def test_start_run_aborts_when_file_source_has_no_destination(mock_get_client: M def test_retry_run_preserves_source_ruleset_destination_and_options( mock_get_client: MagicMock, runner: CliRunner ) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.get_run_info.return_value = RunInfo.model_validate( { + "project": DEFAULT_PROJECT_REFERENCE, "id": 100, "source_connection": "src-uuid", "source_connection_name": "my_src", @@ -331,11 +313,12 @@ def test_retry_run_preserves_source_ruleset_destination_and_options( @patch(f"{MODULE}.get_client") def test_retry_run_strips_server_managed_option_keys(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client # `get_run_info` echoes server-managed option keys the POST endpoint rejects. client.get_run_info.return_value = RunInfo.model_validate( { + "project": DEFAULT_PROJECT_REFERENCE, "id": 300, "source_connection": "src-uuid", "source_connection_name": "my_src", @@ -363,10 +346,11 @@ def test_retry_run_strips_server_managed_option_keys(mock_get_client: MagicMock, @patch(f"{MODULE}.get_client") def test_retry_run_aborts_when_original_missing_ruleset(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.get_run_info.return_value = RunInfo.model_validate( { + "project": DEFAULT_PROJECT_REFERENCE, "id": 200, "source_connection": "src-uuid", "source_connection_name": "my_src", @@ -389,7 +373,7 @@ def test_retry_run_aborts_when_original_missing_ruleset(mock_get_client: MagicMo @patch(f"{MODULE}.time") @patch(f"{MODULE}.get_client") def test_logs_follow_polls_until_terminal(mock_get_client: MagicMock, _mock_time: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.get_run_log.side_effect = ["line 1\n", "line 1\nline 2\n", "line 1\nline 2\nline 3\n"] client.get_run_info.side_effect = [ @@ -413,7 +397,7 @@ def test_logs_follow_polls_until_terminal(mock_get_client: MagicMock, _mock_time def test_logs_follow_recovers_when_server_rotates_log( mock_get_client: MagicMock, _mock_time: MagicMock, runner: CliRunner ) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client # Second poll returns a shorter log (server rotated / compacted). # Third poll adds a new line to the rotated buffer; it must still print. @@ -440,7 +424,7 @@ def test_logs_follow_recovers_when_server_rotates_log( @patch(f"{MODULE}.time") @patch(f"{MODULE}.get_client") def test_wait_run_polls_until_terminal(mock_get_client: MagicMock, _mock_time: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.get_run_info.side_effect = [ _run_info(id=1, status="queued"), @@ -456,7 +440,7 @@ def test_wait_run_polls_until_terminal(mock_get_client: MagicMock, _mock_time: M @patch(f"{MODULE}.time") @patch(f"{MODULE}.get_client") def test_wait_run_failure_exits_1(mock_get_client: MagicMock, _mock_time: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.get_run_info.return_value = _run_info(id=1, status="failed") diff --git a/tests/commands/test_seeds.py b/tests/commands/test_seeds.py index 6f1e0c3..4d8fd38 100644 --- a/tests/commands/test_seeds.py +++ b/tests/commands/test_seeds.py @@ -8,15 +8,16 @@ from datamasque_cli.errors import ExitCode from datamasque_cli.main import app +from tests.conftest import DEFAULT_PROJECT_REFERENCE, with_projects MODULE = "datamasque_cli.commands.seeds" @patch(f"{MODULE}.get_client") def test_delete_seed_aborts_when_missing(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client - client.get_file_of_type_by_name.return_value = None + client.list_files_of_type.return_value = [] result = runner.invoke(app, ["seeds", "delete", "nope.csv", "--yes"]) @@ -26,10 +27,10 @@ def test_delete_seed_aborts_when_missing(mock_get_client: MagicMock, runner: Cli @patch(f"{MODULE}.get_client") def test_delete_seed_proceeds_when_present(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client - match = SeedFile(id="abc", name="foo.csv", created_date=datetime.now(tz=UTC)) - client.get_file_of_type_by_name.return_value = match + match = SeedFile(id="abc", name="foo.csv", created_date=datetime.now(tz=UTC), project=DEFAULT_PROJECT_REFERENCE) + client.list_files_of_type.return_value = [match] result = runner.invoke(app, ["seeds", "delete", "foo.csv", "--yes"]) diff --git a/tests/commands/test_table_references.py b/tests/commands/test_table_references.py index 1930668..c41a4a6 100644 --- a/tests/commands/test_table_references.py +++ b/tests/commands/test_table_references.py @@ -13,16 +13,22 @@ from datamasque_cli.errors import ExitCode from datamasque_cli.main import app +from tests.conftest import DEFAULT_PROJECT_REFERENCE, make_project, with_projects MODULE = "datamasque_cli.commands.table_references" def _mock_client() -> MagicMock: - return MagicMock(spec=DataMasqueClient) + return with_projects(MagicMock(spec=DataMasqueClient)) def _reference(**overrides: object) -> TableReference: - defaults: dict[str, object] = {"name": "customer_identities", "connection": "conn-1", "source": "in/customers.csv"} + defaults: dict[str, object] = { + "name": "customer_identities", + "connection": "conn-1", + "source": "in/customers.csv", + "project": DEFAULT_PROJECT_REFERENCE, + } defaults.update(overrides) return TableReference(**defaults) @@ -48,7 +54,13 @@ def test_list_references(mock_get_client: MagicMock, runner: CliRunner) -> None: assert result.exit_code == 0 payload = json.loads(result.stdout) assert payload == [ - {"id": "ref-1", "name": "customer_identities", "connection": "conn-1", "source": "in/customers.csv"} + { + "id": "ref-1", + "project": "Default", + "name": "customer_identities", + "connection": "conn-1", + "source": "in/customers.csv", + } ] @@ -97,9 +109,9 @@ def test_list_references_non_404_error_surfaces_cleanly(mock_get_client: MagicMo def test_get_reference(mock_get_client: MagicMock, runner: CliRunner) -> None: client = _mock_client() mock_get_client.return_value = client - client.get_table_reference_by_name.return_value = _reference( - id="ref-1", options=TableReferenceOptions(format=TableReferenceFormat.parquet) - ) + client.list_table_references.return_value = [ + _reference(id="ref-1", options=TableReferenceOptions(format=TableReferenceFormat.parquet)) + ] result = runner.invoke(app, ["table-references", "get", "customer_identities", "--json"]) @@ -115,7 +127,7 @@ def test_get_reference_with_no_options_shows_null_not_fabricated_defaults( ) -> None: client = _mock_client() mock_get_client.return_value = client - client.get_table_reference_by_name.return_value = _reference(id="ref-1") + client.list_table_references.return_value = [_reference(id="ref-1")] result = runner.invoke(app, ["table-references", "get", "customer_identities", "--json"]) @@ -129,7 +141,7 @@ def test_get_reference_with_no_options_shows_null_not_fabricated_defaults( def test_get_reference_not_found(mock_get_client: MagicMock, runner: CliRunner) -> None: client = _mock_client() mock_get_client.return_value = client - client.get_table_reference_by_name.return_value = None + client.list_table_references.return_value = [] result = runner.invoke(app, ["table-references", "get", "missing"]) @@ -141,7 +153,7 @@ def test_get_reference_not_found(mock_get_client: MagicMock, runner: CliRunner) def test_get_reference_not_supported_by_server(mock_get_client: MagicMock, runner: CliRunner) -> None: client = _mock_client() mock_get_client.return_value = client - client.get_table_reference_by_name.side_effect = _api_error(HTTPStatus.NOT_FOUND) + client.list_table_references.side_effect = _api_error(HTTPStatus.NOT_FOUND) result = runner.invoke(app, ["table-references", "get", "customer_identities"]) @@ -156,7 +168,9 @@ def test_get_reference_not_supported_by_server(mock_get_client: MagicMock, runne def test_create_reference_by_connection_name(mock_get_client: MagicMock, runner: CliRunner) -> None: client = _mock_client() mock_get_client.return_value = client - client.list_connections.return_value = [SimpleNamespace(id="conn-1", name="input")] + client.list_connections.return_value = [ + SimpleNamespace(id="conn-1", name="input", project=DEFAULT_PROJECT_REFERENCE) + ] result = runner.invoke( app, @@ -183,7 +197,9 @@ def test_create_reference_by_connection_name(mock_get_client: MagicMock, runner: def test_create_reference_by_connection_id(mock_get_client: MagicMock, runner: CliRunner) -> None: client = _mock_client() mock_get_client.return_value = client - client.list_connections.return_value = [SimpleNamespace(id="conn-1", name="input")] + client.list_connections.return_value = [ + SimpleNamespace(id="conn-1", name="input", project=DEFAULT_PROJECT_REFERENCE) + ] result = runner.invoke( app, @@ -208,7 +224,9 @@ def test_create_reference_by_connection_id(mock_get_client: MagicMock, runner: C def test_create_reference_unknown_connection_aborts(mock_get_client: MagicMock, runner: CliRunner) -> None: client = _mock_client() mock_get_client.return_value = client - client.list_connections.return_value = [SimpleNamespace(id="conn-1", name="input")] + client.list_connections.return_value = [ + SimpleNamespace(id="conn-1", name="input", project=DEFAULT_PROJECT_REFERENCE) + ] result = runner.invoke( app, @@ -232,7 +250,9 @@ def test_create_reference_unknown_connection_aborts(mock_get_client: MagicMock, def test_create_reference_with_csv_options(mock_get_client: MagicMock, runner: CliRunner) -> None: client = _mock_client() mock_get_client.return_value = client - client.list_connections.return_value = [SimpleNamespace(id="conn-1", name="input")] + client.list_connections.return_value = [ + SimpleNamespace(id="conn-1", name="input", project=DEFAULT_PROJECT_REFERENCE) + ] result = runner.invoke( app, @@ -272,7 +292,9 @@ def test_create_reference_parquet_with_csv_options_passes_through( """CSV options are unfiltered pass-through — the server, not the CLI, decides whether they apply.""" client = _mock_client() mock_get_client.return_value = client - client.list_connections.return_value = [SimpleNamespace(id="conn-1", name="input")] + client.list_connections.return_value = [ + SimpleNamespace(id="conn-1", name="input", project=DEFAULT_PROJECT_REFERENCE) + ] result = runner.invoke( app, @@ -315,7 +337,9 @@ def test_create_reference_server_validation_error_surfaces_cleanly( ) -> None: client = _mock_client() mock_get_client.return_value = client - client.list_connections.return_value = [SimpleNamespace(id="conn-1", name="input")] + client.list_connections.return_value = [ + SimpleNamespace(id="conn-1", name="input", project=DEFAULT_PROJECT_REFERENCE) + ] client.create_or_update_table_reference.side_effect = _api_error( HTTPStatus.BAD_REQUEST, "table reference with this name already exists" ) @@ -343,8 +367,10 @@ def test_create_reference_server_validation_error_surfaces_cleanly( def test_create_reference_not_supported_by_server(mock_get_client: MagicMock, runner: CliRunner) -> None: client = _mock_client() mock_get_client.return_value = client - client.list_connections.return_value = [SimpleNamespace(id="conn-1", name="input")] - client.get_table_reference_by_name.side_effect = _api_error(HTTPStatus.NOT_FOUND) + client.list_connections.return_value = [ + SimpleNamespace(id="conn-1", name="input", project=DEFAULT_PROJECT_REFERENCE) + ] + client.list_table_references.side_effect = _api_error(HTTPStatus.NOT_FOUND) result = runner.invoke( app, @@ -372,8 +398,10 @@ def test_create_reference_missing_on_write_is_not_reported_as_unsupported( """A 404 from the create/update call itself is a real failure, not evidence the endpoint is missing.""" client = _mock_client() mock_get_client.return_value = client - client.list_connections.return_value = [SimpleNamespace(id="conn-1", name="input")] - client.get_table_reference_by_name.return_value = None + client.list_connections.return_value = [ + SimpleNamespace(id="conn-1", name="input", project=DEFAULT_PROJECT_REFERENCE) + ] + client.list_table_references.return_value = [] client.create_or_update_table_reference.side_effect = _api_error(HTTPStatus.NOT_FOUND, "Not found.") result = runner.invoke( @@ -493,9 +521,9 @@ def test_create_reference_file_with_other_flags_aborts( def test_update_reference_merges_only_passed_fields(mock_get_client: MagicMock, runner: CliRunner) -> None: client = _mock_client() mock_get_client.return_value = client - client.get_table_reference_by_name.return_value = _reference( - id="ref-1", options=TableReferenceOptions(delimiter=",", encoding="utf-8") - ) + client.list_table_references.return_value = [ + _reference(id="ref-1", options=TableReferenceOptions(delimiter=",", encoding="utf-8")) + ] result = runner.invoke( app, ["table-references", "update", "customer_identities", "--source", "in/new.csv", "--delimiter", ";"] @@ -516,7 +544,7 @@ def test_update_reference_format_when_options_previously_none(mock_get_client: M """A reference whose options were never set has no existing values to preserve on a full PUT.""" client = _mock_client() mock_get_client.return_value = client - client.get_table_reference_by_name.return_value = _reference(id="ref-1") + client.list_table_references.return_value = [_reference(id="ref-1")] result = runner.invoke(app, ["table-references", "update", "customer_identities", "--format", "parquet"]) @@ -530,8 +558,10 @@ def test_update_reference_format_when_options_previously_none(mock_get_client: M def test_update_reference_connection_by_name(mock_get_client: MagicMock, runner: CliRunner) -> None: client = _mock_client() mock_get_client.return_value = client - client.get_table_reference_by_name.return_value = _reference(id="ref-1") - client.list_connections.return_value = [SimpleNamespace(id="conn-2", name="other")] + client.list_table_references.return_value = [_reference(id="ref-1")] + client.list_connections.return_value = [ + SimpleNamespace(id="conn-2", name="other", project=DEFAULT_PROJECT_REFERENCE) + ] result = runner.invoke(app, ["table-references", "update", "customer_identities", "--connection", "other"]) @@ -541,12 +571,82 @@ def test_update_reference_connection_by_name(mock_get_client: MagicMock, runner: assert updated.connection == "conn-2" +def _shared_connection_names(client: MagicMock) -> None: + """Give `Default` and `Finance` a connection each named `input`, and only `Finance` one named `archive`.""" + with_projects(client, make_project(1, "Default"), make_project(2, "Finance")) + client.list_connections.return_value = [ + SimpleNamespace(id="conn-default", name="input", project=DEFAULT_PROJECT_REFERENCE), + SimpleNamespace(id="conn-finance", name="input", project="2-finance"), + SimpleNamespace(id="conn-archive", name="archive", project="2-finance"), + ] + + +@patch(f"{MODULE}.get_client") +def test_update_reference_connection_prefers_the_references_own_project( + mock_get_client: MagicMock, runner: CliRunner +) -> None: + client = _mock_client() + mock_get_client.return_value = client + _shared_connection_names(client) + client.list_table_references.return_value = [_reference(id="ref-1", project="2-finance")] + + for connection, expected in (("input", "conn-finance"), ("archive", "conn-archive")): + result = runner.invoke(app, ["table-references", "update", "customer_identities", "--connection", connection]) + + assert result.exit_code == 0, result.output + assert client.update_table_reference.call_args[0][0].connection == expected + + +@patch(f"{MODULE}.get_client") +def test_update_reference_connection_in_another_project_only_is_found( + mock_get_client: MagicMock, runner: CliRunner +) -> None: + client = _mock_client() + mock_get_client.return_value = client + _shared_connection_names(client) + client.list_table_references.return_value = [_reference(id="ref-1")] + + result = runner.invoke(app, ["table-references", "update", "customer_identities", "--connection", "archive"]) + + assert result.exit_code == 0, result.output + assert client.update_table_reference.call_args[0][0].connection == "conn-archive" + + +@patch(f"{MODULE}.get_client") +def test_create_reference_connection_prefers_the_target_project(mock_get_client: MagicMock, runner: CliRunner) -> None: + """An update through `create` with no `--project` targets the existing reference's project, and so its connection.""" + client = _mock_client() + mock_get_client.return_value = client + _shared_connection_names(client) + client.list_table_references.return_value = [_reference(id="ref-1", project="2-finance")] + + result = runner.invoke( + app, + [ + "table-references", + "create", + "--name", + "customer_identities", + "--connection", + "input", + "--source", + "in/customers.csv", + ], + ) + + assert result.exit_code == 0, result.output + created = client.create_or_update_table_reference.call_args[0][0] + assert (created.connection, created.project) == ("conn-finance", "2-finance") + + @patch(f"{MODULE}.get_client") def test_update_reference_unknown_connection_aborts(mock_get_client: MagicMock, runner: CliRunner) -> None: client = _mock_client() mock_get_client.return_value = client - client.get_table_reference_by_name.return_value = _reference(id="ref-1") - client.list_connections.return_value = [SimpleNamespace(id="conn-2", name="other")] + client.list_table_references.return_value = [_reference(id="ref-1")] + client.list_connections.return_value = [ + SimpleNamespace(id="conn-2", name="other", project=DEFAULT_PROJECT_REFERENCE) + ] result = runner.invoke(app, ["table-references", "update", "customer_identities", "--connection", "nope"]) @@ -558,12 +658,12 @@ def test_update_reference_unknown_connection_aborts(mock_get_client: MagicMock, def test_update_reference_aborts_without_any_fields(mock_get_client: MagicMock, runner: CliRunner) -> None: client = _mock_client() mock_get_client.return_value = client - client.get_table_reference_by_name.return_value = _reference(id="ref-1") + client.list_table_references.return_value = [_reference(id="ref-1")] result = runner.invoke(app, ["table-references", "update", "customer_identities"]) assert result.exit_code == ExitCode.INVALID_INPUT - client.get_table_reference_by_name.assert_not_called() + client.list_table_references.assert_not_called() client.update_table_reference.assert_not_called() @@ -571,7 +671,7 @@ def test_update_reference_aborts_without_any_fields(mock_get_client: MagicMock, def test_update_reference_aborts_when_missing(mock_get_client: MagicMock, runner: CliRunner) -> None: client = _mock_client() mock_get_client.return_value = client - client.get_table_reference_by_name.return_value = None + client.list_table_references.return_value = [] result = runner.invoke(app, ["table-references", "update", "missing", "--source", "in/new.csv"]) @@ -583,7 +683,7 @@ def test_update_reference_aborts_when_missing(mock_get_client: MagicMock, runner def test_update_reference_not_supported_by_server(mock_get_client: MagicMock, runner: CliRunner) -> None: client = _mock_client() mock_get_client.return_value = client - client.get_table_reference_by_name.side_effect = _api_error(HTTPStatus.NOT_FOUND) + client.list_table_references.side_effect = _api_error(HTTPStatus.NOT_FOUND) result = runner.invoke(app, ["table-references", "update", "customer_identities", "--source", "in/new.csv"]) @@ -597,7 +697,7 @@ def test_update_reference_missing_on_write_is_not_reported_as_unsupported( ) -> None: client = _mock_client() mock_get_client.return_value = client - client.get_table_reference_by_name.return_value = _reference(id="ref-1") + client.list_table_references.return_value = [_reference(id="ref-1")] client.update_table_reference.side_effect = _api_error(HTTPStatus.NOT_FOUND, "Not found.") result = runner.invoke(app, ["table-references", "update", "customer_identities", "--source", "in/new.csv"]) @@ -613,43 +713,43 @@ def test_update_reference_missing_on_write_is_not_reported_as_unsupported( def test_delete_reference_confirmed(mock_get_client: MagicMock, runner: CliRunner) -> None: client = _mock_client() mock_get_client.return_value = client - client.get_table_reference_by_name.return_value = _reference(id="ref-1") + client.list_table_references.return_value = [_reference(id="ref-1")] result = runner.invoke(app, ["table-references", "delete", "customer_identities", "--yes"]) assert result.exit_code == 0 - client.delete_table_reference_by_name_if_exists.assert_called_once_with("customer_identities") + client.delete_table_reference_by_id_if_exists.assert_called_once_with("ref-1") @patch(f"{MODULE}.get_client") def test_delete_reference_declined(mock_get_client: MagicMock, runner: CliRunner) -> None: client = _mock_client() mock_get_client.return_value = client - client.get_table_reference_by_name.return_value = _reference(id="ref-1") + client.list_table_references.return_value = [_reference(id="ref-1")] result = runner.invoke(app, ["table-references", "delete", "customer_identities"], input="n\n") assert result.exit_code == ExitCode.CANCELLED - client.delete_table_reference_by_name_if_exists.assert_not_called() + client.delete_table_reference_by_id_if_exists.assert_not_called() @patch(f"{MODULE}.get_client") def test_delete_reference_aborts_when_missing(mock_get_client: MagicMock, runner: CliRunner) -> None: client = _mock_client() mock_get_client.return_value = client - client.get_table_reference_by_name.return_value = None + client.list_table_references.return_value = [] result = runner.invoke(app, ["table-references", "delete", "missing", "--yes"]) assert result.exit_code == ExitCode.NOT_FOUND - client.delete_table_reference_by_name_if_exists.assert_not_called() + client.delete_table_reference_by_id_if_exists.assert_not_called() @patch(f"{MODULE}.get_client") def test_delete_reference_not_supported_by_server(mock_get_client: MagicMock, runner: CliRunner) -> None: client = _mock_client() mock_get_client.return_value = client - client.get_table_reference_by_name.side_effect = _api_error(HTTPStatus.NOT_FOUND) + client.list_table_references.side_effect = _api_error(HTTPStatus.NOT_FOUND) result = runner.invoke(app, ["table-references", "delete", "customer_identities", "--yes"]) @@ -661,8 +761,8 @@ def test_delete_reference_not_supported_by_server(mock_get_client: MagicMock, ru def test_delete_reference_non_404_error_surfaces_cleanly(mock_get_client: MagicMock, runner: CliRunner) -> None: client = _mock_client() mock_get_client.return_value = client - client.get_table_reference_by_name.return_value = _reference(id="ref-1") - client.delete_table_reference_by_name_if_exists.side_effect = _api_error(HTTPStatus.CONFLICT, "referenced by a run") + client.list_table_references.return_value = [_reference(id="ref-1")] + client.delete_table_reference_by_id_if_exists.side_effect = _api_error(HTTPStatus.CONFLICT, "referenced by a run") result = runner.invoke(app, ["table-references", "delete", "customer_identities", "--yes"]) diff --git a/tests/conftest.py b/tests/conftest.py index f6ad2f5..b19690f 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,10 +1,12 @@ from __future__ import annotations +from datetime import UTC, datetime from types import SimpleNamespace from typing import Any from unittest.mock import MagicMock import pytest +from datamasque.client.models.project import Project, ProjectId from datamasque.client.models.ruleset import RulesetType from typer.testing import CliRunner @@ -31,18 +33,41 @@ def runner() -> CliRunner: @pytest.fixture() def mock_client() -> MagicMock: - """Pre-configured mock with two connections and one ruleset.""" - client = MagicMock() + """Pre-configured mock with one project, two connections and one ruleset, all in `Default`.""" + client = with_projects(MagicMock()) client.list_connections.return_value = [ - SimpleNamespace(id=1, name="my_conn", mask_type="database"), - SimpleNamespace(id=2, name="other_conn", mask_type="database"), + SimpleNamespace(id=1, name="my_conn", mask_type="database", project=DEFAULT_PROJECT_REFERENCE), + SimpleNamespace(id=2, name="other_conn", mask_type="database", project=DEFAULT_PROJECT_REFERENCE), ] client.list_rulesets.return_value = [ - SimpleNamespace(id=10, name="my_ruleset", ruleset_type=RulesetType.database, yaml=""), + SimpleNamespace( + id=10, name="my_ruleset", ruleset_type=RulesetType.database, yaml="", project=DEFAULT_PROJECT_REFERENCE + ), ] return client +DEFAULT_PROJECT_REFERENCE = "1-default" + + +def make_project(project_id: int = 1, name: str = "Default") -> Project: + """A project as `list_projects` returns it, with the `-` reference the server derives from its name.""" + stamp = datetime(2026, 1, 1, tzinfo=UTC) + return Project( + id=ProjectId(project_id), + reference=f"{project_id}-{name.lower()}", + name=name, + created=stamp, + updated=stamp, + ) + + +def with_projects(client: MagicMock, *projects: Project) -> MagicMock: + """Make `client.list_projects` return `projects`, or just `Default` when none are given.""" + client.list_projects.return_value = list(projects) or [make_project()] + return client + + def make_api_response(data: Any, *, is_ok: bool = True) -> MagicMock: resp = MagicMock() resp.json.return_value = data diff --git a/tests/integration/conftest.py b/tests/integration/conftest.py index 7e6a7f8..4b81a36 100644 --- a/tests/integration/conftest.py +++ b/tests/integration/conftest.py @@ -8,8 +8,10 @@ from pathlib import Path import pytest +from datamasque.client.models.project import ProjectCreateRequest from typer.testing import CliRunner +from datamasque_cli.client import get_client from datamasque_cli.errors import ErrorEnvelope from datamasque_cli.main import app @@ -186,26 +188,42 @@ def db_yaml(tmp_path: Path) -> Path: return path -DISCOVERY_TEST_NAMESPACE = "dm_int_ns" +def create_discovery_config( + runner: CliRunner, name: str, config_type: str, yaml_file: Path, project: str | None = None +) -> None: + """Create a discovery config, in `project` when given, and fail the test when the CLI rejects it.""" + args = ["discover", "configs", "create", "--name", name, "--type", config_type, "-f", str(yaml_file)] + if project: + args += ["--project", project] + result = runner.invoke(app, args) + assert result.exit_code == 0, f"could not create {config_type} config '{name}': {result.stdout}{result.stderr}" -def create_discovery_config(runner: CliRunner, name: str, config_type: str, yaml_file: Path) -> None: - """Create a discovery config, and fail the test when the CLI rejects it.""" - result = runner.invoke( - app, - ["discover", "configs", "create", "--name", name, "--type", config_type, "-f", str(yaml_file)], - ) - assert result.exit_code == 0, f"could not create {config_type} config '{name}': {result.stdout}{result.stderr}" +def create_discovery_config_library(runner: CliRunner, name: str, yaml_file: Path, project: str | None = None) -> None: + """Create a discovery config library, in `project` when given, and fail the test when the CLI rejects it.""" + args = ["discover", "libraries", "create", "--name", name, "-f", str(yaml_file)] + if project: + args += ["--project", project] + result = runner.invoke(app, args) + label = f"{project}/{name}" if project else name + assert result.exit_code == 0, f"could not create library '{label}': {result.stdout}{result.stderr}" -def create_discovery_config_library(runner: CliRunner, name: str, yaml_file: Path, namespace: str = "") -> None: - """Create a discovery config library, and fail the test when the CLI rejects it.""" - result = runner.invoke( - app, - ["discover", "libraries", "create", "--name", name, "--namespace", namespace, "-f", str(yaml_file)], +@pytest.fixture() +def second_project() -> Iterator[str]: + """ + A second project for the duration of one test, deleted afterwards into the lowest-id project. + + While it exists, a create that names no project fails, so the test passes `--project` on every create. + """ + client = get_client() + project = client.create_project(ProjectCreateRequest(name=f"dm_int_{uuid.uuid4().hex[:8]}")) + yield project.name + home = min( + (p for p in client.list_projects() if p.id != project.id), + key=lambda p: p.id, ) - label = f"{namespace}/{name}" if namespace else name - assert result.exit_code == 0, f"could not create library '{label}': {result.stdout}{result.stderr}" + client.delete_project(project, home) @pytest.fixture() @@ -220,11 +238,7 @@ def discovery_config_name(runner: CliRunner) -> Iterator[str]: def discovery_library_name(runner: CliRunner) -> Iterator[str]: name = f"dm_int_{uuid.uuid4().hex[:8]}" yield name - for namespace in ("", DISCOVERY_TEST_NAMESPACE): - args = ["discover", "libraries", "delete", name, "--yes", "--force"] - if namespace: - args += ["--namespace", namespace] - runner.invoke(app, args) + runner.invoke(app, ["discover", "libraries", "delete", name, "--yes", "--force"]) @pytest.fixture() diff --git a/tests/integration/test_discovery_configs.py b/tests/integration/test_discovery_configs.py index 291a4ed..e5cfc98 100644 --- a/tests/integration/test_discovery_configs.py +++ b/tests/integration/test_discovery_configs.py @@ -9,7 +9,6 @@ from datamasque_cli.errors import ExitCode from datamasque_cli.main import app from tests.integration.conftest import ( - DISCOVERY_TEST_NAMESPACE, create_discovery_config, create_discovery_config_library, get_error_envelope_from_stderr, @@ -123,22 +122,25 @@ def test_library_create_get_delete_lifecycle( assert gone.exit_code == ExitCode.NOT_FOUND -def test_library_namespace_is_isolated( +def test_library_project_is_isolated( runner: CliRunner, discovery_library_name: str, + second_project: str, discovery_library_yaml: Path, ) -> None: - create_discovery_config_library( - runner, discovery_library_name, discovery_library_yaml, namespace=DISCOVERY_TEST_NAMESPACE - ) + create_discovery_config_library(runner, discovery_library_name, discovery_library_yaml, project=second_project) - in_namespace = runner.invoke( - app, ["discover", "libraries", "get", discovery_library_name, "--namespace", DISCOVERY_TEST_NAMESPACE] + in_project = runner.invoke( + app, ["discover", "libraries", "get", discovery_library_name, "--project", second_project] ) - assert in_namespace.exit_code == 0 + assert in_project.exit_code == 0 - default_namespace = runner.invoke(app, ["discover", "libraries", "get", discovery_library_name]) - assert default_namespace.exit_code == ExitCode.NOT_FOUND + other_projects = [ + row["project"] + for row in json.loads(runner.invoke(app, ["discover", "libraries", "list", "--json"]).stdout) + if row["name"] == discovery_library_name + ] + assert other_projects == [second_project] def test_library_validate_rejects_invalid_yaml( @@ -158,6 +160,7 @@ def test_library_delete_refuses_while_imported_then_force_succeeds( runner: CliRunner, discovery_library_name: str, discovery_config_name: str, + second_project: str, tmp_path: Path, ) -> None: library = tmp_path / "importable.yaml" @@ -173,9 +176,9 @@ def test_library_delete_refuses_while_imported_then_force_succeeds( " type: regex\n" " pattern: dm_int_column\n" ) - create_discovery_config_library(runner, discovery_library_name, library, namespace=DISCOVERY_TEST_NAMESPACE) + create_discovery_config_library(runner, discovery_library_name, library, project=second_project) - ref = f"{DISCOVERY_TEST_NAMESPACE}/{discovery_library_name}" + ref = f"{second_project}/{discovery_library_name}" config = tmp_path / "importing.yaml" config.write_text( f"imports:\n" @@ -189,15 +192,15 @@ def test_library_delete_refuses_while_imported_then_force_succeeds( f" include:\n" f' - "*.csv"\n' ) - create_discovery_config(runner, discovery_config_name, "file", config) + create_discovery_config(runner, discovery_config_name, "file", config, project=second_project) delete = [ "discover", "libraries", "delete", discovery_library_name, - "--namespace", - DISCOVERY_TEST_NAMESPACE, + "--project", + second_project, "--yes", ] diff --git a/tests/integration/test_rulesets.py b/tests/integration/test_rulesets.py index e087902..520a268 100644 --- a/tests/integration/test_rulesets.py +++ b/tests/integration/test_rulesets.py @@ -49,7 +49,7 @@ def test_create_without_type_aborts_when_name_is_ambiguous( assert "Multiple rulesets" in result.stderr -def test_create_with_type_updates_only_matching_namespace( +def test_create_with_type_updates_only_the_ruleset_of_that_type( runner: CliRunner, ruleset_name: str, file_yaml: Path, @@ -70,7 +70,7 @@ def test_create_with_type_updates_only_matching_namespace( assert "mask_table" in db_after.stdout -def test_delete_with_type_leaves_other_namespace_intact( +def test_delete_with_type_leaves_the_other_types_ruleset( runner: CliRunner, ruleset_name: str, file_yaml: Path, diff --git a/tests/test_projects.py b/tests/test_projects.py new file mode 100644 index 0000000..a6d6d11 --- /dev/null +++ b/tests/test_projects.py @@ -0,0 +1,131 @@ +from __future__ import annotations + +from types import SimpleNamespace +from unittest.mock import MagicMock + +import pytest +from datamasque.client.models.project import Project + +from datamasque_cli.errors import ExitCode +from datamasque_cli.projects import ( + filter_by_project, + get_project_names_by_reference, + project_label, + require_single_or_abort, + resolve_create_project, + resolve_project, + resolve_target_project, +) +from tests.conftest import make_project, with_projects + +DEFAULT = make_project(1, "Default") +FINANCE = make_project(2, "Finance") + + +def _client(*projects: Project) -> MagicMock: + return with_projects(MagicMock(), *projects) + + +@pytest.mark.parametrize("name_or_id", ["Finance", "finance", "FINANCE", "2"]) +def test_resolve_project_by_name_ignoring_case_or_by_id(name_or_id: str) -> None: + assert resolve_project(_client(DEFAULT, FINANCE), name_or_id) == FINANCE + + +def test_resolve_project_prefers_a_name_over_an_equal_id() -> None: + """A project named `1` wins over the project with id 1, as names are tried first.""" + named_one = make_project(5, "1") + + assert resolve_project(_client(DEFAULT, named_one), "1") == named_one + + +def test_resolve_project_unknown_is_not_found() -> None: + with pytest.raises(SystemExit) as raised: + resolve_project(_client(DEFAULT), "Finance") + + assert raised.value.code == ExitCode.NOT_FOUND + + +def test_resolve_target_project_uses_the_only_project_when_none_is_given() -> None: + assert resolve_target_project(_client(DEFAULT), None) == DEFAULT + + +def test_resolve_target_project_needs_a_project_once_there_are_two() -> None: + with pytest.raises(SystemExit) as raised: + resolve_target_project(_client(DEFAULT, FINANCE), None) + + assert raised.value.code == ExitCode.AMBIGUOUS + + +def test_get_project_names_by_reference_includes_archived_projects() -> None: + client = _client(DEFAULT, FINANCE) + + assert get_project_names_by_reference(client) == {"1-default": "Default", "2-finance": "Finance"} + client.list_projects.assert_called_once_with(include_archived=True) + + +def test_project_label_names_the_project_and_leaves_a_built_in_blank() -> None: + names = {"2-finance": "Finance"} + + assert project_label(names, "2-finance") == "Finance" + assert project_label(names, None) == "" + + +def test_filter_by_project_keeps_only_that_projects_items() -> None: + items = [SimpleNamespace(project="1-default"), SimpleNamespace(project="2-finance")] + + assert filter_by_project(items, FINANCE) == [items[1]] + assert filter_by_project(items, None) == items + + +def test_require_single_returns_the_only_match() -> None: + match = SimpleNamespace(project="1-default") + + assert require_single_or_abort(_client(DEFAULT), [match], "Ruleset 'r'") is match + + +def test_require_single_with_no_match_is_not_found() -> None: + with pytest.raises(SystemExit) as raised: + require_single_or_abort(_client(DEFAULT), [], "Ruleset 'r'") + + assert raised.value.code == ExitCode.NOT_FOUND + + +def test_require_single_with_a_match_in_two_projects_is_ambiguous(capsys: pytest.CaptureFixture[str]) -> None: + matches = [SimpleNamespace(project="1-default"), SimpleNamespace(project="2-finance")] + + with pytest.raises(SystemExit) as raised: + require_single_or_abort(_client(DEFAULT, FINANCE), matches, "Ruleset 'r'") + + assert raised.value.code == ExitCode.AMBIGUOUS + assert capsys.readouterr().err == ( + "Error: Ruleset 'r' exists in more than one project:\n" + " project=Default\n" + " project=Finance\n" + "Hint: Pass --project to disambiguate.\n" + ) + + +def test_resolve_create_project_prefers_the_named_project() -> None: + existing = [SimpleNamespace(project="1-default")] + + assert resolve_create_project(_client(DEFAULT, FINANCE), "Finance", existing) == "2-finance" + + +def test_resolve_create_project_updates_where_the_name_already_is() -> None: + """An update needs no `--project` when only one project has the name, even on a multi-project instance.""" + existing = [SimpleNamespace(project="2-finance"), SimpleNamespace(project="2-finance")] + + assert resolve_create_project(_client(DEFAULT, FINANCE), None, existing) == "2-finance" + + +def test_resolve_create_project_with_the_name_in_two_projects_is_ambiguous() -> None: + existing = [SimpleNamespace(project="1-default"), SimpleNamespace(project="2-finance")] + + with pytest.raises(SystemExit) as raised: + resolve_create_project(_client(DEFAULT, FINANCE), None, existing) + + assert raised.value.code == ExitCode.AMBIGUOUS + + +def test_resolve_create_project_for_a_new_name_uses_the_only_project() -> None: + assert resolve_create_project(_client(DEFAULT), None, []) == "1-default" diff --git a/uv.lock b/uv.lock index 7189372..fd6666d 100644 --- a/uv.lock +++ b/uv.lock @@ -162,7 +162,7 @@ dev = [ [package.metadata] requires-dist = [ - { name = "datamasque-python", specifier = ">=1.2.5,<2" }, + { name = "datamasque-python", specifier = ">=1.6.0,<2" }, { name = "pydantic", specifier = ">=2.5,<3" }, { name = "rich", specifier = ">=13.8" }, { name = "tomli-w", specifier = ">=1.0.0,<2" }, @@ -180,15 +180,15 @@ dev = [ [[package]] name = "datamasque-python" -version = "1.2.5" +version = "1.6.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "pydantic" }, { name = "requests" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/dd/e3/2f48d7182c6e38abece16b7bb218fd94f2bce07d5025c1d2e532183c70b4/datamasque_python-1.2.5.tar.gz", hash = "sha256:5969e9a6303970433eddb9a6ca15f255666216f51d9a13ce7f23e26eb37ffb8b", size = 209710, upload-time = "2026-08-21T07:41:48.559Z" } +sdist = { url = "https://files.pythonhosted.org/packages/dd/78/930fbd2cecf2d5896908370d437cd2f1d242e9100b7f064e4d287894574e/datamasque_python-1.6.0.tar.gz", hash = "sha256:d97d2320a4e802b52c3dd0a4b2b6f0d247f50d944b2f35d810f0c88ac0493481", size = 259133, upload-time = "2026-11-20T01:39:31.755Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/fe/69/61f3b32309773b3ff716334c3f4f75dbfb8b1e1939f066d2cfebe123e024/datamasque_python-1.2.5-py3-none-any.whl", hash = "sha256:ad3776f7b321308d827203f821e567255def52a7ef899d0aa80cc490a5a096e3", size = 77348, upload-time = "2026-08-21T07:41:47.19Z" }, + { url = "https://files.pythonhosted.org/packages/4e/87/749bb0310b7dfb48857d6e2767ea89ab591ff412d26a80ef5c3c4da11a93/datamasque_python-1.6.0-py3-none-any.whl", hash = "sha256:2f57e6fe6857e80adad0da1d2bc33e9b46be150c0328541f70b61159805ed68a", size = 108255, upload-time = "2026-11-20T01:39:30.272Z" }, ] [[package]]