diff --git a/.github/workflows/compatibility.yml b/.github/workflows/compatibility.yml index 3befd2c9..a61c87f2 100644 --- a/.github/workflows/compatibility.yml +++ b/.github/workflows/compatibility.yml @@ -2,7 +2,7 @@ name: Compatibility matrix on: # Standard GitHub-hosted runners are free for public repositories. - # Run the complete compatibility matrix for package/test changes and on PR review. + # Run the complete matrix on main and for releases; PRs use a bounded smoke matrix. push: branches: - main @@ -18,7 +18,22 @@ on: - ".github/workflows/compatibility.yml" - ".github/workflows/publish.yml" workflow_dispatch: + inputs: + scope: + description: "Select the full matrix or the bounded pull-request smoke matrix." + required: false + type: choice + options: + - full + - pull-request + default: full workflow_call: + inputs: + scope: + description: "Full matrix by default; pull-request selects boundary environments only." + required: false + type: string + default: full permissions: contents: read @@ -88,6 +103,7 @@ jobs: needs: validate-matrix name: ${{ matrix.env }} runs-on: ubuntu-latest + if: inputs.scope != 'pull-request' timeout-minutes: 30 strategy: fail-fast: false @@ -150,3 +166,45 @@ jobs: - name: Run compatibility environment run: tox run -e ${{ matrix.env }} + + tox-pr-smoke: + needs: validate-matrix + name: PR smoke / ${{ matrix.env }} + if: inputs.scope == 'pull-request' + runs-on: ubuntu-latest + timeout-minutes: 30 + strategy: + fail-fast: false + matrix: + include: + - env: py310-django42 + python: "3.10" + - env: py315-django61 + python: "3.15" + - env: lint + python: "3.15" + + steps: + - name: Checkout source + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + persist-credentials: false + + - name: Set up Python + uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 + with: + python-version: ${{ matrix.python }} + + - name: Cache uv environments + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6 + with: + path: ~/.cache/uv + key: uv-${{ runner.os }}-${{ matrix.env }}-${{ hashFiles('tox.ini', 'pyproject.toml') }} + restore-keys: | + uv-${{ runner.os }}-${{ matrix.env }}- + + - name: Install tox and tox-uv + run: python -m pip install tox tox-uv + + - name: Run compatibility smoke environment + run: tox run -e ${{ matrix.env }} diff --git a/.github/workflows/openapi-contract.yml b/.github/workflows/openapi-contract.yml index c6fe66e6..c1ad4f37 100644 --- a/.github/workflows/openapi-contract.yml +++ b/.github/workflows/openapi-contract.yml @@ -33,14 +33,22 @@ jobs: python -m pip install -e . python -m pip install -r examples/openapi_contract/requirements.txt - - name: Verify runtime routing and versioned OpenAPI schemas - run: python examples/openapi_contract/verify.py - - name: Export versioned OpenAPI schemas run: | python examples/openapi_contract/generate_schemas.py \ --output-dir "$RUNNER_TEMP/openapi-contract-schemas" + - name: Upload generated OpenAPI schemas for review + uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6 + with: + name: versioned-openapi-contract-schemas + path: ${{ runner.temp }}/openapi-contract-schemas/ + if-no-files-found: error + retention-days: 7 + + - name: Verify runtime routing and versioned OpenAPI schemas + run: python examples/openapi_contract/verify.py + - name: Install pinned oasdiff run: | archive="$RUNNER_TEMP/oasdiff_1.38.0_linux_amd64.tar.gz" @@ -70,10 +78,3 @@ jobs: examples/openapi_contract/schemas/v2/openapi.yaml \ "$RUNNER_TEMP/openapi-contract-schemas/v2/openapi.yaml" - - name: Upload generated OpenAPI schemas for review - uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6 - with: - name: versioned-openapi-contract-schemas - path: ${{ runner.temp }}/openapi-contract-schemas/ - if-no-files-found: error - retention-days: 7 diff --git a/.github/workflows/pull-request-gate.yml b/.github/workflows/pull-request-gate.yml index 5393078f..891cbb08 100644 --- a/.github/workflows/pull-request-gate.yml +++ b/.github/workflows/pull-request-gate.yml @@ -60,6 +60,8 @@ jobs: needs: changes if: needs.changes.outputs.compatibility == 'true' uses: ./.github/workflows/compatibility.yml + with: + scope: pull-request permissions: contents: read diff --git a/CHANGELOG.md b/CHANGELOG.md index 17e32e8d..1056f0fc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added + +- Add explicit endpoint removal through `remove_endpoint()` and `VersionedRouter.remove()`. Removed routes remain available in earlier API versions, disappear from runtime routing and URL reversal at the removal boundary, and may be explicitly reintroduced by a later version declaration. + ## [1.1.0] - 2026-11-18 ### Added diff --git a/README.md b/README.md index fbcc049d..bd823376 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..382a2d20 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,23 @@ 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 +215,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 +238,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 bc873cc3..b40026b6 100644 --- a/django_api_versioning/routers.py +++ b/django_api_versioning/routers.py @@ -129,6 +129,25 @@ 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): + raise TypeError("prefix must be a string.") + if not prefix or prefix.startswith("/") or prefix.endswith("/"): + raise VersioningError( + "prefix must be a non-empty relative path without leading " + "or trailing '/'." + ) + if not isinstance(route_name, str): + raise TypeError("route_name must be a string.") + if 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/README.md b/docs/README.md index ca9a25a2..32eddcd3 100644 --- a/docs/README.md +++ b/docs/README.md @@ -55,7 +55,7 @@ The files in `articles/` are the only editable article sources. Each article's f ### OpenAPI contract and schema compatibility -- [Executable versioned OpenAPI contract example](../examples/openapi_contract/README.md): a real consumer project that generates and validates one drf-spectacular schema per VersionedRouter API version, checks serializer selection, inherited actions, and deterministic output. Schema snapshots and semantic breaking-change CI are a separate follow-up; this example does not imply that route-matrix checks prove response compatibility. +- [Executable versioned OpenAPI contract example](../examples/openapi_contract/README.md): a real consumer project that generates and validates one drf-spectacular schema per VersionedRouter API version, checks serializer selection, inherited actions, explicit endpoint removal, runtime 404 behavior, and deterministic output. The committed per-version schema baselines and `oasdiff breaking` CI gate are implemented. This does not imply that route-matrix checks or schema diffs prove business-level response compatibility. ### Routing operations and API compatibility diff --git a/docs/articles/024-django-api-versioning-supported-versions.md b/docs/articles/024-django-api-versioning-supported-versions.md index 20757f26..dbde1a1e 100644 --- a/docs/articles/024-django-api-versioning-supported-versions.md +++ b/docs/articles/024-django-api-versioning-supported-versions.md @@ -136,6 +136,10 @@ These classifiers describe the versions associated with the package metadata. Th The actual Django version installed during a test run depends on the dependency constraints and the versions resolved by pip at that time. +The compatibility matrix still includes Django 4.2 to detect regressions for existing installations, but that does not make 4.2 a supported production target today. Django 4.2 reached the end of extended support on 7 April 2026 and no longer receives security fixes. For new deployments, choose a currently supported Django series; Django 5.2 is the current LTS line and has extended support through April 2028. Django 6.0 and 6.1 are also currently supported, with shorter support windows. + +Check Django's [live supported-versions table](https://www.djangoproject.com/download/) before selecting a deployment version, because support windows change independently of this package's CI matrix. The Django team explicitly [announced the end of Django 4.2 extended support](https://www.djangoproject.com/weblog/2026/apr/07/security-releases/) and recommends upgrading to Django 5.2 or later. + ## What Do GitHub Actions and tox Actually Test? The repository has separate workflows for the focused Python test suites and the broader Python/Django compatibility matrix. They serve different purposes and should not be treated as the same test configuration. diff --git a/docs/design/endpoint-removal.md b/docs/design/endpoint-removal.md new file mode 100644 index 00000000..31632654 --- /dev/null +++ b/docs/design/endpoint-removal.md @@ -0,0 +1,94 @@ +# Explicit endpoint removal and reintroduction + +**Status:** Implemented in PR #44 +**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 + +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/design/request-version-resolution.md b/docs/design/request-version-resolution.md index 6350d47a..da6d5d56 100644 --- a/docs/design/request-version-resolution.md +++ b/docs/design/request-version-resolution.md @@ -152,10 +152,21 @@ A reverse call without an explicit version may use only a configured default. It ### 4.7 Caching and security -Header-selected responses must include `Vary: Accept-Version`. Tenant-specific version selection must also account for the tenant dimension in the application's cache key and vary policy. The package must not allow a shared cache to serve one tenant's effective-version response to another tenant. +Header-selected responses must include `Vary: Accept-Version`. That response header is part of HTTP's cache-selection contract, but it is not a substitute for configuring every CDN or reverse proxy correctly: the cache must honor the nominated header and include it in its cache key. A CDN configuration that ignores `Vary` or does not forward/cache on `Accept-Version` can still serve the wrong representation. + +Query-selected responses use distinct request target URIs, but deployments must not assume that every CDN includes query strings in its cache key. For example, CloudFront cache policies can exclude all query strings or include only selected names. The configured `version` parameter must be included in the cache key and forwarded to the origin whenever query mode is used. + +Tenant-specific version selection must also account for the tenant dimension in the application's cache key and vary policy. A tenant identifier should not be trusted merely because it appears in a client-controlled header. If a trusted tenant context cannot be represented safely in the shared cache key, tenant-specific responses must bypass shared caching or be marked private. The package must not allow a shared cache to serve one tenant's effective-version response to another tenant. The resolver must consume trusted server-side context. A client-supplied version is a request, not authorization to access a tenant's version. Resolver outcomes must be validated against the global version range and the endpoint's registered implementations. +Implementation acceptance tests must verify the response's `Vary` behavior and tenant isolation at the application boundary. CDN cache-key configuration remains a deployment responsibility and must be covered by the consumer's infrastructure tests or deployment checklist. + +References: +- [RFC 9111: HTTP Caching, cache keys and Vary](https://www.rfc-editor.org/rfc/rfc9111.html) +- [Cloudflare: Vary and cache-key behavior](https://developers.cloudflare.com/cache/concepts/vary/) +- [Amazon CloudFront: cache policy and query-string cache keys](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/cache-key-understand-cache-policy.html) + ## 5. Explicit non-goals The package will not become a serializer transformation framework. It will not promise automatic compatibility for response fields, validation semantics, ORM models, database migrations, or generated OpenAPI schemas. Applications remain responsible for the data contract implemented by each view. diff --git a/docs/reference/versioning-contract.md b/docs/reference/versioning-contract.md index dd91b64f..a0655667 100644 --- a/docs/reference/versioning-contract.md +++ b/docs/reference/versioning-contract.md @@ -1,8 +1,8 @@ # django-api-versioning: canonical routing contract -> **Applies to:** the `1.1.0` release candidate on `main`; the `v1.1.0` tag is created only after the release PR is merged and verified. -> **Current stable release:** `1.0.1`, published from the annotated `v1.0.1` tag. The tag-based publish workflow verifies the tag target, runs the compatibility matrix, builds and verifies the wheel and sdist, smoke-tests the installed wheel, and publishes the verified artifacts to PyPI through Trusted Publishing. The configured Python/Django environments are defined in [`tox.ini`](../../tox.ini) and checked against the [compatibility workflow](../../.github/workflows/compatibility.yml). Actual outcomes are commit-specific; consult the [workflow run history](https://github.com/mojtaba-arvin/django-api-versioning/actions/workflows/compatibility.yml) rather than treating the configured matrix as proof of a passing run. The [v0.3.8 compatibility report](../reports/compatibility-0.3.8.md) is historical evidence for that release only. +> **Applies to:** `django-api-versioning` `1.1.0`, published from the annotated `v1.1.0` tag. +> **Current stable release:** `1.1.0`. The tag-based publish workflow verified the release tag, ran the compatibility matrix, built and verified the wheel and sdist, smoke-tested the installed wheel, and published both artifacts to PyPI through Trusted Publishing. The release workflow completed successfully on commit `66bb4da557b9df4081be3ee65b9ad01db5030f2a`. The tag-based publish workflow verifies the tag target, runs the compatibility matrix, builds and verifies the wheel and sdist, smoke-tests the installed wheel, and publishes the verified artifacts to PyPI through Trusted Publishing. The configured Python/Django environments are defined in [`tox.ini`](../../tox.ini) and checked against the [compatibility workflow](../../.github/workflows/compatibility.yml). Actual outcomes are commit-specific; consult the [workflow run history](https://github.com/mojtaba-arvin/django-api-versioning/actions/workflows/compatibility.yml) rather than treating the configured matrix as proof of a passing run. The [v0.3.8 compatibility report](../reports/compatibility-0.3.8.md) is historical evidence for that release only. > > This document defines the package-specific contract for version identifiers, public imports, URL construction, endpoint registration, route precedence, URL reversal, and Django REST Framework integration. > @@ -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/examples/openapi_contract/README.md b/examples/openapi_contract/README.md index 60cc099c..2d629510 100644 --- a/examples/openapi_contract/README.md +++ b/examples/openapi_contract/README.md @@ -3,6 +3,10 @@ This executable consumer project uses the public VersionedRouter API and the same URLconf for runtime requests and drf-spectacular schema generation. +The V1-only `legacy/export/` action is explicitly removed from V2. The verifier checks that it remains available and present in the V1 schema, while returning 404 and disappearing from the V2 schema. + +Version lifecycle is separate from route removal: V1 is marked deprecated and emits RFC 9745 `Deprecation` plus RFC 8594 `Sunset` headers, while V2 remains active. To roll back the V2 endpoint removal before release, revert the `router.remove()` declaration; the V1 registration remains unchanged. + It deliberately tests: - V1 and V2 implementations for the same list/detail routes. - Different serializer contracts for the two versions. diff --git a/examples/openapi_contract/contract_app/views.py b/examples/openapi_contract/contract_app/views.py index 08623a2e..3d1e612a 100644 --- a/examples/openapi_contract/contract_app/views.py +++ b/examples/openapi_contract/contract_app/views.py @@ -32,6 +32,15 @@ def retrieve(self, request, pk: int | None = None): payload = {"id": int(pk or 1), "name": "Desk lamp", "price": "12.50"} return Response(self.get_serializer(payload).data) + @extend_schema(responses=AvailabilitySerializer) + @action(detail=False, methods=["get"], url_path="legacy/export") + def legacy_export(self, request): + payload = { + "available": True, + "checked_at": datetime(2026, 1, 1, tzinfo=timezone.utc), + } + return Response(AvailabilitySerializer(payload).data) + @extend_schema(responses=AvailabilitySerializer) @action(detail=False, methods=["get"]) def availability(self, request): diff --git a/examples/openapi_contract/contract_project/settings.py b/examples/openapi_contract/contract_project/settings.py index 43f44c50..829beef6 100644 --- a/examples/openapi_contract/contract_project/settings.py +++ b/examples/openapi_contract/contract_project/settings.py @@ -19,7 +19,7 @@ "django_api_versioning", "contract_app", ] -MIDDLEWARE = [] +MIDDLEWARE = ["django_api_versioning.lifecycle.LifecycleMiddleware"] DATABASES = {"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}} DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField" USE_TZ = True @@ -30,6 +30,14 @@ API_BASE_PATH = "api/v{version}/" API_MIN_VERSION = 1 API_MAX_VERSION = 2 +API_VERSION_LIFECYCLE = { + 1: { + "status": "deprecated", + "deprecated_at": "2026-01-01T00:00:00+00:00", + "sunset": "2027-06-30", + }, + 2: {"status": "active"}, +} REST_FRAMEWORK = { "DEFAULT_SCHEMA_CLASS": "drf_spectacular.openapi.AutoSchema", diff --git a/examples/openapi_contract/contract_project/urls.py b/examples/openapi_contract/contract_project/urls.py index a36c0605..9555b760 100644 --- a/examples/openapi_contract/contract_project/urls.py +++ b/examples/openapi_contract/contract_project/urls.py @@ -7,4 +7,5 @@ router = VersionedRouter() router.register("products", ProductViewSetV1, version=1, basename="product") router.register("products", ProductViewSetV2, version=2, basename="product") +router.remove("products", "product-legacy-export", from_version=2) urlpatterns = router.urls diff --git a/examples/openapi_contract/schemas/v1/openapi.yaml b/examples/openapi_contract/schemas/v1/openapi.yaml index 64ccec91..edb4d475 100644 --- a/examples/openapi_contract/schemas/v1/openapi.yaml +++ b/examples/openapi_contract/schemas/v1/openapi.yaml @@ -51,6 +51,19 @@ paths: schema: $ref: '#/components/schemas/Availability' description: '' + /api/v1/products/legacy/export/: + get: + operationId: v1_products_legacy_export_retrieve + description: V1 implementation and custom action inherited by V2. + tags: + - v1 + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/Availability' + description: '' components: schemas: Availability: diff --git a/examples/openapi_contract/verify.py b/examples/openapi_contract/verify.py index b0ec54ab..fedb8598 100644 --- a/examples/openapi_contract/verify.py +++ b/examples/openapi_contract/verify.py @@ -18,6 +18,10 @@ "1": "/api/v1/products/availability/", "2": "/api/v2/products/availability/", } +LEGACY_EXPORT_PATHS = { + "1": "/api/v1/products/legacy/export/", + "2": "/api/v2/products/legacy/export/", +} def generate(version: str, output: Path) -> bytes: @@ -68,14 +72,23 @@ def verify_runtime() -> None: assert v1.status_code == 200, v1.content assert v1.json()[0]["price"] == "12.50" assert "currency" not in v1.json()[0] +assert v1.headers["Deprecation"] == "@1767225600" +assert v1.headers["Sunset"] == "Wed, 30 Jun 2027 00:00:00 GMT" v2 = client.get("/api/v2/products/") assert v2.status_code == 200, v2.content assert v2.json()[0]["currency"] == "USD" +assert "Deprecation" not in v2.headers +assert "Sunset" not in v2.headers inherited = client.get("/api/v2/products/availability/") assert inherited.status_code == 200, inherited.content assert inherited.json()["available"] is True + +legacy_v1 = client.get("/api/v1/products/legacy/export/") +assert legacy_v1.status_code == 200, legacy_v1.content +legacy_v2 = client.get("/api/v2/products/legacy/export/") +assert legacy_v2.status_code == 404, legacy_v2.content """ subprocess.run([sys.executable, "-c", code], cwd=ROOT, env=env, check=True) @@ -102,6 +115,8 @@ def verify_schema(version: str) -> dict: assert product_path in document["paths"] assert action_path in document["paths"] assert PRODUCT_PATHS[other_version] not in document["paths"] + legacy_path = LEGACY_EXPORT_PATHS[version] + assert (legacy_path in document["paths"]) is (version == "1") product = component(document, response_schema(document, product_path)) fields = product["properties"] @@ -130,6 +145,7 @@ def main() -> None: "deterministic": True, "version_specific_serializers": True, "inherited_custom_action": True, + "removed_action_absent_from_v2_runtime_and_schema": True, }, indent=2, ) diff --git a/scripts/check_tox_workflow_matrix.py b/scripts/check_tox_workflow_matrix.py index 8ed8d4d6..6172ddeb 100644 --- a/scripts/check_tox_workflow_matrix.py +++ b/scripts/check_tox_workflow_matrix.py @@ -14,12 +14,37 @@ WORKFLOW = ROOT / ".github" / "workflows" / "compatibility.yml" +def matrix_entries_for_job(workflow_text: str, job_id: str) -> list[str]: + """Return environment names from one job's matrix include list.""" + match = re.search( + rf"(?ms)^ {re.escape(job_id)}:\n(.*?)(?=^ [A-Za-z0-9_-]+:\n|\Z)", + workflow_text, + ) + if match is None: + raise ValueError(f"Could not find the {job_id!r} job in compatibility.yml.") + + return re.findall( + r"^\s+- env:\s*([A-Za-z0-9_.-]+)\s*$", + match.group(1), + flags=re.MULTILINE, + ) + + def main() -> int: tox_executable = shutil.which("tox") command = ( [tox_executable, "config", "-k", "type", "--format", "json"] if tox_executable - else [sys.executable, "-m", "tox", "config", "-k", "type", "--format", "json"] + else [ + sys.executable, + "-m", + "tox", + "config", + "-k", + "type", + "--format", + "json", + ] ) result = subprocess.run( command, @@ -43,25 +68,42 @@ def main() -> int: return 2 workflow_text = WORKFLOW.read_text(encoding="utf-8") - matrix_entries = re.findall( - r"^\s+- env:\s*([A-Za-z0-9_.-]+)\s*$", - workflow_text, - flags=re.MULTILINE, - ) - workflow_environments = set(matrix_entries) + try: + full_entries = matrix_entries_for_job(workflow_text, "tox") + smoke_entries = matrix_entries_for_job(workflow_text, "tox-pr-smoke") + except ValueError as exc: + print(str(exc), file=sys.stderr) + return 2 + + full_environments = set(full_entries) + smoke_environments = set(smoke_entries) + if len(full_entries) != len(full_environments): + print( + "Duplicate environment names found in the full tox matrix.", + file=sys.stderr, + ) + return 1 + if len(smoke_entries) != len(smoke_environments): + print( + "Duplicate environment names found in the PR smoke matrix.", + file=sys.stderr, + ) + return 1 - if len(matrix_entries) != len(workflow_environments): + smoke_only = sorted(smoke_environments - full_environments) + if smoke_only: print( - "Duplicate environment names found in compatibility.yml.", + "PR smoke environments are absent from the full matrix: " + f"{', '.join(smoke_only)}", file=sys.stderr, ) return 1 - missing_from_workflow = sorted(tox_environments - workflow_environments) - missing_from_tox = sorted(workflow_environments - tox_environments) + missing_from_workflow = sorted(tox_environments - full_environments) + missing_from_tox = sorted(full_environments - tox_environments) if missing_from_workflow or missing_from_tox: print( - "tox.ini and compatibility.yml define different environments.", + "tox.ini and the full compatibility matrix define different environments.", file=sys.stderr, ) if missing_from_workflow: @@ -76,7 +118,10 @@ def main() -> int: ) return 1 - print(f"Verified {len(tox_environments)} tox environments.") + print( + f"Verified {len(tox_environments)} full tox environments and " + f"{len(smoke_environments)} PR smoke environments." + ) return 0 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..e5da3ae7 --- /dev/null +++ b/tests/test_route_removal.py @@ -0,0 +1,281 @@ +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 VersioningError, 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 rest_framework import viewsets + from rest_framework.decorators import action + from rest_framework.response import Response + from rest_framework.test import APIClient + + from django_api_versioning.routers import VersionedRouter + + class OrderViewSetV1(viewsets.ViewSet): + def list(self, request): + return Response({"route": "list"}) + + def retrieve(self, request, pk=None): + return Response({"route": "detail", "pk": pk}) + + @action(detail=True, methods=["get"], url_path="archive") + def archive(self, request, pk=None): + return Response({"route": "archive"}) + + @action(detail=False, methods=["get"]) + def availability(self, request): + return Response({"route": "availability"}) + + 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-detail" in active + assert "order-archive" in active + assert "order-availability" 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/42/archive/").status_code == 200 + assert client.get("/api/v3/orders/").status_code == 200 + assert client.get("/api/v3/orders/42/").json() == { + "route": "detail", + "pk": "42", + } + assert client.get("/api/v3/orders/availability/").status_code == 200 + assert client.get("/api/v3/orders/42/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() + + +@pytest.mark.parametrize("prefix", ["/orders", "orders/"]) +def test_router_remove_rejects_non_normalized_prefix(prefix): + from django_api_versioning.routers import VersionedRouter + + router = VersionedRouter() + with pytest.raises(VersioningError, match="relative path"): + router.remove(prefix, "order-archive", from_version=3) + + +def test_router_remove_rejects_empty_route_name(): + from django_api_versioning.routers import VersionedRouter + + router = VersionedRouter() + with pytest.raises(VersioningError, match="route_name"): + router.remove("orders", "", from_version=3) diff --git a/tox.ini b/tox.ini index 10a0fe2a..ca07e6e0 100644 --- a/tox.ini +++ b/tox.ini @@ -17,7 +17,7 @@ deps = commands = flake8 django_api_versioning tests integration_test_project scripts black --check . - isort --check-only . + isort --check-only --diff . [testenv] setenv =