From c3dd5c5304de4df12eb2763ee3fc09cf62c94b6a Mon Sep 17 00:00:00 2001 From: Cyril Achard Date: Thu, 26 Nov 2026 15:20:03 +0100 Subject: [PATCH 1/3] Copy project inspection and capabilities, with the tests that need inspect_project --- dlccore/project/capabilities.py | 72 ++ dlccore/project/inspection.py | 121 +++ dlccore/project/schemas/capabilities.py | 60 ++ tests/project/discovery/test_observer.py | 41 +- tests/project/discovery/test_symlinks.py | 214 ++++- tests/project/inspection/conftest.py | 46 + tests/project/inspection/test_config.py | 45 + tests/project/inspection/test_invariants.py | 20 + tests/project/inspection/test_project_name.py | 97 +++ .../inspection/test_project_structure.py | 43 + tests/project/inspection/test_resolution.py | 59 ++ tests/project/inspection/test_resources.py | 35 + tests/project/inspection/test_scope_query.py | 181 +++- tests/project/inspection/test_serialize.py | 248 ++++++ tests/project/inspection/test_snapshot.py | 210 +++++ .../inspection/test_validation_error.py | 100 ++- .../inspection/test_validation_request.py | 55 ++ .../schemas/test_labeled_data_layout.py | 76 ++ tests/project/schemas/test_schema_id.py | 24 +- tests/project/test_capabilities.py | 148 ++++ .../deeplabcut/test_labeled_data.py | 47 + .../deeplabcut/test_project_path.py | 316 +++++++ .../validation/deeplabcut/test_videos.py | 824 ++++++++++++++++++ tests/project/validation/test_baseline.py | 65 +- tests/project/validation/test_context.py | 40 + .../validation/test_finding_schema_ids.py | 166 +++- tests/project/validation/test_project.py | 55 ++ .../validation/test_validation_coverage.py | 24 + 28 files changed, 3328 insertions(+), 104 deletions(-) create mode 100644 dlccore/project/capabilities.py create mode 100644 dlccore/project/inspection.py create mode 100644 dlccore/project/schemas/capabilities.py create mode 100644 tests/project/inspection/conftest.py create mode 100644 tests/project/inspection/test_config.py create mode 100644 tests/project/inspection/test_invariants.py create mode 100644 tests/project/inspection/test_project_name.py create mode 100644 tests/project/inspection/test_project_structure.py create mode 100644 tests/project/inspection/test_resolution.py create mode 100644 tests/project/inspection/test_resources.py create mode 100644 tests/project/inspection/test_serialize.py create mode 100644 tests/project/inspection/test_snapshot.py create mode 100644 tests/project/inspection/test_validation_request.py create mode 100644 tests/project/schemas/test_labeled_data_layout.py create mode 100644 tests/project/test_capabilities.py create mode 100644 tests/project/validation/deeplabcut/test_labeled_data.py create mode 100644 tests/project/validation/deeplabcut/test_project_path.py create mode 100644 tests/project/validation/deeplabcut/test_videos.py create mode 100644 tests/project/validation/test_context.py create mode 100644 tests/project/validation/test_project.py create mode 100644 tests/project/validation/test_validation_coverage.py diff --git a/dlccore/project/capabilities.py b/dlccore/project/capabilities.py new file mode 100644 index 0000000..7757795 --- /dev/null +++ b/dlccore/project/capabilities.py @@ -0,0 +1,72 @@ +from __future__ import annotations + +from dlc_octopus.schemas.base.filesystem import ( + NodeSchema, + child_schemas, + index_layout, +) +from dlc_octopus.schemas.capabilities import ( + BaselineValidationCapability, + LayoutCapability, + ProjectManagerCapabilities, + ValidationCapability, +) +from dlc_octopus.schemas.project_layout.project import PROJECT +from dlc_octopus.schemas.snapshots import ( + PROJECT_SNAPSHOT_VERSION, +) +from dlc_octopus.validation.baseline import ( + iter_baseline_check_registrations, +) +from dlc_octopus.validation.registry import ( + iter_validator_registrations, +) + + +def get_project_manager_capabilities() -> ProjectManagerCapabilities: + """Return the layout and validations supported by this installation.""" + + baseline_validations = tuple( + BaselineValidationCapability( + code=registration.code, + description=registration.description, + ) + for registration in iter_baseline_check_registrations() + ) + + validations = tuple( + ValidationCapability( + kind=kind, + supported_depths=tuple(registration.supported_depths), + ) + for kind, registration in iter_validator_registrations() + ) + + return ProjectManagerCapabilities( + snapshot_version=PROJECT_SNAPSHOT_VERSION, + layout=_describe_layout(PROJECT, inside_repeated=index_layout(PROJECT).inside_repeated), + baseline_validations=baseline_validations, + validations=validations, + ) + + +def _describe_layout( + schema: NodeSchema, + *, + inside_repeated: frozenset[str], + repeated: bool = False, +) -> LayoutCapability: + """Project one schema node into public capability metadata.""" + + return LayoutCapability( + schema_id=schema.schema_id, + kind=schema.kind, + required=schema.required, + management=schema.management, + repeated=repeated, + inside_repeated=schema.schema_id in inside_repeated, + children=tuple( + _describe_layout(child, inside_repeated=inside_repeated, repeated=child_repeated) + for child, child_repeated in child_schemas(schema) + ), + ) diff --git a/dlccore/project/inspection.py b/dlccore/project/inspection.py new file mode 100644 index 0000000..0a47c86 --- /dev/null +++ b/dlccore/project/inspection.py @@ -0,0 +1,121 @@ +"""Inspect a DeepLabCut project into a snapshot, and read DeepLabCut's name for it.""" + +from __future__ import annotations + +import re +from datetime import date +from pathlib import Path + +from dlc_octopus.discovery.observer import discover_project +from dlc_octopus.errors import ProjectValidationError, _blocking_findings +from dlc_octopus.schemas.base.findings import Finding +from dlc_octopus.schemas.snapshots import ProjectSnapshot +from dlc_octopus.validation import ProjectValidationRequest, validate_project +from dlc_octopus.validation.config import validate_project_config + +# DeepLabCut's create_new_project: config ``date`` is the 3-letter month and unpadded day, e.g. "Oct30". +_MONTHS = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec") +_ISO_DATE = re.compile(r"\d{4}-\d{2}-\d{2}") + + +def inspect_project( + path: str | Path, + *, + validation: ProjectValidationRequest | None = None, + raise_on_validation_error: bool = False, +) -> ProjectSnapshot: + """Inspect a DeepLabCut project without modifying its contents. + + Args: + path: Path to a project root directory or its ``config.yaml`` file. + validation: Resource validation to request, or ``None`` for baseline only. + raise_on_validation_error: Whether to raise when a finding is of blocking severity. + + Raises: + FileNotFoundError: If the supplied project root does not exist. + ValueError: If the supplied existing file is not named ``config.yaml``. + ProjectValidationError: If requested and a finding has ``ERROR`` severity. + """ + + project_root = _resolve_project_root(path) + config_path = project_root / "config.yaml" + + config_observation = None + config_findings: tuple[Finding, ...] = () + + if config_path.is_file(): + config_observation, config_findings = validate_project_config(config_path) + + project = discover_project(project_root) + + snapshot = ProjectSnapshot.from_project( + project_root=project_root, + config_observation=config_observation, + project=project, + findings=config_findings, + ) + validation_result = validate_project( + snapshot, + request=validation, + ) + + snapshot = snapshot.with_validation_result(validation_result) + + if raise_on_validation_error and _blocking_findings(snapshot): + raise ProjectValidationError(snapshot) + + return snapshot + + +def project_name(snapshot: ProjectSnapshot) -> str | None: + """Return DeepLabCut's name for the project, ``Task-scorer-YYYY-MM-DD``, as ``create_new_project`` built it. + + Read from the project folder's name when it is exactly that and agrees with the config's ``date``; ``None`` + otherwise, since ``date`` alone (``Oct30``) has no year. The config's ``project_path`` is not read: DeepLabCut + rewrites it to the current location whenever it loads the config. + + Raises: + ConfigUnavailableError: If the config was not loaded. + """ + + config = snapshot.config + prefix = f"{config.Task}-{config.scorer}-" + folder = snapshot.project_root.name + + if folder.startswith(prefix) and _agrees_with(folder.removeprefix(prefix), str(config.date)): + return folder + + return None + + +def _agrees_with(stamp: str, config_date: str) -> bool: + if not _ISO_DATE.fullmatch(stamp): + return False + try: + created = date.fromisoformat(stamp) + except ValueError: + return False + + return f"{_MONTHS[created.month - 1]}{created.day}" == config_date + + +def _resolve_project_root( + path: str | Path, +) -> Path: + """Resolve an absolute project root from a directory or ``config.yaml`` path, without following links.""" + + supplied_path = Path(path).absolute() + + if supplied_path.is_dir(): + return supplied_path + + if supplied_path.is_file(): + if supplied_path.name != "config.yaml": + raise ValueError(f"A project file input must be named 'config.yaml': {supplied_path}") + + return supplied_path.parent + + if supplied_path.name == "config.yaml": + return supplied_path.parent + + raise FileNotFoundError(f"Project path does not exist: {supplied_path}") diff --git a/dlccore/project/schemas/capabilities.py b/dlccore/project/schemas/capabilities.py new file mode 100644 index 0000000..f9c1193 --- /dev/null +++ b/dlccore/project/schemas/capabilities.py @@ -0,0 +1,60 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING + +from dlc_octopus.schemas.base.core import FrozenModel, SchemaId +from dlc_octopus.schemas.base.resources import ( + ResourceKind, + ResourceManagement, +) +from dlc_octopus.schemas.base.validation import ( + ValidationDepth, +) + +if TYPE_CHECKING: + from IPython.lib.pretty import RepresentationPrinter + + +class LayoutCapability(FrozenModel): + """One node in the declared DeepLabCut project layout.""" + + schema_id: SchemaId + kind: ResourceKind + required: bool + management: ResourceManagement + repeated: bool = False + inside_repeated: bool = False + children: tuple[LayoutCapability, ...] = () + + +class BaselineValidationCapability(FrozenModel): + """One automatic project-level validation capability.""" + + code: str + description: str + + +class ValidationCapability(FrozenModel): + """Validation depths available for one resource kind.""" + + kind: ResourceKind + supported_depths: tuple[ValidationDepth, ...] + + +class ProjectManagerCapabilities(FrozenModel): + """Versioned description of project-management affordances.""" + + snapshot_version: str + layout: LayoutCapability + baseline_validations: tuple[BaselineValidationCapability, ...] = () + validations: tuple[ValidationCapability, ...] = () + + def _repr_pretty_(self, printer: RepresentationPrinter, cycle: bool) -> None: # noqa: FBT001 - IPython's signature + from dlc_octopus.visualization.capabilities import render_capabilities + + printer.text("ProjectManagerCapabilities(...)" if cycle else render_capabilities(self)) + + def _repr_markdown_(self) -> str: + from dlc_octopus.visualization.capabilities import render_capabilities + + return render_capabilities(self, style="markdown") diff --git a/tests/project/discovery/test_observer.py b/tests/project/discovery/test_observer.py index e5ad48b..a8aa95e 100644 --- a/tests/project/discovery/test_observer.py +++ b/tests/project/discovery/test_observer.py @@ -1,36 +1,26 @@ -# -# 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 collections.abc import Iterator from pathlib import Path import pytest -from dlccore.project.discovery.observer import discover_directory_node, discover_project -from dlccore.project.schemas.base.filesystem import ( +from dlc_octopus.api import inspect_project +from dlc_octopus.discovery.observer import discover_directory_node, discover_project +from dlc_octopus.schemas.base.filesystem import ( DirectorySchema, FileSchema, NamePattern, NodeSchema, ) -from dlccore.project.schemas.base.observations import ( +from dlc_octopus.schemas.base.observations import ( NodeStatus, ) -from dlccore.project.schemas.base.probes import FilesystemEntryKind, PathProbeStatus -from dlccore.project.schemas.base.resources import ( +from dlc_octopus.schemas.base.probes import FilesystemEntryKind, PathProbeStatus +from dlc_octopus.schemas.base.resources import ( DirectoryResourceKind, FileResourceKind, ResourceManagement, ) -from dlccore.project.schemas.project_layout.project import PROJECT +from dlc_octopus.schemas.project_layout.project import PROJECT def test_discovered_directory_populates_renamed_fields( @@ -374,3 +364,20 @@ def test_without_file_ids_a_subdirectory_is_not_a_symlink_loop(tmp_path: Path) - assert by_path[Path("videos")].status == NodeStatus.PRESENT assert by_path[Path("labeled-data")].status == NodeStatus.PRESENT assert by_path[Path("labeled-data")].traversal_error_type is None + + +@pytest.mark.xfail( + reason="on a case-insensitive filesystem, a layout directory spelled differently on disk is discovered twice: " + "as the layout node under the layout's spelling, and as an unclaimed directory under its own", + strict=True, + raises=AssertionError, +) +def test_a_differently_cased_layout_directory_is_one_resource(tmp_path: Path) -> None: + (tmp_path / "VIDEOS").mkdir() + + if not (tmp_path / "videos").exists(): + pytest.skip("case-sensitive filesystem: VIDEOS is simply another directory") + + resources = inspect_project(tmp_path).resources + + assert len([resource for resource in resources if str(resource.project_relative_path).lower() == "videos"]) == 1 diff --git a/tests/project/discovery/test_symlinks.py b/tests/project/discovery/test_symlinks.py index 600356a..47937e2 100644 --- a/tests/project/discovery/test_symlinks.py +++ b/tests/project/discovery/test_symlinks.py @@ -1,39 +1,31 @@ -# -# 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 collections.abc import Callable from pathlib import Path import pytest +from deeplabcut.core.config import ProjectConfig -from dlccore.project.discovery.observer import ( +from dlc_octopus.api import inspect_project +from dlc_octopus.discovery.observer import ( ExpectedEntryKind, classify_unclaimed_entry, status_for_expected_entry, ) -from dlccore.project.discovery.probe import probe_path -from dlccore.project.schemas.base.observations import NodeStatus -from dlccore.project.schemas.base.probes import ( +from dlc_octopus.discovery.probe import probe_path +from dlc_octopus.schemas.base.observations import NodeStatus +from dlc_octopus.schemas.base.probes import ( FilesystemEntryKind, PathProbe, PathProbeStatus, ) -from dlccore.project.schemas.base.resources import ( +from dlc_octopus.schemas.base.resources import ( DirectoryResourceKind, FileResourceKind, + ResourceManagement, UnknownResourceKind, ) -from dlccore.project.schemas.base.symlinks import ( +from dlc_octopus.schemas.base.symlinks import ( SymlinkObservation, SymlinkTargetKind, ) @@ -279,3 +271,191 @@ def test_mapping_functions_do_not_touch_the_filesystem(tmp_path: Path) -> None: assert status == NodeStatus.PRESENT assert kind is FileResourceKind.UNKNOWN_FILE assert symlink is None + + +def test_inspection_preserves_valid_video_symlink( + valid_project: Path, + tmp_path: Path, + create_symlink_or_skip: Callable[..., None], +) -> None: + target = tmp_path / "external.mp4" + target.touch() + + link = valid_project / "videos" / "external.mp4" + create_symlink_or_skip( + link, + target, + ) + + snapshot = inspect_project(valid_project) + resource = snapshot.resource_at("videos/external.mp4") + + assert resource is not None + assert resource.kind == FileResourceKind.SOURCE_VIDEO + assert resource.symlink is not None + assert resource.symlink.absolute_target == target.absolute() + assert resource.symlink.target_kind == SymlinkTargetKind.FILE + + +def test_inspection_preserves_broken_video_symlink( + valid_project: Path, + tmp_path: Path, + create_symlink_or_skip: Callable[..., None], +) -> None: + target = tmp_path / "missing.mp4" + + link = valid_project / "videos" / "missing.mp4" + create_symlink_or_skip( + link, + target, + ) + + snapshot = inspect_project(valid_project) + resource = snapshot.resource_at("videos/missing.mp4") + + assert resource is not None + assert resource.kind == FileResourceKind.SOURCE_VIDEO + assert resource.symlink is not None + assert resource.symlink.absolute_target == target.absolute() + assert resource.symlink.target_kind == SymlinkTargetKind.MISSING + + +def test_inspection_retains_an_unclaimed_directory_symlink( + valid_project: Path, + tmp_path: Path, + create_symlink_or_skip: Callable[..., None], +) -> None: + """End to end: a relocated project directory survives inspection as a resource. + + The mapping is covered by constructed probes above, which run everywhere. + This covers the wiring - probe, unknown-child collection, ``ProjectResource`` + construction and flattening - and needs a real link, so it skips on Windows. + """ + + target = tmp_path / "relocated" + target.mkdir() + + link = valid_project / "training-datasets" + create_symlink_or_skip( + link, + target, + target_is_directory=True, + ) + + snapshot = inspect_project(valid_project) + resource = snapshot.resource_at("training-datasets") + + assert resource is not None + assert resource.kind == DirectoryResourceKind.UNKNOWN_DIRECTORY + assert resource.management == ResourceManagement.UNDETERMINED + assert resource.symlink is not None + assert resource.symlink.absolute_target == target.absolute() + assert resource.symlink.target_kind == SymlinkTargetKind.DIRECTORY + + +def test_an_unclaimed_entry_that_vanishes_is_not_reported_as_a_resource( + valid_project: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """``resources`` holds only entries with a filesystem entry, as claimed nodes do. + + An entry can disappear between ``iterdir`` and the probe, and a resource for + something that no longer exists is a phantom row for any consumer. + """ + + (valid_project / "notes.txt").touch() + + real_probe_path = probe_path + + def fake_probe_path(path: Path) -> PathProbe: + if path.name == "notes.txt": + return PathProbe(status=PathProbeStatus.MISSING) + + return real_probe_path(path) + + monkeypatch.setattr( + "dlc_octopus.discovery.observer.probe_path", + fake_probe_path, + ) + + snapshot = inspect_project(valid_project) + + assert snapshot.resource_at("notes.txt") is None + assert snapshot.resource_at("config.yaml") is not None + + +def test_a_symlinked_videos_directory_is_reported_not_raised( + tmp_path: Path, + create_symlink_or_skip: Callable[..., None], +) -> None: + real_videos = tmp_path / "real_videos" + real_videos.mkdir() + project = tmp_path / "project" + project.mkdir() + create_symlink_or_skip(project / "videos", real_videos, target_is_directory=True) + + snapshot = inspect_project(project) + resource = snapshot.resource_at("videos") + + assert resource is not None + assert resource.kind == DirectoryResourceKind.VIDEOS_DIRECTORY + assert resource.symlink is not None + assert resource.symlink.target_kind == SymlinkTargetKind.DIRECTORY + + +@pytest.mark.parametrize("given", ["root", "config"], ids=["root", "config_yaml"]) +def test_a_project_whose_root_is_a_symlink_is_inspected_through_it( + tmp_path: Path, + valid_project_config: ProjectConfig, + create_symlink_or_skip: Callable[..., None], + given: str, +) -> None: + real = tmp_path / "real" + (real / "videos").mkdir(parents=True) + (real / "labeled-data").mkdir() + valid_project_config.to_yaml(real / "config.yaml") + link = tmp_path / "link" + create_symlink_or_skip(link, real, target_is_directory=True) + + snapshot = inspect_project(link if given == "root" else link / "config.yaml") + + assert snapshot.project_root == link.absolute() + assert snapshot.resource_at("videos") is not None + assert snapshot.config_state.value == "valid" + + +def test_a_symlinked_dataset_is_traversed( + valid_project: Path, + tmp_path_factory: pytest.TempPathFactory, + create_symlink_or_skip: Callable[..., None], +) -> None: + storage = tmp_path_factory.mktemp("storage") / "session-02" + storage.mkdir() + (storage / "img000.png").touch() + create_symlink_or_skip(valid_project / "labeled-data" / "session-02", storage, target_is_directory=True) + + snapshot = inspect_project(valid_project) + dataset = snapshot.resource_at("labeled-data/session-02") + + assert dataset is not None + assert dataset.kind == DirectoryResourceKind.LABELED_DATASET + assert dataset.symlink is not None + assert snapshot.resource_at("labeled-data/session-02/img000.png") is not None + + +def test_a_directory_linked_to_its_own_ancestor_is_unreadable_not_entered( + valid_project: Path, + create_symlink_or_skip: Callable[..., None], +) -> None: + (valid_project / "labeled-data").rmdir() + create_symlink_or_skip(valid_project / "labeled-data", valid_project, target_is_directory=True) + + snapshot = inspect_project(valid_project) + + (finding,) = ( + finding + for finding in snapshot.findings + if finding.code == "PROJECT_NODE_UNREADABLE" and finding.schema_id == "dlc.labeled_data" + ) + assert finding.evidence["error_type"] == "SymlinkLoop" + assert snapshot.resource_at("labeled-data/config.yaml") is None diff --git a/tests/project/inspection/conftest.py b/tests/project/inspection/conftest.py new file mode 100644 index 0000000..7f30421 --- /dev/null +++ b/tests/project/inspection/conftest.py @@ -0,0 +1,46 @@ +from __future__ import annotations + +from collections.abc import Callable +from pathlib import Path + +import pytest + +from dlc_octopus.schemas.base.resources import ProjectResource +from dlc_octopus.schemas.snapshots import ProjectSnapshot + + +@pytest.fixture +def resources_by_path() -> Callable[ + [ProjectSnapshot], + dict[Path, ProjectResource], +]: + """Return a helper that indexes snapshot resources by project path.""" + + def index( + snapshot: ProjectSnapshot, + ) -> dict[Path, ProjectResource]: + return {resource.project_relative_path: resource for resource in snapshot.resources} + + return index + + +@pytest.fixture +def file_state() -> Callable[ + [Path], + dict[Path, tuple[bytes, int]], +]: + """Return a helper that captures file contents and modification times.""" + + def capture( + project_root: Path, + ) -> dict[Path, tuple[bytes, int]]: + return { + path.relative_to(project_root): ( + path.read_bytes(), + path.stat().st_mtime_ns, + ) + for path in project_root.rglob("*") + if path.is_file() + } + + return capture diff --git a/tests/project/inspection/test_config.py b/tests/project/inspection/test_config.py new file mode 100644 index 0000000..cc347e8 --- /dev/null +++ b/tests/project/inspection/test_config.py @@ -0,0 +1,45 @@ +from pathlib import Path + +import pytest + +from dlc_octopus.api import inspect_project +from dlc_octopus.errors import ( + ConfigUnavailableError, +) + + +def test_valid_config_is_available( + valid_project: Path, +) -> None: + snapshot = inspect_project(valid_project) + + assert snapshot.config.scorer == "test-scorer" + assert snapshot.config_observation is not None + assert snapshot.failed_config is None + assert snapshot.findings == () + + +def test_missing_config_is_distinct_from_failed_config( + tmp_path: Path, +) -> None: + snapshot = inspect_project(tmp_path) + + with pytest.raises(ConfigUnavailableError): + _ = snapshot.config + + assert snapshot.config_observation is None + assert snapshot.failed_config is None + assert "PROJECT_REQUIRED_NODE_MISSING" in {finding.code for finding in snapshot.findings} + + +def test_invalid_config_is_available_only_for_diagnostics( + invalid_project: Path, +) -> None: + snapshot = inspect_project(invalid_project) + + with pytest.raises(ConfigUnavailableError): + _ = snapshot.config + + assert snapshot.failed_config is not None + assert snapshot.failed_config.raw_config is not None + assert any(finding.code == "CONFIG_VALIDATION_ERROR" for finding in snapshot.findings) diff --git a/tests/project/inspection/test_invariants.py b/tests/project/inspection/test_invariants.py new file mode 100644 index 0000000..8c7cadc --- /dev/null +++ b/tests/project/inspection/test_invariants.py @@ -0,0 +1,20 @@ +from collections.abc import Callable +from pathlib import Path + +from dlc_octopus.api import inspect_project + + +def test_inspect_project_does_not_modify_files( + valid_project: Path, + file_state: Callable[ + [Path], + dict[Path, tuple[bytes, int]], + ], +) -> None: + before = file_state(valid_project) + + inspect_project(valid_project) + + after = file_state(valid_project) + + assert after == before diff --git a/tests/project/inspection/test_project_name.py b/tests/project/inspection/test_project_name.py new file mode 100644 index 0000000..3491f3c --- /dev/null +++ b/tests/project/inspection/test_project_name.py @@ -0,0 +1,97 @@ +from __future__ import annotations + +from pathlib import Path + +import pytest +from deeplabcut.core.config.utils import write_config + +from dlc_octopus import api +from dlc_octopus.errors import ConfigUnavailableError + +# DeepLabCut's own example project: examples/openfield-Pranav-2018-10-30, config date "Oct30". +TASK, SCORER, CONFIG_DATE = "openfield", "Pranav", "Oct30" +NAME = "openfield-Pranav-2018-10-30" + + +def _project( + root: Path, + folder: str, + config_data: dict, + *, + project_path: str, + task: str = TASK, + scorer: str = SCORER, + date: str = CONFIG_DATE, +) -> Path: + project = root / folder + (project / "videos").mkdir(parents=True) + (project / "labeled-data").mkdir() + write_config( + project / "config.yaml", + {**config_data, "Task": task, "scorer": scorer, "date": date, "project_path": project_path}, + ) + return project + + +def test_the_name_comes_from_the_folder(tmp_path: Path, valid_config_data: dict) -> None: + project = _project(tmp_path, NAME, valid_config_data, project_path="WILL BE AUTOMATICALLY UPDATED BY DEMO CODE") + + assert api.project_name(api.inspect_project(project)) == NAME + + +def test_a_renamed_folder_has_no_name_whatever_the_config_path_says(tmp_path: Path, valid_config_data: dict) -> None: + project = _project(tmp_path, "horse10", valid_config_data, project_path=rf"C:\Users\lab\{NAME}") + + assert api.project_name(api.inspect_project(project)) is None + + +def test_a_relative_project_root_names_the_inspected_folder_after_a_chdir( + tmp_path: Path, valid_config_data: dict, monkeypatch: pytest.MonkeyPatch +) -> None: + project = _project(tmp_path, NAME, valid_config_data, project_path="placeholder") + same_day_next_year = _project( + tmp_path, "openfield-Pranav-2019-10-30", valid_config_data, project_path="placeholder" + ) + monkeypatch.chdir(project) + snapshots = [api.inspect_project("."), api.inspect_project("config.yaml")] + + monkeypatch.chdir(same_day_next_year) + + assert [api.project_name(snapshot) for snapshot in snapshots] == [NAME, NAME] + + +def test_a_folder_date_that_disagrees_with_the_config_gives_no_name(tmp_path: Path, valid_config_data: dict) -> None: + project = _project(tmp_path, "openfield-Pranav-2018-10-31", valid_config_data, project_path="placeholder") + + assert api.project_name(api.inspect_project(project)) is None + + +@pytest.mark.parametrize( + ("stamp", "config_date"), + [("20181030", "Oct30"), ("2018-02-30", "Feb30")], + ids=["not_dashed", "not_a_calendar_date"], +) +def test_a_folder_stamp_that_is_not_a_date_gives_no_name( + tmp_path: Path, valid_config_data: dict, stamp: str, config_date: str +) -> None: + project = _project( + tmp_path, f"{TASK}-{SCORER}-{stamp}", valid_config_data, project_path="placeholder", date=config_date + ) + + assert api.project_name(api.inspect_project(project)) is None + + +def test_a_hyphenated_task_is_matched_exactly(tmp_path: Path, valid_config_data: dict) -> None: + name = "reaching-task-Linus-2026-10-06" + project = _project( + tmp_path, name, valid_config_data, project_path="placeholder", task="reaching-task", scorer="Linus", date="Oct6" + ) + + assert api.project_name(api.inspect_project(project)) == name + + +def test_a_project_without_a_loaded_config_has_no_canonical_name(invalid_project: Path) -> None: + snapshot = api.inspect_project(invalid_project) + + with pytest.raises(ConfigUnavailableError): + api.project_name(snapshot) diff --git a/tests/project/inspection/test_project_structure.py b/tests/project/inspection/test_project_structure.py new file mode 100644 index 0000000..f8898f3 --- /dev/null +++ b/tests/project/inspection/test_project_structure.py @@ -0,0 +1,43 @@ +from pathlib import Path + +from dlc_octopus.api import inspect_project +from dlc_octopus.schemas.base.finding_codes import ConfigFindingCode, StructureFindingCode + + +def test_inspect_project_includes_missing_required_node_finding( + tmp_path: Path, +) -> None: + snapshot = inspect_project(tmp_path) + finding_codes = {finding.code for finding in snapshot.findings} + + assert "PROJECT_REQUIRED_NODE_MISSING" in finding_codes + assert not any(isinstance(code, ConfigFindingCode) for code in finding_codes) + + +def test_inspect_project_reports_wrong_type( + valid_project: Path, +) -> None: + videos = valid_project / "videos" + videos.rmdir() + videos.write_text( + "not a directory", + encoding="utf-8", + ) + + snapshot = inspect_project(valid_project) + finding = next(finding for finding in snapshot.findings if finding.code == "PROJECT_NODE_WRONG_TYPE") + + assert finding.path == videos + assert finding.evidence["expected_type"] == "directory" + + resource = snapshot.resource_at("videos") + + assert resource is not None + + +def test_valid_project_has_no_structural_findings( + valid_project: Path, +) -> None: + snapshot = inspect_project(valid_project) + + assert not any(isinstance(finding.code, StructureFindingCode) for finding in snapshot.findings) diff --git a/tests/project/inspection/test_resolution.py b/tests/project/inspection/test_resolution.py new file mode 100644 index 0000000..5b97d12 --- /dev/null +++ b/tests/project/inspection/test_resolution.py @@ -0,0 +1,59 @@ +from pathlib import Path + +import pytest + +from dlc_octopus.api import inspect_project +from dlc_octopus.schemas.base.finding_codes import ConfigFindingCode +from dlc_octopus.schemas.snapshots import ( + ConfigState, +) + + +def test_inspect_from_config_matches_inspect_from_root( + valid_project: Path, +) -> None: + from_root = inspect_project(valid_project) + from_config = inspect_project(valid_project / "config.yaml") + + assert from_config == from_root + + +def test_inspect_rejects_existing_non_config_file( + tmp_path: Path, +) -> None: + file_path = tmp_path / "notes.txt" + file_path.write_text( + "notes", + encoding="utf-8", + ) + + with pytest.raises( + ValueError, + match=r"config\.yaml", + ): + inspect_project(file_path) + + +def test_inspect_rejects_missing_project_root( + tmp_path: Path, +) -> None: + missing_root = tmp_path / "missing-project" + + with pytest.raises( + FileNotFoundError, + match="does not exist", + ): + inspect_project(missing_root) + + +def test_missing_config_path_resolves_to_parent( + tmp_path: Path, +) -> None: + snapshot = inspect_project(tmp_path / "config.yaml") + + finding_codes = {finding.code for finding in snapshot.findings} + + assert snapshot.project_root == tmp_path + assert snapshot.config_state == ConfigState.MISSING + assert "PROJECT_REQUIRED_NODE_MISSING" in finding_codes + assert not any(isinstance(code, ConfigFindingCode) for code in finding_codes) diff --git a/tests/project/inspection/test_resources.py b/tests/project/inspection/test_resources.py new file mode 100644 index 0000000..23d0d9f --- /dev/null +++ b/tests/project/inspection/test_resources.py @@ -0,0 +1,35 @@ +from collections.abc import Callable +from pathlib import Path + +from dlc_octopus.api import inspect_project +from dlc_octopus.schemas.base.resources import ( + FileResourceKind, + ProjectResource, + ResourceManagement, +) +from dlc_octopus.schemas.snapshots import ProjectSnapshot + + +def test_napari_metadata_is_known_unmanaged( + valid_project: Path, + resources_by_path: Callable[ + [ProjectSnapshot], + dict[Path, ProjectResource], + ], +) -> None: + dataset = valid_project / "labeled-data" / "session-01" + dataset.mkdir() + + metadata = dataset / ".napari-deeplabcut.json" + metadata.write_text( + "{}", + encoding="utf-8", + ) + + snapshot = inspect_project(valid_project) + resources = resources_by_path(snapshot) + resource = resources[Path("labeled-data/session-01/.napari-deeplabcut.json")] + + assert resource.kind == FileResourceKind.NAPARI_DLC_METADATA + assert resource.management == ResourceManagement.KNOWN_UNMANAGED + assert not any(finding.path == metadata for finding in snapshot.findings) diff --git a/tests/project/inspection/test_scope_query.py b/tests/project/inspection/test_scope_query.py index 3356ec1..7f0272e 100644 --- a/tests/project/inspection/test_scope_query.py +++ b/tests/project/inspection/test_scope_query.py @@ -1,30 +1,181 @@ -# -# 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 re +from pathlib import Path + import pytest -from dlccore.project import api -from dlccore.project.api import helpers -from dlccore.project.schemas.project_layout.labeled_data import LABELED_DATASET, LABELED_FRAME -from dlccore.project.schemas.project_layout.videos import VIDEOS +from dlc_octopus import api +from dlc_octopus.api import helpers +from dlc_octopus.schemas.base.filesystem import NodeSchema +from dlc_octopus.schemas.base.finding_codes import StructureFindingCode +from dlc_octopus.schemas.base.findings import Finding, Reach +from dlc_octopus.schemas.project_layout.labeled_data import LABELED_DATASET, LABELED_FRAME +from dlc_octopus.schemas.project_layout.project import PROJECT_CONFIG +from dlc_octopus.schemas.project_layout.videos import VIDEOS _DS1 = ("labeled-data", "ds1") +def _planted( + schema_id: str, + reach: Reach, + instance: tuple[str, ...] = (), + *, + field_location: tuple[str, ...] = (), + code: StructureFindingCode = StructureFindingCode.PROJECT_NODE_UNREADABLE, +) -> Finding: + return Finding( + code=code, + schema_id=schema_id, + reach=reach, + instance=instance, + field_location=field_location, + evidence=dict.fromkeys(code.evidence_keys, "placeholder"), + ) + + +def _scoped(tmp_path: Path, findings: tuple[Finding, ...], scope: helpers.Scope) -> list[Finding]: + snapshot = api.inspect_project(tmp_path).model_copy(update={"findings": findings}) + + return list(api.findings_in_scope(snapshot, scope)) + + +def _in_scope( + tmp_path: Path, + findings: tuple[Finding, ...], + node: NodeSchema, + within: tuple[str, ...] = (), +) -> list[Finding]: + return _scoped(tmp_path, findings, helpers.Scope(node, within=within)) + + def test_octopus_provides_the_scope_query() -> None: assert hasattr(api, "findings_in_scope") +def test_scope_raises_on_finding_not_declared_by_schema_id(tmp_path: Path) -> None: + """Rather than dropping it.""" + not_found = _planted("dlc.not_declared_anywhere", Reach.ONE_PER_PROJECT) + + with pytest.raises(ValueError, match=re.escape(not_found.schema_id)): + _in_scope(tmp_path, (not_found,), PROJECT_CONFIG) + + +def test_the_scope_holds_the_subtree_and_the_ancestors(tmp_path: Path) -> None: + inside = ( + _planted("dlc.labeled_data.dataset", Reach.ONE_OF, _DS1), + _planted("dlc.labeled_data.frame", Reach.ONE_OF, (*_DS1, "img0.png")), + _planted("dlc.labeled_data", Reach.ONE_PER_PROJECT), + _planted("dlc.project", Reach.ONE_PER_PROJECT), + ) + outside = ( + _planted("dlc.videos.source_video", Reach.ONE_OF, ("videos", "a.mp4")), + _planted("dlc.labeled_data.frame", Reach.ONE_OF, ("labeled-data", "ds2", "img0.png")), + ) + + scoped = _in_scope(tmp_path, inside + outside, LABELED_DATASET, _DS1) + + assert scoped == list(inside) + + +def test_an_unverified_node_depends_on_the_whole_config(tmp_path: Path) -> None: + unused_field = _planted( + "dlc.project.config", + Reach.ONE_PER_PROJECT, + field_location=("video_sets", "/videos/a.mp4"), + ) + + assert _in_scope(tmp_path, (unused_field,), LABELED_DATASET, _DS1) == [unused_field] + + +def test_the_scope_reads_the_location_only(tmp_path: Path) -> None: + # Same locations, different codes, severities and evidence: membership must not change. + unreadable = _planted("dlc.labeled_data.frame", Reach.ONE_OF, (*_DS1, "img0.png")) + wrong_type = _planted( + "dlc.labeled_data.frame", + Reach.ONE_OF, + (*_DS1, "img0.png"), + code=StructureFindingCode.PROJECT_NODE_WRONG_TYPE, + ) + elsewhere = _planted( + "dlc.labeled_data.frame", + Reach.ONE_OF, + ("labeled-data", "ds2", "img0.png"), + code=StructureFindingCode.PROJECT_NODE_WRONG_TYPE, + ) + + assert _in_scope(tmp_path, (unreadable, wrong_type, elsewhere), LABELED_DATASET, _DS1) == [unreadable, wrong_type] + + +def test_an_ancestor_instance_is_in_scope_for_its_own_descendants_only(tmp_path: Path) -> None: + own_dataset = _planted("dlc.labeled_data.dataset", Reach.ONE_OF, _DS1) + other_dataset = _planted("dlc.labeled_data.dataset", Reach.ONE_OF, ("labeled-data", "ds2")) + + scoped = _in_scope(tmp_path, (own_dataset, other_dataset), LABELED_FRAME, (*_DS1, "img0.png")) + + assert scoped == [own_dataset] + + +def test_an_all_of_finding_with_a_shorter_prefix_is_in_scope(tmp_path: Path) -> None: + every_frame = _planted("dlc.labeled_data.frame", Reach.ALL_OF) + every_frame_of_ds1 = _planted("dlc.labeled_data.frame", Reach.ALL_OF, _DS1) + + scoped = _in_scope(tmp_path, (every_frame, every_frame_of_ds1), LABELED_DATASET, _DS1) + + assert scoped == [every_frame, every_frame_of_ds1] + + +def test_another_instance_is_out_of_scope(tmp_path: Path) -> None: + every_frame_of_ds2 = _planted("dlc.labeled_data.frame", Reach.ALL_OF, ("labeled-data", "ds2")) + + assert _in_scope(tmp_path, (every_frame_of_ds2,), LABELED_DATASET, _DS1) == [] + + +def test_a_union_of_scopes_returns_each_finding_once_in_snapshot_order(tmp_path: Path) -> None: + video = _planted("dlc.videos.source_video", Reach.ONE_OF, ("videos", "a.mp4")) + config = _planted("dlc.project.config", Reach.ONE_PER_PROJECT) + frame = _planted("dlc.labeled_data.frame", Reach.ONE_OF, (*_DS1, "img0.png")) + + union = helpers.Scope(LABELED_DATASET, within=_DS1) | helpers.Scope(VIDEOS) + + # The config finding concerns both parts, and comes back once. + assert _scoped(tmp_path, (video, config, frame), union) == [video, config, frame] + + +def test_a_union_of_scopes_only_widens(tmp_path: Path) -> None: + findings = ( + _planted("dlc.videos.source_video", Reach.ONE_OF, ("videos", "a.mp4")), + _planted("dlc.project.config", Reach.ONE_PER_PROJECT), + _planted("dlc.labeled_data.frame", Reach.ONE_OF, (*_DS1, "img0.png")), + _planted("dlc.labeled_data.frame", Reach.ONE_OF, ("labeled-data", "ds2", "img0.png")), + ) + datasets = helpers.Scope(LABELED_DATASET, within=_DS1) + videos = helpers.Scope(VIDEOS) + + combined = _scoped(tmp_path, findings, datasets | videos) + + for part in (datasets, videos): + assert all(finding in combined for finding in _scoped(tmp_path, findings, part)) + + +@pytest.mark.xfail( + reason="field-level dependencies are not declared yet: once a node's config fields are verified against " + "DeepLabCut, a finding on another config field leaves its scope, and a consumer widens by naming fields. " + "When this passes, test_an_unverified_node_depends_on_the_whole_config must move to a node still unverified", + strict=True, + raises=AssertionError, +) +def test_a_verified_node_depends_only_on_its_declared_config_fields(tmp_path: Path) -> None: + video_sets_finding = _planted( + "dlc.project.config", + Reach.ONE_PER_PROJECT, + field_location=("video_sets", "/videos/a.mp4"), + ) + + assert _in_scope(tmp_path, (video_sets_finding,), LABELED_DATASET, _DS1) == [] + + def test_a_scope_covers_the_file_nodes_of_its_subtrees_in_walk_order() -> None: scope = helpers.Scope(VIDEOS) | helpers.Scope(LABELED_DATASET, within=_DS1) diff --git a/tests/project/inspection/test_serialize.py b/tests/project/inspection/test_serialize.py new file mode 100644 index 0000000..db3393d --- /dev/null +++ b/tests/project/inspection/test_serialize.py @@ -0,0 +1,248 @@ +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from pydantic import ValidationError + +from dlc_octopus.api import inspect_project +from dlc_octopus.capabilities import get_project_manager_capabilities +from dlc_octopus.discovery.probe import probe_path +from dlc_octopus.schemas.base.probes import ( + FilesystemEntryKind, + PathProbe, + PathProbeStatus, +) +from dlc_octopus.schemas.base.resources import ( + ProjectResource, + UnknownResourceKind, +) +from dlc_octopus.schemas.snapshots import ( + PROJECT_SNAPSHOT_VERSION, + ProjectSnapshot, +) + +_VERSION_FIELD_NAMES = frozenset({"version", "snapshot_version"}) + +_FINDING_WIRE_KEYS = frozenset( + { + "code", + "severity", + "schema_id", + "reach", + "instance", + "path", + "field_location", + "evidence", + } +) + + +def test_project_snapshot_is_json_serializable( + valid_project: Path, +) -> None: + serialized = inspect_project(valid_project).model_dump_json() + + assert '"project_root"' in serialized + assert '"project"' in serialized + assert '"resources"' in serialized + assert '"config_observation"' in serialized + + +def test_project_snapshot_nodes_include_probe( + valid_project: Path, +) -> None: + serialized = inspect_project(valid_project).model_dump_json() + + assert '"probe"' in serialized + + +def test_runtime_config_is_excluded_from_json( + valid_project: Path, +) -> None: + serialized = inspect_project(valid_project).model_dump_json() + + assert '"config_path"' in serialized + assert '"value"' not in serialized + + +def test_failed_raw_config_is_excluded_from_json( + invalid_project: Path, +) -> None: + serialized = inspect_project(invalid_project).model_dump_json() + + assert '"raw_config"' not in serialized + + +def test_project_snapshot_includes_format_version( + valid_project: Path, +) -> None: + snapshot = inspect_project(valid_project) + + assert snapshot.version == PROJECT_SNAPSHOT_VERSION + assert ( + snapshot.model_dump( + mode="json", + )["version"] + == PROJECT_SNAPSHOT_VERSION + ) + + +def test_project_snapshot_json_includes_format_version( + valid_project: Path, +) -> None: + serialized = inspect_project(valid_project).model_dump_json() + + assert f'"version":"{PROJECT_SNAPSHOT_VERSION}"' in serialized + + +@pytest.mark.xfail( + reason="the snapshot format is 0.x and unstable; bumping is owed once a consumer reads one back", + strict=True, + raises=AssertionError, +) +def test_snapshot_format_version_has_left_zero() -> None: + """The prototype declares no compatibility, and must stop doing so before one is relied on. + + ``0.x`` is accurate while the vocabulary still moves and nothing reads a + stored snapshot. This passes the day the version is raised, which fails the + suite and asks whether the format is now a contract. + """ + + assert not PROJECT_SNAPSHOT_VERSION.startswith("0.") + + +def test_project_snapshot_with_findings_round_trips( + tmp_path: Path, +) -> None: + snapshot = inspect_project(tmp_path) + + assert snapshot.findings + + restored = ProjectSnapshot.model_validate(json.loads(snapshot.model_dump_json())) + + assert restored.findings == snapshot.findings + + +def test_findings_serialize_a_pinned_key_set( + tmp_path: Path, +) -> None: + # Changing this set changes the wire format; once the format has left 0.x, bump PROJECT_SNAPSHOT_VERSION with it. + snapshot = inspect_project(tmp_path) + + assert snapshot.findings + + for finding in snapshot.findings: + assert finding.model_dump(mode="json").keys() == _FINDING_WIRE_KEYS + + +def test_serialized_findings_carry_no_message( + tmp_path: Path, +) -> None: + serialized = inspect_project(tmp_path).model_dump_json() + + assert '"message"' not in serialized + + +def test_project_snapshot_rejects_unknown_format_version( + tmp_path: Path, +) -> None: + payload = inspect_project(tmp_path).model_dump() + payload["version"] = "2.0" + + with pytest.raises(ValidationError) as raised: + ProjectSnapshot.model_validate(payload) + + errors = raised.value.errors() + + assert [error["type"] for error in errors] == ["literal_error"] + assert errors[0]["loc"] == ("version",) + + +def test_an_unknown_resource_kind_round_trips( + valid_project: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """``UnknownResourceKind`` is wire-visible, so it must survive the union on the way back.""" + + (valid_project / "device-node").touch() + + real_probe_path = probe_path + + def fake_probe_path(path: Path) -> PathProbe: + if path.name == "device-node": + return PathProbe( + status=PathProbeStatus.OBSERVED, + entry_kind=FilesystemEntryKind.OTHER, + ) + + return real_probe_path(path) + + monkeypatch.setattr( + "dlc_octopus.discovery.observer.probe_path", + fake_probe_path, + ) + + snapshot = inspect_project(valid_project) + + assert '"unknown"' in snapshot.model_dump_json() + + resource = snapshot.resource_at("device-node") + + assert resource is not None + assert resource.kind is UnknownResourceKind.UNKNOWN + + # The whole snapshot cannot round-trip while the config is excluded; see + # test_project_snapshot_of_a_valid_project_round_trips. + restored = ProjectResource.model_validate_json(resource.model_dump_json()) + + assert restored.kind is UnknownResourceKind.UNKNOWN + + +@pytest.mark.xfail( + reason="a snapshot from a newer catalogue is to be refused by its version before any finding " + "code is resolved; today an unknown code fails resolution alongside the version", + strict=True, + raises=AssertionError, +) +def test_a_newer_catalogue_is_refused_by_version( + tmp_path: Path, +) -> None: + payload = inspect_project(tmp_path).model_dump(mode="json") + payload["version"] = "2.0" + payload["findings"][0]["code"] = "A_CODE_FROM_A_NEWER_CATALOGUE" + + with pytest.raises(ValidationError) as raised: + ProjectSnapshot.model_validate(payload) + + assert [error["loc"] for error in raised.value.errors()] == [("version",)] + + +@pytest.mark.xfail( + reason="the config is excluded to keep `deeplabcut` out of the snapshot read path; " + "it can be carried once the canonical config schema is in dlccore", + strict=True, + raises=ValidationError, +) +def test_project_snapshot_of_a_valid_project_round_trips( + valid_project: Path, +) -> None: + snapshot = inspect_project(valid_project) + + restored = ProjectSnapshot.model_validate(json.loads(snapshot.model_dump_json())) + + assert restored.config_observation == snapshot.config_observation + + +@pytest.mark.owed_before_release( + reason="the snapshot serializes `version` while capabilities advertises `snapshot_version`", + raises=AssertionError, +) +def test_snapshot_and_capabilities_name_the_version_field_alike( + valid_project: Path, +) -> None: + snapshot_fields = _VERSION_FIELD_NAMES & inspect_project(valid_project).model_dump().keys() + capability_fields = _VERSION_FIELD_NAMES & get_project_manager_capabilities().model_dump().keys() + + assert snapshot_fields == capability_fields diff --git a/tests/project/inspection/test_snapshot.py b/tests/project/inspection/test_snapshot.py new file mode 100644 index 0000000..462260a --- /dev/null +++ b/tests/project/inspection/test_snapshot.py @@ -0,0 +1,210 @@ +from collections.abc import Callable +from pathlib import Path + +import pytest + +from dlc_octopus.api import inspect_project +from dlc_octopus.schemas.base.observations import NodeStatus +from dlc_octopus.schemas.base.resources import ( + DirectoryResourceKind, + FileResourceKind, + ProjectResource, +) +from dlc_octopus.schemas.base.validation import ( + ValidationCheck, + ValidationCheckStatus, + ValidationDepth, +) +from dlc_octopus.schemas.snapshots import ConfigState, ProjectSnapshot +from dlc_octopus.validation.results import ValidationResult + + +def test_inspect_project_returns_expected_snapshot( + valid_project: Path, + resources_by_path: Callable[ + [ProjectSnapshot], + dict[Path, ProjectResource], + ], +) -> None: + videos = valid_project / "videos" + dataset = valid_project / "labeled-data" / "session-01" + dataset.mkdir() + + (videos / "session-01.mp4").touch() + (videos / "notes.txt").write_text( + "user notes", + encoding="utf-8", + ) + (dataset / "img001.png").touch() + (dataset / "CollectedData_test-scorer.h5").touch() + + snapshot = inspect_project(valid_project) + resources = resources_by_path(snapshot) + + assert snapshot.project_root == valid_project + assert snapshot.project.status == NodeStatus.PRESENT + assert resources[Path("config.yaml")].kind == FileResourceKind.PROJECT_CONFIG + assert resources[Path("videos/session-01.mp4")].kind == FileResourceKind.SOURCE_VIDEO + assert resources[Path("videos/notes.txt")].kind == FileResourceKind.UNKNOWN_FILE + assert resources[Path("labeled-data/session-01")].kind == DirectoryResourceKind.LABELED_DATASET + + +def test_resources_by_path_indexes_all_resources( + valid_project: Path, +) -> None: + video = valid_project / "videos" / "session-01.mp4" + video.touch() + + snapshot = inspect_project(valid_project) + + assert snapshot.resources_by_path[Path("config.yaml")].kind == FileResourceKind.PROJECT_CONFIG + assert snapshot.resources_by_path[Path("videos/session-01.mp4")].kind == FileResourceKind.SOURCE_VIDEO + + +def test_resources_of_kind_returns_only_requested_kind( + valid_project: Path, +) -> None: + videos = valid_project / "videos" + + (videos / "session-01.mp4").touch() + (videos / "session-02.avi").touch() + (videos / "notes.txt").write_text( + "notes", + encoding="utf-8", + ) + + snapshot = inspect_project(valid_project) + source_videos = snapshot.resources_of_kind(FileResourceKind.SOURCE_VIDEO) + + assert tuple(resource.project_relative_path for resource in source_videos) == ( + Path("videos/session-01.mp4"), + Path("videos/session-02.avi"), + ) + assert all(resource.kind == FileResourceKind.SOURCE_VIDEO for resource in source_videos) + + +def test_resources_of_kind_supports_directory_kinds( + valid_project: Path, +) -> None: + snapshot = inspect_project(valid_project) + + resources = snapshot.resources_of_kind(DirectoryResourceKind.VIDEOS_DIRECTORY) + + assert len(resources) == 1 + assert resources[0].project_relative_path == Path("videos") + + +def test_resources_of_kind_returns_empty_tuple_when_absent( + valid_project: Path, +) -> None: + snapshot = inspect_project(valid_project) + + assert snapshot.resources_of_kind(FileResourceKind.MACHINE_LABELS) == () + + +def test_resource_at_returns_matching_resource( + valid_project: Path, +) -> None: + video = valid_project / "videos" / "session-01.mp4" + video.touch() + + snapshot = inspect_project(valid_project) + + resource = snapshot.resource_at("videos/session-01.mp4") + + assert resource is not None + assert resource.kind == FileResourceKind.SOURCE_VIDEO + + +def test_resource_at_returns_none_when_absent( + valid_project: Path, +) -> None: + snapshot = inspect_project(valid_project) + + assert snapshot.resource_at("videos/missing.mp4") is None + + +def test_valid_config_state( + valid_project: Path, +) -> None: + snapshot = inspect_project(valid_project) + + assert snapshot.config_state == ConfigState.VALID + + +def test_missing_config_state( + tmp_path: Path, +) -> None: + snapshot = inspect_project(tmp_path) + + assert snapshot.config_state == ConfigState.MISSING + + +def test_invalid_config_state( + invalid_project: Path, +) -> None: + snapshot = inspect_project(invalid_project) + + assert snapshot.config_state == ConfigState.INVALID + + +def test_resource_projections_do_not_mutate_snapshot( + valid_project: Path, +) -> None: + snapshot = inspect_project(valid_project) + resources_before = snapshot.resources + + snapshot.resources_of_kind(FileResourceKind.PROJECT_CONFIG) + snapshot.resource_at("config.yaml") + _ = snapshot.resources_by_path + + assert snapshot.resources == resources_before + + +def _check( + code: str, +) -> ValidationCheck: + """Return a completed check carrying one code.""" + + return ValidationCheck( + code=code, + kind=DirectoryResourceKind.VIDEOS_DIRECTORY, + depth=ValidationDepth.FILENAME_ONLY, + status=ValidationCheckStatus.COMPLETED, + message="Checked.", + ) + + +def test_with_validation_result_accumulates_checks_across_calls( + valid_project: Path, +) -> None: + """Checks accumulate as findings do, matching ``ValidationResult.merge``.""" + + snapshot = inspect_project(valid_project) + + merged = snapshot.with_validation_result( + ValidationResult(checks=(_check("FIRST"),)), + ).with_validation_result( + ValidationResult(checks=(_check("SECOND"),)), + ) + + assert tuple(check.code for check in merged.validation_checks) == ( + "FIRST", + "SECOND", + ) + + +@pytest.mark.xfail( + reason="a consumer is to get the resource kind of any schema_id in one call, including for a node missing " + "on disk; resource_at covers only existing entries, by path, and resource_kind in structure evidence is " + "the stop-gap until then. When this passes, drop resource_kind from the structure codes' evidence_keys", + strict=True, + raises=AttributeError, +) +def test_the_kind_of_a_schema_id_is_one_call_away( + tmp_path: Path, +) -> None: + snapshot = inspect_project(tmp_path) + + assert snapshot.resource_at(Path("config.yaml")) is None + assert snapshot.kind_of("dlc.project.config") is FileResourceKind.PROJECT_CONFIG diff --git a/tests/project/inspection/test_validation_error.py b/tests/project/inspection/test_validation_error.py index db65e64..cf4211d 100644 --- a/tests/project/inspection/test_validation_error.py +++ b/tests/project/inspection/test_validation_error.py @@ -1,19 +1,93 @@ -# -# 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 dlccore.project.errors import BLOCKING_SEVERITIES -from dlccore.project.schemas.base.finding_codes import Severity +from pathlib import Path + +import pytest + +from dlc_octopus.api import inspect_project +from dlc_octopus.errors import BLOCKING_SEVERITIES, ProjectValidationError, _blocking_findings +from dlc_octopus.schemas.base.finding_codes import ConfigFindingCode, Severity + +_UNPARSEABLE_CONFIG = "a:\n b: [\n" def test_only_error_blocks() -> None: assert {Severity.ERROR} == BLOCKING_SEVERITIES + + +def test_inspect_project_does_not_raise_without_blocking_findings( + valid_project: Path, +) -> None: + snapshot = inspect_project( + valid_project, + raise_on_validation_error=True, + ) + + assert _blocking_findings(snapshot) == () + + +def test_inspect_project_does_not_raise_unless_asked( + invalid_project: Path, +) -> None: + snapshot = inspect_project(invalid_project) + + assert _blocking_findings(snapshot) + + +def test_inspect_project_raises_on_an_error_finding( + invalid_project: Path, +) -> None: + with pytest.raises(ProjectValidationError) as raised: + inspect_project( + invalid_project, + raise_on_validation_error=True, + ) + + assert ConfigFindingCode.CONFIG_VALIDATION_ERROR in {finding.code for finding in raised.value.findings} + + +def test_inspect_project_raises_on_an_unparseable_config( + tmp_path: Path, +) -> None: + (tmp_path / "config.yaml").write_text( + _UNPARSEABLE_CONFIG, + encoding="utf-8", + ) + + with pytest.raises(ProjectValidationError) as raised: + inspect_project( + tmp_path, + raise_on_validation_error=True, + ) + + codes = {finding.code for finding in raised.value.findings} + + assert ConfigFindingCode.CONFIG_PARSE_FAILED in codes + assert raised.value.findings[0].severity is Severity.ERROR + + +def test_project_validation_error_names_the_blocking_codes( + tmp_path: Path, +) -> None: + (tmp_path / "config.yaml").write_text( + _UNPARSEABLE_CONFIG, + encoding="utf-8", + ) + + with pytest.raises(ProjectValidationError, match="CONFIG_PARSE_FAILED"): + inspect_project( + tmp_path, + raise_on_validation_error=True, + ) + + +def test_project_validation_error_retains_the_snapshot( + invalid_project: Path, +) -> None: + with pytest.raises(ProjectValidationError) as raised: + inspect_project( + invalid_project, + raise_on_validation_error=True, + ) + + assert raised.value.snapshot.project_root == invalid_project diff --git a/tests/project/inspection/test_validation_request.py b/tests/project/inspection/test_validation_request.py new file mode 100644 index 0000000..e81b343 --- /dev/null +++ b/tests/project/inspection/test_validation_request.py @@ -0,0 +1,55 @@ +from pathlib import Path + +import pytest + +from dlc_octopus.api import inspect_project +from dlc_octopus.schemas.base.finding_codes import ConfigFindingCode +from dlc_octopus.schemas.base.resources import ( + DirectoryResourceKind, +) +from dlc_octopus.schemas.base.validation import ( + ValidationDepth, +) +from dlc_octopus.validation import ( + ProjectValidationRequest, + ResourceValidationRequest, +) + + +def test_inspection_without_request_runs_baseline_validation( + tmp_path: Path, +) -> None: + snapshot = inspect_project(tmp_path) + codes = {finding.code for finding in snapshot.findings} + + assert "PROJECT_REQUIRED_NODE_MISSING" in codes + assert not any(isinstance(code, ConfigFindingCode) for code in codes) + assert snapshot.validation_checks == () + + +def test_unregistered_resource_validation_is_rejected( + valid_project: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setattr( + "dlc_octopus.validation.project.get_validator_registration", + lambda _kind: None, + ) + + request = ProjectValidationRequest( + resources=( + ResourceValidationRequest( + kind=DirectoryResourceKind.VIDEOS_DIRECTORY, + depth=ValidationDepth.FILENAME_ONLY, + ), + ) + ) + + with pytest.raises( + ValueError, + match="No validator is available for resource kind", + ): + inspect_project( + valid_project, + validation=request, + ) diff --git a/tests/project/schemas/test_labeled_data_layout.py b/tests/project/schemas/test_labeled_data_layout.py new file mode 100644 index 0000000..d4396ac --- /dev/null +++ b/tests/project/schemas/test_labeled_data_layout.py @@ -0,0 +1,76 @@ +from pathlib import Path + +import pytest + +from dlc_octopus.api import inspect_project +from dlc_octopus.schemas.base.resources import FileResourceKind + + +def _kinds_in_a_dataset(project_root: Path, names: tuple[str, ...]) -> dict[str, FileResourceKind]: + dataset = project_root / "labeled-data" / "session-01" + dataset.mkdir() + for name in names: + (dataset / name).touch() + + resources = inspect_project(project_root).resources_by_path + + return {name: resources[Path("labeled-data/session-01") / name].kind for name in names} + + +@pytest.mark.parametrize( + "name", + [ + # DeepLabCut v3.0.2 extract_outlier_frames and the tracklet toolbox; napari-deeplabcut v0.4.0 ui/cropping.py. + "machinelabels-iter0.h5", + "machinelabels-iter12.h5", + # DeepLabCut v3.0.2 extract_outlier_frames and the tracklet toolbox, beside the H5. + "machinelabels.csv", + ], +) +def test_a_machine_labels_file_a_producer_writes_is_discovered(valid_project: Path, name: str) -> None: + assert _kinds_in_a_dataset(valid_project, (name,)) == {name: FileResourceKind.MACHINE_LABELS} + + +def test_machine_and_human_labels_are_told_apart_in_one_dataset(valid_project: Path) -> None: + kinds = _kinds_in_a_dataset( + valid_project, ("CollectedData_me.h5", "CollectedData_me.csv", "machinelabels-iter0.h5", "machinelabels.csv") + ) + + assert kinds == { + "CollectedData_me.h5": FileResourceKind.HUMAN_LABELS, + "CollectedData_me.csv": FileResourceKind.HUMAN_LABELS, + "machinelabels-iter0.h5": FileResourceKind.MACHINE_LABELS, + "machinelabels.csv": FileResourceKind.MACHINE_LABELS, + } + + +@pytest.mark.parametrize( + "name", + [ + # napari-deeplabcut v0.4.0 opens any case (core/discovery.py); no producer writes it. + "MachineLabels-iter0.h5", + # DeepLabCut v3.0.2 merge_datasets checks it exists; nothing in DeepLabCut's history writes it. + "MachineLabelsRefine.h5", + "machinelabels-iter0.csv", + ], +) +def test_a_machine_labels_name_no_producer_writes_is_not_machine_labels(valid_project: Path, name: str) -> None: + assert _kinds_in_a_dataset(valid_project, (name,)) == {name: FileResourceKind.UNKNOWN_FILE} + + +def test_a_non_numeric_iteration_is_still_machine_labels(valid_project: Path) -> None: + """The prefix does not check that the iteration is a number; no producer writes one that is not.""" + + name = "machinelabels-iterX.h5" + + assert _kinds_in_a_dataset(valid_project, (name,)) == {name: FileResourceKind.MACHINE_LABELS} + + +@pytest.mark.parametrize( + "name", + ["CollectedData_me - Copy.csv", "CollectedData_me.h5.bak_20260410_101324.h5", "CollectedData_someone-else.h5"], +) +def test_a_copy_backup_or_other_scorer_is_still_human_labels(valid_project: Path, name: str) -> None: + """The layout cannot know the config's scorer; telling these apart is owed to validation.""" + + assert _kinds_in_a_dataset(valid_project, (name,)) == {name: FileResourceKind.HUMAN_LABELS} diff --git a/tests/project/schemas/test_schema_id.py b/tests/project/schemas/test_schema_id.py index 689f49a..55621bc 100644 --- a/tests/project/schemas/test_schema_id.py +++ b/tests/project/schemas/test_schema_id.py @@ -1,21 +1,13 @@ -# -# 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 json + import pytest from pydantic import ValidationError -from dlccore.project.schemas.base.filesystem import FileSchema, NamePattern -from dlccore.project.schemas.base.resources import FileResourceKind +from dlc_octopus.capabilities import get_project_manager_capabilities +from dlc_octopus.schemas.base.filesystem import FileSchema, NamePattern +from dlc_octopus.schemas.base.resources import FileResourceKind def _file_schema(schema_id: str) -> FileSchema: @@ -31,3 +23,9 @@ def test_a_malformed_schema_id_is_refused_where_it_is_declared(schema_id: str) - 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" + + +def test_a_schema_id_serializes_as_a_plain_string() -> None: + layout = json.loads(get_project_manager_capabilities().model_dump_json())["layout"] + + assert layout["schema_id"] == "dlc.project" diff --git a/tests/project/test_capabilities.py b/tests/project/test_capabilities.py new file mode 100644 index 0000000..4842c0b --- /dev/null +++ b/tests/project/test_capabilities.py @@ -0,0 +1,148 @@ +from __future__ import annotations + +import pytest + +from dlc_octopus.capabilities import ( + get_project_manager_capabilities, +) +from dlc_octopus.schemas.base.resources import ( + DirectoryResourceKind, +) +from dlc_octopus.schemas.base.validation import ( + ValidationDepth, +) +from dlc_octopus.schemas.capabilities import LayoutCapability +from dlc_octopus.schemas.snapshots import ( + PROJECT_SNAPSHOT_VERSION, + ProjectSnapshot, +) +from dlc_octopus.validation.context import ( + ValidationContext, +) +from dlc_octopus.validation.registry import ( + ValidatorRegistration, +) +from dlc_octopus.validation.results import ( + ValidationResult, +) + + +def test_capabilities_include_snapshot_version() -> None: + capabilities = get_project_manager_capabilities() + + assert capabilities.snapshot_version == PROJECT_SNAPSHOT_VERSION + + +def test_capabilities_advertise_config_validation_as_baseline() -> None: + capabilities = get_project_manager_capabilities() + + codes = {baseline.code for baseline in capabilities.baseline_validations} + + assert "PROJECT_CONFIG_VALIDATION" in codes + + +def test_capabilities_describe_declared_layout() -> None: + capabilities = get_project_manager_capabilities() + + assert capabilities.layout.kind == DirectoryResourceKind.PROJECT_ROOT + + child_kinds = {child.kind for child in capabilities.layout.children} + + assert DirectoryResourceKind.VIDEOS_DIRECTORY in child_kinds + assert DirectoryResourceKind.LABELED_DATA_DIRECTORY in child_kinds + + +def test_capabilities_mark_repeated_layout_nodes() -> None: + capabilities = get_project_manager_capabilities() + + labeled_data = next( + child for child in capabilities.layout.children if child.kind == DirectoryResourceKind.LABELED_DATA_DIRECTORY + ) + + assert any( + child.repeated and child.kind == DirectoryResourceKind.LABELED_DATASET for child in labeled_data.children + ) + + +def test_capabilities_derive_validation_depths_from_registry( + monkeypatch: pytest.MonkeyPatch, +) -> None: + def validator( + snapshot: ProjectSnapshot, + context: ValidationContext | None, + depth: ValidationDepth, + ) -> ValidationResult: + del snapshot, context, depth + + return ValidationResult() + + registration = ValidatorRegistration( + code="TEST_ONLY_DONOTUSE", + validator=validator, + supported_depths=(ValidationDepth.FILENAME_ONLY,), + ) + + monkeypatch.setattr( + "dlc_octopus.capabilities.iter_validator_registrations", + lambda: ( + ( + DirectoryResourceKind.VIDEOS_DIRECTORY, + registration, + ), + ), + ) + + capabilities = get_project_manager_capabilities() + + assert len(capabilities.validations) == 1 + assert capabilities.validations[0].kind == (DirectoryResourceKind.VIDEOS_DIRECTORY) + assert capabilities.validations[0].supported_depths == (ValidationDepth.FILENAME_ONLY,) + + +def test_capabilities_are_json_serializable() -> None: + capabilities = get_project_manager_capabilities() + + serialized = capabilities.model_dump_json() + + assert '"snapshot_version"' in serialized + assert '"layout"' in serialized + assert '"validations"' in serialized + + +def _published_schema_ids(node: LayoutCapability) -> set[str]: + """Return every schema_id the published layout declares.""" + + ids = {node.schema_id} + + for child in node.children: + ids |= _published_schema_ids(child) + + return ids + + +@pytest.mark.xfail( + reason="a training-dataset shuffle is a logical layout node with no resource kind, keyed by " + "(train_percent, shuffle_index), so shuffle findings take it as their schema_id rather than their dataset; " + "due with Stack B's training-data work, which observes shuffles outside the tree today", + strict=True, + raises=AssertionError, +) +def test_a_training_shuffle_is_a_published_logical_node() -> None: + layout = get_project_manager_capabilities().layout + + assert "dlc.training_data.dataset.shuffle" in _published_schema_ids(layout) + + +def test_capabilities_flag_nodes_inside_a_repeated_node() -> None: + flags: dict[str, bool] = {} + pending = [get_project_manager_capabilities().layout] + + while pending: + node = pending.pop() + flags[node.schema_id] = node.inside_repeated + pending.extend(node.children) + + assert flags["dlc.project.config"] is False + assert flags["dlc.videos.source_video"] is True + assert flags["dlc.labeled_data.dataset"] is True + assert flags["dlc.labeled_data.napari_metadata"] is True diff --git a/tests/project/validation/deeplabcut/test_labeled_data.py b/tests/project/validation/deeplabcut/test_labeled_data.py new file mode 100644 index 0000000..7afac38 --- /dev/null +++ b/tests/project/validation/deeplabcut/test_labeled_data.py @@ -0,0 +1,47 @@ +from __future__ import annotations + +from pathlib import Path + +import pytest + +from dlc_octopus.api import inspect_project +from dlc_octopus.schemas.base.resources import DirectoryResourceKind +from dlc_octopus.schemas.base.validation import ValidationDepth +from dlc_octopus.validation import ProjectValidationRequest, ResourceValidationRequest + + +@pytest.mark.xfail( + reason="Human labels are CollectedData_.h5 and .csv only, as DeepLabCut reads them; the layout " + "cannot know the scorer, so a copy, a backup or another scorer's file is discovered as human labels and is " + "to be a finding at that file. No labeled-data suite is registered yet, so requesting one raises", + strict=True, + raises=(ValueError, AssertionError), +) +def test_a_collected_data_file_not_named_for_the_config_scorer_is_reported(valid_project: Path) -> None: + """Both extra names were found in real projects, beside the pair DeepLabCut wrote.""" + + dataset = valid_project / "labeled-data" / "session-01" + dataset.mkdir() + labels = ("CollectedData_test-scorer.h5", "CollectedData_test-scorer.csv") + extras = ( + "CollectedData_test-scorer - Copy.csv", + "CollectedData_test-scorer.h5.bak_20260410_101324.h5", + "CollectedData_someone-else.h5", + ) + for name in labels + extras: + (dataset / name).touch() + + snapshot = inspect_project( + valid_project, + validation=ProjectValidationRequest( + resources=( + ResourceValidationRequest( + kind=DirectoryResourceKind.LABELED_DATA_DIRECTORY, depth=ValidationDepth.FILENAME_ONLY + ), + ) + ), + ) + + assert sorted( + finding.instance[-1] for finding in snapshot.findings if finding.schema_id == "dlc.labeled_data.human_labels" + ) == sorted(extras) diff --git a/tests/project/validation/deeplabcut/test_project_path.py b/tests/project/validation/deeplabcut/test_project_path.py new file mode 100644 index 0000000..b879d20 --- /dev/null +++ b/tests/project/validation/deeplabcut/test_project_path.py @@ -0,0 +1,316 @@ +from __future__ import annotations + +import ctypes +import os +import sys +from collections.abc import Callable +from pathlib import Path + +import pytest +from deeplabcut.core.config.utils import read_config, write_config + +from dlc_octopus.api import inspect_project +from dlc_octopus.schemas.base.finding_codes import ConfigFindingCode +from dlc_octopus.schemas.base.findings import Severity +from dlc_octopus.schemas.base.probes import PathProbe, PathProbeStatus +from dlc_octopus.validation.context import ( + build_validation_context, +) +from dlc_octopus.validation.deeplabcut import project_path as project_path_module +from dlc_octopus.validation.deeplabcut.project_path import ( + validate_project_path, +) + + +def test_matching_project_path_has_no_finding( + valid_project: Path, +) -> None: + snapshot = inspect_project(valid_project) + context = build_validation_context(snapshot) + + assert context is not None + assert validate_project_path(context) == () + + +def test_mismatched_project_path_produces_note( + tmp_path: Path, + valid_config_data: dict, +) -> None: + (tmp_path / "videos").mkdir() + (tmp_path / "labeled-data").mkdir() + + declared_path = tmp_path / "declared-elsewhere" + + config_data = dict(valid_config_data) + config_data["project_path"] = str(declared_path) + + write_config( + tmp_path / "config.yaml", + config_data, + ) + + snapshot = inspect_project(tmp_path) + + finding = next(finding for finding in snapshot.findings if finding.code == "CONFIG_PROJECT_PATH_MISMATCH") + + assert finding.severity == Severity.NOTE + assert finding.schema_id == "dlc.project.config" + assert finding.path == tmp_path / "config.yaml" + assert finding.field_location == ("project_path",) + assert finding.evidence == { + "declared_project_path": str(declared_path.absolute()), + "observed_project_root": str(tmp_path.absolute()), + "declared_path_probe": "missing", + "error_type": None, + "error_message": None, + } + + +def test_inspecting_a_moved_project_leaves_its_config_untouched( + tmp_path: Path, + valid_config_data: dict, +) -> None: + """Octopus never repairs, although DeepLabCut's own reader rewrites this config on read.""" + + (tmp_path / "videos").mkdir() + (tmp_path / "labeled-data").mkdir() + + config_path = tmp_path / "config.yaml" + config_data = dict(valid_config_data) + config_data["project_path"] = str(tmp_path / "declared-elsewhere") + + write_config( + config_path, + config_data, + ) + + before = config_path.read_bytes() + + inspect_project(tmp_path) + + assert config_path.read_bytes() == before + + # Positive control: the scenario is one that DeepLabCut's reader repairs by writing. + read_config(config_path) + + assert config_path.read_bytes() != before + + +_ABSENT = object() + + +def _project_with_declared_path( + root: Path, + config_data: dict, + declared: object, +) -> Path: + (root / "videos").mkdir(parents=True) + (root / "labeled-data").mkdir() + + config_data = dict(config_data) + + if declared is _ABSENT: + del config_data["project_path"] + else: + config_data["project_path"] = declared + + write_config(root / "config.yaml", config_data) + + return root + + +def _project_path_findings(project: Path) -> list: + return [finding for finding in inspect_project(project).findings if finding.field_location == ("project_path",)] + + +@pytest.mark.parametrize( + ("declared", "reported"), + [ + (_ABSENT, None), + (None, None), + ("", None), + (".", "."), + ("mouse-project", "mouse-project"), + ("C:mouse-project", "C:mouse-project"), + ("\\mouse-project", "\\mouse-project"), + ], + ids=["absent", "null", "empty", "dot", "relative", "drive-relative", "root-relative"], +) +def test_a_project_path_naming_no_location_is_reported_as_not_absolute( + tmp_path: Path, + valid_config_data: dict, + declared: object, + reported: str | None, +) -> None: + project = _project_with_declared_path(tmp_path, valid_config_data, declared) + + finding = next( + finding + for finding in inspect_project(project).findings + if finding.code == ConfigFindingCode.CONFIG_PROJECT_PATH_NOT_ABSOLUTE + ) + + assert finding.severity == Severity.NOTE + assert finding.field_location == ("project_path",) + assert finding.evidence == {"declared_project_path": reported} + assert not any( + finding.code == ConfigFindingCode.CONFIG_PROJECT_PATH_MISMATCH for finding in inspect_project(project).findings + ) + + +@pytest.mark.parametrize("declared", [_ABSENT, "."], ids=["absent", "dot"]) +def test_project_path_findings_do_not_depend_on_the_working_directory( + tmp_path: Path, + valid_config_data: dict, + monkeypatch: pytest.MonkeyPatch, + declared: object, +) -> None: + project = _project_with_declared_path(tmp_path / "project", valid_config_data, declared) + elsewhere = tmp_path / "elsewhere" + elsewhere.mkdir() + + monkeypatch.chdir(project) + from_root = _project_path_findings(project) + monkeypatch.chdir(elsewhere) + from_elsewhere = _project_path_findings(project) + + # Positive control: the condition is reported at all, so equality is not two empty lists. + assert from_root + assert [(f.code, f.evidence) for f in from_root] == [(f.code, f.evidence) for f in from_elsewhere] + + +@pytest.mark.parametrize( + "declared", + ["/home/someone/mouse-project", "D:/data/mouse-project"], + ids=["posix", "windows-drive"], +) +def test_an_absolute_project_path_from_either_platform_is_compared( + tmp_path: Path, + valid_config_data: dict, + declared: str, +) -> None: + project = _project_with_declared_path(tmp_path, valid_config_data, declared) + + (finding,) = _project_path_findings(project) + + assert finding.code == ConfigFindingCode.CONFIG_PROJECT_PATH_MISMATCH + assert finding.evidence["declared_project_path"] == declared + + +def test_a_path_absolute_only_on_another_platform_is_not_probed( + tmp_path: Path, + valid_config_data: dict, + monkeypatch: pytest.MonkeyPatch, +) -> None: + declared = "/home/someone/mouse-project" if sys.platform == "win32" else "D:/data/mouse-project" + project = _project_with_declared_path(tmp_path / "project", valid_config_data, declared) + # On POSIX, a probe would resolve the declared path here and find this directory. + elsewhere = tmp_path / "elsewhere" + (elsewhere / declared.lstrip("/")).mkdir(parents=True) + monkeypatch.chdir(elsewhere) + + (finding,) = _project_path_findings(project) + + assert finding.code == ConfigFindingCode.CONFIG_PROJECT_PATH_MISMATCH + assert ( + finding.evidence["declared_path_probe"], + finding.evidence["error_type"], + finding.evidence["error_message"], + ) == (None, None, None) + + +def test_a_project_declared_through_a_linked_parent_matches( + tmp_path: Path, + valid_config_data: dict, + create_symlink_or_skip: Callable[..., None], +) -> None: + """``project_path`` names the project through a linked parent folder; the project is inspected by its real path.""" + + real = tmp_path / "real" + real.mkdir() + create_symlink_or_skip(tmp_path / "alias", real, target_is_directory=True) + project = _project_with_declared_path(real / "project", valid_config_data, str(tmp_path / "alias" / "project")) + + assert _project_path_findings(project) == [] + + +@pytest.mark.skipif(sys.platform != "win32", reason="8.3 short names exist only on Windows") +def test_a_project_declared_by_its_windows_short_name_matches( + tmp_path: Path, + valid_config_data: dict, +) -> None: + project = tmp_path / "long project name" + buffer = ctypes.create_unicode_buffer(1024) + project.mkdir() + ctypes.windll.kernel32.GetShortPathNameW(str(project), buffer, len(buffer)) + + if Path(buffer.value).name == project.name: + pytest.skip("8.3 short names are disabled on this volume") + + _project_with_declared_path(project, valid_config_data, buffer.value) + + assert _project_path_findings(project) == [] + + +def test_a_copied_project_whose_original_still_exists_is_a_mismatch( + tmp_path: Path, + valid_config_data: dict, +) -> None: + original = tmp_path / "original" + original.mkdir() + copy = _project_with_declared_path(tmp_path / "copy", valid_config_data, str(original)) + + (finding,) = _project_path_findings(copy) + + assert finding.code == ConfigFindingCode.CONFIG_PROJECT_PATH_MISMATCH + assert finding.evidence["declared_path_probe"] == "observed" + + +def test_an_inaccessible_declared_path_is_reported_with_its_error( + tmp_path: Path, + valid_config_data: dict, + monkeypatch: pytest.MonkeyPatch, +) -> None: + project = _project_with_declared_path(tmp_path, valid_config_data, "//unreachable-server/share/mouse-project") + inaccessible = PathProbe( + status=PathProbeStatus.INACCESSIBLE, + error_type="PermissionError", + error_message="access denied", + ) + monkeypatch.setattr(project_path_module, "probe_path", lambda _path: inaccessible) + + (finding,) = _project_path_findings(project) + + assert finding.code == ConfigFindingCode.CONFIG_PROJECT_PATH_MISMATCH + assert finding.evidence["declared_path_probe"] == "inaccessible" + assert finding.evidence["error_type"] == "PermissionError" + assert finding.evidence["error_message"] == "access denied" + + +def test_an_existing_declared_path_that_cannot_be_compared_keeps_the_error( + tmp_path: Path, + valid_config_data: dict, + monkeypatch: pytest.MonkeyPatch, +) -> None: + original = tmp_path / "original" + original.mkdir() + copy = _project_with_declared_path(tmp_path / "copy", valid_config_data, str(original)) + + def uncomparable(*_paths: object) -> bool: + raise OSError("target vanished") + + monkeypatch.setattr(os.path, "samefile", uncomparable) + + (finding,) = _project_path_findings(copy) + + assert finding.evidence["declared_path_probe"] == "observed" + assert finding.evidence["error_type"] == "OSError" + assert finding.evidence["error_message"] == "target vanished" + + +def test_invalid_config_skips_project_path_validation( + invalid_project: Path, +) -> None: + snapshot = inspect_project(invalid_project) + + assert not any(finding.code == "CONFIG_PROJECT_PATH_MISMATCH" for finding in snapshot.findings) diff --git a/tests/project/validation/deeplabcut/test_videos.py b/tests/project/validation/deeplabcut/test_videos.py new file mode 100644 index 0000000..080c334 --- /dev/null +++ b/tests/project/validation/deeplabcut/test_videos.py @@ -0,0 +1,824 @@ +from __future__ import annotations + +from collections.abc import Callable +from pathlib import Path + +import pytest +from deeplabcut.core.config.utils import ( + read_config_as_dict, + write_config, +) + +from dlc_octopus.api import inspect_project +from dlc_octopus.discovery.probe import probe_path +from dlc_octopus.schemas.base.findings import Reach, Severity +from dlc_octopus.schemas.base.probes import ( + FilesystemEntryKind, + PathProbe, + PathProbeStatus, +) +from dlc_octopus.schemas.base.resources import ( + DirectoryResourceKind, +) +from dlc_octopus.schemas.base.symlinks import ( + SymlinkObservation, + SymlinkTargetKind, +) +from dlc_octopus.schemas.base.validation import ( + ValidationCheckStatus, + ValidationDepth, +) +from dlc_octopus.validation import ( + ProjectValidationRequest, + ResourceValidationRequest, +) +from dlc_octopus.validation.deeplabcut import videos + +pytestmark = pytest.mark.data_validator("VIDEOS") + + +def video_filename_request() -> ProjectValidationRequest: + """Request lightweight validation for the videos area.""" + + return ProjectValidationRequest( + resources=( + ResourceValidationRequest( + kind=DirectoryResourceKind.VIDEOS_DIRECTORY, + depth=ValidationDepth.FILENAME_ONLY, + ), + ) + ) + + +def set_configured_videos( + project_root: Path, + video_paths: tuple[Path, ...], +) -> None: + """Replace video_sets in a canonical test config.""" + + config_path = project_root / "config.yaml" + config = read_config_as_dict(config_path) + + config["video_sets"] = {str(video_path): {} for video_path in video_paths} + + write_config( + config_path, + config, + ) + + +def _symlink_probe( + target: Path, + target_kind: SymlinkTargetKind, +) -> Callable[[Path], PathProbe]: + """Return a ``probe_path`` replacement reporting one symlink observation. + + Lets the symlink branches be covered where the platform withholds the + privilege needed to create a real link. + """ + + def fake_probe_path(_path: Path) -> PathProbe: + return PathProbe( + status=PathProbeStatus.OBSERVED, + entry_kind=FilesystemEntryKind.SYMLINK, + symlink=SymlinkObservation( + raw_target=target, + absolute_target=target.absolute(), + target_kind=target_kind, + ), + ) + + return fake_probe_path + + +def test_configured_videos_present_completes_without_findings( + valid_project: Path, +) -> None: + video_path = valid_project / "videos" / "session-01.mp4" + video_path.touch() + + set_configured_videos( + valid_project, + (video_path,), + ) + + snapshot = inspect_project( + valid_project, + validation=video_filename_request(), + ) + + video_findings = tuple( + finding for finding in snapshot.findings if finding.code.startswith("CONFIGURED_VIDEO_PATH_") + ) + + assert video_findings == () + assert len(snapshot.validation_checks) == 1 + + check = snapshot.validation_checks[0] + + assert check.code == "VIDEO_FILENAME_VALIDATION" + assert check.status == ValidationCheckStatus.COMPLETED + + +def test_missing_configured_video_produces_finding( + valid_project: Path, +) -> None: + missing_video = valid_project / "videos" / "missing.mp4" + + set_configured_videos( + valid_project, + (missing_video,), + ) + + snapshot = inspect_project( + valid_project, + validation=video_filename_request(), + ) + + finding = next(finding for finding in snapshot.findings if finding.code == "CONFIGURED_VIDEO_PATH_MISSING") + + assert finding.schema_id == "dlc.project.config" + assert finding.instance == () + assert finding.path == missing_video + assert finding.field_location == ( + "video_sets", + str(missing_video), + ) + assert finding.evidence == {} + assert snapshot.validation_checks[0].status == ValidationCheckStatus.COMPLETED + + +def test_keys_under_a_vanished_root_are_one_finding_not_one_per_video( + valid_project: Path, + tmp_path: Path, +) -> None: + vanished_root = tmp_path / "vanished-root" + names = ("session-01.mp4", "session-02.mp4") + + for name in names: + (valid_project / "videos" / name).touch() + + set_configured_videos( + valid_project, + tuple(vanished_root / "videos" / name for name in names), + ) + + snapshot = inspect_project( + valid_project, + validation=video_filename_request(), + ) + + assert snapshot.validation_checks[0].status == ValidationCheckStatus.COMPLETED + assert [finding for finding in snapshot.findings if finding.code == "CONFIGURED_VIDEO_PATH_MISSING"] == [] + + (finding,) = snapshot.findings + + assert finding.code == "CONFIGURED_VIDEOS_UNDER_MISSING_ROOT" + assert finding.severity == Severity.WARNING + assert (finding.schema_id, finding.reach, finding.field_location) == ( + "dlc.project.config", + Reach.ONE_PER_PROJECT, + ("video_sets",), + ) + assert finding.evidence == { + "declared_paths": [str(vanished_root / "videos" / name) for name in names], + "matched_paths": [f"videos/{name}" for name in names], + } + + +def test_a_key_written_with_backslashes_still_names_its_video( + valid_project: Path, +) -> None: + """A Windows-written key read on Linux is one path segment there; it still matches by name.""" + + (valid_project / "videos" / "session-01.mp4").touch() + key = r"Z:\vanished-root\videos\session-01.mp4" + + set_configured_videos(valid_project, (Path(key),)) + + snapshot = inspect_project(valid_project, validation=video_filename_request()) + + (finding,) = snapshot.findings + + assert finding.code == "CONFIGURED_VIDEOS_UNDER_MISSING_ROOT" + assert finding.evidence["declared_paths"] == [key] + + +def test_a_key_into_another_copy_of_the_project_is_reported( + valid_project: Path, + tmp_path: Path, +) -> None: + (valid_project / "videos" / "session-01.mp4").write_bytes(b"here") + other = tmp_path / "other-copy" / "videos" / "session-01.mp4" + other.parent.mkdir(parents=True) + other.write_bytes(b"there") + + set_configured_videos(valid_project, (other,)) + + snapshot = inspect_project(valid_project, validation=video_filename_request()) + + (finding,) = snapshot.findings + + assert finding.code == "CONFIGURED_VIDEO_IN_OTHER_COPY" + assert finding.severity == Severity.WARNING + assert finding.field_location == ("video_sets", str(other)) + assert finding.path == other.absolute() + assert finding.evidence == {"matched_path": "videos/session-01.mp4"} + + +def test_a_key_to_a_file_with_nothing_in_videos_is_outside_the_project( + valid_project: Path, + tmp_path: Path, +) -> None: + outside = tmp_path / "raw-data" / "session-01.mp4" + outside.parent.mkdir() + outside.touch() + + set_configured_videos(valid_project, (outside,)) + + snapshot = inspect_project(valid_project, validation=video_filename_request()) + + (finding,) = snapshot.findings + + assert finding.code == "CONFIGURED_VIDEO_OUTSIDE_PROJECT" + assert finding.severity == Severity.ERROR + assert finding.field_location == ("video_sets", str(outside)) + + +def test_a_video_no_key_matches_is_reported_at_that_video( + valid_project: Path, +) -> None: + declared = valid_project / "videos" / "session-01.mp4" + declared.touch() + (valid_project / "videos" / "session-02.mp4").touch() + + set_configured_videos(valid_project, (declared,)) + + snapshot = inspect_project(valid_project, validation=video_filename_request()) + + (finding,) = snapshot.findings + + assert finding.code == "VIDEO_NOT_IN_VIDEO_SETS" + assert finding.severity == Severity.NOTE + assert (finding.schema_id, finding.reach, finding.instance) == ( + "dlc.videos.source_video", + Reach.ONE_OF, + ("videos", "session-02.mp4"), + ) + + +@pytest.mark.xfail( + reason="DeepLabCut builds a training set from the stems of video_sets keys " + "(merge_annotateddatasets, v3.0.2), so a labeled dataset no key's stem names is left out of training " + "silently whenever any key matches; it is to be a finding at that dataset. No labeled-data suite is " + "registered yet, so requesting one raises", + strict=True, + raises=(ValueError, AssertionError), +) +def test_a_labeled_dataset_no_key_names_is_reported( + valid_project: Path, +) -> None: + declared = valid_project / "videos" / "session-01.mp4" + declared.touch() + + for stem in ("session-01", "session-07"): + dataset = valid_project / "labeled-data" / stem + dataset.mkdir() + (dataset / "CollectedData_test-scorer.h5").touch() + + set_configured_videos(valid_project, (declared,)) + + snapshot = inspect_project( + valid_project, + validation=ProjectValidationRequest( + resources=tuple( + ResourceValidationRequest(kind=kind, depth=ValidationDepth.FILENAME_ONLY) + for kind in (DirectoryResourceKind.VIDEOS_DIRECTORY, DirectoryResourceKind.LABELED_DATA_DIRECTORY) + ) + ), + ) + + assert [ + (finding.schema_id, finding.reach, finding.instance) + for finding in snapshot.findings + if finding.instance[:2] == ("labeled-data", "session-07") + ] == [("dlc.labeled_data.dataset", Reach.ONE_OF, ("labeled-data", "session-07"))] + + +def test_the_demo_placeholder_key_is_reported_missing_not_raised( + valid_project: Path, +) -> None: + placeholder = "WILL BE AUTOMATICALLY UPDATED BY DEMO CODE" + + set_configured_videos(valid_project, (Path(placeholder),)) + + snapshot = inspect_project(valid_project, validation=video_filename_request()) + + (finding,) = snapshot.findings + + assert snapshot.validation_checks[0].status == ValidationCheckStatus.COMPLETED + assert finding.code == "CONFIGURED_VIDEO_PATH_MISSING" + assert finding.field_location == ("video_sets", placeholder) + + +def test_a_broken_link_in_videos_is_reported_once( + valid_project: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """The structure finding at the video stands; the key adds no second one. + + The file exists so discovery lists it; both probes are faked as a broken link. + """ + + link = valid_project / "videos" / "session-01.mp4" + link.touch() + broken = _symlink_probe(valid_project / "gone.mp4", SymlinkTargetKind.MISSING) + real_probe_path = probe_path + + def fake_probe_path(path: Path) -> PathProbe: + return broken(path) if path.name == link.name else real_probe_path(path) + + monkeypatch.setattr("dlc_octopus.discovery.observer.probe_path", fake_probe_path) + monkeypatch.setattr(videos, "probe_path", fake_probe_path) + set_configured_videos(valid_project, (link,)) + + snapshot = inspect_project(valid_project, validation=video_filename_request()) + + assert [finding.code for finding in snapshot.findings] == ["PROJECT_SYMLINK_TARGET_MISSING"] + + +def test_a_resolved_path_never_reaches_a_finding( + valid_project: Path, + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """On Windows with an SMB-mounted drive, ``Path.resolve`` returns ``\\\\?\\Volume{GUID}\\...``.""" + + for name in ("session-01.mp4", "session-02.mp4", "session-03.mp4", "session-04.mp4"): + (valid_project / "videos" / name).write_bytes(name.encode()) + + other = tmp_path / "other-copy" / "videos" / "session-03.mp4" + outside = tmp_path / "raw-data" / "session-05.mp4" + + for path in (other, outside): + path.parent.mkdir(parents=True) + path.touch() + + set_configured_videos( + valid_project, + ( + valid_project / "videos" / "session-01.mp4", + tmp_path / "vanished-root" / "videos" / "session-02.mp4", + other, + outside, + ), + ) + + real_resolve = Path.resolve + resolved: list[Path] = [] + + def volume_guid_resolve(self: Path, strict: bool = False) -> Path: # noqa: FBT001, FBT002 - Path.resolve's signature + path = real_resolve(self, strict=strict) + resolved.append(path) + + return Path(r"\\?\Volume{0f1e2d3c-0000-0000-0000-000000000000}") / path.relative_to(path.anchor) + + monkeypatch.setattr(Path, "resolve", volume_guid_resolve) + + snapshot = inspect_project(valid_project, validation=video_filename_request()) + + assert resolved + assert {finding.code for finding in snapshot.findings} == { + "CONFIGURED_VIDEOS_UNDER_MISSING_ROOT", + "CONFIGURED_VIDEO_IN_OTHER_COPY", + "CONFIGURED_VIDEO_OUTSIDE_PROJECT", + "VIDEO_NOT_IN_VIDEO_SETS", + } + assert "Volume{" not in snapshot.model_dump_json() + + +def test_configured_video_directory_produces_not_file_finding( + valid_project: Path, +) -> None: + directory_path = valid_project / "videos" / "not-a-video" + directory_path.mkdir() + + set_configured_videos( + valid_project, + (directory_path,), + ) + + snapshot = inspect_project( + valid_project, + validation=video_filename_request(), + ) + + finding = next(finding for finding in snapshot.findings if finding.code == "CONFIGURED_VIDEO_PATH_NOT_FILE") + + assert finding.path == directory_path + assert finding.field_location == ( + "video_sets", + str(directory_path), + ) + + +def test_configured_video_wrong_type_still_produces_not_file_finding( + valid_project: Path, +) -> None: + """A schema-matched video path that is a directory still gets its own finding. + + ``videos/session-01.mp4`` matches the source-video naming pattern, so it + becomes a WRONG_TYPE resource (not an unclaimed one) once discovered - + this must not be mistaken for a valid, present video. + """ + + video_path = valid_project / "videos" / "session-01.mp4" + video_path.mkdir() + + set_configured_videos( + valid_project, + (video_path,), + ) + + snapshot = inspect_project( + valid_project, + validation=video_filename_request(), + ) + + finding = next(finding for finding in snapshot.findings if finding.code == "CONFIGURED_VIDEO_PATH_NOT_FILE") + + assert finding.path == video_path + assert finding.field_location == ( + "video_sets", + str(video_path), + ) + + resource = snapshot.resource_at("videos/session-01.mp4") + + assert resource is not None + + +def test_configured_video_symlink_to_file_is_a_present_file( + valid_project: Path, + create_symlink_or_skip: Callable[..., None], +) -> None: + """A declared video that is a symlink to a file is a file, not a broken path. + + The link sits outside ``videos/`` so it is not indexed as an observed + source video, which routes the check through its ``probe_path`` fallback. + """ + + target = valid_project / "external.mp4" + target.touch() + + link = valid_project / "linked.mp4" + create_symlink_or_skip( + link, + target, + ) + + set_configured_videos( + valid_project, + (link,), + ) + + snapshot = inspect_project( + valid_project, + validation=video_filename_request(), + ) + + assert [finding.code for finding in snapshot.findings] == ["CONFIGURED_VIDEO_OUTSIDE_PROJECT"] + + +def test_configured_video_symlink_to_file_is_a_present_file_from_probe_alone( + valid_project: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """The fallback takes a symlink-to-file probe as a file without creating one. + + Mirrors the test above on platforms that withhold symlink privileges, so + the accepting branch stays covered where the filesystem cannot exercise it. + """ + + link = valid_project / "linked.mp4" + target = valid_project / "external.mp4" + + monkeypatch.setattr( + videos, + "probe_path", + _symlink_probe( + target, + SymlinkTargetKind.FILE, + ), + ) + + set_configured_videos( + valid_project, + (link,), + ) + + snapshot = inspect_project( + valid_project, + validation=video_filename_request(), + ) + + assert [finding.code for finding in snapshot.findings] == ["CONFIGURED_VIDEO_OUTSIDE_PROJECT"] + + +def test_configured_video_broken_symlink_reports_missing_target( + valid_project: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A broken symlink is distinguished from an unreadable path.""" + + link = valid_project / "linked.mp4" + target = valid_project / "missing.mp4" + + monkeypatch.setattr( + videos, + "probe_path", + _symlink_probe( + target, + SymlinkTargetKind.MISSING, + ), + ) + + set_configured_videos( + valid_project, + (link,), + ) + + snapshot = inspect_project( + valid_project, + validation=video_filename_request(), + ) + + finding = next( + finding for finding in snapshot.findings if finding.code == "CONFIGURED_VIDEO_PATH_SYMLINK_TARGET_MISSING" + ) + + assert finding.evidence["absolute_target"] == str(target.absolute()) + + +def test_configured_video_unreadable_path_is_not_reported_as_wrong_type( + valid_project: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """An access failure must not be reported as a type error. + + The path is never created, so project discovery never probes it and only + the configured-path check reaches the patched probe. + """ + + unreadable = valid_project / "unreadable.mp4" + + def fake_probe_path(_path: Path) -> PathProbe: + return PathProbe( + status=PathProbeStatus.INACCESSIBLE, + error_type="PermissionError", + error_message="Access is denied", + ) + + monkeypatch.setattr(videos, "probe_path", fake_probe_path) + + set_configured_videos( + valid_project, + (unreadable,), + ) + + snapshot = inspect_project( + valid_project, + validation=video_filename_request(), + ) + + finding = next(finding for finding in snapshot.findings if finding.code.startswith("CONFIGURED_VIDEO_PATH_")) + + assert finding.code == "CONFIGURED_VIDEO_PATH_UNREADABLE" + assert finding.evidence["error_type"] == "PermissionError" + + +def test_relative_configured_video_path_is_resolved_from_project_root( + valid_project: Path, +) -> None: + relative_path = Path("videos/session-01.mp4") + (valid_project / relative_path).touch() + + set_configured_videos( + valid_project, + (relative_path,), + ) + + snapshot = inspect_project( + valid_project, + validation=video_filename_request(), + ) + + assert not any(finding.code.startswith("CONFIGURED_VIDEO_PATH_") for finding in snapshot.findings) + + +def test_video_validation_is_unavailable_without_canonical_config( + tmp_path: Path, +) -> None: + snapshot = inspect_project( + tmp_path, + validation=video_filename_request(), + ) + + assert len(snapshot.validation_checks) == 1 + + check = snapshot.validation_checks[0] + + assert check.code == "VIDEO_FILENAME_VALIDATION" + assert check.status == ValidationCheckStatus.UNAVAILABLE + assert not any(finding.code.startswith("CONFIGURED_VIDEO_PATH_") for finding in snapshot.findings) + + +def test_two_videos_resolving_to_one_file_are_reported_not_raised( + valid_project: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Two symlinks to one master file is a normal disk-saving layout. + + Probes are faked for the two links only, so the collision branch is covered + where the platform withholds the privilege needed to create a real link. + """ + + master = valid_project / "master.mp4" + master.touch() + + linked = {"session-01.mp4", "session-02.mp4"} + + for name in sorted(linked): + (valid_project / "videos" / name).touch() + + real_probe_path = probe_path + + def fake_probe_path(path: Path) -> PathProbe: + if path.name in linked: + return _symlink_probe( + master, + SymlinkTargetKind.FILE, + )(path) + + return real_probe_path(path) + + monkeypatch.setattr( + "dlc_octopus.discovery.observer.probe_path", + fake_probe_path, + ) + + set_configured_videos( + valid_project, + (master,), + ) + + snapshot = inspect_project( + valid_project, + validation=video_filename_request(), + ) + + collisions = tuple(finding for finding in snapshot.findings if finding.code == "PROJECT_RESOURCE_PATH_COLLISION") + + assert [finding.instance for finding in collisions] == [ + ("videos", "session-01.mp4"), + ("videos", "session-02.mp4"), + ] + + for finding in collisions: + assert finding.severity == Severity.ERROR + assert (finding.schema_id, finding.reach) == ("dlc.videos.source_video", Reach.ONE_OF) + assert finding.evidence["collision_path"] == str(master.absolute()) + assert finding.evidence["resource_kind"] == "source_video" + assert finding.evidence["collision_group"] == ["videos", "session-01.mp4"] + + +def test_a_collision_reports_each_video_once_with_a_shared_key( + valid_project: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + master = valid_project / "master.mp4" + master.touch() + + linked = {"session-01.mp4", "session-02.mp4"} + + for name in sorted(linked): + (valid_project / "videos" / name).touch() + + real_probe_path = probe_path + + def fake_probe_path(path: Path) -> PathProbe: + if path.name in linked: + return _symlink_probe(master, SymlinkTargetKind.FILE)(path) + + return real_probe_path(path) + + monkeypatch.setattr("dlc_octopus.discovery.observer.probe_path", fake_probe_path) + set_configured_videos(valid_project, (master,)) + + snapshot = inspect_project(valid_project, validation=video_filename_request()) + collisions = sorted( + (finding for finding in snapshot.findings if finding.code == "PROJECT_RESOURCE_PATH_COLLISION"), + key=lambda finding: finding.instance, + ) + + assert [(finding.schema_id, finding.instance) for finding in collisions] == [ + ("dlc.videos.source_video", ("videos", "session-01.mp4")), + ("dlc.videos.source_video", ("videos", "session-02.mp4")), + ] + assert collisions[0].evidence["collision_group"] == collisions[1].evidence["collision_group"] + + +def test_three_videos_resolving_to_one_file_are_one_collision( + valid_project: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + master = valid_project / "master.mp4" + master.touch() + + linked = {"session-01.mp4", "session-02.mp4", "session-03.mp4"} + + for name in sorted(linked): + (valid_project / "videos" / name).touch() + + real_probe_path = probe_path + + def fake_probe_path(path: Path) -> PathProbe: + if path.name in linked: + return _symlink_probe(master, SymlinkTargetKind.FILE)(path) + + return real_probe_path(path) + + monkeypatch.setattr("dlc_octopus.discovery.observer.probe_path", fake_probe_path) + set_configured_videos(valid_project, (master,)) + + snapshot = inspect_project(valid_project, validation=video_filename_request()) + collisions = [finding for finding in snapshot.findings if finding.code == "PROJECT_RESOURCE_PATH_COLLISION"] + + assert sorted(finding.instance for finding in collisions) == [("videos", name) for name in sorted(linked)] + assert {tuple(finding.evidence["collision_group"]) for finding in collisions} == {("videos", "session-01.mp4")} + + +def test_two_real_links_to_one_file_collide( + valid_project: Path, + create_symlink_or_skip: Callable[..., None], +) -> None: + """The unfaked counterpart of the test above.""" + + master = valid_project / "master.mp4" + master.touch() + + for name in ("session-01.mp4", "session-02.mp4"): + create_symlink_or_skip( + valid_project / "videos" / name, + master, + ) + + snapshot = inspect_project( + valid_project, + validation=video_filename_request(), + ) + + collisions = tuple(finding for finding in snapshot.findings if finding.code == "PROJECT_RESOURCE_PATH_COLLISION") + + assert len(collisions) == 2 + assert {finding.evidence["collision_path"] for finding in collisions} == {str(master.absolute())} + + +def test_a_chain_of_links_to_one_file_collides( + valid_project: Path, + create_symlink_or_skip: Callable[..., None], +) -> None: + """Identity is the file a chain ends at; evidence keeps the observed first hop.""" + + master = valid_project / "master.mp4" + master.touch() + + hop = valid_project / "hop.mp4" + create_symlink_or_skip( + hop, + master, + ) + create_symlink_or_skip( + valid_project / "videos" / "session-01.mp4", + master, + ) + create_symlink_or_skip( + valid_project / "videos" / "session-02.mp4", + hop, + ) + + snapshot = inspect_project( + valid_project, + validation=video_filename_request(), + ) + + collisions = tuple(finding for finding in snapshot.findings if finding.code == "PROJECT_RESOURCE_PATH_COLLISION") + + by_instance = {finding.instance: finding.evidence for finding in collisions} + + assert by_instance[("videos", "session-01.mp4")]["collision_path"] == str(master.absolute()) + assert by_instance[("videos", "session-02.mp4")]["collision_path"] == str(hop.absolute()) + assert {tuple(evidence["collision_group"]) for evidence in by_instance.values()} == { + ("videos", "session-01.mp4"), + } + assert len(collisions) == 2 diff --git a/tests/project/validation/test_baseline.py b/tests/project/validation/test_baseline.py index a44f9c8..2055408 100644 --- a/tests/project/validation/test_baseline.py +++ b/tests/project/validation/test_baseline.py @@ -1,17 +1,13 @@ -# -# 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 dlccore.project.validation.baseline import ( +from pathlib import Path + +from dlc_octopus.api import inspect_project +from dlc_octopus.capabilities import get_project_manager_capabilities +from dlc_octopus.validation.baseline import ( iter_baseline_check_registrations, + run_baseline_checks, +) +from dlc_octopus.validation.context import ( + build_validation_context, ) @@ -26,3 +22,46 @@ def test_baseline_check_registrations_are_well_formed() -> None: assert registration.code assert registration.description assert callable(registration.validator) + + +def test_baseline_checks_return_structural_findings( + tmp_path: Path, +) -> None: + snapshot = inspect_project(tmp_path) + context = build_validation_context(snapshot) + + findings = run_baseline_checks( + snapshot, + context, + ) + + assert "PROJECT_REQUIRED_NODE_MISSING" in {finding.code for finding in findings} + + +def test_config_path_check_is_not_applicable_without_context( + tmp_path: Path, +) -> None: + snapshot = inspect_project(tmp_path) + + registration = next( + registration + for registration in iter_baseline_check_registrations() + if registration.code == "PROJECT_CONFIG_PATH_RELATIONSHIP" + ) + + assert ( + registration.validator( + snapshot, + None, + ) + == () + ) + + +def test_baseline_capabilities_match_registrations() -> None: + capabilities = get_project_manager_capabilities() + + capability_codes = tuple(capability.code for capability in capabilities.baseline_validations) + registration_codes = tuple(registration.code for registration in iter_baseline_check_registrations()) + + assert capability_codes == registration_codes diff --git a/tests/project/validation/test_context.py b/tests/project/validation/test_context.py new file mode 100644 index 0000000..aa4c4f0 --- /dev/null +++ b/tests/project/validation/test_context.py @@ -0,0 +1,40 @@ +from __future__ import annotations + +from pathlib import Path + +from dlc_octopus.api import inspect_project +from dlc_octopus.validation.context import ( + build_validation_context, +) + + +def test_build_validation_context_for_valid_config( + valid_project: Path, +) -> None: + snapshot = inspect_project(valid_project) + + context = build_validation_context(snapshot) + + assert context is not None + assert context.snapshot is snapshot + assert context.config is snapshot.config + + +def test_no_validation_context_without_config( + tmp_path: Path, +) -> None: + snapshot = inspect_project(tmp_path) + + context = build_validation_context(snapshot) + + assert context is None + + +def test_no_validation_context_for_invalid_config( + invalid_project: Path, +) -> None: + snapshot = inspect_project(invalid_project) + + context = build_validation_context(snapshot) + + assert context is None diff --git a/tests/project/validation/test_finding_schema_ids.py b/tests/project/validation/test_finding_schema_ids.py index d337e7a..885959c 100644 --- a/tests/project/validation/test_finding_schema_ids.py +++ b/tests/project/validation/test_finding_schema_ids.py @@ -1,29 +1,40 @@ -# -# 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 dlccore.project.schemas.base.filesystem import walk_schema -from dlccore.project.schemas.base.finding_codes import ( +from collections.abc import Callable +from pathlib import Path + +import pytest +from deeplabcut.core.config.utils import write_config + +from dlc_octopus.api import inspect_project +from dlc_octopus.discovery.probe import probe_path +from dlc_octopus.schemas.base.filesystem import walk_schema +from dlc_octopus.schemas.base.finding_codes import ( ConfigFindingCode, ConfiguredVideoFindingCode, StructureFindingCode, ) -from dlccore.project.schemas.base.findings import Finding, Reach -from dlccore.project.schemas.locations import all_of, one_of, one_per_project -from dlccore.project.schemas.project_layout.project import PROJECT, PROJECT_INDEX +from dlc_octopus.schemas.base.findings import Finding, Reach +from dlc_octopus.schemas.base.probes import FilesystemEntryKind, PathProbe, PathProbeStatus +from dlc_octopus.schemas.base.resources import DirectoryResourceKind +from dlc_octopus.schemas.base.symlinks import SymlinkObservation, SymlinkTargetKind +from dlc_octopus.schemas.base.validation import ValidationDepth +from dlc_octopus.schemas.locations import all_of, one_of, one_per_project +from dlc_octopus.schemas.project_layout.project import PROJECT, PROJECT_INDEX +from dlc_octopus.schemas.snapshots import ProjectSnapshot +from dlc_octopus.validation import ProjectValidationRequest, ResourceValidationRequest _DECLARED = frozenset(schema.schema_id for schema, _ in walk_schema(PROJECT)) _NODES = PROJECT_INDEX.schemas +_VIDEOS = ProjectValidationRequest( + resources=( + ResourceValidationRequest( + kind=DirectoryResourceKind.VIDEOS_DIRECTORY, + depth=ValidationDepth.FILENAME_ONLY, + ), + ) +) # Moving a code to another node changes every consumer's scope, so each non-structural code's # anchor is pinned here. Structure codes anchor at the node they are about. @@ -70,6 +81,93 @@ def _misfit_reaches(findings: tuple[Finding, ...]) -> set[tuple[str, Reach]]: return misfits +def _empty_directory(root: Path, config: dict) -> None: + del root, config + + +def _unparseable_config(root: Path, config: dict) -> None: + del config + (root / "config.yaml").write_text("a:\n b: [\n", encoding="utf-8") + + +def _invalid_config(root: Path, config: dict) -> None: + write_config(root / "config.yaml", {**config, "pcutoff": "not-a-number"}) + + +def _moved_project_with_a_missing_video(root: Path, config: dict) -> None: + (root / "videos").mkdir() + write_config( + root / "config.yaml", + { + **config, + "project_path": str(root / "declared-elsewhere"), + "video_sets": {str(root / "videos" / "missing.mp4"): {"crop": "0, 10, 0, 10"}}, + }, + ) + + +def _videos_is_a_file(root: Path, config: dict) -> None: + (root / "videos").touch() + write_config(root / "config.yaml", config) + + +@pytest.mark.parametrize( + "build", + [ + _empty_directory, + _unparseable_config, + _invalid_config, + _moved_project_with_a_missing_video, + _videos_is_a_file, + ], + ids=lambda build: build.__name__.strip("_"), +) +def test_every_emitted_finding_has_a_declared_schema_id( + tmp_path: Path, + valid_config_data: dict, + build: Callable[[Path, dict], None], +) -> None: + build(tmp_path, dict(valid_config_data, project_path=str(tmp_path))) + + snapshot: ProjectSnapshot = inspect_project(tmp_path, validation=_VIDEOS) + + # Guards the guard: a scenario that emits nothing would pass vacuously. + assert snapshot.findings + assert _undeclared_schema_ids(snapshot.findings) == set() + assert _misfit_reaches(snapshot.findings) == set() + assert _moved_anchors(snapshot.findings) == set() + + +def test_a_finding_on_a_repeated_node_is_emitted_with_a_fitting_reach( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + (tmp_path / "videos").mkdir() + (tmp_path / "videos" / "session-01.mp4").touch() + + def fake_probe_path(path: Path) -> PathProbe: + if path.name != "session-01.mp4": + return probe_path(path) + + return PathProbe( + status=PathProbeStatus.OBSERVED, + entry_kind=FilesystemEntryKind.SYMLINK, + symlink=SymlinkObservation( + raw_target=tmp_path / "gone.mp4", + absolute_target=tmp_path / "gone.mp4", + target_kind=SymlinkTargetKind.MISSING, + ), + ) + + monkeypatch.setattr("dlc_octopus.discovery.observer.probe_path", fake_probe_path) + + findings = inspect_project(tmp_path).findings + + # Guards the guard: without a ONE_OF finding, only one_per_project would be exercised. + assert {finding.reach for finding in findings} >= {Reach.ONE_OF} + assert _misfit_reaches(findings) == set() + + def test_an_undeclared_schema_id_is_detected() -> None: code = StructureFindingCode.PROJECT_NODE_UNREADABLE planted = Finding( @@ -105,3 +203,39 @@ def test_a_reach_that_does_not_fit_the_layout_is_detected() -> None: ) assert _misfit_reaches((planted,)) == {("dlc.videos.source_video", Reach.ONE_PER_PROJECT)} + + +def test_a_finding_about_something_missing_anchors_at_its_declaration( + tmp_path: Path, + valid_config_data: dict, +) -> None: + empty = tmp_path / "empty" + empty.mkdir() + + (config_missing,) = ( + finding + for finding in inspect_project(empty).findings + if finding.code == StructureFindingCode.PROJECT_REQUIRED_NODE_MISSING + ) + + assert (config_missing.schema_id, config_missing.reach) == ("dlc.project.config", Reach.ONE_PER_PROJECT) + + declared = tmp_path / "declared" + (declared / "videos").mkdir(parents=True) + missing = declared / "videos" / "missing.mp4" + write_config( + declared / "config.yaml", + {**valid_config_data, "project_path": str(declared), "video_sets": {str(missing): {"crop": "0, 10, 0, 10"}}}, + ) + + (video_missing,) = ( + finding + for finding in inspect_project(declared, validation=_VIDEOS).findings + if finding.code == "CONFIGURED_VIDEO_PATH_MISSING" + ) + + assert (video_missing.schema_id, video_missing.reach, video_missing.field_location) == ( + "dlc.project.config", + Reach.ONE_PER_PROJECT, + ("video_sets", str(missing)), + ) diff --git a/tests/project/validation/test_project.py b/tests/project/validation/test_project.py new file mode 100644 index 0000000..8d836c4 --- /dev/null +++ b/tests/project/validation/test_project.py @@ -0,0 +1,55 @@ +from __future__ import annotations + +from pathlib import Path + +import pytest + +from dlc_octopus.api import inspect_project +from dlc_octopus.schemas.base.resources import DirectoryResourceKind +from dlc_octopus.schemas.base.validation import ValidationDepth +from dlc_octopus.validation import validate_project +from dlc_octopus.validation.requests import ProjectValidationRequest, ResourceValidationRequest + + +def test_validate_project_returns_structural_findings( + tmp_path: Path, +) -> None: + snapshot = inspect_project(tmp_path) + + result = validate_project(snapshot) + + assert "PROJECT_REQUIRED_NODE_MISSING" in {finding.code for finding in result.findings} + + +def test_validate_project_returns_no_findings_for_valid_structure( + valid_project: Path, +) -> None: + snapshot = inspect_project(valid_project) + + result = validate_project(snapshot) + + assert result.findings == () + assert result.checks == () + + +def test_inspect_project_includes_validation_findings( + tmp_path: Path, +) -> None: + snapshot = inspect_project(tmp_path) + codes = {finding.code for finding in snapshot.findings} + + assert "PROJECT_REQUIRED_NODE_MISSING" in codes + + +def _videos_at(depth: ValidationDepth) -> ProjectValidationRequest: + return ProjectValidationRequest( + resources=(ResourceValidationRequest(kind=DirectoryResourceKind.VIDEOS_DIRECTORY, depth=depth),) + ) + + +def test_a_depth_the_suite_does_not_support_is_refused_naming_the_supported_ones(valid_project: Path) -> None: + snapshot = inspect_project(valid_project) + validate_project(snapshot, request=_videos_at(ValidationDepth.FILENAME_ONLY)) # control: a supported depth runs + + with pytest.raises(ValueError, match=r"'full' is not supported .* Supported depths are: filename_only\."): + validate_project(snapshot, request=_videos_at(ValidationDepth.FULL)) diff --git a/tests/project/validation/test_validation_coverage.py b/tests/project/validation/test_validation_coverage.py new file mode 100644 index 0000000..b48b187 --- /dev/null +++ b/tests/project/validation/test_validation_coverage.py @@ -0,0 +1,24 @@ +import pytest + +from dlc_octopus.validation.registry import ( + iter_validator_registrations, +) + + +def _tested_validator_codes( + items: list[pytest.Item], +) -> set[str]: + """Return validator codes declared by collected tests.""" + + return {str(marker.args[0]) for item in items for marker in item.iter_markers(name="data_validator") if marker.args} + + +def test_every_registered_validator_has_declared_unit_coverage( + request: pytest.FixtureRequest, +) -> None: + registered_codes = {registration.code for _, registration in iter_validator_registrations()} + covered_codes = _tested_validator_codes(list(request.session.items)) + + missing_coverage = registered_codes - covered_codes + + assert not missing_coverage, f"Registered validators without declared unit coverage: {sorted(missing_coverage)}" From 0b57233cfa349c9d19bcc26519b3d10329ec5700 Mon Sep 17 00:00:00 2001 From: Cyril Achard Date: Thu, 26 Nov 2026 15:24:16 +0100 Subject: [PATCH 2/3] Adapt project inspection and capabilities to dlccore - Rename the packages to dlccore.project, take the config schema from dlccore.config, and add the dlccore license header - Drop ProjectManagerCapabilities' IPython display hooks; they render through the visualization package, which lands later - Re-export inspect_project and project_name from the API package - Register the data_validator marker - Land the tests that need inspect_project: new files, and the rest of test_observer, test_symlinks, test_scope_query, test_validation_error, test_schema_id, test_baseline and test_finding_schema_ids - Move test_inspecting_a_moved_project_leaves_its_config_untouched's positive control, which calls DeepLabCut's read_config, to tests/upstream/test_deeplabcut.py - Reword an xfail reason that named a planning stack --- dlccore/project/api/__init__.py | 3 ++ dlccore/project/capabilities.py | 23 +++++++--- dlccore/project/inspection.py | 23 +++++++--- dlccore/project/schemas/capabilities.py | 32 ++++++-------- pyproject.toml | 1 + tests/project/discovery/test_observer.py | 25 ++++++++--- tests/project/discovery/test_symlinks.py | 29 +++++++++---- tests/project/inspection/conftest.py | 15 ++++++- tests/project/inspection/test_config.py | 15 ++++++- tests/project/inspection/test_invariants.py | 13 +++++- tests/project/inspection/test_project_name.py | 17 ++++++-- .../inspection/test_project_structure.py | 15 ++++++- tests/project/inspection/test_resolution.py | 17 ++++++-- tests/project/inspection/test_resources.py | 17 ++++++-- tests/project/inspection/test_scope_query.py | 27 ++++++++---- tests/project/inspection/test_serialize.py | 25 ++++++++--- tests/project/inspection/test_snapshot.py | 23 +++++++--- .../inspection/test_validation_error.py | 17 ++++++-- .../inspection/test_validation_request.py | 23 +++++++--- .../schemas/test_labeled_data_layout.py | 15 ++++++- tests/project/schemas/test_schema_id.py | 17 ++++++-- tests/project/test_capabilities.py | 31 ++++++++----- .../deeplabcut/test_labeled_data.py | 19 ++++++-- .../deeplabcut/test_project_path.py | 34 +++++++++------ .../validation/deeplabcut/test_videos.py | 43 ++++++++++++------- tests/project/validation/test_baseline.py | 19 ++++++-- tests/project/validation/test_context.py | 15 ++++++- .../validation/test_finding_schema_ids.py | 41 +++++++++++------- tests/project/validation/test_project.py | 21 ++++++--- .../validation/test_validation_coverage.py | 13 +++++- tests/upstream/test_deeplabcut.py | 16 +++++++ 31 files changed, 476 insertions(+), 168 deletions(-) diff --git a/dlccore/project/api/__init__.py b/dlccore/project/api/__init__.py index 4e5e5e7..8e8d3c1 100644 --- a/dlccore/project/api/__init__.py +++ b/dlccore/project/api/__init__.py @@ -12,6 +12,7 @@ """Public entry points of ``dlccore.project``; consumer helpers are in ``api.helpers``. Re-exports only.""" from dlccore.project.api import helpers +from dlccore.project.inspection import inspect_project, project_name from dlccore.project.schemas.base.resources import FileResourceKind from dlccore.project.schemas.scope import findings_in_scope @@ -19,4 +20,6 @@ "FileResourceKind", "findings_in_scope", "helpers", + "inspect_project", + "project_name", ] diff --git a/dlccore/project/capabilities.py b/dlccore/project/capabilities.py index 7757795..a854ede 100644 --- a/dlccore/project/capabilities.py +++ b/dlccore/project/capabilities.py @@ -1,24 +1,35 @@ +# +# 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.filesystem import ( +from dlccore.project.schemas.base.filesystem import ( NodeSchema, child_schemas, index_layout, ) -from dlc_octopus.schemas.capabilities import ( +from dlccore.project.schemas.capabilities import ( BaselineValidationCapability, LayoutCapability, ProjectManagerCapabilities, ValidationCapability, ) -from dlc_octopus.schemas.project_layout.project import PROJECT -from dlc_octopus.schemas.snapshots import ( +from dlccore.project.schemas.project_layout.project import PROJECT +from dlccore.project.schemas.snapshots import ( PROJECT_SNAPSHOT_VERSION, ) -from dlc_octopus.validation.baseline import ( +from dlccore.project.validation.baseline import ( iter_baseline_check_registrations, ) -from dlc_octopus.validation.registry import ( +from dlccore.project.validation.registry import ( iter_validator_registrations, ) diff --git a/dlccore/project/inspection.py b/dlccore/project/inspection.py index 0a47c86..8f6d688 100644 --- a/dlccore/project/inspection.py +++ b/dlccore/project/inspection.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 +# + """Inspect a DeepLabCut project into a snapshot, and read DeepLabCut's name for it.""" from __future__ import annotations @@ -6,12 +17,12 @@ from datetime import date from pathlib import Path -from dlc_octopus.discovery.observer import discover_project -from dlc_octopus.errors import ProjectValidationError, _blocking_findings -from dlc_octopus.schemas.base.findings import Finding -from dlc_octopus.schemas.snapshots import ProjectSnapshot -from dlc_octopus.validation import ProjectValidationRequest, validate_project -from dlc_octopus.validation.config import validate_project_config +from dlccore.project.discovery.observer import discover_project +from dlccore.project.errors import ProjectValidationError, _blocking_findings +from dlccore.project.schemas.base.findings import Finding +from dlccore.project.schemas.snapshots import ProjectSnapshot +from dlccore.project.validation import ProjectValidationRequest, validate_project +from dlccore.project.validation.config import validate_project_config # DeepLabCut's create_new_project: config ``date`` is the 3-letter month and unpadded day, e.g. "Oct30". _MONTHS = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec") diff --git a/dlccore/project/schemas/capabilities.py b/dlccore/project/schemas/capabilities.py index f9c1193..57312f8 100644 --- a/dlccore/project/schemas/capabilities.py +++ b/dlccore/project/schemas/capabilities.py @@ -1,19 +1,25 @@ -from __future__ import annotations +# +# 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 typing import TYPE_CHECKING +from __future__ import annotations -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 ( ResourceKind, ResourceManagement, ) -from dlc_octopus.schemas.base.validation import ( +from dlccore.project.schemas.base.validation import ( ValidationDepth, ) -if TYPE_CHECKING: - from IPython.lib.pretty import RepresentationPrinter - class LayoutCapability(FrozenModel): """One node in the declared DeepLabCut project layout.""" @@ -48,13 +54,3 @@ class ProjectManagerCapabilities(FrozenModel): layout: LayoutCapability baseline_validations: tuple[BaselineValidationCapability, ...] = () validations: tuple[ValidationCapability, ...] = () - - def _repr_pretty_(self, printer: RepresentationPrinter, cycle: bool) -> None: # noqa: FBT001 - IPython's signature - from dlc_octopus.visualization.capabilities import render_capabilities - - printer.text("ProjectManagerCapabilities(...)" if cycle else render_capabilities(self)) - - def _repr_markdown_(self) -> str: - from dlc_octopus.visualization.capabilities import render_capabilities - - return render_capabilities(self, style="markdown") diff --git a/pyproject.toml b/pyproject.toml index fafcbf5..e68fa21 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -94,6 +94,7 @@ ini_options.filterwarnings = [ "error:The default of observed=False is deprecated:FutureWarning", ] ini_options.markers = [ + "data_validator(code): declares coverage of a registered validation suite", "destination(repo): repository this test ultimately belongs to; a file carries exactly one", """\ owed_before_release(reason, raises): prototype maintenance; a strict xfail expecting `raises` while the package and \ diff --git a/tests/project/discovery/test_observer.py b/tests/project/discovery/test_observer.py index a8aa95e..8057054 100644 --- a/tests/project/discovery/test_observer.py +++ b/tests/project/discovery/test_observer.py @@ -1,26 +1,37 @@ +# +# 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 collections.abc import Iterator from pathlib import Path import pytest -from dlc_octopus.api import inspect_project -from dlc_octopus.discovery.observer import discover_directory_node, discover_project -from dlc_octopus.schemas.base.filesystem import ( +from dlccore.project.api import inspect_project +from dlccore.project.discovery.observer import discover_directory_node, discover_project +from dlccore.project.schemas.base.filesystem import ( DirectorySchema, FileSchema, NamePattern, NodeSchema, ) -from dlc_octopus.schemas.base.observations import ( +from dlccore.project.schemas.base.observations import ( NodeStatus, ) -from dlc_octopus.schemas.base.probes import FilesystemEntryKind, PathProbeStatus -from dlc_octopus.schemas.base.resources import ( +from dlccore.project.schemas.base.probes import FilesystemEntryKind, PathProbeStatus +from dlccore.project.schemas.base.resources import ( DirectoryResourceKind, FileResourceKind, ResourceManagement, ) -from dlc_octopus.schemas.project_layout.project import PROJECT +from dlccore.project.schemas.project_layout.project import PROJECT def test_discovered_directory_populates_renamed_fields( diff --git a/tests/project/discovery/test_symlinks.py b/tests/project/discovery/test_symlinks.py index 47937e2..bf805d3 100644 --- a/tests/project/discovery/test_symlinks.py +++ b/tests/project/discovery/test_symlinks.py @@ -1,31 +1,42 @@ +# +# 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 collections.abc import Callable from pathlib import Path import pytest -from deeplabcut.core.config import ProjectConfig -from dlc_octopus.api import inspect_project -from dlc_octopus.discovery.observer import ( +from dlccore.config import ProjectConfig +from dlccore.project.api import inspect_project +from dlccore.project.discovery.observer import ( ExpectedEntryKind, classify_unclaimed_entry, status_for_expected_entry, ) -from dlc_octopus.discovery.probe import probe_path -from dlc_octopus.schemas.base.observations import NodeStatus -from dlc_octopus.schemas.base.probes import ( +from dlccore.project.discovery.probe import probe_path +from dlccore.project.schemas.base.observations import NodeStatus +from dlccore.project.schemas.base.probes import ( FilesystemEntryKind, PathProbe, PathProbeStatus, ) -from dlc_octopus.schemas.base.resources import ( +from dlccore.project.schemas.base.resources import ( DirectoryResourceKind, FileResourceKind, ResourceManagement, UnknownResourceKind, ) -from dlc_octopus.schemas.base.symlinks import ( +from dlccore.project.schemas.base.symlinks import ( SymlinkObservation, SymlinkTargetKind, ) @@ -374,7 +385,7 @@ def fake_probe_path(path: Path) -> PathProbe: return real_probe_path(path) monkeypatch.setattr( - "dlc_octopus.discovery.observer.probe_path", + "dlccore.project.discovery.observer.probe_path", fake_probe_path, ) diff --git a/tests/project/inspection/conftest.py b/tests/project/inspection/conftest.py index 7f30421..c894b98 100644 --- a/tests/project/inspection/conftest.py +++ b/tests/project/inspection/conftest.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 +# + from __future__ import annotations from collections.abc import Callable @@ -5,8 +16,8 @@ import pytest -from dlc_octopus.schemas.base.resources import ProjectResource -from dlc_octopus.schemas.snapshots import ProjectSnapshot +from dlccore.project.schemas.base.resources import ProjectResource +from dlccore.project.schemas.snapshots import ProjectSnapshot @pytest.fixture diff --git a/tests/project/inspection/test_config.py b/tests/project/inspection/test_config.py index cc347e8..c37e38e 100644 --- a/tests/project/inspection/test_config.py +++ b/tests/project/inspection/test_config.py @@ -1,9 +1,20 @@ +# +# 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 pathlib import Path import pytest -from dlc_octopus.api import inspect_project -from dlc_octopus.errors import ( +from dlccore.project.api import inspect_project +from dlccore.project.errors import ( ConfigUnavailableError, ) diff --git a/tests/project/inspection/test_invariants.py b/tests/project/inspection/test_invariants.py index 8c7cadc..c8a63d5 100644 --- a/tests/project/inspection/test_invariants.py +++ b/tests/project/inspection/test_invariants.py @@ -1,7 +1,18 @@ +# +# 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 collections.abc import Callable from pathlib import Path -from dlc_octopus.api import inspect_project +from dlccore.project.api import inspect_project def test_inspect_project_does_not_modify_files( diff --git a/tests/project/inspection/test_project_name.py b/tests/project/inspection/test_project_name.py index 3491f3c..6f2aec0 100644 --- a/tests/project/inspection/test_project_name.py +++ b/tests/project/inspection/test_project_name.py @@ -1,12 +1,23 @@ +# +# 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 pathlib import Path import pytest -from deeplabcut.core.config.utils import write_config -from dlc_octopus import api -from dlc_octopus.errors import ConfigUnavailableError +from dlccore.config.utils import write_config +from dlccore.project import api +from dlccore.project.errors import ConfigUnavailableError # DeepLabCut's own example project: examples/openfield-Pranav-2018-10-30, config date "Oct30". TASK, SCORER, CONFIG_DATE = "openfield", "Pranav", "Oct30" diff --git a/tests/project/inspection/test_project_structure.py b/tests/project/inspection/test_project_structure.py index f8898f3..8dd1084 100644 --- a/tests/project/inspection/test_project_structure.py +++ b/tests/project/inspection/test_project_structure.py @@ -1,7 +1,18 @@ +# +# 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 pathlib import Path -from dlc_octopus.api import inspect_project -from dlc_octopus.schemas.base.finding_codes import ConfigFindingCode, StructureFindingCode +from dlccore.project.api import inspect_project +from dlccore.project.schemas.base.finding_codes import ConfigFindingCode, StructureFindingCode def test_inspect_project_includes_missing_required_node_finding( diff --git a/tests/project/inspection/test_resolution.py b/tests/project/inspection/test_resolution.py index 5b97d12..2f60e44 100644 --- a/tests/project/inspection/test_resolution.py +++ b/tests/project/inspection/test_resolution.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 pathlib import Path import pytest -from dlc_octopus.api import inspect_project -from dlc_octopus.schemas.base.finding_codes import ConfigFindingCode -from dlc_octopus.schemas.snapshots import ( +from dlccore.project.api import inspect_project +from dlccore.project.schemas.base.finding_codes import ConfigFindingCode +from dlccore.project.schemas.snapshots import ( ConfigState, ) diff --git a/tests/project/inspection/test_resources.py b/tests/project/inspection/test_resources.py index 23d0d9f..5d73611 100644 --- a/tests/project/inspection/test_resources.py +++ b/tests/project/inspection/test_resources.py @@ -1,13 +1,24 @@ +# +# 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 collections.abc import Callable from pathlib import Path -from dlc_octopus.api import inspect_project -from dlc_octopus.schemas.base.resources import ( +from dlccore.project.api import inspect_project +from dlccore.project.schemas.base.resources import ( FileResourceKind, ProjectResource, ResourceManagement, ) -from dlc_octopus.schemas.snapshots import ProjectSnapshot +from dlccore.project.schemas.snapshots import ProjectSnapshot def test_napari_metadata_is_known_unmanaged( diff --git a/tests/project/inspection/test_scope_query.py b/tests/project/inspection/test_scope_query.py index 7f0272e..b93acd4 100644 --- a/tests/project/inspection/test_scope_query.py +++ b/tests/project/inspection/test_scope_query.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 +# + from __future__ import annotations import re @@ -5,14 +16,14 @@ import pytest -from dlc_octopus import api -from dlc_octopus.api import helpers -from dlc_octopus.schemas.base.filesystem import NodeSchema -from dlc_octopus.schemas.base.finding_codes import StructureFindingCode -from dlc_octopus.schemas.base.findings import Finding, Reach -from dlc_octopus.schemas.project_layout.labeled_data import LABELED_DATASET, LABELED_FRAME -from dlc_octopus.schemas.project_layout.project import PROJECT_CONFIG -from dlc_octopus.schemas.project_layout.videos import VIDEOS +from dlccore.project import api +from dlccore.project.api import helpers +from dlccore.project.schemas.base.filesystem import NodeSchema +from dlccore.project.schemas.base.finding_codes import StructureFindingCode +from dlccore.project.schemas.base.findings import Finding, Reach +from dlccore.project.schemas.project_layout.labeled_data import LABELED_DATASET, LABELED_FRAME +from dlccore.project.schemas.project_layout.project import PROJECT_CONFIG +from dlccore.project.schemas.project_layout.videos import VIDEOS _DS1 = ("labeled-data", "ds1") diff --git a/tests/project/inspection/test_serialize.py b/tests/project/inspection/test_serialize.py index db3393d..3c04203 100644 --- a/tests/project/inspection/test_serialize.py +++ b/tests/project/inspection/test_serialize.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 +# + from __future__ import annotations import json @@ -6,19 +17,19 @@ import pytest from pydantic import ValidationError -from dlc_octopus.api import inspect_project -from dlc_octopus.capabilities import get_project_manager_capabilities -from dlc_octopus.discovery.probe import probe_path -from dlc_octopus.schemas.base.probes import ( +from dlccore.project.api import inspect_project +from dlccore.project.capabilities import get_project_manager_capabilities +from dlccore.project.discovery.probe import probe_path +from dlccore.project.schemas.base.probes import ( FilesystemEntryKind, PathProbe, PathProbeStatus, ) -from dlc_octopus.schemas.base.resources import ( +from dlccore.project.schemas.base.resources import ( ProjectResource, UnknownResourceKind, ) -from dlc_octopus.schemas.snapshots import ( +from dlccore.project.schemas.snapshots import ( PROJECT_SNAPSHOT_VERSION, ProjectSnapshot, ) @@ -180,7 +191,7 @@ def fake_probe_path(path: Path) -> PathProbe: return real_probe_path(path) monkeypatch.setattr( - "dlc_octopus.discovery.observer.probe_path", + "dlccore.project.discovery.observer.probe_path", fake_probe_path, ) diff --git a/tests/project/inspection/test_snapshot.py b/tests/project/inspection/test_snapshot.py index 462260a..80e0065 100644 --- a/tests/project/inspection/test_snapshot.py +++ b/tests/project/inspection/test_snapshot.py @@ -1,22 +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 collections.abc import Callable from pathlib import Path import pytest -from dlc_octopus.api import inspect_project -from dlc_octopus.schemas.base.observations import NodeStatus -from dlc_octopus.schemas.base.resources import ( +from dlccore.project.api import inspect_project +from dlccore.project.schemas.base.observations import NodeStatus +from dlccore.project.schemas.base.resources import ( DirectoryResourceKind, FileResourceKind, ProjectResource, ) -from dlc_octopus.schemas.base.validation import ( +from dlccore.project.schemas.base.validation import ( ValidationCheck, ValidationCheckStatus, ValidationDepth, ) -from dlc_octopus.schemas.snapshots import ConfigState, ProjectSnapshot -from dlc_octopus.validation.results import ValidationResult +from dlccore.project.schemas.snapshots import ConfigState, ProjectSnapshot +from dlccore.project.validation.results import ValidationResult def test_inspect_project_returns_expected_snapshot( diff --git a/tests/project/inspection/test_validation_error.py b/tests/project/inspection/test_validation_error.py index cf4211d..29b411a 100644 --- a/tests/project/inspection/test_validation_error.py +++ b/tests/project/inspection/test_validation_error.py @@ -1,12 +1,23 @@ +# +# 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 pathlib import Path import pytest -from dlc_octopus.api import inspect_project -from dlc_octopus.errors import BLOCKING_SEVERITIES, ProjectValidationError, _blocking_findings -from dlc_octopus.schemas.base.finding_codes import ConfigFindingCode, Severity +from dlccore.project.api import inspect_project +from dlccore.project.errors import BLOCKING_SEVERITIES, ProjectValidationError, _blocking_findings +from dlccore.project.schemas.base.finding_codes import ConfigFindingCode, Severity _UNPARSEABLE_CONFIG = "a:\n b: [\n" diff --git a/tests/project/inspection/test_validation_request.py b/tests/project/inspection/test_validation_request.py index e81b343..412a5c2 100644 --- a/tests/project/inspection/test_validation_request.py +++ b/tests/project/inspection/test_validation_request.py @@ -1,16 +1,27 @@ +# +# 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 pathlib import Path import pytest -from dlc_octopus.api import inspect_project -from dlc_octopus.schemas.base.finding_codes import ConfigFindingCode -from dlc_octopus.schemas.base.resources import ( +from dlccore.project.api import inspect_project +from dlccore.project.schemas.base.finding_codes import ConfigFindingCode +from dlccore.project.schemas.base.resources import ( DirectoryResourceKind, ) -from dlc_octopus.schemas.base.validation import ( +from dlccore.project.schemas.base.validation import ( ValidationDepth, ) -from dlc_octopus.validation import ( +from dlccore.project.validation import ( ProjectValidationRequest, ResourceValidationRequest, ) @@ -32,7 +43,7 @@ def test_unregistered_resource_validation_is_rejected( monkeypatch: pytest.MonkeyPatch, ) -> None: monkeypatch.setattr( - "dlc_octopus.validation.project.get_validator_registration", + "dlccore.project.validation.project.get_validator_registration", lambda _kind: None, ) diff --git a/tests/project/schemas/test_labeled_data_layout.py b/tests/project/schemas/test_labeled_data_layout.py index d4396ac..99cb1a6 100644 --- a/tests/project/schemas/test_labeled_data_layout.py +++ b/tests/project/schemas/test_labeled_data_layout.py @@ -1,9 +1,20 @@ +# +# 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 pathlib import Path import pytest -from dlc_octopus.api import inspect_project -from dlc_octopus.schemas.base.resources import FileResourceKind +from dlccore.project.api import inspect_project +from dlccore.project.schemas.base.resources import FileResourceKind def _kinds_in_a_dataset(project_root: Path, names: tuple[str, ...]) -> dict[str, FileResourceKind]: diff --git a/tests/project/schemas/test_schema_id.py b/tests/project/schemas/test_schema_id.py index 55621bc..f1fda7b 100644 --- a/tests/project/schemas/test_schema_id.py +++ b/tests/project/schemas/test_schema_id.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 +# + from __future__ import annotations import json @@ -5,9 +16,9 @@ import pytest from pydantic import ValidationError -from dlc_octopus.capabilities import get_project_manager_capabilities -from dlc_octopus.schemas.base.filesystem import FileSchema, NamePattern -from dlc_octopus.schemas.base.resources import FileResourceKind +from dlccore.project.capabilities import get_project_manager_capabilities +from dlccore.project.schemas.base.filesystem import FileSchema, NamePattern +from dlccore.project.schemas.base.resources import FileResourceKind def _file_schema(schema_id: str) -> FileSchema: diff --git a/tests/project/test_capabilities.py b/tests/project/test_capabilities.py index 4842c0b..168138a 100644 --- a/tests/project/test_capabilities.py +++ b/tests/project/test_capabilities.py @@ -1,28 +1,39 @@ +# +# 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 dlc_octopus.capabilities import ( +from dlccore.project.capabilities import ( get_project_manager_capabilities, ) -from dlc_octopus.schemas.base.resources import ( +from dlccore.project.schemas.base.resources import ( DirectoryResourceKind, ) -from dlc_octopus.schemas.base.validation import ( +from dlccore.project.schemas.base.validation import ( ValidationDepth, ) -from dlc_octopus.schemas.capabilities import LayoutCapability -from dlc_octopus.schemas.snapshots import ( +from dlccore.project.schemas.capabilities import LayoutCapability +from dlccore.project.schemas.snapshots import ( PROJECT_SNAPSHOT_VERSION, ProjectSnapshot, ) -from dlc_octopus.validation.context import ( +from dlccore.project.validation.context import ( ValidationContext, ) -from dlc_octopus.validation.registry import ( +from dlccore.project.validation.registry import ( ValidatorRegistration, ) -from dlc_octopus.validation.results import ( +from dlccore.project.validation.results import ( ValidationResult, ) @@ -83,7 +94,7 @@ def validator( ) monkeypatch.setattr( - "dlc_octopus.capabilities.iter_validator_registrations", + "dlccore.project.capabilities.iter_validator_registrations", lambda: ( ( DirectoryResourceKind.VIDEOS_DIRECTORY, @@ -123,7 +134,7 @@ def _published_schema_ids(node: LayoutCapability) -> set[str]: @pytest.mark.xfail( reason="a training-dataset shuffle is a logical layout node with no resource kind, keyed by " "(train_percent, shuffle_index), so shuffle findings take it as their schema_id rather than their dataset; " - "due with Stack B's training-data work, which observes shuffles outside the tree today", + "due with the training-data work, which observes shuffles outside the tree today", strict=True, raises=AssertionError, ) diff --git a/tests/project/validation/deeplabcut/test_labeled_data.py b/tests/project/validation/deeplabcut/test_labeled_data.py index 7afac38..2f3327e 100644 --- a/tests/project/validation/deeplabcut/test_labeled_data.py +++ b/tests/project/validation/deeplabcut/test_labeled_data.py @@ -1,13 +1,24 @@ +# +# 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 pathlib import Path import pytest -from dlc_octopus.api import inspect_project -from dlc_octopus.schemas.base.resources import DirectoryResourceKind -from dlc_octopus.schemas.base.validation import ValidationDepth -from dlc_octopus.validation import ProjectValidationRequest, ResourceValidationRequest +from dlccore.project.api import inspect_project +from dlccore.project.schemas.base.resources import DirectoryResourceKind +from dlccore.project.schemas.base.validation import ValidationDepth +from dlccore.project.validation import ProjectValidationRequest, ResourceValidationRequest @pytest.mark.xfail( diff --git a/tests/project/validation/deeplabcut/test_project_path.py b/tests/project/validation/deeplabcut/test_project_path.py index b879d20..58a7f55 100644 --- a/tests/project/validation/deeplabcut/test_project_path.py +++ b/tests/project/validation/deeplabcut/test_project_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 +# + from __future__ import annotations import ctypes @@ -7,17 +18,17 @@ from pathlib import Path import pytest -from deeplabcut.core.config.utils import read_config, write_config -from dlc_octopus.api import inspect_project -from dlc_octopus.schemas.base.finding_codes import ConfigFindingCode -from dlc_octopus.schemas.base.findings import Severity -from dlc_octopus.schemas.base.probes import PathProbe, PathProbeStatus -from dlc_octopus.validation.context import ( +from dlccore.config.utils import write_config +from dlccore.project.api import inspect_project +from dlccore.project.schemas.base.finding_codes import ConfigFindingCode +from dlccore.project.schemas.base.findings import Severity +from dlccore.project.schemas.base.probes import PathProbe, PathProbeStatus +from dlccore.project.validation.context import ( build_validation_context, ) -from dlc_octopus.validation.deeplabcut import project_path as project_path_module -from dlc_octopus.validation.deeplabcut.project_path import ( +from dlccore.project.validation.deeplabcut import project_path as project_path_module +from dlccore.project.validation.deeplabcut.project_path import ( validate_project_path, ) @@ -70,7 +81,7 @@ def test_inspecting_a_moved_project_leaves_its_config_untouched( tmp_path: Path, valid_config_data: dict, ) -> None: - """Octopus never repairs, although DeepLabCut's own reader rewrites this config on read.""" + """Inspection never repairs, although DeepLabCut's own reader rewrites this config on read (tests/upstream).""" (tmp_path / "videos").mkdir() (tmp_path / "labeled-data").mkdir() @@ -90,11 +101,6 @@ def test_inspecting_a_moved_project_leaves_its_config_untouched( assert config_path.read_bytes() == before - # Positive control: the scenario is one that DeepLabCut's reader repairs by writing. - read_config(config_path) - - assert config_path.read_bytes() != before - _ABSENT = object() diff --git a/tests/project/validation/deeplabcut/test_videos.py b/tests/project/validation/deeplabcut/test_videos.py index 080c334..5b5aaa6 100644 --- a/tests/project/validation/deeplabcut/test_videos.py +++ b/tests/project/validation/deeplabcut/test_videos.py @@ -1,38 +1,49 @@ +# +# 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 collections.abc import Callable from pathlib import Path import pytest -from deeplabcut.core.config.utils import ( + +from dlccore.config.utils import ( read_config_as_dict, write_config, ) - -from dlc_octopus.api import inspect_project -from dlc_octopus.discovery.probe import probe_path -from dlc_octopus.schemas.base.findings import Reach, Severity -from dlc_octopus.schemas.base.probes import ( +from dlccore.project.api import inspect_project +from dlccore.project.discovery.probe import probe_path +from dlccore.project.schemas.base.findings import Reach, Severity +from dlccore.project.schemas.base.probes import ( FilesystemEntryKind, PathProbe, PathProbeStatus, ) -from dlc_octopus.schemas.base.resources import ( +from dlccore.project.schemas.base.resources import ( DirectoryResourceKind, ) -from dlc_octopus.schemas.base.symlinks import ( +from dlccore.project.schemas.base.symlinks import ( SymlinkObservation, SymlinkTargetKind, ) -from dlc_octopus.schemas.base.validation import ( +from dlccore.project.schemas.base.validation import ( ValidationCheckStatus, ValidationDepth, ) -from dlc_octopus.validation import ( +from dlccore.project.validation import ( ProjectValidationRequest, ResourceValidationRequest, ) -from dlc_octopus.validation.deeplabcut import videos +from dlccore.project.validation.deeplabcut import videos pytestmark = pytest.mark.data_validator("VIDEOS") @@ -338,7 +349,7 @@ def test_a_broken_link_in_videos_is_reported_once( def fake_probe_path(path: Path) -> PathProbe: return broken(path) if path.name == link.name else real_probe_path(path) - monkeypatch.setattr("dlc_octopus.discovery.observer.probe_path", fake_probe_path) + monkeypatch.setattr("dlccore.project.discovery.observer.probe_path", fake_probe_path) monkeypatch.setattr(videos, "probe_path", fake_probe_path) set_configured_videos(valid_project, (link,)) @@ -377,7 +388,7 @@ def test_a_resolved_path_never_reaches_a_finding( real_resolve = Path.resolve resolved: list[Path] = [] - def volume_guid_resolve(self: Path, strict: bool = False) -> Path: # noqa: FBT001, FBT002 - Path.resolve's signature + def volume_guid_resolve(self: Path, strict: bool = False) -> Path: path = real_resolve(self, strict=strict) resolved.append(path) @@ -663,7 +674,7 @@ def fake_probe_path(path: Path) -> PathProbe: return real_probe_path(path) monkeypatch.setattr( - "dlc_octopus.discovery.observer.probe_path", + "dlccore.project.discovery.observer.probe_path", fake_probe_path, ) @@ -712,7 +723,7 @@ def fake_probe_path(path: Path) -> PathProbe: return real_probe_path(path) - monkeypatch.setattr("dlc_octopus.discovery.observer.probe_path", fake_probe_path) + monkeypatch.setattr("dlccore.project.discovery.observer.probe_path", fake_probe_path) set_configured_videos(valid_project, (master,)) snapshot = inspect_project(valid_project, validation=video_filename_request()) @@ -748,7 +759,7 @@ def fake_probe_path(path: Path) -> PathProbe: return real_probe_path(path) - monkeypatch.setattr("dlc_octopus.discovery.observer.probe_path", fake_probe_path) + monkeypatch.setattr("dlccore.project.discovery.observer.probe_path", fake_probe_path) set_configured_videos(valid_project, (master,)) snapshot = inspect_project(valid_project, validation=video_filename_request()) diff --git a/tests/project/validation/test_baseline.py b/tests/project/validation/test_baseline.py index 2055408..6f47c01 100644 --- a/tests/project/validation/test_baseline.py +++ b/tests/project/validation/test_baseline.py @@ -1,12 +1,23 @@ +# +# 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 pathlib import Path -from dlc_octopus.api import inspect_project -from dlc_octopus.capabilities import get_project_manager_capabilities -from dlc_octopus.validation.baseline import ( +from dlccore.project.api import inspect_project +from dlccore.project.capabilities import get_project_manager_capabilities +from dlccore.project.validation.baseline import ( iter_baseline_check_registrations, run_baseline_checks, ) -from dlc_octopus.validation.context import ( +from dlccore.project.validation.context import ( build_validation_context, ) diff --git a/tests/project/validation/test_context.py b/tests/project/validation/test_context.py index aa4c4f0..870ae14 100644 --- a/tests/project/validation/test_context.py +++ b/tests/project/validation/test_context.py @@ -1,9 +1,20 @@ +# +# 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 pathlib import Path -from dlc_octopus.api import inspect_project -from dlc_octopus.validation.context import ( +from dlccore.project.api import inspect_project +from dlccore.project.validation.context import ( build_validation_context, ) diff --git a/tests/project/validation/test_finding_schema_ids.py b/tests/project/validation/test_finding_schema_ids.py index 885959c..de4702f 100644 --- a/tests/project/validation/test_finding_schema_ids.py +++ b/tests/project/validation/test_finding_schema_ids.py @@ -1,28 +1,39 @@ +# +# 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 collections.abc import Callable from pathlib import Path import pytest -from deeplabcut.core.config.utils import write_config -from dlc_octopus.api import inspect_project -from dlc_octopus.discovery.probe import probe_path -from dlc_octopus.schemas.base.filesystem import walk_schema -from dlc_octopus.schemas.base.finding_codes import ( +from dlccore.config.utils import write_config +from dlccore.project.api import inspect_project +from dlccore.project.discovery.probe import probe_path +from dlccore.project.schemas.base.filesystem import walk_schema +from dlccore.project.schemas.base.finding_codes import ( ConfigFindingCode, ConfiguredVideoFindingCode, StructureFindingCode, ) -from dlc_octopus.schemas.base.findings import Finding, Reach -from dlc_octopus.schemas.base.probes import FilesystemEntryKind, PathProbe, PathProbeStatus -from dlc_octopus.schemas.base.resources import DirectoryResourceKind -from dlc_octopus.schemas.base.symlinks import SymlinkObservation, SymlinkTargetKind -from dlc_octopus.schemas.base.validation import ValidationDepth -from dlc_octopus.schemas.locations import all_of, one_of, one_per_project -from dlc_octopus.schemas.project_layout.project import PROJECT, PROJECT_INDEX -from dlc_octopus.schemas.snapshots import ProjectSnapshot -from dlc_octopus.validation import ProjectValidationRequest, ResourceValidationRequest +from dlccore.project.schemas.base.findings import Finding, Reach +from dlccore.project.schemas.base.probes import FilesystemEntryKind, PathProbe, PathProbeStatus +from dlccore.project.schemas.base.resources import DirectoryResourceKind +from dlccore.project.schemas.base.symlinks import SymlinkObservation, SymlinkTargetKind +from dlccore.project.schemas.base.validation import ValidationDepth +from dlccore.project.schemas.locations import all_of, one_of, one_per_project +from dlccore.project.schemas.project_layout.project import PROJECT, PROJECT_INDEX +from dlccore.project.schemas.snapshots import ProjectSnapshot +from dlccore.project.validation import ProjectValidationRequest, ResourceValidationRequest _DECLARED = frozenset(schema.schema_id for schema, _ in walk_schema(PROJECT)) _NODES = PROJECT_INDEX.schemas @@ -159,7 +170,7 @@ def fake_probe_path(path: Path) -> PathProbe: ), ) - monkeypatch.setattr("dlc_octopus.discovery.observer.probe_path", fake_probe_path) + monkeypatch.setattr("dlccore.project.discovery.observer.probe_path", fake_probe_path) findings = inspect_project(tmp_path).findings diff --git a/tests/project/validation/test_project.py b/tests/project/validation/test_project.py index 8d836c4..3e28b5f 100644 --- a/tests/project/validation/test_project.py +++ b/tests/project/validation/test_project.py @@ -1,14 +1,25 @@ +# +# 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 pathlib import Path import pytest -from dlc_octopus.api import inspect_project -from dlc_octopus.schemas.base.resources import DirectoryResourceKind -from dlc_octopus.schemas.base.validation import ValidationDepth -from dlc_octopus.validation import validate_project -from dlc_octopus.validation.requests import ProjectValidationRequest, ResourceValidationRequest +from dlccore.project.api import inspect_project +from dlccore.project.schemas.base.resources import DirectoryResourceKind +from dlccore.project.schemas.base.validation import ValidationDepth +from dlccore.project.validation import validate_project +from dlccore.project.validation.requests import ProjectValidationRequest, ResourceValidationRequest def test_validate_project_returns_structural_findings( diff --git a/tests/project/validation/test_validation_coverage.py b/tests/project/validation/test_validation_coverage.py index b48b187..7d595b9 100644 --- a/tests/project/validation/test_validation_coverage.py +++ b/tests/project/validation/test_validation_coverage.py @@ -1,6 +1,17 @@ +# +# 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 +# + import pytest -from dlc_octopus.validation.registry import ( +from dlccore.project.validation.registry import ( iter_validator_registrations, ) diff --git a/tests/upstream/test_deeplabcut.py b/tests/upstream/test_deeplabcut.py index eee206d..4e326da 100644 --- a/tests/upstream/test_deeplabcut.py +++ b/tests/upstream/test_deeplabcut.py @@ -396,3 +396,19 @@ def test_convertcsv2h5_reads_a_bodypart_containing_individuals_as_single_animal( pd.DataFrame([[0.0, 1.0, 2.0, 3.0]] * 3, index=index, columns=columns).to_csv(source) assert list(_convertcsv2h5(valid_project, source).columns) == list(columns) + + +def test_reading_a_moved_project_rewrites_its_config(valid_project: Path) -> None: + """DeepLabCut's reader repairs a moved project by writing; dlccore's inspection of the same project does not.""" + + utils = pytest.importorskip("deeplabcut.core.config.utils") + + config_path = valid_project / "config.yaml" + config = utils.read_config_as_dict(config_path) + config["project_path"] = str(valid_project / "declared-elsewhere") + utils.write_config(config_path, config) + before = config_path.read_bytes() + + utils.read_config(config_path) + + assert config_path.read_bytes() != before From 08f5345a58570ff0107d76f7e458fdd37a75c998 Mon Sep 17 00:00:00 2001 From: Cyril Achard Date: Mon, 30 Nov 2026 10:40:01 +0100 Subject: [PATCH 3/3] Improve symlink and file identity tests Cover video symlink matching and collisions, alternate path spellings, and comparisons without file IDs. Use file identities for cross-platform target assertions. --- tests/project/discovery/test_symlinks.py | 12 ++-- .../deeplabcut/test_project_path.py | 25 ++++++- .../validation/deeplabcut/test_videos.py | 65 +++++++++++++++++-- 3 files changed, 87 insertions(+), 15 deletions(-) diff --git a/tests/project/discovery/test_symlinks.py b/tests/project/discovery/test_symlinks.py index bf805d3..857411f 100644 --- a/tests/project/discovery/test_symlinks.py +++ b/tests/project/discovery/test_symlinks.py @@ -23,7 +23,7 @@ classify_unclaimed_entry, status_for_expected_entry, ) -from dlccore.project.discovery.probe import probe_path +from dlccore.project.discovery.probe import file_identity, probe_path from dlccore.project.schemas.base.observations import NodeStatus from dlccore.project.schemas.base.probes import ( FilesystemEntryKind, @@ -304,7 +304,7 @@ def test_inspection_preserves_valid_video_symlink( assert resource is not None assert resource.kind == FileResourceKind.SOURCE_VIDEO assert resource.symlink is not None - assert resource.symlink.absolute_target == target.absolute() + assert file_identity(resource.symlink.absolute_target) == file_identity(target) assert resource.symlink.target_kind == SymlinkTargetKind.FILE @@ -327,7 +327,9 @@ def test_inspection_preserves_broken_video_symlink( assert resource is not None assert resource.kind == FileResourceKind.SOURCE_VIDEO assert resource.symlink is not None - assert resource.symlink.absolute_target == target.absolute() + assert resource.symlink.raw_target == link.readlink() + assert resource.symlink.absolute_target.name == target.name + assert file_identity(resource.symlink.absolute_target.parent) == file_identity(tmp_path) assert resource.symlink.target_kind == SymlinkTargetKind.MISSING @@ -340,7 +342,7 @@ def test_inspection_retains_an_unclaimed_directory_symlink( The mapping is covered by constructed probes above, which run everywhere. This covers the wiring - probe, unknown-child collection, ``ProjectResource`` - construction and flattening - and needs a real link, so it skips on Windows. + construction and flattening - and needs a real link, so it skips where links cannot be created. """ target = tmp_path / "relocated" @@ -360,7 +362,7 @@ def test_inspection_retains_an_unclaimed_directory_symlink( assert resource.kind == DirectoryResourceKind.UNKNOWN_DIRECTORY assert resource.management == ResourceManagement.UNDETERMINED assert resource.symlink is not None - assert resource.symlink.absolute_target == target.absolute() + assert file_identity(resource.symlink.absolute_target) == file_identity(target) assert resource.symlink.target_kind == SymlinkTargetKind.DIRECTORY diff --git a/tests/project/validation/deeplabcut/test_project_path.py b/tests/project/validation/deeplabcut/test_project_path.py index 58a7f55..46510b4 100644 --- a/tests/project/validation/deeplabcut/test_project_path.py +++ b/tests/project/validation/deeplabcut/test_project_path.py @@ -12,7 +12,6 @@ from __future__ import annotations import ctypes -import os import sys from collections.abc import Callable from pathlib import Path @@ -77,6 +76,26 @@ def test_mismatched_project_path_produces_note( } +@pytest.mark.usefixtures("without_file_ids") +def test_without_file_ids_another_directory_is_still_a_mismatch( + tmp_path: Path, + valid_config_data: dict, +) -> None: + project = tmp_path / "project" + (project / "videos").mkdir(parents=True) + (project / "labeled-data").mkdir() + elsewhere = tmp_path / "elsewhere" + elsewhere.mkdir() + + config_data = dict(valid_config_data) + config_data["project_path"] = str(elsewhere) + write_config(project / "config.yaml", config_data) + + snapshot = inspect_project(project) + + assert "CONFIG_PROJECT_PATH_MISMATCH" in {finding.code for finding in snapshot.findings} + + def test_inspecting_a_moved_project_leaves_its_config_untouched( tmp_path: Path, valid_config_data: dict, @@ -302,10 +321,10 @@ def test_an_existing_declared_path_that_cannot_be_compared_keeps_the_error( original.mkdir() copy = _project_with_declared_path(tmp_path / "copy", valid_config_data, str(original)) - def uncomparable(*_paths: object) -> bool: + def uncomparable(*_args: object, **_kwargs: object) -> object: raise OSError("target vanished") - monkeypatch.setattr(os.path, "samefile", uncomparable) + monkeypatch.setattr(project_path_module, "file_identity", uncomparable) (finding,) = _project_path_findings(copy) diff --git a/tests/project/validation/deeplabcut/test_videos.py b/tests/project/validation/deeplabcut/test_videos.py index 5b5aaa6..df8c3f4 100644 --- a/tests/project/validation/deeplabcut/test_videos.py +++ b/tests/project/validation/deeplabcut/test_videos.py @@ -21,7 +21,7 @@ write_config, ) from dlccore.project.api import inspect_project -from dlccore.project.discovery.probe import probe_path +from dlccore.project.discovery.probe import file_identity, probe_path from dlccore.project.schemas.base.findings import Reach, Severity from dlccore.project.schemas.base.probes import ( FilesystemEntryKind, @@ -332,11 +332,13 @@ def test_the_demo_placeholder_key_is_reported_missing_not_raised( assert finding.field_location == ("video_sets", placeholder) +@pytest.mark.parametrize("key_parts", [("videos",), ("videos", "..", "videos")], ids=["as-is", "other-spelling"]) def test_a_broken_link_in_videos_is_reported_once( valid_project: Path, monkeypatch: pytest.MonkeyPatch, + key_parts: tuple[str, ...], ) -> None: - """The structure finding at the video stands; the key adds no second one. + """The structure finding at the video stands; the key adds no second one, however it spells the link. The file exists so discovery lists it; both probes are faked as a broken link. """ @@ -351,19 +353,23 @@ def fake_probe_path(path: Path) -> PathProbe: monkeypatch.setattr("dlccore.project.discovery.observer.probe_path", fake_probe_path) monkeypatch.setattr(videos, "probe_path", fake_probe_path) - set_configured_videos(valid_project, (link,)) + set_configured_videos(valid_project, (valid_project.joinpath(*key_parts, link.name),)) snapshot = inspect_project(valid_project, validation=video_filename_request()) assert [finding.code for finding in snapshot.findings] == ["PROJECT_SYMLINK_TARGET_MISSING"] +@pytest.mark.usefixtures("without_file_ids") def test_a_resolved_path_never_reaches_a_finding( valid_project: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, ) -> None: - """On Windows with an SMB-mounted drive, ``Path.resolve`` returns ``\\\\?\\Volume{GUID}\\...``.""" + """On Windows with an SMB-mounted drive, ``Path.resolve`` returns ``\\\\?\\Volume{GUID}\\...``. + + File IDs are withheld, so comparison falls back to the resolved path. + """ for name in ("session-01.mp4", "session-02.mp4", "session-03.mp4", "session-04.mp4"): (valid_project / "videos" / name).write_bytes(name.encode()) @@ -790,9 +796,11 @@ def test_two_real_links_to_one_file_collide( ) collisions = tuple(finding for finding in snapshot.findings if finding.code == "PROJECT_RESOURCE_PATH_COLLISION") + collision_paths = {finding.evidence["collision_path"] for finding in collisions} assert len(collisions) == 2 - assert {finding.evidence["collision_path"] for finding in collisions} == {str(master.absolute())} + assert collision_paths == {str((valid_project / "videos" / "session-01.mp4").readlink())} + assert {file_identity(Path(path)) for path in collision_paths} == {file_identity(master)} def test_a_chain_of_links_to_one_file_collides( @@ -827,9 +835,52 @@ def test_a_chain_of_links_to_one_file_collides( by_instance = {finding.instance: finding.evidence for finding in collisions} - assert by_instance[("videos", "session-01.mp4")]["collision_path"] == str(master.absolute()) - assert by_instance[("videos", "session-02.mp4")]["collision_path"] == str(hop.absolute()) + assert by_instance[("videos", "session-01.mp4")]["collision_path"] == str( + (valid_project / "videos" / "session-01.mp4").readlink() + ) + assert by_instance[("videos", "session-02.mp4")]["collision_path"] == str( + (valid_project / "videos" / "session-02.mp4").readlink() + ) + assert file_identity(Path(by_instance[("videos", "session-02.mp4")]["collision_path"])) == file_identity(master) assert {tuple(evidence["collision_group"]) for evidence in by_instance.values()} == { ("videos", "session-01.mp4"), } assert len(collisions) == 2 + + +def test_a_video_symlinked_into_videos_folder_matches_config_entry( + valid_project: Path, + tmp_path: Path, + create_symlink_or_skip: Callable[..., None], +) -> None: + """DeepLabCut's ``create_new_project(copy_videos=False)``: an absolute link in ``videos/``, declared by its path.""" + + source = tmp_path / "raw-data" / "session-01.mp4" + source.parent.mkdir() + source.touch() + + link = valid_project / "videos" / "session-01.mp4" + create_symlink_or_skip(link, source.absolute()) + set_configured_videos(valid_project, (link,)) + + snapshot = inspect_project(valid_project, validation=video_filename_request()) + + assert [finding.code for finding in snapshot.findings] == [] + + +def test_video_and_link_to_it_collide( + valid_project: Path, + create_symlink_or_skip: Callable[..., None], +) -> None: + video = valid_project / "videos" / "session-01.mp4" + video.touch() + create_symlink_or_skip(valid_project / "videos" / "session-02.mp4", video.absolute()) + + snapshot = inspect_project(valid_project, validation=video_filename_request()) + + collisions = [finding for finding in snapshot.findings if finding.code == "PROJECT_RESOURCE_PATH_COLLISION"] + + assert sorted(finding.instance for finding in collisions) == [ + ("videos", "session-01.mp4"), + ("videos", "session-02.mp4"), + ]