diff --git a/README.md b/README.md index faab6ada..13146eb5 100644 --- a/README.md +++ b/README.md @@ -70,6 +70,13 @@ Django API Versioning makes that mapping explicit with `@endpoint`: This is inheritance of route registrations, not automatic backward compatibility. Your application remains responsible for response schemas, business behavior, and compatibility tests. +When an endpoint must stop existing in a later version, declare that explicitly +with `remove_endpoint("orders/", from_version=3)`. The route remains available +in earlier versions, disappears from the removed version onward, and can be +reintroduced by a later version declaration. For DRF, use +`VersionedRouter.remove(prefix, route_name, from_version=...)` to remove one +generated action without removing the rest of its ViewSet. + ## Why use it with Django REST Framework? DRF already provides request-version identification and ViewSet route generation. Django API Versioning adds the missing connection between those capabilities: **mapping each concrete API version to the correct ViewSet implementation while inheriting unchanged routes independently**. diff --git a/django_api_versioning/__init__.py b/django_api_versioning/__init__.py index 8a22774a..f2d8f0f5 100644 --- a/django_api_versioning/__init__.py +++ b/django_api_versioning/__init__.py @@ -1,4 +1,4 @@ -from .decorators import endpoint, ver_range +from .decorators import endpoint, remove_endpoint, ver_range from .reverse import api_reverse -__all__ = ["endpoint", "ver_range", "api_reverse"] +__all__ = ["endpoint", "remove_endpoint", "ver_range", "api_reverse"] diff --git a/django_api_versioning/decorators.py b/django_api_versioning/decorators.py index de50847a..2176d897 100644 --- a/django_api_versioning/decorators.py +++ b/django_api_versioning/decorators.py @@ -139,3 +139,21 @@ def _validate_version(version: int, max_version: int) -> None: raise InvalidVersionError( f"Version {version} is above the maximum allowed version {max_version}." ) + + +def remove_endpoint( + postfix: str, + *, + from_version: int, + app_name: str | None = None, +) -> None: + """Remove a logical endpoint from a version onward. + + A later declaration with a higher source version can reintroduce it. + """ + if not isinstance(postfix, str): + raise TypeError("postfix must be a string.") + if postfix.startswith("/"): + raise VersioningError("postfix must be relative and must not start with '/'.") + app_name_part = f"{app_name}/" if app_name else "" + registry.remove(f"{app_name_part}{postfix}", from_version) diff --git a/django_api_versioning/management/commands/check_versions.py b/django_api_versioning/management/commands/check_versions.py index 04d242a7..9a052054 100644 --- a/django_api_versioning/management/commands/check_versions.py +++ b/django_api_versioning/management/commands/check_versions.py @@ -2,7 +2,7 @@ from django.core.management.base import BaseCommand, CommandError -from ...registry import registry +from ...registry import REMOVED_ROUTE, registry from ...testing import _load_root_urlconf @@ -52,6 +52,8 @@ def handle(self, *args, **options): @staticmethod def _get_callback_name(callback): """Resolve callback name, handling both functions and class-based views.""" + if callback is REMOVED_ROUTE: + return "" # Try to get from class-based view metadata first if hasattr(callback, "view_class"): return callback.view_class.__name__ diff --git a/django_api_versioning/registry.py b/django_api_versioning/registry.py index 4c5e7c88..78b761f3 100644 --- a/django_api_versioning/registry.py +++ b/django_api_versioning/registry.py @@ -4,6 +4,11 @@ from django.urls import URLPattern, path from django.views import View +from .exceptions import InvalidVersionError, VersionRangeError, VersionTypeError +from .settings import api_settings + +REMOVED_ROUTE = object() + ViewType = Callable[..., HttpResponse] | type[View] @@ -16,6 +21,73 @@ class UrlRegistry: def __init__(self) -> None: self.urlpatterns: list[URLPattern] = [] + self._removal_boundaries: dict[str, set[int]] = {} + self._removed_patterns: dict[tuple[str, int], URLPattern] = {} + + def clear(self) -> None: + """Clear active routes and removal declarations.""" + self.urlpatterns.clear() + self._removal_boundaries.clear() + self._removed_patterns.clear() + + def remove(self, logical_endpoint: str, from_version: int) -> None: + """Suppress an endpoint from a concrete version until reintroduced.""" + if not isinstance(logical_endpoint, str) or not logical_endpoint: + raise TypeError("logical_endpoint must be a non-empty string.") + if isinstance(from_version, bool) or not isinstance(from_version, int): + raise VersionTypeError("Removal version must be an integer.") + if from_version > api_settings.API_MAX_VERSION: + raise InvalidVersionError( + f"Removal version {from_version} is above the maximum allowed " + f"version {api_settings.API_MAX_VERSION}." + ) + if from_version < api_settings.API_MIN_VERSION: + raise VersionRangeError( + f"Removal version {from_version} is below the minimum allowed " + f"version {api_settings.API_MIN_VERSION}." + ) + + self._removal_boundaries.setdefault(logical_endpoint, set()).add(from_version) + + for index in range(len(self.urlpatterns) - 1, -1, -1): + pattern = self.urlpatterns[index] + if getattr(pattern, self._LOGICAL_ENDPOINT_ATTR, None) != logical_endpoint: + continue + route_version = getattr(pattern, self._ROUTE_VERSION_ATTR, None) + source_version = getattr(pattern, self._SOURCE_VERSION_ATTR, None) + if route_version is None or route_version < from_version: + continue + if source_version is not None and source_version > from_version: + continue + self._removed_patterns[(logical_endpoint, route_version)] = pattern + del self.urlpatterns[index] + + def _removal_boundary( + self, + logical_endpoint: str | None, + route_version: int | None, + ) -> int | None: + if logical_endpoint is None or route_version is None: + return None + boundaries = self._removal_boundaries.get(logical_endpoint, set()) + applicable = [boundary for boundary in boundaries if boundary <= route_version] + return max(applicable) if applicable else None + + def _is_suppressed( + self, + logical_endpoint: str | None, + route_version: int | None, + source_version: int | None, + ) -> bool: + boundary = self._removal_boundary(logical_endpoint, route_version) + return boundary is not None and ( + source_version is None or source_version <= boundary + ) + + def _record_removed(self, pattern: URLPattern, logical_endpoint: str) -> None: + route_version = getattr(pattern, self._ROUTE_VERSION_ATTR, None) + if route_version is not None: + self._removed_patterns[(logical_endpoint, route_version)] = pattern def register( self, @@ -41,6 +113,23 @@ def register( if logical_endpoint is not None: setattr(pattern, self._LOGICAL_ENDPOINT_ATTR, logical_endpoint) + if self._is_suppressed(logical_endpoint, route_version, source_version): + if route_index is not None: + existing = self.urlpatterns[route_index] + existing_logical = getattr(existing, self._LOGICAL_ENDPOINT_ATTR, None) + existing_version = getattr(existing, self._ROUTE_VERSION_ATTR, None) + existing_source = getattr(existing, self._SOURCE_VERSION_ATTR, None) + if self._is_suppressed( + existing_logical, existing_version, existing_source + ): + del self.urlpatterns[route_index] + if logical_endpoint is not None: + self._record_removed(pattern, logical_endpoint) + return + + if logical_endpoint is not None and route_version is not None: + self._removed_patterns.pop((logical_endpoint, route_version), None) + if route_index is None: self.urlpatterns.append(pattern) else: @@ -78,6 +167,21 @@ def register_urlpattern( if logical_endpoint is not None: setattr(pattern, self._LOGICAL_ENDPOINT_ATTR, logical_endpoint) + if self._is_suppressed(logical_endpoint, route_version, source_version): + if route_index is not None: + existing = self.urlpatterns[route_index] + existing_logical = getattr(existing, self._LOGICAL_ENDPOINT_ATTR, None) + existing_version = getattr(existing, self._ROUTE_VERSION_ATTR, None) + existing_source = getattr(existing, self._SOURCE_VERSION_ATTR, None) + if self._is_suppressed(existing_logical, existing_version, existing_source): + del self.urlpatterns[route_index] + if logical_endpoint is not None: + self._record_removed(pattern, logical_endpoint) + return + + if logical_endpoint is not None and route_version is not None: + self._removed_patterns.pop((logical_endpoint, route_version), None) + if route_index is None: self.urlpatterns.append(pattern) else: @@ -109,6 +213,11 @@ def get_version_matrix(self) -> dict[str, dict[int | None, Callable]]: route = str(pattern.pattern) route_version = getattr(pattern, self._ROUTE_VERSION_ATTR, None) matrix.setdefault(route, {})[route_version] = pattern.callback + for (_, route_version), pattern in self._removed_patterns.items(): + tombstone_path = str(pattern.pattern) + matrix.setdefault(tombstone_path, {}).setdefault( + route_version, REMOVED_ROUTE + ) return matrix def get_logical_version_matrix(self) -> dict[str, dict[int | None, Callable]]: @@ -127,6 +236,8 @@ def get_logical_version_matrix(self) -> dict[str, dict[int | None, Callable]]: ) route_version = getattr(pattern, self._ROUTE_VERSION_ATTR, None) matrix.setdefault(logical_id, {})[route_version] = pattern.callback + for (logical_id, route_version), _pattern in self._removed_patterns.items(): + matrix.setdefault(logical_id, {})[route_version] = REMOVED_ROUTE return matrix def _find_route_index(self, route: str) -> int | None: diff --git a/django_api_versioning/routers.py b/django_api_versioning/routers.py index cacc889a..75c1f257 100644 --- a/django_api_versioning/routers.py +++ b/django_api_versioning/routers.py @@ -130,6 +130,18 @@ def register( route_version=route_version, ) + def remove(self, prefix: str, route_name: str, *, from_version: int) -> None: + """Remove one logical DRF route from a concrete version onward. + + route_name is the URL name generated from the registration basename + and action (for example, "order-archive"), not a regex pattern. + """ + if not isinstance(prefix, str) or not prefix: + raise VersioningError("prefix must be a non-empty string.") + if not isinstance(route_name, str) or not route_name: + raise VersioningError("route_name must be a non-empty string.") + registry.remove(f"{prefix}:{route_name}", from_version) + @staticmethod def _validate_version(version: int) -> None: if isinstance(version, bool) or not isinstance(version, int): diff --git a/django_api_versioning/testing.py b/django_api_versioning/testing.py index c790b07b..282aea9d 100644 --- a/django_api_versioning/testing.py +++ b/django_api_versioning/testing.py @@ -5,7 +5,7 @@ from django.urls.resolvers import URLResolver from .exceptions import VersionMatrixError -from .registry import registry +from .registry import REMOVED_ROUTE, registry def _load_root_urlconf() -> None: @@ -48,6 +48,8 @@ def build_version_matrix() -> dict: def _callback_name(callback: object) -> str: """Return a stable display name for function, class-based, or callable views.""" + if callback is REMOVED_ROUTE: + return "" view_class = getattr(callback, "view_class", None) if view_class is not None: return view_class.__name__ diff --git a/docs/design/endpoint-removal.md b/docs/design/endpoint-removal.md new file mode 100644 index 00000000..5c890e89 --- /dev/null +++ b/docs/design/endpoint-removal.md @@ -0,0 +1,94 @@ +# Explicit endpoint removal and reintroduction + +**Status:** Implementation in progress +**Runtime policy:** Removed endpoint routes are absent and resolve to 404 +**Scope:** Django-native endpoints and DRF VersionedRouter routes + +## Problem + +Forward route inheritance intentionally carries unchanged registrations into later API versions. It currently has no explicit inverse operation: omitting an endpoint from a later declaration does not remove the inherited route. + +Removal must be a first-class declaration, not an accidental side effect of missing imports or manual URLPattern mutation. + +## Public API proposal + +For decorator-registered Django endpoints: + +~~~python +from django_api_versioning import endpoint, remove_endpoint + +@endpoint("orders/", version=1, view_name="orders") +def orders_v1(request): + ... + +remove_endpoint("orders/", from_version=3) +~~~ + +For DRF ViewSets, target one generated route by its stable URL name: + +~~~python +router = VersionedRouter() +router.register("orders", OrderViewSetV1, version=1, basename="order") +router.remove("orders", "order-archive", from_version=3) +~~~ + +The DRF route name is the URL name generated from the basename and action. The logical identity is router prefix plus route name; it is not the generated regex string. + +## Segment semantics + +A removal declaration at version N suppresses an earlier source declaration from N through API_MAX_VERSION. A later registration with source_version greater than N explicitly reintroduces the route from that version onward. + +Examples: + +| Version | v1 declaration | Removal from v3 | Reintroduced at v4 | +| --- | --- | --- | --- | +| v1 | active | active | active | +| v2 | inherited | inherited | inherited | +| v3 | inherited | removed | removed | +| v4 | inherited | removed | new implementation | +| v5 | inherited | removed | new implementation inherited | + +A registration whose source version is equal to or lower than the removal boundary remains suppressed. Only a declaration with a strictly higher source version reintroduces the route. Import order must not change the result: a late-imported v1 declaration cannot resurrect a route removed from v3. + +For explicit registrations, only declared versions are candidates. A tombstone suppresses a matching explicit route at or after its boundary until a later source declaration reintroduces it. + +## Registry model + +- Keep active URLPattern objects in the existing urlpatterns list only. +- Store tombstone boundaries separately by logical endpoint and version. +- When a boundary is declared, remove already-registered patterns whose source version is equal to or lower than the boundary. +- When an older pattern is registered after a boundary, suppress it and retain an explicit removed-state record. +- When a later source version reintroduces the operation, register it normally and clear the removed state for the reintroduced concrete versions. +- Keep the original URLPattern as tombstone evidence so route-matrix output can identify the removed physical path and version. + +## Observable state and compatibility + +The state-aware version matrix must distinguish: +- active: a registered callback exists; +- removed: an explicit tombstone suppresses the route; +- missing: no route or tombstone declaration exists. + +Do not silently change the historical snapshot JSON format for consumers that do not use removal. Extend its output only when tombstones exist, with a stable marker such as REMOVED. The CLI must display removed routes explicitly and must not report them as ordinary missing gaps. + +Strict snapshots must detect an accidental deletion, an intentional removal, and an unexpected reintroduction as distinct changes. + +## Runtime and integrations + +- Removed paths are absent from urlpatterns, so Django returns 404. +- api_reverse(name, version=removed_version) raises NoReverseMatch; it never falls back. +- VersionedRouter.urls omits the tombstoned operation. +- drf-spectacular naturally excludes the route from that version's schema; the OpenAPI consumer example must test this. +- Version-wide LifecycleMiddleware continues to own Deprecation, Sunset, and 410. Endpoint tombstones do not synthesize 410. + +## Required tests + +1. Removal after registration and removal before registration produce identical results. +2. Older declarations imported after a tombstone cannot restore the route. +3. A later version reintroduces the endpoint and its URL reversal. +4. Explicit versions and internal version gaps remain correct. +5. Removing one DRF custom action preserves list/detail and unrelated actions. +6. The route matrix distinguishes active, removed, and missing states. +7. Strict snapshots detect tombstone changes. +8. api_reverse fails for the removed version and succeeds for the reintroduced version. +9. OpenAPI excludes the removed operation and includes a later reintroduction. +10. Existing decorator/router precedence and import behavior remain backward-compatible. diff --git a/docs/reference/versioning-contract.md b/docs/reference/versioning-contract.md index dd91b64f..5903ab3b 100644 --- a/docs/reference/versioning-contract.md +++ b/docs/reference/versioning-contract.md @@ -27,18 +27,18 @@ Do not copy DRF examples using string identifiers such as `"v1"` or `"1.0"` into ## 2. Canonical imports and public API -The package exposes `endpoint`, `ver_range`, and `api_reverse` from its top-level namespace. The optional DRF integration is imported from `django_api_versioning.routers` so core Django users do not need DRF installed. +The package exposes `endpoint`, `remove_endpoint`, `ver_range`, and `api_reverse` from its top-level namespace. The optional DRF integration is imported from `django_api_versioning.routers` so core Django users do not need DRF installed. Use these public imports: ```python -from django_api_versioning import endpoint, ver_range, api_reverse +from django_api_versioning import endpoint, remove_endpoint, ver_range, api_reverse ``` The decorators are implemented in `django_api_versioning.decorators`, so importing them directly from that module also works: ```python -from django_api_versioning.decorators import endpoint, ver_range +from django_api_versioning.decorators import endpoint, remove_endpoint, ver_range ``` For application code and documentation examples, prefer the top-level import path. It is the package's public API and avoids coupling consumers to the internal module structure. @@ -244,6 +244,38 @@ def legacy(request): [1, 2, 3] ``` +### Explicit endpoint removal + +Forward inheritance can be stopped deliberately without deleting the route +from earlier API versions. Use the top-level remove_endpoint() function: + +```python +from django_api_versioning import endpoint, remove_endpoint + + +@endpoint("orders/", version=1, view_name="orders-list") +def orders_v1(request): + ... + + +remove_endpoint("orders/", from_version=3) +``` + +A removal boundary suppresses source declarations at or before that version +for the matching concrete route versions. A later declaration with a strictly +higher source version reintroduces the route from that version onward. The +result is independent of whether the removal or older endpoint module is +imported first. + +Removed routes are absent from Django's active URL patterns and return 404. +api_reverse() raises NoReverseMatch for a removed version; it never falls back +to an older implementation. The version-matrix snapshot records the state as +``, which is distinct from an undeclared/missing route. + +This is an endpoint-level removal, not a version retirement. It does not emit +410 or lifecycle headers; version-wide deprecation and sunset remain the +responsibility of LifecycleMiddleware. + ### Unversioned registration When neither argument is supplied, the endpoint is registered once without a version prefix: @@ -366,7 +398,13 @@ Configure `VersionedRouterVersioning` as DRF's `DEFAULT_VERSIONING_CLASS` or on A manually configured callable such as `MyViewSet.as_view({"get": "list"})` remains valid for a single route, but it does not provide the complete router-generated route set. -The router uses per-route inheritance: a later ViewSet replaces matching routes while earlier custom actions that are not redeclared remain inherited. There is not yet an explicit route-removal/tombstone API; see Issue #39. +The router uses per-route inheritance: a later ViewSet replaces matching routes while earlier custom actions that are not redeclared remain inherited. Remove one generated route/action without removing the rest of the ViewSet by using its URL name: + +```python +router.remove("orders", "order-archive", from_version=3) +``` + +The first argument is the router prefix; the second is the URL name generated from the basename and action. The removal applies from the requested version onward and can be reversed only by a later source-version registration. ## 8. Routing inheritance is not Python inheritance or contract compatibility @@ -549,7 +587,7 @@ It does not: - Select serializers based on a request version. - Replace DRF authentication, permission, throttle, filter, pagination, or renderer behavior. - Provide `DefaultRouter` API-root or format-suffix behavior; the current integration targets `SimpleRouter`. -- Remove an inherited route when a later ViewSet omits its action; explicit route tombstones are tracked separately in Issue #39. +- Infer endpoint removal from an omitted import or missing ViewSet action; use remove_endpoint() or VersionedRouter.remove() to declare it explicitly. - Enable header, query-parameter, host, or tenant-based route negotiation. `API_VERSIONING_CHANNELS` and `API_EFFECTIVE_VERSION_RESOLVER` remain reserved settings with no runtime effect. - Validate response payload compatibility through route-matrix checks. - Automatically generate versioned OpenAPI schemas or diff their compatibility; the optional drf-spectacular/oasdiff workflow is tracked in Issue #38. diff --git a/tests/conftest.py b/tests/conftest.py index cee3138b..2fd904ab 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -7,8 +7,8 @@ @pytest.fixture(autouse=True) def _reset_registry(): """Clear the global registry before and after every test.""" - registry.urlpatterns.clear() + registry.clear() clear_url_caches() yield - registry.urlpatterns.clear() + registry.clear() clear_url_caches() diff --git a/tests/test_registry.py b/tests/test_registry.py index 54706999..d8dee705 100644 --- a/tests/test_registry.py +++ b/tests/test_registry.py @@ -20,11 +20,11 @@ @pytest.fixture def clear_registry(): """Clear registered routes and URL resolver caches.""" - registry.urlpatterns.clear() + registry.clear() clear_url_caches() yield - registry.urlpatterns.clear() + registry.clear() clear_url_caches() diff --git a/tests/test_route_removal.py b/tests/test_route_removal.py new file mode 100644 index 00000000..57e43f93 --- /dev/null +++ b/tests/test_route_removal.py @@ -0,0 +1,249 @@ +from io import StringIO +from types import ModuleType + +import pytest +from django.core.management import call_command +from django.http import JsonResponse +from django.test import override_settings +from django.urls import NoReverseMatch, clear_url_caches + +from django_api_versioning import api_reverse, endpoint, remove_endpoint +from django_api_versioning.exceptions import VersionMatrixError +from django_api_versioning.registry import registry +from django_api_versioning.testing import assert_version_matrix, build_version_matrix + + +def _view(name): + def callback(request): + return JsonResponse({"implementation": name}) + + callback.__name__ = name + return callback + + +def _register_segment(view, source_version=1): + for version in range(source_version, 6): + registry.register( + f"api/v{version}/orders/", + view, + name="orders", + source_version=source_version, + route_version=version, + logical_endpoint="shop/orders/", + ) + + +def _register_explicit(view, versions): + for version in versions: + registry.register( + f"api/v{version}/orders/", + view, + name="orders", + source_version=version, + route_version=version, + logical_endpoint="shop/orders/", + ) + + +def _active_versions(): + return { + getattr(pattern, registry._ROUTE_VERSION_ATTR) + for pattern in registry.urlpatterns + if (getattr(pattern, registry._LOGICAL_ENDPOINT_ATTR, None) == "shop/orders/") + } + + +def test_remove_after_registration_suppresses_the_forward_segment(): + original = _view("orders_v1") + _register_segment(original) + + registry.remove("shop/orders/", from_version=3) + + assert _active_versions() == {1, 2} + matrix = build_version_matrix() + assert matrix["api/v3/orders/"] == {"3": ""} + assert matrix["api/v4/orders/"] == {"4": ""} + assert matrix["api/v5/orders/"] == {"5": ""} + assert api_reverse("orders", version=2) == "/api/v2/orders/" + with pytest.raises(NoReverseMatch): + api_reverse("orders", version=3) + + +def test_removal_before_registration_is_order_independent(): + original = _view("orders_v1") + registry.remove("shop/orders/", from_version=3) + _register_segment(original) + + assert _active_versions() == {1, 2} + matrix = build_version_matrix() + assert matrix["api/v3/orders/"] == {"3": ""} + assert matrix["api/v4/orders/"] == {"4": ""} + assert matrix["api/v5/orders/"] == {"5": ""} + + +def test_later_registration_reintroduces_route_without_resurrecting_gap(): + original = _view("orders_v1") + replacement = _view("orders_v4") + _register_segment(original) + registry.remove("shop/orders/", from_version=3) + _register_segment(replacement, source_version=4) + + assert _active_versions() == {1, 2, 4, 5} + matrix = build_version_matrix() + assert matrix["api/v3/orders/"] == {"3": ""} + assert matrix["api/v4/orders/"] == {"4": "orders_v4"} + assert matrix["api/v5/orders/"] == {"5": "orders_v4"} + assert api_reverse("orders", version=4) == "/api/v4/orders/" + + +def test_late_older_registration_cannot_replace_reintroduced_route(): + original = _view("orders_v1") + replacement = _view("orders_v4") + _register_segment(original) + registry.remove("shop/orders/", from_version=3) + _register_segment(replacement, source_version=4) + + # Simulate a module containing the old declaration being imported late. + for version in range(1, 6): + registry.register( + f"api/v{version}/orders/", + original, + name="orders", + source_version=1, + route_version=version, + logical_endpoint="shop/orders/", + ) + + assert _active_versions() == {1, 2, 4, 5} + assert { + getattr(pattern, registry._ROUTE_VERSION_ATTR): pattern.callback + for pattern in registry.urlpatterns + if getattr(pattern, registry._LOGICAL_ENDPOINT_ATTR, None) == "shop/orders/" + }[4] is replacement + + +def test_explicit_version_registration_respects_removal_boundary(): + original = _view("orders_explicit") + _register_explicit(original, [1, 3, 5]) + registry.remove("shop/orders/", from_version=3) + + assert _active_versions() == {1, 5} + assert api_reverse("orders", version=5) == "/api/v5/orders/" + with pytest.raises(NoReverseMatch): + api_reverse("orders", version=3) + + +def test_public_remove_endpoint_uses_decorator_logical_identity(): + @endpoint("invoices/", version=1, view_name="invoices", app_name="billing") + def invoices(request): + return JsonResponse({}) + + remove_endpoint("invoices/", from_version=4, app_name="billing") + + assert { + getattr(pattern, registry._ROUTE_VERSION_ATTR) + for pattern in registry.urlpatterns + if ( + getattr(pattern, registry._LOGICAL_ENDPOINT_ATTR, None) + == "billing/invoices/" + ) + } == {1, 2, 3} + with pytest.raises(NoReverseMatch): + api_reverse("invoices", version=4) + + +def test_router_removal_is_action_specific(): + from django_api_versioning.routers import VersionedRouter + from rest_framework import viewsets + from rest_framework.decorators import action + from rest_framework.response import Response + from rest_framework.test import APIClient + + class OrderViewSetV1(viewsets.ViewSet): + def list(self, request): + return Response({}) + + @action(detail=False, methods=["get"], url_path="archive") + def archive(self, request): + return Response({}) + + router = VersionedRouter() + router.register("orders", OrderViewSetV1, version=1, basename="order") + router.remove("orders", "order-archive", from_version=3) + + active = { + pattern.name + for pattern in registry.urlpatterns + if getattr(pattern, registry._LOGICAL_ENDPOINT_ATTR, "").startswith("orders:") + } + assert "order-list" in active + assert "order-archive" in active + urlconf = ModuleType("route_removal_test_urls") + urlconf.urlpatterns = router.urls + clear_url_caches() + + with override_settings(ROOT_URLCONF=urlconf): + client = APIClient() + assert client.get("/api/v2/orders/archive/").status_code == 200 + assert client.get("/api/v3/orders/").status_code == 200 + assert client.get("/api/v3/orders/archive/").status_code == 404 + + assert all( + getattr(pattern, registry._ROUTE_VERSION_ATTR) < 3 + for pattern in registry.urlpatterns + if ( + getattr(pattern, registry._LOGICAL_ENDPOINT_ATTR, None) + == "orders:order-archive" + ) + ) + + +def test_strict_snapshot_distinguishes_removed_from_missing(tmp_path): + original = _view("orders_v1") + _register_segment(original) + snapshot = tmp_path / "version-matrix.json" + + assert_version_matrix(snapshot=str(snapshot), update=True, strict=True) + registry.remove("shop/orders/", from_version=3) + + with pytest.raises(VersionMatrixError, match=""): + assert_version_matrix(snapshot=str(snapshot), strict=True) + + assert_version_matrix(snapshot=str(snapshot), update=True, strict=True) + import json + + expected = json.loads(snapshot.read_text()) + assert expected["api/v3/orders/"] == {"3": ""} + assert_version_matrix(snapshot=str(snapshot), strict=True) + + +def test_reused_physical_path_keeps_the_new_active_route_in_snapshot(): + original = _view("orders_v1") + replacement = _view("orders_v3_replacement") + _register_segment(original) + registry.remove("shop/orders/", from_version=3) + + registry.register( + "api/v3/orders/", + replacement, + name="orders", + source_version=3, + route_version=3, + logical_endpoint="shop/replacement-orders/", + ) + + matrix = build_version_matrix() + assert matrix["api/v3/orders/"] == {"3": "orders_v3_replacement"} + + +def test_check_versions_displays_explicit_removed_state(): + original = _view("orders_v1") + _register_segment(original) + registry.remove("shop/orders/", from_version=3) + + output = StringIO() + call_command("check_versions", stdout=output) + + assert "shop/orders/" in output.getvalue() + assert "v3" in output.getvalue() + assert "" in output.getvalue()