django-api-versioning 0.3.2__tar.gz → 0.3.4__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. {django_api_versioning-0.3.2 → django_api_versioning-0.3.4}/CHANGELOG.md +48 -0
  2. {django_api_versioning-0.3.2/django_api_versioning.egg-info → django_api_versioning-0.3.4}/PKG-INFO +7 -2
  3. {django_api_versioning-0.3.2 → django_api_versioning-0.3.4}/README.md +6 -1
  4. django_api_versioning-0.3.4/django_api_versioning/lifecycle.py +154 -0
  5. {django_api_versioning-0.3.2 → django_api_versioning-0.3.4/django_api_versioning.egg-info}/PKG-INFO +7 -2
  6. {django_api_versioning-0.3.2 → django_api_versioning-0.3.4}/pyproject.toml +1 -1
  7. django_api_versioning-0.3.4/tests/test_lifecycle.py +470 -0
  8. django_api_versioning-0.3.2/django_api_versioning/lifecycle.py +0 -82
  9. django_api_versioning-0.3.2/tests/test_lifecycle.py +0 -107
  10. {django_api_versioning-0.3.2 → django_api_versioning-0.3.4}/LICENSE +0 -0
  11. {django_api_versioning-0.3.2 → django_api_versioning-0.3.4}/MANIFEST.in +0 -0
  12. {django_api_versioning-0.3.2 → django_api_versioning-0.3.4}/django_api_versioning/__init__.py +0 -0
  13. {django_api_versioning-0.3.2 → django_api_versioning-0.3.4}/django_api_versioning/channels.py +0 -0
  14. {django_api_versioning-0.3.2 → django_api_versioning-0.3.4}/django_api_versioning/decorators.py +0 -0
  15. {django_api_versioning-0.3.2 → django_api_versioning-0.3.4}/django_api_versioning/exceptions.py +0 -0
  16. {django_api_versioning-0.3.2 → django_api_versioning-0.3.4}/django_api_versioning/management/__init__.py +0 -0
  17. {django_api_versioning-0.3.2 → django_api_versioning-0.3.4}/django_api_versioning/management/commands/__init__.py +0 -0
  18. {django_api_versioning-0.3.2 → django_api_versioning-0.3.4}/django_api_versioning/management/commands/check_versions.py +0 -0
  19. {django_api_versioning-0.3.2 → django_api_versioning-0.3.4}/django_api_versioning/management/commands/migrate_endpoints.py +0 -0
  20. {django_api_versioning-0.3.2 → django_api_versioning-0.3.4}/django_api_versioning/registry.py +0 -0
  21. {django_api_versioning-0.3.2 → django_api_versioning-0.3.4}/django_api_versioning/reverse.py +0 -0
  22. {django_api_versioning-0.3.2 → django_api_versioning-0.3.4}/django_api_versioning/settings.py +0 -0
  23. {django_api_versioning-0.3.2 → django_api_versioning-0.3.4}/django_api_versioning/testing.py +0 -0
  24. {django_api_versioning-0.3.2 → django_api_versioning-0.3.4}/django_api_versioning/urls.py +0 -0
  25. {django_api_versioning-0.3.2 → django_api_versioning-0.3.4}/django_api_versioning.egg-info/SOURCES.txt +0 -0
  26. {django_api_versioning-0.3.2 → django_api_versioning-0.3.4}/django_api_versioning.egg-info/dependency_links.txt +0 -0
  27. {django_api_versioning-0.3.2 → django_api_versioning-0.3.4}/django_api_versioning.egg-info/requires.txt +0 -0
  28. {django_api_versioning-0.3.2 → django_api_versioning-0.3.4}/django_api_versioning.egg-info/top_level.txt +0 -0
  29. {django_api_versioning-0.3.2 → django_api_versioning-0.3.4}/pytest.ini +0 -0
  30. {django_api_versioning-0.3.2 → django_api_versioning-0.3.4}/requirements-dev.txt +0 -0
  31. {django_api_versioning-0.3.2 → django_api_versioning-0.3.4}/requirements.txt +0 -0
  32. {django_api_versioning-0.3.2 → django_api_versioning-0.3.4}/setup.cfg +0 -0
  33. {django_api_versioning-0.3.2 → django_api_versioning-0.3.4}/tests/__init__.py +0 -0
  34. {django_api_versioning-0.3.2 → django_api_versioning-0.3.4}/tests/conftest.py +0 -0
  35. {django_api_versioning-0.3.2 → django_api_versioning-0.3.4}/tests/settings.py +0 -0
  36. {django_api_versioning-0.3.2 → django_api_versioning-0.3.4}/tests/test_channels.py +0 -0
  37. {django_api_versioning-0.3.2 → django_api_versioning-0.3.4}/tests/test_channels_extra.py +0 -0
  38. {django_api_versioning-0.3.2 → django_api_versioning-0.3.4}/tests/test_decorators.py +0 -0
  39. {django_api_versioning-0.3.2 → django_api_versioning-0.3.4}/tests/test_exceptions.py +0 -0
  40. {django_api_versioning-0.3.2 → django_api_versioning-0.3.4}/tests/test_management_commands.py +0 -0
  41. {django_api_versioning-0.3.2 → django_api_versioning-0.3.4}/tests/test_registry.py +0 -0
  42. {django_api_versioning-0.3.2 → django_api_versioning-0.3.4}/tests/test_reverse.py +0 -0
  43. {django_api_versioning-0.3.2 → django_api_versioning-0.3.4}/tests/test_segment_model.py +0 -0
  44. {django_api_versioning-0.3.2 → django_api_versioning-0.3.4}/tests/test_settings.py +0 -0
  45. {django_api_versioning-0.3.2 → django_api_versioning-0.3.4}/tests/test_testing_utils.py +0 -0
  46. {django_api_versioning-0.3.2 → django_api_versioning-0.3.4}/tests/test_urls.py +0 -0
@@ -8,6 +8,54 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
8
8
 
9
9
  ## [Unreleased]
10
10
 
11
+ ## [0.3.4] - 2026-11-11
12
+
13
+ ### Fixed
14
+
15
+ - **LifecycleMiddleware ignoring `override_settings`:** Fixed critical bug where `LifecycleMiddleware` and version extraction functions read from a globally cached settings object initialized at module import time. Now reads `API_VERSION_LIFECYCLE` and `API_BASE_PATH` from `django.conf.settings` at request time, allowing `override_settings` in tests and runtime configuration changes to work correctly. Maintains backward compatibility with existing monkeypatch-based tests by falling back to cached settings when needed.
16
+
17
+ ### Added
18
+
19
+ - **Comprehensive override_settings regression tests:** Added 13 focused tests covering lifecycle status enforcement, version extraction, and settings scope behavior with `override_settings`: deprecated versions with headers, retired versions returning 410, active versions with no headers, custom API_BASE_PATH patterns, extraction precedence preservation, and settings applied/removed within same test session.
20
+
21
+ ### Verified
22
+
23
+ - ✅ All 131 tests passing (22 existing lifecycle tests + 13 new override_settings tests + 96 other tests)
24
+ - ✅ Lifecycle status enforcement with override_settings (active, deprecated, retired)
25
+ - ✅ Version extraction with overridden API_BASE_PATH patterns
26
+ - ✅ Settings scope behavior (within/outside override_settings context)
27
+ - ✅ Backward compatibility with monkeypatch-based tests
28
+ - ✅ Version extraction precedence maintained
29
+ - ✅ Package builds successfully (wheel + sdist)
30
+ - ✅ Imports work correctly
31
+
32
+ ## [0.3.3] - 2026-11-10
33
+
34
+ ### Fixed
35
+
36
+ - **LifecycleMiddleware version extraction:** Fixed version detection from static URL paths generated by `@endpoint` decorator. LifecycleMiddleware now correctly extracts API versions from the URL path as a fallback when `request.version` and `resolver_match.kwargs["version"]` are unavailable, enabling proper Deprecation/Sunset header injection and retired version enforcement for path-based versioned endpoints.
37
+ - **URL path pattern matching with leading slashes:** Fixed regex pattern to correctly handle both `API_BASE_PATH` configurations with and without leading slashes. The pattern `^/?{prefix}(\\d+){suffix}` now properly matches versioned URL paths regardless of leading slash configuration.
38
+
39
+ ### Added
40
+
41
+ - **Comprehensive lifecycle integration tests:** Added 15 focused integration tests covering all lifecycle scenarios: deprecated versions, retired versions, active versions, unversioned endpoints, parameterized routes, query strings, DRF integration, error responses, and url prefix anchoring.
42
+ - **Enhanced unit tests for version extraction:** Added 14 focused unit tests for `_extract_version()` and `_extract_version_from_path()` covering version precedence, multi-digit versions, query strings, path anchoring, and error handling.
43
+
44
+ ### Verified
45
+
46
+ - ✅ All lifecycle integration tests passing (15/15)
47
+ - ✅ All lifecycle unit tests passing (22/22 in test_lifecycle.py)
48
+ - ✅ Complete integration test suite passing (236/236 tests)
49
+ - ✅ Full package test suite passing (118/118 tests)
50
+ - ✅ Version extraction precedence: request.version → resolver_match.kwargs["version"] → static URL path
51
+ - ✅ Multi-digit API versions correctly extracted
52
+ - ✅ Leading and missing leading slashes handled correctly
53
+ - ✅ Regex escaping of literal path segments
54
+ - ✅ Anchored prefix matching (no false positives)
55
+ - ✅ Query string independence verified
56
+ - ✅ Numeric resource identifiers in URL paths don't affect version extraction
57
+ - ✅ DRF response integration verified
58
+
11
59
  ## [0.3.2] - 2026-11-10
12
60
 
13
61
  ### Fixed
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: django-api-versioning
3
- Version: 0.3.2
3
+ Version: 0.3.4
4
4
  Summary: Django API versioning for Django and Django REST Framework (DRF), with decorator-based endpoint versioning, automatic URL registration, backward compatibility, and segment-based forward inheritance.
5
5
  Author-email: Mojtaba Arvin <ArvinDevDay@gmail.com>
6
6
  License: MIT
@@ -470,7 +470,12 @@ Every /api/v1/* request returns:
470
470
  HTTP/1.1 410 Gone
471
471
  ```
472
472
 
473
- The middleware reads request.version (set by DRF) or `resolver_match.kwargs["version"]`. Path-based versioning is fully supported.
473
+ The middleware extracts the version using this priority:
474
+ 1. `request.version` (set by DRF)
475
+ 2. `resolver_match.kwargs["version"]` (from URL parameters)
476
+ 3. Static URL path (version extracted from the actual request URL path)
477
+
478
+ This fallback approach ensures Deprecation/Sunset headers and retired version enforcement work correctly even when the version isn't explicitly set in the request or route parameters.
474
479
 
475
480
  ## Configuration reference
476
481
 
@@ -421,7 +421,12 @@ Every /api/v1/* request returns:
421
421
  HTTP/1.1 410 Gone
422
422
  ```
423
423
 
424
- The middleware reads request.version (set by DRF) or `resolver_match.kwargs["version"]`. Path-based versioning is fully supported.
424
+ The middleware extracts the version using this priority:
425
+ 1. `request.version` (set by DRF)
426
+ 2. `resolver_match.kwargs["version"]` (from URL parameters)
427
+ 3. Static URL path (version extracted from the actual request URL path)
428
+
429
+ This fallback approach ensures Deprecation/Sunset headers and retired version enforcement work correctly even when the version isn't explicitly set in the request or route parameters.
425
430
 
426
431
  ## Configuration reference
427
432
 
@@ -0,0 +1,154 @@
1
+ import logging
2
+ import re
3
+ from datetime import datetime, timezone
4
+ from typing import Any, Callable
5
+
6
+ from django.conf import settings as django_settings
7
+ from django.http import HttpRequest, HttpResponse, HttpResponseGone
8
+
9
+ from .settings import api_settings
10
+
11
+ logger = logging.getLogger(__name__)
12
+
13
+
14
+ def _get_api_setting(name: str, default: Any = None) -> Any:
15
+ """
16
+ Get API setting from django.conf.settings at request time.
17
+
18
+ This ensures that override_settings in tests affects middleware behavior.
19
+ For backward compatibility with monkeypatch-based tests, also checks
20
+ the cached api_settings object if the setting is not found in django.conf.settings.
21
+
22
+ Falls back to default if setting is not configured in either location.
23
+ """
24
+ # First, check if the setting exists in django.conf.settings
25
+ # This handles override_settings() and other dynamic setting changes
26
+ if hasattr(django_settings, name):
27
+ return getattr(django_settings, name)
28
+
29
+ # Fall back to cached api_settings for backward compatibility with tests
30
+ # that use monkeypatch to modify api_settings directly
31
+ if hasattr(api_settings, name):
32
+ return getattr(api_settings, name)
33
+
34
+ return default
35
+
36
+
37
+ class LifecycleMiddleware:
38
+ """
39
+ Inject ``Deprecation`` / ``Sunset`` headers and enforce sunset.
40
+
41
+ Configure via ``API_VERSION_LIFECYCLE``::
42
+
43
+ API_VERSION_LIFECYCLE = {
44
+ 1: {"status": "retired", "sunset": "2024-01-01"},
45
+ 2: {"status": "deprecated", "sunset": "2026-06-01"},
46
+ 3: {"status": "active"},
47
+ }
48
+ """
49
+
50
+ def __init__(self, get_response: Callable) -> None:
51
+ self.get_response = get_response
52
+
53
+ def __call__(self, request: HttpRequest) -> HttpResponse:
54
+ version = _extract_version(request)
55
+ if version is None:
56
+ return self.get_response(request)
57
+
58
+ lifecycle = _get_api_setting("API_VERSION_LIFECYCLE", {})
59
+ meta = lifecycle.get(version)
60
+ if not meta:
61
+ return self.get_response(request)
62
+
63
+ sunset = meta.get("sunset")
64
+ if sunset and _is_past(sunset):
65
+ return HttpResponseGone(
66
+ f"API version {version} has been retired as of {sunset}."
67
+ )
68
+
69
+ response = self.get_response(request)
70
+ if meta.get("status") == "deprecated":
71
+ response["Deprecation"] = "true"
72
+ if sunset:
73
+ response["Sunset"] = _to_http_date(sunset)
74
+ return response
75
+
76
+
77
+ def _extract_version(request: HttpRequest) -> int | None:
78
+ # Path-based: request.version is set by DRF or by URLPathVersioning.
79
+ if hasattr(request, "version") and request.version is not None:
80
+ try:
81
+ return int(request.version)
82
+ except (TypeError, ValueError):
83
+ pass
84
+ # Fallback: parse from resolver_match kwargs.
85
+ match = getattr(request, "resolver_match", None)
86
+ if match and "version" in match.kwargs:
87
+ try:
88
+ return int(match.kwargs["version"])
89
+ except (TypeError, ValueError):
90
+ pass
91
+ # Fallback: extract from static URL path using API_BASE_PATH pattern.
92
+ version = _extract_version_from_path(request)
93
+ if version is not None:
94
+ return version
95
+ return None
96
+
97
+
98
+ def _extract_version_from_path(request: HttpRequest) -> int | None:
99
+ """
100
+ Extract API version from static URL paths generated by @endpoint.
101
+
102
+ For example, with API_BASE_PATH = "api/v{version}/", a request to
103
+ /api/v2/users/ will extract version 2.
104
+
105
+ Returns None if no valid version is found.
106
+ """
107
+ api_base_path = _get_api_setting("API_BASE_PATH", "api/v{version}/")
108
+ if not api_base_path or "{version}" not in api_base_path:
109
+ return None
110
+
111
+ # Get the request path (without query string)
112
+ path = request.path_info or request.path or ""
113
+
114
+ # Build regex pattern from API_BASE_PATH
115
+ # Split on {version}, escape each part, then rejoin with version pattern
116
+ parts = api_base_path.split("{version}")
117
+ if len(parts) != 2:
118
+ return None
119
+
120
+ # Escape regex special characters in each part
121
+ prefix = re.escape(parts[0])
122
+ suffix = re.escape(parts[1])
123
+
124
+ # Create anchored pattern to match only at the beginning of the relevant path.
125
+ # The pattern may have a leading slash (from request.path_info), but API_BASE_PATH
126
+ # typically doesn't, so we allow an optional leading slash.
127
+ pattern = f"^/?{prefix}(\\d+){suffix}"
128
+
129
+ try:
130
+ regex_match = re.match(pattern, path)
131
+ if regex_match:
132
+ version_str = regex_match.group(1)
133
+ return int(version_str)
134
+ except (IndexError, ValueError, re.error):
135
+ pass
136
+
137
+ return None
138
+
139
+
140
+ def _is_past(date_str: str) -> bool:
141
+ try:
142
+ date = datetime.fromisoformat(date_str).replace(tzinfo=timezone.utc)
143
+ except ValueError:
144
+ logger.warning("Invalid sunset date %r; ignoring.", date_str)
145
+ return False
146
+ return date < datetime.now(timezone.utc)
147
+
148
+
149
+ def _to_http_date(date_str: str) -> str:
150
+ try:
151
+ date = datetime.fromisoformat(date_str).replace(tzinfo=timezone.utc)
152
+ except ValueError:
153
+ return date_str
154
+ return date.strftime("%a, %d %b %Y %H:%M:%S GMT")
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: django-api-versioning
3
- Version: 0.3.2
3
+ Version: 0.3.4
4
4
  Summary: Django API versioning for Django and Django REST Framework (DRF), with decorator-based endpoint versioning, automatic URL registration, backward compatibility, and segment-based forward inheritance.
5
5
  Author-email: Mojtaba Arvin <ArvinDevDay@gmail.com>
6
6
  License: MIT
@@ -470,7 +470,12 @@ Every /api/v1/* request returns:
470
470
  HTTP/1.1 410 Gone
471
471
  ```
472
472
 
473
- The middleware reads request.version (set by DRF) or `resolver_match.kwargs["version"]`. Path-based versioning is fully supported.
473
+ The middleware extracts the version using this priority:
474
+ 1. `request.version` (set by DRF)
475
+ 2. `resolver_match.kwargs["version"]` (from URL parameters)
476
+ 3. Static URL path (version extracted from the actual request URL path)
477
+
478
+ This fallback approach ensures Deprecation/Sunset headers and retired version enforcement work correctly even when the version isn't explicitly set in the request or route parameters.
474
479
 
475
480
  ## Configuration reference
476
481
 
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "django-api-versioning"
7
- version = "0.3.2"
7
+ version = "0.3.4"
8
8
  description = "Django API versioning for Django and Django REST Framework (DRF), with decorator-based endpoint versioning, automatic URL registration, backward compatibility, and segment-based forward inheritance."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
@@ -0,0 +1,470 @@
1
+ from datetime import date, timedelta
2
+
3
+ from django.http import HttpResponse
4
+ from django.test import RequestFactory
5
+
6
+ from django_api_versioning.lifecycle import LifecycleMiddleware
7
+ from django_api_versioning.settings import api_settings as settings
8
+
9
+ # Dates relative to "today" so the tests never depend on the current date.
10
+ FUTURE = (date.today() + timedelta(days=365)).isoformat()
11
+ PAST = (date.today() - timedelta(days=365)).isoformat()
12
+
13
+
14
+ def _request(version: str):
15
+ request = RequestFactory().get(f"/api/v{version}/users")
16
+ request.version = version
17
+ return request
18
+
19
+
20
+ def test_deprecated_version_gets_headers(monkeypatch):
21
+ monkeypatch.setitem(
22
+ settings.API_VERSION_LIFECYCLE,
23
+ 2,
24
+ {"status": "deprecated", "sunset": FUTURE},
25
+ )
26
+ middleware = LifecycleMiddleware(lambda req: HttpResponse("ok"))
27
+ response = middleware(_request("2"))
28
+
29
+ assert response["Deprecation"] == "true"
30
+ assert "Sunset" in response
31
+
32
+
33
+ def test_deprecated_without_sunset_only_deprecation(monkeypatch):
34
+ monkeypatch.setitem(
35
+ settings.API_VERSION_LIFECYCLE,
36
+ 2,
37
+ {"status": "deprecated"},
38
+ )
39
+ middleware = LifecycleMiddleware(lambda req: HttpResponse("ok"))
40
+ response = middleware(_request("2"))
41
+
42
+ assert response["Deprecation"] == "true"
43
+ assert "Sunset" not in response
44
+
45
+
46
+ def test_retired_version_returns_410(monkeypatch):
47
+ monkeypatch.setitem(
48
+ settings.API_VERSION_LIFECYCLE,
49
+ 1,
50
+ {"status": "retired", "sunset": PAST},
51
+ )
52
+ middleware = LifecycleMiddleware(lambda req: HttpResponse("ok"))
53
+ response = middleware(_request("1"))
54
+
55
+ assert response.status_code == 410
56
+
57
+
58
+ def test_future_sunset_with_retired_status_still_serves(monkeypatch):
59
+ """status=retired but sunset is in the future -> serve normally with no 410."""
60
+ monkeypatch.setitem(
61
+ settings.API_VERSION_LIFECYCLE,
62
+ 1,
63
+ {"status": "retired", "sunset": FUTURE},
64
+ )
65
+ middleware = LifecycleMiddleware(lambda req: HttpResponse("ok"))
66
+ response = middleware(_request("1"))
67
+
68
+ assert response.status_code == 200
69
+
70
+
71
+ def test_active_version_has_no_headers(monkeypatch):
72
+ monkeypatch.setitem(settings.API_VERSION_LIFECYCLE, 3, {"status": "active"})
73
+ middleware = LifecycleMiddleware(lambda req: HttpResponse("ok"))
74
+ response = middleware(_request("3"))
75
+
76
+ assert "Deprecation" not in response
77
+ assert "Sunset" not in response
78
+
79
+
80
+ def test_unknown_version_is_passthrough(monkeypatch):
81
+ monkeypatch.setitem(settings.API_VERSION_LIFECYCLE, 3, {"status": "active"})
82
+ middleware = LifecycleMiddleware(lambda req: HttpResponse("ok"))
83
+ response = middleware(_request("99"))
84
+
85
+ assert response.status_code == 200
86
+ assert "Deprecation" not in response
87
+
88
+
89
+ def test_request_without_version_is_passthrough():
90
+ request = RequestFactory().get("/some/path")
91
+ middleware = LifecycleMiddleware(lambda req: HttpResponse("ok"))
92
+ response = middleware(request)
93
+
94
+ assert response.status_code == 200
95
+
96
+
97
+ def test_invalid_sunset_date_is_ignored(monkeypatch, caplog):
98
+ monkeypatch.setitem(
99
+ settings.API_VERSION_LIFECYCLE,
100
+ 2,
101
+ {"status": "deprecated", "sunset": "not-a-date"},
102
+ )
103
+ middleware = LifecycleMiddleware(lambda req: HttpResponse("ok"))
104
+ response = middleware(_request("2"))
105
+
106
+ assert response["Deprecation"] == "true"
107
+ assert "Invalid sunset date" in caplog.text
108
+
109
+
110
+ # Tests for _extract_version() and _extract_version_from_path()
111
+ class TestVersionExtraction:
112
+ """Focused unit tests for version extraction logic."""
113
+
114
+ def test_extract_version_prefers_request_version(self):
115
+ """Version extraction prefers request.version when set."""
116
+ from django_api_versioning.lifecycle import _extract_version
117
+
118
+ request = RequestFactory().get("/api/v2/users/")
119
+ request.version = "3"
120
+ # Even though path says v2, request.version should win
121
+ version = _extract_version(request)
122
+ assert version == 3
123
+
124
+ def test_extract_version_prefers_resolver_match_kwargs(self):
125
+ """Version extraction prefers resolver_match.kwargs["version"] over path."""
126
+ from django_api_versioning.lifecycle import _extract_version
127
+ from unittest.mock import Mock
128
+
129
+ request = RequestFactory().get("/api/v2/users/")
130
+ request.version = None
131
+ request.resolver_match = Mock()
132
+ request.resolver_match.kwargs = {"version": "4"}
133
+ # resolver_match should be second priority
134
+ version = _extract_version(request)
135
+ assert version == 4
136
+
137
+ def test_extract_version_falls_back_to_path(self):
138
+ """Version extraction falls back to URL path when others are unavailable."""
139
+ from django_api_versioning.lifecycle import _extract_version
140
+
141
+ request = RequestFactory().get("/api/v2/users/")
142
+ request.version = None
143
+ request.resolver_match = None
144
+ # Should extract version from path
145
+ version = _extract_version(request)
146
+ assert version == 2
147
+
148
+ def test_extract_version_from_path_static_url(self):
149
+ """Extract version from static URL path."""
150
+ from django_api_versioning.lifecycle import _extract_version_from_path
151
+
152
+ request = RequestFactory().get("/api/v1/users/")
153
+ request.version = None
154
+ version = _extract_version_from_path(request)
155
+ assert version == 1
156
+
157
+ def test_extract_version_multi_digit_version(self):
158
+ """Extract multi-digit version numbers from path."""
159
+ from django_api_versioning.lifecycle import _extract_version_from_path
160
+
161
+ request = RequestFactory().get("/api/v42/users/")
162
+ request.version = None
163
+ version = _extract_version_from_path(request)
164
+ assert version == 42
165
+
166
+ def test_extract_version_with_url_parameters(self):
167
+ """Version is extracted from prefix, not from URL parameters."""
168
+ from django_api_versioning.lifecycle import _extract_version_from_path
169
+
170
+ request = RequestFactory().get("/api/v2/users/42/")
171
+ request.version = None
172
+ # Should extract v2, not 42
173
+ version = _extract_version_from_path(request)
174
+ assert version == 2
175
+
176
+ def test_extract_version_with_query_string(self):
177
+ """Query string doesn't affect version extraction."""
178
+ from django_api_versioning.lifecycle import _extract_version_from_path
179
+
180
+ request = RequestFactory().get("/api/v2/users/?page=1&limit=10")
181
+ request.version = None
182
+ version = _extract_version_from_path(request)
183
+ assert version == 2
184
+
185
+ def test_extract_version_no_match_returns_none(self):
186
+ """Returns None when path doesn't match API_BASE_PATH pattern."""
187
+ from django_api_versioning.lifecycle import _extract_version_from_path
188
+
189
+ request = RequestFactory().get("/unrelated/path/")
190
+ request.version = None
191
+ version = _extract_version_from_path(request)
192
+ assert version is None
193
+
194
+ def test_extract_version_invalid_version_format(self):
195
+ """Returns None for non-numeric version strings."""
196
+ from django_api_versioning.lifecycle import _extract_version_from_path
197
+
198
+ request = RequestFactory().get("/api/vx/users/")
199
+ request.version = None
200
+ version = _extract_version_from_path(request)
201
+ assert version is None
202
+
203
+ def test_extract_version_anchored_pattern(self):
204
+ """Version is only extracted from start of path, not middle."""
205
+ from django_api_versioning.lifecycle import _extract_version_from_path
206
+
207
+ # A path where "api/v2" appears but not at the start
208
+ # This should not match (returns None)
209
+ request = RequestFactory().get("/prefix/api/v2/users/")
210
+ request.version = None
211
+ version = _extract_version_from_path(request)
212
+ # Should be None because pattern is anchored at ^
213
+ assert version is None
214
+
215
+ def test_extract_version_with_request_version_invalid(self):
216
+ """Invalid request.version falls back to path extraction."""
217
+ from django_api_versioning.lifecycle import _extract_version
218
+
219
+ request = RequestFactory().get("/api/v2/users/")
220
+ request.version = "not_a_number"
221
+ version = _extract_version(request)
222
+ # Should fall back to path and get 2
223
+ assert version == 2
224
+
225
+ def test_extract_version_empty_lifecycle_config(self):
226
+ """Version extraction works even with empty lifecycle config."""
227
+ from django_api_versioning.lifecycle import _extract_version
228
+
229
+ request = RequestFactory().get("/api/v2/users/")
230
+ request.version = None
231
+ request.resolver_match = None
232
+ version = _extract_version(request)
233
+ # Should still extract from path
234
+ assert version == 2
235
+
236
+ def test_extract_version_no_resolver_match(self):
237
+ """Handles missing resolver_match gracefully."""
238
+ from django_api_versioning.lifecycle import _extract_version
239
+
240
+ request = RequestFactory().get("/api/v1/users/")
241
+ request.version = None
242
+ # Don't set resolver_match at all
243
+ version = _extract_version(request)
244
+ assert version == 1
245
+
246
+ def test_extract_version_precedence_order(self):
247
+ """Verifies version extraction precedence: request.version > kwargs > path."""
248
+ from django_api_versioning.lifecycle import _extract_version
249
+ from unittest.mock import Mock
250
+
251
+ # When all three are set, request.version wins
252
+ request = RequestFactory().get("/api/v1/users/")
253
+ request.version = "5"
254
+ request.resolver_match = Mock()
255
+ request.resolver_match.kwargs = {"version": "3"}
256
+ version = _extract_version(request)
257
+ assert version == 5
258
+
259
+ # When request.version is None, kwargs wins
260
+ request.version = None
261
+ version = _extract_version(request)
262
+ assert version == 3
263
+
264
+ # When both are None, path wins
265
+ request.resolver_match.kwargs = {}
266
+ version = _extract_version(request)
267
+ assert version == 1
268
+
269
+
270
+ # Tests for override_settings compatibility
271
+ class TestOverrideSettingsCompatibility:
272
+ """Regression tests for override_settings compatibility (Bug: LifecycleMiddleware ignores override_settings)."""
273
+
274
+ def test_override_settings_lifecycle_active_version(self):
275
+ """override_settings(API_VERSION_LIFECYCLE) should affect middleware behavior."""
276
+ from django.test import override_settings
277
+
278
+ with override_settings(API_VERSION_LIFECYCLE={1: {"status": "active"}}):
279
+ middleware = LifecycleMiddleware(lambda req: HttpResponse("ok"))
280
+ response = middleware(_request("1"))
281
+
282
+ assert response.status_code == 200
283
+ assert "Deprecation" not in response
284
+
285
+ def test_override_settings_lifecycle_deprecated_version(self):
286
+ """override_settings should apply deprecated status and Sunset header."""
287
+ from django.test import override_settings
288
+
289
+ with override_settings(
290
+ API_VERSION_LIFECYCLE={2: {"status": "deprecated", "sunset": FUTURE}}
291
+ ):
292
+ middleware = LifecycleMiddleware(lambda req: HttpResponse("ok"))
293
+ response = middleware(_request("2"))
294
+
295
+ assert response.status_code == 200
296
+ assert response["Deprecation"] == "true"
297
+ assert "Sunset" in response
298
+
299
+ def test_override_settings_lifecycle_retired_past_sunset(self):
300
+ """override_settings with past sunset should return 410."""
301
+ from django.test import override_settings
302
+
303
+ with override_settings(
304
+ API_VERSION_LIFECYCLE={1: {"status": "retired", "sunset": PAST}}
305
+ ):
306
+ middleware = LifecycleMiddleware(lambda req: HttpResponse("ok"))
307
+ response = middleware(_request("1"))
308
+
309
+ assert response.status_code == 410
310
+
311
+ def test_override_settings_lifecycle_retired_future_sunset(self):
312
+ """override_settings with future sunset should serve normally."""
313
+ from django.test import override_settings
314
+
315
+ with override_settings(
316
+ API_VERSION_LIFECYCLE={1: {"status": "retired", "sunset": FUTURE}}
317
+ ):
318
+ middleware = LifecycleMiddleware(lambda req: HttpResponse("ok"))
319
+ response = middleware(_request("1"))
320
+
321
+ assert response.status_code == 200
322
+ assert "Deprecation" not in response
323
+
324
+ def test_override_settings_lifecycle_empty_dict(self):
325
+ """override_settings with empty lifecycle should pass through."""
326
+ from django.test import override_settings
327
+
328
+ with override_settings(API_VERSION_LIFECYCLE={}):
329
+ middleware = LifecycleMiddleware(lambda req: HttpResponse("ok"))
330
+ response = middleware(_request("1"))
331
+
332
+ assert response.status_code == 200
333
+ assert "Deprecation" not in response
334
+
335
+ def test_override_settings_lifecycle_removed(self):
336
+ """After override_settings context ends, behavior should revert."""
337
+ from django.test import override_settings
338
+
339
+ # First, with override_settings: version 1 is retired
340
+ with override_settings(
341
+ API_VERSION_LIFECYCLE={1: {"status": "retired", "sunset": PAST}}
342
+ ):
343
+ middleware = LifecycleMiddleware(lambda req: HttpResponse("ok"))
344
+ response = middleware(_request("1"))
345
+ assert response.status_code == 410
346
+
347
+ # Then, outside context: version 1 uses cached settings (no lifecycle entry)
348
+ middleware = LifecycleMiddleware(lambda req: HttpResponse("ok"))
349
+ response = middleware(_request("1"))
350
+ assert response.status_code == 200
351
+ assert "Deprecation" not in response
352
+
353
+ def test_override_settings_base_path_extraction(self):
354
+ """override_settings(API_BASE_PATH) should affect version extraction."""
355
+ from django.test import override_settings
356
+ from django_api_versioning.lifecycle import _extract_version_from_path
357
+
358
+ with override_settings(API_BASE_PATH="svc/v{version}/"):
359
+ request = RequestFactory().get("/svc/v2/things/")
360
+ request.version = None
361
+ version = _extract_version_from_path(request)
362
+ assert version == 2
363
+
364
+ def test_override_settings_base_path_extraction_custom_format(self):
365
+ """override_settings with custom base path format should work."""
366
+ from django.test import override_settings
367
+ from django_api_versioning.lifecycle import _extract_version_from_path
368
+
369
+ with override_settings(API_BASE_PATH="api/version-{version}/"):
370
+ request = RequestFactory().get("/api/version-3/users/")
371
+ request.version = None
372
+ version = _extract_version_from_path(request)
373
+ assert version == 3
374
+
375
+ def test_override_settings_base_path_unchanged_outside_context(self):
376
+ """Version extraction should revert after override_settings context."""
377
+ from django.test import override_settings
378
+ from django_api_versioning.lifecycle import _extract_version_from_path
379
+
380
+ # With override_settings, custom path works
381
+ with override_settings(API_BASE_PATH="svc/v{version}/"):
382
+ request = RequestFactory().get("/svc/v2/things/")
383
+ request.version = None
384
+ version = _extract_version_from_path(request)
385
+ assert version == 2
386
+
387
+ # Outside override_settings, custom path doesn't match
388
+ request = RequestFactory().get("/svc/v2/things/")
389
+ request.version = None
390
+ version = _extract_version_from_path(request)
391
+ assert version is None # Uses default api/v{version}/, doesn't match svc/
392
+
393
+ def test_override_settings_lifecycle_multiple_versions(self):
394
+ """override_settings with multiple lifecycle entries should work."""
395
+ from django.test import override_settings
396
+
397
+ with override_settings(
398
+ API_VERSION_LIFECYCLE={
399
+ 1: {"status": "retired", "sunset": PAST},
400
+ 2: {"status": "deprecated", "sunset": FUTURE},
401
+ 3: {"status": "active"},
402
+ }
403
+ ):
404
+ middleware = LifecycleMiddleware(lambda req: HttpResponse("ok"))
405
+
406
+ # Version 1: retired with past sunset -> 410
407
+ response = middleware(_request("1"))
408
+ assert response.status_code == 410
409
+
410
+ # Version 2: deprecated with future sunset -> 200 with headers
411
+ response = middleware(_request("2"))
412
+ assert response.status_code == 200
413
+ assert response["Deprecation"] == "true"
414
+
415
+ # Version 3: active -> 200 with no headers
416
+ response = middleware(_request("3"))
417
+ assert response.status_code == 200
418
+ assert "Deprecation" not in response
419
+
420
+ def test_override_settings_with_extract_version_precedence(self):
421
+ """Version extraction precedence should work with override_settings."""
422
+ from django.test import override_settings
423
+ from django_api_versioning.lifecycle import _extract_version
424
+ from unittest.mock import Mock
425
+
426
+ with override_settings(API_BASE_PATH="custom/v{version}/"):
427
+ # request.version takes precedence even with custom base path
428
+ request = RequestFactory().get("/custom/v1/things/")
429
+ request.version = "5"
430
+ request.resolver_match = None
431
+ version = _extract_version(request)
432
+ assert version == 5
433
+
434
+ # Falls back to custom path when request.version is None
435
+ request.version = None
436
+ version = _extract_version(request)
437
+ assert version == 1
438
+
439
+ def test_override_settings_deprecated_without_sunset(self):
440
+ """override_settings with deprecated status but no sunset."""
441
+ from django.test import override_settings
442
+
443
+ with override_settings(API_VERSION_LIFECYCLE={2: {"status": "deprecated"}}):
444
+ middleware = LifecycleMiddleware(lambda req: HttpResponse("ok"))
445
+ response = middleware(_request("2"))
446
+
447
+ assert response.status_code == 200
448
+ assert response["Deprecation"] == "true"
449
+ assert "Sunset" not in response
450
+
451
+ def test_override_settings_lifecycle_and_base_path_together(self):
452
+ """override_settings with both lifecycle and base path changes."""
453
+ from django.test import override_settings
454
+ from django_api_versioning.lifecycle import _extract_version
455
+
456
+ with override_settings(
457
+ API_BASE_PATH="svc/v{version}/",
458
+ API_VERSION_LIFECYCLE={2: {"status": "retired", "sunset": PAST}},
459
+ ):
460
+ middleware = LifecycleMiddleware(lambda req: HttpResponse("ok"))
461
+
462
+ # Extract version from overridden base path
463
+ request = RequestFactory().get("/svc/v2/things/")
464
+ request.version = None
465
+ version = _extract_version(request)
466
+ assert version == 2
467
+
468
+ # Check lifecycle with extracted version
469
+ response = middleware(request)
470
+ assert response.status_code == 410
@@ -1,82 +0,0 @@
1
- import logging
2
- from datetime import datetime, timezone
3
- from typing import Callable
4
-
5
- from django.http import HttpRequest, HttpResponse, HttpResponseGone
6
-
7
- from .settings import api_settings as settings
8
-
9
- logger = logging.getLogger(__name__)
10
-
11
-
12
- class LifecycleMiddleware:
13
- """
14
- Inject ``Deprecation`` / ``Sunset`` headers and enforce sunset.
15
-
16
- Configure via ``API_VERSION_LIFECYCLE``::
17
-
18
- API_VERSION_LIFECYCLE = {
19
- 1: {"status": "retired", "sunset": "2024-01-01"},
20
- 2: {"status": "deprecated", "sunset": "2026-06-01"},
21
- 3: {"status": "active"},
22
- }
23
- """
24
-
25
- def __init__(self, get_response: Callable) -> None:
26
- self.get_response = get_response
27
-
28
- def __call__(self, request: HttpRequest) -> HttpResponse:
29
- version = _extract_version(request)
30
- if version is None:
31
- return self.get_response(request)
32
-
33
- meta = settings.API_VERSION_LIFECYCLE.get(version)
34
- if not meta:
35
- return self.get_response(request)
36
-
37
- sunset = meta.get("sunset")
38
- if sunset and _is_past(sunset):
39
- return HttpResponseGone(
40
- f"API version {version} has been retired as of {sunset}."
41
- )
42
-
43
- response = self.get_response(request)
44
- if meta.get("status") == "deprecated":
45
- response["Deprecation"] = "true"
46
- if sunset:
47
- response["Sunset"] = _to_http_date(sunset)
48
- return response
49
-
50
-
51
- def _extract_version(request: HttpRequest) -> int | None:
52
- # Path-based: request.version is set by DRF or by URLPathVersioning.
53
- if hasattr(request, "version") and request.version is not None:
54
- try:
55
- return int(request.version)
56
- except (TypeError, ValueError):
57
- pass
58
- # Fallback: parse from resolver_match kwargs.
59
- match = getattr(request, "resolver_match", None)
60
- if match and "version" in match.kwargs:
61
- try:
62
- return int(match.kwargs["version"])
63
- except (TypeError, ValueError):
64
- pass
65
- return None
66
-
67
-
68
- def _is_past(date_str: str) -> bool:
69
- try:
70
- date = datetime.fromisoformat(date_str).replace(tzinfo=timezone.utc)
71
- except ValueError:
72
- logger.warning("Invalid sunset date %r; ignoring.", date_str)
73
- return False
74
- return date < datetime.now(timezone.utc)
75
-
76
-
77
- def _to_http_date(date_str: str) -> str:
78
- try:
79
- date = datetime.fromisoformat(date_str).replace(tzinfo=timezone.utc)
80
- except ValueError:
81
- return date_str
82
- return date.strftime("%a, %d %b %Y %H:%M:%S GMT")
@@ -1,107 +0,0 @@
1
- from datetime import date, timedelta
2
-
3
- from django.http import HttpResponse
4
- from django.test import RequestFactory
5
-
6
- from django_api_versioning.lifecycle import LifecycleMiddleware
7
- from django_api_versioning.settings import api_settings as settings
8
-
9
- # Dates relative to "today" so the tests never depend on the current date.
10
- FUTURE = (date.today() + timedelta(days=365)).isoformat()
11
- PAST = (date.today() - timedelta(days=365)).isoformat()
12
-
13
-
14
- def _request(version: str):
15
- request = RequestFactory().get(f"/api/v{version}/users")
16
- request.version = version
17
- return request
18
-
19
-
20
- def test_deprecated_version_gets_headers(monkeypatch):
21
- monkeypatch.setitem(
22
- settings.API_VERSION_LIFECYCLE,
23
- 2,
24
- {"status": "deprecated", "sunset": FUTURE},
25
- )
26
- middleware = LifecycleMiddleware(lambda req: HttpResponse("ok"))
27
- response = middleware(_request("2"))
28
-
29
- assert response["Deprecation"] == "true"
30
- assert "Sunset" in response
31
-
32
-
33
- def test_deprecated_without_sunset_only_deprecation(monkeypatch):
34
- monkeypatch.setitem(
35
- settings.API_VERSION_LIFECYCLE,
36
- 2,
37
- {"status": "deprecated"},
38
- )
39
- middleware = LifecycleMiddleware(lambda req: HttpResponse("ok"))
40
- response = middleware(_request("2"))
41
-
42
- assert response["Deprecation"] == "true"
43
- assert "Sunset" not in response
44
-
45
-
46
- def test_retired_version_returns_410(monkeypatch):
47
- monkeypatch.setitem(
48
- settings.API_VERSION_LIFECYCLE,
49
- 1,
50
- {"status": "retired", "sunset": PAST},
51
- )
52
- middleware = LifecycleMiddleware(lambda req: HttpResponse("ok"))
53
- response = middleware(_request("1"))
54
-
55
- assert response.status_code == 410
56
-
57
-
58
- def test_future_sunset_with_retired_status_still_serves(monkeypatch):
59
- """status=retired but sunset is in the future -> serve normally with no 410."""
60
- monkeypatch.setitem(
61
- settings.API_VERSION_LIFECYCLE,
62
- 1,
63
- {"status": "retired", "sunset": FUTURE},
64
- )
65
- middleware = LifecycleMiddleware(lambda req: HttpResponse("ok"))
66
- response = middleware(_request("1"))
67
-
68
- assert response.status_code == 200
69
-
70
-
71
- def test_active_version_has_no_headers(monkeypatch):
72
- monkeypatch.setitem(settings.API_VERSION_LIFECYCLE, 3, {"status": "active"})
73
- middleware = LifecycleMiddleware(lambda req: HttpResponse("ok"))
74
- response = middleware(_request("3"))
75
-
76
- assert "Deprecation" not in response
77
- assert "Sunset" not in response
78
-
79
-
80
- def test_unknown_version_is_passthrough(monkeypatch):
81
- monkeypatch.setitem(settings.API_VERSION_LIFECYCLE, 3, {"status": "active"})
82
- middleware = LifecycleMiddleware(lambda req: HttpResponse("ok"))
83
- response = middleware(_request("99"))
84
-
85
- assert response.status_code == 200
86
- assert "Deprecation" not in response
87
-
88
-
89
- def test_request_without_version_is_passthrough():
90
- request = RequestFactory().get("/some/path")
91
- middleware = LifecycleMiddleware(lambda req: HttpResponse("ok"))
92
- response = middleware(request)
93
-
94
- assert response.status_code == 200
95
-
96
-
97
- def test_invalid_sunset_date_is_ignored(monkeypatch, caplog):
98
- monkeypatch.setitem(
99
- settings.API_VERSION_LIFECYCLE,
100
- 2,
101
- {"status": "deprecated", "sunset": "not-a-date"},
102
- )
103
- middleware = LifecycleMiddleware(lambda req: HttpResponse("ok"))
104
- response = middleware(_request("2"))
105
-
106
- assert response["Deprecation"] == "true"
107
- assert "Invalid sunset date" in caplog.text