From 62f6273f8fb9d9ce7c6e8a00f4ba79d7b10cddf0 Mon Sep 17 00:00:00 2001 From: Cyril Achard Date: Wed, 25 Nov 2026 16:26:15 +0100 Subject: [PATCH 1/3] Copy project layout machinery --- dlccore/project/schemas/base/filesystem.py | 214 ++++++++++++++++++ dlccore/project/schemas/base/observations.py | 98 ++++++++ dlccore/project/schemas/base/validation.py | 34 +++ dlccore/project/schemas/utils.py | 83 +++++++ .../schemas/test_project_relative_path.py | 146 ++++++++++++ 5 files changed, 575 insertions(+) create mode 100644 dlccore/project/schemas/base/filesystem.py create mode 100644 dlccore/project/schemas/base/observations.py create mode 100644 dlccore/project/schemas/base/validation.py create mode 100644 dlccore/project/schemas/utils.py create mode 100644 tests/project/schemas/test_project_relative_path.py diff --git a/dlccore/project/schemas/base/filesystem.py b/dlccore/project/schemas/base/filesystem.py new file mode 100644 index 0000000..acda41b --- /dev/null +++ b/dlccore/project/schemas/base/filesystem.py @@ -0,0 +1,214 @@ +# dlc_octopus/schemas/base/filesystem.py + +from __future__ import annotations + +from collections.abc import Iterator, Mapping +from dataclasses import dataclass +from pathlib import Path +from types import MappingProxyType + +from pydantic import model_validator +from typing_extensions import Self + +from dlc_octopus.schemas.base.core import FrozenModel, SchemaId +from dlc_octopus.schemas.base.resources import ( + DirectoryResourceKind, + FileResourceKind, + ResourceManagement, +) + + +class NamePattern(FrozenModel): + """Declarative constraints for a file or directory name. + + Examples: + - exact: "config.yaml" -> matches only "config.yaml" + - prefix: "CollectedData_" -> matches any name starting with "CollectedData_" + - suffixes: ".h5" -> matches any name ending with ".h5" + """ + + exact: str | None = None + prefix: str | None = None + suffixes: frozenset[str] = frozenset() + + def matches(self, path: Path) -> bool: + if self.exact is not None and path.name != self.exact: + return False + + if self.prefix is not None and not path.stem.startswith(self.prefix): + return False + + return not self.suffixes or path.suffix.lower() in self.suffixes + + +class FileSchema(FrozenModel): + """Schema for a file resource. + + Attributes: + schema_id: The unique identifier for this file schema. + kind: See FileResourceKind. Importantly, nodes may share a kind, but not an ID. + name: The name pattern that this file must match, see NamePattern. + required: Whether this file is required. + description: A human-readable description of the file. + management: How this file is managed. + + schema_id should generally be considered immutable and unique across the project. + Changing that field should not be supported nor necessary. + + Discovery records any missing file; validation reports a missing required one. + """ + + schema_id: SchemaId + kind: FileResourceKind + name: NamePattern + required: bool = False + description: str = "" + management: ResourceManagement = ResourceManagement.MANAGED + + @model_validator(mode="after") + def _check_management(self) -> Self: + _refuse_required_unmanaged(self) + + return self + + +class DirectorySchema(FrozenModel): + schema_id: SchemaId + kind: DirectoryResourceKind + name: NamePattern + required: bool = False + description: str = "" + children: tuple[NodeSchema, ...] = () + repeated_children: tuple[RepeatedNodeSchema, ...] = () + management: ResourceManagement = ResourceManagement.MANAGED + + @model_validator(mode="after") + def _check_management(self) -> Self: + _refuse_required_unmanaged(self) + + return self + + +NodeSchema = FileSchema | DirectorySchema + + +class RepeatedNodeSchema(FrozenModel): + child: NodeSchema + + +DirectorySchema.model_rebuild() + + +@dataclass(frozen=True) +class LayoutIndex: + """Every node of one layout by schema ID, with its parent and whether it lies inside a repeated node. + + Built by ``index_layout``, which refuses a schema ID declared at two positions. + + Attributes: + schemas: Each node's schema, in walk order: depth first, a parent before its children. + parents: Each node's parent ID; ``None`` for the root. + inside_repeated: The IDs of every node that is, or lies inside, a repeated node. + """ + + schemas: Mapping[SchemaId, NodeSchema] + parents: Mapping[SchemaId, SchemaId | None] + inside_repeated: frozenset[SchemaId] + + def ancestry(self, schema_id: SchemaId) -> tuple[SchemaId, ...]: + """Return ``schema_id`` followed by its ancestors' IDs, up to the root. + + Raises: + KeyError: If the layout does not declare ``schema_id``. + """ + + chain: list[SchemaId] = [] + current: SchemaId | None = schema_id + + while current is not None: + chain.append(current) + current = self.parents[current] + + return tuple(chain) + + def subtree(self, schema_id: SchemaId) -> tuple[SchemaId, ...]: + """Return ``schema_id`` and every ID declared beneath it, in walk order. + + Raises: + KeyError: If the layout does not declare ``schema_id``. + """ + + if schema_id not in self.schemas: + raise KeyError(schema_id) + + return tuple(other for other in self.schemas if schema_id in self.ancestry(other)) + + def schema_ids_of(self, node_type: type[FileSchema] | type[DirectorySchema]) -> tuple[SchemaId, ...]: + """Return the ID of every node of ``node_type``, in walk order.""" + + return tuple(schema_id for schema_id, node in self.schemas.items() if isinstance(node, node_type)) + + +def _refuse_required_unmanaged(schema: NodeSchema) -> None: + """Refuse a known-unmanaged node declared as required. + + Raises: + ValueError: If the node is both ``KNOWN_UNMANAGED`` and ``required``. + """ + + if schema.management == ResourceManagement.KNOWN_UNMANAGED and schema.required: + raise ValueError(f"{schema.schema_id!r} is known-unmanaged, so it cannot be required.") + + +def child_schemas(schema: NodeSchema) -> tuple[tuple[NodeSchema, bool], ...]: + """Return a node's declared children, plain children first, each with whether it is a repeated child.""" + + if not isinstance(schema, DirectorySchema): + return () + + return ( + *((child, False) for child in schema.children), + *((repeated.child, True) for repeated in schema.repeated_children), + ) + + +def walk_schema(schema: NodeSchema, *, repeated: bool = False) -> Iterator[tuple[NodeSchema, bool]]: + """Yield a node and every declared descendant, depth first, each with whether it is a repeated child.""" + + yield schema, repeated + + for child, child_repeated in child_schemas(schema): + yield from walk_schema(child, repeated=child_repeated) + + +def index_layout(schema: NodeSchema) -> LayoutIndex: + """Index a layout and every declared descendant by schema ID. + + Raises: + ValueError: If one schema ID is declared at more than one position, even with equal definitions. + """ + + schemas: dict[SchemaId, NodeSchema] = {} + parents: dict[SchemaId, SchemaId | None] = {} + inside_repeated: set[SchemaId] = set() + + def visit(node: NodeSchema, parent: SchemaId | None, *, inside: bool) -> None: + if node.schema_id in schemas: + raise ValueError(f"Schema ID {node.schema_id!r} is declared at more than one layout position.") + + schemas[node.schema_id] = node + parents[node.schema_id] = parent + + if inside: + inside_repeated.add(node.schema_id) + + for child, repeated in child_schemas(node): + visit(child, node.schema_id, inside=inside or repeated) + + visit(schema, None, inside=False) + + return LayoutIndex( + schemas=MappingProxyType(schemas), + parents=MappingProxyType(parents), + inside_repeated=frozenset(inside_repeated), + ) diff --git a/dlccore/project/schemas/base/observations.py b/dlccore/project/schemas/base/observations.py new file mode 100644 index 0000000..b78bc1b --- /dev/null +++ b/dlccore/project/schemas/base/observations.py @@ -0,0 +1,98 @@ +# schemas/base/observations.py +from __future__ import annotations + +from enum import Enum +from typing import TYPE_CHECKING + +from dlc_octopus.schemas.base.core import FrozenModel, ProjectRelativePath, SchemaId +from dlc_octopus.schemas.base.probes import PathProbe +from dlc_octopus.schemas.base.resources import ( + DirectoryResourceKind, + FileResourceKind, + ProjectResource, + ResourceManagement, +) +from dlc_octopus.schemas.base.symlinks import ( + SymlinkObservation, +) + +if TYPE_CHECKING: + from IPython.lib.pretty import RepresentationPrinter + + +class NodeStatus(str, Enum): + """Observed state of a project node.""" + + PRESENT = "present" + MISSING = "missing" + UNREADABLE = "unreadable" + WRONG_TYPE = "wrong_type" + + +class ObservedNode(FrozenModel): + """Observed state of one schema-defined project node. + + ``probe`` is the raw filesystem fact the node was built from + ``status`` is a derived, schema-aware compatibility summary of that + probe against the node's expected entry kind + ``symlink`` is a read-only convenience accessor for ``probe.symlink`` + ``traversal_error_type`` and ``traversal_error_message`` say why a present + directory could not be entered; entry-level failures stay on ``probe`` + + This is not a complete recursive filesystem tree. + ``schema_children`` only contains schema-defined nodes that were observed. + ``unclaimed_resources`` contains immediate filesystem entries that were + not claimed by this schema. + Unknown directories are kept as resources but not traversed. + """ + + schema_id: SchemaId + kind: FileResourceKind | DirectoryResourceKind + project_relative_path: ProjectRelativePath + probe: PathProbe + status: NodeStatus + management: ResourceManagement = ResourceManagement.MANAGED + traversal_error_type: str | None = None + traversal_error_message: str | None = None + + schema_children: tuple[ObservedNode, ...] = () + unclaimed_resources: tuple[ProjectResource, ...] = () + + @property + def symlink(self) -> SymlinkObservation | None: + """Convenience accessor for ``probe.symlink``.""" + return self.probe.symlink + + @property + def should_be_file(self) -> bool: + """Whether the project schema defines this node as a file.""" + return isinstance(self.kind, FileResourceKind) + + @property + def should_be_directory(self) -> bool: + """Whether the project schema defines this node as a directory.""" + return isinstance(self.kind, DirectoryResourceKind) + + # Display hooks only IPython and Jupyter call; repr, str and serialization stay pydantic's. + # Imported on call so that schemas never load visualization. + + def _repr_pretty_(self, printer: RepresentationPrinter, cycle: bool) -> None: # noqa: FBT001 - IPython's signature + from dlc_octopus.visualization.tree import render_project_tree + + printer.text("ObservedNode(...)" if cycle else render_project_tree(self)) + + def _repr_html_(self) -> str: + from dlc_octopus.visualization.tree import render_project_tree_html + + return render_project_tree_html(self) + + +def walk_observed_nodes(node: ObservedNode) -> tuple[ObservedNode, ...]: + """Return a node and its schema-recognized descendants, depth first.""" + + nodes = [node] + + for child in node.schema_children: + nodes.extend(walk_observed_nodes(child)) + + return tuple(nodes) diff --git a/dlccore/project/schemas/base/validation.py b/dlccore/project/schemas/base/validation.py new file mode 100644 index 0000000..0dde9f6 --- /dev/null +++ b/dlccore/project/schemas/base/validation.py @@ -0,0 +1,34 @@ +from __future__ import annotations + +from enum import Enum +from pathlib import Path + +from dlc_octopus.schemas.base.core import FrozenModel +from dlc_octopus.schemas.base.resources import ( + ResourceKind, +) + + +class ValidationDepth(str, Enum): + """Supported validation depth for one explicitly requested domain.""" + + FILENAME_ONLY = "filename_only" + FULL = "full" + + +class ValidationCheckStatus(str, Enum): + """Outcome of one requested validation check.""" + + COMPLETED = "completed" + UNAVAILABLE = "unavailable" + + +class ValidationCheck(FrozenModel): + """Execution record for one explicitly requested validation check.""" + + code: str + kind: ResourceKind + depth: ValidationDepth + status: ValidationCheckStatus + message: str + path: Path | None = None diff --git a/dlccore/project/schemas/utils.py b/dlccore/project/schemas/utils.py new file mode 100644 index 0000000..d9c2c32 --- /dev/null +++ b/dlccore/project/schemas/utils.py @@ -0,0 +1,83 @@ +from __future__ import annotations + +from dlc_octopus.schemas.base.observations import ( + NodeStatus, + ObservedNode, +) +from dlc_octopus.schemas.base.resources import ProjectResource + + +def flatten_observed_project( + project: ObservedNode, + *, + include_project_root: bool = False, +) -> tuple[ProjectResource, ...]: + """Return a flat projection of physical project resources. + + Any schema node with an actual filesystem entry is included - + present, wrong-type, or unreadable alike - along with unclaimed + immediate children. Only nodes with no filesystem entry at all + (``NodeStatus.MISSING``) are retained solely in the semantic + observation tree. + + ``ProjectResource.kind`` reports the schema-expected kind even when + the underlying entry does not actually match it; validity is the + job of ``project`` and its findings, not of this projection. + + Unknown directories are included without recursively interpreting + their contents. + """ + + resources: list[ProjectResource] = [] + + if include_project_root: + _collect_resources( + node=project, + resources=resources, + ) + else: + resources.extend(project.unclaimed_resources) + + for child in project.schema_children: + _collect_resources( + node=child, + resources=resources, + ) + + return tuple( + sorted( + resources, + key=lambda resource: ( + resource.project_relative_path.as_posix().casefold(), + resource.project_relative_path.as_posix(), + ), + ) + ) + + +def _collect_resources( + *, + node: ObservedNode, + resources: list[ProjectResource], +) -> None: + """Recursively collect physical resources from one observed node.""" + + is_physical_resource = node.status != NodeStatus.MISSING + + if is_physical_resource: + resources.append( + ProjectResource( + project_relative_path=(node.project_relative_path), + kind=node.kind, + management=node.management, + symlink=node.symlink, + ) + ) + + resources.extend(node.unclaimed_resources) + + for child in node.schema_children: + _collect_resources( + node=child, + resources=resources, + ) diff --git a/tests/project/schemas/test_project_relative_path.py b/tests/project/schemas/test_project_relative_path.py new file mode 100644 index 0000000..8765bdb --- /dev/null +++ b/tests/project/schemas/test_project_relative_path.py @@ -0,0 +1,146 @@ +"""Identity paths must stay project-relative. + +An anchored path is machine-local. `Path.resolve()` on Windows against a mapped +network drive can return a volume-GUID path such as ``\\\\?\\Volume{...}\\...``; +DeepLabCut issue #3348 is that behaviour rewriting a project's ``project_path`` +into an unusable form, and DeepLabCut's own ``auxiliaryfunctions`` now falls back +to ``Path.absolute()`` because of it. + +These paths are identity for a snapshot and eventually for database primary +keys so the constraint is on the value rather than on any one call: no +resolution mechanism, present or future, can make an identity machine-local if an +anchored path cannot be stored in the first place. +""" + +from pathlib import Path, PurePosixPath, PureWindowsPath + +import pytest +from pydantic import ValidationError + +from dlc_octopus.schemas.base.core import reject_anchored_path +from dlc_octopus.schemas.base.observations import NodeStatus, ObservedNode +from dlc_octopus.schemas.base.probes import ( + FilesystemEntryKind, + PathProbe, + PathProbeStatus, +) +from dlc_octopus.schemas.base.resources import FileResourceKind, ProjectResource + +_ANCHORED = [ + "Z:/shared/DLC/project", + "//?/Volume{80D426CE-0000-0000-691B-0D2800000040}/DLC/project", + "//server/share/project", + "C:rel_to_drive", + "/absolute/posix", +] + +_RELATIVE = [ + "videos/vid1.mp4", + "labeled-data/vid1/img001.png", + "config.yaml", +] + +_PROBE = PathProbe( + status=PathProbeStatus.OBSERVED, + entry_kind=FilesystemEntryKind.FILE, +) + + +@pytest.mark.parametrize("raw", _ANCHORED, ids=str) +def test_reject_anchored_path_rejects_an_anchor(raw: str) -> None: + with pytest.raises(ValueError, match="project-relative"): + reject_anchored_path(Path(raw)) + + +@pytest.mark.parametrize("raw", _RELATIVE, ids=str) +def test_reject_anchored_path_accepts_a_relative_path(raw: str) -> None: + assert reject_anchored_path(Path(raw)) == Path(raw) + + +def test_drive_relative_path_is_rejected_though_it_is_not_absolute() -> None: + """``C:rel`` resolves against that drive's working directory. + + ``is_absolute()`` reports ``False`` for it, so a check written against + absoluteness rather than the anchor lets it through. + """ + + drive_relative = Path("C:rel_to_drive") + + assert not drive_relative.is_absolute() + + with pytest.raises(ValueError, match="project-relative"): + reject_anchored_path(drive_relative) + + +@pytest.mark.parametrize("raw", _ANCHORED, ids=str) +def test_anchor_is_rejected_whatever_filesystem_the_host_uses(raw: str) -> None: + """The verdict must come from the value, not from the interpreter reading it. + + A snapshot is written on one platform and validated on another, so handing + the validator a deliberately POSIX path stands in for running it + on Linux. ``PurePosixPath("C:rel_to_drive").anchor`` is empty, so a check + reading ``Path.anchor`` accepts a Windows drive everywhere but on Windows. + """ + + with pytest.raises(ValueError, match="project-relative"): + reject_anchored_path(PurePosixPath(raw)) + + with pytest.raises(ValueError, match="project-relative"): + reject_anchored_path(PureWindowsPath(raw)) + + +@pytest.mark.parametrize("raw", _RELATIVE, ids=str) +def test_relative_path_is_accepted_whatever_filesystem_the_host_uses(raw: str) -> None: + assert reject_anchored_path(PurePosixPath(raw)) is not None + assert reject_anchored_path(PureWindowsPath(raw)) is not None + + +def test_posix_filename_holding_a_colon_is_accepted() -> None: + """POSIX allows a colon in a filename, and asking both filesystems must not forbid it.""" + + assert reject_anchored_path(PurePosixPath("labeled-data/vid:1/img.png")) is not None + + +def test_leading_single_letter_colon_is_rejected_on_every_host() -> None: + """The one accepted cost of asking both filesystems. + + A POSIX directory literally named ``c:foo`` at the head of the path parses + as a Windows drive and is refused. Accepting genuine ``C:rel`` identity is + the worse failure, so this is deliberate rather than overlooked. + """ + + with pytest.raises(ValueError, match="project-relative"): + reject_anchored_path(PurePosixPath("c:foo/bar.png")) + + +def test_escaping_path_is_accepted_here() -> None: + """``..`` is a user-data state, not a programmer error. + + A path escaping the project root is reported by validation, never clamped + at construction; only an anchor means this code built the model wrong. + """ + + assert reject_anchored_path(Path("../outside")) == Path("../outside") + + +def test_project_resource_rejects_an_anchored_path() -> None: + with pytest.raises(ValidationError) as raised: + ProjectResource( + project_relative_path=Path("Z:/shared/DLC/videos/vid1.mp4"), + kind=FileResourceKind.SOURCE_VIDEO, + ) + + assert raised.value.errors()[0]["loc"] == ("project_relative_path",) + + +def test_observed_node_rejects_an_anchored_path() -> None: + with pytest.raises(ValidationError) as raised: + ObservedNode( + schema_id="dlc.project.videos.video", + kind=FileResourceKind.SOURCE_VIDEO, + project_relative_path=Path("Z:/shared/DLC/videos/vid1.mp4"), + probe=_PROBE, + status=NodeStatus.PRESENT, + ) + + assert raised.value.errors()[0]["loc"] == ("project_relative_path",) From e17ddb6f0f84639ea38ffc13dddf12da51f6dcb0 Mon Sep 17 00:00:00 2001 From: Cyril Achard Date: Wed, 25 Nov 2026 16:26:35 +0100 Subject: [PATCH 2/3] Adapt project layout machinery to dlccore - Rename the package to dlccore.project and add the dlccore license header - Drop ObservedNode's IPython display hooks; they render through the visualization package, which lands later - Drop the stale path comments on line 1 --- dlccore/project/schemas/base/filesystem.py | 15 ++++++-- dlccore/project/schemas/base/observations.py | 37 ++++++++----------- dlccore/project/schemas/base/validation.py | 15 +++++++- dlccore/project/schemas/utils.py | 15 +++++++- .../schemas/test_project_relative_path.py | 19 ++++++++-- 5 files changed, 68 insertions(+), 33 deletions(-) diff --git a/dlccore/project/schemas/base/filesystem.py b/dlccore/project/schemas/base/filesystem.py index acda41b..abc9149 100644 --- a/dlccore/project/schemas/base/filesystem.py +++ b/dlccore/project/schemas/base/filesystem.py @@ -1,4 +1,13 @@ -# dlc_octopus/schemas/base/filesystem.py +# +# DeepLabCut Toolbox (deeplabcut.org) +# © A. & M.W. Mathis Labs +# https://github.com/DeepLabCut/dlccore +# +# Contributors: +# https://github.com/DeepLabCut/dlccore/graphs/contributors +# +# Licensed under GNU Lesser General Public License v3.0 +# from __future__ import annotations @@ -10,8 +19,8 @@ from pydantic import model_validator from typing_extensions import Self -from dlc_octopus.schemas.base.core import FrozenModel, SchemaId -from dlc_octopus.schemas.base.resources import ( +from dlccore.project.schemas.base.core import FrozenModel, SchemaId +from dlccore.project.schemas.base.resources import ( DirectoryResourceKind, FileResourceKind, ResourceManagement, diff --git a/dlccore/project/schemas/base/observations.py b/dlccore/project/schemas/base/observations.py index b78bc1b..7fcdab8 100644 --- a/dlccore/project/schemas/base/observations.py +++ b/dlccore/project/schemas/base/observations.py @@ -1,24 +1,30 @@ -# schemas/base/observations.py +# +# DeepLabCut Toolbox (deeplabcut.org) +# © A. & M.W. Mathis Labs +# https://github.com/DeepLabCut/dlccore +# +# Contributors: +# https://github.com/DeepLabCut/dlccore/graphs/contributors +# +# Licensed under GNU Lesser General Public License v3.0 +# + from __future__ import annotations from enum import Enum -from typing import TYPE_CHECKING -from dlc_octopus.schemas.base.core import FrozenModel, ProjectRelativePath, SchemaId -from dlc_octopus.schemas.base.probes import PathProbe -from dlc_octopus.schemas.base.resources import ( +from dlccore.project.schemas.base.core import FrozenModel, ProjectRelativePath, SchemaId +from dlccore.project.schemas.base.probes import PathProbe +from dlccore.project.schemas.base.resources import ( DirectoryResourceKind, FileResourceKind, ProjectResource, ResourceManagement, ) -from dlc_octopus.schemas.base.symlinks import ( +from dlccore.project.schemas.base.symlinks import ( SymlinkObservation, ) -if TYPE_CHECKING: - from IPython.lib.pretty import RepresentationPrinter - class NodeStatus(str, Enum): """Observed state of a project node.""" @@ -73,19 +79,6 @@ def should_be_directory(self) -> bool: """Whether the project schema defines this node as a directory.""" return isinstance(self.kind, DirectoryResourceKind) - # Display hooks only IPython and Jupyter call; repr, str and serialization stay pydantic's. - # Imported on call so that schemas never load visualization. - - def _repr_pretty_(self, printer: RepresentationPrinter, cycle: bool) -> None: # noqa: FBT001 - IPython's signature - from dlc_octopus.visualization.tree import render_project_tree - - printer.text("ObservedNode(...)" if cycle else render_project_tree(self)) - - def _repr_html_(self) -> str: - from dlc_octopus.visualization.tree import render_project_tree_html - - return render_project_tree_html(self) - def walk_observed_nodes(node: ObservedNode) -> tuple[ObservedNode, ...]: """Return a node and its schema-recognized descendants, depth first.""" diff --git a/dlccore/project/schemas/base/validation.py b/dlccore/project/schemas/base/validation.py index 0dde9f6..1abf76e 100644 --- a/dlccore/project/schemas/base/validation.py +++ b/dlccore/project/schemas/base/validation.py @@ -1,10 +1,21 @@ +# +# DeepLabCut Toolbox (deeplabcut.org) +# © A. & M.W. Mathis Labs +# https://github.com/DeepLabCut/dlccore +# +# Contributors: +# https://github.com/DeepLabCut/dlccore/graphs/contributors +# +# Licensed under GNU Lesser General Public License v3.0 +# + from __future__ import annotations from enum import Enum from pathlib import Path -from dlc_octopus.schemas.base.core import FrozenModel -from dlc_octopus.schemas.base.resources import ( +from dlccore.project.schemas.base.core import FrozenModel +from dlccore.project.schemas.base.resources import ( ResourceKind, ) diff --git a/dlccore/project/schemas/utils.py b/dlccore/project/schemas/utils.py index d9c2c32..c0711cf 100644 --- a/dlccore/project/schemas/utils.py +++ b/dlccore/project/schemas/utils.py @@ -1,10 +1,21 @@ +# +# DeepLabCut Toolbox (deeplabcut.org) +# © A. & M.W. Mathis Labs +# https://github.com/DeepLabCut/dlccore +# +# Contributors: +# https://github.com/DeepLabCut/dlccore/graphs/contributors +# +# Licensed under GNU Lesser General Public License v3.0 +# + from __future__ import annotations -from dlc_octopus.schemas.base.observations import ( +from dlccore.project.schemas.base.observations import ( NodeStatus, ObservedNode, ) -from dlc_octopus.schemas.base.resources import ProjectResource +from dlccore.project.schemas.base.resources import ProjectResource def flatten_observed_project( diff --git a/tests/project/schemas/test_project_relative_path.py b/tests/project/schemas/test_project_relative_path.py index 8765bdb..0aa64ca 100644 --- a/tests/project/schemas/test_project_relative_path.py +++ b/tests/project/schemas/test_project_relative_path.py @@ -1,3 +1,14 @@ +# +# DeepLabCut Toolbox (deeplabcut.org) +# © A. & M.W. Mathis Labs +# https://github.com/DeepLabCut/dlccore +# +# Contributors: +# https://github.com/DeepLabCut/dlccore/graphs/contributors +# +# Licensed under GNU Lesser General Public License v3.0 +# + """Identity paths must stay project-relative. An anchored path is machine-local. `Path.resolve()` on Windows against a mapped @@ -17,14 +28,14 @@ import pytest from pydantic import ValidationError -from dlc_octopus.schemas.base.core import reject_anchored_path -from dlc_octopus.schemas.base.observations import NodeStatus, ObservedNode -from dlc_octopus.schemas.base.probes import ( +from dlccore.project.schemas.base.core import reject_anchored_path +from dlccore.project.schemas.base.observations import NodeStatus, ObservedNode +from dlccore.project.schemas.base.probes import ( FilesystemEntryKind, PathProbe, PathProbeStatus, ) -from dlc_octopus.schemas.base.resources import FileResourceKind, ProjectResource +from dlccore.project.schemas.base.resources import FileResourceKind, ProjectResource _ANCHORED = [ "Z:/shared/DLC/project", From 719432083880948e80e10c3b4902481ef5b0f6c9 Mon Sep 17 00:00:00 2001 From: Cyril Achard Date: Thu, 26 Nov 2026 14:54:01 +0100 Subject: [PATCH 3/3] Add the schema ID tests that run without capabilities - Copy tests/schemas/test_schema_id.py without test_a_schema_id_serializes_as_a_plain_string, which needs the capabilities module --- tests/project/schemas/test_schema_id.py | 33 +++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 tests/project/schemas/test_schema_id.py diff --git a/tests/project/schemas/test_schema_id.py b/tests/project/schemas/test_schema_id.py new file mode 100644 index 0000000..689f49a --- /dev/null +++ b/tests/project/schemas/test_schema_id.py @@ -0,0 +1,33 @@ +# +# DeepLabCut Toolbox (deeplabcut.org) +# © A. & M.W. Mathis Labs +# https://github.com/DeepLabCut/dlccore +# +# Contributors: +# https://github.com/DeepLabCut/dlccore/graphs/contributors +# +# Licensed under GNU Lesser General Public License v3.0 +# + +from __future__ import annotations + +import pytest +from pydantic import ValidationError + +from dlccore.project.schemas.base.filesystem import FileSchema, NamePattern +from dlccore.project.schemas.base.resources import FileResourceKind + + +def _file_schema(schema_id: str) -> FileSchema: + return FileSchema(schema_id=schema_id, kind=FileResourceKind.UNKNOWN_FILE, name=NamePattern()) + + +@pytest.mark.parametrize("schema_id", ["dlc.Videos", "dlc.videos ", "videos", "dlc.", "dlc..videos"]) +def test_a_malformed_schema_id_is_refused_where_it_is_declared(schema_id: str) -> None: + with pytest.raises(ValidationError, match="layout schema ID"): + _file_schema(schema_id) + + +def test_a_well_formed_schema_id_is_accepted_even_if_no_node_declares_it() -> None: + # Membership is not this type's job; only the layout knows which IDs exist. + assert _file_schema("dlc.not_declared_anywhere").schema_id == "dlc.not_declared_anywhere"