diff --git a/changelog/+schema-export-client-rules.removed.md b/changelog/+schema-export-client-rules.removed.md new file mode 100644 index 000000000..89654d222 --- /dev/null +++ b/changelog/+schema-export-client-rules.removed.md @@ -0,0 +1 @@ +Removed `schema_to_export_dict`, `RESTRICTED_NAMESPACES`, `NamespaceExport` and `SchemaExport` from `infrahub_sdk.schema`, because Infrahub now builds the schema export. Use `SchemaExportDocument` and `split_by_namespace` instead. diff --git a/changelog/+schema-export-document.changed.md b/changelog/+schema-export-document.changed.md new file mode 100644 index 000000000..f2d42d8c4 --- /dev/null +++ b/changelog/+schema-export-document.changed.md @@ -0,0 +1 @@ +`InfrahubSchema.export` and `InfrahubSchemaSync.export` now return the document that Infrahub builds, as a `SchemaExportDocument`, instead of a `SchemaExport`. They take a `mode` argument, `BRIEF` by default. `split_by_namespace` splits an export, either the `SchemaExportDocument` that `export` returns or the JSON body as a dict, into one dict per namespace. From a dict, it copies every field, including fields this SDK version does not know. Against an Infrahub server without the schema export endpoint, they raise `VersionNotSupportedError` with the first Infrahub release that has it. When `namespaces` names a namespace that does not exist on the branch, or a namespace reserved for Infrahub such as `Core`, they raise the new `SchemaNamespaceNotFoundError`, with one message for each such namespace. When the document holds a value this SDK version cannot read, such as an attribute kind added in a later Infrahub release, they raise `InvalidResponseError`. diff --git a/changelog/+schema-export-endpoint.changed.md b/changelog/+schema-export-endpoint.changed.md new file mode 100644 index 000000000..5cde72d24 --- /dev/null +++ b/changelog/+schema-export-endpoint.changed.md @@ -0,0 +1,18 @@ +`infrahubctl schema export` now asks Infrahub to build the export, so it needs an Infrahub server with the schema export endpoint (Infrahub 1.13.0 or later). With the default `BRIEF` mode, the files it writes differ from the files earlier versions wrote: + +- `branch` on an attribute or relationship is written when it differs from the value Infrahub derives from the node or the peer. +- Values that Infrahub derives when it loads the schema, such as a `label` taken from the name, are left out. +- When an attribute has `unique: true`, the `human_friendly_id` and `uniqueness_constraints` that Infrahub derives from it are left out, and `unique` is written. +- The relationship `identifier`, `cardinality` and `optional`, and the attribute `read_only` and `choices`, are written when they differ from their default value. +- `IpamNamespace` is no longer written. +- A relationship of kind `Group`, `Profile`, `Hierarchy` or `Template` that you defined is now written. A relationship with the kind, name and identifier of one that Infrahub generates, such as `member_of_groups` or `object_template`, is written only when it differs from the relationship Infrahub generates. Earlier versions left out every relationship of kind `Group`, `Profile` or `Hierarchy`, and wrote the `object_template` relationship that Infrahub generates. +- On a `Text` or `TextArea` attribute, `regex`, `min_length` and `max_length` are written under `parameters`. On a `List` attribute, `regex` is written under `parameters`, and `min_length` and `max_length` stay at the top level. On an attribute of any other kind, these settings stay at the top level. +- NumberPool `start_range` and `end_range` are written as one entry of `ranges`. +- Each file has an `infrahub_version` field with the version of the Infrahub server that built it. +- The files hold every field the server returned, including fields that a later Infrahub release adds and this SDK version does not know. +- A value without a line break is written on one line, however long it is. Earlier versions split a value longer than about 80 characters, such as a Jinja2 template, over several lines. +- The files are laid out as `infrahubctl schema format` lays out a schema file: they start with `---` and the `yaml-language-server` comment, and the keys of each node, generic, attribute, relationship and dropdown choice are in the order that command uses. A list that holds no mapping, such as `human_friendly_id` or `uniqueness_constraints`, is written on one line, as in `[[device, name__value]]`. When a file cannot be formatted without changing a value, the command writes no file, prints the error and exits with code 1. +- The deprecated `default_filter` of a node or generic is no longer written. A `FULL` export still writes it. +- No `state` field is written on a node, generic, attribute, relationship or dropdown choice, in either mode. + +`--namespaces` with a namespace that does not exist on the branch, or with a namespace reserved for Infrahub such as `Core`, now prints an error for each such namespace and exits with code 1. diff --git a/changelog/+schema-export-options.added.md b/changelog/+schema-export-options.added.md new file mode 100644 index 000000000..bd870f4d1 --- /dev/null +++ b/changelog/+schema-export-options.added.md @@ -0,0 +1 @@ +Added the `--mode` option to `infrahubctl schema export`: `BRIEF`, the default, leaves out the values Infrahub derives when it loads the schema, and `FULL` writes every value. Added the `--single-file` option, which writes all namespaces to one file, `schema.yml`. diff --git a/changelog/+schema-format-infrahub-version.changed.md b/changelog/+schema-format-infrahub-version.changed.md new file mode 100644 index 000000000..8170883d3 --- /dev/null +++ b/changelog/+schema-format-infrahub-version.changed.md @@ -0,0 +1 @@ +`infrahubctl schema format` writes the `infrahub_version` field of a schema file directly after `version`. It no longer splits a value longer than 4096 characters over several lines, so such a value in an existing file is written on one line the next time you format the file. diff --git a/docs/docs/infrahubctl/infrahubctl-schema.mdx b/docs/docs/infrahubctl/infrahubctl-schema.mdx index ec9f24fe3..1a0f9951d 100644 --- a/docs/docs/infrahubctl/infrahubctl-schema.mdx +++ b/docs/docs/infrahubctl/infrahubctl-schema.mdx @@ -68,7 +68,7 @@ $ infrahubctl schema check [OPTIONS] SCHEMAS... ## `infrahubctl schema export` -Export the schema from Infrahub as YAML files, one per namespace. +Export the schema from Infrahub as YAML files: one per namespace, or one file with --single-file. **Usage**: @@ -78,9 +78,11 @@ $ infrahubctl schema export [OPTIONS] **Options**: -* `--directory PATH`: Directory path to store schema files [default: (dynamic)] +* `--directory PATH`: Directory to write the schema files to. Created if it does not exist; existing files with the same name are overwritten. [default: (./infrahub-schema-export-<YYYYMMDD-HHMMSS>)] * `--branch TEXT`: Branch from which to export the schema * `--namespaces TEXT`: Namespace(s) to export (default: all user-defined) +* `--mode [BRIEF|FULL]`: BRIEF leaves out the values Infrahub derives when the schema is loaded; FULL writes every value [default: BRIEF] +* `--single-file`: Write all namespaces to one file, schema.yml * `--debug / --no-debug`: [default: no-debug] * `--config-file TEXT`: [env var: INFRAHUBCTL_CONFIG; default: infrahubctl.toml] * `--help`: Show this message and exit. diff --git a/infrahub_sdk/ctl/schema.py b/infrahub_sdk/ctl/schema.py index 46b7f2072..2ab7419b7 100644 --- a/infrahub_sdk/ctl/schema.py +++ b/infrahub_sdk/ctl/schema.py @@ -2,6 +2,7 @@ import asyncio import difflib +import sys import time from datetime import datetime, timezone from enum import Enum @@ -17,8 +18,24 @@ from ..async_typer import AsyncTyper from ..ctl.client import initialize_client from ..ctl.utils import catch_exception, init_logging +from ..exceptions import ( + ApiError, + AuthenticationError, + InvalidResponseError, + JsonDecodeError, + SchemaNamespaceNotFoundError, + URLNotFoundError, + VersionNotSupportedError, +) from ..queries import SCHEMA_HASH_SYNC_STATUS -from ..schema import NodeSchemaAPI, SchemaWarning, validate_schema +from ..schema import ( + NodeSchemaAPI, + SchemaExportMode, + SchemaWarning, + split_by_namespace, + validate_schema, +) +from ..schema.export import EXPORT_ELEMENT_SECTIONS from ..yaml import SchemaFile from .parameters import CONFIG_PARAM from .schema_format import ( @@ -32,6 +49,26 @@ SchemaContainer = Literal["nodes", "generics", "relationships"] +_EXPORT_LINE_WIDTH = sys.maxsize +"""Line width for the exported files, so that a long value such as a Jinja2 template stays on one line.""" + + +class _ExportDumper(yaml.SafeDumper): + """Writes a list that holds no mapping inline, as in `[[device, name__value]]`, as schema files usually do.""" + + +def _represent_export_list(dumper: yaml.SafeDumper, data: list[Any]) -> yaml.Node: + return dumper.represent_sequence("tag:yaml.org,2002:seq", data, flow_style=not _holds_mapping(data)) + + +def _holds_mapping(value: Any) -> bool: + if isinstance(value, dict): + return True + return isinstance(value, list) and any(_holds_mapping(item) for item in value) + + +_ExportDumper.add_representer(list, _represent_export_list) + app = AsyncTyper() console = Console() @@ -294,42 +331,92 @@ def _default_export_directory() -> Path: @app.command() @catch_exception(console=console) async def export( - directory: Path = typer.Option(_default_export_directory, help="Directory path to store schema files"), + directory: Path = typer.Option( + _default_export_directory, + show_default="./infrahub-schema-export-", + help="Directory to write the schema files to. Created if it does not exist; existing files with the same name are overwritten.", + ), branch: str = typer.Option(None, help="Branch from which to export the schema"), namespaces: list[str] = typer.Option([], help="Namespace(s) to export (default: all user-defined)"), + mode: SchemaExportMode = typer.Option( + SchemaExportMode.BRIEF, + help="BRIEF leaves out the values Infrahub derives when the schema is loaded; FULL writes every value", + ), + single_file: bool = typer.Option(False, "--single-file", help="Write all namespaces to one file, schema.yml"), debug: bool = False, _: str = CONFIG_PARAM, ) -> None: - """Export the schema from Infrahub as YAML files, one per namespace.""" + """Export the schema from Infrahub as YAML files: one per namespace, or one file with --single-file.""" init_logging(debug=debug) client = initialize_client() - user_schemas = await client.schema.export( - branch=branch, - namespaces=namespaces or None, - ) - - if not user_schemas.namespaces: + try: + # Written as received, so the files keep the fields an older SDK version does not know. + document = await client.schema._export_payload(branch=branch, namespaces=namespaces or None, mode=mode) + except SchemaNamespaceNotFoundError as exc: + for message in exc.messages: + console.print(f"[red]Error: {escape(message)}") + raise typer.Exit(code=1) from exc + except ( + VersionNotSupportedError, + URLNotFoundError, + JsonDecodeError, + InvalidResponseError, + ApiError, + ) as exc: + if isinstance(exc, AuthenticationError): + raise + console.print(f"[red]Error: {escape(str(exc))}") + raise typer.Exit(code=1) from exc + + if not any(document.get(section) for section in EXPORT_ELEMENT_SECTIONS): console.print("[yellow]No user-defined schema found to export.") return + if single_file: + output_file = directory / "schema.yml" + files = [(output_file, document, f"Exported schema to {escape(str(output_file))}")] + else: + files = [ + ( + directory / f"{ns.lower()}.yml", + namespace_document, + f"Exported namespace '{escape(ns)}' to {escape(str(directory / f'{ns.lower()}.yml'))}", + ) + for ns, namespace_document in sorted(split_by_namespace(document).items()) + ] + + try: + # Every file is rendered before any is written, so a failure leaves no partial export behind. + rendered = [(output_file, _render_schema_file(content), message) for output_file, content, message in files] + except FormatError as exc: + console.print(f"[red]Error: {escape(str(exc))}") + raise typer.Exit(code=1) from exc + directory.mkdir(parents=True, exist_ok=True) + for output_file, text, message in rendered: + output_file.write_text(text, encoding="utf-8") + console.print(f"[green] {message}") - for ns, data in sorted(user_schemas.namespaces.items()): - payload: dict[str, Any] = {"version": "1.0"} - if data.generics: - payload["generics"] = data.generics - if data.nodes: - payload["nodes"] = data.nodes - - output_file = directory / f"{ns.lower()}.yml" - output_file.write_text( - yaml.dump(payload, default_flow_style=False, sort_keys=False, allow_unicode=True), - encoding="utf-8", - ) - console.print(f"[green] Exported namespace '{ns}' to {output_file}") + console.print(f"[green] Schema exported to {escape(str(directory))}") + + +def _render_schema_file(document: dict[str, Any]) -> str: + """Return an exported document as YAML in the layout that `infrahubctl schema format` gives a schema file. - console.print(f"[green] Schema exported to {directory}") + Raises: + FormatError: When formatting would change a value of the document. + + """ + text = yaml.dump( + document, + Dumper=_ExportDumper, + default_flow_style=False, + sort_keys=False, + allow_unicode=True, + width=_EXPORT_LINE_WIDTH, + ) + return format_schema_text(text) @app.command(name="list") diff --git a/infrahub_sdk/ctl/schema_format.py b/infrahub_sdk/ctl/schema_format.py index 7dd0a6c7b..2985f8765 100644 --- a/infrahub_sdk/ctl/schema_format.py +++ b/infrahub_sdk/ctl/schema_format.py @@ -32,6 +32,7 @@ import json import re +import sys from dataclasses import dataclass from io import StringIO from typing import Any @@ -73,7 +74,7 @@ # Canonical key orders. Each pair is (leading keys, trailing keys); any key not # listed is preserved in its original position between the two groups so the # formatter never drops data. -FILE_ORDER = ["version", "generics", "nodes", "extensions"] +FILE_ORDER = ["version", "infrahub_version", "generics", "nodes", "extensions"] NODE_ORDER = [ "name", @@ -205,9 +206,9 @@ def _build_yaml() -> YAML: # Match the schema-library layout: block sequences indented under their key # (`attributes:\n - name: ...`). yaml_handler.indent(mapping=2, sequence=4, offset=2) - # A very wide value keeps long scalars (descriptions, Jinja2 templates) on + # An unlimited width keeps long scalars (descriptions, Jinja2 templates) on # their original line instead of being re-wrapped. - yaml_handler.width = 4096 + yaml_handler.width = sys.maxsize return yaml_handler diff --git a/infrahub_sdk/exceptions/__init__.py b/infrahub_sdk/exceptions/__init__.py index 3e84e8254..ab9ecbe76 100644 --- a/infrahub_sdk/exceptions/__init__.py +++ b/infrahub_sdk/exceptions/__init__.py @@ -44,6 +44,7 @@ RateLimitError, RepositoryFileNotFoundError, ResourceNotDefinedError, + SchemaNamespaceNotFoundError, SchemaNotFoundError, ServerNotReachableError, ServerNotResponsiveError, @@ -106,6 +107,7 @@ "RateLimitError", "RepositoryFileNotFoundError", "ResourceNotDefinedError", + "SchemaNamespaceNotFoundError", "SchemaNotFoundError", "ServerNotReachableError", "ServerNotResponsiveError", diff --git a/infrahub_sdk/exceptions/base.py b/infrahub_sdk/exceptions/base.py index 656cd069e..bf3082bc8 100644 --- a/infrahub_sdk/exceptions/base.py +++ b/infrahub_sdk/exceptions/base.py @@ -37,6 +37,7 @@ "RateLimitError", "RepositoryFileNotFoundError", "ResourceNotDefinedError", + "SchemaNamespaceNotFoundError", "SchemaNotFoundError", "ServerNotReachableError", "ServerNotResponsiveError", @@ -206,6 +207,18 @@ def __reduce__(self) -> tuple[type[TrackingGroupCleanupError], tuple[dict[str, s return (self.__class__, (self.failures,)) +class SchemaNamespaceNotFoundError(ApiError): + """Raised when a schema export names a namespace that does not exist on the branch or cannot be exported.""" + + def __init__(self, namespaces: list[str], messages: list[str]) -> None: + self.namespaces = namespaces + self.messages = messages + super().__init__("; ".join(messages)) + + def __reduce__(self) -> tuple[Any, ...]: + return (_rebuild_error, (type(self), self.args, self.__dict__)) + + class VersionNotSupportedError(Error): """Raised when a feature is used against an Infrahub server version that does not support it.""" @@ -215,6 +228,9 @@ def __init__(self, feature: str, required_version: str) -> None: self.message = f"{feature} requires Infrahub {required_version} or later." super().__init__(self.message) + def __reduce__(self) -> tuple[Any, ...]: + return (_rebuild_error, (type(self), self.args, self.__dict__)) + class BranchNotFoundPayload(Protocol): """The fields a server-reported BRANCH_NOT_FOUND carries.""" diff --git a/infrahub_sdk/schema/__init__.py b/infrahub_sdk/schema/__init__.py index fb2d5cddf..95dbc89f5 100644 --- a/infrahub_sdk/schema/__init__.py +++ b/infrahub_sdk/schema/__init__.py @@ -12,18 +12,24 @@ import httpx from pydantic import BaseModel, Field +from pydantic import ValidationError as PydanticValidationError from ..exceptions import ( + ApiError, BranchNotFoundError, InvalidResponseError, JsonDecodeError, + SchemaNamespaceNotFoundError, SchemaNotFoundError, + URLNotFoundError, ValidationError, + VersionNotSupportedError, + authentication_error_from_response, ) from ..graphql import Mutation from ..protocols_base import CoreNodeBase from ..queries import SCHEMA_HASH_SYNC_STATUS -from .export import RESTRICTED_NAMESPACES, NamespaceExport, SchemaExport, schema_to_export_dict +from .export import SchemaExportDocument, SchemaExportMode, split_by_namespace from .generated.read import InfrahubSchemaRead from .generated.write import InfrahubSchemaWrite from .main import ( @@ -66,7 +72,6 @@ "GenericSchemaAPI", "InfrahubSchemaRead", "InfrahubSchemaWrite", - "NamespaceExport", "NodeSchema", "NodeSchemaAPI", "ProfileSchemaAPI", @@ -74,17 +79,31 @@ "RelationshipKind", "RelationshipSchema", "RelationshipSchemaAPI", - "SchemaExport", + "SchemaExportDocument", + "SchemaExportMode", "SchemaRoot", "SchemaRootAPI", "SchemaValidationErrorDetail", "SchemaValidationResult", "SchemaValidationWarningDetail", "TemplateSchemaAPI", - "schema_to_export_dict", + "split_by_namespace", "validate_schema", ] +SCHEMA_EXPORT_MIN_INFRAHUB_VERSION = "1.13.0" +"""First Infrahub release that serves the schema export endpoint.""" + +# An older server routes the export URL as a request for a schema kind named "export". +_SCHEMA_EXPORT_MISSING_MESSAGE = "Unable to find the schema 'export' in the registry" + + +def _error_namespace(error: dict[str, Any]) -> str | None: + """Return the namespace a schema export error names in its extensions, if any.""" + extensions = error.get("extensions") + namespace = extensions.get("namespace") if isinstance(extensions, dict) else None + return namespace if isinstance(namespace, str) else None + class DropdownMutationOptionalArgs(TypedDict): color: str | None @@ -137,47 +156,90 @@ def __init__(self, client: InfrahubClient | InfrahubClientSync) -> None: self.client = client self.cache = {} + def _export_url(self, branch: str, namespaces: list[str] | None, mode: SchemaExportMode) -> str: + url_parts = [("branch", branch)] + if namespaces: + url_parts.extend([("namespaces", ns) for ns in namespaces]) + url_parts.append(("mode", SchemaExportMode(mode).value)) + return f"{self.client.address}/api/schema/export?{urlencode(url_parts)}" + @staticmethod - def _build_export_schemas( - schema_nodes: MutableMapping[str, MainSchemaTypesAPI], - namespaces: list[str] | None = None, - ) -> SchemaExport: - """Organize fetched schemas into a per-namespace export structure. + def _parse_export_response(response: httpx.Response, branch: str) -> tuple[dict[str, Any], SchemaExportDocument]: + """Read the schema export endpoint's response. - Filters out system types (Profile/Template) and restricted namespaces - (see :data:`RESTRICTED_NAMESPACES`), and optionally limits to specific - namespaces. If the caller requests restricted namespaces they are - silently excluded and a :func:`warnings.warn` is emitted. + Returns the JSON body as the server sent it and the document checked against the write models. The write + models of this SDK version drop the fields they do not declare, so only the JSON body holds every field. - Returns: - A :class:`SchemaExport` containing user-defined schemas by namespace. + Raises: + AuthenticationError: When the server rejects the credentials (401) or the permissions (403). + BranchNotFoundError: When the branch does not exist on the server. + VersionNotSupportedError: When the server is older than the first release with the endpoint. + SchemaNamespaceNotFoundError: When a requested namespace does not exist on the branch or cannot be + exported, with one message per namespace. + URLNotFoundError: When the server returns a 404 that does not name a namespace. + ApiError: When the server returns any other error, with the messages the server returned. + JsonDecodeError: When the server returns a body that is not JSON. + InvalidResponseError: When the document holds a value this SDK version cannot read. + + """ # noqa: DOC501 # raises via a factory, whose name ruff reads as the exception's + if response.status_code == httpx.codes.OK: + try: + payload = response.json() + return payload, SchemaExportDocument.model_validate(payload) + except json.decoder.JSONDecodeError as exc: + raise JsonDecodeError( + message=f"Invalid schema export response received from the server at {response.url}: {response.text} [{response.status_code}]", + content=response.text, + url=str(response.url), + ) from exc + except PydanticValidationError as exc: + raise InvalidResponseError( + f"The schema export from {response.url} holds a value this version of the SDK cannot read; " + f"use an SDK version that matches the Infrahub server. {exc}" + ) from exc + + if response.status_code in {httpx.codes.UNAUTHORIZED, httpx.codes.FORBIDDEN}: + raise authentication_error_from_response(response=response) + + if response.status_code == httpx.codes.BAD_REQUEST: + raise BranchNotFoundError( + identifier=branch, message=f"The requested branch was not found on the server [{branch}]" + ) - """ - if namespaces: - restricted = set(namespaces) & set(RESTRICTED_NAMESPACES) - if restricted: - warnings.warn( - f"Restricted namespace(s) {sorted(restricted)} requested but will be excluded from export", - stacklevel=3, - ) + try: + body = response.json() + except json.decoder.JSONDecodeError: + body = None + errors = body.get("errors") if isinstance(body, dict) else None + error_list = [error for error in errors if isinstance(error, dict)] if isinstance(errors, list) else [] + messages = [error["message"] for error in error_list if isinstance(error.get("message"), str)] + + if response.status_code == httpx.codes.UNPROCESSABLE_ENTITY and _SCHEMA_EXPORT_MISSING_MESSAGE in messages: + raise VersionNotSupportedError( + feature="The schema export", required_version=SCHEMA_EXPORT_MIN_INFRAHUB_VERSION + ) - ns_map: dict[str, NamespaceExport] = {} - for schema in schema_nodes.values(): - if isinstance(schema, (ProfileSchemaAPI, TemplateSchemaAPI)): - continue - if schema.namespace in RESTRICTED_NAMESPACES: - continue - if namespaces and schema.namespace not in namespaces: - continue - ns = schema.namespace - if ns not in ns_map: - ns_map[ns] = NamespaceExport() - schema_dict = schema_to_export_dict(schema) - if isinstance(schema, GenericSchemaAPI): - ns_map[ns].generics.append(schema_dict) - else: - ns_map[ns].nodes.append(schema_dict) - return SchemaExport(namespaces=ns_map) + if response.status_code == httpx.codes.NOT_FOUND: + named_errors = [(error, _error_namespace(error)) for error in error_list] + if not named_errors or any(namespace is None for _, namespace in named_errors): + raise URLNotFoundError(url=str(response.url)) + namespaces = [namespace for _, namespace in named_errors if namespace is not None] + namespace_messages = [ + message + if isinstance(message := error.get("message"), str) + else f"The namespace '{namespace}' cannot be exported" + for error, namespace in named_errors + ] + namespace_error = SchemaNamespaceNotFoundError(namespaces=namespaces, messages=namespace_messages) + namespace_error.http_status = response.status_code + namespace_error.errors = error_list + raise namespace_error + + details = " | ".join(messages) if messages else response.text + api_error = ApiError(message=f"HTTP {response.status_code}: {details}") + api_error.http_status = response.status_code + api_error.errors = error_list + raise api_error def validate(self, data: dict[str, Any]) -> SchemaValidationResult: """Validate a schema payload against the generated write contract. @@ -579,28 +641,44 @@ async def export( self, branch: str | None = None, namespaces: list[str] | None = None, - ) -> SchemaExport: - """Export user-defined schemas organized by namespace. - - Fetches schemas from the server, filters out system types and - restricted namespaces (see :data:`RESTRICTED_NAMESPACES`), and returns - a :class:`SchemaExport` object with per-namespace data. Restricted - namespaces such as ``Core`` and ``Builtin`` are always excluded even if - explicitly listed in *namespaces*; a warning is emitted when this - happens. + mode: SchemaExportMode = SchemaExportMode.BRIEF, + ) -> SchemaExportDocument: + """Export the user-defined schema of a branch as one schema file, built by the server. Args: branch: Branch to export from. Defaults to default_branch. - namespaces: Optional list of namespaces to include. If empty/None, - all user-defined namespaces are exported. + namespaces: Namespaces to export. If empty or None, the server exports all user-defined namespaces. + mode: BRIEF leaves out the values Infrahub derives when the file is loaded; FULL writes every value. Returns: - A :class:`SchemaExport` containing user-defined schemas by namespace. + The server's document, holding only the fields the server returned. + + Raises: + BranchNotFoundError: When the branch does not exist on the server. + VersionNotSupportedError: When the server is older than the first release with the export endpoint. + SchemaNamespaceNotFoundError: When a namespace does not exist on the branch or cannot be exported. + URLNotFoundError: When the server returns a 404 that does not name a namespace. + ApiError: When the server returns any other error, with the messages the server returned. + JsonDecodeError: When the server returns a body that is not JSON. + InvalidResponseError: When the document holds a value this SDK version cannot read. """ branch = branch or self.client.default_branch - schema_nodes = await self.fetch(branch=branch, namespaces=namespaces, populate_cache=False) - return self._build_export_schemas(schema_nodes=schema_nodes, namespaces=namespaces) + response = await self.client._get(url=self._export_url(branch=branch, namespaces=namespaces, mode=mode)) + _, document = self._parse_export_response(response=response, branch=branch) + return document + + async def _export_payload( + self, + branch: str | None = None, + namespaces: list[str] | None = None, + mode: SchemaExportMode = SchemaExportMode.BRIEF, + ) -> dict[str, Any]: + """Export the user-defined schema of a branch and return the server's document with every field it holds.""" + branch = branch or self.client.default_branch + response = await self.client._get(url=self._export_url(branch=branch, namespaces=namespaces, mode=mode)) + payload, _ = self._parse_export_response(response=response, branch=branch) + return payload async def get_graphql_schema(self, branch: str | None = None) -> str: """Get the GraphQL schema as a string. @@ -857,28 +935,44 @@ def export( self, branch: str | None = None, namespaces: list[str] | None = None, - ) -> SchemaExport: - """Export user-defined schemas organized by namespace. - - Fetches schemas from the server, filters out system types and - restricted namespaces (see :data:`RESTRICTED_NAMESPACES`), and returns - a :class:`SchemaExport` object with per-namespace data. Restricted - namespaces such as ``Core`` and ``Builtin`` are always excluded even if - explicitly listed in *namespaces*; a warning is emitted when this - happens. + mode: SchemaExportMode = SchemaExportMode.BRIEF, + ) -> SchemaExportDocument: + """Export the user-defined schema of a branch as one schema file, built by the server. Args: branch: Branch to export from. Defaults to default_branch. - namespaces: Optional list of namespaces to include. If empty/None, - all user-defined namespaces are exported. + namespaces: Namespaces to export. If empty or None, the server exports all user-defined namespaces. + mode: BRIEF leaves out the values Infrahub derives when the file is loaded; FULL writes every value. Returns: - A :class:`SchemaExport` containing user-defined schemas by namespace. + The server's document, holding only the fields the server returned. + + Raises: + BranchNotFoundError: When the branch does not exist on the server. + VersionNotSupportedError: When the server is older than the first release with the export endpoint. + SchemaNamespaceNotFoundError: When a namespace does not exist on the branch or cannot be exported. + URLNotFoundError: When the server returns a 404 that does not name a namespace. + ApiError: When the server returns any other error, with the messages the server returned. + JsonDecodeError: When the server returns a body that is not JSON. + InvalidResponseError: When the document holds a value this SDK version cannot read. """ branch = branch or self.client.default_branch - schema_nodes = self.fetch(branch=branch, namespaces=namespaces, populate_cache=False) - return self._build_export_schemas(schema_nodes=schema_nodes, namespaces=namespaces) + response = self.client._get(url=self._export_url(branch=branch, namespaces=namespaces, mode=mode)) + _, document = self._parse_export_response(response=response, branch=branch) + return document + + def _export_payload( + self, + branch: str | None = None, + namespaces: list[str] | None = None, + mode: SchemaExportMode = SchemaExportMode.BRIEF, + ) -> dict[str, Any]: + """Export the user-defined schema of a branch and return the server's document with every field it holds.""" + branch = branch or self.client.default_branch + response = self.client._get(url=self._export_url(branch=branch, namespaces=namespaces, mode=mode)) + payload, _ = self._parse_export_response(response=response, branch=branch) + return payload def get_graphql_schema(self, branch: str | None = None) -> str: """Get the GraphQL schema as a string. diff --git a/infrahub_sdk/schema/export.py b/infrahub_sdk/schema/export.py index 378f0386d..34dc8b9a4 100644 --- a/infrahub_sdk/schema/export.py +++ b/infrahub_sdk/schema/export.py @@ -1,121 +1,46 @@ from __future__ import annotations -from typing import Any +from enum import Enum +from typing import TYPE_CHECKING, Any -from pydantic import BaseModel, Field +from .generated.write import InfrahubSchemaWrite -from .main import GenericSchemaAPI, NodeSchemaAPI +if TYPE_CHECKING: + from collections.abc import Mapping +EXPORT_ELEMENT_SECTIONS = ("generics", "nodes") -class NamespaceExport(BaseModel): - """Export data for a single namespace.""" - nodes: list[dict[str, Any]] = Field(default_factory=list) - generics: list[dict[str, Any]] = Field(default_factory=list) +class SchemaExportMode(str, Enum): + BRIEF = "BRIEF" + """Leaves out the values that Infrahub derives again when the export is loaded.""" + FULL = "FULL" + """Writes every value of the user-defined nodes and generics that a schema file can carry.""" -class SchemaExport(BaseModel): - """Result of a schema export, organized by namespace.""" - namespaces: dict[str, NamespaceExport] = Field(default_factory=dict) +class SchemaExportDocument(InfrahubSchemaWrite): + """Schema file returned by the schema export endpoint, valid as a schema load payload.""" - def to_dict(self) -> dict[str, dict[str, list[dict[str, Any]]]]: - """Convert to plain dict for YAML serialization.""" - return {ns: data.model_dump(exclude_defaults=True) for ns, data in self.namespaces.items()} + infrahub_version: str -# Namespaces reserved by the Infrahub server — mirrored from -# backend/infrahub/core/constants/__init__.py in the opsmill/infrahub repo. -RESTRICTED_NAMESPACES: list[str] = [ - "Account", - "Branch", - "Builtin", - "Core", - "Deprecated", - "Diff", - "Infrahub", - "Internal", - "Lineage", - "Schema", - "Profile", - "Template", -] +def split_by_namespace(document: SchemaExportDocument | Mapping[str, Any]) -> dict[str, dict[str, Any]]: + """Split an exported schema into one document per namespace. -_SCHEMA_EXPORT_EXCLUDE: set[str] = {"hash", "hierarchy", "used_by", "id", "state"} -# branch is inherited from the node and need not be repeated on each field -_FIELD_EXPORT_EXCLUDE: set[str] = {"inherited", "allow_override", "hierarchical", "id", "state", "branch"} - -# Attribute field values that match schema loading defaults — omitted for cleaner output -_ATTR_EXPORT_DEFAULTS: dict[str, Any] = { - "read_only": False, - "optional": False, - "ordered": True, -} - -# Relationship field values that match schema loading defaults — omitted for cleaner output -_REL_EXPORT_DEFAULTS: dict[str, Any] = { - "direction": "bidirectional", - "on_delete": "no-action", - "cardinality": "many", - "optional": True, - "min_count": 0, - "max_count": 0, - "read_only": False, -} - -# Relationship kinds that Infrahub generates automatically — never user-defined -_AUTO_GENERATED_REL_KINDS: frozenset[str] = frozenset({"Group", "Profile", "Hierarchy"}) - - -def schema_to_export_dict(schema: NodeSchemaAPI | GenericSchemaAPI) -> dict[str, Any]: - """Convert an API schema object to an export-ready dict (omits API-internal fields).""" - data = schema.model_dump(exclude=_SCHEMA_EXPORT_EXCLUDE, exclude_none=True) - - # Pop attrs/rels so they can be re-inserted last for better readability - data.pop("attributes", None) - data.pop("relationships", None) - - # Generics with Hierarchy relationships were defined with `hierarchical: true`. - # Restore that flag and drop the auto-generated rels so the schema round-trips cleanly. - if isinstance(schema, GenericSchemaAPI) and any( - rel.kind == "Hierarchy" for rel in schema.relationships if not rel.inherited - ): - data["hierarchical"] = True - - # Strip uniqueness_constraints that are auto-generated from `unique: true` attributes - # (single-field entries of the form ["__value"]). User-defined multi-field - # constraints are preserved. - unique_attr_suffixes = {f"{attr.name}__value" for attr in schema.attributes if attr.unique} - user_constraints = [ - c - for c in (data.pop("uniqueness_constraints", None) or []) - if not (len(c) == 1 and c[0] in unique_attr_suffixes) - ] - if user_constraints: - data["uniqueness_constraints"] = user_constraints - - attributes = [ - { - k: v - for k, v in attr.model_dump(exclude=_FIELD_EXPORT_EXCLUDE, exclude_none=True).items() - if k not in _ATTR_EXPORT_DEFAULTS or v != _ATTR_EXPORT_DEFAULTS[k] - } - for attr in schema.attributes - if not attr.inherited - ] - if attributes: - data["attributes"] = attributes - - relationships = [ - { - k: v - for k, v in rel.model_dump(exclude=_FIELD_EXPORT_EXCLUDE, exclude_none=True).items() - if k not in _REL_EXPORT_DEFAULTS or v != _REL_EXPORT_DEFAULTS[k] - } - for rel in schema.relationships - if not rel.inherited and rel.kind not in _AUTO_GENERATED_REL_KINDS - ] - if relationships: - data["relationships"] = relationships - - return data + Namespaces keep the order of the input. Each document holds every other top-level field of the input, such as + `version` and `infrahub_version`, and holds `generics` or `nodes` only when its namespace has some. A mapping is + copied as it is, including fields this SDK version does not know; a `SchemaExportDocument` holds only the fields + the server set. The documents share the elements and the top-level values with the input instead of copying them. + """ + if isinstance(document, SchemaExportDocument): + document = document.model_dump(mode="json", exclude_unset=True) + shared = {key: value for key, value in document.items() if key not in EXPORT_ELEMENT_SECTIONS} + documents: dict[str, dict[str, Any]] = {} + for section, elements in document.items(): + if section not in EXPORT_ELEMENT_SECTIONS: + continue + for element in elements: + namespace_document = documents.setdefault(element["namespace"], dict(shared)) + namespace_document.setdefault(section, []).append(element) + return documents diff --git a/infrahub_sdk/schema/generated/contract.py b/infrahub_sdk/schema/generated/contract.py index 0d9facdb3..469abbcb3 100644 --- a/infrahub_sdk/schema/generated/contract.py +++ b/infrahub_sdk/schema/generated/contract.py @@ -1,12 +1,16 @@ # Generated by "invoke backend.generate", do not edit directly -"""Read-only fields of the write contract, keyed by generated write class name. +"""Field tables of the write contract, keyed by generated write class name. -A field listed here is one the contract knows at that location but the user may not set: -a field the read API returns, the bookkeeping a schema dumped from the internal models +`READ_ONLY_FIELDS` lists the fields the contract knows at that location but the user may not +set: a field the read API returns, the bookkeeping a schema dumped from the internal models carries, or a field belonging to a sibling variant of a discriminated union. Submitting one is reported as a warning and the value is dropped, where an extra field that is not listed -is an error. Each entry already includes what the class inherits, so a lookup is by class -name alone. +is an error. + +`KEEP_IN_EXPORT_FIELDS` lists the optional fields a schema export keeps unless they hold +their default. + +Each entry already includes what the class inherits, so a lookup is by class name alone. """ READ_ONLY_FIELDS: dict[str, frozenset[str]] = { @@ -34,3 +38,16 @@ "TextAttributeParametersWrite": frozenset({"id", "state"}), "TextAttributeWrite": frozenset({"inherited"}), } + +# Optional fields a schema export keeps unless they hold their default, keyed the same way: a +# shortened export without them fails validation. +KEEP_IN_EXPORT_FIELDS: dict[str, frozenset[str]] = { + "AttributeSchemaBaseWrite": frozenset({"choices", "read_only", "unique"}), + "GenericAttributeWrite": frozenset({"choices", "read_only", "unique"}), + "ListAttributeWrite": frozenset({"choices", "read_only", "unique"}), + "NodeSchemaWrite": frozenset({"inherit_from"}), + "NumberAttributeWrite": frozenset({"choices", "read_only", "unique"}), + "NumberPoolAttributeWrite": frozenset({"choices", "read_only", "unique"}), + "RelationshipSchemaWrite": frozenset({"cardinality", "identifier", "optional"}), + "TextAttributeWrite": frozenset({"choices", "read_only", "unique"}), +} diff --git a/infrahub_sdk/schema/generated/write.py b/infrahub_sdk/schema/generated/write.py index e741aa667..80b14e333 100644 --- a/infrahub_sdk/schema/generated/write.py +++ b/infrahub_sdk/schema/generated/write.py @@ -607,6 +607,7 @@ class SchemaExtensionWrite(BaseModel): class InfrahubSchemaWrite(BaseModel): model_config = ConfigDict(extra="ignore", use_enum_values=True) version: str + infrahub_version: str | None = None nodes: list[NodeSchemaWrite] = Field(default_factory=list) generics: list[GenericSchemaWrite] = Field(default_factory=list) extensions: SchemaExtensionWrite | None = None diff --git a/tests/fixtures/error_catalogue/public_names.json b/tests/fixtures/error_catalogue/public_names.json index ac5a2d102..47f5f32d5 100644 --- a/tests/fixtures/error_catalogue/public_names.json +++ b/tests/fixtures/error_catalogue/public_names.json @@ -34,6 +34,7 @@ "RateLimitError", "RepositoryFileNotFoundError", "ResourceNotDefinedError", + "SchemaNamespaceNotFoundError", "SchemaNotFoundError", "ServerNotReachableError", "ServerNotResponsiveError", diff --git a/tests/unit/ctl/schema/test_schema.py b/tests/unit/ctl/schema/test_schema.py index 771625d30..b4e10a361 100644 --- a/tests/unit/ctl/schema/test_schema.py +++ b/tests/unit/ctl/schema/test_schema.py @@ -2,12 +2,23 @@ from __future__ import annotations +from dataclasses import dataclass +from typing import TYPE_CHECKING, Any from unittest.mock import AsyncMock, MagicMock, patch +import pytest +import yaml from typer.testing import CliRunner from infrahub_sdk.ctl.cli_commands import app -from infrahub_sdk.schema import NodeSchemaAPI +from infrahub_sdk.ctl.schema_format import SCHEMA_HEADER, FormatError, format_schema_text +from infrahub_sdk.schema import SCHEMA_EXPORT_MIN_INFRAHUB_VERSION, NodeSchemaAPI +from tests.helpers.cli import remove_ansi_color + +if TYPE_CHECKING: + from pathlib import Path + + from pytest_httpx import HTTPXMock runner = CliRunner() @@ -325,3 +336,417 @@ def test_schema_show_attribute_with_default_value() -> None: assert result.exit_code == 0, result.stdout assert "1000" in result.stdout + + +# --------------------------------------------------------------------------- +# schema export tests +# --------------------------------------------------------------------------- + +EXPORT_URL = "http://mock/api/schema/export?branch=main&mode=BRIEF" + +EXPORT_RESPONSE: dict[str, Any] = { + "version": "1.0", + "infrahub_version": "1.13.0", + "generics": [ + { + "name": "Interface", + "namespace": "Network", + "attributes": [{"name": "name", "kind": "Text"}], + }, + ], + "nodes": [ + { + "name": "Device", + "namespace": "Network", + "inherit_from": [], + "attributes": [{"name": "name", "kind": "Text", "unique": True}], + "relationships": [{"name": "site", "peer": "LocationSite", "cardinality": "one", "optional": False}], + }, + {"name": "Site", "namespace": "Location", "attributes": [{"name": "name", "kind": "Text"}]}, + ], +} + + +def _read_yaml(path: Path) -> dict[str, Any]: + return yaml.safe_load(path.read_text(encoding="utf-8")) + + +def test_schema_export_writes_one_file_per_namespace(httpx_mock: HTTPXMock, tmp_path: Path) -> None: + httpx_mock.add_response(method="GET", url=EXPORT_URL, json=EXPORT_RESPONSE) + + result = runner.invoke(app, ["schema", "export", "--directory", str(tmp_path)]) + + assert result.exit_code == 0, result.stdout + assert sorted(path.name for path in tmp_path.iterdir()) == ["location.yml", "network.yml"] + + network = _read_yaml(tmp_path / "network.yml") + assert list(network) == ["version", "infrahub_version", "generics", "nodes"] + assert network == { + "version": "1.0", + "infrahub_version": "1.13.0", + "generics": EXPORT_RESPONSE["generics"], + "nodes": [EXPORT_RESPONSE["nodes"][0]], + } + assert _read_yaml(tmp_path / "location.yml") == { + "version": "1.0", + "infrahub_version": "1.13.0", + "nodes": [EXPORT_RESPONSE["nodes"][1]], + } + + +def test_schema_export_single_file_writes_the_endpoint_document(httpx_mock: HTTPXMock, tmp_path: Path) -> None: + httpx_mock.add_response(method="GET", url=EXPORT_URL, json=EXPORT_RESPONSE) + + result = runner.invoke(app, ["schema", "export", "--directory", str(tmp_path), "--single-file"]) + + assert result.exit_code == 0, result.stdout + assert [path.name for path in tmp_path.iterdir()] == ["schema.yml"] + schema = _read_yaml(tmp_path / "schema.yml") + assert list(schema) == ["version", "infrahub_version", "generics", "nodes"] + assert schema == EXPORT_RESPONSE + + +UNKNOWN_NODE = { + "name": "Rack", + "namespace": "Location", + "unknown_node_setting": "kept", + "attributes": [{"name": "name", "kind": "Text", "unknown_attribute_setting": True}], + "relationships": [{"name": "site", "peer": "LocationSite", "unknown_relationship_setting": 1}], +} + +EXPORT_RESPONSE_WITH_UNKNOWN_FIELDS: dict[str, Any] = { + **EXPORT_RESPONSE, + "unknown_document_setting": "kept", + "nodes": [*EXPORT_RESPONSE["nodes"], UNKNOWN_NODE], +} + + +def test_schema_export_single_file_keeps_fields_this_sdk_does_not_know(httpx_mock: HTTPXMock, tmp_path: Path) -> None: + httpx_mock.add_response(method="GET", url=EXPORT_URL, json=EXPORT_RESPONSE_WITH_UNKNOWN_FIELDS) + + result = runner.invoke(app, ["schema", "export", "--directory", str(tmp_path), "--single-file"]) + + assert result.exit_code == 0, result.stdout + assert _read_yaml(tmp_path / "schema.yml") == EXPORT_RESPONSE_WITH_UNKNOWN_FIELDS + + +def test_schema_export_per_namespace_keeps_fields_this_sdk_does_not_know(httpx_mock: HTTPXMock, tmp_path: Path) -> None: + httpx_mock.add_response(method="GET", url=EXPORT_URL, json=EXPORT_RESPONSE_WITH_UNKNOWN_FIELDS) + + result = runner.invoke(app, ["schema", "export", "--directory", str(tmp_path)]) + + assert result.exit_code == 0, result.stdout + location = _read_yaml(tmp_path / "location.yml") + assert list(location) == ["version", "infrahub_version", "nodes", "unknown_document_setting"] + assert location == { + "version": "1.0", + "infrahub_version": "1.13.0", + "nodes": [EXPORT_RESPONSE["nodes"][1], UNKNOWN_NODE], + "unknown_document_setting": "kept", + } + assert _read_yaml(tmp_path / "network.yml")["unknown_document_setting"] == "kept" + + +def test_schema_export_writes_no_default_for_a_field_the_response_left_out( + httpx_mock: HTTPXMock, tmp_path: Path +) -> None: + httpx_mock.add_response(method="GET", url=EXPORT_URL, json=EXPORT_RESPONSE) + + result = runner.invoke(app, ["schema", "export", "--directory", str(tmp_path), "--single-file"]) + + assert result.exit_code == 0, result.stdout + site = _read_yaml(tmp_path / "schema.yml")["nodes"][1] + # These fields have defaults in the schema model, so they would appear if the CLI wrote every field. + for field in ("label", "branch", "state", "generate_profile", "relationships", "inherit_from"): + assert field not in site + assert site["attributes"] == [{"name": "name", "kind": "Text"}] + + +def test_schema_export_sends_mode_and_namespaces(httpx_mock: HTTPXMock, tmp_path: Path) -> None: + httpx_mock.add_response( + method="GET", + url="http://mock/api/schema/export?branch=main&namespaces=Network&namespaces=Location&mode=FULL", + json=EXPORT_RESPONSE, + ) + + result = runner.invoke( + app, + [ + "schema", + "export", + "--directory", + str(tmp_path), + "--mode", + "FULL", + "--namespaces", + "Network", + "--namespaces", + "Location", + ], + ) + + assert result.exit_code == 0, result.stdout + assert len(httpx_mock.get_requests()) == 1 + + +LONG_TEMPLATE = ( + "https://example.com/{{ name__value|lower }}-{{ profession__name__value|upper }}/{{ race__name__value }}/" * 50 +) +"""A value longer than the 4096 characters at which the YAML writers of the CLI used to split a line.""" + + +def test_schema_export_writes_each_long_value_on_one_line(httpx_mock: HTTPXMock, tmp_path: Path) -> None: + site = { + "name": "Site", + "namespace": "Location", + "attributes": [ + { + "name": "url", + "kind": "URL", + "read_only": True, + "computed_attribute": {"kind": "Jinja2", "jinja2_template": LONG_TEMPLATE}, + } + ], + } + httpx_mock.add_response(method="GET", url=EXPORT_URL, json={**EXPORT_RESPONSE, "nodes": [site]}) + + result = runner.invoke(app, ["schema", "export", "--directory", str(tmp_path), "--single-file"]) + + assert result.exit_code == 0, result.stdout + lines = [line.strip() for line in (tmp_path / "schema.yml").read_text(encoding="utf-8").splitlines()] + assert f"jinja2_template: {LONG_TEMPLATE}" in lines + assert _read_yaml(tmp_path / "schema.yml")["nodes"] == [site] + + +UNORDERED_EXPORT_RESPONSE: dict[str, Any] = { + "nodes": [ + { + "relationships": [{"optional": False, "cardinality": "one", "peer": "LocationSite", "name": "site"}], + "attributes": [{"unique": True, "kind": "Text", "name": "name"}], + "namespace": "Network", + "name": "Device", + }, + ], + "infrahub_version": "1.13.0", + "version": "1.0", +} + + +def test_schema_export_writes_files_that_schema_format_leaves_unchanged(httpx_mock: HTTPXMock, tmp_path: Path) -> None: + httpx_mock.add_response(method="GET", url=EXPORT_URL, json=UNORDERED_EXPORT_RESPONSE) + + result = runner.invoke(app, ["schema", "export", "--directory", str(tmp_path)]) + + assert result.exit_code == 0, result.stdout + text = (tmp_path / "network.yml").read_text(encoding="utf-8") + assert text.startswith(SCHEMA_HEADER) + assert format_schema_text(text) == text + network = yaml.safe_load(text) + assert list(network) == ["version", "infrahub_version", "nodes"] + assert list(network["nodes"][0]) == ["name", "namespace", "attributes", "relationships"] + assert list(network["nodes"][0]["attributes"][0]) == ["name", "kind", "unique"] + assert list(network["nodes"][0]["relationships"][0]) == ["name", "peer", "cardinality", "optional"] + assert network == UNORDERED_EXPORT_RESPONSE + + +def test_schema_export_writes_lists_without_mappings_inline(httpx_mock: HTTPXMock, tmp_path: Path) -> None: + device = { + "name": "Device", + "namespace": "Network", + "inherit_from": ["NetworkEndpoint"], + "human_friendly_id": ["name__value"], + "uniqueness_constraints": [["site", "name__value"]], + "attributes": [{"name": "name", "kind": "Text"}], + } + httpx_mock.add_response(method="GET", url=EXPORT_URL, json={**EXPORT_RESPONSE, "generics": [], "nodes": [device]}) + + result = runner.invoke(app, ["schema", "export", "--directory", str(tmp_path), "--single-file"]) + + assert result.exit_code == 0, result.stdout + lines = [line.strip() for line in (tmp_path / "schema.yml").read_text(encoding="utf-8").splitlines()] + assert "inherit_from: [NetworkEndpoint]" in lines + assert "human_friendly_id: [name__value]" in lines + assert "uniqueness_constraints: [[site, name__value]]" in lines + assert "- name: name" in lines + assert _read_yaml(tmp_path / "schema.yml")["nodes"] == [device] + + +def test_schema_export_writes_no_file_when_a_file_cannot_be_formatted( + httpx_mock: HTTPXMock, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + httpx_mock.add_response(method="GET", url=EXPORT_URL, json=EXPORT_RESPONSE) + + def format_all_but_network(text: str) -> str: + if "namespace: Network" in text: + raise FormatError("Formatting would change the schema content; aborting to avoid data loss.") + return format_schema_text(text) + + monkeypatch.setattr("infrahub_sdk.ctl.schema.format_schema_text", format_all_but_network) + directory = tmp_path / "export" + + result = runner.invoke(app, ["schema", "export", "--directory", str(directory)]) + + assert result.exit_code == 1 + assert "Error: Formatting would change the schema content; aborting to avoid data loss." in result.stdout + assert not directory.exists() + + +def test_schema_export_reports_a_body_that_is_not_json(httpx_mock: HTTPXMock, tmp_path: Path) -> None: + httpx_mock.add_response(method="GET", url=EXPORT_URL, text="proxy page") + directory = tmp_path / "export" + + result = runner.invoke(app, ["schema", "export", "--directory", str(directory)]) + + assert result.exit_code == 1 + assert "Error: Invalid schema export response received from the server" in result.stdout + assert not directory.exists() + + +def test_schema_export_empty_document(httpx_mock: HTTPXMock, tmp_path: Path) -> None: + httpx_mock.add_response( + method="GET", + url=EXPORT_URL, + json={"version": "1.0", "infrahub_version": "1.13.0", "generics": [], "nodes": []}, + ) + directory = tmp_path / "export" + + result = runner.invoke(app, ["schema", "export", "--directory", str(directory)]) + + assert result.exit_code == 0, result.stdout + assert "No user-defined schema found to export." in result.stdout + assert not directory.exists() + + +@dataclass +class ExportErrorCase: + name: str + status_code: int + message: str + expected_output: str + + +EXPORT_ERROR_CASES = [ + ExportErrorCase( + name="older-server", + status_code=422, + message="Unable to find the schema 'export' in the registry", + expected_output=f"Infrahub {SCHEMA_EXPORT_MIN_INFRAHUB_VERSION} or later", + ), + ExportErrorCase( + name="422-other-kind", + status_code=422, + message="Unable to find the schema 'NetworkDevice' in the registry", + expected_output="HTTP 422: Unable to find the schema 'NetworkDevice' in the registry", + ), + ExportErrorCase( + name="500", + status_code=500, + message="Internal server error", + expected_output="HTTP 500: Internal server error", + ), +] + + +@pytest.mark.parametrize("case", [pytest.param(case, id=case.name) for case in EXPORT_ERROR_CASES]) +def test_schema_export_error_response(httpx_mock: HTTPXMock, tmp_path: Path, case: ExportErrorCase) -> None: + httpx_mock.add_response( + method="GET", + url=EXPORT_URL, + status_code=case.status_code, + json={"data": None, "errors": [{"message": case.message, "extensions": {"code": case.status_code}}]}, + ) + directory = tmp_path / "export" + + result = runner.invoke(app, ["schema", "export", "--directory", str(directory)]) + + assert result.exit_code == 1 + output = remove_ansi_color(result.stdout.replace("\n", "")) + assert case.expected_output in output + if case.name != "older-server": + assert SCHEMA_EXPORT_MIN_INFRAHUB_VERSION not in output + assert not directory.exists() + + +NAMESPACE_EXPORT_URL = "http://mock/api/schema/export?branch=main&namespaces=Locaton&namespaces=Core&mode=BRIEF" + + +def test_schema_export_prints_each_namespace_the_server_cannot_export(httpx_mock: HTTPXMock, tmp_path: Path) -> None: + httpx_mock.add_response( + method="GET", + url=NAMESPACE_EXPORT_URL, + status_code=404, + json={ + "data": None, + "errors": [ + { + "message": "The namespace 'Locaton' does not exist on the branch 'main'", + "extensions": {"namespace": "Locaton", "code": 404}, + }, + { + "message": "The namespace 'Core' is reserved for Infrahub and cannot be exported", + "extensions": {"namespace": "Core", "code": 404}, + }, + ], + }, + ) + directory = tmp_path / "export" + + result = runner.invoke( + app, + ["schema", "export", "--directory", str(directory), "--namespaces", "Locaton", "--namespaces", "Core"], + ) + + assert result.exit_code == 1 + assert remove_ansi_color(result.stdout).splitlines() == [ + "Error: The namespace 'Locaton' does not exist on the branch 'main'", + "Error: The namespace 'Core' is reserved for Infrahub and cannot be exported", + ] + assert not directory.exists() + + +def test_schema_export_reports_a_404_that_names_no_namespace_as_an_unknown_url( + httpx_mock: HTTPXMock, tmp_path: Path +) -> None: + httpx_mock.add_response( + method="GET", + url=EXPORT_URL, + status_code=404, + json={ + "data": None, + "errors": [ + {"message": "The requested endpoint /api/schema/export does not exist", "extensions": {"code": 404}} + ], + }, + ) + directory = tmp_path / "export" + + result = runner.invoke(app, ["schema", "export", "--directory", str(directory)]) + + assert result.exit_code == 1 + assert remove_ansi_color(result.stdout.replace("\n", "")) == f"Error: `{EXPORT_URL}` not found." + assert not directory.exists() + + +def test_schema_export_reports_a_401_as_an_authentication_failure(httpx_mock: HTTPXMock, tmp_path: Path) -> None: + httpx_mock.add_response( + method="GET", + url=EXPORT_URL, + status_code=401, + json={"data": None, "errors": [{"message": "Authentication is required", "extensions": {"code": 401}}]}, + ) + + result = runner.invoke(app, ["schema", "export", "--directory", str(tmp_path / "export")]) + + assert result.exit_code == 1 + assert remove_ansi_color(result.stdout.replace("\n", "")) == "Authentication failure: Authentication is required" + + +def test_schema_export_prints_a_directory_name_with_brackets(httpx_mock: HTTPXMock, tmp_path: Path) -> None: + httpx_mock.add_response(method="GET", url=EXPORT_URL, json=EXPORT_RESPONSE) + directory = tmp_path / "a[/b]" + + result = runner.invoke(app, ["schema", "export", "--directory", str(directory), "--single-file"]) + + assert result.exit_code == 0, result.stdout + assert remove_ansi_color(result.stdout).splitlines()[-1] == f" Schema exported to {directory}" + assert (directory / "schema.yml").exists() diff --git a/tests/unit/ctl/test_schema_format.py b/tests/unit/ctl/test_schema_format.py index b76cb725c..6e4f9555a 100644 --- a/tests/unit/ctl/test_schema_format.py +++ b/tests/unit/ctl/test_schema_format.py @@ -72,6 +72,23 @@ def test_node_key_order_is_canonical() -> None: ] +def test_value_longer_than_4096_characters_stays_on_one_line() -> None: + template = "{{ name__value }}-" * 300 + raw = f'version: "1.0"\nnodes:\n - namespace: Dcim\n name: Device\n display_label: "{template}"\n' + + text = format_schema_text(raw) + + assert f'display_label: "{template}"' in [line.strip() for line in text.splitlines()] + + +def test_infrahub_version_follows_version() -> None: + raw = 'nodes:\n - name: Device\n namespace: Dcim\ninfrahub_version: "1.13.0"\nversion: "1.0"\n' + + text = format_schema_text(raw) + + assert _keys_of(text, []) == ["version", "infrahub_version", "nodes"] + + def test_attribute_relationship_and_choice_inner_order() -> None: text = format_schema_text(NODE_DOC) diff --git a/tests/unit/sdk/test_schema.py b/tests/unit/sdk/test_schema.py index c10a139fd..e3bf464fc 100644 --- a/tests/unit/sdk/test_schema.py +++ b/tests/unit/sdk/test_schema.py @@ -13,7 +13,14 @@ from infrahub_sdk.ctl.schema import display_schema_load_errors, valid_error_path from infrahub_sdk.exceptions import SchemaNotFoundError, ValidationError from infrahub_sdk.protocols import BuiltinIPAddress, BuiltinIPAddressSync, BuiltinTag, BuiltinTagSync -from infrahub_sdk.schema import BranchSchema, InfrahubSchema, InfrahubSchemaBase, InfrahubSchemaSync, NodeSchemaAPI +from infrahub_sdk.schema import ( + BranchSchema, + InfrahubSchema, + InfrahubSchemaBase, + InfrahubSchemaSync, + NodeSchemaAPI, + validate_schema, +) from infrahub_sdk.schema.repository import ( InfrahubCheckDefinitionConfig, InfrahubJinja2TransformConfig, @@ -567,3 +574,17 @@ async def test_schema_load_surfaces_api_error_on_422(client: InfrahubClient, htt assert response.errors assert response.errors["errors"][0]["message"] == api_error_message assert not response.schema_updated + + +def test_validate_schema_accepts_infrahub_version() -> None: + schema = { + "version": "1.0", + "infrahub_version": "1.0.0", + "nodes": [{"name": "Device", "namespace": "Infra", "attributes": [{"name": "hostname", "kind": "Text"}]}], + } + + result = validate_schema(schema=schema) + + assert result.valid is True + assert result.errors == [] + assert result.warnings == [] diff --git a/tests/unit/sdk/test_schema_export.py b/tests/unit/sdk/test_schema_export.py index e579168c6..fced7068f 100644 --- a/tests/unit/sdk/test_schema_export.py +++ b/tests/unit/sdk/test_schema_export.py @@ -1,289 +1,408 @@ from __future__ import annotations -import warnings +import copy +import pickle # noqa: S403 - round-tripping our own exception, no untrusted data involved +import re +from dataclasses import dataclass from typing import TYPE_CHECKING, Any import pytest +from infrahub_sdk.exceptions import ( + ApiError, + AuthenticationError, + BranchNotFoundError, + InvalidResponseError, + JsonDecodeError, + SchemaNamespaceNotFoundError, + URLNotFoundError, + VersionNotSupportedError, +) from infrahub_sdk.schema import ( - GenericSchemaAPI, - InfrahubSchemaBase, - NodeSchemaAPI, - ProfileSchemaAPI, - SchemaExport, - TemplateSchemaAPI, + SCHEMA_EXPORT_MIN_INFRAHUB_VERSION, + SchemaExportDocument, + SchemaExportMode, + split_by_namespace, ) -from infrahub_sdk.schema.export import schema_to_export_dict if TYPE_CHECKING: + from collections.abc import Callable + from pytest_httpx import HTTPXMock from tests.unit.sdk.conftest import BothClients client_types = ["standard", "sync"] -# --------------------------------------------------------------------------- -# Minimal schema API response builders (reused from ctl tests) -# --------------------------------------------------------------------------- - -_BASE_NODE: dict[str, Any] = { - "id": None, - "state": "present", - "hash": None, - "hierarchy": None, - "label": None, - "description": None, - "include_in_menu": None, - "menu_placement": None, - "display_label": None, - "display_labels": None, - "human_friendly_id": None, - "icon": None, - "uniqueness_constraints": None, - "documentation": None, - "order_by": None, - "inherit_from": [], - "branch": "aware", - "default_filter": None, - "generate_profile": True, - "generate_template": False, - "parent": None, - "children": None, - "attributes": [], - "relationships": [], +EXPORT_RESPONSE: dict[str, Any] = { + "version": "1.0", + "infrahub_version": "1.13.0", + "generics": [ + { + "name": "Interface", + "namespace": "Network", + "human_friendly_id": ["device__name__value", "name__value"], + "attributes": [{"name": "name", "kind": "Text"}], + "relationships": [ + { + "name": "device", + "peer": "NetworkDevice", + "cardinality": "one", + "optional": False, + "kind": "Attribute", + } + ], + }, + ], + "nodes": [ + { + "name": "Device", + "namespace": "Network", + "attributes": [{"name": "name", "kind": "Text", "unique": True}], + }, + {"name": "Site", "namespace": "Location", "attributes": [{"name": "name", "kind": "Text"}]}, + { + "name": "PhysicalInterface", + "namespace": "Network", + "inherit_from": ["NetworkInterface"], + "attributes": [{"name": "speed", "kind": "Number"}], + }, + ], } -_BASE_GENERIC: dict[str, Any] = { - "id": None, - "state": "present", - "hash": None, - "used_by": [], - "label": None, - "description": None, - "include_in_menu": None, - "menu_placement": None, - "display_label": None, - "display_labels": None, - "human_friendly_id": None, - "icon": None, - "uniqueness_constraints": None, - "documentation": None, - "order_by": None, - "attributes": [], - "relationships": [], +OLDER_SERVER_RESPONSE: dict[str, Any] = { + "data": None, + "errors": [{"message": "Unable to find the schema 'export' in the registry", "extensions": {"code": 422}}], } -def _make_node_schema(namespace: str, name: str) -> NodeSchemaAPI: - return NodeSchemaAPI(**{**_BASE_NODE, "namespace": namespace, "name": name}) +async def _export( + clients: BothClients, + client_type: str, + branch: str, + namespaces: list[str] | None = None, + mode: SchemaExportMode = SchemaExportMode.BRIEF, +) -> SchemaExportDocument: + if client_type == "standard": + return await clients.standard.schema.export(branch=branch, namespaces=namespaces, mode=mode) + return clients.sync.schema.export(branch=branch, namespaces=namespaces, mode=mode) + + +@pytest.mark.parametrize("client_type", client_types) +async def test_export_returns_the_endpoint_document( + httpx_mock: HTTPXMock, clients: BothClients, client_type: str +) -> None: + httpx_mock.add_response( + method="GET", url="http://mock/api/schema/export?branch=main&mode=BRIEF", json=EXPORT_RESPONSE + ) + + document = await _export(clients, client_type, branch="main") + assert isinstance(document, SchemaExportDocument) + assert document.model_dump(mode="json", exclude_unset=True) == EXPORT_RESPONSE -def _make_generic_schema(namespace: str, name: str) -> GenericSchemaAPI: - return GenericSchemaAPI(**{**_BASE_GENERIC, "namespace": namespace, "name": name}) +@pytest.mark.parametrize("client_type", client_types) +async def test_export_sends_branch_namespaces_and_mode( + httpx_mock: HTTPXMock, clients: BothClients, client_type: str +) -> None: + httpx_mock.add_response( + method="GET", + url="http://mock/api/schema/export?branch=feature&namespaces=Network&namespaces=Location&mode=FULL", + json=EXPORT_RESPONSE, + ) -def _make_profile_schema(namespace: str, name: str) -> ProfileSchemaAPI: - return ProfileSchemaAPI( - **{ - **_BASE_NODE, - "namespace": namespace, - "name": name, - } + document = await _export( + clients, client_type, branch="feature", namespaces=["Network", "Location"], mode=SchemaExportMode.FULL ) + assert document.infrahub_version == "1.13.0" + + +def test_split_by_namespace_keeps_versions_and_input_order() -> None: + documents = split_by_namespace(EXPORT_RESPONSE) + + assert list(documents) == ["Network", "Location"] + assert documents["Network"] == { + "version": "1.0", + "infrahub_version": "1.13.0", + "generics": EXPORT_RESPONSE["generics"], + "nodes": [EXPORT_RESPONSE["nodes"][0], EXPORT_RESPONSE["nodes"][2]], + } + assert documents["Location"] == { + "version": "1.0", + "infrahub_version": "1.13.0", + "nodes": [EXPORT_RESPONSE["nodes"][1]], + } + + +def test_split_by_namespace_keeps_the_namespace_order_when_nodes_come_before_generics() -> None: + document = { + "version": "1.0", + "nodes": [{"name": "Site", "namespace": "Location"}], + "generics": [{"name": "Interface", "namespace": "Network"}], + } + + documents = split_by_namespace(document) + + assert list(documents) == ["Location", "Network"] + + +def test_split_by_namespace_copies_every_other_top_level_field() -> None: + documents = split_by_namespace({**EXPORT_RESPONSE, "unknown_document_setting": "kept"}) + + assert [namespace_document["unknown_document_setting"] for namespace_document in documents.values()] == [ + "kept", + "kept", + ] -def _make_template_schema(namespace: str, name: str) -> TemplateSchemaAPI: - return TemplateSchemaAPI( - **{ - **_BASE_NODE, - "namespace": namespace, - "name": name, - } + +@pytest.mark.parametrize("client_type", client_types) +async def test_export_names_the_release_on_an_older_server( + httpx_mock: HTTPXMock, clients: BothClients, client_type: str +) -> None: + httpx_mock.add_response( + method="GET", + url="http://mock/api/schema/export?branch=main&mode=BRIEF", + status_code=422, + json=OLDER_SERVER_RESPONSE, ) + with pytest.raises(VersionNotSupportedError, match=re.escape(f"Infrahub {SCHEMA_EXPORT_MIN_INFRAHUB_VERSION}")): + await _export(clients, client_type, branch="main") -# --------------------------------------------------------------------------- -# _build_export_schemas tests -# --------------------------------------------------------------------------- - - -class TestBuildExportSchemas: - def test_separates_nodes_and_generics(self) -> None: - schema_nodes = { - "InfraDevice": _make_node_schema("Infra", "Device"), - "InfraInterface": _make_generic_schema("Infra", "Interface"), - } - result = InfrahubSchemaBase._build_export_schemas(schema_nodes) - assert isinstance(result, SchemaExport) - assert "Infra" in result.namespaces - assert len(result.namespaces["Infra"].nodes) == 1 - assert len(result.namespaces["Infra"].generics) == 1 - assert result.namespaces["Infra"].nodes[0]["name"] == "Device" - assert result.namespaces["Infra"].generics[0]["name"] == "Interface" - - def test_groups_by_namespace(self) -> None: - schema_nodes = { - "InfraDevice": _make_node_schema("Infra", "Device"), - "DcimRack": _make_node_schema("Dcim", "Rack"), - } - result = InfrahubSchemaBase._build_export_schemas(schema_nodes) - assert set(result.namespaces.keys()) == {"Infra", "Dcim"} - - def test_filters_profiles_and_templates(self) -> None: - schema_nodes = { - "InfraDevice": _make_node_schema("Infra", "Device"), - "ProfileInfraDevice": _make_profile_schema("Profile", "InfraDevice"), - "TemplateInfraDevice": _make_template_schema("Template", "InfraDevice"), - } - result = InfrahubSchemaBase._build_export_schemas(schema_nodes) - assert "Infra" in result.namespaces - assert "Profile" not in result.namespaces - assert "Template" not in result.namespaces - - def test_filters_restricted_namespaces(self) -> None: - schema_nodes = { - "CoreRepository": _make_node_schema("Core", "Repository"), - "BuiltinTag": _make_node_schema("Builtin", "Tag"), - "InfraDevice": _make_node_schema("Infra", "Device"), - } - result = InfrahubSchemaBase._build_export_schemas(schema_nodes) - assert "Core" not in result.namespaces - assert "Builtin" not in result.namespaces - assert "Infra" in result.namespaces - - def test_namespace_filter(self) -> None: - schema_nodes = { - "InfraDevice": _make_node_schema("Infra", "Device"), - "DcimRack": _make_node_schema("Dcim", "Rack"), - } - result = InfrahubSchemaBase._build_export_schemas(schema_nodes, namespaces=["Infra"]) - assert "Infra" in result.namespaces - assert "Dcim" not in result.namespaces - - def test_empty_when_no_user_schemas(self) -> None: - schema_nodes = { - "CoreRepository": _make_node_schema("Core", "Repository"), - } - result = InfrahubSchemaBase._build_export_schemas(schema_nodes) - assert result.namespaces == {} - - def test_warns_on_restricted_namespaces(self) -> None: - schema_nodes = { - "InfraDevice": _make_node_schema("Infra", "Device"), - } - with warnings.catch_warnings(record=True) as w: - warnings.simplefilter("always") - result = InfrahubSchemaBase._build_export_schemas(schema_nodes, namespaces=["Infra", "Core"]) - assert len(w) == 1 - assert "Core" in str(w[0].message) - assert "Infra" in result.namespaces - - def test_to_dict(self) -> None: - schema_nodes = { - "InfraDevice": _make_node_schema("Infra", "Device"), - "InfraInterface": _make_generic_schema("Infra", "Interface"), - } - result = InfrahubSchemaBase._build_export_schemas(schema_nodes) - as_dict = result.to_dict() - assert isinstance(as_dict, dict) - assert "Infra" in as_dict - assert isinstance(as_dict["Infra"], dict) - assert len(as_dict["Infra"]["nodes"]) == 1 - assert len(as_dict["Infra"]["generics"]) == 1 - - -def test_export_preserves_non_default_ordered_flag() -> None: - """`ordered: false` survives the fetch -> export round-trip; the default `true` is omitted.""" - node = NodeSchemaAPI( - **{ - **_BASE_NODE, - "namespace": "Infra", - "name": "Device", - "attributes": [ - {"name": "tags_unordered", "kind": "List", "ordered": False}, - {"name": "tags_ordered", "kind": "List"}, - ], - } + +@dataclass +class ErrorResponseCase: + name: str + status_code: int + message: str + + +ERROR_RESPONSE_CASES = [ + ErrorResponseCase( + name="422-other-kind", status_code=422, message="Unable to find the schema 'NetworkDevice' in the registry" + ), + ErrorResponseCase( + name="422-other-message", status_code=422, message="Unable to find the schema export in the database." + ), + ErrorResponseCase(name="500", status_code=500, message="Internal server error"), +] + + +@pytest.mark.parametrize("client_type", client_types) +@pytest.mark.parametrize("case", [pytest.param(case, id=case.name) for case in ERROR_RESPONSE_CASES]) +async def test_export_reports_other_errors_as_returned( + httpx_mock: HTTPXMock, clients: BothClients, client_type: str, case: ErrorResponseCase +) -> None: + httpx_mock.add_response( + method="GET", + url="http://mock/api/schema/export?branch=main&mode=BRIEF", + status_code=case.status_code, + json={"data": None, "errors": [{"message": case.message, "extensions": {"code": case.status_code}}]}, ) - exported = schema_to_export_dict(node) - attrs = {attr["name"]: attr for attr in exported["attributes"]} - assert attrs["tags_unordered"]["ordered"] is False - assert "ordered" not in attrs["tags_ordered"] - - -# --------------------------------------------------------------------------- -# Integration tests for export() method on client.schema -# --------------------------------------------------------------------------- - - -def _schema_response( - nodes: list[dict] | None = None, - generics: list[dict] | None = None, - profiles: list[dict] | None = None, - templates: list[dict] | None = None, -) -> dict: - return { - "main": "aabbccdd", - "nodes": nodes or [], - "generics": generics or [], - "profiles": profiles or [], - "templates": templates or [], - } + with pytest.raises(ApiError, match=re.escape(f"HTTP {case.status_code}: {case.message}")) as exc_info: + await _export(clients, client_type, branch="main") -def _make_node_dict(namespace: str, name: str) -> dict[str, Any]: - return {**_BASE_NODE, "namespace": namespace, "name": name} + assert not isinstance(exc_info.value, VersionNotSupportedError) + assert SCHEMA_EXPORT_MIN_INFRAHUB_VERSION not in str(exc_info.value) + assert exc_info.value.http_status == case.status_code -def _make_generic_dict(namespace: str, name: str) -> dict[str, Any]: - return {**_BASE_GENERIC, "namespace": namespace, "name": name} +NAMESPACE_EXPORT_URL = "http://mock/api/schema/export?branch=main&namespaces=Locaton&namespaces=Core&mode=BRIEF" +LOCATON_ERROR = { + "message": "The namespace 'Locaton' does not exist on the branch 'main'", + "extensions": {"namespace": "Locaton", "code": 404}, +} +CORE_ERROR = { + "message": "The namespace 'Core' is reserved for Infrahub and cannot be exported", + "extensions": {"namespace": "Core", "code": 404}, +} +UNKNOWN_ENDPOINT_ERROR = { + "message": "The requested endpoint /api/schema/export does not exist", + "extensions": {"code": 404}, +} @pytest.mark.parametrize("client_type", client_types) -async def test_export_returns_user_schemas(httpx_mock: HTTPXMock, clients: BothClients, client_type: str) -> None: - response = _schema_response( - nodes=[_make_node_dict("Infra", "Device"), _make_node_dict("Dcim", "Rack")], - generics=[_make_generic_dict("Infra", "GenericInterface")], +async def test_export_names_each_namespace_the_server_cannot_export( + httpx_mock: HTTPXMock, clients: BothClients, client_type: str +) -> None: + httpx_mock.add_response( + method="GET", + url=NAMESPACE_EXPORT_URL, + status_code=404, + json={"data": None, "errors": [LOCATON_ERROR, CORE_ERROR]}, ) - httpx_mock.add_response(method="GET", url="http://mock/api/schema?branch=main", json=response) - if client_type == "standard": - result = await clients.standard.schema.export(branch="main") - else: - result = clients.sync.schema.export(branch="main") + with pytest.raises( + SchemaNamespaceNotFoundError, + match=( + r"^The namespace 'Locaton' does not exist on the branch 'main'; " + r"The namespace 'Core' is reserved for Infrahub and cannot be exported$" + ), + ) as exc_info: + await _export(clients, client_type, branch="main", namespaces=["Locaton", "Core"]) + + assert exc_info.value.namespaces == ["Locaton", "Core"] + assert exc_info.value.messages == [LOCATON_ERROR["message"], CORE_ERROR["message"]] + assert exc_info.value.http_status == 404 + + +@dataclass +class NotFoundCase: + name: str + body: dict[str, Any] + - assert isinstance(result, SchemaExport) - assert "Infra" in result.namespaces - assert "Dcim" in result.namespaces - assert len(result.namespaces["Infra"].nodes) == 1 - assert len(result.namespaces["Infra"].generics) == 1 - assert len(result.namespaces["Dcim"].nodes) == 1 +NOT_FOUND_CASES = [ + NotFoundCase(name="fastapi-default", body={"detail": "Not Found"}), + NotFoundCase(name="infrahub-unknown-endpoint", body={"data": None, "errors": [UNKNOWN_ENDPOINT_ERROR]}), + NotFoundCase( + name="one-error-without-namespace", body={"data": None, "errors": [LOCATON_ERROR, UNKNOWN_ENDPOINT_ERROR]} + ), +] @pytest.mark.parametrize("client_type", client_types) -async def test_export_with_namespace_filter(httpx_mock: HTTPXMock, clients: BothClients, client_type: str) -> None: - response = _schema_response( - nodes=[_make_node_dict("Infra", "Device")], +@pytest.mark.parametrize("case", [pytest.param(case, id=case.name) for case in NOT_FOUND_CASES]) +async def test_export_reports_a_404_that_names_no_namespace_as_an_unknown_url( + httpx_mock: HTTPXMock, clients: BothClients, client_type: str, case: NotFoundCase +) -> None: + httpx_mock.add_response(method="GET", url=NAMESPACE_EXPORT_URL, status_code=404, json=case.body) + + with pytest.raises(URLNotFoundError, match=f"^`{re.escape(NAMESPACE_EXPORT_URL)}` not found.$"): + await _export(clients, client_type, branch="main", namespaces=["Locaton", "Core"]) + + +@pytest.mark.parametrize("client_type", client_types) +async def test_export_names_a_namespace_whose_error_has_no_message( + httpx_mock: HTTPXMock, clients: BothClients, client_type: str +) -> None: + httpx_mock.add_response( + method="GET", + url=NAMESPACE_EXPORT_URL, + status_code=404, + json={"data": None, "errors": [{"message": None, "extensions": {"namespace": "Locaton", "code": 404}}]}, ) - httpx_mock.add_response(method="GET", url="http://mock/api/schema?branch=main&namespaces=Infra", json=response) - if client_type == "standard": - result = await clients.standard.schema.export(branch="main", namespaces=["Infra"]) - else: - result = clients.sync.schema.export(branch="main", namespaces=["Infra"]) + with pytest.raises(SchemaNamespaceNotFoundError, match=r"^The namespace 'Locaton' cannot be exported$"): + await _export(clients, client_type, branch="main", namespaces=["Locaton", "Core"]) + + +@pytest.mark.parametrize("client_type", client_types) +async def test_export_of_an_unknown_branch_raises_branch_not_found( + httpx_mock: HTTPXMock, clients: BothClients, client_type: str +) -> None: + httpx_mock.add_response( + method="GET", + url="http://mock/api/schema/export?branch=nope&mode=BRIEF", + status_code=400, + json={"data": None, "errors": [{"message": "Branch: nope not found.", "extensions": {"code": 400}}]}, + ) + + with pytest.raises(BranchNotFoundError, match=r"^The requested branch was not found on the server \[nope\]$"): + await _export(clients, client_type, branch="nope") + + +@pytest.mark.parametrize("client_type", client_types) +async def test_export_with_a_value_the_sdk_cannot_read_raises_invalid_response( + httpx_mock: HTTPXMock, clients: BothClients, client_type: str +) -> None: + response = { + **EXPORT_RESPONSE, + "generics": [], + "nodes": [{"name": "Device", "namespace": "Network", "attributes": [{"name": "size", "kind": "Decimal"}]}], + } + httpx_mock.add_response(method="GET", url="http://mock/api/schema/export?branch=main&mode=BRIEF", json=response) + + with pytest.raises( + InvalidResponseError, + match=r"^The schema export from http://mock/api/schema/export\?branch=main&mode=BRIEF holds a value this " + r"version of the SDK cannot read; use an SDK version that matches the Infrahub server\. ", + ): + await _export(clients, client_type, branch="main") + + +@pytest.mark.parametrize("client_type", client_types) +async def test_export_with_a_body_that_is_not_json_raises_json_decode_error( + httpx_mock: HTTPXMock, clients: BothClients, client_type: str +) -> None: + httpx_mock.add_response( + method="GET", url="http://mock/api/schema/export?branch=main&mode=BRIEF", text="proxy page" + ) + + with pytest.raises( + JsonDecodeError, + match=r"^Invalid schema export response received from the server at " + r"http://mock/api/schema/export\?branch=main&mode=BRIEF: proxy page \[200\]$", + ): + await _export(clients, client_type, branch="main") + + +@pytest.mark.parametrize("client_type", client_types) +@pytest.mark.parametrize("status_code", [401, 403]) +async def test_export_rejected_for_the_credentials_raises_authentication_error( + httpx_mock: HTTPXMock, clients: BothClients, client_type: str, status_code: int +) -> None: + httpx_mock.add_response( + method="GET", + url="http://mock/api/schema/export?branch=main&mode=BRIEF", + status_code=status_code, + json={"data": None, "errors": [{"message": "Authentication is required", "extensions": {"code": status_code}}]}, + ) + + with pytest.raises(AuthenticationError, match=r"^Authentication is required$"): + await _export(clients, client_type, branch="main") + + +SERIALISATION_ROUND_TRIPS = { + "pickle": lambda exc: pickle.loads(pickle.dumps(exc)), # noqa: S301 + "deepcopy": copy.deepcopy, + "copy": copy.copy, +} + + +@pytest.mark.parametrize("round_trip", [pytest.param(fn, id=name) for name, fn in SERIALISATION_ROUND_TRIPS.items()]) +def test_export_errors_survive_serialisation(round_trip: Callable[[Exception], Exception]) -> None: + namespace_error = SchemaNamespaceNotFoundError(namespaces=["Locaton"], messages=[LOCATON_ERROR["message"]]) + namespace_error.http_status = 404 + version_error = VersionNotSupportedError(feature="The schema export", required_version="1.13.0") + + restored_namespace_error = round_trip(namespace_error) + restored_version_error = round_trip(version_error) + + assert isinstance(restored_namespace_error, SchemaNamespaceNotFoundError) + assert ( + restored_namespace_error.namespaces, + restored_namespace_error.messages, + restored_namespace_error.http_status, + str(restored_namespace_error), + ) == (["Locaton"], [LOCATON_ERROR["message"]], 404, LOCATON_ERROR["message"]) + assert isinstance(restored_version_error, VersionNotSupportedError) + assert (restored_version_error.required_version, str(restored_version_error)) == ( + "1.13.0", + "The schema export requires Infrahub 1.13.0 or later.", + ) + + +def test_split_by_namespace_splits_the_document_export_returns() -> None: + documents = split_by_namespace(SchemaExportDocument.model_validate(EXPORT_RESPONSE)) - assert "Infra" in result.namespaces - assert "Dcim" not in result.namespaces + assert documents == split_by_namespace(EXPORT_RESPONSE) @pytest.mark.parametrize("client_type", client_types) -async def test_export_empty_when_only_restricted(httpx_mock: HTTPXMock, clients: BothClients, client_type: str) -> None: - response = _schema_response(nodes=[_make_node_dict("Core", "Repository")]) - httpx_mock.add_response(method="GET", url="http://mock/api/schema?branch=main", json=response) +async def test_export_payload_returns_every_field_the_server_returned( + httpx_mock: HTTPXMock, clients: BothClients, client_type: str +) -> None: + response = {**EXPORT_RESPONSE, "unknown_document_setting": "kept"} + httpx_mock.add_response(method="GET", url="http://mock/api/schema/export?branch=main&mode=FULL", json=response) if client_type == "standard": - result = await clients.standard.schema.export(branch="main") + payload = await clients.standard.schema._export_payload(branch="main", mode=SchemaExportMode.FULL) else: - result = clients.sync.schema.export(branch="main") + payload = clients.sync.schema._export_payload(branch="main", mode=SchemaExportMode.FULL) - assert result.namespaces == {} + assert payload == response