|
1 | 1 | import pytest
|
2 | 2 | from unittest.mock import patch
|
| 3 | +from django.http import JsonResponse |
| 4 | +from django.views import View |
3 | 5 | from django_api_versioning.settings import api_settings as settings
|
4 | 6 | from django_api_versioning.registry import registry
|
5 | 7 | from django_api_versioning.decorators import endpoint
|
6 | 8 | from django_api_versioning.exceptions import InvalidVersionError, VersionTypeError, VersionRangeError
|
7 | 9 |
|
| 10 | + |
8 | 11 | @pytest.fixture(autouse=True)
|
9 | 12 | def clear_registered_routes():
|
10 | 13 | """Clear the registry before each test to ensure isolation."""
|
@@ -86,3 +89,34 @@ def test_missing_api_version_settings():
|
86 | 89 | @endpoint("users", version=2)
|
87 | 90 | def test_view():
|
88 | 91 | pass
|
| 92 | + |
| 93 | +def test_class_based_view(mock_settings): |
| 94 | + # Create a class-based view and decorate it with the `endpoint` decorator |
| 95 | + @endpoint("users", version=2) |
| 96 | + class UsersView(View): |
| 97 | + def get(self, request): |
| 98 | + return JsonResponse({"message": "API Version 2 Users"}) |
| 99 | + |
| 100 | + # Register the view and check if the route is correctly registered |
| 101 | + registered_routes = [str(p.pattern) for p in registry.urlpatterns] |
| 102 | + assert "api/v2/users" in registered_routes, f"Route for version 2 is missing: {registered_routes}" |
| 103 | + |
| 104 | +def test_class_based_view_with_invalid_version(mock_settings): |
| 105 | + # Test invalid version for class-based view |
| 106 | + with pytest.raises(InvalidVersionError): |
| 107 | + @endpoint("users", version=4) |
| 108 | + class UsersView(View): |
| 109 | + def get(self, request): |
| 110 | + return JsonResponse({"message": "API Version 4 Users"}) |
| 111 | + |
| 112 | +def test_class_based_view_with_backward_compatibility(mock_settings): |
| 113 | + # Test class-based view with backward compatibility |
| 114 | + @endpoint("users", version=3) |
| 115 | + class UsersView(View): |
| 116 | + def get(self, request): |
| 117 | + return JsonResponse({"message": "API Version 3 Users"}) |
| 118 | + |
| 119 | + registered_routes = [str(p.pattern) for p in registry.urlpatterns] |
| 120 | + # Assert that versions 1, 2, and 3 are registered for backward compatibility |
| 121 | + for version in range(1, 4): |
| 122 | + assert f"api/v{version}/users" in registered_routes, f"Missing route for v{version}: {registered_routes}" |
0 commit comments