summaryrefslogtreecommitdiff
path: root/tests
diff options
context:
space:
mode:
author93578237 <43147888+93578237@users.noreply.github.com>2026-02-09 16:06:50 -0500
committerJacob Walls <jacobtylerwalls@gmail.com>2026-02-10 16:54:46 -0500
commitdeac58ed822c6cd819e916e6c3d1736c7adfa31e (patch)
tree705f1e46ce13320352804c299509fcf8fa3e27af /tests
parent254b30483def1fa75270de9f45ad1f2a19f39bdb (diff)
[6.0.x] Fixed #36903 -- Fixed further NameErrors when inspecting functions with deferred annotations.
Provide a wrapper for safe introspection of user functions on Python 3.14+. Follow-up to 601914722956cc41f1f2c53972d669ddee6ffc04. Backport of 56ed37e17e5b1a509aa68a0c797dcff34fcc1366 from main.
Diffstat (limited to 'tests')
-rw-r--r--tests/auth_tests/test_auth_backends.py30
-rw-r--r--tests/check_framework/test_security.py21
-rw-r--r--tests/check_framework/test_urls.py11
-rw-r--r--tests/check_framework/urls/good_error_handler_deferred_annotations.py15
-rw-r--r--tests/deprecation/test_deprecate_posargs.py17
-rw-r--r--tests/expressions/tests.py13
-rw-r--r--tests/template_tests/tests.py21
7 files changed, 128 insertions, 0 deletions
diff --git a/tests/auth_tests/test_auth_backends.py b/tests/auth_tests/test_auth_backends.py
index 0ba169249b..3ea6ff6a69 100644
--- a/tests/auth_tests/test_auth_backends.py
+++ b/tests/auth_tests/test_auth_backends.py
@@ -1,5 +1,7 @@
import sys
+import unittest
from datetime import date
+from typing import TYPE_CHECKING
from unittest import mock
from unittest.mock import patch
@@ -30,6 +32,7 @@ from django.test import (
override_settings,
)
from django.urls import reverse
+from django.utils.version import PY314
from django.views.debug import ExceptionReporter, technical_500_response
from django.views.decorators.debug import sensitive_variables
@@ -41,6 +44,10 @@ from .models import (
UUIDUser,
)
+if TYPE_CHECKING:
+ type AnnotatedUsername = str
+ type AnnotatedPassword = str
+
class FilteredExceptionReporter(ExceptionReporter):
def get_traceback_frames(self):
@@ -1285,6 +1292,29 @@ class AuthenticateTests(TestCase):
def test_skips_backends_with_decorated_method(self):
self.assertEqual(authenticate(username="test", password="test"), self.user1)
+ @unittest.skipUnless(PY314, "Deferred annotations are Python 3.14+ only")
+ @override_settings(
+ AUTHENTICATION_BACKENDS=[
+ "auth_tests.test_auth_backends.AnnotatedBackend",
+ ],
+ )
+ def test_backend_uses_deferred_annotations(self):
+ class AnnotatedBackend:
+ invariant_user = self.user1
+
+ def authenticate(
+ self,
+ request: HttpRequest,
+ username: AnnotatedUsername,
+ password: AnnotatedPassword,
+ ) -> User | None:
+ return self.invariant_user
+
+ with unittest.mock.patch(
+ "django.contrib.auth.import_string", return_value=AnnotatedBackend
+ ):
+ self.assertEqual(authenticate(username="test", password="test"), self.user1)
+
class ImproperlyConfiguredUserModelTest(TestCase):
"""
diff --git a/tests/check_framework/test_security.py b/tests/check_framework/test_security.py
index d5cc8a9ad6..0f03845c15 100644
--- a/tests/check_framework/test_security.py
+++ b/tests/check_framework/test_security.py
@@ -1,4 +1,6 @@
import itertools
+import unittest
+from typing import TYPE_CHECKING
from django.conf import settings
from django.core.checks.messages import Error, Warning
@@ -6,8 +8,12 @@ from django.core.checks.security import base, csrf, sessions
from django.core.management.utils import get_random_secret_key
from django.test import SimpleTestCase
from django.test.utils import override_settings
+from django.utils.version import PY314
from django.views.generic import View
+if TYPE_CHECKING:
+ from django.http.request import HttpRequest
+
class CheckSessionCookieSecureTest(SimpleTestCase):
@override_settings(
@@ -613,6 +619,12 @@ def failure_view_with_invalid_signature():
pass
+if PY314:
+
+ def failure_view_with_deferred_annotations(request: HttpRequest, reason: str):
+ pass
+
+
good_class_based_csrf_failure_view = View.as_view()
@@ -653,6 +665,15 @@ class CSRFFailureViewTest(SimpleTestCase):
def test_failure_view_valid_class_based(self):
self.assertEqual(csrf.check_csrf_failure_view(None), [])
+ @unittest.skipUnless(PY314, "Deferred annotations are Python 3.14+ only")
+ @override_settings(
+ CSRF_FAILURE_VIEW=(
+ "check_framework.test_security.failure_view_with_deferred_annotations"
+ ),
+ )
+ def test_failure_view_valid_deferred_annotations(self):
+ self.assertEqual(csrf.check_csrf_failure_view(None), [])
+
class CheckCrossOriginOpenerPolicyTest(SimpleTestCase):
@override_settings(
diff --git a/tests/check_framework/test_urls.py b/tests/check_framework/test_urls.py
index a3b219f3a4..5164fe7671 100644
--- a/tests/check_framework/test_urls.py
+++ b/tests/check_framework/test_urls.py
@@ -1,3 +1,5 @@
+import unittest
+
from django.conf import settings
from django.core.checks.messages import Error, Warning
from django.core.checks.urls import (
@@ -10,6 +12,7 @@ from django.core.checks.urls import (
)
from django.test import SimpleTestCase
from django.test.utils import override_settings
+from django.utils.version import PY314
class CheckUrlConfigTests(SimpleTestCase):
@@ -323,6 +326,14 @@ class CheckCustomErrorHandlersTests(SimpleTestCase):
result = check_custom_error_handlers(None)
self.assertEqual(result, [])
+ @unittest.skipUnless(PY314, "Deferred annotations are Python 3.14+ only")
+ @override_settings(
+ ROOT_URLCONF="check_framework.urls.good_error_handler_deferred_annotations",
+ )
+ def test_good_function_based_handlers_deferred_annotations(self):
+ result = check_custom_error_handlers(None)
+ self.assertEqual(result, [])
+
@override_settings(
ROOT_URLCONF="check_framework.urls.good_class_based_error_handlers",
)
diff --git a/tests/check_framework/urls/good_error_handler_deferred_annotations.py b/tests/check_framework/urls/good_error_handler_deferred_annotations.py
new file mode 100644
index 0000000000..8b4ead5566
--- /dev/null
+++ b/tests/check_framework/urls/good_error_handler_deferred_annotations.py
@@ -0,0 +1,15 @@
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+ from django.http.request import HttpRequest
+
+urlpatterns = []
+
+handler400 = __name__ + ".good_handler_deferred_annotations"
+handler403 = __name__ + ".good_handler_deferred_annotations"
+handler404 = __name__ + ".good_handler_deferred_annotations"
+handler500 = __name__ + ".good_handler_deferred_annotations"
+
+
+def good_handler_deferred_annotations(request: HttpRequest, exception=None):
+ pass
diff --git a/tests/deprecation/test_deprecate_posargs.py b/tests/deprecation/test_deprecate_posargs.py
index 166fe5dd69..8c70d5d205 100644
--- a/tests/deprecation/test_deprecate_posargs.py
+++ b/tests/deprecation/test_deprecate_posargs.py
@@ -1,7 +1,13 @@
import inspect
+import unittest
+from typing import TYPE_CHECKING
from django.test import SimpleTestCase
from django.utils.deprecation import RemovedAfterNextVersionWarning, deprecate_posargs
+from django.utils.version import PY314
+
+if TYPE_CHECKING:
+ type AnnotatedKwarg = int
class DeprecatePosargsTests(SimpleTestCase):
@@ -355,6 +361,17 @@ class DeprecatePosargsTests(SimpleTestCase):
def func(*args, b=1):
return args, b
+ @unittest.skipUnless(PY314, "Deferred annotations are Python 3.14+ only")
+ def test_decorator_rejects_var_positional_param_with_deferred_annotation(self):
+ with self.assertRaisesMessage(
+ TypeError,
+ "@deprecate_posargs() cannot be used with variable positional `*args`.",
+ ):
+
+ @deprecate_posargs(RemovedAfterNextVersionWarning, ["b"])
+ def func(*args, b: AnnotatedKwarg = 1):
+ return args, b
+
def test_decorator_does_not_apply_to_class(self):
with self.assertRaisesMessage(
TypeError,
diff --git a/tests/expressions/tests.py b/tests/expressions/tests.py
index 981d84e9e8..c058c6e275 100644
--- a/tests/expressions/tests.py
+++ b/tests/expressions/tests.py
@@ -5,6 +5,7 @@ import uuid
from collections import namedtuple
from copy import deepcopy
from decimal import Decimal
+from typing import TYPE_CHECKING
from unittest import mock
from django.core.exceptions import FieldError
@@ -77,6 +78,7 @@ from django.test.utils import (
register_lookup,
)
from django.utils.functional import SimpleLazyObject
+from django.utils.version import PY314
from .models import (
UUID,
@@ -94,6 +96,9 @@ from .models import (
Time,
)
+if TYPE_CHECKING:
+ type AnnotatedKwarg = str
+
class BasicExpressionsTests(TestCase):
@classmethod
@@ -1589,6 +1594,14 @@ class SimpleExpressionTests(SimpleTestCase):
replaced = expression.replace_expressions({"replacement": Expression()})
self.assertEqual(replaced.get_source_expressions(), [falsey])
+ @unittest.skipUnless(PY314, "Deferred annotations are Python 3.14+ only")
+ def test_expression_signature_uses_deferred_annotations(self):
+ class AnnotatedExpression(Expression):
+ def __init__(self, *args, my_kw: AnnotatedKwarg, **kwargs):
+ super().__init__(*args, **kwargs)
+
+ self.assertEqual(AnnotatedExpression(my_kw=""), AnnotatedExpression(my_kw=""))
+
class ExpressionsNumericTests(TestCase):
@classmethod
diff --git a/tests/template_tests/tests.py b/tests/template_tests/tests.py
index 7364c7ca64..573fd9db2e 100644
--- a/tests/template_tests/tests.py
+++ b/tests/template_tests/tests.py
@@ -1,10 +1,16 @@
import sys
+import unittest
+from typing import TYPE_CHECKING
from django.template import Context, Engine, TemplateDoesNotExist, TemplateSyntaxError
from django.template.base import UNKNOWN_SOURCE
from django.test import SimpleTestCase, override_settings
from django.urls import NoReverseMatch
from django.utils import translation
+from django.utils.version import PY314
+
+if TYPE_CHECKING:
+ type AnnotatedKwarg = str
class TemplateTestMixin:
@@ -221,6 +227,21 @@ class TemplateTestMixin:
template = self._engine().from_string("{{ description.count }}")
self.assertEqual(template.render(Context({"description": "test"})), "")
+ @unittest.skipUnless(PY314, "Deferred annotations are Python 3.14+ only")
+ def test_callable_uses_deferred_annotations(self):
+ """
+ Missing required arguments are gracefully handled when a signature uses
+ deferred annotations.
+ """
+
+ class MyObject:
+ @staticmethod
+ def uses_deferred_annotations(value: AnnotatedKwarg):
+ return value
+
+ template = self._engine().from_string("{{ obj.uses_deferred_annotations }}")
+ self.assertEqual(template.render(Context({"obj": MyObject()})), "")
+
class TemplateTests(TemplateTestMixin, SimpleTestCase):
debug_engine = False