diff --git a/dlccore/project/schemas/locations.py b/dlccore/project/schemas/locations.py new file mode 100644 index 0000000..a6b7ee6 --- /dev/null +++ b/dlccore/project/schemas/locations.py @@ -0,0 +1,126 @@ +# +# 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 typing import TypedDict + +from dlccore.project.schemas.base.core import LayoutInstance, SchemaId, instance_from_path +from dlccore.project.schemas.base.filesystem import LayoutIndex, NodeSchema +from dlccore.project.schemas.base.findings import Reach +from dlccore.project.schemas.project_layout.project import PROJECT_INDEX + + +class Location(TypedDict): + """Where a finding is anchored in the layout, ready to pass to ``Finding``.""" + + schema_id: SchemaId + reach: Reach + instance: LayoutInstance + + +def one_per_project( + node: NodeSchema, + *, + index: LayoutIndex = PROJECT_INDEX, +) -> Location: + """Anchor a finding at the only node of its kind in the project. + + Raises: + ValueError: If the node is not in the layout, or lies inside a repeated node. + """ + + if _inside_repeated(index, node): + raise ValueError(f"{node.schema_id!r} lies inside a repeated node, so it has no single instance.") + + return Location(schema_id=node.schema_id, reach=Reach.ONE_PER_PROJECT, instance=()) + + +def one_of( + node: NodeSchema, + instance: LayoutInstance, + *, + index: LayoutIndex = PROJECT_INDEX, +) -> Location: + """Anchor a finding at one named instance of a node that is or lies inside a repeated node. + + Raises: + ValueError: If the node is not in the layout, does not lie inside a repeated node, + or the instance is empty. + """ + + if not _inside_repeated(index, node): + raise ValueError(f"{node.schema_id!r} is the only node of its kind, so it has no instances.") + + if not instance: + raise ValueError(f"{node.schema_id!r} names one instance, but got none.") + + return Location(schema_id=node.schema_id, reach=Reach.ONE_OF, instance=instance) + + +def all_of( + node: NodeSchema, + within: LayoutInstance = (), + *, + index: LayoutIndex = PROJECT_INDEX, +) -> Location: + """Anchor a finding at every instance of a node, optionally within an instance prefix. + + Raises: + ValueError: If the node is not in the layout, or does not lie inside a repeated node. + """ + + if not _inside_repeated(index, node): + raise ValueError(f"{node.schema_id!r} is the only node of its kind, so it has no instances.") + + return Location(schema_id=node.schema_id, reach=Reach.ALL_OF, instance=within) + + +def _inside_repeated( + index: LayoutIndex, + node: NodeSchema, +) -> bool: + """Return whether a layout node is, or lies inside, a repeated node. + + Raises: + ValueError: If the layout does not declare this node. + """ + + if index.schemas.get(node.schema_id) != node: + raise ValueError(f"The layout does not declare this {node.schema_id!r} node.") + + return node.schema_id in index.inside_repeated + + +def node_location( + schema_id: SchemaId, + project_relative_path: Path, + *, + index: LayoutIndex = PROJECT_INDEX, +) -> Location: + """Anchor a finding at the observed node with this schema ID and path: one instance if repeated, else the only one. + + Raises: + ValueError: If the layout does not declare ``schema_id``, or the path is anchored. + """ + + node = index.schemas.get(schema_id) + + if node is None: + raise ValueError(f"The layout does not declare {schema_id!r}.") + + instance = instance_from_path(project_relative_path) + + if schema_id in index.inside_repeated: + return one_of(node, instance, index=index) + + return one_per_project(node, index=index) diff --git a/dlccore/project/schemas/project_layout/config/__init__.py b/dlccore/project/schemas/project_layout/config/__init__.py new file mode 100644 index 0000000..d299338 --- /dev/null +++ b/dlccore/project/schemas/project_layout/config/__init__.py @@ -0,0 +1,22 @@ +# +# 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 .observations import ( + ConfigObservation, + FailedConfigObservation, + ValidConfigObservation, +) + +__all__ = [ + "ConfigObservation", + "FailedConfigObservation", + "ValidConfigObservation", +] diff --git a/dlccore/project/schemas/project_layout/config/observations.py b/dlccore/project/schemas/project_layout/config/observations.py new file mode 100644 index 0000000..73ed480 --- /dev/null +++ b/dlccore/project/schemas/project_layout/config/observations.py @@ -0,0 +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 pathlib import Path +from typing import Any, Literal + +from pydantic import Field + +from dlccore.config import ProjectConfig +from dlccore.project.schemas.base.core import FrozenModel + + +class ValidConfigObservation(FrozenModel): + """A project config successfully loaded through the canonical schema.""" + + status: Literal["valid"] = "valid" + config_path: Path + declared_project_path: str | None = None + + value: ProjectConfig = Field( + exclude=True, + repr=False, + ) + + +class FailedConfigObservation(FrozenModel): + """Diagnostic information retained after config loading failed.""" + + status: Literal["failed"] = "failed" + config_path: Path + + raw_config: dict[str, Any] | None = Field( + default=None, + exclude=True, + repr=False, + ) + + +ConfigObservation = ValidConfigObservation | FailedConfigObservation diff --git a/dlccore/project/schemas/snapshots.py b/dlccore/project/schemas/snapshots.py new file mode 100644 index 0000000..4f80965 --- /dev/null +++ b/dlccore/project/schemas/snapshots.py @@ -0,0 +1,210 @@ +# +# DeepLabCut Toolbox (deeplabcut.org) +# © A. & M.W. Mathis Labs +# https://github.com/DeepLabCut/dlccore +# +# Contributors: +# https://github.com/DeepLabCut/dlccore/graphs/contributors +# +# Licensed under GNU Lesser General Public License v3.0 +# + +from __future__ import annotations + +from enum import Enum +from pathlib import Path +from typing import TYPE_CHECKING, Literal + +from pydantic import model_validator +from typing_extensions import Self + +from dlccore.project.errors import ConfigUnavailableError +from dlccore.project.schemas.base.core import FrozenModel +from dlccore.project.schemas.base.findings import ( + Finding, + Reach, +) +from dlccore.project.schemas.base.observations import ObservedNode +from dlccore.project.schemas.base.resources import ( + ProjectResource, + ResourceKind, +) +from dlccore.project.schemas.base.validation import ValidationCheck +from dlccore.project.schemas.project_layout.config import ( + ConfigObservation, + FailedConfigObservation, + ValidConfigObservation, +) +from dlccore.project.schemas.utils import flatten_observed_project + +if TYPE_CHECKING: + from dlccore.config import ProjectConfig + from dlccore.project.validation.results import ValidationResult + +# 0.x declares the snapshot format unstable: it changes with the vocabulary and carries +# no compatibility promise. Bumping is owed once a consumer reads a snapshot back. +ProjectSnapshotVersion = Literal["0.0"] +PROJECT_SNAPSHOT_VERSION: ProjectSnapshotVersion = "0.0" + + +class ConfigState(str, Enum): + MISSING = "missing" + VALID = "valid" + INVALID = "invalid" + + +class ProjectSnapshot(FrozenModel): + """Read-only description of a DeepLabCut project at inspection time. + + ``project`` is the authoritative schema-derived tree. It includes + expected nodes that may be missing, unreadable, or have the wrong + filesystem type. + + ``resources`` is a deterministic flat projection of physical entries + from that tree. It includes any schema-defined node with an actual + filesystem entry - present, wrong-type, or unreadable alike - plus + immediate unclaimed resources. Only nodes with no filesystem entry at + all remain available exclusively through ``project``. + """ + + version: ProjectSnapshotVersion = PROJECT_SNAPSHOT_VERSION + project_root: Path + config_observation: ConfigObservation | None = None + project: ObservedNode + resources: tuple[ProjectResource, ...] = () + findings: tuple[Finding, ...] = () + validation_checks: tuple[ValidationCheck, ...] = () + + @property + def resources_by_path( + self, + ) -> dict[Path, ProjectResource]: + """Index the flat resource projection (physical) by project-relative path.""" + + return {resource.project_relative_path: resource for resource in self.resources} + + @classmethod + def from_project( + cls, + *, + project_root: Path, + project: ObservedNode, + config_observation: ConfigObservation | None = None, + findings: tuple[Finding, ...] = (), + validation_checks: tuple[ValidationCheck, ...] = (), + ) -> ProjectSnapshot: + """Build a snapshot from the observed project tree and derive its resources.""" + return cls( + project_root=project_root, + project=project, + config_observation=config_observation, + findings=findings, + resources=flatten_observed_project(project), + validation_checks=validation_checks, + ) + + def with_validation_result( + self, + result: ValidationResult, + ) -> ProjectSnapshot: + """Return a copy with validation findings and checks merged in. + + Unlike ``model_copy``, this reconstructs the snapshot from its + current field values, so model validators run again on the result + """ + + return ProjectSnapshot( + **{ + **dict(self), + "findings": (self.findings + result.findings), + "validation_checks": (self.validation_checks + result.checks), + } + ) + + @model_validator(mode="after") + def validate_resource_projection( + self, + ) -> Self: + expected = flatten_observed_project(self.project) + + if self.resources != expected: + raise ValueError("Snapshot resources must be the deterministic projection of the observed project tree.") + + return self + + @model_validator(mode="after") + def refuse_unrooted_findings(self) -> Self: + """Refuse a finding outside any known project: the scope query matches instances from the project root.""" + + if unrooted := [finding for finding in self.findings if finding.reach is Reach.UNROOTED]: + raise ValueError(f"A snapshot holds no UNROOTED finding; got {unrooted[0].code} at {unrooted[0].instance}.") + + return self + + def resources_of_kind( + self, + kind: ResourceKind, + ) -> tuple[ProjectResource, ...]: + """Return resources having the requested semantic kind.""" + + return tuple(resource for resource in self.resources if resource.kind == kind) + + def resource_at( + self, + project_relative_path: str | Path, + ) -> ProjectResource | None: + """Return the resource observed at one project-relative path.""" + target = Path(project_relative_path) + return next( + (resource for resource in self.resources if resource.project_relative_path == target), + None, + ) + + @property + def config_state( + self, + ) -> ConfigState: + """Return the canonical configuration observation state.""" + + if self.config_observation is None: + return ConfigState.MISSING + + if self.failed_config is not None: + return ConfigState.INVALID + + return ConfigState.VALID + + @property + def config(self) -> ProjectConfig: + """Return canonical config data or fail explicitly.""" + observation = self.config_observation + if isinstance( + observation, + ValidConfigObservation, + ): + return observation.value + + if isinstance( + observation, + FailedConfigObservation, + ): + raise ConfigUnavailableError( + "The project config was found but could not be loaded through the canonical ProjectConfig schema." + ) + + raise ConfigUnavailableError("The project does not have an observed config.") + + @property + def failed_config( + self, + ) -> FailedConfigObservation | None: + """Return failed config diagnostics, if loading failed.""" + observation = self.config_observation + + if isinstance( + observation, + FailedConfigObservation, + ): + return observation + + return None diff --git a/pyproject.toml b/pyproject.toml index a54dffd..fafcbf5 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -93,3 +93,10 @@ ini_options.filterwarnings = [ # A categorical groupby must state observed=; the default changes in pandas 3. "error:The default of observed=False is deprecated:FutureWarning", ] +ini_options.markers = [ + "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 \ + snapshot versions are both 0.x, a plain test once either leaves\ + """, +] diff --git a/tests/config/test_config_breakage.py b/tests/config/test_config_breakage.py index 6622414..6c8c7e9 100644 --- a/tests/config/test_config_breakage.py +++ b/tests/config/test_config_breakage.py @@ -30,7 +30,8 @@ @pytest.mark.xfail( reason="This may make validation difficult and cause subtle issues " "if we start changing how functions such as append() operate." - " Avoiding lists in configs could be a better long-term solution." + " Avoiding lists in configs could be a better long-term solution.", + raises=pytest.fail.Exception, ) def test_in_place_list_mutation_should_be_validated_like_assignment(): """Appending to a config list changes config state without calling __setattr__. @@ -49,7 +50,7 @@ def test_in_place_list_mutation_should_be_validated_like_assignment(): cfg.TrainingFraction.append(1.5) -@pytest.mark.xfail(reason="Not implemented yet") +@pytest.mark.xfail(reason="Not implemented yet", raises=AssertionError) @pytest.mark.parametrize( ("field_name", "mutate"), [ @@ -257,6 +258,7 @@ def test_item_assignment_with_alias_should_warn_once_and_track_canonical_field() "model validators run on each assignment, so intermediate states " "like multianimalproject=True with bodyparts=[] are rejected." ), + raises=ValidationError, ) def test_update_applies_cross_field_overrides_atomically(): """Bulk update should validate the merged state, not each setattr in isolation.""" diff --git a/tests/config/test_project_config.py b/tests/config/test_project_config.py index 19ad559..b83597a 100644 --- a/tests/config/test_project_config.py +++ b/tests/config/test_project_config.py @@ -336,6 +336,7 @@ def test_unversioned_yaml_treated_as_v0(self, tmp_path): class TestFieldsPendingSchemaMigration: @pytest.mark.xfail( strict=True, + raises=AssertionError, reason=( "bboxes_pcutoff is a property until the schema version is bumped, " "see https://github.com/DeepLabCut/DeepLabCut/pull/3470" diff --git a/tests/conftest.py b/tests/conftest.py index c048e39..8d169e3 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -12,11 +12,83 @@ import gc import os from collections.abc import Callable +from importlib import metadata from pathlib import Path import pytest +from dlccore.config import ProjectConfig from dlccore.project.schemas.base.finding_codes import FindingCode, Severity +from dlccore.project.schemas.snapshots import PROJECT_SNAPSHOT_VERSION + + +def _owed_is_deferred(package_version: str, snapshot_version: str) -> bool: + """Whether prototype maintenance may still wait: only while both versions are 0.x.""" + + return package_version.startswith("0.") and snapshot_version.startswith("0.") + + +@pytest.fixture +def owed_is_deferred() -> Callable[[str, str], bool]: + """The rule behind ``owed_before_release``, exposed so it can be tested.""" + + return _owed_is_deferred + + +def _expected_failures_without_raises(items: list[pytest.Item]) -> list[str]: + """Node ids of tests with an ``xfail`` or ``owed_before_release`` marker that does not name its exception. + + Without ``raises=``, any exception satisfies an xfail, so a test broken by a rename or a fixture error + still counts as the expected failure. + """ + + return [ + item.nodeid + for item in items + if any( + "raises" not in marker.kwargs + for name in ("xfail", "owed_before_release") + for marker in item.iter_markers(name) + ) + ] + + +@pytest.fixture +def expected_failures_without_raises() -> Callable[[list[pytest.Item]], list[str]]: + """The rule behind the collection check on ``raises=``, exposed so it can be tested.""" + + return _expected_failures_without_raises + + +def pytest_collection_modifyitems(items: list[pytest.Item]) -> None: + """Refuse an expected failure that does not name its exception, and turn every ``owed_before_release`` test + into a strict xfail while the package is 0.x. + + Raises: + pytest.UsageError: If a collected ``xfail`` or ``owed_before_release`` marker has no ``raises=``. + """ + + missing = _expected_failures_without_raises(items) + + if missing: + raise pytest.UsageError( + "Every xfail and owed_before_release marker must declare raises=:\n " + "\n ".join(missing) + ) + + if not _owed_is_deferred(metadata.version("dlccore"), PROJECT_SNAPSHOT_VERSION): + return + + for item in items: + marker = item.get_closest_marker("owed_before_release") + + if marker is not None: + item.add_marker( + pytest.mark.xfail( + reason=f"owed before release: {marker.kwargs['reason']}", + strict=True, + raises=marker.kwargs["raises"], + ) + ) def _create_symlink_or_skip( @@ -100,3 +172,35 @@ def pytest_runtest_setup() -> None: if _example_codes_declared: gc.collect() _example_codes_declared = False + + +@pytest.fixture +def valid_project_config( + tmp_path: Path, +) -> ProjectConfig: + """Return a canonical valid project configuration for tests.""" + + return ProjectConfig( + Task="test-project", + scorer="test-scorer", + date="2026-01-01", + project_path=tmp_path, + bodyparts=["nose", "tail"], + ) + + +@pytest.fixture +def valid_project( + tmp_path: Path, + valid_project_config: ProjectConfig, +) -> Path: + """Create a minimal project containing a canonical config.""" + + (tmp_path / "videos").mkdir() + (tmp_path / "labeled-data").mkdir() + + valid_project_config.to_yaml( + tmp_path / "config.yaml", + ) + + return tmp_path diff --git a/tests/project/schemas/test_locations.py b/tests/project/schemas/test_locations.py new file mode 100644 index 0000000..c884ef1 --- /dev/null +++ b/tests/project/schemas/test_locations.py @@ -0,0 +1,110 @@ +# +# 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 dlccore.project.schemas.base.filesystem import FileSchema, NamePattern +from dlccore.project.schemas.base.findings import Reach +from dlccore.project.schemas.base.resources import FileResourceKind +from dlccore.project.schemas.locations import all_of, node_location, one_of, one_per_project +from dlccore.project.schemas.project_layout.labeled_data import LABELED_DATASET, LABELED_FRAME, NAPARI_DLC_METADATA +from dlccore.project.schemas.project_layout.project import PROJECT_CONFIG +from dlccore.project.schemas.project_layout.videos import SOURCE_VIDEO + + +def test_the_only_node_of_its_kind_is_one_per_project() -> None: + assert one_per_project(PROJECT_CONFIG) == { + "schema_id": "dlc.project.config", + "reach": Reach.ONE_PER_PROJECT, + "instance": (), + } + + +def test_a_repeated_node_is_not_one_per_project() -> None: + with pytest.raises(ValueError, match=r"dlc\.videos\.source_video"): + one_per_project(SOURCE_VIDEO) + + +def test_one_instance_of_a_repeated_node_is_one_of() -> None: + assert one_of(SOURCE_VIDEO, ("videos", "a.mp4")) == { + "schema_id": "dlc.videos.source_video", + "reach": Reach.ONE_OF, + "instance": ("videos", "a.mp4"), + } + + +def test_a_node_inside_a_repeated_node_is_one_of() -> None: + location = one_of(NAPARI_DLC_METADATA, ("labeled-data", "m1", ".napari-deeplabcut.json")) + + assert location["reach"] is Reach.ONE_OF + + +def test_one_of_refuses_an_empty_instance() -> None: + with pytest.raises(ValueError, match="got none"): + one_of(SOURCE_VIDEO, ()) + + +def test_the_only_node_of_its_kind_is_not_one_of() -> None: + with pytest.raises(ValueError, match=r"dlc\.project\.config"): + one_of(PROJECT_CONFIG, ("config.yaml",)) + + +def test_every_instance_within_a_prefix_is_all_of() -> None: + assert all_of(LABELED_FRAME, ("labeled-data", "m1")) == { + "schema_id": "dlc.labeled_data.frame", + "reach": Reach.ALL_OF, + "instance": ("labeled-data", "m1"), + } + assert all_of(LABELED_DATASET)["instance"] == () + + +def test_the_only_node_of_its_kind_is_not_all_of() -> None: + with pytest.raises(ValueError, match=r"dlc\.project\.config"): + all_of(PROJECT_CONFIG) + + +def test_a_node_the_layout_does_not_declare_is_refused() -> None: + elsewhere = FileSchema( + schema_id="dlc.elsewhere", + kind=FileResourceKind.PROJECT_CONFIG, + name=NamePattern(exact="elsewhere.yaml"), + ) + + with pytest.raises(ValueError, match="does not declare"): + one_per_project(elsewhere) + + +def test_a_node_reusing_a_layout_id_with_another_definition_is_refused() -> None: + impostor = PROJECT_CONFIG.model_copy(update={"description": "Not the declared config node."}) + + with pytest.raises(ValueError, match="does not declare"): + one_per_project(impostor) + + +def test_an_observed_node_is_anchored_by_its_schema_id_and_path() -> None: + assert node_location("dlc.project.config", Path("config.yaml")) == one_per_project(PROJECT_CONFIG) + assert node_location("dlc.videos.source_video", Path("videos/a.mp4")) == one_of(SOURCE_VIDEO, ("videos", "a.mp4")) + + +@pytest.mark.parametrize("schema_id", ["dlc.project.config", "dlc.videos.source_video"]) +@pytest.mark.parametrize("path", [Path("/abs/config.yaml"), Path("C:/abs/config.yaml")], ids=["posix", "windows"]) +def test_an_anchored_path_is_refused_for_every_node(schema_id: str, path: Path) -> None: + with pytest.raises(ValueError): + node_location(schema_id, path) + + +def test_an_observed_node_the_layout_does_not_declare_is_refused() -> None: + with pytest.raises(ValueError, match=r"dlc\.nowhere"): + node_location("dlc.nowhere", Path("x")) diff --git a/tests/test_expected_failures.py b/tests/test_expected_failures.py new file mode 100644 index 0000000..f3b6cb2 --- /dev/null +++ b/tests/test_expected_failures.py @@ -0,0 +1,101 @@ +# +# 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 subprocess +import sys +from collections.abc import Callable, Iterator +from dataclasses import dataclass +from pathlib import Path + +import pytest + +Rule = Callable[[list], list[str]] + + +@dataclass(frozen=True) +class _Item: + nodeid: str + marks: tuple[pytest.Mark, ...] + + def iter_markers(self, name: str) -> Iterator[pytest.Mark]: + return (mark for mark in self.marks if mark.name == name) + + +def _item(*marks: pytest.MarkDecorator) -> _Item: + return _Item(nodeid="test_x.py::test_x", marks=tuple(mark.mark for mark in marks)) + + +@pytest.mark.parametrize( + "marks", + [ + (pytest.mark.xfail(reason="owed", strict=True),), + (pytest.mark.owed_before_release(reason="owed"),), + (pytest.mark.xfail(reason="class", strict=True), pytest.mark.xfail(reason="test", raises=AssertionError)), + ], + ids=["xfail", "owed_before_release", "one_of_several_xfails"], +) +def test_an_expected_failure_without_raises_is_flagged( + expected_failures_without_raises: Rule, + marks: tuple[pytest.MarkDecorator, ...], +) -> None: + assert expected_failures_without_raises([_item(*marks)]) == ["test_x.py::test_x"] + + +def test_expected_failures_that_name_their_exception_pass(expected_failures_without_raises: Rule) -> None: + items = [ + _item(pytest.mark.xfail(reason="owed", strict=True, raises=AssertionError)), + _item(pytest.mark.owed_before_release(reason="owed", raises=AttributeError)), + _item(pytest.mark.parametrize("x", [1])), + ] + + assert expected_failures_without_raises(items) == [] + + +def test_every_collected_expected_failure_names_its_exception( + expected_failures_without_raises: Rule, + request: pytest.FixtureRequest, +) -> None: + items = request.session.items + expected = [ + item for item in items if item.get_closest_marker("xfail") or item.get_closest_marker("owed_before_release") + ] + + if not expected: + pytest.skip("no xfail or owed_before_release test was selected in this run") + + assert expected_failures_without_raises(items) == [] + + +def test_an_xfail_raising_another_exception_fails(tmp_path: Path) -> None: + # Control: raises= only helps if pytest reports a different exception as a failure, not as the expected one. + (tmp_path / "test_probe.py").write_text( + "import pytest\n\n" + "@pytest.mark.xfail(raises=AssertionError, strict=True)\n" + "def test_wrong_reason():\n" + " undefined_name\n\n" + "@pytest.mark.xfail(raises=AssertionError, strict=True)\n" + "def test_right_reason():\n" + " assert False\n", + encoding="utf-8", + ) + (tmp_path / "pytest.ini").write_text("[pytest]\n", encoding="utf-8") + + run = subprocess.run( + [sys.executable, "-m", "pytest", "-q", "-p", "no:cacheprovider", "--rootdir", str(tmp_path), str(tmp_path)], + capture_output=True, + text=True, + cwd=tmp_path, + check=False, + ) + + assert "1 failed, 1 xfailed" in run.stdout, run.stdout + run.stderr diff --git a/tests/test_owed_before_release.py b/tests/test_owed_before_release.py new file mode 100644 index 0000000..0013a93 --- /dev/null +++ b/tests/test_owed_before_release.py @@ -0,0 +1,44 @@ +# +# 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 + +import pytest + + +@pytest.mark.parametrize( + ("package_version", "snapshot_version", "deferred"), + [ + ("0.0.1", "0.0", True), + ("1.0.0", "0.0", False), + ("0.0.1", "1.0", False), + ("1.0.0", "1.0", False), + ], +) +def test_owed_work_waits_only_while_both_versions_are_zero( + owed_is_deferred: Callable[[str, str], bool], + package_version: str, + snapshot_version: str, + *, + deferred: bool, +) -> None: + assert owed_is_deferred(package_version, snapshot_version) is deferred + + +def test_every_owed_test_is_xfailed_while_deferred(request: pytest.FixtureRequest) -> None: + owed = [item for item in request.session.items if item.get_closest_marker("owed_before_release")] + + if not owed: + pytest.skip("no owed_before_release test was selected in this run") + + assert all(item.get_closest_marker("xfail") is not None for item in owed) diff --git a/tests/upstream/test_deeplabcut.py b/tests/upstream/test_deeplabcut.py new file mode 100644 index 0000000..eee206d --- /dev/null +++ b/tests/upstream/test_deeplabcut.py @@ -0,0 +1,398 @@ +# +# 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 +# + +"""Tests whose home is DeepLabCut. Imports ``deeplabcut`` only.""" + +import shutil +from pathlib import Path +from typing import TYPE_CHECKING + +import pytest + +if TYPE_CHECKING: + import pandas as pd + + from dlccore.io.labeled_data._wide.row_index import LabeledDataRowIndex + +pytestmark = pytest.mark.destination("deeplabcut") + +LABELED_DATA_FIXTURES = Path(__file__).parents[1] / "io" / "fixtures" / "labeled_data" +_FIXTURE_SCORER = "Sc" + +_SUBSTRING_FILTER = ( + "labeled-data folders are filtered with the substring '_labeled', " + "so a legitimately named dataset folder is invisible to DeepLabCut's own enumeration" +) + + +def _configured_videos(project_root: Path) -> dict[str, dict]: + """Return ``video_sets`` as DeepLabCut would read it back from disk.""" + + utils = pytest.importorskip("deeplabcut.core.config.utils") + + return utils.read_config_as_dict(project_root / "config.yaml")["video_sets"] + + +def _declare_videos(project_root: Path, stems: tuple[str, ...]) -> None: + """Point ``video_sets`` at ``videos/.mp4`` without creating the files. + + The files are deliberately absent. Reconciliation re-adds a folder that has + no config entry by opening the matching video, and an empty ``.mp4`` raises + from ``VideoReader`` — which would make a test fail for a reason that has + nothing to do with what it is pinning. + """ + + utils = pytest.importorskip("deeplabcut.core.config.utils") + + config_path = project_root / "config.yaml" + config = utils.read_config_as_dict(config_path) + + config["video_sets"] = {str(project_root / "videos" / f"{stem}.mp4"): {"crop": "0, 100, 0, 100"} for stem in stems} + + utils.write_config(config_path, config) + + +def _add_dataset_folder(project_root: Path, name: str) -> Path: + folder = project_root / "labeled-data" / name + folder.mkdir(parents=True, exist_ok=True) + + return folder + + +def test_normally_named_folder_keeps_its_video_entry(valid_project: Path) -> None: + """Control: the reconciliation runs and leaves a matched pair alone. + + Without this, a test asserting that some entry survives cannot distinguish + "the filter is correct" from "the function never did anything". + """ + + trainingsetmanipulation = pytest.importorskip("deeplabcut.generate_training_dataset.trainingsetmanipulation") + + _declare_videos(valid_project, ("session-01",)) + _add_dataset_folder(valid_project, "session-01") + + trainingsetmanipulation.adddatasetstovideolistandviceversa(str(valid_project / "config.yaml")) + + assert [Path(video).stem for video in _configured_videos(valid_project)] == ["session-01"] + + +@pytest.mark.xfail(reason=_SUBSTRING_FILTER, strict=True, raises=AssertionError) +def test_a_video_named_labeled_keeps_its_config_entry(valid_project: Path) -> None: + """A user's video may legitimately be called ``trial_labeled_v2``. + + Its dataset folder is filtered out as if it were ``check_labels`` output, + the stem is then reported missing, and the entry is deleted from + ``config.yaml`` on disk. + """ + + trainingsetmanipulation = pytest.importorskip("deeplabcut.generate_training_dataset.trainingsetmanipulation") + + _declare_videos(valid_project, ("trial_labeled_v2",)) + _add_dataset_folder(valid_project, "trial_labeled_v2") + + trainingsetmanipulation.adddatasetstovideolistandviceversa(str(valid_project / "config.yaml")) + + assert [Path(video).stem for video in _configured_videos(valid_project)] == ["trial_labeled_v2"] + + +@pytest.mark.xfail( + reason="the removal loop matches with 'in', so dropping Sample1 also drops Sample10", + strict=True, + raises=AssertionError, +) +def test_dropping_one_stem_does_not_drop_names_containing_it(valid_project: Path) -> None: + """``Sample1`` has no folder; ``Sample10`` has one and must survive. + + ``horse10`` ships ``Sample1`` through ``Sample20``, so this is the shape of + a real project rather than a contrived name. + """ + + trainingsetmanipulation = pytest.importorskip("deeplabcut.generate_training_dataset.trainingsetmanipulation") + + _declare_videos(valid_project, ("Sample1", "Sample10")) + _add_dataset_folder(valid_project, "Sample10") + + trainingsetmanipulation.adddatasetstovideolistandviceversa(str(valid_project / "config.yaml")) + + assert "Sample10" in [Path(video).stem for video in _configured_videos(valid_project)] + + +@pytest.mark.xfail(reason=_SUBSTRING_FILTER, strict=True, raises=AssertionError) +def test_comparison_does_not_report_a_labeled_named_folder_as_missing( + valid_project: Path, + capsys: pytest.CaptureFixture[str], +) -> None: + """The read-only report should agree that the folder is present.""" + + trainingsetmanipulation = pytest.importorskip("deeplabcut.generate_training_dataset.trainingsetmanipulation") + + _declare_videos(valid_project, ("trial_labeled_v2",)) + _add_dataset_folder(valid_project, "trial_labeled_v2") + + trainingsetmanipulation.comparevideolistsanddatafolders(str(valid_project / "config.yaml")) + + assert "is missing as a folder" not in capsys.readouterr().out + + +@pytest.mark.xfail( + reason="labeled-data is enumerated with an unfiltered iterdir(), " + "so any directory holding a CollectedData file is merged whatever its name", + strict=True, + raises=AssertionError, +) +def test_a_directory_the_config_does_not_name_is_not_merged(valid_project: Path) -> None: + """A copy of a dataset folder is merged as though it were a second dataset. + + ``merge_windowsannotationdataONlinuxsystem`` lists ``labeled-data/`` with + ``d.is_dir()`` and no filter, so a directory belongs to the training set by + holding a ``CollectedData`` file rather than by being named in the config. + + Reached from ``create_training_dataset`` through ``merge_annotateddatasets``' + empty-result branch. + + ``check_labels`` output is not an instance of this: ``_labeled/`` holds + rendered images only, so the loop skips it. + """ + + pd = pytest.importorskip("pandas") + conversioncode = pytest.importorskip("deeplabcut.utils.conversioncode") + utils = pytest.importorskip("deeplabcut.core.config.utils") + + config = utils.read_config_as_dict(valid_project / "config.yaml") + scorer = config["scorer"] + + def write_collected_data(folder: Path, frame: str) -> None: + columns = pd.MultiIndex.from_tuples( + [(scorer, "nose", "x"), (scorer, "nose", "y")], + names=["scorer", "bodyparts", "coords"], + ) + frame_index = [("labeled-data", folder.name, frame)] + pd.DataFrame([[1.0, 2.0]], columns=columns, index=pd.MultiIndex.from_tuples(frame_index)).to_hdf( + folder / f"CollectedData_{scorer}.h5", + key="df_with_missing", + mode="w", + ) + + dataset = _add_dataset_folder(valid_project, "session-01") + copy = _add_dataset_folder(valid_project, "session-01_backup") + + write_collected_data(dataset, "img001.png") + write_collected_data(copy, "img001.png") + + merged = conversioncode.merge_windowsannotationdataONlinuxsystem(config) + + merged_folders = {entry[1] for entry in pd.concat(merged).index} + + assert merged_folders == {"session-01"} + + +@pytest.mark.xfail( + reason="read_config writes project_path as the config path's parent as given, so 'config.yaml' writes '.'", + strict=True, + raises=AssertionError, +) +def test_reading_a_moved_project_by_a_relative_path_writes_an_absolute_project_path( + valid_project: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Public calls such as ``check_labels("config.yaml")`` from inside a moved project write ``project_path: .``.""" + + 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.parent / "moved-from") + utils.write_config(config_path, config) + + monkeypatch.chdir(valid_project) + utils.read_config("config.yaml") + + assert Path(utils.read_config_as_dict(config_path)["project_path"]) == valid_project.absolute() + + +@pytest.mark.parametrize( + "entries", + [ + ["labeled-data/session-01/img001.png", "labeled-data/session-01/img002.png"], + [r"labeled-data\session-01\img001.png", r"labeled-data\session-01\img002.png"], + ], + ids=["posix", "windows"], +) +def test_split_frame_path_matches_guarantee_multiindex_rows(entries: list[str]) -> None: + """The one shared definition of a frame path agrees with DeepLabCut's on string paths of equal depth. + + DeepLabCut pads a ragged index with ``NaN`` and stringifies a numeric folder; ``split_frame_path`` does + neither, so those cases are deliberately left out. + """ + + pd = pytest.importorskip("pandas") + conversioncode = pytest.importorskip("deeplabcut.utils.conversioncode") + + from dlccore.io.labeled_data._wide.row_index import split_frame_path + + frame = pd.DataFrame({"x": range(len(entries))}, index=entries) + conversioncode.guarantee_multiindex_rows(frame) + + assert list(frame.index) == [split_frame_path(entry) for entry in entries] + + +def _fixture_dataset(project_root: Path, **config_fields: object) -> Path: + """Name ``session-01`` in ``video_sets`` under the fixtures' scorer, and return its dataset folder.""" + + utils = pytest.importorskip("deeplabcut.core.config.utils") + + _declare_videos(project_root, ("session-01",)) + config_path = project_root / "config.yaml" + config = utils.read_config_as_dict(config_path) + config.update(scorer=_FIXTURE_SCORER, **config_fields) + utils.write_config(config_path, config) + + return _add_dataset_folder(project_root, "session-01") + + +def _convertcsv2h5(project_root: Path, csv_source: Path) -> "pd.DataFrame": + """Return the table ``convertcsv2h5`` writes for ``csv_source``.""" + + pd = pytest.importorskip("pandas") + conversioncode = pytest.importorskip("deeplabcut.utils.conversioncode") + + collected_data = _fixture_dataset(project_root) / f"CollectedData_{_FIXTURE_SCORER}.csv" + shutil.copyfile(csv_source, collected_data) + conversioncode.convertcsv2h5(str(project_root / "config.yaml"), userfeedback=False) + + return pd.read_hdf(collected_data.with_suffix(".h5")) + + +def _read_and_classify_csv(path: Path) -> tuple["pd.DataFrame", "LabeledDataRowIndex"]: + from dlccore.io.labeled_data._wide.csv import read_labeled_data_csv + from dlccore.io.labeled_data._wide.table import classify_labeled_data_read + + read = read_labeled_data_csv(path) + _header, row_index = classify_labeled_data_read(read) + + return read.dataframe, row_index + + +@pytest.mark.parametrize("filename", sorted(path.name for path in LABELED_DATA_FIXTURES.glob("*.csv"))) +def test_read_labeled_data_csv_matches_convertcsv2h5(valid_project: Path, filename: str) -> None: + """Same columns and values, and each row's path parts as DeepLabCut stores them; a flat index stays flat in ours.""" + + pd = pytest.importorskip("pandas") + + converted = _convertcsv2h5(valid_project, LABELED_DATA_FIXTURES / filename) + dataframe, row_index = _read_and_classify_csv(LABELED_DATA_FIXTURES / filename) + + pd.testing.assert_frame_equal(dataframe.reset_index(drop=True), converted.reset_index(drop=True)) + assert list(row_index.frames) == list(converted.index) + + +def test_read_labeled_data_csv_keeps_a_numeric_folder_as_text_like_convertcsv2h5(valid_project: Path) -> None: + pd = pytest.importorskip("pandas") + + columns = pd.MultiIndex.from_tuples([(_FIXTURE_SCORER, "nose", "x")], names=["scorer", "bodyparts", "coords"]) + index = pd.MultiIndex.from_tuples([("labeled-data", "2019", "img0.png")]) + source = valid_project / "source.csv" + pd.DataFrame([[1.0]], index=index, columns=columns).to_csv(source) + + converted = _convertcsv2h5(valid_project, source) + _dataframe, row_index = _read_and_classify_csv(source) + + assert list(row_index.frames) == list(converted.index) + + +_MULTI_KEY_FIXTURE = "ambiguous_multi_key.h5" +_SINGLE_KEY_H5_FIXTURES = sorted( + path.name for path in LABELED_DATA_FIXTURES.glob("*.h5") if path.name != _MULTI_KEY_FIXTURE +) + + +def _deeplabcut_read(path: Path) -> "pd.DataFrame": + """Read a labels file as ``merge_annotateddatasets`` does: the file's only key, rows as path parts.""" + + pd = pytest.importorskip("pandas") + conversioncode = pytest.importorskip("deeplabcut.utils.conversioncode") + + frame = pd.read_hdf(path) + conversioncode.guarantee_multiindex_rows(frame) + return frame + + +def _rewrite(source: Path, tmp_path: Path, *, move_one_point: bool = False) -> Path: + import numpy as np + + from dlccore.io.labeled_data import LabeledData, read_labeled_data, write_labeled_data + + table = read_labeled_data(source).labeled_data + if move_one_point: + long = table.to_long_df() + long.loc[np.flatnonzero(long["x"].notna())[0], "x"] += 1.0 + table = LabeledData.from_long_df(long) + + # Human labels never carry a likelihood, so labels that have one are rewritten as machine labels. + human = f"CollectedData_{_FIXTURE_SCORER}.h5" + target = tmp_path / ("machinelabels-iter0.h5" if table.has_likelihood else human) + write_labeled_data(table, target, replaces=None) + return target + + +def test_every_single_key_h5_fixture_is_found() -> None: + # Control: an empty glob would let the rewrite test pass by running nothing. + assert len(_SINGLE_KEY_H5_FIXTURES) == 7 + + +@pytest.mark.parametrize("filename", _SINGLE_KEY_H5_FIXTURES) +def test_deeplabcut_reads_a_rewritten_labels_file_as_the_original(tmp_path: Path, filename: str) -> None: + pd = pytest.importorskip("pandas") + source = LABELED_DATA_FIXTURES / filename + + pd.testing.assert_frame_equal( + _deeplabcut_read(_rewrite(source, tmp_path)), _deeplabcut_read(source), check_exact=True + ) + + +def test_deeplabcut_sees_one_moved_point_in_a_rewritten_labels_file(tmp_path: Path) -> None: + # Control: the comparison above can fail. + pd = pytest.importorskip("pandas") + source = LABELED_DATA_FIXTURES / "single_animal_human.h5" + + with pytest.raises(AssertionError): + pd.testing.assert_frame_equal( + _deeplabcut_read(_rewrite(source, tmp_path, move_one_point=True)), + _deeplabcut_read(source), + check_exact=True, + ) + + +def test_deeplabcut_reads_the_rewrite_of_a_multi_key_labels_file_it_cannot_read(tmp_path: Path) -> None: + source = LABELED_DATA_FIXTURES / _MULTI_KEY_FIXTURE + + with pytest.raises(ValueError, match="key must be provided"): + _deeplabcut_read(source) + assert not _deeplabcut_read(_rewrite(source, tmp_path)).empty + + +@pytest.mark.xfail( + reason="convertcsv2h5 counts header rows by finding 'individuals' anywhere in the second line, " + "so a single-animal bodypart containing it is read as a fourth header row", + strict=True, + raises=AssertionError, +) +def test_convertcsv2h5_reads_a_bodypart_containing_individuals_as_single_animal(valid_project: Path) -> None: + pd = pytest.importorskip("pandas") + + columns = pd.MultiIndex.from_product( + [[_FIXTURE_SCORER], ["nose", "individuals_marker"], ["x", "y"]], names=["scorer", "bodyparts", "coords"] + ) + index = pd.MultiIndex.from_tuples([("labeled-data", "session-01", f"img{frame}.png") for frame in range(3)]) + source = valid_project / "source.csv" + 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)