repo stringlengths 7 90 | file_url stringlengths 81 315 | file_path stringlengths 4 228 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 14:38:15 2026-01-05 02:33:18 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/check_framework/template_test_apps/same_tags_app_1/apps.py | tests/check_framework/template_test_apps/same_tags_app_1/apps.py | from django.apps import AppConfig
class SameTagsApp1AppConfig(AppConfig):
name = "check_framework.template_test_apps.same_tags_app_1"
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/check_framework/template_test_apps/same_tags_app_1/templatetags/same_tags.py | tests/check_framework/template_test_apps/same_tags_app_1/templatetags/same_tags.py | from django.template import Library
register = Library()
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/check_framework/template_test_apps/same_tags_app_1/templatetags/__init__.py | tests/check_framework/template_test_apps/same_tags_app_1/templatetags/__init__.py | python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false | |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/check_framework/custom_commands_app/management/commands/makemigrations.py | tests/check_framework/custom_commands_app/management/commands/makemigrations.py | from django.core.management.commands.makemigrations import (
Command as MakeMigrationsCommand,
)
class Command(MakeMigrationsCommand):
autodetector = int
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/check_framework/urls/good_function_based_error_handlers.py | tests/check_framework/urls/good_function_based_error_handlers.py | urlpatterns = []
handler400 = __name__ + ".good_handler"
handler403 = __name__ + ".good_handler"
handler404 = __name__ + ".good_handler"
handler500 = __name__ + ".good_handler"
def good_handler(request, exception=None, foo="bar"):
pass
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/check_framework/urls/unique_namespaces.py | tests/check_framework/urls/unique_namespaces.py | from django.urls import include, path
common_url_patterns = (
[
path("app-ns1/", include([])),
path("app-url/", include([])),
],
"common",
)
nested_url_patterns = (
[
path("common/", include(common_url_patterns, namespace="nested")),
],
"nested",
)
urlpatterns = [
path("app-ns1-0/", include(common_url_patterns, namespace="app-include-1")),
path("app-ns1-1/", include(common_url_patterns, namespace="app-include-2")),
# 'nested' is included twice but namespaced by nested-1 and nested-2.
path("app-ns1-2/", include(nested_url_patterns, namespace="nested-1")),
path("app-ns1-3/", include(nested_url_patterns, namespace="nested-2")),
# namespaced URLs inside non-namespaced URLs.
path("app-ns1-4/", include([path("abc/", include(common_url_patterns))])),
]
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/check_framework/urls/include_contains_tuple.py | tests/check_framework/urls/include_contains_tuple.py | from django.urls import include, path
urlpatterns = [
path("", include([(r"^tuple/$", lambda x: x)])),
]
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/check_framework/urls/contains_tuple.py | tests/check_framework/urls/contains_tuple.py | urlpatterns = [
(r"^tuple/$", lambda x: x),
]
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/check_framework/urls/non_unique_namespaces.py | tests/check_framework/urls/non_unique_namespaces.py | from django.urls import include, path
common_url_patterns = (
[
path("app-ns1/", include([])),
path("app-url/", include([])),
],
"app-ns1",
)
urlpatterns = [
path("app-ns1-0/", include(common_url_patterns)),
path("app-ns1-1/", include(common_url_patterns)),
path("app-some-url/", include(([], "app"), namespace="app-1")),
path("app-some-url-2/", include(([], "app"), namespace="app-1")),
]
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/check_framework/urls/beginning_with_slash.py | tests/check_framework/urls/beginning_with_slash.py | from django.urls import path, re_path
urlpatterns = [
path("/path-starting-with-slash/", lambda x: x),
re_path(r"/url-starting-with-slash/$", lambda x: x),
]
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/check_framework/urls/include_with_dollar.py | tests/check_framework/urls/include_with_dollar.py | from django.urls import include, re_path
urlpatterns = [
re_path("^include-with-dollar$", include([])),
]
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/check_framework/urls/bad_class_based_error_handlers.py | tests/check_framework/urls/bad_class_based_error_handlers.py | urlpatterns = []
class HandlerView:
@classmethod
def as_view(cls):
def view():
pass
return view
handler400 = HandlerView.as_view()
handler403 = HandlerView.as_view()
handler404 = HandlerView.as_view()
handler500 = HandlerView.as_view()
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/check_framework/urls/warning_in_include.py | tests/check_framework/urls/warning_in_include.py | from django.urls import include, path, re_path
urlpatterns = [
path(
"",
include(
[
re_path("^include-with-dollar$", include([])),
]
),
),
]
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/check_framework/urls/no_warnings.py | tests/check_framework/urls/no_warnings.py | from django.urls import include, path, re_path
urlpatterns = [
path("foo/", lambda x: x, name="foo"),
# This dollar is ok as it is escaped
re_path(
r"^\$",
include(
[
path("bar/", lambda x: x, name="bar"),
]
),
),
]
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/check_framework/urls/bad_error_handlers_invalid_path.py | tests/check_framework/urls/bad_error_handlers_invalid_path.py | urlpatterns = []
handler400 = "django.views.bad_handler"
handler403 = "django.invalid_module.bad_handler"
handler404 = "invalid_module.bad_handler"
handler500 = "django"
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/check_framework/urls/name_with_colon.py | tests/check_framework/urls/name_with_colon.py | from django.urls import re_path
urlpatterns = [
re_path("^$", lambda x: x, name="name_with:colon"),
]
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/check_framework/urls/no_warnings_i18n.py | tests/check_framework/urls/no_warnings_i18n.py | from django.conf.urls.i18n import i18n_patterns
from django.urls import path
from django.utils.translation import gettext_lazy as _
urlpatterns = i18n_patterns(
path(_("translated/"), lambda x: x, name="i18n_prefixed"),
)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/check_framework/urls/__init__.py | tests/check_framework/urls/__init__.py | python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false | |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/check_framework/urls/good_class_based_error_handlers.py | tests/check_framework/urls/good_class_based_error_handlers.py | from django.views.generic import View
urlpatterns = []
handler400 = View.as_view()
handler403 = View.as_view()
handler404 = View.as_view()
handler500 = View.as_view()
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/check_framework/urls/cbv_as_view.py | tests/check_framework/urls/cbv_as_view.py | from django.http import HttpResponse
from django.urls import path
from django.views import View
class EmptyCBV(View):
pass
class EmptyCallableView:
def __call__(self, request, *args, **kwargs):
return HttpResponse()
urlpatterns = [
path("missing_as_view", EmptyCBV),
path("has_as_view", EmptyCBV.as_view()),
path("callable_class", EmptyCallableView()),
]
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/check_framework/urls/bad_function_based_error_handlers.py | tests/check_framework/urls/bad_function_based_error_handlers.py | urlpatterns = []
handler400 = __name__ + ".bad_handler"
handler403 = __name__ + ".bad_handler"
handler404 = __name__ + ".bad_handler"
handler500 = __name__ + ".bad_handler"
def bad_handler():
pass
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/check_framework/urls/path_compatibility/contains_re_named_group.py | tests/check_framework/urls/path_compatibility/contains_re_named_group.py | from django.urls import path
urlpatterns = [
path(r"(?P<named_group>\d+)", lambda x: x),
]
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/check_framework/urls/path_compatibility/beginning_with_caret.py | tests/check_framework/urls/path_compatibility/beginning_with_caret.py | from django.urls import path
urlpatterns = [
path("^beginning-with-caret", lambda x: x),
]
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/check_framework/urls/path_compatibility/__init__.py | tests/check_framework/urls/path_compatibility/__init__.py | python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false | |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/check_framework/urls/path_compatibility/unmatched_angle_brackets.py | tests/check_framework/urls/path_compatibility/unmatched_angle_brackets.py | from django.urls import path
urlpatterns = [
path("beginning-with/<angle_bracket", lambda x: x),
path("ending-with/angle_bracket>", lambda x: x),
path("closed_angle>/x/<opened_angle", lambda x: x),
path("<mixed>angle_bracket>", lambda x: x),
]
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/check_framework/urls/path_compatibility/ending_with_dollar.py | tests/check_framework/urls/path_compatibility/ending_with_dollar.py | from django.urls import path
urlpatterns = [
path("ending-with-dollar$", lambda x: x),
]
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/check_framework/urls/path_compatibility/matched_angle_brackets.py | tests/check_framework/urls/path_compatibility/matched_angle_brackets.py | from django.urls import path
urlpatterns = [
path("<int:angle_bracket>", lambda x: x),
]
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/custom_migration_operations/operations.py | tests/custom_migration_operations/operations.py | from django.db.migrations.operations.base import Operation
class TestOperation(Operation):
def __init__(self):
pass
def deconstruct(self):
return (self.__class__.__name__, [], {})
@property
def reversible(self):
return True
def state_forwards(self, app_label, state):
pass
def database_forwards(self, app_label, schema_editor, from_state, to_state):
pass
def state_backwards(self, app_label, state):
pass
def database_backwards(self, app_label, schema_editor, from_state, to_state):
pass
class CreateModel(TestOperation):
pass
class ArgsOperation(TestOperation):
def __init__(self, arg1, arg2):
self.arg1, self.arg2 = arg1, arg2
def deconstruct(self):
return (self.__class__.__name__, [self.arg1, self.arg2], {})
class KwargsOperation(TestOperation):
def __init__(self, kwarg1=None, kwarg2=None):
self.kwarg1, self.kwarg2 = kwarg1, kwarg2
def deconstruct(self):
kwargs = {}
if self.kwarg1 is not None:
kwargs["kwarg1"] = self.kwarg1
if self.kwarg2 is not None:
kwargs["kwarg2"] = self.kwarg2
return (self.__class__.__name__, [], kwargs)
class ArgsKwargsOperation(TestOperation):
def __init__(self, arg1, arg2, kwarg1=None, kwarg2=None):
self.arg1, self.arg2 = arg1, arg2
self.kwarg1, self.kwarg2 = kwarg1, kwarg2
def deconstruct(self):
kwargs = {}
if self.kwarg1 is not None:
kwargs["kwarg1"] = self.kwarg1
if self.kwarg2 is not None:
kwargs["kwarg2"] = self.kwarg2
return (
self.__class__.__name__,
[self.arg1, self.arg2],
kwargs,
)
class ArgsAndKeywordOnlyArgsOperation(ArgsKwargsOperation):
def __init__(self, arg1, arg2, *, kwarg1, kwarg2):
super().__init__(arg1, arg2, kwarg1=kwarg1, kwarg2=kwarg2)
class ExpandArgsOperation(TestOperation):
serialization_expand_args = ["arg"]
def __init__(self, arg):
self.arg = arg
def deconstruct(self):
return (self.__class__.__name__, [self.arg], {})
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/custom_migration_operations/more_operations.py | tests/custom_migration_operations/more_operations.py | from django.db.migrations.operations.base import Operation
class TestOperation(Operation):
def __init__(self):
pass
def deconstruct(self):
return (self.__class__.__name__, [], {})
@property
def reversible(self):
return True
def state_forwards(self, app_label, state):
pass
def database_forwards(self, app_label, schema_editor, from_state, to_state):
pass
def state_backwards(self, app_label, state):
pass
def database_backwards(self, app_label, schema_editor, from_state, to_state):
pass
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/custom_migration_operations/__init__.py | tests/custom_migration_operations/__init__.py | python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false | |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/migrations2/models.py | tests/migrations2/models.py | # Required for migration detection (#22645)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/migrations2/__init__.py | tests/migrations2/__init__.py | python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false | |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/migrations2/test_migrations_2_no_deps/0001_initial.py | tests/migrations2/test_migrations_2_no_deps/0001_initial.py | from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = []
operations = [
migrations.CreateModel(
"OtherAuthor",
[
("id", models.AutoField(primary_key=True)),
("name", models.CharField(max_length=255)),
("slug", models.SlugField(null=True)),
("age", models.IntegerField(default=0)),
("silly_field", models.BooleanField(default=False)),
],
),
]
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/migrations2/test_migrations_2_no_deps/__init__.py | tests/migrations2/test_migrations_2_no_deps/__init__.py | python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false | |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/migrations2/test_migrations_2_squashed_with_replaces/0001_squashed_0002.py | tests/migrations2/test_migrations_2_squashed_with_replaces/0001_squashed_0002.py | from django.db import migrations, models
class Migration(migrations.Migration):
replaces = [
("migrations2", "0001_initial"),
("migrations2", "0002_second"),
]
operations = [
migrations.CreateModel(
"OtherAuthor",
[
("id", models.AutoField(primary_key=True)),
("name", models.CharField(max_length=255)),
],
),
migrations.CreateModel(
"OtherBook",
[
("id", models.AutoField(primary_key=True)),
(
"author",
models.ForeignKey(
"migrations2.OtherAuthor", models.SET_NULL, null=True
),
),
],
),
]
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/migrations2/test_migrations_2_squashed_with_replaces/__init__.py | tests/migrations2/test_migrations_2_squashed_with_replaces/__init__.py | python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false | |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/migrations2/test_migrations_2/0001_initial.py | tests/migrations2/test_migrations_2/0001_initial.py | from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("migrations", "0002_second")]
operations = [
migrations.CreateModel(
"OtherAuthor",
[
("id", models.AutoField(primary_key=True)),
("name", models.CharField(max_length=255)),
("slug", models.SlugField(null=True)),
("age", models.IntegerField(default=0)),
("silly_field", models.BooleanField(default=False)),
],
),
]
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/migrations2/test_migrations_2/__init__.py | tests/migrations2/test_migrations_2/__init__.py | python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false | |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/migrations2/test_migrations_2_first/0001_initial.py | tests/migrations2/test_migrations_2_first/0001_initial.py | from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("migrations", "__first__"),
]
operations = [
migrations.CreateModel(
"OtherAuthor",
[
("id", models.AutoField(primary_key=True)),
("name", models.CharField(max_length=255)),
("slug", models.SlugField(null=True)),
("age", models.IntegerField(default=0)),
("silly_field", models.BooleanField(default=False)),
],
),
]
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/migrations2/test_migrations_2_first/0002_second.py | tests/migrations2/test_migrations_2_first/0002_second.py | from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("migrations2", "0001_initial")]
operations = [
migrations.CreateModel(
"Bookstore",
[
("id", models.AutoField(primary_key=True)),
("name", models.CharField(max_length=255)),
("slug", models.SlugField(null=True)),
],
),
]
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/migrations2/test_migrations_2_first/__init__.py | tests/migrations2/test_migrations_2_first/__init__.py | python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false | |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/field_defaults/models.py | tests/field_defaults/models.py | """
Callable defaults
You can pass callable objects as the ``default`` parameter to a field. When
the object is created without an explicit value passed in, Django will call
the method to determine the default value.
This example uses ``datetime.datetime.now`` as the default for the ``pub_date``
field.
"""
from datetime import datetime
from decimal import Decimal
from django.db import models
from django.db.models.functions import Coalesce, ExtractYear, Now, Pi
from django.db.models.lookups import GreaterThan
class Article(models.Model):
headline = models.CharField(max_length=100, default="Default headline")
pub_date = models.DateTimeField(default=datetime.now)
def __str__(self):
return self.headline
class DBArticle(models.Model):
"""
Values or expressions can be passed as the db_default parameter to a field.
When the object is created without an explicit value passed in, the
database will insert the default value automatically.
"""
headline = models.CharField(max_length=100, db_default="Default headline")
pub_date = models.DateTimeField(db_default=Now())
cost = models.DecimalField(
max_digits=3, decimal_places=2, db_default=Decimal("3.33")
)
class Meta:
required_db_features = {"supports_expression_defaults"}
class DBDefaults(models.Model):
both = models.IntegerField(default=1, db_default=2)
null = models.FloatField(null=True, db_default=1.1)
class DBDefaultsFunction(models.Model):
number = models.FloatField(db_default=Pi())
year = models.IntegerField(db_default=ExtractYear(Now()))
added = models.FloatField(db_default=Pi() + 4.5)
multiple_subfunctions = models.FloatField(db_default=Coalesce(4.5, Pi()))
case_when = models.IntegerField(
db_default=models.Case(models.When(GreaterThan(2, 1), then=3), default=4)
)
class Meta:
required_db_features = {"supports_expression_defaults"}
class DBDefaultsPK(models.Model):
language_code = models.CharField(primary_key=True, max_length=2, db_default="en")
class DBDefaultsFK(models.Model):
language_code = models.ForeignKey(
DBDefaultsPK, db_default="fr", on_delete=models.CASCADE
)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/field_defaults/__init__.py | tests/field_defaults/__init__.py | python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false | |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/field_defaults/tests.py | tests/field_defaults/tests.py | from datetime import datetime
from decimal import Decimal
from math import pi
from django.core.exceptions import ValidationError
from django.db import connection
from django.db.models import Case, F, FloatField, Value, When
from django.db.models.expressions import (
Expression,
ExpressionList,
ExpressionWrapper,
Func,
OrderByList,
RawSQL,
)
from django.db.models.functions import Collate
from django.db.models.lookups import GreaterThan
from django.test import SimpleTestCase, TestCase, override_settings, skipUnlessDBFeature
from django.utils import timezone
from .models import (
Article,
DBArticle,
DBDefaults,
DBDefaultsFK,
DBDefaultsFunction,
DBDefaultsPK,
)
class DefaultTests(TestCase):
def test_field_defaults(self):
a = Article()
now = datetime.now()
a.save()
self.assertIsInstance(a.id, int)
self.assertEqual(a.headline, "Default headline")
self.assertLess((now - a.pub_date).seconds, 5)
@skipUnlessDBFeature("supports_expression_defaults")
def test_field_db_defaults_returning(self):
a = DBArticle()
a.save()
self.assertIsInstance(a.id, int)
expected_num_queries = (
0 if connection.features.can_return_columns_from_insert else 3
)
with self.assertNumQueries(expected_num_queries):
self.assertEqual(a.headline, "Default headline")
self.assertIsInstance(a.pub_date, datetime)
self.assertEqual(a.cost, Decimal("3.33"))
@skipUnlessDBFeature("supports_expression_defaults")
def test_field_db_defaults_refresh(self):
a = DBArticle()
a.save()
expected_num_queries = (
0 if connection.features.can_return_columns_from_insert else 3
)
self.assertIsInstance(a.id, int)
with self.assertNumQueries(expected_num_queries):
self.assertEqual(a.headline, "Default headline")
self.assertIsInstance(a.pub_date, datetime)
self.assertEqual(a.cost, Decimal("3.33"))
def test_null_db_default(self):
obj1 = DBDefaults.objects.create()
expected_num_queries = (
0 if connection.features.can_return_columns_from_insert else 1
)
with self.assertNumQueries(expected_num_queries):
self.assertEqual(obj1.null, 1.1)
obj2 = DBDefaults.objects.create(null=None)
with self.assertNumQueries(0):
self.assertIsNone(obj2.null)
@skipUnlessDBFeature("supports_expression_defaults")
@override_settings(USE_TZ=True)
def test_db_default_function(self):
m = DBDefaultsFunction.objects.create()
expected_num_queries = (
0 if connection.features.can_return_columns_from_insert else 4
)
with self.assertNumQueries(expected_num_queries):
self.assertAlmostEqual(m.number, pi)
self.assertEqual(m.year, timezone.now().year)
self.assertAlmostEqual(m.added, pi + 4.5)
self.assertEqual(m.multiple_subfunctions, 4.5)
@skipUnlessDBFeature("insert_test_table_with_defaults")
def test_both_default(self):
create_sql = connection.features.insert_test_table_with_defaults
with connection.cursor() as cursor:
cursor.execute(create_sql.format(DBDefaults._meta.db_table))
obj1 = DBDefaults.objects.get()
self.assertEqual(obj1.both, 2)
obj2 = DBDefaults.objects.create()
self.assertEqual(obj2.both, 1)
def test_pk_db_default(self):
obj1 = DBDefaultsPK.objects.create()
if not connection.features.can_return_columns_from_insert:
# refresh_from_db() cannot be used because that needs the pk to
# already be known to Django.
obj1 = DBDefaultsPK.objects.get(pk="en")
self.assertEqual(obj1.pk, "en")
self.assertEqual(obj1.language_code, "en")
obj2 = DBDefaultsPK.objects.create(language_code="de")
self.assertEqual(obj2.pk, "de")
self.assertEqual(obj2.language_code, "de")
def test_foreign_key_db_default(self):
parent1 = DBDefaultsPK.objects.create(language_code="fr")
child1 = DBDefaultsFK.objects.create()
if not connection.features.can_return_columns_from_insert:
child1.refresh_from_db()
self.assertEqual(child1.language_code, parent1)
parent2 = DBDefaultsPK.objects.create()
if not connection.features.can_return_columns_from_insert:
# refresh_from_db() cannot be used because that needs the pk to
# already be known to Django.
parent2 = DBDefaultsPK.objects.get(pk="en")
child2 = DBDefaultsFK.objects.create(language_code=parent2)
self.assertEqual(child2.language_code, parent2)
@skipUnlessDBFeature("supports_expression_defaults")
def test_case_when_db_default_returning(self):
m = DBDefaultsFunction.objects.create()
expected_num_queries = (
0 if connection.features.can_return_columns_from_insert else 1
)
with self.assertNumQueries(expected_num_queries):
self.assertEqual(m.case_when, 3)
@skipUnlessDBFeature("supports_expression_defaults")
def test_case_when_db_default_no_returning(self):
m = DBDefaultsFunction.objects.create()
m.refresh_from_db()
self.assertEqual(m.case_when, 3)
@skipUnlessDBFeature("supports_expression_defaults")
def test_bulk_create_all_db_defaults(self):
articles = [DBArticle(), DBArticle()]
DBArticle.objects.bulk_create(articles)
headlines = DBArticle.objects.values_list("headline", flat=True)
self.assertSequenceEqual(headlines, ["Default headline", "Default headline"])
@skipUnlessDBFeature("supports_expression_defaults")
def test_bulk_create_all_db_defaults_one_field(self):
pub_date = datetime.now()
articles = [DBArticle(pub_date=pub_date), DBArticle(pub_date=pub_date)]
DBArticle.objects.bulk_create(articles)
headlines = DBArticle.objects.values_list("headline", "pub_date", "cost")
self.assertSequenceEqual(
headlines,
[
("Default headline", pub_date, Decimal("3.33")),
("Default headline", pub_date, Decimal("3.33")),
],
)
@skipUnlessDBFeature("supports_expression_defaults")
def test_bulk_create_mixed_db_defaults(self):
articles = [DBArticle(), DBArticle(headline="Something else")]
DBArticle.objects.bulk_create(articles)
headlines = DBArticle.objects.values_list("headline", flat=True)
self.assertCountEqual(headlines, ["Default headline", "Something else"])
@skipUnlessDBFeature("supports_expression_defaults")
@override_settings(USE_TZ=True)
def test_bulk_create_mixed_db_defaults_function(self):
instances = [DBDefaultsFunction(), DBDefaultsFunction(year=2000)]
DBDefaultsFunction.objects.bulk_create(instances)
years = DBDefaultsFunction.objects.values_list("year", flat=True)
self.assertCountEqual(years, [2000, timezone.now().year])
@skipUnlessDBFeature("supports_expression_defaults")
def test_full_clean(self):
obj = DBArticle()
obj.full_clean()
obj.save()
obj.refresh_from_db()
self.assertEqual(obj.headline, "Default headline")
obj = DBArticle(headline="Other title")
obj.full_clean()
obj.save()
obj.refresh_from_db()
self.assertEqual(obj.headline, "Other title")
obj = DBArticle(headline="")
with self.assertRaises(ValidationError):
obj.full_clean()
class AllowedDefaultTests(SimpleTestCase):
def test_allowed(self):
class Max(Func):
function = "MAX"
tests = [
Value(10),
Max(1, 2),
RawSQL("Now()", ()),
Value(10) + Value(7), # Combined expression.
ExpressionList(Value(1), Value(2)),
ExpressionWrapper(Value(1), output_field=FloatField()),
Case(When(GreaterThan(2, 1), then=3), default=4),
]
for expression in tests:
with self.subTest(expression=expression):
self.assertIs(expression.allowed_default, True)
def test_disallowed(self):
class Max(Func):
function = "MAX"
tests = [
Expression(),
F("field"),
Max(F("count"), 1),
Value(10) + F("count"), # Combined expression.
ExpressionList(F("count"), Value(2)),
ExpressionWrapper(F("count"), output_field=FloatField()),
Collate(Value("John"), "nocase"),
OrderByList("field"),
]
for expression in tests:
with self.subTest(expression=expression):
self.assertIs(expression.allowed_default, False)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/mail/custombackend.py | tests/mail/custombackend.py | """A custom backend for testing."""
from django.core.mail.backends.base import BaseEmailBackend
class EmailBackend(BaseEmailBackend):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.test_outbox = []
def send_messages(self, email_messages):
# Messages are stored in an instance variable for testing.
self.test_outbox.extend(email_messages)
return len(email_messages)
class FailingEmailBackend(BaseEmailBackend):
def send_messages(self, email_messages):
raise ValueError("FailingEmailBackend is doomed to fail.")
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/mail/test_deprecated.py | tests/mail/test_deprecated.py | # RemovedInDjango70Warning: This entire file.
from email.mime.text import MIMEText
from django.core.mail import (
EmailAlternative,
EmailAttachment,
EmailMessage,
EmailMultiAlternatives,
)
from django.core.mail.message import forbid_multi_line_headers, sanitize_address
from django.test import SimpleTestCase, ignore_warnings
from django.utils.deprecation import RemovedInDjango70Warning
from .tests import MailTestsMixin
class DeprecationWarningTests(MailTestsMixin, SimpleTestCase):
def test_deprecated_on_import(self):
"""
These items are not typically called from user code,
so generate deprecation warnings immediately at the time
they are imported from django.core.mail.
"""
cases = [
# name, msg
(
"BadHeaderError",
"BadHeaderError is deprecated. Replace with ValueError.",
),
(
"SafeMIMEText",
"SafeMIMEText is deprecated. The return value of"
" EmailMessage.message() is an email.message.EmailMessage.",
),
(
"SafeMIMEMultipart",
"SafeMIMEMultipart is deprecated. The return value of"
" EmailMessage.message() is an email.message.EmailMessage.",
),
]
for name, msg in cases:
with self.subTest(name=name):
with self.assertWarnsMessage(RemovedInDjango70Warning, msg):
__import__("django.core.mail", fromlist=[name])
def test_sanitize_address_deprecated(self):
msg = (
"The internal API sanitize_address() is deprecated."
" Python's modern email API (with email.message.EmailMessage or"
" email.policy.default) will handle most required validation and"
" encoding. Use Python's email.headerregistry.Address to construct"
" formatted addresses from component parts."
)
with self.assertWarnsMessage(RemovedInDjango70Warning, msg):
sanitize_address("to@example.com", "ascii")
def test_forbid_multi_line_headers_deprecated(self):
msg = (
"The internal API forbid_multi_line_headers() is deprecated."
" Python's modern email API (with email.message.EmailMessage or"
" email.policy.default) will reject multi-line headers."
)
with self.assertWarnsMessage(RemovedInDjango70Warning, msg):
forbid_multi_line_headers("To", "to@example.com", "ascii")
class UndocumentedFeatureErrorTests(SimpleTestCase):
"""
These undocumented features were removed without going through deprecation.
In case they were being used, they now raise errors.
"""
def test_undocumented_mixed_subtype(self):
"""
Trying to use the previously undocumented, now unsupported
EmailMessage.mixed_subtype causes an error.
"""
msg = (
"EmailMessage no longer supports"
" the undocumented `mixed_subtype` attribute"
)
email = EmailMessage(
attachments=[EmailAttachment(None, b"GIF89a...", "image/gif")]
)
email.mixed_subtype = "related"
with self.assertRaisesMessage(AttributeError, msg):
email.message()
def test_undocumented_alternative_subtype(self):
"""
Trying to use the previously undocumented, now unsupported
EmailMultiAlternatives.alternative_subtype causes an error.
"""
msg = (
"EmailMultiAlternatives no longer supports"
" the undocumented `alternative_subtype` attribute"
)
email = EmailMultiAlternatives(
alternatives=[EmailAlternative("", "text/plain")]
)
email.alternative_subtype = "multilingual"
with self.assertRaisesMessage(AttributeError, msg):
email.message()
@ignore_warnings(category=RemovedInDjango70Warning)
class DeprecatedCompatibilityTests(SimpleTestCase):
def test_bad_header_error(self):
"""
Existing code that catches deprecated BadHeaderError should be
compatible with modern email (which raises ValueError instead).
"""
from django.core.mail import BadHeaderError
with self.assertRaises(BadHeaderError):
EmailMessage(subject="Bad\r\nHeader").message()
def test_attachments_mimebase_in_constructor(self):
txt = MIMEText("content1")
msg = EmailMessage(attachments=[txt])
payload = msg.message().get_payload()
self.assertEqual(payload[0], txt)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/mail/__init__.py | tests/mail/__init__.py | python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false | |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/mail/test_sendtestemail.py | tests/mail/test_sendtestemail.py | from django.core import mail
from django.core.management import CommandError, call_command
from django.test import SimpleTestCase, override_settings
@override_settings(
ADMINS=["admin@example.com", "admin_and_manager@example.com"],
MANAGERS=["manager@example.com", "admin_and_manager@example.com"],
)
class SendTestEmailManagementCommand(SimpleTestCase):
"""
Test the sending of a test email using the `sendtestemail` command.
"""
def test_single_receiver(self):
"""
The mail is sent with the correct subject and recipient.
"""
recipient = "joe@example.com"
call_command("sendtestemail", recipient)
self.assertEqual(len(mail.outbox), 1)
mail_message = mail.outbox[0]
self.assertEqual(mail_message.subject[0:15], "Test email from")
self.assertEqual(mail_message.recipients(), [recipient])
def test_multiple_receivers(self):
"""
The mail may be sent with multiple recipients.
"""
recipients = ["joe@example.com", "jane@example.com"]
call_command("sendtestemail", recipients[0], recipients[1])
self.assertEqual(len(mail.outbox), 1)
mail_message = mail.outbox[0]
self.assertEqual(mail_message.subject[0:15], "Test email from")
self.assertEqual(
sorted(mail_message.recipients()),
[
"jane@example.com",
"joe@example.com",
],
)
def test_missing_receivers(self):
"""
The command should complain if no receivers are given (and --admins or
--managers are not set).
"""
msg = (
"You must specify some email recipients, or pass the --managers or "
"--admin options."
)
with self.assertRaisesMessage(CommandError, msg):
call_command("sendtestemail")
def test_manager_receivers(self):
"""
The mail should be sent to the email addresses specified in
settings.MANAGERS.
"""
call_command("sendtestemail", "--managers")
self.assertEqual(len(mail.outbox), 1)
mail_message = mail.outbox[0]
self.assertEqual(
sorted(mail_message.recipients()),
[
"admin_and_manager@example.com",
"manager@example.com",
],
)
def test_admin_receivers(self):
"""
The mail should be sent to the email addresses specified in
settings.ADMIN.
"""
call_command("sendtestemail", "--admins")
self.assertEqual(len(mail.outbox), 1)
mail_message = mail.outbox[0]
self.assertEqual(
sorted(mail_message.recipients()),
[
"admin@example.com",
"admin_and_manager@example.com",
],
)
def test_manager_and_admin_receivers(self):
"""
The mail should be sent to the email addresses specified in both
settings.MANAGERS and settings.ADMINS.
"""
call_command("sendtestemail", "--managers", "--admins")
self.assertEqual(len(mail.outbox), 2)
manager_mail = mail.outbox[0]
self.assertEqual(
sorted(manager_mail.recipients()),
[
"admin_and_manager@example.com",
"manager@example.com",
],
)
admin_mail = mail.outbox[1]
self.assertEqual(
sorted(admin_mail.recipients()),
[
"admin@example.com",
"admin_and_manager@example.com",
],
)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/mail/tests.py | tests/mail/tests.py | import ast
import mimetypes
import os
import pickle
import re
import shutil
import socket
import sys
import tempfile
from datetime import datetime, timezone
from email import message_from_binary_file
from email import message_from_bytes as _message_from_bytes
from email import policy
from email.headerregistry import Address
from email.message import EmailMessage as PyEmailMessage
from email.message import Message as PyMessage
from email.message import MIMEPart
from email.mime.image import MIMEImage
from email.mime.text import MIMEText
from io import StringIO
from pathlib import Path
from smtplib import SMTP, SMTPException
from ssl import SSLError
from textwrap import dedent
from unittest import mock, skipUnless
from django.core import mail
from django.core.exceptions import ImproperlyConfigured
from django.core.mail import (
DNS_NAME,
EmailAlternative,
EmailAttachment,
EmailMessage,
EmailMultiAlternatives,
mail_admins,
mail_managers,
send_mail,
send_mass_mail,
)
from django.core.mail.backends import console, dummy, filebased, locmem, smtp
from django.test import SimpleTestCase, override_settings
from django.test.utils import ignore_warnings, requires_tz_support
from django.utils.deprecation import RemovedInDjango70Warning
from django.utils.translation import gettext_lazy
try:
from aiosmtpd.controller import Controller
HAS_AIOSMTPD = True
except ImportError:
HAS_AIOSMTPD = False
# Check whether python/cpython#128110 has been fixed by seeing if space between
# encoded-words is ignored (as required by RFC 2047 section 6.2).
NEEDS_CPYTHON_128110_WORKAROUND = (
_message_from_bytes(b"To: =??q?a?= =??q?b?= <to@ex>", policy=policy.default)
)["To"].addresses[0].display_name != "ab"
RFC2047_PREFIX = "=?" # start of an encoded-word.
def _apply_cpython_128110_workaround(message, msg_bytes):
"""
Updates message in place to correct misparsed rfc2047 display-names in
address headers caused by https://github.com/python/cpython/issues/128110.
"""
from email.header import decode_header
from email.headerregistry import AddressHeader
from email.parser import BytesHeaderParser
from email.utils import getaddresses
def rfc2047_decode(s):
# Decode using legacy decode_header() (which doesn't have the bug).
return "".join(
(
segment
if charset is None and isinstance(segment, str)
else segment.decode(charset or "ascii")
)
for segment, charset in decode_header(s)
)
def build_address(name, address):
if "@" in address:
return Address(display_name=name, addr_spec=address)
return Address(display_name=name, username=address, domain="")
# This workaround only applies to messages parsed with a modern policy.
assert not isinstance(message.policy, policy.Compat32)
# Reparse with compat32 to get access to raw (undecoded) headers.
raw_headers = BytesHeaderParser(policy=policy.compat32).parsebytes(msg_bytes)
for header, modern_value in message.items():
if not isinstance(modern_value, AddressHeader):
# The bug only affects structured address headers.
continue
raw_value = raw_headers[header]
if RFC2047_PREFIX in raw_value:
# Headers should not appear more than once.
assert len(message.get_all(header)) == 1
# Reconstruct Address objects using legacy APIs.
unfolded = raw_value.replace("\r\n", "").replace("\n", "")
corrected_addresses = (
build_address(rfc2047_decode(name), address)
for name, address in getaddresses([unfolded])
)
message.replace_header(header, corrected_addresses)
def message_from_bytes(s):
"""
email.message_from_bytes() using modern email.policy.default.
Returns a modern email.message.EmailMessage.
"""
# The modern email parser has a bug with adjacent rfc2047 encoded-words.
# This doesn't affect django.core.mail (which doesn't parse messages),
# but it can confuse our tests that try to verify sent content by reparsing
# the generated message. Apply a workaround if needed.
message = _message_from_bytes(s, policy=policy.default)
if NEEDS_CPYTHON_128110_WORKAROUND and RFC2047_PREFIX.encode() in s:
_apply_cpython_128110_workaround(message, s)
return message
class MailTestsMixin:
def assertMessageHasHeaders(self, message, headers):
"""
Asserts that the `message` has all `headers`.
message: can be an instance of an email.Message subclass or bytes
with the contents of an email message.
headers: should be a set of (header-name, header-value) tuples.
"""
if isinstance(message, bytes):
message = message_from_bytes(message)
msg_headers = set(message.items())
if not headers.issubset(msg_headers):
missing = "\n".join(f" {h}: {v}" for h, v in headers - msg_headers)
actual = "\n".join(f" {h}: {v}" for h, v in msg_headers)
raise self.failureException(
f"Expected headers not found in message.\n"
f"Missing headers:\n{missing}\n"
f"Actual headers:\n{actual}"
)
# In assertStartsWith()/assertEndsWith() failure messages, when truncating
# a long first ("haystack") string, include this many characters beyond the
# length of the second ("needle") string.
START_END_EXTRA_CONTEXT = 15
def assertStartsWith(self, first, second):
if not first.startswith(second):
# Use assertEqual() for failure message with diffs. If first value
# is much longer than second, truncate end and add an ellipsis.
self.longMessage = True
max_len = len(second) + self.START_END_EXTRA_CONTEXT
start_of_first = (
first
if len(first) <= max_len
else first[:max_len] + ("…" if isinstance(first, str) else b"...")
)
self.assertEqual(
start_of_first,
second,
"First string doesn't start with the second.",
)
def assertEndsWith(self, first, second):
if not first.endswith(second):
# Use assertEqual() for failure message with diffs. If first value
# is much longer than second, truncate start and prepend an
# ellipsis.
self.longMessage = True
max_len = len(second) + self.START_END_EXTRA_CONTEXT
end_of_first = (
first
if len(first) <= max_len
else ("…" if isinstance(first, str) else b"...") + first[-max_len:]
)
self.assertEqual(
end_of_first,
second,
"First string doesn't end with the second.",
)
def get_raw_attachments(self, django_message):
"""
Return a list of the raw attachment parts in the MIME message generated
by serializing django_message and reparsing the result.
This returns only "top-level" attachments. It will not descend into
message/* attached emails to find nested attachments.
"""
msg_bytes = django_message.message().as_bytes()
message = message_from_bytes(msg_bytes)
return list(message.iter_attachments())
def get_decoded_attachments(self, django_message):
"""
Return a list of decoded attachments resulting from serializing
django_message and reparsing the result.
Each attachment is returned as an EmailAttachment named tuple with
fields filename, content, and mimetype. The content will be decoded
to str for mimetype text/*; retained as bytes for other mimetypes.
"""
return [
EmailAttachment(
attachment.get_filename(),
attachment.get_content(),
attachment.get_content_type(),
)
for attachment in self.get_raw_attachments(django_message)
]
def get_message_structure(self, message, level=0):
"""
Return a multiline indented string representation
of the message's MIME content-type structure, e.g.:
multipart/mixed
multipart/alternative
text/plain
text/html
image/jpg
text/calendar
"""
# Adapted from email.iterators._structure().
indent = " " * (level * 4)
structure = [f"{indent}{message.get_content_type()}\n"]
if message.is_multipart():
for subpart in message.get_payload():
structure.append(self.get_message_structure(subpart, level + 1))
return "".join(structure)
class MailTests(MailTestsMixin, SimpleTestCase):
"""
Non-backend specific tests.
"""
def test_ascii(self):
email = EmailMessage(
"Subject", "Content\n", "from@example.com", ["to@example.com"]
)
message = email.message()
self.assertEqual(message["Subject"], "Subject")
self.assertEqual(message.get_payload(), "Content\n")
self.assertEqual(message["From"], "from@example.com")
self.assertEqual(message["To"], "to@example.com")
# RemovedInDjango70Warning.
@ignore_warnings(category=RemovedInDjango70Warning)
@mock.patch("django.core.mail.message.MIMEText.set_payload")
def test_nonascii_as_string_with_ascii_charset(self, mock_set_payload):
"""Line length check should encode the payload supporting
`surrogateescape`.
Following https://github.com/python/cpython/issues/76511, newer
versions of Python (3.12.3 and 3.13+) ensure that a message's
payload is encoded with the provided charset and `surrogateescape` is
used as the error handling strategy.
This test is heavily based on the test from the fix for the bug above.
Line length checks in SafeMIMEText's set_payload should also use the
same error handling strategy to avoid errors such as:
UnicodeEncodeError: 'utf-8' codec can't encode <...>: surrogates not
allowed
"""
# This test is specific to Python's legacy MIMEText. This can be safely
# removed when EmailMessage.message() uses Python's modern email API.
# (Using surrogateescape for non-utf8 is covered in test_encoding().)
from django.core.mail import SafeMIMEText
def simplified_set_payload(instance, payload, charset):
instance._payload = payload
mock_set_payload.side_effect = simplified_set_payload
text = (
"Text heavily based in Python's text for non-ascii messages: Föö bär"
).encode("iso-8859-1")
body = text.decode("ascii", errors="surrogateescape")
message = SafeMIMEText(body, "plain", "ascii")
mock_set_payload.assert_called_once()
self.assertEqual(message.get_payload(decode=True), text)
def test_multiple_recipients(self):
email = EmailMessage(
"Subject",
"Content\n",
"from@example.com",
["to@example.com", "other@example.com"],
)
message = email.message()
self.assertEqual(message["Subject"], "Subject")
self.assertEqual(message.get_payload(), "Content\n")
self.assertEqual(message["From"], "from@example.com")
self.assertEqual(message["To"], "to@example.com, other@example.com")
def test_header_omitted_for_no_to_recipients(self):
message = EmailMessage(
"Subject", "Content", "from@example.com", cc=["cc@example.com"]
).message()
self.assertNotIn("To", message)
def test_recipients_with_empty_strings(self):
"""
Empty strings in various recipient arguments are always stripped
off the final recipient list.
"""
email = EmailMessage(
"Subject",
"Content",
"from@example.com",
["to@example.com", ""],
cc=["cc@example.com", ""],
bcc=["", "bcc@example.com"],
reply_to=["", None],
)
self.assertEqual(
email.recipients(), ["to@example.com", "cc@example.com", "bcc@example.com"]
)
def test_cc(self):
"""Regression test for #7722"""
email = EmailMessage(
"Subject",
"Content",
"from@example.com",
["to@example.com"],
cc=["cc@example.com"],
)
message = email.message()
self.assertEqual(message["Cc"], "cc@example.com")
self.assertEqual(email.recipients(), ["to@example.com", "cc@example.com"])
# Test multiple CC with multiple To
email = EmailMessage(
"Subject",
"Content",
"from@example.com",
["to@example.com", "other@example.com"],
cc=["cc@example.com", "cc.other@example.com"],
)
message = email.message()
self.assertEqual(message["Cc"], "cc@example.com, cc.other@example.com")
self.assertEqual(
email.recipients(),
[
"to@example.com",
"other@example.com",
"cc@example.com",
"cc.other@example.com",
],
)
# Testing with Bcc
email = EmailMessage(
"Subject",
"Content",
"from@example.com",
["to@example.com", "other@example.com"],
cc=["cc@example.com", "cc.other@example.com"],
bcc=["bcc@example.com"],
)
message = email.message()
self.assertEqual(message["Cc"], "cc@example.com, cc.other@example.com")
self.assertEqual(
email.recipients(),
[
"to@example.com",
"other@example.com",
"cc@example.com",
"cc.other@example.com",
"bcc@example.com",
],
)
def test_cc_headers(self):
message = EmailMessage(
"Subject",
"Content",
"bounce@example.com",
["to@example.com"],
cc=["foo@example.com"],
headers={"Cc": "override@example.com"},
).message()
self.assertEqual(message.get_all("Cc"), ["override@example.com"])
def test_cc_in_headers_only(self):
message = EmailMessage(
"Subject",
"Content",
"bounce@example.com",
["to@example.com"],
headers={"Cc": "foo@example.com"},
).message()
self.assertEqual(message.get_all("Cc"), ["foo@example.com"])
def test_bcc_not_in_headers(self):
"""
A bcc address should be in the recipients,
but not in the (visible) message headers.
"""
email = EmailMessage(
to=["to@example.com"],
bcc=["bcc@example.com"],
)
message = email.message()
self.assertNotIn("Bcc", message)
self.assertNotIn("bcc@example.com", message.as_string())
self.assertEqual(email.recipients(), ["to@example.com", "bcc@example.com"])
def test_reply_to(self):
email = EmailMessage(
"Subject",
"Content",
"from@example.com",
["to@example.com"],
reply_to=["reply_to@example.com"],
)
message = email.message()
self.assertEqual(message["Reply-To"], "reply_to@example.com")
email = EmailMessage(
"Subject",
"Content",
"from@example.com",
["to@example.com"],
reply_to=["reply_to1@example.com", "reply_to2@example.com"],
)
message = email.message()
self.assertEqual(
message["Reply-To"], "reply_to1@example.com, reply_to2@example.com"
)
def test_recipients_as_tuple(self):
email = EmailMessage(
"Subject",
"Content",
"from@example.com",
("to@example.com", "other@example.com"),
cc=("cc@example.com", "cc.other@example.com"),
bcc=("bcc@example.com",),
)
message = email.message()
self.assertEqual(message["Cc"], "cc@example.com, cc.other@example.com")
self.assertEqual(
email.recipients(),
[
"to@example.com",
"other@example.com",
"cc@example.com",
"cc.other@example.com",
"bcc@example.com",
],
)
def test_recipients_as_string(self):
with self.assertRaisesMessage(
TypeError, '"to" argument must be a list or tuple'
):
EmailMessage(to="foo@example.com")
with self.assertRaisesMessage(
TypeError, '"cc" argument must be a list or tuple'
):
EmailMessage(cc="foo@example.com")
with self.assertRaisesMessage(
TypeError, '"bcc" argument must be a list or tuple'
):
EmailMessage(bcc="foo@example.com")
with self.assertRaisesMessage(
TypeError, '"reply_to" argument must be a list or tuple'
):
EmailMessage(reply_to="reply_to@example.com")
def test_header_injection(self):
msg = "Header values may not contain linefeed or carriage return characters"
cases = [
{"subject": "Subject\nInjection Test"},
{"subject": gettext_lazy("Lazy Subject\nInjection Test")},
{"to": ["Name\nInjection test <to@example.com>"]},
]
for kwargs in cases:
with self.subTest(case=kwargs):
email = EmailMessage(**kwargs)
with self.assertRaisesMessage(ValueError, msg):
email.message()
def test_folding_white_space(self):
"""
Test for correct use of "folding white space" in long headers (#7747)
"""
email = EmailMessage(
"Long subject lines that get wrapped should contain a space continuation "
"character to comply with RFC 822",
)
message = email.message()
msg_bytes = message.as_bytes()
self.assertIn(
b"Subject: Long subject lines that get wrapped should contain a space\n"
b" continuation character to comply with RFC 822",
msg_bytes,
)
def test_message_header_overrides(self):
"""
Specifying dates or message-ids in the extra headers overrides the
default values (#9233)
"""
headers = {"date": "Fri, 09 Nov 2001 01:08:47 -0000", "Message-ID": "foo"}
email = EmailMessage(headers=headers)
self.assertMessageHasHeaders(
email.message(),
{
("Message-ID", "foo"),
("date", "Fri, 09 Nov 2001 01:08:47 -0000"),
},
)
def test_datetime_in_date_header(self):
"""
A datetime in headers should be passed through to Python email intact,
so that it uses the email header date format.
"""
email = EmailMessage(
headers={"Date": datetime(2001, 11, 9, 1, 8, 47, tzinfo=timezone.utc)},
)
message = email.message()
self.assertEqual(message["Date"], "Fri, 09 Nov 2001 01:08:47 +0000")
# Not the default ISO format from force_str(strings_only=False).
self.assertNotEqual(message["Date"], "2001-11-09 01:08:47+00:00")
def test_from_header(self):
"""
Make sure we can manually set the From header (#9214)
"""
email = EmailMessage(
from_email="bounce@example.com",
headers={"From": "from@example.com"},
)
message = email.message()
self.assertEqual(message.get_all("From"), ["from@example.com"])
def test_to_header(self):
"""
Make sure we can manually set the To header (#17444)
"""
email = EmailMessage(
to=["list-subscriber@example.com", "list-subscriber2@example.com"],
headers={"To": "mailing-list@example.com"},
)
message = email.message()
self.assertEqual(message.get_all("To"), ["mailing-list@example.com"])
self.assertEqual(
email.to, ["list-subscriber@example.com", "list-subscriber2@example.com"]
)
# If we don't set the To header manually, it should default to the `to`
# argument to the constructor.
email = EmailMessage(
to=["list-subscriber@example.com", "list-subscriber2@example.com"],
)
message = email.message()
self.assertEqual(
message.get_all("To"),
["list-subscriber@example.com, list-subscriber2@example.com"],
)
self.assertEqual(
email.to, ["list-subscriber@example.com", "list-subscriber2@example.com"]
)
def test_to_in_headers_only(self):
message = EmailMessage(
headers={"To": "to@example.com"},
).message()
self.assertEqual(message.get_all("To"), ["to@example.com"])
def test_reply_to_header(self):
"""
Specifying 'Reply-To' in headers should override reply_to.
"""
email = EmailMessage(
reply_to=["foo@example.com"],
headers={"Reply-To": "override@example.com"},
)
message = email.message()
self.assertEqual(message.get_all("Reply-To"), ["override@example.com"])
def test_reply_to_in_headers_only(self):
message = EmailMessage(
headers={"Reply-To": "reply_to@example.com"},
).message()
self.assertEqual(message.get_all("Reply-To"), ["reply_to@example.com"])
def test_lazy_headers(self):
message = EmailMessage(
subject=gettext_lazy("subject"),
headers={"List-Unsubscribe": gettext_lazy("list-unsubscribe")},
).message()
self.assertEqual(message.get_all("Subject"), ["subject"])
self.assertEqual(message.get_all("List-Unsubscribe"), ["list-unsubscribe"])
def test_multiple_message_call(self):
"""
Regression for #13259 - Make sure that headers are not changed when
calling EmailMessage.message()
"""
email = EmailMessage(
from_email="bounce@example.com",
headers={"From": "from@example.com"},
)
message = email.message()
self.assertEqual(message.get_all("From"), ["from@example.com"])
message = email.message()
self.assertEqual(message.get_all("From"), ["from@example.com"])
def test_unicode_address_header(self):
"""
Regression for #11144 - When a to/from/cc header contains Unicode,
make sure the email addresses are parsed correctly (especially with
regards to commas)
"""
email = EmailMessage(
to=['"Firstname Sürname" <to@example.com>', "other@example.com"],
)
parsed = message_from_bytes(email.message().as_bytes())
self.assertEqual(
parsed["To"].addresses,
(
Address(display_name="Firstname Sürname", addr_spec="to@example.com"),
Address(addr_spec="other@example.com"),
),
)
email = EmailMessage(
to=['"Sürname, Firstname" <to@example.com>', "other@example.com"],
)
parsed = message_from_bytes(email.message().as_bytes())
self.assertEqual(
parsed["To"].addresses,
(
Address(display_name="Sürname, Firstname", addr_spec="to@example.com"),
Address(addr_spec="other@example.com"),
),
)
def test_unicode_headers(self):
email = EmailMessage(
subject="Gżegżółka",
to=["to@example.com"],
headers={
"Sender": '"Firstname Sürname" <sender@example.com>',
"Comments": "My Sürname is non-ASCII",
},
)
message = email.message()
# Verify sent headers use RFC 2047 encoded-words (not raw utf-8).
# The exact encoding details don't matter so long as the result parses
# to the original values.
msg_bytes = message.as_bytes()
self.assertTrue(msg_bytes.isascii()) # not unencoded utf-8.
parsed = message_from_bytes(msg_bytes)
self.assertEqual(parsed["Subject"], "Gżegżółka")
self.assertEqual(
parsed["Sender"].address,
Address(display_name="Firstname Sürname", addr_spec="sender@example.com"),
)
self.assertEqual(parsed["Comments"], "My Sürname is non-ASCII")
def test_non_utf8_headers_multipart(self):
"""
Make sure headers can be set with a different encoding than utf-8 in
EmailMultiAlternatives as well.
"""
headers = {"Date": "Fri, 09 Nov 2001 01:08:47 -0000", "Message-ID": "foo"}
from_email = "from@example.com"
to = '"Sürname, Firstname" <to@example.com>'
text_content = "This is an important message."
html_content = "<p>This is an <strong>important</strong> message.</p>"
email = EmailMultiAlternatives(
"Message from Firstname Sürname",
text_content,
from_email,
[to],
headers=headers,
)
email.attach_alternative(html_content, "text/html")
email.encoding = "iso-8859-1"
message = email.message()
# Verify sent headers use RFC 2047 encoded-words, not raw utf-8.
msg_bytes = message.as_bytes()
self.assertTrue(msg_bytes.isascii())
# Verify sent headers parse to original values.
parsed = message_from_bytes(msg_bytes)
self.assertEqual(parsed["Subject"], "Message from Firstname Sürname")
self.assertEqual(
parsed["To"].addresses,
(Address(display_name="Sürname, Firstname", addr_spec="to@example.com"),),
)
def test_multipart_with_attachments(self):
"""
EmailMultiAlternatives includes alternatives if the body is empty and
it has attachments.
"""
msg = EmailMultiAlternatives(body="")
html_content = "<p>This is <strong>html</strong></p>"
msg.attach_alternative(html_content, "text/html")
msg.attach("example.txt", "Text file content", "text/plain")
self.assertIn(html_content, msg.message().as_string())
def test_alternatives(self):
msg = EmailMultiAlternatives()
html_content = "<p>This is <strong>html</strong></p>"
mime_type = "text/html"
msg.attach_alternative(html_content, mime_type)
self.assertIsInstance(msg.alternatives[0], EmailAlternative)
self.assertEqual(msg.alternatives[0][0], html_content)
self.assertEqual(msg.alternatives[0].content, html_content)
self.assertEqual(msg.alternatives[0][1], mime_type)
self.assertEqual(msg.alternatives[0].mimetype, mime_type)
self.assertIn(html_content, msg.message().as_string())
def test_alternatives_constructor(self):
html_content = "<p>This is <strong>html</strong></p>"
mime_type = "text/html"
msg = EmailMultiAlternatives(
alternatives=[EmailAlternative(html_content, mime_type)]
)
self.assertIsInstance(msg.alternatives[0], EmailAlternative)
self.assertEqual(msg.alternatives[0][0], html_content)
self.assertEqual(msg.alternatives[0].content, html_content)
self.assertEqual(msg.alternatives[0][1], mime_type)
self.assertEqual(msg.alternatives[0].mimetype, mime_type)
self.assertIn(html_content, msg.message().as_string())
def test_alternatives_constructor_from_tuple(self):
html_content = "<p>This is <strong>html</strong></p>"
mime_type = "text/html"
msg = EmailMultiAlternatives(alternatives=[(html_content, mime_type)])
self.assertIsInstance(msg.alternatives[0], EmailAlternative)
self.assertEqual(msg.alternatives[0][0], html_content)
self.assertEqual(msg.alternatives[0].content, html_content)
self.assertEqual(msg.alternatives[0][1], mime_type)
self.assertEqual(msg.alternatives[0].mimetype, mime_type)
self.assertIn(html_content, msg.message().as_string())
def test_alternative_alternatives(self):
"""
Alternatives can be attached as either string or bytes
and need not use a text/* mimetype.
"""
cases = [
# (mimetype, content, expected decoded payload)
("application/x-ccmail-rtf", b"non-text\x07bytes", b"non-text\x07bytes"),
("application/x-ccmail-rtf", "non-text\x07string", b"non-text\x07string"),
("text/x-amp-html", b"text bytes\n", b"text bytes\n"),
("text/x-amp-html", "text string\n", b"text string\n"),
]
for mimetype, content, expected in cases:
with self.subTest(case=(mimetype, content)):
email = EmailMultiAlternatives()
email.attach_alternative(content, mimetype)
msg = email.message()
self.assertEqual(msg.get_content_type(), "multipart/alternative")
alternative = msg.get_payload()[0]
self.assertEqual(alternative.get_content_type(), mimetype)
self.assertEqual(alternative.get_payload(decode=True), expected)
def test_alternatives_and_attachment_serializable(self):
html_content = "<p>This is <strong>html</strong></p>"
mime_type = "text/html"
msg = EmailMultiAlternatives(alternatives=[(html_content, mime_type)])
msg.attach("test.txt", "This is plain text.", "plain/text")
# Alternatives and attachments can be serialized.
restored = pickle.loads(pickle.dumps(msg))
self.assertEqual(restored.subject, msg.subject)
self.assertEqual(restored.body, msg.body)
self.assertEqual(restored.from_email, msg.from_email)
self.assertEqual(restored.to, msg.to)
self.assertEqual(restored.alternatives, msg.alternatives)
self.assertEqual(restored.attachments, msg.attachments)
def test_none_body(self):
msg = EmailMessage("subject", None, "from@example.com", ["to@example.com"])
self.assertEqual(msg.body, "")
# The modern email API forces trailing newlines on all text/* parts,
# even an empty body.
self.assertEqual(msg.message().get_payload(), "\n")
@mock.patch("socket.getfqdn", return_value="漢字")
def test_non_ascii_dns_non_unicode_email(self, mocked_getfqdn):
delattr(DNS_NAME, "_fqdn")
email = EmailMessage()
email.encoding = "iso-8859-1"
self.assertIn("@xn--p8s937b>", email.message()["Message-ID"])
def test_encoding(self):
"""
Regression for #12791 - Encode body correctly with other encodings
than utf-8
"""
email = EmailMessage(body="Firstname Sürname is a great guy.\n")
email.encoding = "iso-8859-1"
message = email.message()
self.assertEqual(message["Content-Type"], 'text/plain; charset="iso-8859-1"')
# Check that body is actually encoded with iso-8859-1.
msg_bytes = message.as_bytes()
self.assertEqual(message["Content-Transfer-Encoding"], "8bit")
self.assertIn(b"Firstname S\xfc", msg_bytes)
parsed = message_from_bytes(msg_bytes)
self.assertEqual(parsed.get_content(), "Firstname Sürname is a great guy.\n")
def test_encoding_alternatives(self):
"""
Encode alternatives correctly with other encodings than utf-8.
"""
text_content = "Firstname Sürname is a great guy.\n"
html_content = "<p>Firstname Sürname is a <strong>great</strong> guy.</p>\n"
email = EmailMultiAlternatives(body=text_content)
email.encoding = "iso-8859-1"
email.attach_alternative(html_content, "text/html")
message = email.message()
# Check both parts are sent using the specified encoding.
self.assertEqual(
message.get_payload(0)["Content-Type"], 'text/plain; charset="iso-8859-1"'
)
self.assertEqual(
message.get_payload(1)["Content-Type"], 'text/html; charset="iso-8859-1"'
)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | true |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/base/models.py | tests/base/models.py | from django.db import models
# The models definitions below used to crash. Generating models dynamically
# at runtime is a bad idea because it pollutes the app registry. This doesn't
# integrate well with the test suite but at least it prevents regressions.
class CustomBaseModel(models.base.ModelBase):
pass
class MyModel(models.Model, metaclass=CustomBaseModel):
"""Model subclass with a custom base using metaclass."""
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/base/__init__.py | tests/base/__init__.py | python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false | |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/settings_tests/__init__.py | tests/settings_tests/__init__.py | python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false | |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/settings_tests/tests.py | tests/settings_tests/tests.py | import os
import sys
import unittest
from types import ModuleType, SimpleNamespace
from unittest import mock
from django.conf import ENVIRONMENT_VARIABLE, LazySettings, Settings, settings
from django.core.exceptions import ImproperlyConfigured
from django.http import HttpRequest
from django.test import (
SimpleTestCase,
TestCase,
TransactionTestCase,
modify_settings,
override_settings,
signals,
)
from django.test.utils import requires_tz_support
from django.urls import clear_script_prefix, set_script_prefix
@modify_settings(ITEMS={"prepend": ["b"], "append": ["d"], "remove": ["a", "e"]})
@override_settings(
ITEMS=["a", "c", "e"], ITEMS_OUTER=[1, 2, 3], TEST="override", TEST_OUTER="outer"
)
class FullyDecoratedTranTestCase(TransactionTestCase):
available_apps = []
def test_override(self):
self.assertEqual(settings.ITEMS, ["b", "c", "d"])
self.assertEqual(settings.ITEMS_OUTER, [1, 2, 3])
self.assertEqual(settings.TEST, "override")
self.assertEqual(settings.TEST_OUTER, "outer")
@modify_settings(
ITEMS={
"append": ["e", "f"],
"prepend": ["a"],
"remove": ["d", "c"],
}
)
def test_method_list_override(self):
self.assertEqual(settings.ITEMS, ["a", "b", "e", "f"])
self.assertEqual(settings.ITEMS_OUTER, [1, 2, 3])
@modify_settings(
ITEMS={
"append": ["b"],
"prepend": ["d"],
"remove": ["a", "c", "e"],
}
)
def test_method_list_override_no_ops(self):
self.assertEqual(settings.ITEMS, ["b", "d"])
@modify_settings(
ITEMS={
"append": "e",
"prepend": "a",
"remove": "c",
}
)
def test_method_list_override_strings(self):
self.assertEqual(settings.ITEMS, ["a", "b", "d", "e"])
@modify_settings(ITEMS={"remove": ["b", "d"]})
@modify_settings(ITEMS={"append": ["b"], "prepend": ["d"]})
def test_method_list_override_nested_order(self):
self.assertEqual(settings.ITEMS, ["d", "c", "b"])
@override_settings(TEST="override2")
def test_method_override(self):
self.assertEqual(settings.TEST, "override2")
self.assertEqual(settings.TEST_OUTER, "outer")
def test_decorated_testcase_name(self):
self.assertEqual(
FullyDecoratedTranTestCase.__name__, "FullyDecoratedTranTestCase"
)
def test_decorated_testcase_module(self):
self.assertEqual(FullyDecoratedTranTestCase.__module__, __name__)
@modify_settings(ITEMS={"prepend": ["b"], "append": ["d"], "remove": ["a", "e"]})
@override_settings(ITEMS=["a", "c", "e"], TEST="override")
class FullyDecoratedTestCase(TestCase):
def test_override(self):
self.assertEqual(settings.ITEMS, ["b", "c", "d"])
self.assertEqual(settings.TEST, "override")
@modify_settings(
ITEMS={
"append": "e",
"prepend": "a",
"remove": "c",
}
)
@override_settings(TEST="override2")
def test_method_override(self):
self.assertEqual(settings.ITEMS, ["a", "b", "d", "e"])
self.assertEqual(settings.TEST, "override2")
class ClassDecoratedTestCaseSuper(TestCase):
"""
Dummy class for testing max recursion error in child class call to
super(). Refs #17011.
"""
def test_max_recursion_error(self):
pass
@override_settings(TEST="override")
class ClassDecoratedTestCase(ClassDecoratedTestCaseSuper):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.foo = getattr(settings, "TEST", "BUG")
def test_override(self):
self.assertEqual(settings.TEST, "override")
def test_setupclass_override(self):
"""Settings are overridden within setUpClass (#21281)."""
self.assertEqual(self.foo, "override")
@override_settings(TEST="override2")
def test_method_override(self):
self.assertEqual(settings.TEST, "override2")
def test_max_recursion_error(self):
"""
Overriding a method on a super class and then calling that method on
the super class should not trigger infinite recursion. See #17011.
"""
super().test_max_recursion_error()
@modify_settings(ITEMS={"append": "mother"})
@override_settings(ITEMS=["father"], TEST="override-parent")
class ParentDecoratedTestCase(TestCase):
pass
@modify_settings(ITEMS={"append": ["child"]})
@override_settings(TEST="override-child")
class ChildDecoratedTestCase(ParentDecoratedTestCase):
def test_override_settings_inheritance(self):
self.assertEqual(settings.ITEMS, ["father", "mother", "child"])
self.assertEqual(settings.TEST, "override-child")
class SettingsTests(SimpleTestCase):
def setUp(self):
self.testvalue = None
signals.setting_changed.connect(self.signal_callback)
self.addCleanup(signals.setting_changed.disconnect, self.signal_callback)
def signal_callback(self, sender, setting, value, **kwargs):
if setting == "TEST":
self.testvalue = value
def test_override(self):
settings.TEST = "test"
self.assertEqual("test", settings.TEST)
with self.settings(TEST="override"):
self.assertEqual("override", settings.TEST)
self.assertEqual("test", settings.TEST)
del settings.TEST
def test_override_change(self):
settings.TEST = "test"
self.assertEqual("test", settings.TEST)
with self.settings(TEST="override"):
self.assertEqual("override", settings.TEST)
settings.TEST = "test2"
self.assertEqual("test", settings.TEST)
del settings.TEST
def test_override_doesnt_leak(self):
with self.assertRaises(AttributeError):
getattr(settings, "TEST")
with self.settings(TEST="override"):
self.assertEqual("override", settings.TEST)
settings.TEST = "test"
with self.assertRaises(AttributeError):
getattr(settings, "TEST")
@override_settings(TEST="override")
def test_decorator(self):
self.assertEqual("override", settings.TEST)
def test_context_manager(self):
with self.assertRaises(AttributeError):
getattr(settings, "TEST")
override = override_settings(TEST="override")
with self.assertRaises(AttributeError):
getattr(settings, "TEST")
override.enable()
self.assertEqual("override", settings.TEST)
override.disable()
with self.assertRaises(AttributeError):
getattr(settings, "TEST")
def test_class_decorator(self):
# SimpleTestCase can be decorated by override_settings, but not
# ut.TestCase
class SimpleTestCaseSubclass(SimpleTestCase):
pass
class UnittestTestCaseSubclass(unittest.TestCase):
pass
decorated = override_settings(TEST="override")(SimpleTestCaseSubclass)
self.assertIsInstance(decorated, type)
self.assertTrue(issubclass(decorated, SimpleTestCase))
with self.assertRaisesMessage(
Exception, "Only subclasses of Django SimpleTestCase"
):
decorated = override_settings(TEST="override")(UnittestTestCaseSubclass)
def test_signal_callback_context_manager(self):
with self.assertRaises(AttributeError):
getattr(settings, "TEST")
with self.settings(TEST="override"):
self.assertEqual(self.testvalue, "override")
self.assertIsNone(self.testvalue)
@override_settings(TEST="override")
def test_signal_callback_decorator(self):
self.assertEqual(self.testvalue, "override")
#
# Regression tests for #10130: deleting settings.
#
def test_settings_delete(self):
settings.TEST = "test"
self.assertEqual("test", settings.TEST)
del settings.TEST
msg = "'Settings' object has no attribute 'TEST'"
with self.assertRaisesMessage(AttributeError, msg):
getattr(settings, "TEST")
def test_settings_delete_wrapped(self):
with self.assertRaisesMessage(TypeError, "can't delete _wrapped."):
delattr(settings, "_wrapped")
def test_override_settings_delete(self):
"""
Allow deletion of a setting in an overridden settings set (#18824)
"""
previous_i18n = settings.USE_I18N
previous_tz = settings.USE_TZ
with self.settings(USE_I18N=False):
del settings.USE_I18N
with self.assertRaises(AttributeError):
getattr(settings, "USE_I18N")
# Should also work for a non-overridden setting
del settings.USE_TZ
with self.assertRaises(AttributeError):
getattr(settings, "USE_TZ")
self.assertNotIn("USE_I18N", dir(settings))
self.assertNotIn("USE_TZ", dir(settings))
self.assertEqual(settings.USE_I18N, previous_i18n)
self.assertEqual(settings.USE_TZ, previous_tz)
def test_override_settings_nested(self):
"""
override_settings uses the actual _wrapped attribute at
runtime, not when it was instantiated.
"""
with self.assertRaises(AttributeError):
getattr(settings, "TEST")
with self.assertRaises(AttributeError):
getattr(settings, "TEST2")
inner = override_settings(TEST2="override")
with override_settings(TEST="override"):
self.assertEqual("override", settings.TEST)
with inner:
self.assertEqual("override", settings.TEST)
self.assertEqual("override", settings.TEST2)
# inner's __exit__ should have restored the settings of the outer
# context manager, not those when the class was instantiated
self.assertEqual("override", settings.TEST)
with self.assertRaises(AttributeError):
getattr(settings, "TEST2")
with self.assertRaises(AttributeError):
getattr(settings, "TEST")
with self.assertRaises(AttributeError):
getattr(settings, "TEST2")
@override_settings(SECRET_KEY="")
def test_no_secret_key(self):
msg = "The SECRET_KEY setting must not be empty."
with self.assertRaisesMessage(ImproperlyConfigured, msg):
settings.SECRET_KEY
def test_no_settings_module(self):
msg = (
"Requested setting%s, but settings are not configured. You "
"must either define the environment variable DJANGO_SETTINGS_MODULE "
"or call settings.configure() before accessing settings."
)
orig_settings = os.environ[ENVIRONMENT_VARIABLE]
os.environ[ENVIRONMENT_VARIABLE] = ""
try:
with self.assertRaisesMessage(ImproperlyConfigured, msg % "s"):
settings._setup()
with self.assertRaisesMessage(ImproperlyConfigured, msg % " TEST"):
settings._setup("TEST")
finally:
os.environ[ENVIRONMENT_VARIABLE] = orig_settings
def test_already_configured(self):
with self.assertRaisesMessage(RuntimeError, "Settings already configured."):
settings.configure()
def test_nonupper_settings_prohibited_in_configure(self):
s = LazySettings()
with self.assertRaisesMessage(TypeError, "Setting 'foo' must be uppercase."):
s.configure(foo="bar")
def test_nonupper_settings_ignored_in_default_settings(self):
s = LazySettings()
s.configure(SimpleNamespace(foo="bar"))
with self.assertRaises(AttributeError):
getattr(s, "foo")
@requires_tz_support
@mock.patch("django.conf.global_settings.TIME_ZONE", "test")
def test_incorrect_timezone(self):
with self.assertRaisesMessage(ValueError, "Incorrect timezone setting: test"):
settings._setup()
class TestComplexSettingOverride(SimpleTestCase):
def setUp(self):
self.old_warn_override_settings = signals.COMPLEX_OVERRIDE_SETTINGS.copy()
signals.COMPLEX_OVERRIDE_SETTINGS.add("TEST_WARN")
def tearDown(self):
signals.COMPLEX_OVERRIDE_SETTINGS = self.old_warn_override_settings
self.assertNotIn("TEST_WARN", signals.COMPLEX_OVERRIDE_SETTINGS)
def test_complex_override_warning(self):
"""Regression test for #19031"""
msg = "Overriding setting TEST_WARN can lead to unexpected behavior."
with self.assertWarnsMessage(UserWarning, msg) as cm:
with override_settings(TEST_WARN="override"):
self.assertEqual(settings.TEST_WARN, "override")
self.assertEqual(cm.filename, __file__)
class SecureProxySslHeaderTest(SimpleTestCase):
@override_settings(SECURE_PROXY_SSL_HEADER=None)
def test_none(self):
req = HttpRequest()
self.assertIs(req.is_secure(), False)
@override_settings(SECURE_PROXY_SSL_HEADER=("HTTP_X_FORWARDED_PROTO", "https"))
def test_set_without_xheader(self):
req = HttpRequest()
self.assertIs(req.is_secure(), False)
@override_settings(SECURE_PROXY_SSL_HEADER=("HTTP_X_FORWARDED_PROTO", "https"))
def test_set_with_xheader_wrong(self):
req = HttpRequest()
req.META["HTTP_X_FORWARDED_PROTO"] = "wrongvalue"
self.assertIs(req.is_secure(), False)
@override_settings(SECURE_PROXY_SSL_HEADER=("HTTP_X_FORWARDED_PROTO", "https"))
def test_set_with_xheader_right(self):
req = HttpRequest()
req.META["HTTP_X_FORWARDED_PROTO"] = "https"
self.assertIs(req.is_secure(), True)
@override_settings(SECURE_PROXY_SSL_HEADER=("HTTP_X_FORWARDED_PROTO", "https"))
def test_set_with_xheader_leftmost_right(self):
req = HttpRequest()
req.META["HTTP_X_FORWARDED_PROTO"] = "https, http"
self.assertIs(req.is_secure(), True)
req.META["HTTP_X_FORWARDED_PROTO"] = "https , http"
self.assertIs(req.is_secure(), True)
@override_settings(SECURE_PROXY_SSL_HEADER=("HTTP_X_FORWARDED_PROTO", "https"))
def test_set_with_xheader_leftmost_not_secure(self):
req = HttpRequest()
req.META["HTTP_X_FORWARDED_PROTO"] = "http, https"
self.assertIs(req.is_secure(), False)
@override_settings(SECURE_PROXY_SSL_HEADER=("HTTP_X_FORWARDED_PROTO", "https"))
def test_set_with_xheader_multiple_not_secure(self):
req = HttpRequest()
req.META["HTTP_X_FORWARDED_PROTO"] = "http ,wrongvalue,http,http"
self.assertIs(req.is_secure(), False)
@override_settings(SECURE_PROXY_SSL_HEADER=("HTTP_X_FORWARDED_PROTO", "https"))
def test_xheader_preferred_to_underlying_request(self):
class ProxyRequest(HttpRequest):
def _get_scheme(self):
"""Proxy always connecting via HTTPS"""
return "https"
# Client connects via HTTP.
req = ProxyRequest()
req.META["HTTP_X_FORWARDED_PROTO"] = "http"
self.assertIs(req.is_secure(), False)
class IsOverriddenTest(SimpleTestCase):
def test_configure(self):
s = LazySettings()
s.configure(SECRET_KEY="foo")
self.assertTrue(s.is_overridden("SECRET_KEY"))
def test_module(self):
settings_module = ModuleType("fake_settings_module")
settings_module.SECRET_KEY = "foo"
settings_module.USE_TZ = False
sys.modules["fake_settings_module"] = settings_module
try:
s = Settings("fake_settings_module")
self.assertTrue(s.is_overridden("SECRET_KEY"))
self.assertFalse(s.is_overridden("ALLOWED_HOSTS"))
finally:
del sys.modules["fake_settings_module"]
def test_override(self):
self.assertFalse(settings.is_overridden("ALLOWED_HOSTS"))
with override_settings(ALLOWED_HOSTS=[]):
self.assertTrue(settings.is_overridden("ALLOWED_HOSTS"))
def test_unevaluated_lazysettings_repr(self):
lazy_settings = LazySettings()
expected = "<LazySettings [Unevaluated]>"
self.assertEqual(repr(lazy_settings), expected)
def test_evaluated_lazysettings_repr(self):
lazy_settings = LazySettings()
module = os.environ.get(ENVIRONMENT_VARIABLE)
expected = '<LazySettings "%s">' % module
# Force evaluation of the lazy object.
lazy_settings.APPEND_SLASH
self.assertEqual(repr(lazy_settings), expected)
def test_usersettingsholder_repr(self):
lazy_settings = LazySettings()
lazy_settings.configure(APPEND_SLASH=False)
expected = "<UserSettingsHolder>"
self.assertEqual(repr(lazy_settings._wrapped), expected)
def test_settings_repr(self):
module = os.environ.get(ENVIRONMENT_VARIABLE)
lazy_settings = Settings(module)
expected = '<Settings "%s">' % module
self.assertEqual(repr(lazy_settings), expected)
class TestListSettings(SimpleTestCase):
"""
Make sure settings that should be lists or tuples throw
ImproperlyConfigured if they are set to a string instead of a list or
tuple.
"""
list_or_tuple_settings = (
"ALLOWED_HOSTS",
"INSTALLED_APPS",
"TEMPLATE_DIRS",
"LOCALE_PATHS",
"SECRET_KEY_FALLBACKS",
)
def test_tuple_settings(self):
settings_module = ModuleType("fake_settings_module")
settings_module.SECRET_KEY = "foo"
msg = "The %s setting must be a list or a tuple."
for setting in self.list_or_tuple_settings:
setattr(settings_module, setting, ("non_list_or_tuple_value"))
sys.modules["fake_settings_module"] = settings_module
try:
with self.assertRaisesMessage(ImproperlyConfigured, msg % setting):
Settings("fake_settings_module")
finally:
del sys.modules["fake_settings_module"]
delattr(settings_module, setting)
class SettingChangeEnterException(Exception):
pass
class SettingChangeExitException(Exception):
pass
class OverrideSettingsIsolationOnExceptionTests(SimpleTestCase):
"""
The override_settings context manager restore settings if one of the
receivers of "setting_changed" signal fails. Check the three cases of
receiver failure detailed in receiver(). In each case, ALL receivers are
called when exiting the context manager.
"""
def setUp(self):
signals.setting_changed.connect(self.receiver)
self.addCleanup(signals.setting_changed.disconnect, self.receiver)
# Create a spy that's connected to the `setting_changed` signal and
# executed AFTER `self.receiver`.
self.spy_receiver = mock.Mock()
signals.setting_changed.connect(self.spy_receiver)
self.addCleanup(signals.setting_changed.disconnect, self.spy_receiver)
def receiver(self, **kwargs):
"""
A receiver that fails while certain settings are being changed.
- SETTING_BOTH raises an error while receiving the signal
on both entering and exiting the context manager.
- SETTING_ENTER raises an error only on enter.
- SETTING_EXIT raises an error only on exit.
"""
setting = kwargs["setting"]
enter = kwargs["enter"]
if setting in ("SETTING_BOTH", "SETTING_ENTER") and enter:
raise SettingChangeEnterException
if setting in ("SETTING_BOTH", "SETTING_EXIT") and not enter:
raise SettingChangeExitException
def check_settings(self):
"""Assert that settings for these tests aren't present."""
self.assertFalse(hasattr(settings, "SETTING_BOTH"))
self.assertFalse(hasattr(settings, "SETTING_ENTER"))
self.assertFalse(hasattr(settings, "SETTING_EXIT"))
self.assertFalse(hasattr(settings, "SETTING_PASS"))
def check_spy_receiver_exit_calls(self, call_count):
"""
Assert that `self.spy_receiver` was called exactly `call_count` times
with the ``enter=False`` keyword argument.
"""
kwargs_with_exit = [
kwargs
for args, kwargs in self.spy_receiver.call_args_list
if ("enter", False) in kwargs.items()
]
self.assertEqual(len(kwargs_with_exit), call_count)
def test_override_settings_both(self):
"""Receiver fails on both enter and exit."""
with self.assertRaises(SettingChangeEnterException):
with override_settings(SETTING_PASS="BOTH", SETTING_BOTH="BOTH"):
pass
self.check_settings()
# Two settings were touched, so expect two calls of `spy_receiver`.
self.check_spy_receiver_exit_calls(call_count=2)
def test_override_settings_enter(self):
"""Receiver fails on enter only."""
with self.assertRaises(SettingChangeEnterException):
with override_settings(SETTING_PASS="ENTER", SETTING_ENTER="ENTER"):
pass
self.check_settings()
# Two settings were touched, so expect two calls of `spy_receiver`.
self.check_spy_receiver_exit_calls(call_count=2)
def test_override_settings_exit(self):
"""Receiver fails on exit only."""
with self.assertRaises(SettingChangeExitException):
with override_settings(SETTING_PASS="EXIT", SETTING_EXIT="EXIT"):
pass
self.check_settings()
# Two settings were touched, so expect two calls of `spy_receiver`.
self.check_spy_receiver_exit_calls(call_count=2)
def test_override_settings_reusable_on_enter(self):
"""
Error is raised correctly when reusing the same override_settings
instance.
"""
@override_settings(SETTING_ENTER="ENTER")
def decorated_function():
pass
with self.assertRaises(SettingChangeEnterException):
decorated_function()
signals.setting_changed.disconnect(self.receiver)
# This call shouldn't raise any errors.
decorated_function()
class MediaURLStaticURLPrefixTest(SimpleTestCase):
def set_script_name(self, val):
clear_script_prefix()
if val is not None:
set_script_prefix(val)
def test_not_prefixed(self):
# Don't add SCRIPT_NAME prefix to absolute paths, URLs, or None.
tests = (
"/path/",
"http://myhost.com/path/",
"http://myhost/path/",
"https://myhost/path/",
None,
)
for setting in ("MEDIA_URL", "STATIC_URL"):
for path in tests:
new_settings = {setting: path}
with self.settings(**new_settings):
for script_name in ["/somesubpath", "/somesubpath/", "/", "", None]:
with self.subTest(script_name=script_name, **new_settings):
try:
self.set_script_name(script_name)
self.assertEqual(getattr(settings, setting), path)
finally:
clear_script_prefix()
def test_add_script_name_prefix(self):
tests = (
# Relative paths.
("/somesubpath", "path/", "/somesubpath/path/"),
("/somesubpath/", "path/", "/somesubpath/path/"),
("/", "path/", "/path/"),
# Invalid URLs.
(
"/somesubpath/",
"htp://myhost.com/path/",
"/somesubpath/htp://myhost.com/path/",
),
# Blank settings.
("/somesubpath/", "", "/somesubpath/"),
)
for setting in ("MEDIA_URL", "STATIC_URL"):
for script_name, path, expected_path in tests:
new_settings = {setting: path}
with self.settings(**new_settings):
with self.subTest(script_name=script_name, **new_settings):
try:
self.set_script_name(script_name)
self.assertEqual(getattr(settings, setting), expected_path)
finally:
clear_script_prefix()
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/m2m_intermediary/models.py | tests/m2m_intermediary/models.py | """
Many-to-many relationships via an intermediary table
For many-to-many relationships that need extra fields on the intermediary
table, use an intermediary model.
In this example, an ``Article`` can have multiple ``Reporter`` objects, and
each ``Article``-``Reporter`` combination (a ``Writer``) has a ``position``
field, which specifies the ``Reporter``'s position for the given article
(e.g. "Staff writer").
"""
from django.db import models
class Reporter(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
def __str__(self):
return "%s %s" % (self.first_name, self.last_name)
class Article(models.Model):
headline = models.CharField(max_length=100)
pub_date = models.DateField()
class Writer(models.Model):
reporter = models.ForeignKey(Reporter, models.CASCADE)
article = models.ForeignKey(Article, models.CASCADE)
position = models.CharField(max_length=100)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/m2m_intermediary/__init__.py | tests/m2m_intermediary/__init__.py | python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false | |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/m2m_intermediary/tests.py | tests/m2m_intermediary/tests.py | from datetime import datetime
from django.test import TestCase
from .models import Article, Reporter, Writer
class M2MIntermediaryTests(TestCase):
def test_intermediary(self):
r1 = Reporter.objects.create(first_name="John", last_name="Smith")
r2 = Reporter.objects.create(first_name="Jane", last_name="Doe")
a = Article.objects.create(
headline="This is a test", pub_date=datetime(2005, 7, 27)
)
w1 = Writer.objects.create(reporter=r1, article=a, position="Main writer")
w2 = Writer.objects.create(reporter=r2, article=a, position="Contributor")
self.assertQuerySetEqual(
a.writer_set.select_related().order_by("-position"),
[
("John Smith", "Main writer"),
("Jane Doe", "Contributor"),
],
lambda w: (str(w.reporter), w.position),
)
self.assertEqual(w1.reporter, r1)
self.assertEqual(w2.reporter, r2)
self.assertEqual(w1.article, a)
self.assertEqual(w2.article, a)
self.assertQuerySetEqual(
r1.writer_set.all(),
[("John Smith", "Main writer")],
lambda w: (str(w.reporter), w.position),
)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/fixtures_regress/models.py | tests/fixtures_regress/models.py | from django.contrib.auth.models import User
from django.db import models
class Animal(models.Model):
name = models.CharField(max_length=150)
latin_name = models.CharField(max_length=150)
count = models.IntegerField()
weight = models.FloatField()
# use a non-default name for the default manager
specimens = models.Manager()
def __str__(self):
return self.name
class Plant(models.Model):
name = models.CharField(max_length=150)
class Meta:
# For testing when upper case letter in app name; regression for #4057
db_table = "Fixtures_regress_plant"
class Stuff(models.Model):
name = models.CharField(max_length=20, null=True)
owner = models.ForeignKey(User, models.SET_NULL, null=True)
def __str__(self):
return self.name + " is owned by " + str(self.owner)
class Absolute(models.Model):
name = models.CharField(max_length=40)
class Parent(models.Model):
name = models.CharField(max_length=10)
class Meta:
ordering = ("id",)
class Child(Parent):
data = models.CharField(max_length=10)
# Models to regression test #7572, #20820
class Channel(models.Model):
name = models.CharField(max_length=255)
class Article(models.Model):
title = models.CharField(max_length=255)
channels = models.ManyToManyField(Channel)
class Meta:
ordering = ("id",)
# Subclass of a model with a ManyToManyField for test_ticket_20820
class SpecialArticle(Article):
pass
# Models to regression test #22421
class CommonFeature(Article):
class Meta:
abstract = True
class Feature(CommonFeature):
pass
# Models to regression test #11428
class Widget(models.Model):
name = models.CharField(max_length=255)
class Meta:
ordering = ("name",)
def __str__(self):
return self.name
class WidgetProxy(Widget):
class Meta:
proxy = True
# Check for forward references in FKs and M2Ms with natural keys
class TestManager(models.Manager):
def get_by_natural_key(self, key):
return self.get(name=key)
class Store(models.Model):
name = models.CharField(max_length=255, unique=True)
main = models.ForeignKey("self", models.SET_NULL, null=True)
objects = TestManager()
class Meta:
ordering = ("name",)
def __str__(self):
return self.name
def natural_key(self):
return (self.name,)
class Person(models.Model):
name = models.CharField(max_length=255, unique=True)
objects = TestManager()
class Meta:
ordering = ("name",)
def __str__(self):
return self.name
# Person doesn't actually have a dependency on store, but we need to define
# one to test the behavior of the dependency resolution algorithm.
def natural_key(self):
return (self.name,)
natural_key.dependencies = ["fixtures_regress.store"]
class Book(models.Model):
name = models.CharField(max_length=255)
author = models.ForeignKey(Person, models.CASCADE)
stores = models.ManyToManyField(Store)
class Meta:
ordering = ("name",)
def __str__(self):
return "%s by %s (available at %s)" % (
self.name,
self.author.name,
", ".join(s.name for s in self.stores.all()),
)
class NaturalKeyWithFKDependencyManager(models.Manager):
def get_by_natural_key(self, name, author):
return self.get(name=name, author__name=author)
class NaturalKeyWithFKDependency(models.Model):
name = models.CharField(max_length=255)
author = models.ForeignKey(Person, models.CASCADE)
objects = NaturalKeyWithFKDependencyManager()
class Meta:
unique_together = ["name", "author"]
def natural_key(self):
return (self.name,) + self.author.natural_key()
natural_key.dependencies = ["fixtures_regress.Person"]
class NKManager(models.Manager):
def get_by_natural_key(self, data):
return self.get(data=data)
class NKChild(Parent):
data = models.CharField(max_length=10, unique=True)
objects = NKManager()
def natural_key(self):
return (self.data,)
def __str__(self):
return "NKChild %s:%s" % (self.name, self.data)
class RefToNKChild(models.Model):
text = models.CharField(max_length=10)
nk_fk = models.ForeignKey(NKChild, models.CASCADE, related_name="ref_fks")
nk_m2m = models.ManyToManyField(NKChild, related_name="ref_m2ms")
def __str__(self):
return "%s: Reference to %s [%s]" % (
self.text,
self.nk_fk,
", ".join(str(o) for o in self.nk_m2m.all()),
)
# ome models with pathological circular dependencies
class Circle1(models.Model):
name = models.CharField(max_length=255, unique=True)
def natural_key(self):
return (self.name,)
natural_key.dependencies = ["fixtures_regress.circle2"]
class Circle2(models.Model):
name = models.CharField(max_length=255, unique=True)
def natural_key(self):
return (self.name,)
natural_key.dependencies = ["fixtures_regress.circle1"]
class Circle3(models.Model):
name = models.CharField(max_length=255, unique=True)
def natural_key(self):
return (self.name,)
natural_key.dependencies = ["fixtures_regress.circle3"]
class Circle4(models.Model):
name = models.CharField(max_length=255, unique=True)
def natural_key(self):
return (self.name,)
natural_key.dependencies = ["fixtures_regress.circle5"]
class Circle5(models.Model):
name = models.CharField(max_length=255, unique=True)
def natural_key(self):
return (self.name,)
natural_key.dependencies = ["fixtures_regress.circle6"]
class Circle6(models.Model):
name = models.CharField(max_length=255, unique=True)
def natural_key(self):
return (self.name,)
natural_key.dependencies = ["fixtures_regress.circle4"]
class ExternalDependency(models.Model):
name = models.CharField(max_length=255, unique=True)
def natural_key(self):
return (self.name,)
natural_key.dependencies = ["fixtures_regress.book"]
# Model for regression test of #11101
class Thingy(models.Model):
name = models.CharField(max_length=255)
class M2MToSelf(models.Model):
parent = models.ManyToManyField("self", blank=True)
class BaseNKModel(models.Model):
"""
Base model with a natural_key and a manager with `get_by_natural_key`
"""
data = models.CharField(max_length=20, unique=True)
objects = NKManager()
class Meta:
abstract = True
def __str__(self):
return self.data
def natural_key(self):
return (self.data,)
class M2MSimpleA(BaseNKModel):
b_set = models.ManyToManyField("M2MSimpleB")
class M2MSimpleB(BaseNKModel):
pass
class M2MSimpleCircularA(BaseNKModel):
b_set = models.ManyToManyField("M2MSimpleCircularB")
class M2MSimpleCircularB(BaseNKModel):
a_set = models.ManyToManyField("M2MSimpleCircularA")
class M2MComplexA(BaseNKModel):
b_set = models.ManyToManyField("M2MComplexB", through="M2MThroughAB")
class M2MComplexB(BaseNKModel):
pass
class M2MThroughAB(BaseNKModel):
a = models.ForeignKey(M2MComplexA, models.CASCADE)
b = models.ForeignKey(M2MComplexB, models.CASCADE)
class M2MComplexCircular1A(BaseNKModel):
b_set = models.ManyToManyField(
"M2MComplexCircular1B", through="M2MCircular1ThroughAB"
)
class M2MComplexCircular1B(BaseNKModel):
c_set = models.ManyToManyField(
"M2MComplexCircular1C", through="M2MCircular1ThroughBC"
)
class M2MComplexCircular1C(BaseNKModel):
a_set = models.ManyToManyField(
"M2MComplexCircular1A", through="M2MCircular1ThroughCA"
)
class M2MCircular1ThroughAB(BaseNKModel):
a = models.ForeignKey(M2MComplexCircular1A, models.CASCADE)
b = models.ForeignKey(M2MComplexCircular1B, models.CASCADE)
class M2MCircular1ThroughBC(BaseNKModel):
b = models.ForeignKey(M2MComplexCircular1B, models.CASCADE)
c = models.ForeignKey(M2MComplexCircular1C, models.CASCADE)
class M2MCircular1ThroughCA(BaseNKModel):
c = models.ForeignKey(M2MComplexCircular1C, models.CASCADE)
a = models.ForeignKey(M2MComplexCircular1A, models.CASCADE)
class M2MComplexCircular2A(BaseNKModel):
b_set = models.ManyToManyField(
"M2MComplexCircular2B", through="M2MCircular2ThroughAB"
)
class M2MComplexCircular2B(BaseNKModel):
def natural_key(self):
return (self.data,)
# Fake the dependency for a circularity
natural_key.dependencies = ["fixtures_regress.M2MComplexCircular2A"]
class M2MCircular2ThroughAB(BaseNKModel):
a = models.ForeignKey(M2MComplexCircular2A, models.CASCADE)
b = models.ForeignKey(M2MComplexCircular2B, models.CASCADE)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/fixtures_regress/__init__.py | tests/fixtures_regress/__init__.py | python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false | |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/fixtures_regress/tests.py | tests/fixtures_regress/tests.py | # Unittests for fixtures.
import json
import os
import unittest
from io import StringIO
from pathlib import Path
from django.core import management, serializers
from django.core.exceptions import ImproperlyConfigured
from django.core.serializers.base import DeserializationError
from django.db import IntegrityError, transaction
from django.db.models import signals
from django.test import (
TestCase,
TransactionTestCase,
override_settings,
skipIfDBFeature,
skipUnlessDBFeature,
)
from .models import (
Absolute,
Animal,
Article,
Book,
Child,
Circle1,
Circle2,
Circle3,
ExternalDependency,
M2MCircular1ThroughAB,
M2MCircular1ThroughBC,
M2MCircular1ThroughCA,
M2MCircular2ThroughAB,
M2MComplexA,
M2MComplexB,
M2MComplexCircular1A,
M2MComplexCircular1B,
M2MComplexCircular1C,
M2MComplexCircular2A,
M2MComplexCircular2B,
M2MSimpleA,
M2MSimpleB,
M2MSimpleCircularA,
M2MSimpleCircularB,
M2MThroughAB,
NaturalKeyWithFKDependency,
NKChild,
Parent,
Person,
RefToNKChild,
Store,
Stuff,
Thingy,
Widget,
)
try:
import yaml # NOQA
HAS_YAML = True
except ImportError:
HAS_YAML = False
_cur_dir = os.path.dirname(os.path.abspath(__file__))
class TestFixtures(TestCase):
def animal_pre_save_check(self, signal, sender, instance, **kwargs):
self.pre_save_checks.append(
(
"Count = %s (%s)" % (instance.count, type(instance.count)),
"Weight = %s (%s)" % (instance.weight, type(instance.weight)),
)
)
def test_duplicate_pk(self):
"""
This is a regression test for ticket #3790.
"""
# Load a fixture that uses PK=1
management.call_command(
"loaddata",
"sequence",
verbosity=0,
)
# Create a new animal. Without a sequence reset, this new object
# will take a PK of 1 (on Postgres), and the save will fail.
animal = Animal(
name="Platypus",
latin_name="Ornithorhynchus anatinus",
count=2,
weight=2.2,
)
animal.save()
self.assertGreater(animal.id, 1)
def test_loaddata_not_found_fields_not_ignore(self):
"""
Test for ticket #9279 -- Error is raised for entries in
the serialized data for fields that have been removed
from the database when not ignored.
"""
test_fixtures = [
"sequence_extra",
"sequence_extra_jsonl",
]
if HAS_YAML:
test_fixtures.append("sequence_extra_yaml")
for fixture_file in test_fixtures:
with (
self.subTest(fixture_file=fixture_file),
self.assertRaises(DeserializationError),
):
management.call_command(
"loaddata",
fixture_file,
verbosity=0,
)
def test_loaddata_not_found_fields_ignore(self):
"""
Test for ticket #9279 -- Ignores entries in
the serialized data for fields that have been removed
from the database.
"""
management.call_command(
"loaddata",
"sequence_extra",
ignore=True,
verbosity=0,
)
self.assertEqual(Animal.specimens.all()[0].name, "Lion")
def test_loaddata_not_found_fields_ignore_xml(self):
"""
Test for ticket #19998 -- Ignore entries in the XML serialized data
for fields that have been removed from the model definition.
"""
management.call_command(
"loaddata",
"sequence_extra_xml",
ignore=True,
verbosity=0,
)
self.assertEqual(Animal.specimens.all()[0].name, "Wolf")
def test_loaddata_not_found_fields_ignore_jsonl(self):
management.call_command(
"loaddata",
"sequence_extra_jsonl",
ignore=True,
verbosity=0,
)
self.assertEqual(Animal.specimens.all()[0].name, "Eagle")
@unittest.skipUnless(HAS_YAML, "No yaml library detected")
def test_loaddata_not_found_fields_ignore_yaml(self):
management.call_command(
"loaddata",
"sequence_extra_yaml",
ignore=True,
verbosity=0,
)
self.assertEqual(Animal.specimens.all()[0].name, "Cat")
def test_loaddata_empty_lines_jsonl(self):
management.call_command(
"loaddata",
"sequence_empty_lines_jsonl.jsonl",
verbosity=0,
)
self.assertEqual(Animal.specimens.all()[0].name, "Eagle")
@skipIfDBFeature("interprets_empty_strings_as_nulls")
def test_pretty_print_xml(self):
"""
Regression test for ticket #4558 -- pretty printing of XML fixtures
doesn't affect parsing of None values.
"""
# Load a pretty-printed XML fixture with Nulls.
management.call_command(
"loaddata",
"pretty.xml",
verbosity=0,
)
self.assertIsNone(Stuff.objects.all()[0].name)
self.assertIsNone(Stuff.objects.all()[0].owner)
@skipUnlessDBFeature("interprets_empty_strings_as_nulls")
def test_pretty_print_xml_empty_strings(self):
"""
Regression test for ticket #4558 -- pretty printing of XML fixtures
doesn't affect parsing of None values.
"""
# Load a pretty-printed XML fixture with Nulls.
management.call_command(
"loaddata",
"pretty.xml",
verbosity=0,
)
self.assertEqual(Stuff.objects.all()[0].name, "")
self.assertIsNone(Stuff.objects.all()[0].owner)
def test_absolute_path(self):
"""
Regression test for ticket #6436 --
os.path.join will throw away the initial parts of a path if it
encounters an absolute path.
This means that if a fixture is specified as an absolute path,
we need to make sure we don't discover the absolute path in every
fixture directory.
"""
load_absolute_path = os.path.join(
os.path.dirname(__file__), "fixtures", "absolute.json"
)
management.call_command(
"loaddata",
load_absolute_path,
verbosity=0,
)
self.assertEqual(Absolute.objects.count(), 1)
def test_relative_path(self, path=["fixtures", "absolute.json"]):
relative_path = os.path.join(*path)
cwd = os.getcwd()
try:
os.chdir(_cur_dir)
management.call_command(
"loaddata",
relative_path,
verbosity=0,
)
finally:
os.chdir(cwd)
self.assertEqual(Absolute.objects.count(), 1)
@override_settings(FIXTURE_DIRS=[os.path.join(_cur_dir, "fixtures_1")])
def test_relative_path_in_fixture_dirs(self):
self.test_relative_path(path=["inner", "absolute.json"])
def test_path_containing_dots(self):
management.call_command(
"loaddata",
"path.containing.dots.json",
verbosity=0,
)
self.assertEqual(Absolute.objects.count(), 1)
def test_unknown_format(self):
"""
Test for ticket #4371 -- Loading data of an unknown format should fail
Validate that error conditions are caught correctly
"""
msg = (
"Problem installing fixture 'bad_fix.ture1': unkn is not a known "
"serialization format."
)
with self.assertRaisesMessage(management.CommandError, msg):
management.call_command(
"loaddata",
"bad_fix.ture1.unkn",
verbosity=0,
)
@override_settings(SERIALIZATION_MODULES={"unkn": "unexistent.path"})
def test_unimportable_serializer(self):
"""
Failing serializer import raises the proper error
"""
with self.assertRaisesMessage(ImportError, "No module named 'unexistent'"):
management.call_command(
"loaddata",
"bad_fix.ture1.unkn",
verbosity=0,
)
def test_invalid_data(self):
"""
Test for ticket #4371 -- Loading a fixture file with invalid data
using explicit filename.
Test for ticket #18213 -- warning conditions are caught correctly
"""
msg = "No fixture data found for 'bad_fixture2'. (File format may be invalid.)"
with self.assertWarnsMessage(RuntimeWarning, msg):
management.call_command(
"loaddata",
"bad_fixture2.xml",
verbosity=0,
)
def test_invalid_data_no_ext(self):
"""
Test for ticket #4371 -- Loading a fixture file with invalid data
without file extension.
Test for ticket #18213 -- warning conditions are caught correctly
"""
msg = "No fixture data found for 'bad_fixture2'. (File format may be invalid.)"
with self.assertWarnsMessage(RuntimeWarning, msg):
management.call_command(
"loaddata",
"bad_fixture2",
verbosity=0,
)
def test_empty(self):
"""
Test for ticket #18213 -- Loading a fixture file with no data output a
warning. Previously empty fixture raises an error exception, see ticket
#4371.
"""
msg = "No fixture data found for 'empty'. (File format may be invalid.)"
with self.assertWarnsMessage(RuntimeWarning, msg):
management.call_command(
"loaddata",
"empty",
verbosity=0,
)
def test_error_message(self):
"""
Regression for #9011 - error message is correct.
Change from error to warning for ticket #18213.
"""
msg = "No fixture data found for 'bad_fixture2'. (File format may be invalid.)"
with self.assertWarnsMessage(RuntimeWarning, msg):
management.call_command(
"loaddata",
"bad_fixture2",
"animal",
verbosity=0,
)
def test_pg_sequence_resetting_checks(self):
"""
Test for ticket #7565 -- PostgreSQL sequence resetting checks shouldn't
ascend to parent models when inheritance is used
(since they are treated individually).
"""
management.call_command(
"loaddata",
"model-inheritance.json",
verbosity=0,
)
self.assertEqual(Parent.objects.all()[0].id, 1)
self.assertEqual(Child.objects.all()[0].id, 1)
def test_close_connection_after_loaddata(self):
"""
Test for ticket #7572 -- MySQL has a problem if the same connection is
used to create tables, load data, and then query over that data.
To compensate, we close the connection after running loaddata.
This ensures that a new connection is opened when test queries are
issued.
"""
management.call_command(
"loaddata",
"big-fixture.json",
verbosity=0,
)
articles = Article.objects.exclude(id=9)
self.assertEqual(
list(articles.values_list("id", flat=True)), [1, 2, 3, 4, 5, 6, 7, 8]
)
# Just for good measure, run the same query again.
# Under the influence of ticket #7572, this will
# give a different result to the previous call.
self.assertEqual(
list(articles.values_list("id", flat=True)), [1, 2, 3, 4, 5, 6, 7, 8]
)
def test_field_value_coerce(self):
"""
Test for tickets #8298, #9942 - Field values should be coerced into the
correct type by the deserializer, not as part of the database write.
"""
self.pre_save_checks = []
signals.pre_save.connect(self.animal_pre_save_check)
try:
management.call_command(
"loaddata",
"animal.xml",
verbosity=0,
)
self.assertEqual(
self.pre_save_checks,
[("Count = 42 (<class 'int'>)", "Weight = 1.2 (<class 'float'>)")],
)
finally:
signals.pre_save.disconnect(self.animal_pre_save_check)
def test_dumpdata_uses_default_manager(self):
"""
Regression for #11286
Dumpdata honors the default manager. Dump the current contents of
the database as a JSON fixture
"""
management.call_command(
"loaddata",
"animal.xml",
verbosity=0,
)
management.call_command(
"loaddata",
"sequence.json",
verbosity=0,
)
animal = Animal(
name="Platypus",
latin_name="Ornithorhynchus anatinus",
count=2,
weight=2.2,
)
animal.save()
out = StringIO()
management.call_command(
"dumpdata",
"fixtures_regress.animal",
format="json",
stdout=out,
)
# Output order isn't guaranteed, so check for parts
data = out.getvalue()
animals_data = sorted(
[
{
"pk": 1,
"model": "fixtures_regress.animal",
"fields": {
"count": 3,
"weight": 1.2,
"name": "Lion",
"latin_name": "Panthera leo",
},
},
{
"pk": 10,
"model": "fixtures_regress.animal",
"fields": {
"count": 42,
"weight": 1.2,
"name": "Emu",
"latin_name": "Dromaius novaehollandiae",
},
},
{
"pk": animal.pk,
"model": "fixtures_regress.animal",
"fields": {
"count": 2,
"weight": 2.2,
"name": "Platypus",
"latin_name": "Ornithorhynchus anatinus",
},
},
],
key=lambda x: x["pk"],
)
data = sorted(json.loads(data), key=lambda x: x["pk"])
self.maxDiff = 1024
self.assertEqual(data, animals_data)
def test_proxy_model_included(self):
"""
Regression for #11428 - Proxy models aren't included when you dumpdata
"""
out = StringIO()
# Create an instance of the concrete class
widget = Widget.objects.create(name="grommet")
management.call_command(
"dumpdata",
"fixtures_regress.widget",
"fixtures_regress.widgetproxy",
format="json",
stdout=out,
)
self.assertJSONEqual(
out.getvalue(),
'[{"pk": %d, "model": "fixtures_regress.widget", '
'"fields": {"name": "grommet"}}]' % widget.pk,
)
@skipUnlessDBFeature("supports_forward_references")
def test_loaddata_works_when_fixture_has_forward_refs(self):
"""
Forward references cause fixtures not to load in MySQL (InnoDB).
"""
management.call_command(
"loaddata",
"forward_ref.json",
verbosity=0,
)
self.assertEqual(Book.objects.all()[0].id, 1)
self.assertEqual(Person.objects.all()[0].id, 4)
def test_loaddata_raises_error_when_fixture_has_invalid_foreign_key(self):
"""
Data with nonexistent child key references raises error.
"""
with self.assertRaisesMessage(IntegrityError, "Problem installing fixture"):
management.call_command(
"loaddata",
"forward_ref_bad_data.json",
verbosity=0,
)
@skipUnlessDBFeature("supports_forward_references")
@override_settings(
FIXTURE_DIRS=[
os.path.join(_cur_dir, "fixtures_1"),
os.path.join(_cur_dir, "fixtures_2"),
]
)
def test_loaddata_forward_refs_split_fixtures(self):
"""
Regression for #17530 - should be able to cope with forward references
when the fixtures are not in the same files or directories.
"""
management.call_command(
"loaddata",
"forward_ref_1.json",
"forward_ref_2.json",
verbosity=0,
)
self.assertEqual(Book.objects.all()[0].id, 1)
self.assertEqual(Person.objects.all()[0].id, 4)
def test_loaddata_no_fixture_specified(self):
"""
Error is quickly reported when no fixtures is provided in the command
line.
"""
msg = (
"No database fixture specified. Please provide the path of at least one "
"fixture in the command line."
)
with self.assertRaisesMessage(management.CommandError, msg):
management.call_command(
"loaddata",
verbosity=0,
)
def test_ticket_20820(self):
"""
Regression for ticket #20820 -- loaddata on a model that inherits
from a model with a M2M shouldn't blow up.
"""
management.call_command(
"loaddata",
"special-article.json",
verbosity=0,
)
def test_ticket_22421(self):
"""
Regression for ticket #22421 -- loaddata on a model that inherits from
a grand-parent model with a M2M but via an abstract parent shouldn't
blow up.
"""
management.call_command(
"loaddata",
"feature.json",
verbosity=0,
)
def test_loaddata_with_m2m_to_self(self):
"""
Regression test for ticket #17946.
"""
management.call_command(
"loaddata",
"m2mtoself.json",
verbosity=0,
)
@override_settings(
FIXTURE_DIRS=[
os.path.join(_cur_dir, "fixtures_1"),
os.path.join(_cur_dir, "fixtures_1"),
]
)
def test_fixture_dirs_with_duplicates(self):
"""
settings.FIXTURE_DIRS cannot contain duplicates in order to avoid
repeated fixture loading.
"""
with self.assertRaisesMessage(
ImproperlyConfigured, "settings.FIXTURE_DIRS contains duplicates."
):
management.call_command("loaddata", "absolute.json", verbosity=0)
@override_settings(FIXTURE_DIRS=[os.path.join(_cur_dir, "fixtures")])
def test_fixture_dirs_with_default_fixture_path(self):
"""
settings.FIXTURE_DIRS cannot contain a default fixtures directory
for application (app/fixtures) in order to avoid repeated fixture
loading.
"""
msg = (
"'%s' is a default fixture directory for the '%s' app "
"and cannot be listed in settings.FIXTURE_DIRS."
% (os.path.join(_cur_dir, "fixtures"), "fixtures_regress")
)
with self.assertRaisesMessage(ImproperlyConfigured, msg):
management.call_command("loaddata", "absolute.json", verbosity=0)
@override_settings(FIXTURE_DIRS=[Path(_cur_dir) / "fixtures"])
def test_fixture_dirs_with_default_fixture_path_as_pathlib(self):
"""
settings.FIXTURE_DIRS cannot contain a default fixtures directory
for application (app/fixtures) in order to avoid repeated fixture
loading.
"""
msg = (
"'%s' is a default fixture directory for the '%s' app "
"and cannot be listed in settings.FIXTURE_DIRS."
% (os.path.join(_cur_dir, "fixtures"), "fixtures_regress")
)
with self.assertRaisesMessage(ImproperlyConfigured, msg):
management.call_command("loaddata", "absolute.json", verbosity=0)
@override_settings(
FIXTURE_DIRS=[
os.path.join(_cur_dir, "fixtures_1"),
os.path.join(_cur_dir, "fixtures_2"),
]
)
def test_loaddata_with_valid_fixture_dirs(self):
management.call_command(
"loaddata",
"absolute.json",
verbosity=0,
)
@override_settings(FIXTURE_DIRS=[Path(_cur_dir) / "fixtures_1"])
def test_fixtures_dir_pathlib(self):
management.call_command("loaddata", "inner/absolute.json", verbosity=0)
self.assertQuerySetEqual(Absolute.objects.all(), [1], transform=lambda o: o.pk)
class NaturalKeyFixtureTests(TestCase):
def test_nk_deserialize(self):
"""
Test for ticket #13030 - Python based parser version
natural keys deserialize with fk to inheriting model
"""
management.call_command(
"loaddata",
"model-inheritance.json",
verbosity=0,
)
management.call_command(
"loaddata",
"nk-inheritance.json",
verbosity=0,
)
self.assertEqual(NKChild.objects.get(pk=1).data, "apple")
self.assertEqual(RefToNKChild.objects.get(pk=1).nk_fk.data, "apple")
def test_nk_deserialize_xml(self):
"""
Test for ticket #13030 - XML version
natural keys deserialize with fk to inheriting model
"""
management.call_command(
"loaddata",
"model-inheritance.json",
verbosity=0,
)
management.call_command(
"loaddata",
"nk-inheritance.json",
verbosity=0,
)
management.call_command(
"loaddata",
"nk-inheritance2.xml",
verbosity=0,
)
self.assertEqual(NKChild.objects.get(pk=2).data, "banana")
self.assertEqual(RefToNKChild.objects.get(pk=2).nk_fk.data, "apple")
def test_nk_on_serialize(self):
"""
Natural key requirements are taken into account when serializing
models.
"""
management.call_command(
"loaddata",
"forward_ref_lookup.json",
verbosity=0,
)
out = StringIO()
management.call_command(
"dumpdata",
"fixtures_regress.book",
"fixtures_regress.person",
"fixtures_regress.store",
verbosity=0,
format="json",
use_natural_foreign_keys=True,
use_natural_primary_keys=True,
stdout=out,
)
self.assertJSONEqual(
out.getvalue(),
"""
[{"fields": {"main": null, "name": "Amazon"},
"model": "fixtures_regress.store"},
{"fields": {"main": null, "name": "Borders"},
"model": "fixtures_regress.store"},
{"fields": {"name": "Neal Stephenson"}, "model": "fixtures_regress.person"},
{"pk": 1, "model": "fixtures_regress.book",
"fields": {"stores": [["Amazon"], ["Borders"]],
"name": "Cryptonomicon", "author": ["Neal Stephenson"]}}]
""",
)
def test_dependency_sorting(self):
"""
It doesn't matter what order you mention the models, Store *must* be
serialized before then Person, and both must be serialized before Book.
"""
sorted_deps = serializers.sort_dependencies(
[("fixtures_regress", [Book, Person, Store])]
)
self.assertEqual(sorted_deps, [Store, Person, Book])
def test_dependency_sorting_2(self):
sorted_deps = serializers.sort_dependencies(
[("fixtures_regress", [Book, Store, Person])]
)
self.assertEqual(sorted_deps, [Store, Person, Book])
def test_dependency_sorting_3(self):
sorted_deps = serializers.sort_dependencies(
[("fixtures_regress", [Store, Book, Person])]
)
self.assertEqual(sorted_deps, [Store, Person, Book])
def test_dependency_sorting_4(self):
sorted_deps = serializers.sort_dependencies(
[("fixtures_regress", [Store, Person, Book])]
)
self.assertEqual(sorted_deps, [Store, Person, Book])
def test_dependency_sorting_5(self):
sorted_deps = serializers.sort_dependencies(
[("fixtures_regress", [Person, Book, Store])]
)
self.assertEqual(sorted_deps, [Store, Person, Book])
def test_dependency_sorting_6(self):
sorted_deps = serializers.sort_dependencies(
[("fixtures_regress", [Person, Store, Book])]
)
self.assertEqual(sorted_deps, [Store, Person, Book])
def test_dependency_sorting_dangling(self):
sorted_deps = serializers.sort_dependencies(
[("fixtures_regress", [Person, Circle1, Store, Book])]
)
self.assertEqual(sorted_deps, [Circle1, Store, Person, Book])
def test_dependency_sorting_tight_circular(self):
with self.assertRaisesMessage(
RuntimeError,
"Can't resolve dependencies for fixtures_regress.Circle1, "
"fixtures_regress.Circle2 in serialized app list.",
):
serializers.sort_dependencies(
[("fixtures_regress", [Person, Circle2, Circle1, Store, Book])]
)
def test_dependency_sorting_tight_circular_2(self):
with self.assertRaisesMessage(
RuntimeError,
"Can't resolve dependencies for fixtures_regress.Circle1, "
"fixtures_regress.Circle2 in serialized app list.",
):
serializers.sort_dependencies(
[("fixtures_regress", [Circle1, Book, Circle2])]
)
def test_dependency_self_referential(self):
with self.assertRaisesMessage(
RuntimeError,
"Can't resolve dependencies for fixtures_regress.Circle3 in "
"serialized app list.",
):
serializers.sort_dependencies([("fixtures_regress", [Book, Circle3])])
def test_dependency_sorting_long(self):
with self.assertRaisesMessage(
RuntimeError,
"Can't resolve dependencies for fixtures_regress.Circle1, "
"fixtures_regress.Circle2, fixtures_regress.Circle3 in serialized "
"app list.",
):
serializers.sort_dependencies(
[("fixtures_regress", [Person, Circle2, Circle1, Circle3, Store, Book])]
)
def test_dependency_sorting_normal(self):
sorted_deps = serializers.sort_dependencies(
[("fixtures_regress", [Person, ExternalDependency, Book])]
)
self.assertEqual(sorted_deps, [Person, Book, ExternalDependency])
def test_normal_pk(self):
"""
Normal primary keys work on a model with natural key capabilities.
"""
management.call_command(
"loaddata",
"non_natural_1.json",
verbosity=0,
)
management.call_command(
"loaddata",
"forward_ref_lookup.json",
verbosity=0,
)
management.call_command(
"loaddata",
"non_natural_2.xml",
verbosity=0,
)
books = Book.objects.all()
self.assertQuerySetEqual(
books,
[
"<Book: Cryptonomicon by Neal Stephenson (available at Amazon, "
"Borders)>",
"<Book: Ender's Game by Orson Scott Card (available at Collins "
"Bookstore)>",
"<Book: Permutation City by Greg Egan (available at Angus and "
"Robertson)>",
],
transform=repr,
)
class NaturalKeyFixtureOnOtherDatabaseTests(TestCase):
databases = {"other"}
def test_natural_key_dependencies(self):
"""
Natural keys with foreign keys in dependencies works in a multiple
database setup.
"""
management.call_command(
"loaddata",
"nk_with_foreign_key.json",
database="other",
verbosity=0,
)
obj = NaturalKeyWithFKDependency.objects.using("other").get()
self.assertEqual(obj.name, "The Lord of the Rings")
self.assertEqual(obj.author.name, "J.R.R. Tolkien")
class M2MNaturalKeyFixtureTests(TestCase):
"""Tests for ticket #14426."""
def test_dependency_sorting_m2m_simple(self):
"""
M2M relations without explicit through models SHOULD count as
dependencies
Regression test for bugs that could be caused by flawed fixes to
#14226, namely if M2M checks are removed from sort_dependencies
altogether.
"""
sorted_deps = serializers.sort_dependencies(
[("fixtures_regress", [M2MSimpleA, M2MSimpleB])]
)
self.assertEqual(sorted_deps, [M2MSimpleB, M2MSimpleA])
def test_dependency_sorting_m2m_simple_circular(self):
"""
Resolving circular M2M relations without explicit through models should
fail loudly
"""
with self.assertRaisesMessage(
RuntimeError,
"Can't resolve dependencies for fixtures_regress.M2MSimpleCircularA, "
"fixtures_regress.M2MSimpleCircularB in serialized app list.",
):
serializers.sort_dependencies(
[("fixtures_regress", [M2MSimpleCircularA, M2MSimpleCircularB])]
)
def test_dependency_sorting_m2m_complex(self):
"""
M2M relations with explicit through models should NOT count as
dependencies. The through model itself will have dependencies, though.
"""
sorted_deps = serializers.sort_dependencies(
[("fixtures_regress", [M2MComplexA, M2MComplexB, M2MThroughAB])]
)
# Order between M2MComplexA and M2MComplexB doesn't matter. The through
# model has dependencies to them though, so it should come last.
self.assertEqual(sorted_deps[-1], M2MThroughAB)
def test_dependency_sorting_m2m_complex_circular_1(self):
"""
Circular M2M relations with explicit through models should be
serializable
"""
A, B, C, AtoB, BtoC, CtoA = (
M2MComplexCircular1A,
M2MComplexCircular1B,
M2MComplexCircular1C,
M2MCircular1ThroughAB,
M2MCircular1ThroughBC,
M2MCircular1ThroughCA,
)
sorted_deps = serializers.sort_dependencies(
[("fixtures_regress", [A, B, C, AtoB, BtoC, CtoA])]
)
# The dependency sorting should not result in an error, and the
# through model should have dependencies to the other models and as
# such come last in the list.
self.assertEqual(sorted_deps[:3], [A, B, C])
self.assertEqual(sorted_deps[3:], [AtoB, BtoC, CtoA])
def test_dependency_sorting_m2m_complex_circular_2(self):
"""
Circular M2M relations with explicit through models should be
serializable This test tests the circularity with explicit
natural_key.dependencies
"""
sorted_deps = serializers.sort_dependencies(
[
(
"fixtures_regress",
[M2MComplexCircular2A, M2MComplexCircular2B, M2MCircular2ThroughAB],
)
]
)
self.assertEqual(sorted_deps[:2], [M2MComplexCircular2A, M2MComplexCircular2B])
self.assertEqual(sorted_deps[2:], [M2MCircular2ThroughAB])
def test_dump_and_load_m2m_simple(self):
"""
Test serializing and deserializing back models with simple M2M
relations
"""
a = M2MSimpleA.objects.create(data="a")
b1 = M2MSimpleB.objects.create(data="b1")
b2 = M2MSimpleB.objects.create(data="b2")
a.b_set.add(b1)
a.b_set.add(b2)
out = StringIO()
management.call_command(
"dumpdata",
"fixtures_regress.M2MSimpleA",
"fixtures_regress.M2MSimpleB",
use_natural_foreign_keys=True,
stdout=out,
)
for model in [M2MSimpleA, M2MSimpleB]:
model.objects.all().delete()
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | true |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/cache/failing_cache.py | tests/cache/failing_cache.py | from django.core.cache.backends.locmem import LocMemCache
class CacheClass(LocMemCache):
def set(self, *args, **kwargs):
raise Exception("Faked exception saving to cache")
async def aset(self, *args, **kwargs):
raise Exception("Faked exception saving to cache")
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/cache/models.py | tests/cache/models.py | from django.db import models
from django.utils import timezone
def expensive_calculation():
expensive_calculation.num_runs += 1
return timezone.now()
class Poll(models.Model):
question = models.CharField(max_length=200)
answer = models.CharField(max_length=200)
pub_date = models.DateTimeField("date published", default=expensive_calculation)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/cache/closeable_cache.py | tests/cache/closeable_cache.py | from django.core.cache.backends.locmem import LocMemCache
class CloseHookMixin:
closed = False
def close(self, **kwargs):
self.closed = True
class CacheClass(CloseHookMixin, LocMemCache):
pass
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/cache/liberal_backend.py | tests/cache/liberal_backend.py | from django.core.cache.backends.locmem import LocMemCache
class LiberalKeyValidationMixin:
def validate_key(self, key):
pass
class CacheClass(LiberalKeyValidationMixin, LocMemCache):
pass
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/cache/__init__.py | tests/cache/__init__.py | python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false | |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/cache/tests.py | tests/cache/tests.py | # Unit tests for cache framework
# Uses whatever cache backend is set in the test settings file.
import copy
import io
import os
import pickle
import re
import shutil
import sys
import tempfile
import threading
import time
import unittest
from functools import wraps
from pathlib import Path
from unittest import mock, skipIf
from django.conf import settings
from django.core import management, signals
from django.core.cache import (
DEFAULT_CACHE_ALIAS,
CacheHandler,
CacheKeyWarning,
InvalidCacheKey,
cache,
caches,
)
from django.core.cache.backends.base import BaseCache, InvalidCacheBackendError
from django.core.cache.backends.redis import RedisCacheClient
from django.core.cache.utils import make_template_fragment_key
from django.db import close_old_connections, connection, connections
from django.db.backends.utils import CursorWrapper
from django.http import (
HttpRequest,
HttpResponse,
HttpResponseNotModified,
StreamingHttpResponse,
)
from django.middleware.cache import (
CacheMiddleware,
FetchFromCacheMiddleware,
UpdateCacheMiddleware,
)
from django.middleware.csrf import CsrfViewMiddleware
from django.template import engines
from django.template.context_processors import csrf
from django.template.response import TemplateResponse
from django.test import (
RequestFactory,
SimpleTestCase,
TestCase,
TransactionTestCase,
override_settings,
)
from django.test.signals import setting_changed
from django.test.utils import CaptureQueriesContext
from django.utils import timezone, translation
from django.utils.cache import (
get_cache_key,
learn_cache_key,
patch_cache_control,
patch_vary_headers,
)
from django.views.decorators.cache import cache_control, cache_page
from .models import Poll, expensive_calculation
# functions/classes for complex data type tests
def f():
return 42
class C:
def m(n):
return 24
class Unpicklable:
def __getstate__(self):
raise pickle.PickleError()
def empty_response(request):
return HttpResponse()
KEY_ERRORS_WITH_MEMCACHED_MSG = (
"Cache key contains characters that will cause errors if used with memcached: %r"
)
def retry(retries=3, delay=1):
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
attempts = 0
while attempts < retries:
try:
return func(*args, **kwargs)
except AssertionError:
attempts += 1
if attempts >= retries:
raise
time.sleep(delay)
return wrapper
return decorator
@override_settings(
CACHES={
"default": {
"BACKEND": "django.core.cache.backends.dummy.DummyCache",
}
}
)
class DummyCacheTests(SimpleTestCase):
# The Dummy cache backend doesn't really behave like a test backend,
# so it has its own test case.
def test_simple(self):
"Dummy cache backend ignores cache set calls"
cache.set("key", "value")
self.assertIsNone(cache.get("key"))
def test_add(self):
"Add doesn't do anything in dummy cache backend"
self.assertIs(cache.add("addkey1", "value"), True)
self.assertIs(cache.add("addkey1", "newvalue"), True)
self.assertIsNone(cache.get("addkey1"))
def test_non_existent(self):
"Nonexistent keys aren't found in the dummy cache backend"
self.assertIsNone(cache.get("does_not_exist"))
self.assertEqual(cache.get("does_not_exist", "bang!"), "bang!")
def test_get_many(self):
"get_many returns nothing for the dummy cache backend"
cache.set_many({"a": "a", "b": "b", "c": "c", "d": "d"})
self.assertEqual(cache.get_many(["a", "c", "d"]), {})
self.assertEqual(cache.get_many(["a", "b", "e"]), {})
def test_get_many_invalid_key(self):
msg = KEY_ERRORS_WITH_MEMCACHED_MSG % ":1:key with spaces"
with self.assertWarnsMessage(CacheKeyWarning, msg):
cache.get_many(["key with spaces"])
def test_delete(self):
"Cache deletion is transparently ignored on the dummy cache backend"
cache.set_many({"key1": "spam", "key2": "eggs"})
self.assertIsNone(cache.get("key1"))
self.assertIs(cache.delete("key1"), False)
self.assertIsNone(cache.get("key1"))
self.assertIsNone(cache.get("key2"))
def test_has_key(self):
"""
The has_key method doesn't ever return True for the dummy cache backend
"""
cache.set("hello1", "goodbye1")
self.assertIs(cache.has_key("hello1"), False)
self.assertIs(cache.has_key("goodbye1"), False)
def test_in(self):
"The in operator doesn't ever return True for the dummy cache backend"
cache.set("hello2", "goodbye2")
self.assertNotIn("hello2", cache)
self.assertNotIn("goodbye2", cache)
def test_incr(self):
"Dummy cache values can't be incremented"
cache.set("answer", 42)
with self.assertRaises(ValueError):
cache.incr("answer")
with self.assertRaises(ValueError):
cache.incr("does_not_exist")
with self.assertRaises(ValueError):
cache.incr("does_not_exist", -1)
def test_decr(self):
"Dummy cache values can't be decremented"
cache.set("answer", 42)
with self.assertRaises(ValueError):
cache.decr("answer")
with self.assertRaises(ValueError):
cache.decr("does_not_exist")
with self.assertRaises(ValueError):
cache.decr("does_not_exist", -1)
def test_touch(self):
"""Dummy cache can't do touch()."""
self.assertIs(cache.touch("whatever"), False)
def test_data_types(self):
"All data types are ignored equally by the dummy cache"
tests = {
"string": "this is a string",
"int": 42,
"bool": True,
"list": [1, 2, 3, 4],
"tuple": (1, 2, 3, 4),
"dict": {"A": 1, "B": 2},
"function": f,
"class": C,
}
for key, value in tests.items():
with self.subTest(key=key):
cache.set(key, value)
self.assertIsNone(cache.get(key))
def test_expiration(self):
"Expiration has no effect on the dummy cache"
cache.set("expire1", "very quickly", 1)
cache.set("expire2", "very quickly", 1)
cache.set("expire3", "very quickly", 1)
time.sleep(2)
self.assertIsNone(cache.get("expire1"))
self.assertIs(cache.add("expire2", "newvalue"), True)
self.assertIsNone(cache.get("expire2"))
self.assertIs(cache.has_key("expire3"), False)
def test_unicode(self):
"Unicode values are ignored by the dummy cache"
stuff = {
"ascii": "ascii_value",
"unicode_ascii": "Iñtërnâtiônàlizætiøn1",
"Iñtërnâtiônàlizætiøn": "Iñtërnâtiônàlizætiøn2",
"ascii2": {"x": 1},
}
for key, value in stuff.items():
with self.subTest(key=key):
cache.set(key, value)
self.assertIsNone(cache.get(key))
def test_set_many(self):
"set_many does nothing for the dummy cache backend"
self.assertEqual(cache.set_many({"a": 1, "b": 2}), [])
self.assertEqual(cache.set_many({"a": 1, "b": 2}, timeout=2, version="1"), [])
def test_set_many_invalid_key(self):
msg = KEY_ERRORS_WITH_MEMCACHED_MSG % ":1:key with spaces"
with self.assertWarnsMessage(CacheKeyWarning, msg):
cache.set_many({"key with spaces": "foo"})
def test_delete_many(self):
"delete_many does nothing for the dummy cache backend"
cache.delete_many(["a", "b"])
def test_delete_many_invalid_key(self):
msg = KEY_ERRORS_WITH_MEMCACHED_MSG % ":1:key with spaces"
with self.assertWarnsMessage(CacheKeyWarning, msg):
cache.delete_many(["key with spaces"])
def test_clear(self):
"clear does nothing for the dummy cache backend"
cache.clear()
def test_incr_version(self):
"Dummy cache versions can't be incremented"
cache.set("answer", 42)
with self.assertRaises(ValueError):
cache.incr_version("answer")
with self.assertRaises(ValueError):
cache.incr_version("does_not_exist")
def test_decr_version(self):
"Dummy cache versions can't be decremented"
cache.set("answer", 42)
with self.assertRaises(ValueError):
cache.decr_version("answer")
with self.assertRaises(ValueError):
cache.decr_version("does_not_exist")
def test_get_or_set(self):
self.assertEqual(cache.get_or_set("mykey", "default"), "default")
self.assertIsNone(cache.get_or_set("mykey", None))
def test_get_or_set_callable(self):
def my_callable():
return "default"
self.assertEqual(cache.get_or_set("mykey", my_callable), "default")
self.assertEqual(cache.get_or_set("mykey", my_callable()), "default")
def custom_key_func(key, key_prefix, version):
"A customized cache key function"
return "CUSTOM-" + "-".join([key_prefix, str(version), key])
_caches_setting_base = {
"default": {},
"prefix": {"KEY_PREFIX": "cacheprefix{}".format(os.getpid())},
"v2": {"VERSION": 2},
"custom_key": {"KEY_FUNCTION": custom_key_func},
"custom_key2": {"KEY_FUNCTION": "cache.tests.custom_key_func"},
"cull": {"OPTIONS": {"MAX_ENTRIES": 30}},
"zero_cull": {"OPTIONS": {"CULL_FREQUENCY": 0, "MAX_ENTRIES": 30}},
}
def caches_setting_for_tests(base=None, exclude=None, **params):
# `base` is used to pull in the memcached config from the original
# settings, `exclude` is a set of cache names denoting which
# `_caches_setting_base` keys should be omitted. `params` are test specific
# overrides and `_caches_settings_base` is the base config for the tests.
# This results in the following search order:
# params -> _caches_setting_base -> base
base = base or {}
exclude = exclude or set()
setting = {k: base.copy() for k in _caches_setting_base if k not in exclude}
for key, cache_params in setting.items():
cache_params.update(_caches_setting_base[key])
cache_params.update(params)
return setting
class BaseCacheTests:
# A common set of tests to apply to all cache backends
factory = RequestFactory()
# Some clients raise custom exceptions when .incr() or .decr() are called
# with a non-integer value.
incr_decr_type_error = TypeError
def tearDown(self):
cache.clear()
def test_simple(self):
# Simple cache set/get works
cache.set("key", "value")
self.assertEqual(cache.get("key"), "value")
def test_default_used_when_none_is_set(self):
"""If None is cached, get() returns it instead of the default."""
cache.set("key_default_none", None)
self.assertIsNone(cache.get("key_default_none", default="default"))
def test_add(self):
# A key can be added to a cache
self.assertIs(cache.add("addkey1", "value"), True)
self.assertIs(cache.add("addkey1", "newvalue"), False)
self.assertEqual(cache.get("addkey1"), "value")
def test_prefix(self):
# Test for same cache key conflicts between shared backend
cache.set("somekey", "value")
# should not be set in the prefixed cache
self.assertIs(caches["prefix"].has_key("somekey"), False)
caches["prefix"].set("somekey", "value2")
self.assertEqual(cache.get("somekey"), "value")
self.assertEqual(caches["prefix"].get("somekey"), "value2")
def test_non_existent(self):
"""Nonexistent cache keys return as None/default."""
self.assertIsNone(cache.get("does_not_exist"))
self.assertEqual(cache.get("does_not_exist", "bang!"), "bang!")
def test_get_many(self):
# Multiple cache keys can be returned using get_many
cache.set_many({"a": "a", "b": "b", "c": "c", "d": "d"})
self.assertEqual(
cache.get_many(["a", "c", "d"]), {"a": "a", "c": "c", "d": "d"}
)
self.assertEqual(cache.get_many(["a", "b", "e"]), {"a": "a", "b": "b"})
self.assertEqual(cache.get_many(iter(["a", "b", "e"])), {"a": "a", "b": "b"})
cache.set_many({"x": None, "y": 1})
self.assertEqual(cache.get_many(["x", "y"]), {"x": None, "y": 1})
def test_delete(self):
# Cache keys can be deleted
cache.set_many({"key1": "spam", "key2": "eggs"})
self.assertEqual(cache.get("key1"), "spam")
self.assertIs(cache.delete("key1"), True)
self.assertIsNone(cache.get("key1"))
self.assertEqual(cache.get("key2"), "eggs")
def test_delete_nonexistent(self):
self.assertIs(cache.delete("nonexistent_key"), False)
def test_has_key(self):
# The cache can be inspected for cache keys
cache.set("hello1", "goodbye1")
self.assertIs(cache.has_key("hello1"), True)
self.assertIs(cache.has_key("goodbye1"), False)
cache.set("no_expiry", "here", None)
self.assertIs(cache.has_key("no_expiry"), True)
cache.set("null", None)
self.assertIs(cache.has_key("null"), True)
def test_in(self):
# The in operator can be used to inspect cache contents
cache.set("hello2", "goodbye2")
self.assertIn("hello2", cache)
self.assertNotIn("goodbye2", cache)
cache.set("null", None)
self.assertIn("null", cache)
def test_incr(self):
# Cache values can be incremented
cache.set("answer", 41)
self.assertEqual(cache.incr("answer"), 42)
self.assertEqual(cache.get("answer"), 42)
self.assertEqual(cache.incr("answer", 10), 52)
self.assertEqual(cache.get("answer"), 52)
self.assertEqual(cache.incr("answer", -10), 42)
with self.assertRaises(ValueError):
cache.incr("does_not_exist")
with self.assertRaises(ValueError):
cache.incr("does_not_exist", -1)
cache.set("null", None)
with self.assertRaises(self.incr_decr_type_error):
cache.incr("null")
def test_decr(self):
# Cache values can be decremented
cache.set("answer", 43)
self.assertEqual(cache.decr("answer"), 42)
self.assertEqual(cache.get("answer"), 42)
self.assertEqual(cache.decr("answer", 10), 32)
self.assertEqual(cache.get("answer"), 32)
self.assertEqual(cache.decr("answer", -10), 42)
with self.assertRaises(ValueError):
cache.decr("does_not_exist")
with self.assertRaises(ValueError):
cache.incr("does_not_exist", -1)
cache.set("null", None)
with self.assertRaises(self.incr_decr_type_error):
cache.decr("null")
def test_close(self):
self.assertTrue(hasattr(cache, "close"))
cache.close()
def test_data_types(self):
# Many different data types can be cached
tests = {
"string": "this is a string",
"int": 42,
"bool": True,
"list": [1, 2, 3, 4],
"tuple": (1, 2, 3, 4),
"dict": {"A": 1, "B": 2},
"function": f,
"class": C,
}
for key, value in tests.items():
with self.subTest(key=key):
cache.set(key, value)
self.assertEqual(cache.get(key), value)
def test_cache_read_for_model_instance(self):
# Don't want fields with callable as default to be called on cache read
expensive_calculation.num_runs = 0
Poll.objects.all().delete()
my_poll = Poll.objects.create(question="Well?")
self.assertEqual(Poll.objects.count(), 1)
pub_date = my_poll.pub_date
cache.set("question", my_poll)
cached_poll = cache.get("question")
self.assertEqual(cached_poll.pub_date, pub_date)
# We only want the default expensive calculation run once
self.assertEqual(expensive_calculation.num_runs, 1)
def test_cache_write_for_model_instance_with_deferred(self):
# Don't want fields with callable as default to be called on cache
# write
expensive_calculation.num_runs = 0
Poll.objects.all().delete()
Poll.objects.create(question="What?")
self.assertEqual(expensive_calculation.num_runs, 1)
defer_qs = Poll.objects.defer("question")
self.assertEqual(defer_qs.count(), 1)
self.assertEqual(expensive_calculation.num_runs, 1)
cache.set("deferred_queryset", defer_qs)
# cache set should not re-evaluate default functions
self.assertEqual(expensive_calculation.num_runs, 1)
def test_cache_read_for_model_instance_with_deferred(self):
# Don't want fields with callable as default to be called on cache read
expensive_calculation.num_runs = 0
Poll.objects.all().delete()
Poll.objects.create(question="What?")
self.assertEqual(expensive_calculation.num_runs, 1)
defer_qs = Poll.objects.defer("question")
self.assertEqual(defer_qs.count(), 1)
cache.set("deferred_queryset", defer_qs)
self.assertEqual(expensive_calculation.num_runs, 1)
runs_before_cache_read = expensive_calculation.num_runs
cache.get("deferred_queryset")
# We only want the default expensive calculation run on creation and
# set
self.assertEqual(expensive_calculation.num_runs, runs_before_cache_read)
def test_expiration(self):
# Cache values can be set to expire
cache.set("expire1", "very quickly", 1)
cache.set("expire2", "very quickly", 1)
cache.set("expire3", "very quickly", 1)
time.sleep(2)
self.assertIsNone(cache.get("expire1"))
self.assertIs(cache.add("expire2", "newvalue"), True)
self.assertEqual(cache.get("expire2"), "newvalue")
self.assertIs(cache.has_key("expire3"), False)
@retry()
def test_touch(self):
# cache.touch() updates the timeout.
cache.set("expire1", "very quickly", timeout=1)
self.assertIs(cache.touch("expire1", timeout=4), True)
time.sleep(2)
self.assertIs(cache.has_key("expire1"), True)
time.sleep(3)
self.assertIs(cache.has_key("expire1"), False)
# cache.touch() works without the timeout argument.
cache.set("expire1", "very quickly", timeout=1)
self.assertIs(cache.touch("expire1"), True)
time.sleep(2)
self.assertIs(cache.has_key("expire1"), True)
self.assertIs(cache.touch("nonexistent"), False)
def test_unicode(self):
# Unicode values can be cached
stuff = {
"ascii": "ascii_value",
"unicode_ascii": "Iñtërnâtiônàlizætiøn1",
"Iñtërnâtiônàlizætiøn": "Iñtërnâtiônàlizætiøn2",
"ascii2": {"x": 1},
}
# Test `set`
for key, value in stuff.items():
with self.subTest(key=key):
cache.set(key, value)
self.assertEqual(cache.get(key), value)
# Test `add`
for key, value in stuff.items():
with self.subTest(key=key):
self.assertIs(cache.delete(key), True)
self.assertIs(cache.add(key, value), True)
self.assertEqual(cache.get(key), value)
# Test `set_many`
for key, value in stuff.items():
self.assertIs(cache.delete(key), True)
cache.set_many(stuff)
for key, value in stuff.items():
with self.subTest(key=key):
self.assertEqual(cache.get(key), value)
def test_binary_string(self):
# Binary strings should be cacheable
from zlib import compress, decompress
value = "value_to_be_compressed"
compressed_value = compress(value.encode())
# Test set
cache.set("binary1", compressed_value)
compressed_result = cache.get("binary1")
self.assertEqual(compressed_value, compressed_result)
self.assertEqual(value, decompress(compressed_result).decode())
# Test add
self.assertIs(cache.add("binary1-add", compressed_value), True)
compressed_result = cache.get("binary1-add")
self.assertEqual(compressed_value, compressed_result)
self.assertEqual(value, decompress(compressed_result).decode())
# Test set_many
cache.set_many({"binary1-set_many": compressed_value})
compressed_result = cache.get("binary1-set_many")
self.assertEqual(compressed_value, compressed_result)
self.assertEqual(value, decompress(compressed_result).decode())
def test_set_many(self):
# Multiple keys can be set using set_many
cache.set_many({"key1": "spam", "key2": "eggs"})
self.assertEqual(cache.get("key1"), "spam")
self.assertEqual(cache.get("key2"), "eggs")
def test_set_many_returns_empty_list_on_success(self):
"""set_many() returns an empty list when all keys are inserted."""
failing_keys = cache.set_many({"key1": "spam", "key2": "eggs"})
self.assertEqual(failing_keys, [])
def test_set_many_expiration(self):
# set_many takes a second ``timeout`` parameter
cache.set_many({"key1": "spam", "key2": "eggs"}, 1)
time.sleep(2)
self.assertIsNone(cache.get("key1"))
self.assertIsNone(cache.get("key2"))
def test_set_many_empty_data(self):
self.assertEqual(cache.set_many({}), [])
def test_delete_many(self):
# Multiple keys can be deleted using delete_many
cache.set_many({"key1": "spam", "key2": "eggs", "key3": "ham"})
cache.delete_many(["key1", "key2"])
self.assertIsNone(cache.get("key1"))
self.assertIsNone(cache.get("key2"))
self.assertEqual(cache.get("key3"), "ham")
def test_delete_many_no_keys(self):
self.assertIsNone(cache.delete_many([]))
def test_clear(self):
# The cache can be emptied using clear
cache.set_many({"key1": "spam", "key2": "eggs"})
cache.clear()
self.assertIsNone(cache.get("key1"))
self.assertIsNone(cache.get("key2"))
def test_long_timeout(self):
"""
Follow memcached's convention where a timeout greater than 30 days is
treated as an absolute expiration timestamp instead of a relative
offset (#12399).
"""
cache.set("key1", "eggs", 60 * 60 * 24 * 30 + 1) # 30 days + 1 second
self.assertEqual(cache.get("key1"), "eggs")
self.assertIs(cache.add("key2", "ham", 60 * 60 * 24 * 30 + 1), True)
self.assertEqual(cache.get("key2"), "ham")
cache.set_many(
{"key3": "sausage", "key4": "lobster bisque"}, 60 * 60 * 24 * 30 + 1
)
self.assertEqual(cache.get("key3"), "sausage")
self.assertEqual(cache.get("key4"), "lobster bisque")
@retry()
def test_forever_timeout(self):
"""
Passing in None into timeout results in a value that is cached forever
"""
cache.set("key1", "eggs", None)
self.assertEqual(cache.get("key1"), "eggs")
self.assertIs(cache.add("key2", "ham", None), True)
self.assertEqual(cache.get("key2"), "ham")
self.assertIs(cache.add("key1", "new eggs", None), False)
self.assertEqual(cache.get("key1"), "eggs")
cache.set_many({"key3": "sausage", "key4": "lobster bisque"}, None)
self.assertEqual(cache.get("key3"), "sausage")
self.assertEqual(cache.get("key4"), "lobster bisque")
cache.set("key5", "belgian fries", timeout=1)
self.assertIs(cache.touch("key5", timeout=None), True)
time.sleep(2)
self.assertEqual(cache.get("key5"), "belgian fries")
def test_zero_timeout(self):
"""
Passing in zero into timeout results in a value that is not cached
"""
cache.set("key1", "eggs", 0)
self.assertIsNone(cache.get("key1"))
self.assertIs(cache.add("key2", "ham", 0), True)
self.assertIsNone(cache.get("key2"))
cache.set_many({"key3": "sausage", "key4": "lobster bisque"}, 0)
self.assertIsNone(cache.get("key3"))
self.assertIsNone(cache.get("key4"))
cache.set("key5", "belgian fries", timeout=5)
self.assertIs(cache.touch("key5", timeout=0), True)
self.assertIsNone(cache.get("key5"))
def test_float_timeout(self):
# Make sure a timeout given as a float doesn't crash anything.
cache.set("key1", "spam", 100.2)
self.assertEqual(cache.get("key1"), "spam")
def _perform_cull_test(self, cull_cache_name, initial_count, final_count):
try:
cull_cache = caches[cull_cache_name]
except InvalidCacheBackendError:
self.skipTest("Culling isn't implemented.")
# Create initial cache key entries. This will overflow the cache,
# causing a cull.
for i in range(1, initial_count):
cull_cache.set("cull%d" % i, "value", 1000)
count = 0
# Count how many keys are left in the cache.
for i in range(1, initial_count):
if cull_cache.has_key("cull%d" % i):
count += 1
self.assertEqual(count, final_count)
def test_cull(self):
self._perform_cull_test("cull", 50, 29)
def test_zero_cull(self):
self._perform_cull_test("zero_cull", 50, 19)
def test_cull_delete_when_store_empty(self):
try:
cull_cache = caches["cull"]
except InvalidCacheBackendError:
self.skipTest("Culling isn't implemented.")
old_max_entries = cull_cache._max_entries
# Force _cull to delete on first cached record.
cull_cache._max_entries = -1
try:
cull_cache.set("force_cull_delete", "value", 1000)
self.assertIs(cull_cache.has_key("force_cull_delete"), True)
finally:
cull_cache._max_entries = old_max_entries
def _perform_invalid_key_test(self, key, expected_warning, key_func=None):
"""
All the builtin backends should warn (except memcached that should
error) on keys that would be refused by memcached. This encourages
portable caching code without making it too difficult to use production
backends with more liberal key rules. Refs #6447.
"""
# mimic custom ``make_key`` method being defined since the default will
# never show the below warnings
def func(key, *args):
return key
old_func = cache.key_func
cache.key_func = key_func or func
tests = [
("add", [key, 1]),
("get", [key]),
("set", [key, 1]),
("incr", [key]),
("decr", [key]),
("touch", [key]),
("delete", [key]),
("get_many", [[key, "b"]]),
("set_many", [{key: 1, "b": 2}]),
("delete_many", [[key, "b"]]),
]
try:
for operation, args in tests:
with self.subTest(operation=operation):
with self.assertWarns(CacheKeyWarning) as cm:
getattr(cache, operation)(*args)
self.assertEqual(str(cm.warning), expected_warning)
finally:
cache.key_func = old_func
def test_invalid_key_characters(self):
# memcached doesn't allow whitespace or control characters in keys.
key = "key with spaces and 清"
self._perform_invalid_key_test(key, KEY_ERRORS_WITH_MEMCACHED_MSG % key)
def test_invalid_key_length(self):
# memcached limits key length to 250.
key = ("a" * 250) + "清"
expected_warning = (
"Cache key will cause errors if used with memcached: "
"%r (longer than %s)" % (key, 250)
)
self._perform_invalid_key_test(key, expected_warning)
def test_invalid_with_version_key_length(self):
# Custom make_key() that adds a version to the key and exceeds the
# limit.
def key_func(key, *args):
return key + ":1"
key = "a" * 249
expected_warning = (
"Cache key will cause errors if used with memcached: "
"%r (longer than %s)" % (key_func(key), 250)
)
self._perform_invalid_key_test(key, expected_warning, key_func=key_func)
def test_cache_versioning_get_set(self):
# set, using default version = 1
cache.set("answer1", 42)
self.assertEqual(cache.get("answer1"), 42)
self.assertEqual(cache.get("answer1", version=1), 42)
self.assertIsNone(cache.get("answer1", version=2))
self.assertIsNone(caches["v2"].get("answer1"))
self.assertEqual(caches["v2"].get("answer1", version=1), 42)
self.assertIsNone(caches["v2"].get("answer1", version=2))
# set, default version = 1, but manually override version = 2
cache.set("answer2", 42, version=2)
self.assertIsNone(cache.get("answer2"))
self.assertIsNone(cache.get("answer2", version=1))
self.assertEqual(cache.get("answer2", version=2), 42)
self.assertEqual(caches["v2"].get("answer2"), 42)
self.assertIsNone(caches["v2"].get("answer2", version=1))
self.assertEqual(caches["v2"].get("answer2", version=2), 42)
# v2 set, using default version = 2
caches["v2"].set("answer3", 42)
self.assertIsNone(cache.get("answer3"))
self.assertIsNone(cache.get("answer3", version=1))
self.assertEqual(cache.get("answer3", version=2), 42)
self.assertEqual(caches["v2"].get("answer3"), 42)
self.assertIsNone(caches["v2"].get("answer3", version=1))
self.assertEqual(caches["v2"].get("answer3", version=2), 42)
# v2 set, default version = 2, but manually override version = 1
caches["v2"].set("answer4", 42, version=1)
self.assertEqual(cache.get("answer4"), 42)
self.assertEqual(cache.get("answer4", version=1), 42)
self.assertIsNone(cache.get("answer4", version=2))
self.assertIsNone(caches["v2"].get("answer4"))
self.assertEqual(caches["v2"].get("answer4", version=1), 42)
self.assertIsNone(caches["v2"].get("answer4", version=2))
def test_cache_versioning_add(self):
# add, default version = 1, but manually override version = 2
self.assertIs(cache.add("answer1", 42, version=2), True)
self.assertIsNone(cache.get("answer1", version=1))
self.assertEqual(cache.get("answer1", version=2), 42)
self.assertIs(cache.add("answer1", 37, version=2), False)
self.assertIsNone(cache.get("answer1", version=1))
self.assertEqual(cache.get("answer1", version=2), 42)
self.assertIs(cache.add("answer1", 37, version=1), True)
self.assertEqual(cache.get("answer1", version=1), 37)
self.assertEqual(cache.get("answer1", version=2), 42)
# v2 add, using default version = 2
self.assertIs(caches["v2"].add("answer2", 42), True)
self.assertIsNone(cache.get("answer2", version=1))
self.assertEqual(cache.get("answer2", version=2), 42)
self.assertIs(caches["v2"].add("answer2", 37), False)
self.assertIsNone(cache.get("answer2", version=1))
self.assertEqual(cache.get("answer2", version=2), 42)
self.assertIs(caches["v2"].add("answer2", 37, version=1), True)
self.assertEqual(cache.get("answer2", version=1), 37)
self.assertEqual(cache.get("answer2", version=2), 42)
# v2 add, default version = 2, but manually override version = 1
self.assertIs(caches["v2"].add("answer3", 42, version=1), True)
self.assertEqual(cache.get("answer3", version=1), 42)
self.assertIsNone(cache.get("answer3", version=2))
self.assertIs(caches["v2"].add("answer3", 37, version=1), False)
self.assertEqual(cache.get("answer3", version=1), 42)
self.assertIsNone(cache.get("answer3", version=2))
self.assertIs(caches["v2"].add("answer3", 37), True)
self.assertEqual(cache.get("answer3", version=1), 42)
self.assertEqual(cache.get("answer3", version=2), 37)
def test_cache_versioning_has_key(self):
cache.set("answer1", 42)
# has_key
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | true |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/cache/tests_async.py | tests/cache/tests_async.py | import asyncio
from django.core.cache import CacheKeyWarning, cache
from django.test import SimpleTestCase, override_settings
from .tests import KEY_ERRORS_WITH_MEMCACHED_MSG
@override_settings(
CACHES={
"default": {
"BACKEND": "django.core.cache.backends.dummy.DummyCache",
}
}
)
class AsyncDummyCacheTests(SimpleTestCase):
async def test_simple(self):
"""Dummy cache backend ignores cache set calls."""
await cache.aset("key", "value")
self.assertIsNone(await cache.aget("key"))
async def test_aadd(self):
"""Add doesn't do anything in dummy cache backend."""
self.assertIs(await cache.aadd("key", "value"), True)
self.assertIs(await cache.aadd("key", "new_value"), True)
self.assertIsNone(await cache.aget("key"))
async def test_non_existent(self):
"""Nonexistent keys aren't found in the dummy cache backend."""
self.assertIsNone(await cache.aget("does_not_exist"))
self.assertEqual(await cache.aget("does_not_exist", "default"), "default")
async def test_aget_many(self):
"""aget_many() returns nothing for the dummy cache backend."""
await cache.aset_many({"a": "a", "b": "b", "c": "c", "d": "d"})
self.assertEqual(await cache.aget_many(["a", "c", "d"]), {})
self.assertEqual(await cache.aget_many(["a", "b", "e"]), {})
async def test_aget_many_invalid_key(self):
msg = KEY_ERRORS_WITH_MEMCACHED_MSG % ":1:key with spaces"
with self.assertWarnsMessage(CacheKeyWarning, msg):
await cache.aget_many(["key with spaces"])
async def test_adelete(self):
"""
Cache deletion is transparently ignored on the dummy cache backend.
"""
await cache.aset_many({"key1": "spam", "key2": "eggs"})
self.assertIsNone(await cache.aget("key1"))
self.assertIs(await cache.adelete("key1"), False)
self.assertIsNone(await cache.aget("key1"))
self.assertIsNone(await cache.aget("key2"))
async def test_ahas_key(self):
"""ahas_key() doesn't ever return True for the dummy cache backend."""
await cache.aset("hello1", "goodbye1")
self.assertIs(await cache.ahas_key("hello1"), False)
self.assertIs(await cache.ahas_key("goodbye1"), False)
async def test_aincr(self):
"""Dummy cache values can't be incremented."""
await cache.aset("answer", 42)
with self.assertRaises(ValueError):
await cache.aincr("answer")
with self.assertRaises(ValueError):
await cache.aincr("does_not_exist")
with self.assertRaises(ValueError):
await cache.aincr("does_not_exist", -1)
async def test_adecr(self):
"""Dummy cache values can't be decremented."""
await cache.aset("answer", 42)
with self.assertRaises(ValueError):
await cache.adecr("answer")
with self.assertRaises(ValueError):
await cache.adecr("does_not_exist")
with self.assertRaises(ValueError):
await cache.adecr("does_not_exist", -1)
async def test_atouch(self):
self.assertIs(await cache.atouch("key"), False)
async def test_data_types(self):
"""All data types are ignored equally by the dummy cache."""
def f():
return 42
class C:
def m(n):
return 24
data = {
"string": "this is a string",
"int": 42,
"list": [1, 2, 3, 4],
"tuple": (1, 2, 3, 4),
"dict": {"A": 1, "B": 2},
"function": f,
"class": C,
}
await cache.aset("data", data)
self.assertIsNone(await cache.aget("data"))
async def test_expiration(self):
"""Expiration has no effect on the dummy cache."""
await cache.aset("expire1", "very quickly", 1)
await cache.aset("expire2", "very quickly", 1)
await cache.aset("expire3", "very quickly", 1)
await asyncio.sleep(2)
self.assertIsNone(await cache.aget("expire1"))
self.assertIs(await cache.aadd("expire2", "new_value"), True)
self.assertIsNone(await cache.aget("expire2"))
self.assertIs(await cache.ahas_key("expire3"), False)
async def test_unicode(self):
"""Unicode values are ignored by the dummy cache."""
tests = {
"ascii": "ascii_value",
"unicode_ascii": "Iñtërnâtiônàlizætiøn1",
"Iñtërnâtiônàlizætiøn": "Iñtërnâtiônàlizætiøn2",
"ascii2": {"x": 1},
}
for key, value in tests.items():
with self.subTest(key=key):
await cache.aset(key, value)
self.assertIsNone(await cache.aget(key))
async def test_aset_many(self):
"""aset_many() does nothing for the dummy cache backend."""
self.assertEqual(await cache.aset_many({"a": 1, "b": 2}), [])
self.assertEqual(
await cache.aset_many({"a": 1, "b": 2}, timeout=2, version="1"),
[],
)
async def test_aset_many_invalid_key(self):
msg = KEY_ERRORS_WITH_MEMCACHED_MSG % ":1:key with spaces"
with self.assertWarnsMessage(CacheKeyWarning, msg):
await cache.aset_many({"key with spaces": "foo"})
async def test_adelete_many(self):
"""adelete_many() does nothing for the dummy cache backend."""
await cache.adelete_many(["a", "b"])
async def test_adelete_many_invalid_key(self):
msg = KEY_ERRORS_WITH_MEMCACHED_MSG % ":1:key with spaces"
with self.assertWarnsMessage(CacheKeyWarning, msg):
await cache.adelete_many({"key with spaces": "foo"})
async def test_aclear(self):
"""aclear() does nothing for the dummy cache backend."""
await cache.aclear()
async def test_aclose(self):
"""aclose() does nothing for the dummy cache backend."""
await cache.aclose()
async def test_aincr_version(self):
"""Dummy cache versions can't be incremented."""
await cache.aset("answer", 42)
with self.assertRaises(ValueError):
await cache.aincr_version("answer")
with self.assertRaises(ValueError):
await cache.aincr_version("answer", version=2)
with self.assertRaises(ValueError):
await cache.aincr_version("does_not_exist")
async def test_adecr_version(self):
"""Dummy cache versions can't be decremented."""
await cache.aset("answer", 42)
with self.assertRaises(ValueError):
await cache.adecr_version("answer")
with self.assertRaises(ValueError):
await cache.adecr_version("answer", version=2)
with self.assertRaises(ValueError):
await cache.adecr_version("does_not_exist")
async def test_aget_or_set(self):
self.assertEqual(await cache.aget_or_set("key", "default"), "default")
self.assertIsNone(await cache.aget_or_set("key", None))
async def test_aget_or_set_callable(self):
def my_callable():
return "default"
self.assertEqual(await cache.aget_or_set("key", my_callable), "default")
self.assertEqual(await cache.aget_or_set("key", my_callable()), "default")
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_docs/namespace_urls.py | tests/admin_docs/namespace_urls.py | from django.contrib import admin
from django.urls import include, path
from . import views
backend_urls = (
[
path("something/", views.XViewClass.as_view(), name="something"),
],
"backend",
)
urlpatterns = [
path("admin/doc/", include("django.contrib.admindocs.urls")),
path("admin/", admin.site.urls),
path("api/backend/", include(backend_urls, namespace="backend")),
]
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_docs/views.py | tests/admin_docs/views.py | from django.contrib.admindocs.middleware import XViewMiddleware
from django.http import HttpResponse
from django.utils.decorators import decorator_from_middleware
from django.views.generic import View
xview_dec = decorator_from_middleware(XViewMiddleware)
def xview(request):
return HttpResponse()
class XViewClass(View):
def get(self, request):
return HttpResponse()
class XViewCallableObject(View):
def __call__(self, request):
return HttpResponse()
class CompanyView(View):
"""
This is a view for :model:`myapp.Company`
"""
def get(self, request):
return HttpResponse()
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_docs/test_utils.py | tests/admin_docs/test_utils.py | import unittest
from django.contrib.admindocs.utils import (
docutils_is_available,
parse_docstring,
parse_rst,
)
from django.test.utils import captured_stderr
from .tests import AdminDocsSimpleTestCase
@unittest.skipUnless(docutils_is_available, "no docutils installed.")
class TestUtils(AdminDocsSimpleTestCase):
"""
This __doc__ output is required for testing. I copied this example from
`admindocs` documentation. (TITLE)
Display an individual :model:`myapp.MyModel`.
**Context**
``RequestContext``
``mymodel``
An instance of :model:`myapp.MyModel`.
**Template:**
:template:`myapp/my_template.html` (DESCRIPTION)
some_metadata: some data
"""
def setUp(self):
self.docstring = self.__doc__
def test_parse_docstring(self):
title, description, metadata = parse_docstring(self.docstring)
docstring_title = (
"This __doc__ output is required for testing. I copied this example from\n"
"`admindocs` documentation. (TITLE)"
)
docstring_description = (
"Display an individual :model:`myapp.MyModel`.\n\n"
"**Context**\n\n``RequestContext``\n\n``mymodel``\n"
" An instance of :model:`myapp.MyModel`.\n\n"
"**Template:**\n\n:template:`myapp/my_template.html` "
"(DESCRIPTION)"
)
self.assertEqual(title, docstring_title)
self.assertEqual(description, docstring_description)
self.assertEqual(metadata, {"some_metadata": "some data"})
def test_title_output(self):
title, description, metadata = parse_docstring(self.docstring)
title_output = parse_rst(title, "model", "model:admindocs")
self.assertIn("TITLE", title_output)
title_rendered = (
"<p>This __doc__ output is required for testing. I copied this "
'example from\n<a class="reference external" '
'href="/admindocs/models/admindocs/">admindocs</a> documentation. '
"(TITLE)</p>\n"
)
self.assertHTMLEqual(title_output, title_rendered)
def test_description_output(self):
title, description, metadata = parse_docstring(self.docstring)
description_output = parse_rst(description, "model", "model:admindocs")
description_rendered = (
'<p>Display an individual <a class="reference external" '
'href="/admindocs/models/myapp.mymodel/">myapp.MyModel</a>.</p>\n'
'<p><strong>Context</strong></p>\n<p><tt class="docutils literal">'
'RequestContext</tt></p>\n<dl class="docutils">\n<dt><tt class="'
'docutils literal">mymodel</tt></dt>\n<dd>An instance of <a class="'
'reference external" href="/admindocs/models/myapp.mymodel/">'
"myapp.MyModel</a>.</dd>\n</dl>\n<p><strong>Template:</strong></p>"
'\n<p><a class="reference external" href="/admindocs/templates/'
'myapp/my_template.html/">myapp/my_template.html</a> (DESCRIPTION)'
"</p>\n"
)
self.assertHTMLEqual(description_output, description_rendered)
def test_initial_header_level(self):
header = "should be h3...\n\nHeader\n------\n"
output = parse_rst(header, "header")
self.assertIn("<h3>Header</h3>", output)
def test_parse_rst(self):
"""
parse_rst() should use `cmsreference` as the default role.
"""
markup = '<p><a class="reference external" href="/admindocs/%s">title</a></p>\n'
self.assertEqual(parse_rst("`title`", "model"), markup % "models/title/")
self.assertEqual(parse_rst("`title`", "view"), markup % "views/title/")
self.assertEqual(parse_rst("`title`", "template"), markup % "templates/title/")
self.assertEqual(parse_rst("`title`", "filter"), markup % "filters/#title")
self.assertEqual(parse_rst("`title`", "tag"), markup % "tags/#title")
def test_parse_rst_with_docstring_no_leading_line_feed(self):
title, body, _ = parse_docstring("firstline\n\n second line")
with captured_stderr() as stderr:
self.assertEqual(parse_rst(title, ""), "<p>firstline</p>\n")
self.assertEqual(parse_rst(body, ""), "<p>second line</p>\n")
self.assertEqual(stderr.getvalue(), "")
def test_parse_rst_view_case_sensitive(self):
source = ":view:`myapp.views.Index`"
rendered = (
'<p><a class="reference external" '
'href="/admindocs/views/myapp.views.Index/">myapp.views.Index</a></p>'
)
self.assertHTMLEqual(parse_rst(source, "view"), rendered)
def test_parse_rst_template_case_sensitive(self):
source = ":template:`Index.html`"
rendered = (
'<p><a class="reference external" href="/admindocs/templates/Index.html/">'
"Index.html</a></p>"
)
self.assertHTMLEqual(parse_rst(source, "template"), rendered)
def test_publish_parts(self):
"""
Django shouldn't break the default role for interpreted text
when ``publish_parts`` is used directly, by setting it to
``cmsreference`` (#6681).
"""
import docutils
self.assertNotEqual(
docutils.parsers.rst.roles.DEFAULT_INTERPRETED_ROLE, "cmsreference"
)
source = "reST, `interpreted text`, default role."
markup = "<p>reST, <cite>interpreted text</cite>, default role.</p>\n"
parts = docutils.core.publish_parts(source=source, writer="html4css1")
self.assertEqual(parts["fragment"], markup)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_docs/test_views.py | tests/admin_docs/test_views.py | import sys
import unittest
from django.conf import settings
from django.contrib import admin
from django.contrib.admindocs import utils, views
from django.contrib.admindocs.views import get_return_data_type, simplify_regex
from django.contrib.auth.models import Permission, User
from django.contrib.contenttypes.models import ContentType
from django.contrib.sites.models import Site
from django.db import models
from django.db.models import fields
from django.test import SimpleTestCase, modify_settings, override_settings
from django.test.utils import captured_stderr
from django.urls import include, path, reverse
from django.utils.functional import SimpleLazyObject
from .models import Company, Person
from .tests import AdminDocsTestCase, TestDataMixin
@unittest.skipUnless(utils.docutils_is_available, "no docutils installed.")
class AdminDocViewTests(TestDataMixin, AdminDocsTestCase):
def setUp(self):
self.client.force_login(self.superuser)
def test_index(self):
response = self.client.get(reverse("django-admindocs-docroot"))
self.assertContains(response, "<h1>Documentation</h1>", html=True)
self.assertContains(
response,
'<div id="site-name"><a href="/admin/">Django administration</a></div>',
)
self.client.logout()
response = self.client.get(reverse("django-admindocs-docroot"), follow=True)
# Should display the login screen
self.assertContains(
response, '<input type="hidden" name="next" value="/admindocs/">', html=True
)
def test_bookmarklets(self):
response = self.client.get(reverse("django-admindocs-bookmarklets"))
self.assertContains(response, "/admindocs/views/")
def test_templatetag_index(self):
response = self.client.get(reverse("django-admindocs-tags"))
self.assertContains(
response, '<h3 id="built_in-extends">extends</h3>', html=True
)
def test_templatefilter_index(self):
response = self.client.get(reverse("django-admindocs-filters"))
self.assertContains(response, '<h3 id="built_in-first">first</h3>', html=True)
def test_view_index(self):
response = self.client.get(reverse("django-admindocs-views-index"))
self.assertContains(
response,
'<h3><a href="/admindocs/views/django.contrib.admindocs.views.'
'BaseAdminDocsView/">/admindocs/</a></h3>',
html=True,
)
self.assertContains(response, "Views by namespace test")
self.assertContains(response, "Name: <code>test:func</code>.")
self.assertContains(
response,
'<h3><a href="/admindocs/views/admin_docs.views.XViewCallableObject/">'
"/xview/callable_object_without_xview/</a></h3>",
html=True,
)
def test_view_index_with_method(self):
"""
Views that are methods are listed correctly.
"""
response = self.client.get(reverse("django-admindocs-views-index"))
self.assertContains(
response,
"<h3>"
'<a href="/admindocs/views/django.contrib.admin.sites.AdminSite.index/">'
"/admin/</a></h3>",
html=True,
)
def test_view_detail(self):
url = reverse(
"django-admindocs-views-detail",
args=["django.contrib.admindocs.views.BaseAdminDocsView"],
)
response = self.client.get(url)
# View docstring
self.assertContains(response, "Base view for admindocs views.")
def testview_docstring_links(self):
summary = (
'<h2 class="subhead">This is a view for '
'<a class="reference external" href="/admindocs/models/myapp.company/">'
"myapp.Company</a></h2>"
)
url = reverse(
"django-admindocs-views-detail", args=["admin_docs.views.CompanyView"]
)
response = self.client.get(url)
self.assertContains(response, summary, html=True)
@override_settings(ROOT_URLCONF="admin_docs.namespace_urls")
def test_namespaced_view_detail(self):
url = reverse(
"django-admindocs-views-detail", args=["admin_docs.views.XViewClass"]
)
response = self.client.get(url)
self.assertContains(response, "<h1>admin_docs.views.XViewClass</h1>")
def test_view_detail_illegal_import(self):
url = reverse(
"django-admindocs-views-detail",
args=["urlpatterns_reverse.nonimported_module.view"],
)
response = self.client.get(url)
self.assertEqual(response.status_code, 404)
self.assertNotIn("urlpatterns_reverse.nonimported_module", sys.modules)
def test_view_detail_as_method(self):
"""
Views that are methods can be displayed.
"""
url = reverse(
"django-admindocs-views-detail",
args=["django.contrib.admin.sites.AdminSite.index"],
)
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
def test_model_index(self):
response = self.client.get(reverse("django-admindocs-models-index"))
self.assertContains(
response,
'<h2 id="app-auth">Authentication and Authorization (django.contrib.auth)'
"</h2>",
html=True,
)
def test_template_detail(self):
response = self.client.get(
reverse(
"django-admindocs-templates", args=["admin_doc/template_detail.html"]
)
)
self.assertContains(
response,
"<h1>Template: <q>admin_doc/template_detail.html</q></h1>",
html=True,
)
def test_template_detail_loader(self):
response = self.client.get(
reverse("django-admindocs-templates", args=["view_for_loader_test.html"])
)
self.assertContains(response, "view_for_loader_test.html</code></li>")
def test_missing_docutils(self):
utils.docutils_is_available = False
try:
response = self.client.get(reverse("django-admindocs-docroot"))
self.assertContains(
response,
"<h3>The admin documentation system requires Python’s "
'<a href="https://docutils.sourceforge.io/">docutils</a> '
"library.</h3>"
"<p>Please ask your administrators to install "
'<a href="https://pypi.org/project/docutils/">docutils</a>.</p>',
html=True,
)
self.assertContains(
response,
'<div id="site-name"><a href="/admin/">Django administration</a></div>',
)
finally:
utils.docutils_is_available = True
@modify_settings(INSTALLED_APPS={"remove": "django.contrib.sites"})
@override_settings(SITE_ID=None) # will restore SITE_ID after the test
def test_no_sites_framework(self):
"""
Without the sites framework, should not access SITE_ID or Site
objects. Deleting settings is fine here as UserSettingsHolder is used.
"""
Site.objects.all().delete()
del settings.SITE_ID
response = self.client.get(reverse("django-admindocs-views-index"))
self.assertContains(response, "View documentation")
def test_callable_urlconf(self):
"""
Index view should correctly resolve view patterns when ROOT_URLCONF is
not a string.
"""
def urlpatterns():
return (
path("admin/doc/", include("django.contrib.admindocs.urls")),
path("admin/", admin.site.urls),
)
with self.settings(ROOT_URLCONF=SimpleLazyObject(urlpatterns)):
response = self.client.get(reverse("django-admindocs-views-index"))
self.assertEqual(response.status_code, 200)
@unittest.skipUnless(utils.docutils_is_available, "no docutils installed.")
class AdminDocViewDefaultEngineOnly(TestDataMixin, AdminDocsTestCase):
def setUp(self):
self.client.force_login(self.superuser)
def test_template_detail_path_traversal(self):
cases = ["/etc/passwd", "../passwd"]
for fpath in cases:
with self.subTest(path=fpath):
response = self.client.get(
reverse("django-admindocs-templates", args=[fpath]),
)
self.assertEqual(response.status_code, 400)
@override_settings(
TEMPLATES=[
{
"NAME": "ONE",
"BACKEND": "django.template.backends.django.DjangoTemplates",
"APP_DIRS": True,
},
{
"NAME": "TWO",
"BACKEND": "django.template.backends.django.DjangoTemplates",
"APP_DIRS": True,
},
]
)
@unittest.skipUnless(utils.docutils_is_available, "no docutils installed.")
class AdminDocViewWithMultipleEngines(AdminDocViewTests):
def test_templatefilter_index(self):
# Overridden because non-trivial TEMPLATES settings aren't supported
# but the page shouldn't crash (#24125).
response = self.client.get(reverse("django-admindocs-filters"))
self.assertContains(response, "<title>Template filters</title>", html=True)
def test_templatetag_index(self):
# Overridden because non-trivial TEMPLATES settings aren't supported
# but the page shouldn't crash (#24125).
response = self.client.get(reverse("django-admindocs-tags"))
self.assertContains(response, "<title>Template tags</title>", html=True)
@unittest.skipUnless(utils.docutils_is_available, "no docutils installed.")
class TestModelDetailView(TestDataMixin, AdminDocsTestCase):
def setUp(self):
self.client.force_login(self.superuser)
with captured_stderr() as self.docutils_stderr:
self.response = self.client.get(
reverse("django-admindocs-models-detail", args=["admin_docs", "Person"])
)
def test_table_headers(self):
tests = [
("Method", 1),
("Arguments", 1),
("Description", 2),
("Field", 1),
("Type", 1),
("Method", 1),
]
for table_header, count in tests:
self.assertContains(
self.response, f'<th scope="col">{table_header}</th>', count=count
)
def test_method_excludes(self):
"""
Methods that begin with strings defined in
``django.contrib.admindocs.views.MODEL_METHODS_EXCLUDE``
shouldn't be displayed in the admin docs.
"""
self.assertContains(self.response, "<td>get_full_name</td>")
self.assertNotContains(self.response, "<td>_get_full_name</td>")
self.assertNotContains(self.response, "<td>add_image</td>")
self.assertNotContains(self.response, "<td>delete_image</td>")
self.assertNotContains(self.response, "<td>set_status</td>")
self.assertNotContains(self.response, "<td>save_changes</td>")
def test_methods_with_arguments(self):
"""
Methods that take arguments should also displayed.
"""
self.assertContains(self.response, "<h3>Methods with arguments</h3>")
self.assertContains(self.response, "<td>rename_company</td>")
self.assertContains(self.response, "<td>dummy_function</td>")
self.assertContains(self.response, "<td>dummy_function_keyword_only_arg</td>")
self.assertContains(self.response, "<td>all_kinds_arg_function</td>")
self.assertContains(self.response, "<td>suffix_company_name</td>")
def test_methods_with_arguments_display_arguments(self):
"""
Methods with arguments should have their arguments displayed.
"""
self.assertContains(self.response, "<td>new_name</td>")
self.assertContains(self.response, "<td>keyword_only_arg</td>")
def test_methods_with_arguments_display_arguments_default_value(self):
"""
Methods with keyword arguments should have their arguments displayed.
"""
self.assertContains(self.response, "<td>suffix='ltd'</td>")
def test_methods_with_multiple_arguments_display_arguments(self):
"""
Methods with multiple arguments should have all their arguments
displayed, but omitting 'self'.
"""
self.assertContains(
self.response, "<td>baz, rox, *some_args, **some_kwargs</td>"
)
self.assertContains(self.response, "<td>position_only_arg, arg, kwarg</td>")
def test_instance_of_property_methods_are_displayed(self):
"""Model properties are displayed as fields."""
self.assertContains(self.response, "<td>a_property</td>")
def test_instance_of_cached_property_methods_are_displayed(self):
"""Model cached properties are displayed as fields."""
self.assertContains(self.response, "<td>a_cached_property</td>")
def test_method_data_types(self):
company = Company.objects.create(name="Django")
person = Person.objects.create(
first_name="Human", last_name="User", company=company
)
self.assertEqual(
get_return_data_type(person.get_status_count.__name__), "Integer"
)
self.assertEqual(get_return_data_type(person.get_groups_list.__name__), "List")
def test_descriptions_render_correctly(self):
"""
The ``description`` field should render correctly for each field type.
"""
# help text in fields
self.assertContains(
self.response, "<td>first name - The person's first name</td>"
)
self.assertContains(
self.response, "<td>last name - The person's last name</td>"
)
# method docstrings
self.assertContains(self.response, "<p>Get the full name of the person</p>")
link = '<a class="reference external" href="/admindocs/models/%s/">%s</a>'
markup = "<p>the related %s object</p>"
company_markup = markup % (link % ("admin_docs.company", "admin_docs.Company"))
# foreign keys
self.assertContains(self.response, company_markup)
# foreign keys with help text
self.assertContains(self.response, "%s\n - place of work" % company_markup)
# many to many fields
self.assertContains(
self.response,
"number of related %s objects"
% (link % ("admin_docs.group", "admin_docs.Group")),
)
self.assertContains(
self.response,
"all related %s objects"
% (link % ("admin_docs.group", "admin_docs.Group")),
)
# "raw" and "include" directives are disabled
self.assertContains(
self.response,
"<p>"raw" directive disabled.</p>",
)
self.assertContains(
self.response, ".. raw:: html\n :file: admin_docs/evilfile.txt"
)
self.assertContains(
self.response,
"<p>"include" directive disabled.</p>",
)
self.assertContains(self.response, ".. include:: admin_docs/evilfile.txt")
out = self.docutils_stderr.getvalue()
self.assertIn('"raw" directive disabled', out)
self.assertIn('"include" directive disabled', out)
def test_model_with_many_to_one(self):
link = '<a class="reference external" href="/admindocs/models/%s/">%s</a>'
response = self.client.get(
reverse("django-admindocs-models-detail", args=["admin_docs", "company"])
)
self.assertContains(
response,
"number of related %s objects"
% (link % ("admin_docs.person", "admin_docs.Person")),
)
self.assertContains(
response,
"all related %s objects"
% (link % ("admin_docs.person", "admin_docs.Person")),
)
def test_model_with_no_backward_relations_render_only_relevant_fields(self):
"""
A model with ``related_name`` of `+` shouldn't show backward
relationship links.
"""
response = self.client.get(
reverse("django-admindocs-models-detail", args=["admin_docs", "family"])
)
fields = response.context_data.get("fields")
self.assertEqual(len(fields), 2)
def test_model_docstring_renders_correctly(self):
summary = (
'<h2 class="subhead">Stores information about a person, related to '
'<a class="reference external" href="/admindocs/models/myapp.company/">'
"myapp.Company</a>.</h2>"
)
subheading = "<p><strong>Notes</strong></p>"
body = (
'<p>Use <tt class="docutils literal">save_changes()</tt> when saving this '
"object.</p>"
)
model_body = (
'<dl class="docutils"><dt><tt class="'
'docutils literal">company</tt></dt><dd>Field storing <a class="'
'reference external" href="/admindocs/models/myapp.company/">'
"myapp.Company</a> where the person works.</dd></dl>"
)
self.assertContains(self.response, "DESCRIPTION")
self.assertContains(self.response, summary, html=True)
self.assertContains(self.response, subheading, html=True)
self.assertContains(self.response, body, html=True)
self.assertContains(self.response, model_body, html=True)
def test_model_docstring_built_in_tag_links(self):
summary = "Links with different link text."
body = (
'<p>This is a line with tag <a class="reference external" '
'href="/admindocs/tags/#built_in-extends">extends</a>\n'
'This is a line with model <a class="reference external" '
'href="/admindocs/models/myapp.family/">Family</a>\n'
'This is a line with view <a class="reference external" '
'href="/admindocs/views/myapp.views.Index/">Index</a>\n'
'This is a line with template <a class="reference external" '
'href="/admindocs/templates/Index.html/">index template</a>\n'
'This is a line with filter <a class="reference external" '
'href="/admindocs/filters/#filtername">example filter</a></p>'
)
url = reverse("django-admindocs-models-detail", args=["admin_docs", "family"])
response = self.client.get(url)
self.assertContains(response, summary, html=True)
self.assertContains(response, body, html=True)
def test_model_detail_title(self):
self.assertContains(self.response, "<h1>admin_docs.Person</h1>", html=True)
def test_app_not_found(self):
response = self.client.get(
reverse("django-admindocs-models-detail", args=["doesnotexist", "Person"])
)
self.assertEqual(response.context["exception"], "App 'doesnotexist' not found")
self.assertEqual(response.status_code, 404)
def test_model_not_found(self):
response = self.client.get(
reverse(
"django-admindocs-models-detail", args=["admin_docs", "doesnotexist"]
)
)
self.assertEqual(
response.context["exception"],
"Model 'doesnotexist' not found in app 'admin_docs'",
)
self.assertEqual(response.status_code, 404)
def test_model_permission_denied(self):
person_url = reverse(
"django-admindocs-models-detail", args=["admin_docs", "person"]
)
company_url = reverse(
"django-admindocs-models-detail", args=["admin_docs", "company"]
)
staff_user = User.objects.create_user(
username="staff", password="secret", is_staff=True
)
self.client.force_login(staff_user)
response_for_person = self.client.get(person_url)
response_for_company = self.client.get(company_url)
# No access without permissions.
self.assertEqual(response_for_person.status_code, 403)
self.assertEqual(response_for_company.status_code, 403)
company_content_type = ContentType.objects.get_for_model(Company)
person_content_type = ContentType.objects.get_for_model(Person)
view_company = Permission.objects.get(
codename="view_company", content_type=company_content_type
)
change_person = Permission.objects.get(
codename="change_person", content_type=person_content_type
)
staff_user.user_permissions.add(view_company, change_person)
with captured_stderr():
response_for_person = self.client.get(person_url)
response_for_company = self.client.get(company_url)
# View or change permission grants access.
self.assertEqual(response_for_person.status_code, 200)
self.assertEqual(response_for_company.status_code, 200)
@unittest.skipUnless(utils.docutils_is_available, "no docutils installed.")
class TestModelIndexView(TestDataMixin, AdminDocsTestCase):
def test_model_index_superuser(self):
self.client.force_login(self.superuser)
index_url = reverse("django-admindocs-models-index")
response = self.client.get(index_url)
self.assertContains(
response,
'<a href="/admindocs/models/admin_docs.family/">Family</a>',
html=True,
)
self.assertContains(
response,
'<a href="/admindocs/models/admin_docs.person/">Person</a>',
html=True,
)
self.assertContains(
response,
'<a href="/admindocs/models/admin_docs.company/">Company</a>',
html=True,
)
def test_model_index_with_model_permission(self):
staff_user = User.objects.create_user(
username="staff", password="secret", is_staff=True
)
self.client.force_login(staff_user)
index_url = reverse("django-admindocs-models-index")
response = self.client.get(index_url)
# Models are not listed without permissions.
self.assertNotContains(
response,
'<a href="/admindocs/models/admin_docs.family/">Family</a>',
html=True,
)
self.assertNotContains(
response,
'<a href="/admindocs/models/admin_docs.person/">Person</a>',
html=True,
)
self.assertNotContains(
response,
'<a href="/admindocs/models/admin_docs.company/">Company</a>',
html=True,
)
company_content_type = ContentType.objects.get_for_model(Company)
person_content_type = ContentType.objects.get_for_model(Person)
view_company = Permission.objects.get(
codename="view_company", content_type=company_content_type
)
change_person = Permission.objects.get(
codename="change_person", content_type=person_content_type
)
staff_user.user_permissions.add(view_company, change_person)
response = self.client.get(index_url)
# View or change permission grants access.
self.assertNotContains(
response,
'<a href="/admindocs/models/admin_docs.family/">Family</a>',
html=True,
)
self.assertContains(
response,
'<a href="/admindocs/models/admin_docs.person/">Person</a>',
html=True,
)
self.assertContains(
response,
'<a href="/admindocs/models/admin_docs.company/">Company</a>',
html=True,
)
class CustomField(models.Field):
description = "A custom field type"
class DescriptionLackingField(models.Field):
pass
class TestFieldType(unittest.TestCase):
def test_field_name(self):
with self.assertRaises(AttributeError):
views.get_readable_field_data_type("NotAField")
def test_builtin_fields(self):
self.assertEqual(
views.get_readable_field_data_type(fields.BooleanField()),
"Boolean (Either True or False)",
)
def test_char_fields(self):
self.assertEqual(
views.get_readable_field_data_type(fields.CharField(max_length=255)),
"String (up to 255)",
)
self.assertEqual(
views.get_readable_field_data_type(fields.CharField()),
"String (unlimited)",
)
def test_custom_fields(self):
self.assertEqual(
views.get_readable_field_data_type(CustomField()), "A custom field type"
)
self.assertEqual(
views.get_readable_field_data_type(DescriptionLackingField()),
"Field of type: DescriptionLackingField",
)
class AdminDocViewFunctionsTests(SimpleTestCase):
def test_simplify_regex(self):
tests = (
# Named and unnamed groups.
(r"^(?P<a>\w+)/b/(?P<c>\w+)/$", "/<a>/b/<c>/"),
(r"^(?P<a>\w+)/b/(?P<c>\w+)$", "/<a>/b/<c>"),
(r"^(?P<a>\w+)/b/(?P<c>\w+)", "/<a>/b/<c>"),
(r"^(?P<a>\w+)/b/(\w+)$", "/<a>/b/<var>"),
(r"^(?P<a>\w+)/b/(\w+)", "/<a>/b/<var>"),
(r"^(?P<a>\w+)/b/((x|y)\w+)$", "/<a>/b/<var>"),
(r"^(?P<a>\w+)/b/((x|y)\w+)", "/<a>/b/<var>"),
(r"^(?P<a>(x|y))/b/(?P<c>\w+)$", "/<a>/b/<c>"),
(r"^(?P<a>(x|y))/b/(?P<c>\w+)", "/<a>/b/<c>"),
(r"^(?P<a>(x|y))/b/(?P<c>\w+)ab", "/<a>/b/<c>ab"),
(r"^(?P<a>(x|y)(\(|\)))/b/(?P<c>\w+)ab", "/<a>/b/<c>ab"),
# Non-capturing groups.
(r"^a(?:\w+)b", "/ab"),
(r"^a(?:(x|y))", "/a"),
(r"^(?:\w+(?:\w+))a", "/a"),
(r"^a(?:\w+)/b(?:\w+)", "/a/b"),
(r"(?P<a>\w+)/b/(?:\w+)c(?:\w+)", "/<a>/b/c"),
(r"(?P<a>\w+)/b/(\w+)/(?:\w+)c(?:\w+)", "/<a>/b/<var>/c"),
# Single and repeated metacharacters.
(r"^a", "/a"),
(r"^^a", "/a"),
(r"^^^a", "/a"),
(r"a$", "/a"),
(r"a$$", "/a"),
(r"a$$$", "/a"),
(r"a?", "/a"),
(r"a??", "/a"),
(r"a???", "/a"),
(r"a*", "/a"),
(r"a**", "/a"),
(r"a***", "/a"),
(r"a+", "/a"),
(r"a++", "/a"),
(r"a+++", "/a"),
(r"\Aa", "/a"),
(r"\A\Aa", "/a"),
(r"\A\A\Aa", "/a"),
(r"a\Z", "/a"),
(r"a\Z\Z", "/a"),
(r"a\Z\Z\Z", "/a"),
(r"\ba", "/a"),
(r"\b\ba", "/a"),
(r"\b\b\ba", "/a"),
(r"a\B", "/a"),
(r"a\B\B", "/a"),
(r"a\B\B\B", "/a"),
# Multiple mixed metacharacters.
(r"^a/?$", "/a/"),
(r"\Aa\Z", "/a"),
(r"\ba\B", "/a"),
# Escaped single metacharacters.
(r"\^a", r"/^a"),
(r"\\^a", r"/\\a"),
(r"\\\^a", r"/\\^a"),
(r"\\\\^a", r"/\\\\a"),
(r"\\\\\^a", r"/\\\\^a"),
(r"a\$", r"/a$"),
(r"a\\$", r"/a\\"),
(r"a\\\$", r"/a\\$"),
(r"a\\\\$", r"/a\\\\"),
(r"a\\\\\$", r"/a\\\\$"),
(r"a\?", r"/a?"),
(r"a\\?", r"/a\\"),
(r"a\\\?", r"/a\\?"),
(r"a\\\\?", r"/a\\\\"),
(r"a\\\\\?", r"/a\\\\?"),
(r"a\*", r"/a*"),
(r"a\\*", r"/a\\"),
(r"a\\\*", r"/a\\*"),
(r"a\\\\*", r"/a\\\\"),
(r"a\\\\\*", r"/a\\\\*"),
(r"a\+", r"/a+"),
(r"a\\+", r"/a\\"),
(r"a\\\+", r"/a\\+"),
(r"a\\\\+", r"/a\\\\"),
(r"a\\\\\+", r"/a\\\\+"),
(r"\\Aa", r"/\Aa"),
(r"\\\Aa", r"/\\a"),
(r"\\\\Aa", r"/\\\Aa"),
(r"\\\\\Aa", r"/\\\\a"),
(r"\\\\\\Aa", r"/\\\\\Aa"),
(r"a\\Z", r"/a\Z"),
(r"a\\\Z", r"/a\\"),
(r"a\\\\Z", r"/a\\\Z"),
(r"a\\\\\Z", r"/a\\\\"),
(r"a\\\\\\Z", r"/a\\\\\Z"),
# Escaped mixed metacharacters.
(r"^a\?$", r"/a?"),
(r"^a\\?$", r"/a\\"),
(r"^a\\\?$", r"/a\\?"),
(r"^a\\\\?$", r"/a\\\\"),
(r"^a\\\\\?$", r"/a\\\\?"),
# Adjacent escaped metacharacters.
(r"^a\?\$", r"/a?$"),
(r"^a\\?\\$", r"/a\\\\"),
(r"^a\\\?\\\$", r"/a\\?\\$"),
(r"^a\\\\?\\\\$", r"/a\\\\\\\\"),
(r"^a\\\\\?\\\\\$", r"/a\\\\?\\\\$"),
# Complex examples with metacharacters and (un)named groups.
(r"^\b(?P<slug>\w+)\B/(\w+)?", "/<slug>/<var>"),
(r"^\A(?P<slug>\w+)\Z", "/<slug>"),
)
for pattern, output in tests:
with self.subTest(pattern=pattern):
self.assertEqual(simplify_regex(pattern), output)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_docs/models.py | tests/admin_docs/models.py | """
Models for testing various aspects of the django.contrib.admindocs app.
"""
from django.db import models
from django.utils.functional import cached_property
class Company(models.Model):
name = models.CharField(max_length=200)
class Group(models.Model):
name = models.CharField(max_length=200)
class Family(models.Model):
"""
Links with different link text.
This is a line with tag :tag:`extends <built_in-extends>`
This is a line with model :model:`Family <myapp.Family>`
This is a line with view :view:`Index <myapp.views.Index>`
This is a line with template :template:`index template <Index.html>`
This is a line with filter :filter:`example filter <filtername>`
"""
last_name = models.CharField(max_length=200)
class Person(models.Model):
"""
Stores information about a person, related to :model:`myapp.Company`.
**Notes**
Use ``save_changes()`` when saving this object.
``company``
Field storing :model:`myapp.Company` where the person works.
(DESCRIPTION)
.. raw:: html
:file: admin_docs/evilfile.txt
.. include:: admin_docs/evilfile.txt
"""
first_name = models.CharField(max_length=200, help_text="The person's first name")
last_name = models.CharField(max_length=200, help_text="The person's last name")
company = models.ForeignKey(Company, models.CASCADE, help_text="place of work")
family = models.ForeignKey(Family, models.SET_NULL, related_name="+", null=True)
groups = models.ManyToManyField(Group, help_text="has membership")
def _get_full_name(self):
return "%s %s" % (self.first_name, self.last_name)
def rename_company(self, new_name):
self.company.name = new_name
self.company.save()
return new_name
def dummy_function(self, baz, rox, *some_args, **some_kwargs):
return some_kwargs
def dummy_function_keyword_only_arg(self, *, keyword_only_arg):
return keyword_only_arg
def all_kinds_arg_function(self, position_only_arg, /, arg, *, kwarg):
return position_only_arg, arg, kwarg
@property
def a_property(self):
return "a_property"
@cached_property
def a_cached_property(self):
return "a_cached_property"
def suffix_company_name(self, suffix="ltd"):
return self.company.name + suffix
def add_image(self):
pass
def delete_image(self):
pass
def save_changes(self):
pass
def set_status(self):
pass
def get_full_name(self):
"""
Get the full name of the person
"""
return self._get_full_name()
def get_status_count(self):
return 0
def get_groups_list(self):
return []
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_docs/test_middleware.py | tests/admin_docs/test_middleware.py | from django.contrib.auth.models import User
from django.core.exceptions import ImproperlyConfigured
from django.test import override_settings
from .tests import AdminDocsTestCase, TestDataMixin
class XViewMiddlewareTest(TestDataMixin, AdminDocsTestCase):
def test_xview_func(self):
user = User.objects.get(username="super")
response = self.client.head("/xview/func/")
self.assertNotIn("X-View", response)
self.client.force_login(self.superuser)
response = self.client.head("/xview/func/")
self.assertIn("X-View", response)
self.assertEqual(response.headers["X-View"], "admin_docs.views.xview")
user.is_staff = False
user.save()
response = self.client.head("/xview/func/")
self.assertNotIn("X-View", response)
user.is_staff = True
user.is_active = False
user.save()
response = self.client.head("/xview/func/")
self.assertNotIn("X-View", response)
def test_xview_class(self):
user = User.objects.get(username="super")
response = self.client.head("/xview/class/")
self.assertNotIn("X-View", response)
self.client.force_login(self.superuser)
response = self.client.head("/xview/class/")
self.assertIn("X-View", response)
self.assertEqual(response.headers["X-View"], "admin_docs.views.XViewClass")
user.is_staff = False
user.save()
response = self.client.head("/xview/class/")
self.assertNotIn("X-View", response)
user.is_staff = True
user.is_active = False
user.save()
response = self.client.head("/xview/class/")
self.assertNotIn("X-View", response)
def test_callable_object_view(self):
self.client.force_login(self.superuser)
response = self.client.head("/xview/callable_object/")
self.assertEqual(
response.headers["X-View"], "admin_docs.views.XViewCallableObject"
)
@override_settings(MIDDLEWARE=[])
def test_no_auth_middleware(self):
msg = (
"The XView middleware requires authentication middleware to be "
"installed. Edit your MIDDLEWARE setting to insert "
"'django.contrib.auth.middleware.AuthenticationMiddleware'."
)
with self.assertRaisesMessage(ImproperlyConfigured, msg):
self.client.head("/xview/func/")
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_docs/__init__.py | tests/admin_docs/__init__.py | python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false | |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_docs/tests.py | tests/admin_docs/tests.py | from django.contrib.auth.models import User
from django.test import SimpleTestCase, TestCase, modify_settings, override_settings
class TestDataMixin:
@classmethod
def setUpTestData(cls):
cls.superuser = User.objects.create_superuser(
username="super", password="secret", email="super@example.com"
)
@override_settings(ROOT_URLCONF="admin_docs.urls")
@modify_settings(INSTALLED_APPS={"append": "django.contrib.admindocs"})
class AdminDocsSimpleTestCase(SimpleTestCase):
pass
@override_settings(ROOT_URLCONF="admin_docs.urls")
@modify_settings(INSTALLED_APPS={"append": "django.contrib.admindocs"})
class AdminDocsTestCase(TestCase):
pass
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_docs/urls.py | tests/admin_docs/urls.py | from django.contrib import admin
from django.urls import include, path
from . import views
ns_patterns = (
[
path("xview/func/", views.xview_dec(views.xview), name="func"),
],
"test",
)
urlpatterns = [
path("admin/", admin.site.urls),
path("admindocs/", include("django.contrib.admindocs.urls")),
path("", include(ns_patterns, namespace="test")),
path("company/", views.CompanyView.as_view()),
path("xview/func/", views.xview_dec(views.xview)),
path("xview/class/", views.xview_dec(views.XViewClass.as_view())),
path("xview/callable_object/", views.xview_dec(views.XViewCallableObject())),
path("xview/callable_object_without_xview/", views.XViewCallableObject()),
]
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/ordering/models.py | tests/ordering/models.py | """
Specifying ordering
Specify default ordering for a model using the ``ordering`` attribute, which
should be a list or tuple of field names. This tells Django how to order
``QuerySet`` results.
If a field name in ``ordering`` starts with a hyphen, that field will be
ordered in descending order. Otherwise, it'll be ordered in ascending order.
The special-case field name ``"?"`` specifies random order.
The ordering attribute is not required. If you leave it off, ordering will be
undefined -- not random, just undefined.
"""
from django.db import models
class Author(models.Model):
name = models.CharField(max_length=63, null=True, blank=True)
editor = models.ForeignKey("self", models.CASCADE, null=True)
class Meta:
ordering = ("-pk",)
class Article(models.Model):
author = models.ForeignKey(Author, models.SET_NULL, null=True)
second_author = models.ForeignKey(
Author, models.SET_NULL, null=True, related_name="+"
)
headline = models.CharField(max_length=100)
pub_date = models.DateTimeField()
class Meta:
ordering = (
"-pub_date",
models.F("headline"),
models.F("author__name").asc(),
models.OrderBy(models.F("second_author__name")),
)
class OrderedByAuthorArticle(Article):
class Meta:
proxy = True
ordering = ("author", "second_author")
class OrderedByFArticle(Article):
class Meta:
proxy = True
ordering = (models.F("author").asc(nulls_first=True), "id")
class ChildArticle(Article):
pass
class Reference(models.Model):
article = models.ForeignKey(OrderedByAuthorArticle, models.CASCADE)
class Meta:
ordering = ("article",)
class OrderedByExpression(models.Model):
name = models.CharField(max_length=30)
class Meta:
ordering = [models.functions.Lower("name")]
class OrderedByExpressionChild(models.Model):
parent = models.ForeignKey(OrderedByExpression, models.CASCADE)
class Meta:
ordering = ["parent"]
class OrderedByExpressionGrandChild(models.Model):
parent = models.ForeignKey(OrderedByExpressionChild, models.CASCADE)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/ordering/__init__.py | tests/ordering/__init__.py | python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false | |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/ordering/tests.py | tests/ordering/tests.py | from datetime import datetime
from operator import attrgetter
from django.core.exceptions import FieldError
from django.db.models import (
Case,
CharField,
Count,
DateTimeField,
F,
IntegerField,
Max,
OrderBy,
OuterRef,
Subquery,
Value,
When,
)
from django.db.models.functions import Length, Upper
from django.test import TestCase
from .models import (
Article,
Author,
ChildArticle,
OrderedByExpression,
OrderedByExpressionChild,
OrderedByExpressionGrandChild,
OrderedByFArticle,
Reference,
)
class OrderingTests(TestCase):
@classmethod
def setUpTestData(cls):
cls.a1 = Article.objects.create(
headline="Article 1", pub_date=datetime(2005, 7, 26)
)
cls.a2 = Article.objects.create(
headline="Article 2", pub_date=datetime(2005, 7, 27)
)
cls.a3 = Article.objects.create(
headline="Article 3", pub_date=datetime(2005, 7, 27)
)
cls.a4 = Article.objects.create(
headline="Article 4", pub_date=datetime(2005, 7, 28)
)
cls.author_1 = Author.objects.create(name="Name 1")
cls.author_2 = Author.objects.create(name="Name 2")
for i in range(2):
Author.objects.create()
def test_default_ordering(self):
"""
By default, Article.objects.all() orders by pub_date descending, then
headline ascending.
"""
self.assertQuerySetEqual(
Article.objects.all(),
[
"Article 4",
"Article 2",
"Article 3",
"Article 1",
],
attrgetter("headline"),
)
# Getting a single item should work too:
self.assertEqual(Article.objects.all()[0], self.a4)
def test_default_ordering_override(self):
"""
Override ordering with order_by, which is in the same format as the
ordering attribute in models.
"""
self.assertQuerySetEqual(
Article.objects.order_by("headline"),
[
"Article 1",
"Article 2",
"Article 3",
"Article 4",
],
attrgetter("headline"),
)
self.assertQuerySetEqual(
Article.objects.order_by("pub_date", "-headline"),
[
"Article 1",
"Article 3",
"Article 2",
"Article 4",
],
attrgetter("headline"),
)
def test_default_ordering_override_unknown_field(self):
"""
Attempts to override default ordering on related models with an unknown
field should result in an error.
"""
msg = (
"Cannot resolve keyword 'unknown_field' into field. Choices are: "
"article, author, editor, editor_id, id, name"
)
with self.assertRaisesMessage(FieldError, msg):
list(Article.objects.order_by("author__unknown_field"))
def test_order_by_override(self):
"""
Only the last order_by has any effect (since they each override any
previous ordering).
"""
self.assertQuerySetEqual(
Article.objects.order_by("id"),
[
"Article 1",
"Article 2",
"Article 3",
"Article 4",
],
attrgetter("headline"),
)
self.assertQuerySetEqual(
Article.objects.order_by("id").order_by("-headline"),
[
"Article 4",
"Article 3",
"Article 2",
"Article 1",
],
attrgetter("headline"),
)
def test_order_by_nulls_first_and_last(self):
msg = "nulls_first and nulls_last are mutually exclusive"
with self.assertRaisesMessage(ValueError, msg):
Article.objects.order_by(
F("author").desc(nulls_last=True, nulls_first=True)
)
def assertQuerySetEqualReversible(self, queryset, sequence):
self.assertSequenceEqual(queryset, sequence)
self.assertSequenceEqual(queryset.reverse(), list(reversed(sequence)))
def test_order_by_nulls_last(self):
Article.objects.filter(headline="Article 3").update(author=self.author_1)
Article.objects.filter(headline="Article 4").update(author=self.author_2)
# asc and desc are chainable with nulls_last.
self.assertQuerySetEqualReversible(
Article.objects.order_by(F("author").desc(nulls_last=True), "headline"),
[self.a4, self.a3, self.a1, self.a2],
)
self.assertQuerySetEqualReversible(
Article.objects.order_by(F("author").asc(nulls_last=True), "headline"),
[self.a3, self.a4, self.a1, self.a2],
)
self.assertQuerySetEqualReversible(
Article.objects.order_by(
Upper("author__name").desc(nulls_last=True), "headline"
),
[self.a4, self.a3, self.a1, self.a2],
)
self.assertQuerySetEqualReversible(
Article.objects.order_by(
Upper("author__name").asc(nulls_last=True), "headline"
),
[self.a3, self.a4, self.a1, self.a2],
)
self.assertQuerySetEqualReversible(
Article.objects.annotate(upper_name=Upper("author__name")).order_by(
F("upper_name").asc(nulls_last=True), "headline"
),
[self.a3, self.a4, self.a1, self.a2],
)
def test_order_by_nulls_first(self):
Article.objects.filter(headline="Article 3").update(author=self.author_1)
Article.objects.filter(headline="Article 4").update(author=self.author_2)
# asc and desc are chainable with nulls_first.
self.assertQuerySetEqualReversible(
Article.objects.order_by(F("author").asc(nulls_first=True), "headline"),
[self.a1, self.a2, self.a3, self.a4],
)
self.assertQuerySetEqualReversible(
Article.objects.order_by(F("author").desc(nulls_first=True), "headline"),
[self.a1, self.a2, self.a4, self.a3],
)
self.assertQuerySetEqualReversible(
Article.objects.order_by(
Upper("author__name").asc(nulls_first=True), "headline"
),
[self.a1, self.a2, self.a3, self.a4],
)
self.assertQuerySetEqualReversible(
Article.objects.order_by(
Upper("author__name").desc(nulls_first=True), "headline"
),
[self.a1, self.a2, self.a4, self.a3],
)
self.assertQuerySetEqualReversible(
Article.objects.annotate(upper_name=Upper("author__name")).order_by(
F("upper_name").desc(nulls_first=True), "headline"
),
[self.a1, self.a2, self.a4, self.a3],
)
def test_orders_nulls_first_on_filtered_subquery(self):
Article.objects.filter(headline="Article 1").update(author=self.author_1)
Article.objects.filter(headline="Article 2").update(author=self.author_1)
Article.objects.filter(headline="Article 4").update(author=self.author_2)
Author.objects.filter(name__isnull=True).delete()
author_3 = Author.objects.create(name="Name 3")
article_subquery = (
Article.objects.filter(
author=OuterRef("pk"),
headline__icontains="Article",
)
.order_by()
.values("author")
.annotate(
last_date=Max("pub_date"),
)
.values("last_date")
)
self.assertQuerySetEqualReversible(
Author.objects.annotate(
last_date=Subquery(article_subquery, output_field=DateTimeField())
)
.order_by(F("last_date").asc(nulls_first=True))
.distinct(),
[author_3, self.author_1, self.author_2],
)
def test_stop_slicing(self):
"""
Use the 'stop' part of slicing notation to limit the results.
"""
self.assertQuerySetEqual(
Article.objects.order_by("headline")[:2],
[
"Article 1",
"Article 2",
],
attrgetter("headline"),
)
def test_stop_start_slicing(self):
"""
Use the 'stop' and 'start' parts of slicing notation to offset the
result list.
"""
self.assertQuerySetEqual(
Article.objects.order_by("headline")[1:3],
[
"Article 2",
"Article 3",
],
attrgetter("headline"),
)
def test_random_ordering(self):
"""
Use '?' to order randomly.
"""
self.assertEqual(len(list(Article.objects.order_by("?"))), 4)
def test_reversed_ordering(self):
"""
Ordering can be reversed using the reverse() method on a queryset.
This allows you to extract things like "the last two items" (reverse
and then take the first two).
"""
self.assertQuerySetEqual(
Article.objects.reverse()[:2],
[
"Article 1",
"Article 3",
],
attrgetter("headline"),
)
def test_reverse_ordering_pure(self):
qs1 = Article.objects.order_by(F("headline").asc())
qs2 = qs1.reverse()
self.assertQuerySetEqual(
qs2,
[
"Article 4",
"Article 3",
"Article 2",
"Article 1",
],
attrgetter("headline"),
)
self.assertQuerySetEqual(
qs1,
[
"Article 1",
"Article 2",
"Article 3",
"Article 4",
],
attrgetter("headline"),
)
def test_reverse_meta_ordering_pure(self):
Article.objects.create(
headline="Article 5",
pub_date=datetime(2005, 7, 30),
author=self.author_1,
second_author=self.author_2,
)
Article.objects.create(
headline="Article 5",
pub_date=datetime(2005, 7, 30),
author=self.author_2,
second_author=self.author_1,
)
self.assertQuerySetEqual(
Article.objects.filter(headline="Article 5").reverse(),
["Name 2", "Name 1"],
attrgetter("author.name"),
)
self.assertQuerySetEqual(
Article.objects.filter(headline="Article 5"),
["Name 1", "Name 2"],
attrgetter("author.name"),
)
def test_no_reordering_after_slicing(self):
msg = "Cannot reverse a query once a slice has been taken."
qs = Article.objects.all()[0:2]
with self.assertRaisesMessage(TypeError, msg):
qs.reverse()
with self.assertRaisesMessage(TypeError, msg):
qs.last()
def test_extra_ordering(self):
"""
Ordering can be based on fields included from an 'extra' clause
"""
self.assertQuerySetEqual(
Article.objects.extra(
select={"foo": "pub_date"}, order_by=["foo", "headline"]
),
[
"Article 1",
"Article 2",
"Article 3",
"Article 4",
],
attrgetter("headline"),
)
def test_extra_ordering_quoting(self):
"""
If the extra clause uses an SQL keyword for a name, it will be
protected by quoting.
"""
self.assertQuerySetEqual(
Article.objects.extra(
select={"order": "pub_date"}, order_by=["order", "headline"]
),
[
"Article 1",
"Article 2",
"Article 3",
"Article 4",
],
attrgetter("headline"),
)
def test_extra_ordering_with_table_name(self):
self.assertQuerySetEqual(
Article.objects.extra(order_by=["ordering_article.headline"]),
[
"Article 1",
"Article 2",
"Article 3",
"Article 4",
],
attrgetter("headline"),
)
self.assertQuerySetEqual(
Article.objects.extra(order_by=["-ordering_article.headline"]),
[
"Article 4",
"Article 3",
"Article 2",
"Article 1",
],
attrgetter("headline"),
)
def test_order_by_pk(self):
"""
'pk' works as an ordering option in Meta.
"""
self.assertEqual(
[a.pk for a in Author.objects.all()],
[a.pk for a in Author.objects.order_by("-pk")],
)
def test_order_by_fk_attname(self):
"""
ordering by a foreign key by its attribute name prevents the query
from inheriting its related model ordering option (#19195).
"""
authors = list(Author.objects.order_by("id"))
for i in range(1, 5):
author = authors[i - 1]
article = getattr(self, "a%d" % (5 - i))
article.author = author
article.save(update_fields={"author"})
self.assertQuerySetEqual(
Article.objects.order_by("author_id"),
[
"Article 4",
"Article 3",
"Article 2",
"Article 1",
],
attrgetter("headline"),
)
def test_order_by_self_referential_fk(self):
self.a1.author = Author.objects.create(editor=self.author_1)
self.a1.save()
self.a2.author = Author.objects.create(editor=self.author_2)
self.a2.save()
self.assertQuerySetEqual(
Article.objects.filter(author__isnull=False).order_by("author__editor"),
["Article 2", "Article 1"],
attrgetter("headline"),
)
self.assertQuerySetEqual(
Article.objects.filter(author__isnull=False).order_by("author__editor_id"),
["Article 1", "Article 2"],
attrgetter("headline"),
)
def test_order_by_f_expression(self):
self.assertQuerySetEqual(
Article.objects.order_by(F("headline")),
[
"Article 1",
"Article 2",
"Article 3",
"Article 4",
],
attrgetter("headline"),
)
self.assertQuerySetEqual(
Article.objects.order_by(F("headline").asc()),
[
"Article 1",
"Article 2",
"Article 3",
"Article 4",
],
attrgetter("headline"),
)
self.assertQuerySetEqual(
Article.objects.order_by(F("headline").desc()),
[
"Article 4",
"Article 3",
"Article 2",
"Article 1",
],
attrgetter("headline"),
)
def test_order_by_f_expression_duplicates(self):
"""
A column may only be included once (the first occurrence) so we check
to ensure there are no duplicates by inspecting the SQL.
"""
qs = Article.objects.order_by(F("headline").asc(), F("headline").desc())
sql = str(qs.query).upper()
fragment = sql[sql.find("ORDER BY") :]
self.assertEqual(fragment.count("HEADLINE"), 1)
self.assertQuerySetEqual(
qs,
[
"Article 1",
"Article 2",
"Article 3",
"Article 4",
],
attrgetter("headline"),
)
qs = Article.objects.order_by(F("headline").desc(), F("headline").asc())
sql = str(qs.query).upper()
fragment = sql[sql.find("ORDER BY") :]
self.assertEqual(fragment.count("HEADLINE"), 1)
self.assertQuerySetEqual(
qs,
[
"Article 4",
"Article 3",
"Article 2",
"Article 1",
],
attrgetter("headline"),
)
def test_order_by_constant_value(self):
# Order by annotated constant from selected columns.
qs = Article.objects.annotate(
constant=Value("1", output_field=CharField()),
).order_by("constant", "-headline")
self.assertSequenceEqual(qs, [self.a4, self.a3, self.a2, self.a1])
# Order by annotated constant which is out of selected columns.
self.assertSequenceEqual(
qs.values_list("headline", flat=True),
[
"Article 4",
"Article 3",
"Article 2",
"Article 1",
],
)
# Order by constant.
qs = Article.objects.order_by(Value("1", output_field=CharField()), "-headline")
self.assertSequenceEqual(qs, [self.a4, self.a3, self.a2, self.a1])
def test_order_by_case_when_constant_value(self):
qs = Article.objects.order_by(
Case(
When(pk__in=[], then=Value(1)),
default=Value(0),
output_field=IntegerField(),
).desc(),
"pk",
)
self.assertSequenceEqual(qs, [self.a1, self.a2, self.a3, self.a4])
def test_related_ordering_duplicate_table_reference(self):
"""
An ordering referencing a model with an ordering referencing a model
multiple time no circular reference should be detected (#24654).
"""
first_author = Author.objects.create()
second_author = Author.objects.create()
self.a1.author = first_author
self.a1.second_author = second_author
self.a1.save()
self.a2.author = second_author
self.a2.second_author = first_author
self.a2.save()
r1 = Reference.objects.create(article_id=self.a1.pk)
r2 = Reference.objects.create(article_id=self.a2.pk)
self.assertSequenceEqual(Reference.objects.all(), [r2, r1])
def test_default_ordering_by_f_expression(self):
"""F expressions can be used in Meta.ordering."""
articles = OrderedByFArticle.objects.all()
articles.filter(headline="Article 2").update(author=self.author_2)
articles.filter(headline="Article 3").update(author=self.author_1)
self.assertQuerySetEqual(
articles,
["Article 1", "Article 4", "Article 3", "Article 2"],
attrgetter("headline"),
)
def test_order_by_ptr_field_with_default_ordering_by_expression(self):
ca1 = ChildArticle.objects.create(
headline="h2",
pub_date=datetime(2005, 7, 27),
author=self.author_2,
)
ca2 = ChildArticle.objects.create(
headline="h2",
pub_date=datetime(2005, 7, 27),
author=self.author_1,
)
ca3 = ChildArticle.objects.create(
headline="h3",
pub_date=datetime(2005, 7, 27),
author=self.author_1,
)
ca4 = ChildArticle.objects.create(headline="h1", pub_date=datetime(2005, 7, 28))
articles = ChildArticle.objects.order_by("article_ptr")
self.assertSequenceEqual(articles, [ca4, ca2, ca1, ca3])
def test_default_ordering_does_not_affect_group_by(self):
Article.objects.exclude(headline="Article 4").update(author=self.author_1)
Article.objects.filter(headline="Article 4").update(author=self.author_2)
articles = Article.objects.values("author").annotate(count=Count("author"))
self.assertCountEqual(
articles,
[
{"author": self.author_1.pk, "count": 3},
{"author": self.author_2.pk, "count": 1},
],
)
def test_order_by_parent_fk_with_expression_in_default_ordering(self):
p3 = OrderedByExpression.objects.create(name="oBJ 3")
p2 = OrderedByExpression.objects.create(name="OBJ 2")
p1 = OrderedByExpression.objects.create(name="obj 1")
c3 = OrderedByExpressionChild.objects.create(parent=p3)
c2 = OrderedByExpressionChild.objects.create(parent=p2)
c1 = OrderedByExpressionChild.objects.create(parent=p1)
self.assertSequenceEqual(
OrderedByExpressionChild.objects.order_by("parent"),
[c1, c2, c3],
)
def test_order_by_grandparent_fk_with_expression_in_default_ordering(self):
p3 = OrderedByExpression.objects.create(name="oBJ 3")
p2 = OrderedByExpression.objects.create(name="OBJ 2")
p1 = OrderedByExpression.objects.create(name="obj 1")
c3 = OrderedByExpressionChild.objects.create(parent=p3)
c2 = OrderedByExpressionChild.objects.create(parent=p2)
c1 = OrderedByExpressionChild.objects.create(parent=p1)
g3 = OrderedByExpressionGrandChild.objects.create(parent=c3)
g2 = OrderedByExpressionGrandChild.objects.create(parent=c2)
g1 = OrderedByExpressionGrandChild.objects.create(parent=c1)
self.assertSequenceEqual(
OrderedByExpressionGrandChild.objects.order_by("parent"),
[g1, g2, g3],
)
def test_order_by_expression_ref(self):
self.assertQuerySetEqual(
Author.objects.annotate(upper_name=Upper("name")).order_by(
Length("upper_name")
),
Author.objects.order_by(Length(Upper("name"))),
)
def test_ordering_select_related_collision(self):
self.assertEqual(
Article.objects.select_related("author")
.annotate(name=Upper("author__name"))
.filter(pk=self.a1.pk)
.order_by(OrderBy(F("name")))
.first(),
self.a1,
)
self.assertEqual(
Article.objects.select_related("author")
.annotate(name=Upper("author__name"))
.filter(pk=self.a1.pk)
.order_by("name")
.first(),
self.a1,
)
def test_order_by_expr_query_reuse(self):
qs = Author.objects.annotate(num=Count("article")).order_by(
F("num").desc(), "pk"
)
self.assertCountEqual(qs, qs.iterator())
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/get_earliest_or_latest/models.py | tests/get_earliest_or_latest/models.py | from django.db import models
class Article(models.Model):
headline = models.CharField(max_length=100)
pub_date = models.DateField()
expire_date = models.DateField()
class Meta:
get_latest_by = "pub_date"
class Person(models.Model):
name = models.CharField(max_length=30)
birthday = models.DateField()
# Note that this model doesn't have "get_latest_by" set.
class Comment(models.Model):
article = models.ForeignKey(Article, on_delete=models.CASCADE)
likes_count = models.PositiveIntegerField()
# Ticket #23555 - model with an intentionally broken QuerySet.__iter__ method.
class IndexErrorQuerySet(models.QuerySet):
"""
Emulates the case when some internal code raises an unexpected
IndexError.
"""
def __iter__(self):
raise IndexError
class IndexErrorArticle(Article):
objects = IndexErrorQuerySet.as_manager()
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/get_earliest_or_latest/__init__.py | tests/get_earliest_or_latest/__init__.py | python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false | |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/get_earliest_or_latest/tests.py | tests/get_earliest_or_latest/tests.py | from datetime import datetime
from django.db.models import Avg
from django.test import TestCase
from .models import Article, Comment, IndexErrorArticle, Person
class EarliestOrLatestTests(TestCase):
"""Tests for the earliest() and latest() objects methods"""
@classmethod
def setUpClass(cls):
super().setUpClass()
cls._article_get_latest_by = Article._meta.get_latest_by
def tearDown(self):
Article._meta.get_latest_by = self._article_get_latest_by
def test_earliest(self):
# Because no Articles exist yet, earliest() raises ArticleDoesNotExist.
with self.assertRaises(Article.DoesNotExist):
Article.objects.earliest()
a1 = Article.objects.create(
headline="Article 1",
pub_date=datetime(2005, 7, 26),
expire_date=datetime(2005, 9, 1),
)
a2 = Article.objects.create(
headline="Article 2",
pub_date=datetime(2005, 7, 27),
expire_date=datetime(2005, 7, 28),
)
a3 = Article.objects.create(
headline="Article 3",
pub_date=datetime(2005, 7, 28),
expire_date=datetime(2005, 8, 27),
)
a4 = Article.objects.create(
headline="Article 4",
pub_date=datetime(2005, 7, 28),
expire_date=datetime(2005, 7, 30),
)
# Get the earliest Article.
self.assertEqual(Article.objects.earliest(), a1)
# Get the earliest Article that matches certain filters.
self.assertEqual(
Article.objects.filter(pub_date__gt=datetime(2005, 7, 26)).earliest(), a2
)
# Pass a custom field name to earliest() to change the field that's
# used to determine the earliest object.
self.assertEqual(Article.objects.earliest("expire_date"), a2)
self.assertEqual(
Article.objects.filter(pub_date__gt=datetime(2005, 7, 26)).earliest(
"expire_date"
),
a2,
)
# earliest() overrides any other ordering specified on the query.
# Refs #11283.
self.assertEqual(Article.objects.order_by("id").earliest(), a1)
# Error is raised if the user forgot to add a get_latest_by
# in the Model.Meta
Article.objects.model._meta.get_latest_by = None
with self.assertRaisesMessage(
ValueError,
"earliest() and latest() require either fields as positional "
"arguments or 'get_latest_by' in the model's Meta.",
):
Article.objects.earliest()
# Earliest publication date, earliest expire date.
self.assertEqual(
Article.objects.filter(pub_date=datetime(2005, 7, 28)).earliest(
"pub_date", "expire_date"
),
a4,
)
# Earliest publication date, latest expire date.
self.assertEqual(
Article.objects.filter(pub_date=datetime(2005, 7, 28)).earliest(
"pub_date", "-expire_date"
),
a3,
)
# Meta.get_latest_by may be a tuple.
Article.objects.model._meta.get_latest_by = ("pub_date", "expire_date")
self.assertEqual(
Article.objects.filter(pub_date=datetime(2005, 7, 28)).earliest(), a4
)
def test_earliest_sliced_queryset(self):
msg = "Cannot change a query once a slice has been taken."
with self.assertRaisesMessage(TypeError, msg):
Article.objects.all()[0:5].earliest()
def test_latest(self):
# Because no Articles exist yet, latest() raises ArticleDoesNotExist.
with self.assertRaises(Article.DoesNotExist):
Article.objects.latest()
a1 = Article.objects.create(
headline="Article 1",
pub_date=datetime(2005, 7, 26),
expire_date=datetime(2005, 9, 1),
)
a2 = Article.objects.create(
headline="Article 2",
pub_date=datetime(2005, 7, 27),
expire_date=datetime(2005, 7, 28),
)
a3 = Article.objects.create(
headline="Article 3",
pub_date=datetime(2005, 7, 27),
expire_date=datetime(2005, 8, 27),
)
a4 = Article.objects.create(
headline="Article 4",
pub_date=datetime(2005, 7, 28),
expire_date=datetime(2005, 7, 30),
)
# Get the latest Article.
self.assertEqual(Article.objects.latest(), a4)
# Get the latest Article that matches certain filters.
self.assertEqual(
Article.objects.filter(pub_date__lt=datetime(2005, 7, 27)).latest(), a1
)
# Pass a custom field name to latest() to change the field that's used
# to determine the latest object.
self.assertEqual(Article.objects.latest("expire_date"), a1)
self.assertEqual(
Article.objects.filter(pub_date__gt=datetime(2005, 7, 26)).latest(
"expire_date"
),
a3,
)
# latest() overrides any other ordering specified on the query
# (#11283).
self.assertEqual(Article.objects.order_by("id").latest(), a4)
# Error is raised if get_latest_by isn't in Model.Meta.
Article.objects.model._meta.get_latest_by = None
with self.assertRaisesMessage(
ValueError,
"earliest() and latest() require either fields as positional "
"arguments or 'get_latest_by' in the model's Meta.",
):
Article.objects.latest()
# Latest publication date, latest expire date.
self.assertEqual(
Article.objects.filter(pub_date=datetime(2005, 7, 27)).latest(
"pub_date", "expire_date"
),
a3,
)
# Latest publication date, earliest expire date.
self.assertEqual(
Article.objects.filter(pub_date=datetime(2005, 7, 27)).latest(
"pub_date", "-expire_date"
),
a2,
)
# Meta.get_latest_by may be a tuple.
Article.objects.model._meta.get_latest_by = ("pub_date", "expire_date")
self.assertEqual(
Article.objects.filter(pub_date=datetime(2005, 7, 27)).latest(), a3
)
def test_latest_sliced_queryset(self):
msg = "Cannot change a query once a slice has been taken."
with self.assertRaisesMessage(TypeError, msg):
Article.objects.all()[0:5].latest()
def test_latest_manual(self):
# You can still use latest() with a model that doesn't have
# "get_latest_by" set -- just pass in the field name manually.
Person.objects.create(name="Ralph", birthday=datetime(1950, 1, 1))
p2 = Person.objects.create(name="Stephanie", birthday=datetime(1960, 2, 3))
msg = (
"earliest() and latest() require either fields as positional arguments "
"or 'get_latest_by' in the model's Meta."
)
with self.assertRaisesMessage(ValueError, msg):
Person.objects.latest()
self.assertEqual(Person.objects.latest("birthday"), p2)
class TestFirstLast(TestCase):
def test_first(self):
p1 = Person.objects.create(name="Bob", birthday=datetime(1950, 1, 1))
p2 = Person.objects.create(name="Alice", birthday=datetime(1961, 2, 3))
self.assertEqual(Person.objects.first(), p1)
self.assertEqual(Person.objects.order_by("name").first(), p2)
self.assertEqual(
Person.objects.filter(birthday__lte=datetime(1955, 1, 1)).first(), p1
)
self.assertIsNone(
Person.objects.filter(birthday__lte=datetime(1940, 1, 1)).first()
)
def test_last(self):
p1 = Person.objects.create(name="Alice", birthday=datetime(1950, 1, 1))
p2 = Person.objects.create(name="Bob", birthday=datetime(1960, 2, 3))
# Note: by default PK ordering.
self.assertEqual(Person.objects.last(), p2)
self.assertEqual(Person.objects.order_by("-name").last(), p1)
self.assertEqual(
Person.objects.filter(birthday__lte=datetime(1955, 1, 1)).last(), p1
)
self.assertIsNone(
Person.objects.filter(birthday__lte=datetime(1940, 1, 1)).last()
)
def test_index_error_not_suppressed(self):
"""
#23555 -- Unexpected IndexError exceptions in QuerySet iteration
shouldn't be suppressed.
"""
def check():
# We know that we've broken the __iter__ method, so the queryset
# should always raise an exception.
with self.assertRaises(IndexError):
IndexErrorArticle.objects.all()[:10:2]
with self.assertRaises(IndexError):
IndexErrorArticle.objects.first()
with self.assertRaises(IndexError):
IndexErrorArticle.objects.last()
check()
# And it does not matter if there are any records in the DB.
IndexErrorArticle.objects.create(
headline="Article 1",
pub_date=datetime(2005, 7, 26),
expire_date=datetime(2005, 9, 1),
)
check()
def test_first_last_unordered_qs_aggregation_error(self):
a1 = Article.objects.create(
headline="Article 1",
pub_date=datetime(2005, 7, 26),
expire_date=datetime(2005, 9, 1),
)
Comment.objects.create(article=a1, likes_count=5)
qs = Comment.objects.values("article").annotate(avg_likes=Avg("likes_count"))
msg = (
"Cannot use QuerySet.%s() on an unordered queryset performing aggregation. "
"Add an ordering with order_by()."
)
with self.assertRaisesMessage(TypeError, msg % "first"):
qs.first()
with self.assertRaisesMessage(TypeError, msg % "last"):
qs.last()
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/introspection/models.py | tests/introspection/models.py | from django.db import models
class City(models.Model):
id = models.BigAutoField(primary_key=True)
name = models.CharField(max_length=50)
class Country(models.Model):
id = models.SmallAutoField(primary_key=True)
name = models.CharField(max_length=50)
class District(models.Model):
city = models.ForeignKey(City, models.CASCADE, primary_key=True)
name = models.CharField(max_length=50)
class Reporter(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
email = models.EmailField()
facebook_user_id = models.BigIntegerField(null=True)
raw_data = models.BinaryField(null=True)
small_int = models.SmallIntegerField()
interval = models.DurationField()
class Meta:
unique_together = ("first_name", "last_name")
class Article(models.Model):
headline = models.CharField(max_length=100)
pub_date = models.DateField()
body = models.TextField(default="")
reporter = models.ForeignKey(Reporter, models.CASCADE)
response_to = models.ForeignKey("self", models.SET_NULL, null=True)
unmanaged_reporters = models.ManyToManyField(
Reporter, through="ArticleReporter", related_name="+"
)
class Meta:
ordering = ("headline",)
indexes = [
models.Index(fields=["headline", "pub_date"]),
models.Index(fields=["headline", "response_to", "pub_date", "reporter"]),
]
class ArticleReporter(models.Model):
article = models.ForeignKey(Article, models.CASCADE)
reporter = models.ForeignKey(Reporter, models.CASCADE)
class Meta:
managed = False
class Comment(models.Model):
ref = models.UUIDField(unique=True)
article = models.ForeignKey(Article, models.CASCADE, db_index=True)
email = models.EmailField()
pub_date = models.DateTimeField()
body = models.TextField()
class Meta:
constraints = [
models.UniqueConstraint(
fields=["article", "email", "pub_date"],
name="article_email_pub_date_uniq",
),
]
indexes = [
models.Index(fields=["email", "pub_date"], name="email_pub_date_idx"),
]
class CheckConstraintModel(models.Model):
up_votes = models.PositiveIntegerField()
voting_number = models.PositiveIntegerField(unique=True)
class Meta:
required_db_features = {
"supports_table_check_constraints",
}
constraints = [
models.CheckConstraint(
name="up_votes_gte_0_check", condition=models.Q(up_votes__gte=0)
),
]
class UniqueConstraintConditionModel(models.Model):
name = models.CharField(max_length=255)
color = models.CharField(max_length=32, null=True)
class Meta:
required_db_features = {"supports_partial_indexes"}
constraints = [
models.UniqueConstraint(
fields=["name"],
name="cond_name_without_color_uniq",
condition=models.Q(color__isnull=True),
),
]
class DbCommentModel(models.Model):
name = models.CharField(max_length=15, db_comment="'Name' column comment")
class Meta:
db_table_comment = "Custom table comment"
required_db_features = {"supports_comments"}
class DbOnDeleteCascadeModel(models.Model):
fk_do_nothing = models.ForeignKey(Country, on_delete=models.DO_NOTHING)
fk_db_cascade = models.ForeignKey(City, on_delete=models.DB_CASCADE)
class Meta:
required_db_features = {"supports_on_delete_db_cascade"}
class DbOnDeleteSetNullModel(models.Model):
fk_set_null = models.ForeignKey(Reporter, on_delete=models.DB_SET_NULL, null=True)
class Meta:
required_db_features = {"supports_on_delete_db_null"}
class DbOnDeleteSetDefaultModel(models.Model):
fk_db_set_default = models.ForeignKey(
Country, on_delete=models.DB_SET_DEFAULT, db_default=models.Value(1)
)
class Meta:
required_db_features = {"supports_on_delete_db_default"}
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/introspection/__init__.py | tests/introspection/__init__.py | python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false | |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/introspection/tests.py | tests/introspection/tests.py | from django.db import DatabaseError, connection
from django.db.models import DB_CASCADE, DB_SET_DEFAULT, DB_SET_NULL, DO_NOTHING, Index
from django.test import TransactionTestCase, skipUnlessDBFeature
from .models import (
Article,
ArticleReporter,
CheckConstraintModel,
City,
Comment,
Country,
DbCommentModel,
DbOnDeleteCascadeModel,
DbOnDeleteSetDefaultModel,
DbOnDeleteSetNullModel,
District,
Reporter,
UniqueConstraintConditionModel,
)
class IntrospectionTests(TransactionTestCase):
available_apps = ["introspection"]
def test_table_names(self):
tl = connection.introspection.table_names()
self.assertEqual(tl, sorted(tl))
self.assertIn(
Reporter._meta.db_table,
tl,
"'%s' isn't in table_list()." % Reporter._meta.db_table,
)
self.assertIn(
Article._meta.db_table,
tl,
"'%s' isn't in table_list()." % Article._meta.db_table,
)
def test_django_table_names(self):
with connection.cursor() as cursor:
cursor.execute("CREATE TABLE django_ixn_test_table (id INTEGER);")
tl = connection.introspection.django_table_names()
cursor.execute("DROP TABLE django_ixn_test_table;")
self.assertNotIn(
"django_ixn_test_table",
tl,
"django_table_names() returned a non-Django table",
)
def test_django_table_names_retval_type(self):
# Table name is a list #15216
tl = connection.introspection.django_table_names(only_existing=True)
self.assertIs(type(tl), list)
tl = connection.introspection.django_table_names(only_existing=False)
self.assertIs(type(tl), list)
def test_table_names_with_views(self):
with connection.cursor() as cursor:
try:
cursor.execute(
"CREATE VIEW introspection_article_view AS SELECT headline "
"from introspection_article;"
)
except DatabaseError as e:
if "insufficient privileges" in str(e):
self.fail("The test user has no CREATE VIEW privileges")
else:
raise
try:
self.assertIn(
"introspection_article_view",
connection.introspection.table_names(include_views=True),
)
self.assertNotIn(
"introspection_article_view", connection.introspection.table_names()
)
finally:
with connection.cursor() as cursor:
cursor.execute("DROP VIEW introspection_article_view")
def test_unmanaged_through_model(self):
tables = connection.introspection.django_table_names()
self.assertNotIn(ArticleReporter._meta.db_table, tables)
def test_installed_models(self):
tables = [Article._meta.db_table, Reporter._meta.db_table]
models = connection.introspection.installed_models(tables)
self.assertEqual(models, {Article, Reporter})
def test_sequence_list(self):
sequences = connection.introspection.sequence_list()
reporter_seqs = [
seq for seq in sequences if seq["table"] == Reporter._meta.db_table
]
self.assertEqual(
len(reporter_seqs), 1, "Reporter sequence not found in sequence_list()"
)
self.assertEqual(reporter_seqs[0]["column"], "id")
def test_get_table_description_names(self):
with connection.cursor() as cursor:
desc = connection.introspection.get_table_description(
cursor, Reporter._meta.db_table
)
self.assertEqual(
[r[0] for r in desc], [f.column for f in Reporter._meta.fields]
)
def test_get_table_description_types(self):
with connection.cursor() as cursor:
desc = connection.introspection.get_table_description(
cursor, Reporter._meta.db_table
)
self.assertEqual(
[connection.introspection.get_field_type(r[1], r) for r in desc],
[
connection.features.introspected_field_types[field]
for field in (
"BigAutoField",
"CharField",
"CharField",
"CharField",
"BigIntegerField",
"BinaryField",
"SmallIntegerField",
"DurationField",
)
],
)
def test_get_table_description_col_lengths(self):
with connection.cursor() as cursor:
desc = connection.introspection.get_table_description(
cursor, Reporter._meta.db_table
)
self.assertEqual(
[
r[2]
for r in desc
if connection.introspection.get_field_type(r[1], r) == "CharField"
],
[30, 30, 254],
)
def test_get_table_description_nullable(self):
with connection.cursor() as cursor:
desc = connection.introspection.get_table_description(
cursor, Reporter._meta.db_table
)
nullable_by_backend = connection.features.interprets_empty_strings_as_nulls
self.assertEqual(
[r[6] for r in desc],
[
False,
nullable_by_backend,
nullable_by_backend,
nullable_by_backend,
True,
True,
False,
False,
],
)
def test_bigautofield(self):
with connection.cursor() as cursor:
desc = connection.introspection.get_table_description(
cursor, City._meta.db_table
)
self.assertIn(
connection.features.introspected_field_types["BigAutoField"],
[connection.introspection.get_field_type(r[1], r) for r in desc],
)
def test_smallautofield(self):
with connection.cursor() as cursor:
desc = connection.introspection.get_table_description(
cursor, Country._meta.db_table
)
self.assertIn(
connection.features.introspected_field_types["SmallAutoField"],
[connection.introspection.get_field_type(r[1], r) for r in desc],
)
@skipUnlessDBFeature("supports_comments")
def test_db_comments(self):
with connection.cursor() as cursor:
desc = connection.introspection.get_table_description(
cursor, DbCommentModel._meta.db_table
)
table_list = connection.introspection.get_table_list(cursor)
self.assertEqual(
["'Name' column comment"],
[field.comment for field in desc if field.name == "name"],
)
self.assertEqual(
["Custom table comment"],
[
table.comment
for table in table_list
if table.name == "introspection_dbcommentmodel"
],
)
# Regression test for #9991 - 'real' types in postgres
@skipUnlessDBFeature("has_real_datatype")
def test_postgresql_real_type(self):
with connection.cursor() as cursor:
cursor.execute("CREATE TABLE django_ixn_real_test_table (number REAL);")
desc = connection.introspection.get_table_description(
cursor, "django_ixn_real_test_table"
)
cursor.execute("DROP TABLE django_ixn_real_test_table;")
self.assertEqual(
connection.introspection.get_field_type(desc[0][1], desc[0]), "FloatField"
)
@skipUnlessDBFeature("can_introspect_foreign_keys")
def test_get_relations(self):
with connection.cursor() as cursor:
relations = connection.introspection.get_relations(
cursor, Article._meta.db_table
)
if connection.vendor == "mysql" and connection.mysql_is_mariadb:
no_db_on_delete = None
else:
no_db_on_delete = DO_NOTHING
# {field_name: (field_name_other_table, other_table, db_on_delete)}
expected_relations = {
"reporter_id": ("id", Reporter._meta.db_table, no_db_on_delete),
"response_to_id": ("id", Article._meta.db_table, no_db_on_delete),
}
self.assertEqual(relations, expected_relations)
# Removing a field shouldn't disturb get_relations (#17785)
body = Article._meta.get_field("body")
with connection.schema_editor() as editor:
editor.remove_field(Article, body)
with connection.cursor() as cursor:
relations = connection.introspection.get_relations(
cursor, Article._meta.db_table
)
with connection.schema_editor() as editor:
editor.add_field(Article, body)
self.assertEqual(relations, expected_relations)
@skipUnlessDBFeature("can_introspect_foreign_keys", "supports_on_delete_db_cascade")
def test_get_relations_db_on_delete_cascade(self):
with connection.cursor() as cursor:
relations = connection.introspection.get_relations(
cursor, DbOnDeleteCascadeModel._meta.db_table
)
if connection.vendor == "mysql" and connection.mysql_is_mariadb:
no_db_on_delete = None
else:
no_db_on_delete = DO_NOTHING
# {field_name: (field_name_other_table, other_table, db_on_delete)}
expected_relations = {
"fk_db_cascade_id": ("id", City._meta.db_table, DB_CASCADE),
"fk_do_nothing_id": ("id", Country._meta.db_table, no_db_on_delete),
}
self.assertEqual(relations, expected_relations)
@skipUnlessDBFeature("can_introspect_foreign_keys", "supports_on_delete_db_null")
def test_get_relations_db_on_delete_null(self):
with connection.cursor() as cursor:
relations = connection.introspection.get_relations(
cursor, DbOnDeleteSetNullModel._meta.db_table
)
# {field_name: (field_name_other_table, other_table, db_on_delete)}
expected_relations = {
"fk_set_null_id": ("id", Reporter._meta.db_table, DB_SET_NULL),
}
self.assertEqual(relations, expected_relations)
@skipUnlessDBFeature("can_introspect_foreign_keys", "supports_on_delete_db_default")
def test_get_relations_db_on_delete_default(self):
with connection.cursor() as cursor:
relations = connection.introspection.get_relations(
cursor, DbOnDeleteSetDefaultModel._meta.db_table
)
# {field_name: (field_name_other_table, other_table, db_on_delete)}
expected_relations = {
"fk_db_set_default_id": ("id", Country._meta.db_table, DB_SET_DEFAULT),
}
self.assertEqual(relations, expected_relations)
def test_get_primary_key_column(self):
with connection.cursor() as cursor:
primary_key_column = connection.introspection.get_primary_key_column(
cursor, Article._meta.db_table
)
pk_fk_column = connection.introspection.get_primary_key_column(
cursor, District._meta.db_table
)
self.assertEqual(primary_key_column, "id")
self.assertEqual(pk_fk_column, "city_id")
def test_get_constraints_index_types(self):
with connection.cursor() as cursor:
constraints = connection.introspection.get_constraints(
cursor, Article._meta.db_table
)
index = {}
index2 = {}
for val in constraints.values():
if val["columns"] == ["headline", "pub_date"]:
index = val
if val["columns"] == [
"headline",
"response_to_id",
"pub_date",
"reporter_id",
]:
index2 = val
self.assertEqual(index["type"], Index.suffix)
self.assertEqual(index2["type"], Index.suffix)
@skipUnlessDBFeature("supports_index_column_ordering")
def test_get_constraints_indexes_orders(self):
"""
Indexes have the 'orders' key with a list of 'ASC'/'DESC' values.
"""
with connection.cursor() as cursor:
constraints = connection.introspection.get_constraints(
cursor, Article._meta.db_table
)
indexes_verified = 0
expected_columns = [
["headline", "pub_date"],
["headline", "response_to_id", "pub_date", "reporter_id"],
]
if connection.features.indexes_foreign_keys:
expected_columns += [
["reporter_id"],
["response_to_id"],
]
for val in constraints.values():
if val["index"] and not (val["primary_key"] or val["unique"]):
self.assertIn(val["columns"], expected_columns)
self.assertEqual(val["orders"], ["ASC"] * len(val["columns"]))
indexes_verified += 1
self.assertEqual(indexes_verified, len(expected_columns))
@skipUnlessDBFeature("supports_index_column_ordering", "supports_partial_indexes")
def test_get_constraints_unique_indexes_orders(self):
with connection.cursor() as cursor:
constraints = connection.introspection.get_constraints(
cursor,
UniqueConstraintConditionModel._meta.db_table,
)
self.assertIn("cond_name_without_color_uniq", constraints)
constraint = constraints["cond_name_without_color_uniq"]
self.assertIs(constraint["unique"], True)
self.assertEqual(constraint["columns"], ["name"])
self.assertEqual(constraint["orders"], ["ASC"])
def test_get_constraints(self):
def assertDetails(
details,
cols,
primary_key=False,
unique=False,
index=False,
check=False,
foreign_key=None,
):
# Different backends have different values for same constraints:
# PRIMARY KEY UNIQUE CONSTRAINT UNIQUE INDEX
# MySQL pk=1 uniq=1 idx=1 pk=0 uniq=1 idx=1 pk=0 uniq=1 idx=1
# Postgres pk=1 uniq=1 idx=0 pk=0 uniq=1 idx=0 pk=0 uniq=1 idx=1
# SQLite pk=1 uniq=0 idx=0 pk=0 uniq=1 idx=0 pk=0 uniq=1 idx=1
if details["primary_key"]:
details["unique"] = True
if details["unique"]:
details["index"] = False
self.assertEqual(details["columns"], cols)
self.assertEqual(details["primary_key"], primary_key)
self.assertEqual(details["unique"], unique)
self.assertEqual(details["index"], index)
self.assertEqual(details["check"], check)
self.assertEqual(details["foreign_key"], foreign_key)
# Test custom constraints
custom_constraints = {
"article_email_pub_date_uniq",
"email_pub_date_idx",
}
with connection.cursor() as cursor:
constraints = connection.introspection.get_constraints(
cursor, Comment._meta.db_table
)
if (
connection.features.supports_column_check_constraints
and connection.features.can_introspect_check_constraints
):
constraints.update(
connection.introspection.get_constraints(
cursor, CheckConstraintModel._meta.db_table
)
)
custom_constraints.add("up_votes_gte_0_check")
assertDetails(
constraints["up_votes_gte_0_check"], ["up_votes"], check=True
)
assertDetails(
constraints["article_email_pub_date_uniq"],
["article_id", "email", "pub_date"],
unique=True,
)
assertDetails(
constraints["email_pub_date_idx"], ["email", "pub_date"], index=True
)
# Test field constraints
field_constraints = set()
for name, details in constraints.items():
if name in custom_constraints:
continue
elif details["columns"] == ["up_votes"] and details["check"]:
assertDetails(details, ["up_votes"], check=True)
field_constraints.add(name)
elif details["columns"] == ["voting_number"] and details["check"]:
assertDetails(details, ["voting_number"], check=True)
field_constraints.add(name)
elif details["columns"] == ["ref"] and details["unique"]:
assertDetails(details, ["ref"], unique=True)
field_constraints.add(name)
elif details["columns"] == ["voting_number"] and details["unique"]:
assertDetails(details, ["voting_number"], unique=True)
field_constraints.add(name)
elif details["columns"] == ["article_id"] and details["index"]:
assertDetails(details, ["article_id"], index=True)
field_constraints.add(name)
elif details["columns"] == ["id"] and details["primary_key"]:
assertDetails(details, ["id"], primary_key=True, unique=True)
field_constraints.add(name)
elif details["columns"] == ["article_id"] and details["foreign_key"]:
assertDetails(
details, ["article_id"], foreign_key=("introspection_article", "id")
)
field_constraints.add(name)
elif details["check"]:
# Some databases (e.g. Oracle) include additional check
# constraints.
field_constraints.add(name)
# All constraints are accounted for.
self.assertEqual(
constraints.keys() ^ (custom_constraints | field_constraints), set()
)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/proxy_models/admin.py | tests/proxy_models/admin.py | from django.contrib import admin
from .models import ProxyTrackerUser, TrackerUser
site = admin.AdminSite(name="admin_proxy")
site.register(TrackerUser)
site.register(ProxyTrackerUser)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/proxy_models/models.py | tests/proxy_models/models.py | """
By specifying the 'proxy' Meta attribute, model subclasses can specify that
they will take data directly from the table of their base class table rather
than using a new table of their own. This allows them to act as simple proxies,
providing a modified interface to the data from the base class.
"""
from django.db import models
# A couple of managers for testing managing overriding in proxy model cases.
class PersonManager(models.Manager):
def get_queryset(self):
return super().get_queryset().exclude(name="fred")
class SubManager(models.Manager):
def get_queryset(self):
return super().get_queryset().exclude(name="wilma")
class Person(models.Model):
"""
A simple concrete base class.
"""
name = models.CharField(max_length=50)
objects = PersonManager()
def __str__(self):
return self.name
class Abstract(models.Model):
"""
A simple abstract base class, to be used for error checking.
"""
data = models.CharField(max_length=10)
class Meta:
abstract = True
class MyPerson(Person):
"""
A proxy subclass, this should not get a new table. Overrides the default
manager.
"""
class Meta:
proxy = True
ordering = ["name"]
permissions = (("display_users", "May display users information"),)
objects = SubManager()
other = PersonManager()
def has_special_name(self):
return self.name.lower() == "special"
class ManagerMixin(models.Model):
excluder = SubManager()
class Meta:
abstract = True
class OtherPerson(Person, ManagerMixin):
"""
A class with the default manager from Person, plus a secondary manager.
"""
class Meta:
proxy = True
ordering = ["name"]
class StatusPerson(MyPerson):
"""
A non-proxy subclass of a proxy, it should get a new table.
"""
status = models.CharField(max_length=80)
objects = models.Manager()
# We can even have proxies of proxies (and subclass of those).
class MyPersonProxy(MyPerson):
class Meta:
proxy = True
class LowerStatusPerson(MyPersonProxy):
status = models.CharField(max_length=80)
objects = models.Manager()
class User(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
class UserProxy(User):
class Meta:
proxy = True
class AnotherUserProxy(User):
class Meta:
proxy = True
class UserProxyProxy(UserProxy):
class Meta:
proxy = True
class MultiUserProxy(UserProxy, AnotherUserProxy):
class Meta:
proxy = True
# We can still use `select_related()` to include related models in our
# querysets.
class Country(models.Model):
name = models.CharField(max_length=50)
class State(models.Model):
name = models.CharField(max_length=50)
country = models.ForeignKey(Country, models.CASCADE)
def __str__(self):
return self.name
class StateProxy(State):
class Meta:
proxy = True
# Proxy models still works with filters (on related fields)
# and select_related, even when mixed with model inheritance
class BaseUser(models.Model):
name = models.CharField(max_length=255)
def __str__(self):
return ":".join(
(
self.__class__.__name__,
self.name,
)
)
class TrackerUser(BaseUser):
status = models.CharField(max_length=50)
class ProxyTrackerUser(TrackerUser):
class Meta:
proxy = True
class Issue(models.Model):
summary = models.CharField(max_length=255)
assignee = models.ForeignKey(
ProxyTrackerUser, models.CASCADE, related_name="issues"
)
def __str__(self):
return ":".join(
(
self.__class__.__name__,
self.summary,
)
)
class Bug(Issue):
version = models.CharField(max_length=50)
reporter = models.ForeignKey(BaseUser, models.CASCADE)
class ProxyBug(Bug):
"""
Proxy of an inherited class
"""
class Meta:
proxy = True
class ProxyProxyBug(ProxyBug):
"""
A proxy of proxy model with related field
"""
class Meta:
proxy = True
class Improvement(Issue):
"""
A model that has relation to a proxy model
or to a proxy of proxy model
"""
version = models.CharField(max_length=50)
reporter = models.ForeignKey(ProxyTrackerUser, models.CASCADE)
associated_bug = models.ForeignKey(ProxyProxyBug, models.CASCADE)
class ProxyImprovement(Improvement):
class Meta:
proxy = True
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/proxy_models/__init__.py | tests/proxy_models/__init__.py | python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false | |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/proxy_models/tests.py | tests/proxy_models/tests.py | from django.contrib import admin
from django.contrib.auth.models import User as AuthUser
from django.contrib.contenttypes.models import ContentType
from django.core import checks, management
from django.db import DEFAULT_DB_ALIAS, models
from django.db.models import signals
from django.test import TestCase, override_settings
from django.test.utils import isolate_apps
from django.urls import reverse
from .admin import admin as force_admin_model_registration # NOQA
from .models import (
Abstract,
BaseUser,
Bug,
Country,
Improvement,
Issue,
LowerStatusPerson,
MultiUserProxy,
MyPerson,
MyPersonProxy,
OtherPerson,
Person,
ProxyBug,
ProxyImprovement,
ProxyProxyBug,
ProxyTrackerUser,
State,
StateProxy,
StatusPerson,
TrackerUser,
User,
UserProxy,
UserProxyProxy,
)
class ProxyModelTests(TestCase):
def test_same_manager_queries(self):
"""
The MyPerson model should be generating the same database queries as
the Person model (when the same manager is used in each case).
"""
my_person_sql = (
MyPerson.other.all().query.get_compiler(DEFAULT_DB_ALIAS).as_sql()
)
person_sql = (
Person.objects.order_by("name")
.query.get_compiler(DEFAULT_DB_ALIAS)
.as_sql()
)
self.assertEqual(my_person_sql, person_sql)
def test_inheritance_new_table(self):
"""
The StatusPerson models should have its own table (it's using ORM-level
inheritance).
"""
sp_sql = (
StatusPerson.objects.all().query.get_compiler(DEFAULT_DB_ALIAS).as_sql()
)
p_sql = Person.objects.all().query.get_compiler(DEFAULT_DB_ALIAS).as_sql()
self.assertNotEqual(sp_sql, p_sql)
def test_basic_proxy(self):
"""
Creating a Person makes them accessible through the MyPerson proxy.
"""
person = Person.objects.create(name="Foo McBar")
self.assertEqual(len(Person.objects.all()), 1)
self.assertEqual(len(MyPerson.objects.all()), 1)
self.assertEqual(MyPerson.objects.get(name="Foo McBar").id, person.id)
self.assertFalse(MyPerson.objects.get(id=person.id).has_special_name())
def test_no_proxy(self):
"""
Person is not proxied by StatusPerson subclass.
"""
Person.objects.create(name="Foo McBar")
self.assertEqual(list(StatusPerson.objects.all()), [])
def test_basic_proxy_reverse(self):
"""
A new MyPerson also shows up as a standard Person.
"""
MyPerson.objects.create(name="Bazza del Frob")
self.assertEqual(len(MyPerson.objects.all()), 1)
self.assertEqual(len(Person.objects.all()), 1)
LowerStatusPerson.objects.create(status="low", name="homer")
lsps = [lsp.name for lsp in LowerStatusPerson.objects.all()]
self.assertEqual(lsps, ["homer"])
def test_correct_type_proxy_of_proxy(self):
"""
Correct type when querying a proxy of proxy
"""
Person.objects.create(name="Foo McBar")
MyPerson.objects.create(name="Bazza del Frob")
LowerStatusPerson.objects.create(status="low", name="homer")
pp = sorted(mpp.name for mpp in MyPersonProxy.objects.all())
self.assertEqual(pp, ["Bazza del Frob", "Foo McBar", "homer"])
def test_proxy_included_in_ancestors(self):
"""
Proxy models are included in the ancestors for a model's DoesNotExist
and MultipleObjectsReturned
"""
Person.objects.create(name="Foo McBar")
MyPerson.objects.create(name="Bazza del Frob")
LowerStatusPerson.objects.create(status="low", name="homer")
max_id = Person.objects.aggregate(max_id=models.Max("id"))["max_id"]
with self.assertRaises(Person.DoesNotExist):
MyPersonProxy.objects.get(name="Zathras")
with self.assertRaises(Person.MultipleObjectsReturned):
MyPersonProxy.objects.get(id__lt=max_id + 1)
with self.assertRaises(Person.DoesNotExist):
StatusPerson.objects.get(name="Zathras")
StatusPerson.objects.create(name="Bazza Jr.")
StatusPerson.objects.create(name="Foo Jr.")
max_id = Person.objects.aggregate(max_id=models.Max("id"))["max_id"]
with self.assertRaises(Person.MultipleObjectsReturned):
StatusPerson.objects.get(id__lt=max_id + 1)
def test_abstract_base_with_model_fields(self):
msg = (
"Abstract base class containing model fields not permitted for proxy model "
"'NoAbstract'."
)
with self.assertRaisesMessage(TypeError, msg):
class NoAbstract(Abstract):
class Meta:
proxy = True
def test_too_many_concrete_classes(self):
msg = (
"Proxy model 'TooManyBases' has more than one non-abstract model base "
"class."
)
with self.assertRaisesMessage(TypeError, msg):
class TooManyBases(User, Person):
class Meta:
proxy = True
def test_no_base_classes(self):
msg = "Proxy model 'NoBaseClasses' has no non-abstract model base class."
with self.assertRaisesMessage(TypeError, msg):
class NoBaseClasses(models.Model):
class Meta:
proxy = True
@isolate_apps("proxy_models")
def test_new_fields(self):
class NoNewFields(Person):
newfield = models.BooleanField()
class Meta:
proxy = True
errors = NoNewFields.check()
expected = [
checks.Error(
"Proxy model 'NoNewFields' contains model fields.",
id="models.E017",
)
]
self.assertEqual(errors, expected)
@override_settings(TEST_SWAPPABLE_MODEL="proxy_models.AlternateModel")
@isolate_apps("proxy_models")
def test_swappable(self):
class SwappableModel(models.Model):
class Meta:
swappable = "TEST_SWAPPABLE_MODEL"
class AlternateModel(models.Model):
pass
# You can't proxy a swapped model
with self.assertRaises(TypeError):
class ProxyModel(SwappableModel):
class Meta:
proxy = True
def test_myperson_manager(self):
Person.objects.create(name="fred")
Person.objects.create(name="wilma")
Person.objects.create(name="barney")
resp = [p.name for p in MyPerson.objects.all()]
self.assertEqual(resp, ["barney", "fred"])
resp = [p.name for p in MyPerson._default_manager.all()]
self.assertEqual(resp, ["barney", "fred"])
def test_otherperson_manager(self):
Person.objects.create(name="fred")
Person.objects.create(name="wilma")
Person.objects.create(name="barney")
resp = [p.name for p in OtherPerson.objects.all()]
self.assertEqual(resp, ["barney", "wilma"])
resp = [p.name for p in OtherPerson.excluder.all()]
self.assertEqual(resp, ["barney", "fred"])
resp = [p.name for p in OtherPerson._default_manager.all()]
self.assertEqual(resp, ["barney", "wilma"])
def test_permissions_created(self):
from django.contrib.auth.models import Permission
Permission.objects.get(name="May display users information")
def test_proxy_model_signals(self):
"""
Test save signals for proxy models
"""
output = []
def make_handler(model, event):
def _handler(*args, **kwargs):
output.append("%s %s save" % (model, event))
return _handler
h1 = make_handler("MyPerson", "pre")
h2 = make_handler("MyPerson", "post")
h3 = make_handler("Person", "pre")
h4 = make_handler("Person", "post")
signals.pre_save.connect(h1, sender=MyPerson)
signals.post_save.connect(h2, sender=MyPerson)
signals.pre_save.connect(h3, sender=Person)
signals.post_save.connect(h4, sender=Person)
MyPerson.objects.create(name="dino")
self.assertEqual(output, ["MyPerson pre save", "MyPerson post save"])
output = []
h5 = make_handler("MyPersonProxy", "pre")
h6 = make_handler("MyPersonProxy", "post")
signals.pre_save.connect(h5, sender=MyPersonProxy)
signals.post_save.connect(h6, sender=MyPersonProxy)
MyPersonProxy.objects.create(name="pebbles")
self.assertEqual(output, ["MyPersonProxy pre save", "MyPersonProxy post save"])
signals.pre_save.disconnect(h1, sender=MyPerson)
signals.post_save.disconnect(h2, sender=MyPerson)
signals.pre_save.disconnect(h3, sender=Person)
signals.post_save.disconnect(h4, sender=Person)
signals.pre_save.disconnect(h5, sender=MyPersonProxy)
signals.post_save.disconnect(h6, sender=MyPersonProxy)
def test_content_type(self):
ctype = ContentType.objects.get_for_model
self.assertIs(ctype(Person), ctype(OtherPerson))
def test_user_proxy_models(self):
User.objects.create(name="Bruce")
resp = [u.name for u in User.objects.all()]
self.assertEqual(resp, ["Bruce"])
resp = [u.name for u in UserProxy.objects.all()]
self.assertEqual(resp, ["Bruce"])
resp = [u.name for u in UserProxyProxy.objects.all()]
self.assertEqual(resp, ["Bruce"])
self.assertEqual([u.name for u in MultiUserProxy.objects.all()], ["Bruce"])
def test_proxy_for_model(self):
self.assertEqual(UserProxy, UserProxyProxy._meta.proxy_for_model)
def test_concrete_model(self):
self.assertEqual(User, UserProxyProxy._meta.concrete_model)
def test_proxy_delete(self):
"""
Proxy objects can be deleted
"""
User.objects.create(name="Bruce")
u2 = UserProxy.objects.create(name="George")
resp = [u.name for u in UserProxy.objects.all()]
self.assertEqual(resp, ["Bruce", "George"])
u2.delete()
resp = [u.name for u in UserProxy.objects.all()]
self.assertEqual(resp, ["Bruce"])
def test_proxy_update(self):
user = User.objects.create(name="Bruce")
with self.assertNumQueries(1):
UserProxy.objects.filter(id=user.id).update(name="George")
user.refresh_from_db()
self.assertEqual(user.name, "George")
def test_select_related(self):
"""
We can still use `select_related()` to include related models in our
querysets.
"""
country = Country.objects.create(name="Australia")
State.objects.create(name="New South Wales", country=country)
resp = [s.name for s in State.objects.select_related()]
self.assertEqual(resp, ["New South Wales"])
resp = [s.name for s in StateProxy.objects.select_related()]
self.assertEqual(resp, ["New South Wales"])
self.assertEqual(
StateProxy.objects.get(name="New South Wales").name, "New South Wales"
)
resp = StateProxy.objects.select_related().get(name="New South Wales")
self.assertEqual(resp.name, "New South Wales")
def test_filter_proxy_relation_reverse(self):
tu = TrackerUser.objects.create(name="Contributor", status="contrib")
ptu = ProxyTrackerUser.objects.get()
issue = Issue.objects.create(assignee=tu)
self.assertEqual(tu.issues.get(), issue)
self.assertEqual(ptu.issues.get(), issue)
self.assertSequenceEqual(TrackerUser.objects.filter(issues=issue), [tu])
self.assertSequenceEqual(ProxyTrackerUser.objects.filter(issues=issue), [ptu])
def test_proxy_bug(self):
contributor = ProxyTrackerUser.objects.create(
name="Contributor", status="contrib"
)
someone = BaseUser.objects.create(name="Someone")
Bug.objects.create(
summary="fix this",
version="1.1beta",
assignee=contributor,
reporter=someone,
)
pcontributor = ProxyTrackerUser.objects.create(
name="OtherContributor", status="proxy"
)
Improvement.objects.create(
summary="improve that",
version="1.1beta",
assignee=contributor,
reporter=pcontributor,
associated_bug=ProxyProxyBug.objects.all()[0],
)
# Related field filter on proxy
resp = ProxyBug.objects.get(version__icontains="beta")
self.assertEqual(repr(resp), "<ProxyBug: ProxyBug:fix this>")
# Select related + filter on proxy
resp = ProxyBug.objects.select_related().get(version__icontains="beta")
self.assertEqual(repr(resp), "<ProxyBug: ProxyBug:fix this>")
# Proxy of proxy, select_related + filter
resp = ProxyProxyBug.objects.select_related().get(version__icontains="beta")
self.assertEqual(repr(resp), "<ProxyProxyBug: ProxyProxyBug:fix this>")
# Select related + filter on a related proxy field
resp = ProxyImprovement.objects.select_related().get(
reporter__name__icontains="butor"
)
self.assertEqual(
repr(resp), "<ProxyImprovement: ProxyImprovement:improve that>"
)
# Select related + filter on a related proxy of proxy field
resp = ProxyImprovement.objects.select_related().get(
associated_bug__summary__icontains="fix"
)
self.assertEqual(
repr(resp), "<ProxyImprovement: ProxyImprovement:improve that>"
)
def test_proxy_load_from_fixture(self):
management.call_command("loaddata", "mypeople.json", verbosity=0)
p = MyPerson.objects.get(pk=100)
self.assertEqual(p.name, "Elvis Presley")
def test_select_related_only(self):
user = ProxyTrackerUser.objects.create(name="Joe Doe", status="test")
issue = Issue.objects.create(summary="New issue", assignee=user)
qs = Issue.objects.select_related("assignee").only("assignee__status")
self.assertEqual(qs.get(), issue)
def test_eq(self):
self.assertEqual(MyPerson(id=100), Person(id=100))
@override_settings(ROOT_URLCONF="proxy_models.urls")
class ProxyModelAdminTests(TestCase):
@classmethod
def setUpTestData(cls):
cls.superuser = AuthUser.objects.create(is_superuser=True, is_staff=True)
cls.tu1 = ProxyTrackerUser.objects.create(name="Django Pony", status="emperor")
cls.i1 = Issue.objects.create(summary="Pony's Issue", assignee=cls.tu1)
def test_cascade_delete_proxy_model_admin_warning(self):
"""
Test if admin gives warning about cascade deleting models referenced
to concrete model by deleting proxy object.
"""
tracker_user = TrackerUser.objects.all()[0]
base_user = BaseUser.objects.all()[0]
issue = Issue.objects.all()[0]
with self.assertNumQueries(6):
collector = admin.utils.NestedObjects("default")
collector.collect(ProxyTrackerUser.objects.all())
self.assertIn(tracker_user, collector.edges.get(None, ()))
self.assertIn(base_user, collector.edges.get(None, ()))
self.assertIn(issue, collector.edges.get(tracker_user, ()))
def test_delete_str_in_model_admin(self):
"""
Test if the admin delete page shows the correct string representation
for a proxy model.
"""
user = TrackerUser.objects.get(name="Django Pony")
proxy = ProxyTrackerUser.objects.get(name="Django Pony")
user_str = 'Tracker user: <a href="%s">%s</a>' % (
reverse("admin_proxy:proxy_models_trackeruser_change", args=(user.pk,)),
user,
)
proxy_str = 'Proxy tracker user: <a href="%s">%s</a>' % (
reverse(
"admin_proxy:proxy_models_proxytrackeruser_change", args=(proxy.pk,)
),
proxy,
)
self.client.force_login(self.superuser)
response = self.client.get(
reverse("admin_proxy:proxy_models_trackeruser_delete", args=(user.pk,))
)
delete_str = response.context["deleted_objects"][0]
self.assertEqual(delete_str, user_str)
response = self.client.get(
reverse(
"admin_proxy:proxy_models_proxytrackeruser_delete", args=(proxy.pk,)
)
)
delete_str = response.context["deleted_objects"][0]
self.assertEqual(delete_str, proxy_str)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/proxy_models/urls.py | tests/proxy_models/urls.py | from django.urls import path
from .admin import site
urlpatterns = [
path("admin/", site.urls),
]
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/force_insert_update/models.py | tests/force_insert_update/models.py | """
Tests for forcing insert and update queries (instead of Django's normal
automatic behavior).
"""
from django.db import models
class Counter(models.Model):
name = models.CharField(max_length=10)
value = models.IntegerField()
class InheritedCounter(Counter):
tag = models.CharField(max_length=10)
class ProxyCounter(Counter):
class Meta:
proxy = True
class SubCounter(Counter):
pass
class SubSubCounter(SubCounter):
pass
class WithCustomPK(models.Model):
name = models.IntegerField(primary_key=True)
value = models.IntegerField()
class OtherSubCounter(Counter):
other_counter_ptr = models.OneToOneField(
Counter, primary_key=True, parent_link=True, on_delete=models.CASCADE
)
class DiamondSubSubCounter(SubCounter, OtherSubCounter):
pass
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/force_insert_update/__init__.py | tests/force_insert_update/__init__.py | python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false | |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/force_insert_update/tests.py | tests/force_insert_update/tests.py | from django.core.exceptions import ObjectNotUpdated
from django.db import DatabaseError, IntegrityError, models, transaction
from django.test import TestCase
from .models import (
Counter,
DiamondSubSubCounter,
InheritedCounter,
OtherSubCounter,
ProxyCounter,
SubCounter,
SubSubCounter,
WithCustomPK,
)
class ForceTests(TestCase):
def test_force_update(self):
c = Counter.objects.create(name="one", value=1)
# The normal case
c.value = 2
c.save()
# Same thing, via an update
c.value = 3
c.save(force_update=True)
# Won't work because force_update and force_insert are mutually
# exclusive
c.value = 4
msg = "Cannot force both insert and updating in model saving."
with self.assertRaisesMessage(ValueError, msg):
c.save(force_insert=True, force_update=True)
# Try to update something that doesn't have a primary key in the first
# place.
c1 = Counter(name="two", value=2)
msg = "Cannot force an update in save() with no primary key."
with self.assertRaisesMessage(ValueError, msg):
with transaction.atomic():
c1.save(force_update=True)
c1.save(force_insert=True)
# Won't work because we can't insert a pk of the same value.
c.value = 5
with self.assertRaises(IntegrityError):
with transaction.atomic():
c.save(force_insert=True)
# Trying to update should still fail, even with manual primary keys, if
# the data isn't in the database already.
obj = WithCustomPK(name=1, value=1)
msg = "Forced update did not affect any rows."
# Make sure backward compatibility with DatabaseError is preserved.
exceptions = [DatabaseError, ObjectNotUpdated, WithCustomPK.NotUpdated]
for exception in exceptions:
with (
self.subTest(exception),
self.assertRaisesMessage(DatabaseError, msg),
transaction.atomic(),
):
obj.save(force_update=True)
class InheritanceTests(TestCase):
def test_force_update_on_inherited_model(self):
a = InheritedCounter(name="count", value=1, tag="spam")
a.save()
a.save(force_update=True)
def test_force_update_on_proxy_model(self):
a = ProxyCounter(name="count", value=1)
a.save()
a.save(force_update=True)
def test_force_update_on_inherited_model_without_fields(self):
"""
Issue 13864: force_update fails on subclassed models, if they don't
specify custom fields.
"""
a = SubCounter(name="count", value=1)
a.save()
a.value = 2
a.save(force_update=True)
class ForceInsertInheritanceTests(TestCase):
def test_force_insert_not_bool_or_tuple(self):
msg = "force_insert must be a bool or tuple."
with self.assertRaisesMessage(TypeError, msg), transaction.atomic():
Counter().save(force_insert=1)
with self.assertRaisesMessage(TypeError, msg), transaction.atomic():
Counter().save(force_insert="test")
with self.assertRaisesMessage(TypeError, msg), transaction.atomic():
Counter().save(force_insert=[])
def test_force_insert_not_model(self):
msg = f"Invalid force_insert member. {object!r} must be a model subclass."
with self.assertRaisesMessage(TypeError, msg), transaction.atomic():
Counter().save(force_insert=(object,))
instance = Counter()
msg = f"Invalid force_insert member. {instance!r} must be a model subclass."
with self.assertRaisesMessage(TypeError, msg), transaction.atomic():
Counter().save(force_insert=(instance,))
def test_force_insert_not_base(self):
msg = "Invalid force_insert member. SubCounter must be a base of Counter."
with self.assertRaisesMessage(TypeError, msg):
Counter().save(force_insert=(SubCounter,))
def test_force_insert_false(self):
with self.assertNumQueries(3):
obj = SubCounter.objects.create(pk=1, value=0)
with self.assertNumQueries(2):
SubCounter(pk=obj.pk, value=1).save()
obj.refresh_from_db()
self.assertEqual(obj.value, 1)
with self.assertNumQueries(2):
SubCounter(pk=obj.pk, value=2).save(force_insert=False)
obj.refresh_from_db()
self.assertEqual(obj.value, 2)
with self.assertNumQueries(2):
SubCounter(pk=obj.pk, value=3).save(force_insert=())
obj.refresh_from_db()
self.assertEqual(obj.value, 3)
def test_force_insert_false_with_existing_parent(self):
parent = Counter.objects.create(pk=1, value=1)
with self.assertNumQueries(2):
SubCounter.objects.create(pk=parent.pk, value=2)
def test_force_insert_parent(self):
with self.assertNumQueries(3):
SubCounter(pk=1, value=1).save(force_insert=True)
# Force insert a new parent and don't UPDATE first.
with self.assertNumQueries(2):
SubCounter(pk=2, value=1).save(force_insert=(Counter,))
with self.assertNumQueries(2):
SubCounter(pk=3, value=1).save(force_insert=(models.Model,))
def test_force_insert_with_grandparent(self):
with self.assertNumQueries(4):
SubSubCounter(pk=1, value=1).save(force_insert=True)
# Force insert parents on all levels and don't UPDATE first.
with self.assertNumQueries(3):
SubSubCounter(pk=2, value=1).save(force_insert=(models.Model,))
with self.assertNumQueries(3):
SubSubCounter(pk=3, value=1).save(force_insert=(Counter,))
# Force insert only the last parent.
with self.assertNumQueries(4):
SubSubCounter(pk=4, value=1).save(force_insert=(SubCounter,))
def test_force_insert_with_existing_grandparent(self):
# Force insert only the last child.
grandparent = Counter.objects.create(pk=1, value=1)
with self.assertNumQueries(4):
SubSubCounter(pk=grandparent.pk, value=1).save(force_insert=True)
# Force insert a parent, and don't force insert a grandparent.
grandparent = Counter.objects.create(pk=2, value=1)
with self.assertNumQueries(3):
SubSubCounter(pk=grandparent.pk, value=1).save(force_insert=(SubCounter,))
# Force insert parents on all levels, grandparent conflicts.
grandparent = Counter.objects.create(pk=3, value=1)
with self.assertRaises(IntegrityError), transaction.atomic():
SubSubCounter(pk=grandparent.pk, value=1).save(force_insert=(Counter,))
def test_force_insert_diamond_mti(self):
# Force insert all parents.
with self.assertNumQueries(4):
DiamondSubSubCounter(pk=1, value=1).save(
force_insert=(Counter, SubCounter, OtherSubCounter)
)
with self.assertNumQueries(4):
DiamondSubSubCounter(pk=2, value=1).save(force_insert=(models.Model,))
# Force insert parents, and don't force insert a common grandparent.
with self.assertNumQueries(5):
DiamondSubSubCounter(pk=3, value=1).save(
force_insert=(SubCounter, OtherSubCounter)
)
grandparent = Counter.objects.create(pk=4, value=1)
with self.assertNumQueries(4):
DiamondSubSubCounter(pk=grandparent.pk, value=1).save(
force_insert=(SubCounter, OtherSubCounter),
)
# Force insert all parents, grandparent conflicts.
grandparent = Counter.objects.create(pk=5, value=1)
with self.assertRaises(IntegrityError), transaction.atomic():
DiamondSubSubCounter(pk=grandparent.pk, value=1).save(
force_insert=(models.Model,)
)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/bash_completion/__init__.py | tests/bash_completion/__init__.py | python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false | |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/bash_completion/tests.py | tests/bash_completion/tests.py | """
A series of tests to establish that the command-line bash completion works.
"""
import os
import sys
import unittest
from django.apps import apps
from django.core.management import ManagementUtility
from django.test.utils import captured_stdout
class BashCompletionTests(unittest.TestCase):
"""
Testing the Python level bash completion code.
This requires setting up the environment as if we got passed data
from bash.
"""
def setUp(self):
self.old_DJANGO_AUTO_COMPLETE = os.environ.get("DJANGO_AUTO_COMPLETE")
os.environ["DJANGO_AUTO_COMPLETE"] = "1"
def tearDown(self):
if self.old_DJANGO_AUTO_COMPLETE:
os.environ["DJANGO_AUTO_COMPLETE"] = self.old_DJANGO_AUTO_COMPLETE
else:
del os.environ["DJANGO_AUTO_COMPLETE"]
def _user_input(self, input_str):
"""
Set the environment and the list of command line arguments.
This sets the bash variables $COMP_WORDS and $COMP_CWORD. The former is
an array consisting of the individual words in the current command
line, the latter is the index of the current cursor position, so in
case a word is completed and the cursor is placed after a whitespace,
$COMP_CWORD must be incremented by 1:
* 'django-admin start' -> COMP_CWORD=1
* 'django-admin startproject' -> COMP_CWORD=1
* 'django-admin startproject ' -> COMP_CWORD=2
"""
os.environ["COMP_WORDS"] = input_str
idx = len(input_str.split(" ")) - 1 # Index of the last word
comp_cword = idx + 1 if input_str.endswith(" ") else idx
os.environ["COMP_CWORD"] = str(comp_cword)
sys.argv = input_str.split()
def _run_autocomplete(self):
util = ManagementUtility(argv=sys.argv)
with captured_stdout() as stdout:
try:
util.autocomplete()
except SystemExit:
pass
return stdout.getvalue().strip().split("\n")
def test_django_admin_py(self):
"django_admin.py will autocomplete option flags"
self._user_input("django-admin sqlmigrate --verb")
output = self._run_autocomplete()
self.assertEqual(output, ["--verbosity="])
def test_manage_py(self):
"manage.py will autocomplete option flags"
self._user_input("manage.py sqlmigrate --verb")
output = self._run_autocomplete()
self.assertEqual(output, ["--verbosity="])
def test_custom_command(self):
"A custom command can autocomplete option flags"
self._user_input("django-admin test_command --l")
output = self._run_autocomplete()
self.assertEqual(output, ["--list"])
def test_subcommands(self):
"Subcommands can be autocompleted"
self._user_input("django-admin sql")
output = self._run_autocomplete()
self.assertEqual(output, ["sqlflush sqlmigrate sqlsequencereset"])
def test_completed_subcommand(self):
"Show option flags in case a subcommand is completed"
self._user_input("django-admin startproject ") # Trailing whitespace
output = self._run_autocomplete()
for item in output:
self.assertTrue(item.startswith("--"))
def test_help(self):
"No errors, just an empty list if there are no autocomplete options"
self._user_input("django-admin help --")
output = self._run_autocomplete()
self.assertEqual(output, [""])
def test_app_completion(self):
"Application names will be autocompleted for an AppCommand"
self._user_input("django-admin sqlmigrate a")
output = self._run_autocomplete()
a_labels = sorted(
app_config.label
for app_config in apps.get_app_configs()
if app_config.label.startswith("a")
)
self.assertEqual(output, a_labels)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/bash_completion/management/__init__.py | tests/bash_completion/management/__init__.py | python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false | |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/bash_completion/management/commands/test_command.py | tests/bash_completion/management/commands/test_command.py | from django.core.management.base import BaseCommand
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument("--list", action="store_true", help="Print all options")
def handle(self, *args, **options):
pass
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/bash_completion/management/commands/__init__.py | tests/bash_completion/management/commands/__init__.py | python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false | |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/custom_columns/models.py | tests/custom_columns/models.py | """
Custom column/table names
If your database column name is different than your model attribute, use the
``db_column`` parameter. Note that you'll use the field's name, not its column
name, in API usage.
If your database table name is different than your model name, use the
``db_table`` Meta attribute. This has no effect on the API used to
query the database.
If you need to use a table name for a many-to-many relationship that differs
from the default generated name, use the ``db_table`` parameter on the
``ManyToManyField``. This has no effect on the API for querying the database.
"""
from django.db import models
class Author(models.Model):
Author_ID = models.AutoField(primary_key=True, db_column="Author ID")
first_name = models.CharField(max_length=30, db_column="firstname")
last_name = models.CharField(max_length=30, db_column="last")
class Meta:
db_table = "my_author_table"
ordering = ("last_name", "first_name")
def __str__(self):
return "%s %s" % (self.first_name, self.last_name)
class Article(models.Model):
Article_ID = models.AutoField(primary_key=True, db_column="Article ID")
headline = models.CharField(max_length=100)
authors = models.ManyToManyField(Author, db_table="my_m2m_table")
primary_author = models.ForeignKey(
Author,
models.SET_NULL,
db_column="Author ID",
related_name="primary_set",
null=True,
)
class Meta:
ordering = ("headline",)
def __str__(self):
return self.headline
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/custom_columns/__init__.py | tests/custom_columns/__init__.py | python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false | |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/custom_columns/tests.py | tests/custom_columns/tests.py | from django.core.exceptions import FieldError
from django.test import TestCase
from .models import Article, Author
class CustomColumnsTests(TestCase):
@classmethod
def setUpTestData(cls):
cls.a1 = Author.objects.create(first_name="John", last_name="Smith")
cls.a2 = Author.objects.create(first_name="Peter", last_name="Jones")
cls.authors = [cls.a1, cls.a2]
cls.article = Article.objects.create(
headline="Django lets you build web apps easily", primary_author=cls.a1
)
cls.article.authors.set(cls.authors)
def test_query_all_available_authors(self):
self.assertSequenceEqual(Author.objects.all(), [self.a2, self.a1])
def test_get_first_name(self):
self.assertEqual(
Author.objects.get(first_name__exact="John"),
self.a1,
)
def test_filter_first_name(self):
self.assertSequenceEqual(
Author.objects.filter(first_name__exact="John"),
[self.a1],
)
def test_field_error(self):
msg = (
"Cannot resolve keyword 'firstname' into field. Choices are: "
"Author_ID, article, first_name, last_name, primary_set"
)
with self.assertRaisesMessage(FieldError, msg):
Author.objects.filter(firstname__exact="John")
def test_attribute_error(self):
with self.assertRaises(AttributeError):
self.a1.firstname
with self.assertRaises(AttributeError):
self.a1.last
def test_get_all_authors_for_an_article(self):
self.assertSequenceEqual(self.article.authors.all(), [self.a2, self.a1])
def test_get_all_articles_for_an_author(self):
self.assertQuerySetEqual(
self.a1.article_set.all(),
[
"Django lets you build web apps easily",
],
lambda a: a.headline,
)
def test_get_author_m2m_relation(self):
self.assertSequenceEqual(
self.article.authors.filter(last_name="Jones"), [self.a2]
)
def test_author_querying(self):
self.assertSequenceEqual(
Author.objects.order_by("last_name"),
[self.a2, self.a1],
)
def test_author_filtering(self):
self.assertSequenceEqual(
Author.objects.filter(first_name__exact="John"),
[self.a1],
)
def test_author_get(self):
self.assertEqual(self.a1, Author.objects.get(first_name__exact="John"))
def test_filter_on_nonexistent_field(self):
msg = (
"Cannot resolve keyword 'firstname' into field. Choices are: "
"Author_ID, article, first_name, last_name, primary_set"
)
with self.assertRaisesMessage(FieldError, msg):
Author.objects.filter(firstname__exact="John")
def test_author_get_attributes(self):
a = Author.objects.get(last_name__exact="Smith")
self.assertEqual("John", a.first_name)
self.assertEqual("Smith", a.last_name)
with self.assertRaisesMessage(
AttributeError, "'Author' object has no attribute 'firstname'"
):
getattr(a, "firstname")
with self.assertRaisesMessage(
AttributeError, "'Author' object has no attribute 'last'"
):
getattr(a, "last")
def test_m2m_table(self):
self.assertSequenceEqual(
self.article.authors.order_by("last_name"),
[self.a2, self.a1],
)
self.assertSequenceEqual(self.a1.article_set.all(), [self.article])
self.assertSequenceEqual(
self.article.authors.filter(last_name="Jones"),
[self.a2],
)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.