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/app_loading/not_installed/__init__.py | tests/app_loading/not_installed/__init__.py | python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false | |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/transactions/models.py | tests/transactions/models.py | """
Transactions
Django handles transactions in three different ways. The default is to commit
each transaction upon a write, but you can decorate a function to get
commit-on-success behavior. Alternatively, you can manage the transaction
manually.
"""
from django.db import models
class Reporter(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
email = models.EmailField()
class Meta:
ordering = ("first_name", "last_name")
def __str__(self):
return ("%s %s" % (self.first_name, self.last_name)).strip()
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/transactions/__init__.py | tests/transactions/__init__.py | python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false | |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/transactions/tests.py | tests/transactions/tests.py | import sys
import threading
import time
from unittest import skipIf, skipUnless
from django.db import (
DatabaseError,
Error,
IntegrityError,
OperationalError,
connection,
transaction,
)
from django.test import (
TestCase,
TransactionTestCase,
skipIfDBFeature,
skipUnlessDBFeature,
)
from .models import Reporter
@skipUnlessDBFeature("uses_savepoints")
class AtomicTests(TransactionTestCase):
"""
Tests for the atomic decorator and context manager.
The tests make assertions on internal attributes because there isn't a
robust way to ask the database for its current transaction state.
Since the decorator syntax is converted into a context manager (see the
implementation), there are only a few basic tests with the decorator
syntax and the bulk of the tests use the context manager syntax.
"""
available_apps = ["transactions"]
def test_decorator_syntax_commit(self):
@transaction.atomic
def make_reporter():
return Reporter.objects.create(first_name="Tintin")
reporter = make_reporter()
self.assertSequenceEqual(Reporter.objects.all(), [reporter])
def test_decorator_syntax_rollback(self):
@transaction.atomic
def make_reporter():
Reporter.objects.create(first_name="Haddock")
raise Exception("Oops, that's his last name")
with self.assertRaisesMessage(Exception, "Oops"):
make_reporter()
self.assertSequenceEqual(Reporter.objects.all(), [])
def test_alternate_decorator_syntax_commit(self):
@transaction.atomic()
def make_reporter():
return Reporter.objects.create(first_name="Tintin")
reporter = make_reporter()
self.assertSequenceEqual(Reporter.objects.all(), [reporter])
def test_alternate_decorator_syntax_rollback(self):
@transaction.atomic()
def make_reporter():
Reporter.objects.create(first_name="Haddock")
raise Exception("Oops, that's his last name")
with self.assertRaisesMessage(Exception, "Oops"):
make_reporter()
self.assertSequenceEqual(Reporter.objects.all(), [])
def test_commit(self):
with transaction.atomic():
reporter = Reporter.objects.create(first_name="Tintin")
self.assertSequenceEqual(Reporter.objects.all(), [reporter])
def test_rollback(self):
with self.assertRaisesMessage(Exception, "Oops"):
with transaction.atomic():
Reporter.objects.create(first_name="Haddock")
raise Exception("Oops, that's his last name")
self.assertSequenceEqual(Reporter.objects.all(), [])
def test_nested_commit_commit(self):
with transaction.atomic():
reporter1 = Reporter.objects.create(first_name="Tintin")
with transaction.atomic():
reporter2 = Reporter.objects.create(
first_name="Archibald", last_name="Haddock"
)
self.assertSequenceEqual(Reporter.objects.all(), [reporter2, reporter1])
def test_nested_commit_rollback(self):
with transaction.atomic():
reporter = Reporter.objects.create(first_name="Tintin")
with self.assertRaisesMessage(Exception, "Oops"):
with transaction.atomic():
Reporter.objects.create(first_name="Haddock")
raise Exception("Oops, that's his last name")
self.assertSequenceEqual(Reporter.objects.all(), [reporter])
def test_nested_rollback_commit(self):
with self.assertRaisesMessage(Exception, "Oops"):
with transaction.atomic():
Reporter.objects.create(last_name="Tintin")
with transaction.atomic():
Reporter.objects.create(last_name="Haddock")
raise Exception("Oops, that's his first name")
self.assertSequenceEqual(Reporter.objects.all(), [])
def test_nested_rollback_rollback(self):
with self.assertRaisesMessage(Exception, "Oops"):
with transaction.atomic():
Reporter.objects.create(last_name="Tintin")
with self.assertRaisesMessage(Exception, "Oops"):
with transaction.atomic():
Reporter.objects.create(first_name="Haddock")
raise Exception("Oops, that's his last name")
raise Exception("Oops, that's his first name")
self.assertSequenceEqual(Reporter.objects.all(), [])
def test_merged_commit_commit(self):
with transaction.atomic():
reporter1 = Reporter.objects.create(first_name="Tintin")
with transaction.atomic(savepoint=False):
reporter2 = Reporter.objects.create(
first_name="Archibald", last_name="Haddock"
)
self.assertSequenceEqual(Reporter.objects.all(), [reporter2, reporter1])
def test_merged_commit_rollback(self):
with transaction.atomic():
Reporter.objects.create(first_name="Tintin")
with self.assertRaisesMessage(Exception, "Oops"):
with transaction.atomic(savepoint=False):
Reporter.objects.create(first_name="Haddock")
raise Exception("Oops, that's his last name")
# Writes in the outer block are rolled back too.
self.assertSequenceEqual(Reporter.objects.all(), [])
def test_merged_rollback_commit(self):
with self.assertRaisesMessage(Exception, "Oops"):
with transaction.atomic():
Reporter.objects.create(last_name="Tintin")
with transaction.atomic(savepoint=False):
Reporter.objects.create(last_name="Haddock")
raise Exception("Oops, that's his first name")
self.assertSequenceEqual(Reporter.objects.all(), [])
def test_merged_rollback_rollback(self):
with self.assertRaisesMessage(Exception, "Oops"):
with transaction.atomic():
Reporter.objects.create(last_name="Tintin")
with self.assertRaisesMessage(Exception, "Oops"):
with transaction.atomic(savepoint=False):
Reporter.objects.create(first_name="Haddock")
raise Exception("Oops, that's his last name")
raise Exception("Oops, that's his first name")
self.assertSequenceEqual(Reporter.objects.all(), [])
def test_reuse_commit_commit(self):
atomic = transaction.atomic()
with atomic:
reporter1 = Reporter.objects.create(first_name="Tintin")
with atomic:
reporter2 = Reporter.objects.create(
first_name="Archibald", last_name="Haddock"
)
self.assertSequenceEqual(Reporter.objects.all(), [reporter2, reporter1])
def test_reuse_commit_rollback(self):
atomic = transaction.atomic()
with atomic:
reporter = Reporter.objects.create(first_name="Tintin")
with self.assertRaisesMessage(Exception, "Oops"):
with atomic:
Reporter.objects.create(first_name="Haddock")
raise Exception("Oops, that's his last name")
self.assertSequenceEqual(Reporter.objects.all(), [reporter])
def test_reuse_rollback_commit(self):
atomic = transaction.atomic()
with self.assertRaisesMessage(Exception, "Oops"):
with atomic:
Reporter.objects.create(last_name="Tintin")
with atomic:
Reporter.objects.create(last_name="Haddock")
raise Exception("Oops, that's his first name")
self.assertSequenceEqual(Reporter.objects.all(), [])
def test_reuse_rollback_rollback(self):
atomic = transaction.atomic()
with self.assertRaisesMessage(Exception, "Oops"):
with atomic:
Reporter.objects.create(last_name="Tintin")
with self.assertRaisesMessage(Exception, "Oops"):
with atomic:
Reporter.objects.create(first_name="Haddock")
raise Exception("Oops, that's his last name")
raise Exception("Oops, that's his first name")
self.assertSequenceEqual(Reporter.objects.all(), [])
def test_force_rollback(self):
with transaction.atomic():
Reporter.objects.create(first_name="Tintin")
# atomic block shouldn't rollback, but force it.
self.assertFalse(transaction.get_rollback())
transaction.set_rollback(True)
self.assertSequenceEqual(Reporter.objects.all(), [])
def test_prevent_rollback(self):
with transaction.atomic():
reporter = Reporter.objects.create(first_name="Tintin")
sid = transaction.savepoint()
# trigger a database error inside an inner atomic without savepoint
with self.assertRaises(DatabaseError):
with transaction.atomic(savepoint=False):
with connection.cursor() as cursor:
cursor.execute("SELECT no_such_col FROM transactions_reporter")
# prevent atomic from rolling back since we're recovering manually
self.assertTrue(transaction.get_rollback())
transaction.set_rollback(False)
transaction.savepoint_rollback(sid)
self.assertSequenceEqual(Reporter.objects.all(), [reporter])
@skipUnlessDBFeature("can_release_savepoints")
def test_failure_on_exit_transaction(self):
with transaction.atomic():
with self.assertRaises(DatabaseError):
with transaction.atomic():
Reporter.objects.create(last_name="Tintin")
self.assertEqual(len(Reporter.objects.all()), 1)
# Incorrect savepoint id to provoke a database error.
connection.savepoint_ids.append("12")
with self.assertRaises(transaction.TransactionManagementError):
len(Reporter.objects.all())
self.assertIs(connection.needs_rollback, True)
if connection.savepoint_ids:
connection.savepoint_ids.pop()
self.assertSequenceEqual(Reporter.objects.all(), [])
class AtomicInsideTransactionTests(AtomicTests):
"""
All basic tests for atomic should also pass within an existing transaction.
"""
def setUp(self):
self.atomic = transaction.atomic()
self.atomic.__enter__()
def tearDown(self):
self.atomic.__exit__(*sys.exc_info())
class AtomicWithoutAutocommitTests(AtomicTests):
"""
All basic tests for atomic should also pass when autocommit is turned off.
"""
def setUp(self):
transaction.set_autocommit(False)
self.addCleanup(transaction.set_autocommit, True)
# The tests access the database after exercising 'atomic', initiating
# a transaction ; a rollback is required before restoring autocommit.
self.addCleanup(transaction.rollback)
@skipUnlessDBFeature("uses_savepoints")
class AtomicMergeTests(TransactionTestCase):
"""Test merging transactions with savepoint=False."""
available_apps = ["transactions"]
def test_merged_outer_rollback(self):
with transaction.atomic():
Reporter.objects.create(first_name="Tintin")
with transaction.atomic(savepoint=False):
Reporter.objects.create(first_name="Archibald", last_name="Haddock")
with self.assertRaisesMessage(Exception, "Oops"):
with transaction.atomic(savepoint=False):
Reporter.objects.create(first_name="Calculus")
raise Exception("Oops, that's his last name")
# The third insert couldn't be roll back. Temporarily mark the
# connection as not needing rollback to check it.
self.assertTrue(transaction.get_rollback())
transaction.set_rollback(False)
self.assertEqual(Reporter.objects.count(), 3)
transaction.set_rollback(True)
# The second insert couldn't be roll back. Temporarily mark the
# connection as not needing rollback to check it.
self.assertTrue(transaction.get_rollback())
transaction.set_rollback(False)
self.assertEqual(Reporter.objects.count(), 3)
transaction.set_rollback(True)
# The first block has a savepoint and must roll back.
self.assertSequenceEqual(Reporter.objects.all(), [])
def test_merged_inner_savepoint_rollback(self):
with transaction.atomic():
reporter = Reporter.objects.create(first_name="Tintin")
with transaction.atomic():
Reporter.objects.create(first_name="Archibald", last_name="Haddock")
with self.assertRaisesMessage(Exception, "Oops"):
with transaction.atomic(savepoint=False):
Reporter.objects.create(first_name="Calculus")
raise Exception("Oops, that's his last name")
# The third insert couldn't be roll back. Temporarily mark the
# connection as not needing rollback to check it.
self.assertTrue(transaction.get_rollback())
transaction.set_rollback(False)
self.assertEqual(Reporter.objects.count(), 3)
transaction.set_rollback(True)
# The second block has a savepoint and must roll back.
self.assertEqual(Reporter.objects.count(), 1)
self.assertSequenceEqual(Reporter.objects.all(), [reporter])
@skipUnlessDBFeature("uses_savepoints")
class AtomicErrorsTests(TransactionTestCase):
available_apps = ["transactions"]
forbidden_atomic_msg = "This is forbidden when an 'atomic' block is active."
def test_atomic_prevents_setting_autocommit(self):
autocommit = transaction.get_autocommit()
with transaction.atomic():
with self.assertRaisesMessage(
transaction.TransactionManagementError, self.forbidden_atomic_msg
):
transaction.set_autocommit(not autocommit)
# Make sure autocommit wasn't changed.
self.assertEqual(connection.autocommit, autocommit)
def test_atomic_prevents_calling_transaction_methods(self):
with transaction.atomic():
with self.assertRaisesMessage(
transaction.TransactionManagementError, self.forbidden_atomic_msg
):
transaction.commit()
with self.assertRaisesMessage(
transaction.TransactionManagementError, self.forbidden_atomic_msg
):
transaction.rollback()
def test_atomic_prevents_queries_in_broken_transaction(self):
r1 = Reporter.objects.create(first_name="Archibald", last_name="Haddock")
with transaction.atomic():
r2 = Reporter(first_name="Cuthbert", last_name="Calculus", id=r1.id)
with self.assertRaises(IntegrityError):
r2.save(force_insert=True)
# The transaction is marked as needing rollback.
msg = (
"An error occurred in the current transaction. You can't "
"execute queries until the end of the 'atomic' block."
)
with self.assertRaisesMessage(
transaction.TransactionManagementError, msg
) as cm:
r2.save(force_update=True)
self.assertIsInstance(cm.exception.__cause__, IntegrityError)
self.assertEqual(Reporter.objects.get(pk=r1.pk).last_name, "Haddock")
@skipIfDBFeature("atomic_transactions")
def test_atomic_allows_queries_after_fixing_transaction(self):
r1 = Reporter.objects.create(first_name="Archibald", last_name="Haddock")
with transaction.atomic():
r2 = Reporter(first_name="Cuthbert", last_name="Calculus", id=r1.id)
with self.assertRaises(IntegrityError):
r2.save(force_insert=True)
# Mark the transaction as no longer needing rollback.
transaction.set_rollback(False)
r2.save(force_update=True)
self.assertEqual(Reporter.objects.get(pk=r1.pk).last_name, "Calculus")
@skipUnlessDBFeature("test_db_allows_multiple_connections")
def test_atomic_prevents_queries_in_broken_transaction_after_client_close(self):
with transaction.atomic():
Reporter.objects.create(first_name="Archibald", last_name="Haddock")
connection.close()
# The connection is closed and the transaction is marked as
# needing rollback. This will raise an InterfaceError on databases
# that refuse to create cursors on closed connections (PostgreSQL)
# and a TransactionManagementError on other databases.
with self.assertRaises(Error):
Reporter.objects.create(first_name="Cuthbert", last_name="Calculus")
# The connection is usable again .
self.assertEqual(Reporter.objects.count(), 0)
@skipUnlessDBFeature("uses_savepoints")
@skipUnless(connection.vendor == "mysql", "MySQL-specific behaviors")
class AtomicMySQLTests(TransactionTestCase):
available_apps = ["transactions"]
@skipIf(threading is None, "Test requires threading")
def test_implicit_savepoint_rollback(self):
"""
MySQL implicitly rolls back savepoints when it deadlocks (#22291).
"""
Reporter.objects.create(id=1)
Reporter.objects.create(id=2)
main_thread_ready = threading.Event()
def other_thread():
try:
with transaction.atomic():
Reporter.objects.select_for_update().get(id=1)
main_thread_ready.wait()
# 1) This line locks... (see below for 2)
Reporter.objects.exclude(id=1).update(id=2)
finally:
# This is the thread-local connection, not the main connection.
connection.close()
other_thread = threading.Thread(target=other_thread)
other_thread.start()
with self.assertRaisesMessage(OperationalError, "Deadlock found"):
# Double atomic to enter a transaction and create a savepoint.
with transaction.atomic():
with transaction.atomic():
Reporter.objects.select_for_update().get(id=2)
main_thread_ready.set()
# The two threads can't be synchronized with an event here
# because the other thread locks. Sleep for a little while.
time.sleep(1)
# 2) ... and this line deadlocks. (see above for 1)
Reporter.objects.exclude(id=2).update(id=1)
other_thread.join()
class AtomicMiscTests(TransactionTestCase):
available_apps = ["transactions"]
def test_wrap_callable_instance(self):
"""#20028 -- Atomic must support wrapping callable instances."""
class Callable:
def __call__(self):
pass
# Must not raise an exception
transaction.atomic(Callable())
@skipUnlessDBFeature("can_release_savepoints")
def test_atomic_does_not_leak_savepoints_on_failure(self):
"""#23074 -- Savepoints must be released after rollback."""
# Expect an error when rolling back a savepoint that doesn't exist.
# Done outside of the transaction block to ensure proper recovery.
with self.assertRaises(Error):
# Start a plain transaction.
with transaction.atomic():
# Swallow the intentional error raised in the sub-transaction.
with self.assertRaisesMessage(Exception, "Oops"):
# Start a sub-transaction with a savepoint.
with transaction.atomic():
sid = connection.savepoint_ids[-1]
raise Exception("Oops")
# This is expected to fail because the savepoint no longer
# exists.
connection.savepoint_rollback(sid)
def test_mark_for_rollback_on_error_in_transaction(self):
with transaction.atomic(savepoint=False):
# Swallow the intentional error raised.
with self.assertRaisesMessage(Exception, "Oops"):
# Wrap in `mark_for_rollback_on_error` to check if the
# transaction is marked broken.
with transaction.mark_for_rollback_on_error():
# Ensure that we are still in a good state.
self.assertFalse(transaction.get_rollback())
raise Exception("Oops")
# mark_for_rollback_on_error marked the transaction as broken …
self.assertTrue(transaction.get_rollback())
# … and further queries fail.
msg = "You can't execute queries until the end of the 'atomic' block."
with self.assertRaisesMessage(transaction.TransactionManagementError, msg):
Reporter.objects.create()
# Transaction errors are reset at the end of an transaction, so this
# should just work.
Reporter.objects.create()
def test_mark_for_rollback_on_error_in_autocommit(self):
self.assertTrue(transaction.get_autocommit())
# Swallow the intentional error raised.
with self.assertRaisesMessage(Exception, "Oops"):
# Wrap in `mark_for_rollback_on_error` to check if the transaction
# is marked broken.
with transaction.mark_for_rollback_on_error():
# Ensure that we are still in a good state.
self.assertFalse(transaction.get_connection().needs_rollback)
raise Exception("Oops")
# Ensure that `mark_for_rollback_on_error` did not mark the
# transaction as broken, since we are in autocommit mode …
self.assertFalse(transaction.get_connection().needs_rollback)
# … and further queries work nicely.
Reporter.objects.create()
class NonAutocommitTests(TransactionTestCase):
available_apps = []
def setUp(self):
transaction.set_autocommit(False)
self.addCleanup(transaction.set_autocommit, True)
self.addCleanup(transaction.rollback)
def test_orm_query_after_error_and_rollback(self):
"""
ORM queries are allowed after an error and a rollback in non-autocommit
mode (#27504).
"""
r1 = Reporter.objects.create(first_name="Archibald", last_name="Haddock")
r2 = Reporter(first_name="Cuthbert", last_name="Calculus", id=r1.id)
with self.assertRaises(IntegrityError):
r2.save(force_insert=True)
transaction.rollback()
Reporter.objects.last()
def test_orm_query_without_autocommit(self):
"""
#24921 -- ORM queries must be possible after set_autocommit(False).
"""
Reporter.objects.create(first_name="Tintin")
class DurableTestsBase:
available_apps = ["transactions"]
def test_commit(self):
with transaction.atomic(durable=True):
reporter = Reporter.objects.create(first_name="Tintin")
self.assertEqual(Reporter.objects.get(), reporter)
def test_nested_outer_durable(self):
with transaction.atomic(durable=True):
reporter1 = Reporter.objects.create(first_name="Tintin")
with transaction.atomic():
reporter2 = Reporter.objects.create(
first_name="Archibald",
last_name="Haddock",
)
self.assertSequenceEqual(Reporter.objects.all(), [reporter2, reporter1])
def test_nested_both_durable(self):
msg = "A durable atomic block cannot be nested within another atomic block."
with transaction.atomic(durable=True):
with self.assertRaisesMessage(RuntimeError, msg):
with transaction.atomic(durable=True):
pass
def test_nested_inner_durable(self):
msg = "A durable atomic block cannot be nested within another atomic block."
with transaction.atomic():
with self.assertRaisesMessage(RuntimeError, msg):
with transaction.atomic(durable=True):
pass
def test_sequence_of_durables(self):
with transaction.atomic(durable=True):
reporter = Reporter.objects.create(first_name="Tintin 1")
self.assertEqual(Reporter.objects.get(first_name="Tintin 1"), reporter)
with transaction.atomic(durable=True):
reporter = Reporter.objects.create(first_name="Tintin 2")
self.assertEqual(Reporter.objects.get(first_name="Tintin 2"), reporter)
class DurableTransactionTests(DurableTestsBase, TransactionTestCase):
pass
class DurableTests(DurableTestsBase, TestCase):
pass
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/backends/test_utils.py | tests/backends/test_utils.py | """Tests for django.db.backends.utils"""
from decimal import Decimal, Rounded
from django.db import NotSupportedError, connection
from django.db.backends.utils import (
format_number,
split_identifier,
split_tzname_delta,
truncate_name,
)
from django.test import (
SimpleTestCase,
TransactionTestCase,
skipIfDBFeature,
skipUnlessDBFeature,
)
class TestUtils(SimpleTestCase):
def test_truncate_name(self):
self.assertEqual(truncate_name("some_table", 10), "some_table")
self.assertEqual(truncate_name("some_long_table", 10), "some_la38a")
self.assertEqual(truncate_name("some_long_table", 10, 3), "some_loa38")
self.assertEqual(truncate_name("some_long_table"), "some_long_table")
# "user"."table" syntax
self.assertEqual(
truncate_name('username"."some_table', 10), 'username"."some_table'
)
self.assertEqual(
truncate_name('username"."some_long_table', 10), 'username"."some_la38a'
)
self.assertEqual(
truncate_name('username"."some_long_table', 10, 3), 'username"."some_loa38'
)
def test_split_identifier(self):
self.assertEqual(split_identifier("some_table"), ("", "some_table"))
self.assertEqual(split_identifier('"some_table"'), ("", "some_table"))
self.assertEqual(
split_identifier('namespace"."some_table'), ("namespace", "some_table")
)
self.assertEqual(
split_identifier('"namespace"."some_table"'), ("namespace", "some_table")
)
def test_format_number(self):
def equal(value, max_d, places, result):
self.assertEqual(format_number(Decimal(value), max_d, places), result)
equal("0", 12, 3, "0.000")
equal("0", 12, 8, "0.00000000")
equal("1", 12, 9, "1.000000000")
equal("0.00000000", 12, 8, "0.00000000")
equal("0.000000004", 12, 8, "0.00000000")
equal("0.000000008", 12, 8, "0.00000001")
equal("0.000000000000000000999", 10, 8, "0.00000000")
equal("0.1234567890", 12, 10, "0.1234567890")
equal("0.1234567890", 12, 9, "0.123456789")
equal("0.1234567890", 12, 8, "0.12345679")
equal("0.1234567890", 12, 5, "0.12346")
equal("0.1234567890", 12, 3, "0.123")
equal("0.1234567890", 12, 1, "0.1")
equal("0.1234567890", 12, 0, "0")
equal("0.1234567890", None, 0, "0")
equal("1234567890.1234567890", None, 0, "1234567890")
equal("1234567890.1234567890", None, 2, "1234567890.12")
equal("0.1234", 5, None, "0.1234")
equal("123.12", 5, None, "123.12")
with self.assertRaises(Rounded):
equal("0.1234567890", 5, None, "0.12346")
with self.assertRaises(Rounded):
equal("1234567890.1234", 5, None, "1234600000")
def test_split_tzname_delta(self):
tests = [
("Asia/Ust+Nera", ("Asia/Ust+Nera", None, None)),
("Asia/Ust-Nera", ("Asia/Ust-Nera", None, None)),
("Asia/Ust+Nera-02:00", ("Asia/Ust+Nera", "-", "02:00")),
("Asia/Ust-Nera+05:00", ("Asia/Ust-Nera", "+", "05:00")),
("America/Coral_Harbour-01:00", ("America/Coral_Harbour", "-", "01:00")),
("America/Coral_Harbour+02:30", ("America/Coral_Harbour", "+", "02:30")),
("UTC+15:00", ("UTC", "+", "15:00")),
("UTC-04:43", ("UTC", "-", "04:43")),
("UTC", ("UTC", None, None)),
("UTC+1", ("UTC+1", None, None)),
]
for tzname, expected in tests:
with self.subTest(tzname=tzname):
self.assertEqual(split_tzname_delta(tzname), expected)
class CursorWrapperTests(TransactionTestCase):
available_apps = []
def _test_procedure(self, procedure_sql, params, param_types, kparams=None):
with connection.cursor() as cursor:
cursor.execute(procedure_sql)
# Use a new cursor because in MySQL a procedure can't be used in the
# same cursor in which it was created.
with connection.cursor() as cursor:
cursor.callproc("test_procedure", params, kparams)
with connection.schema_editor() as editor:
editor.remove_procedure("test_procedure", param_types)
@skipUnlessDBFeature("create_test_procedure_without_params_sql")
def test_callproc_without_params(self):
self._test_procedure(
connection.features.create_test_procedure_without_params_sql, [], []
)
@skipUnlessDBFeature("create_test_procedure_with_int_param_sql")
def test_callproc_with_int_params(self):
self._test_procedure(
connection.features.create_test_procedure_with_int_param_sql,
[1],
["INTEGER"],
)
@skipUnlessDBFeature(
"create_test_procedure_with_int_param_sql", "supports_callproc_kwargs"
)
def test_callproc_kparams(self):
self._test_procedure(
connection.features.create_test_procedure_with_int_param_sql,
[],
["INTEGER"],
{"P_I": 1},
)
@skipIfDBFeature("supports_callproc_kwargs")
def test_unsupported_callproc_kparams_raises_error(self):
msg = (
"Keyword parameters for callproc are not supported on this database "
"backend."
)
with self.assertRaisesMessage(NotSupportedError, msg):
with connection.cursor() as cursor:
cursor.callproc("test_procedure", [], {"P_I": 1})
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/backends/models.py | tests/backends/models.py | from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
from django.contrib.contenttypes.models import ContentType
from django.db import models
class Square(models.Model):
root = models.IntegerField()
square = models.PositiveIntegerField(db_default=9)
def __str__(self):
return "%s ** 2 == %s" % (self.root, self.square)
class Person(models.Model):
first_name = models.CharField(max_length=20)
last_name = models.CharField(max_length=20)
def __str__(self):
return "%s %s" % (self.first_name, self.last_name)
class SchoolClassManager(models.Manager):
def get_queryset(self):
return super().get_queryset().exclude(year=1000)
class SchoolClass(models.Model):
year = models.PositiveIntegerField()
day = models.CharField(max_length=9, blank=True)
last_updated = models.DateTimeField()
objects = SchoolClassManager()
class SchoolBusManager(models.Manager):
def get_queryset(self):
return super().get_queryset().prefetch_related("schoolclasses")
class SchoolBus(models.Model):
number = models.IntegerField()
schoolclasses = models.ManyToManyField("SchoolClass")
objects = SchoolBusManager()
class Meta:
base_manager_name = "objects"
class VeryLongModelNameZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ(models.Model):
primary_key_is_quite_long_zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz = models.AutoField(
primary_key=True
)
charfield_is_quite_long_zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz = models.CharField(
max_length=100
)
m2m_also_quite_long_zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz = (
models.ManyToManyField(Person, blank=True)
)
class Tag(models.Model):
name = models.CharField(max_length=30)
content_type = models.ForeignKey(
ContentType, models.CASCADE, related_name="backend_tags"
)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey("content_type", "object_id")
class Post(models.Model):
name = models.CharField(max_length=30)
text = models.TextField()
tags = GenericRelation("Tag")
class Meta:
db_table = "CaseSensitive_Post"
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 ReporterProxy(Reporter):
class Meta:
proxy = True
class Article(models.Model):
headline = models.CharField(max_length=100)
pub_date = models.DateField()
reporter = models.ForeignKey(Reporter, models.CASCADE)
reporter_proxy = models.ForeignKey(
ReporterProxy,
models.SET_NULL,
null=True,
related_name="reporter_proxy",
)
def __str__(self):
return self.headline
class Item(models.Model):
name = models.CharField(max_length=30)
date = models.DateField()
time = models.TimeField()
last_modified = models.DateTimeField()
def __str__(self):
return self.name
class Object(models.Model):
related_objects = models.ManyToManyField(
"self", db_constraint=False, symmetrical=False
)
obj_ref = models.ForeignKey("ObjectReference", models.CASCADE, null=True)
def __str__(self):
return str(self.id)
class ObjectReference(models.Model):
obj = models.ForeignKey(Object, models.CASCADE, db_constraint=False)
def __str__(self):
return str(self.obj_id)
class ObjectSelfReference(models.Model):
key = models.CharField(max_length=3, unique=True)
obj = models.ForeignKey("ObjectSelfReference", models.SET_NULL, null=True)
class CircularA(models.Model):
key = models.CharField(max_length=3, unique=True)
obj = models.ForeignKey("CircularB", models.SET_NULL, null=True)
def natural_key(self):
return (self.key,)
class CircularB(models.Model):
key = models.CharField(max_length=3, unique=True)
obj = models.ForeignKey("CircularA", models.SET_NULL, null=True)
def natural_key(self):
return (self.key,)
class RawData(models.Model):
raw_data = models.BinaryField()
class Author(models.Model):
name = models.CharField(max_length=255, unique=True)
class Book(models.Model):
author = models.ForeignKey(Author, models.CASCADE, to_field="name")
class SQLKeywordsModel(models.Model):
id = models.AutoField(primary_key=True, db_column="select")
reporter = models.ForeignKey(Reporter, models.CASCADE, db_column="where")
class Meta:
db_table = "order"
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/backends/__init__.py | tests/backends/__init__.py | python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false | |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/backends/tests.py | tests/backends/tests.py | """Tests related to django.db.backends that haven't been organized."""
import datetime
import logging
import threading
import unittest
import warnings
from django.core.management.color import no_style
from django.db import (
DEFAULT_DB_ALIAS,
DatabaseError,
IntegrityError,
connection,
connections,
reset_queries,
transaction,
)
from django.db.backends.base.base import BaseDatabaseWrapper
from django.db.backends.signals import connection_created
from django.db.backends.utils import CursorWrapper
from django.db.models import BigAutoField, Value
from django.db.models.sql.constants import CURSOR
from django.test import (
TestCase,
TransactionTestCase,
override_settings,
skipIfDBFeature,
skipUnlessDBFeature,
)
from .models import (
Article,
Object,
ObjectReference,
Person,
Post,
RawData,
Reporter,
ReporterProxy,
SchoolClass,
SQLKeywordsModel,
Square,
VeryLongModelNameZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ,
)
class DateQuotingTest(TestCase):
def test_django_date_trunc(self):
"""
Test the custom ``django_date_trunc method``, in particular against
fields which clash with strings passed to it (e.g. 'year') (#12818).
"""
updated = datetime.datetime(2010, 2, 20)
SchoolClass.objects.create(year=2009, last_updated=updated)
years = SchoolClass.objects.dates("last_updated", "year")
self.assertEqual(list(years), [datetime.date(2010, 1, 1)])
def test_django_date_extract(self):
"""
Test the custom ``django_date_extract method``, in particular against
fields which clash with strings passed to it (e.g. 'day') (#12818).
"""
updated = datetime.datetime(2010, 2, 20)
SchoolClass.objects.create(year=2009, last_updated=updated)
classes = SchoolClass.objects.filter(last_updated__day=20)
self.assertEqual(len(classes), 1)
@override_settings(DEBUG=True)
class LastExecutedQueryTest(TestCase):
def test_last_executed_query_without_previous_query(self):
"""
last_executed_query should not raise an exception even if no previous
query has been run.
"""
suffix = connection.features.bare_select_suffix
with connection.cursor() as cursor:
if connection.vendor == "oracle":
cursor.statement = None
# No previous query has been run.
connection.ops.last_executed_query(cursor, "", ())
# Previous query crashed.
connection.ops.last_executed_query(cursor, "SELECT %s" + suffix, (1,))
def test_debug_sql(self):
list(Reporter.objects.filter(first_name="test"))
sql = connection.queries[-1]["sql"].lower()
self.assertIn("select", sql)
self.assertIn(Reporter._meta.db_table, sql)
def test_query_encoding(self):
"""last_executed_query() returns a string."""
data = RawData.objects.filter(raw_data=b"\x00\x46 \xfe").extra(
select={"föö": 1}
)
sql, params = data.query.sql_with_params()
with data.query.get_compiler("default").execute_sql(CURSOR) as cursor:
last_sql = cursor.db.ops.last_executed_query(cursor, sql, params)
self.assertIsInstance(last_sql, str)
def test_last_executed_query(self):
# last_executed_query() interpolate all parameters, in most cases it is
# not equal to QuerySet.query.
for qs in (
Article.objects.filter(pk=1),
Article.objects.filter(pk__in=(1, 2), reporter__pk=3),
Article.objects.filter(
pk=1,
reporter__pk=9,
).exclude(reporter__pk__in=[2, 1]),
Article.objects.filter(pk__in=list(range(20, 31))),
):
sql, params = qs.query.sql_with_params()
with qs.query.get_compiler(DEFAULT_DB_ALIAS).execute_sql(CURSOR) as cursor:
self.assertEqual(
cursor.db.ops.last_executed_query(cursor, sql, params),
str(qs.query),
)
@skipUnlessDBFeature("supports_paramstyle_pyformat")
def test_last_executed_query_dict(self):
square_opts = Square._meta
sql = "INSERT INTO %s (%s, %s) VALUES (%%(root)s, %%(square)s)" % (
connection.introspection.identifier_converter(square_opts.db_table),
connection.ops.quote_name(square_opts.get_field("root").column),
connection.ops.quote_name(square_opts.get_field("square").column),
)
with connection.cursor() as cursor:
params = {"root": 2, "square": 4}
cursor.execute(sql, params)
self.assertEqual(
cursor.db.ops.last_executed_query(cursor, sql, params),
sql % params,
)
@skipUnlessDBFeature("supports_paramstyle_pyformat")
def test_last_executed_query_dict_overlap_keys(self):
square_opts = Square._meta
sql = "INSERT INTO %s (%s, %s) VALUES (%%(root)s, %%(root2)s)" % (
connection.introspection.identifier_converter(square_opts.db_table),
connection.ops.quote_name(square_opts.get_field("root").column),
connection.ops.quote_name(square_opts.get_field("square").column),
)
with connection.cursor() as cursor:
params = {"root": 2, "root2": 4}
cursor.execute(sql, params)
self.assertEqual(
cursor.db.ops.last_executed_query(cursor, sql, params),
sql % params,
)
def test_last_executed_query_with_duplicate_params(self):
square_opts = Square._meta
table = connection.introspection.identifier_converter(square_opts.db_table)
id_column = connection.ops.quote_name(square_opts.get_field("id").column)
root_column = connection.ops.quote_name(square_opts.get_field("root").column)
sql = f"UPDATE {table} SET {root_column} = %s + %s WHERE {id_column} = %s"
with connection.cursor() as cursor:
params = [42, 42, 1]
cursor.execute(sql, params)
last_executed_query = connection.ops.last_executed_query(
cursor, sql, params
)
self.assertEqual(
last_executed_query,
f"UPDATE {table} SET {root_column} = 42 + 42 WHERE {id_column} = 1",
)
class ParameterHandlingTest(TestCase):
def test_bad_parameter_count(self):
"""
An executemany call with too many/not enough parameters will raise an
exception.
"""
with connection.cursor() as cursor:
query = "INSERT INTO %s (%s, %s) VALUES (%%s, %%s)" % (
connection.introspection.identifier_converter("backends_square"),
connection.ops.quote_name("root"),
connection.ops.quote_name("square"),
)
with self.assertRaises(Exception):
cursor.executemany(query, [(1, 2, 3)])
with self.assertRaises(Exception):
cursor.executemany(query, [(1,)])
class LongNameTest(TransactionTestCase):
"""Long primary keys and model names can result in a sequence name
that exceeds the database limits, which will result in truncation
on certain databases (e.g., Postgres). The backend needs to use
the correct sequence name in last_insert_id and other places, so
check it is. Refs #8901.
"""
available_apps = ["backends"]
def test_sequence_name_length_limits_create(self):
"""Creation of model with long name and long pk name doesn't error."""
VeryLongModelNameZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ.objects.create()
def test_sequence_name_length_limits_m2m(self):
"""
An m2m save of a model with a long name and a long m2m field name
doesn't error (#8901).
"""
obj = (
VeryLongModelNameZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ.objects.create()
)
rel_obj = Person.objects.create(first_name="Django", last_name="Reinhardt")
obj.m2m_also_quite_long_zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz.add(rel_obj)
def test_sequence_name_length_limits_flush(self):
"""
Sequence resetting as part of a flush with model with long name and
long pk name doesn't error (#8901).
"""
# A full flush is expensive to the full test, so we dig into the
# internals to generate the likely offending SQL and run it manually
# Some convenience aliases
VLM = VeryLongModelNameZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ
VLM_m2m = (
VLM.m2m_also_quite_long_zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz.through
)
tables = [
VLM._meta.db_table,
VLM_m2m._meta.db_table,
]
sql_list = connection.ops.sql_flush(no_style(), tables, reset_sequences=True)
connection.ops.execute_sql_flush(sql_list)
@skipUnlessDBFeature("supports_sequence_reset")
class SequenceResetTest(TestCase):
def test_generic_relation(self):
"""
Sequence names are correct when resetting generic relations (Ref
#13941)
"""
# Create an object with a manually specified PK
Post.objects.create(id=10, name="1st post", text="hello world")
# Reset the sequences for the database
commands = connections[DEFAULT_DB_ALIAS].ops.sequence_reset_sql(
no_style(), [Post]
)
with connection.cursor() as cursor:
for sql in commands:
cursor.execute(sql)
# If we create a new object now, it should have a PK greater
# than the PK we specified manually.
obj = Post.objects.create(name="New post", text="goodbye world")
self.assertGreater(obj.pk, 10)
# This test needs to run outside of a transaction, otherwise closing the
# connection would implicitly rollback and cause problems during teardown.
class ConnectionCreatedSignalTest(TransactionTestCase):
available_apps = []
# Unfortunately with sqlite3 the in-memory test database cannot be closed,
# and so it cannot be re-opened during testing.
@skipUnlessDBFeature("test_db_allows_multiple_connections")
def test_signal(self):
data = {}
def receiver(sender, connection, **kwargs):
data["connection"] = connection
connection_created.connect(receiver)
connection.close()
with connection.cursor():
pass
self.assertIs(data["connection"].connection, connection.connection)
connection_created.disconnect(receiver)
data.clear()
with connection.cursor():
pass
self.assertEqual(data, {})
class EscapingChecks(TestCase):
"""
All tests in this test case are also run with settings.DEBUG=True in
EscapingChecksDebug test case, to also test CursorDebugWrapper.
"""
bare_select_suffix = connection.features.bare_select_suffix
def test_paramless_no_escaping(self):
with connection.cursor() as cursor:
cursor.execute("SELECT '%s'" + self.bare_select_suffix)
self.assertEqual(cursor.fetchall()[0][0], "%s")
def test_parameter_escaping(self):
with connection.cursor() as cursor:
cursor.execute("SELECT '%%', %s" + self.bare_select_suffix, ("%d",))
self.assertEqual(cursor.fetchall()[0], ("%", "%d"))
@override_settings(DEBUG=True)
class EscapingChecksDebug(EscapingChecks):
pass
class BackendTestCase(TransactionTestCase):
available_apps = ["backends"]
def create_squares_with_executemany(self, args):
self.create_squares(args, "format", True)
def create_squares(self, args, paramstyle, multiple):
opts = Square._meta
tbl = connection.introspection.identifier_converter(opts.db_table)
f1 = connection.ops.quote_name(opts.get_field("root").column)
f2 = connection.ops.quote_name(opts.get_field("square").column)
if paramstyle == "format":
query = "INSERT INTO %s (%s, %s) VALUES (%%s, %%s)" % (tbl, f1, f2)
elif paramstyle == "pyformat":
query = "INSERT INTO %s (%s, %s) VALUES (%%(root)s, %%(square)s)" % (
tbl,
f1,
f2,
)
else:
raise ValueError("unsupported paramstyle in test")
with connection.cursor() as cursor:
if multiple:
cursor.executemany(query, args)
else:
cursor.execute(query, args)
def test_cursor_executemany(self):
# Test cursor.executemany #4896
args = [(i, i**2) for i in range(-5, 6)]
self.create_squares_with_executemany(args)
self.assertEqual(Square.objects.count(), 11)
for i in range(-5, 6):
square = Square.objects.get(root=i)
self.assertEqual(square.square, i**2)
def test_cursor_executemany_with_empty_params_list(self):
# Test executemany with params=[] does nothing #4765
args = []
self.create_squares_with_executemany(args)
self.assertEqual(Square.objects.count(), 0)
def test_cursor_executemany_with_iterator(self):
# Test executemany accepts iterators #10320
args = ((i, i**2) for i in range(-3, 2))
self.create_squares_with_executemany(args)
self.assertEqual(Square.objects.count(), 5)
args = ((i, i**2) for i in range(3, 7))
with override_settings(DEBUG=True):
# same test for DebugCursorWrapper
self.create_squares_with_executemany(args)
self.assertEqual(Square.objects.count(), 9)
@skipUnlessDBFeature("supports_paramstyle_pyformat")
def test_cursor_execute_with_pyformat(self):
# Support pyformat style passing of parameters #10070
args = {"root": 3, "square": 9}
self.create_squares(args, "pyformat", multiple=False)
self.assertEqual(Square.objects.count(), 1)
@skipUnlessDBFeature("supports_paramstyle_pyformat")
def test_cursor_executemany_with_pyformat(self):
# Support pyformat style passing of parameters #10070
args = [{"root": i, "square": i**2} for i in range(-5, 6)]
self.create_squares(args, "pyformat", multiple=True)
self.assertEqual(Square.objects.count(), 11)
for i in range(-5, 6):
square = Square.objects.get(root=i)
self.assertEqual(square.square, i**2)
@skipUnlessDBFeature("supports_paramstyle_pyformat")
def test_cursor_executemany_with_pyformat_iterator(self):
args = ({"root": i, "square": i**2} for i in range(-3, 2))
self.create_squares(args, "pyformat", multiple=True)
self.assertEqual(Square.objects.count(), 5)
args = ({"root": i, "square": i**2} for i in range(3, 7))
with override_settings(DEBUG=True):
# same test for DebugCursorWrapper
self.create_squares(args, "pyformat", multiple=True)
self.assertEqual(Square.objects.count(), 9)
def test_unicode_fetches(self):
# fetchone, fetchmany, fetchall return strings as Unicode objects.
qn = connection.ops.quote_name
Person(first_name="John", last_name="Doe").save()
Person(first_name="Jane", last_name="Doe").save()
Person(first_name="Mary", last_name="Agnelline").save()
Person(first_name="Peter", last_name="Parker").save()
Person(first_name="Clark", last_name="Kent").save()
opts2 = Person._meta
f3, f4 = opts2.get_field("first_name"), opts2.get_field("last_name")
with connection.cursor() as cursor:
cursor.execute(
"SELECT %s, %s FROM %s ORDER BY %s"
% (
qn(f3.column),
qn(f4.column),
connection.introspection.identifier_converter(opts2.db_table),
qn(f3.column),
)
)
self.assertEqual(cursor.fetchone(), ("Clark", "Kent"))
self.assertEqual(
list(cursor.fetchmany(2)), [("Jane", "Doe"), ("John", "Doe")]
)
self.assertEqual(
list(cursor.fetchall()), [("Mary", "Agnelline"), ("Peter", "Parker")]
)
def test_unicode_password(self):
old_password = connection.settings_dict["PASSWORD"]
connection.settings_dict["PASSWORD"] = "françois"
try:
with connection.cursor():
pass
except DatabaseError:
# As password is probably wrong, a database exception is expected
pass
except Exception as e:
self.fail("Unexpected error raised with Unicode password: %s" % e)
finally:
connection.settings_dict["PASSWORD"] = old_password
def test_database_operations_helper_class(self):
# Ticket #13630
self.assertTrue(hasattr(connection, "ops"))
self.assertTrue(hasattr(connection.ops, "connection"))
self.assertEqual(connection, connection.ops.connection)
def test_database_operations_init(self):
"""
DatabaseOperations initialization doesn't query the database.
See #17656.
"""
with self.assertNumQueries(0):
connection.ops.__class__(connection)
def test_cached_db_features(self):
self.assertIn(connection.features.supports_transactions, (True, False))
self.assertIn(connection.features.can_introspect_foreign_keys, (True, False))
def test_duplicate_table_error(self):
"""Creating an existing table returns a DatabaseError"""
query = "CREATE TABLE %s (id INTEGER);" % Article._meta.db_table
with connection.cursor() as cursor:
with self.assertRaises(DatabaseError):
cursor.execute(query)
def test_cursor_contextmanager(self):
"""
Cursors can be used as a context manager
"""
with connection.cursor() as cursor:
self.assertIsInstance(cursor, CursorWrapper)
# Both InterfaceError and ProgrammingError seem to be used when
# accessing closed cursor (psycopg has InterfaceError, rest seem
# to use ProgrammingError).
with self.assertRaises(connection.features.closed_cursor_error_class):
# cursor should be closed, so no queries should be possible.
cursor.execute("SELECT 1" + connection.features.bare_select_suffix)
@unittest.skipUnless(
connection.vendor == "postgresql",
"Psycopg specific cursor.closed attribute needed",
)
def test_cursor_contextmanager_closing(self):
# There isn't a generic way to test that cursors are closed, but
# psycopg offers us a way to check that by closed attribute.
# So, run only on psycopg for that reason.
with connection.cursor() as cursor:
self.assertIsInstance(cursor, CursorWrapper)
self.assertTrue(cursor.closed)
# Unfortunately with sqlite3 the in-memory test database cannot be closed.
@skipUnlessDBFeature("test_db_allows_multiple_connections")
def test_is_usable_after_database_disconnects(self):
"""
is_usable() doesn't crash when the database disconnects (#21553).
"""
# Open a connection to the database.
with connection.cursor():
pass
# Emulate a connection close by the database.
connection._close()
# Even then is_usable() should not raise an exception.
try:
self.assertFalse(connection.is_usable())
finally:
# Clean up the mess created by connection._close(). Since the
# connection is already closed, this crashes on some backends.
try:
connection.close()
except Exception:
pass
@override_settings(DEBUG=True)
def test_queries(self):
"""
Test the documented API of connection.queries.
"""
sql = "SELECT 1" + connection.features.bare_select_suffix
with connection.cursor() as cursor:
reset_queries()
cursor.execute(sql)
self.assertEqual(1, len(connection.queries))
self.assertIsInstance(connection.queries, list)
self.assertIsInstance(connection.queries[0], dict)
self.assertEqual(list(connection.queries[0]), ["sql", "time"])
self.assertEqual(connection.queries[0]["sql"], sql)
reset_queries()
self.assertEqual(0, len(connection.queries))
sql = "INSERT INTO %s (%s, %s) VALUES (%%s, %%s)" % (
connection.introspection.identifier_converter("backends_square"),
connection.ops.quote_name("root"),
connection.ops.quote_name("square"),
)
with connection.cursor() as cursor:
cursor.executemany(sql, [(1, 1), (2, 4)])
self.assertEqual(1, len(connection.queries))
self.assertIsInstance(connection.queries, list)
self.assertIsInstance(connection.queries[0], dict)
self.assertEqual(list(connection.queries[0]), ["sql", "time"])
self.assertEqual(connection.queries[0]["sql"], "2 times: %s" % sql)
# Unfortunately with sqlite3 the in-memory test database cannot be closed.
@skipUnlessDBFeature("test_db_allows_multiple_connections")
@override_settings(DEBUG=True)
def test_queries_limit(self):
"""
The backend doesn't store an unlimited number of queries (#12581).
"""
old_queries_limit = BaseDatabaseWrapper.queries_limit
BaseDatabaseWrapper.queries_limit = 3
new_connection = connection.copy()
# Initialize the connection and clear initialization statements.
with new_connection.cursor():
pass
new_connection.queries_log.clear()
try:
with new_connection.cursor() as cursor:
cursor.execute("SELECT 1" + new_connection.features.bare_select_suffix)
cursor.execute("SELECT 2" + new_connection.features.bare_select_suffix)
with warnings.catch_warnings(record=True) as w:
self.assertEqual(2, len(new_connection.queries))
self.assertEqual(0, len(w))
with new_connection.cursor() as cursor:
cursor.execute("SELECT 3" + new_connection.features.bare_select_suffix)
cursor.execute("SELECT 4" + new_connection.features.bare_select_suffix)
msg = (
"Limit for query logging exceeded, only the last 3 queries will be "
"returned."
)
with self.assertWarnsMessage(UserWarning, msg) as ctx:
self.assertEqual(3, len(new_connection.queries))
self.assertEqual(ctx.filename, __file__)
finally:
BaseDatabaseWrapper.queries_limit = old_queries_limit
new_connection.close()
@override_settings(DEBUG=True)
def test_queries_logger(self):
sql = "select 1" + connection.features.bare_select_suffix
with (
connection.cursor() as cursor,
self.assertLogs("django.db.backends", "DEBUG") as handler,
):
cursor.execute(sql)
self.assertGreaterEqual(
records_len := len(handler.records),
1,
f"Wrong number of calls for {handler=} in (expected at least 1, got "
f"{records_len}).",
)
record = handler.records[-1]
# Log raw message, effective level and args are correct.
self.assertEqual(record.msg, "(%.3f) %s; args=%s; alias=%s")
self.assertEqual(record.levelno, logging.DEBUG)
self.assertEqual(len(record.args), 4)
duration, logged_sql, params, alias = record.args
# Duration is hard to test without mocking time, expect under 1 second.
self.assertIsInstance(duration, float)
self.assertLess(duration, 1)
self.assertEqual(duration, record.duration)
# SQL is correct and not formatted.
self.assertEqual(logged_sql, sql)
self.assertNotEqual(logged_sql, connection.ops.format_debug_sql(sql))
self.assertEqual(logged_sql, record.sql)
# Params is None and alias is connection.alias.
self.assertIsNone(params)
self.assertIsNone(record.params)
self.assertEqual(alias, connection.alias)
self.assertEqual(alias, record.alias)
def test_queries_bare_where(self):
sql = f"SELECT 1{connection.features.bare_select_suffix} WHERE 1=1"
with connection.cursor() as cursor:
cursor.execute(sql)
self.assertEqual(cursor.fetchone(), (1,))
def test_timezone_none_use_tz_false(self):
connection.ensure_connection()
with self.settings(TIME_ZONE=None, USE_TZ=False):
connection.init_connection_state()
# These tests aren't conditional because it would require differentiating
# between MySQL+InnoDB and MySQL+MYISAM (something we currently can't do).
class FkConstraintsTests(TransactionTestCase):
available_apps = ["backends"]
def setUp(self):
# Create a Reporter.
self.r = Reporter.objects.create(first_name="John", last_name="Smith")
def test_integrity_checks_on_creation(self):
"""
Try to create a model instance that violates a FK constraint. If it
fails it should fail with IntegrityError.
"""
a1 = Article(
headline="This is a test",
pub_date=datetime.datetime(2005, 7, 27),
reporter_id=30,
)
try:
a1.save()
except IntegrityError:
pass
else:
self.skipTest("This backend does not support integrity checks.")
# Now that we know this backend supports integrity checks we make sure
# constraints are also enforced for proxy Refs #17519
a2 = Article(
headline="This is another test",
reporter=self.r,
pub_date=datetime.datetime(2012, 8, 3),
reporter_proxy_id=30,
)
with self.assertRaises(IntegrityError):
a2.save()
def test_integrity_checks_on_update(self):
"""
Try to update a model instance introducing a FK constraint violation.
If it fails it should fail with IntegrityError.
"""
# Create an Article.
Article.objects.create(
headline="Test article",
pub_date=datetime.datetime(2010, 9, 4),
reporter=self.r,
)
# Retrieve it from the DB
a1 = Article.objects.get(headline="Test article")
a1.reporter_id = 30
try:
a1.save()
except IntegrityError:
pass
else:
self.skipTest("This backend does not support integrity checks.")
# Now that we know this backend supports integrity checks we make sure
# constraints are also enforced for proxy Refs #17519
# Create another article
r_proxy = ReporterProxy.objects.get(pk=self.r.pk)
Article.objects.create(
headline="Another article",
pub_date=datetime.datetime(1988, 5, 15),
reporter=self.r,
reporter_proxy=r_proxy,
)
# Retrieve the second article from the DB
a2 = Article.objects.get(headline="Another article")
a2.reporter_proxy_id = 30
with self.assertRaises(IntegrityError):
a2.save()
def test_disable_constraint_checks_manually(self):
"""
When constraint checks are disabled, should be able to write bad data
without IntegrityErrors.
"""
with transaction.atomic():
# Create an Article.
Article.objects.create(
headline="Test article",
pub_date=datetime.datetime(2010, 9, 4),
reporter=self.r,
)
# Retrieve it from the DB
a = Article.objects.get(headline="Test article")
a.reporter_id = 30
try:
connection.disable_constraint_checking()
a.save()
connection.enable_constraint_checking()
except IntegrityError:
self.fail("IntegrityError should not have occurred.")
transaction.set_rollback(True)
def test_disable_constraint_checks_context_manager(self):
"""
When constraint checks are disabled (using context manager), should be
able to write bad data without IntegrityErrors.
"""
with transaction.atomic():
# Create an Article.
Article.objects.create(
headline="Test article",
pub_date=datetime.datetime(2010, 9, 4),
reporter=self.r,
)
# Retrieve it from the DB
a = Article.objects.get(headline="Test article")
a.reporter_id = 30
try:
with connection.constraint_checks_disabled():
a.save()
except IntegrityError:
self.fail("IntegrityError should not have occurred.")
transaction.set_rollback(True)
def test_check_constraints(self):
"""
Constraint checks should raise an IntegrityError when bad data is in
the DB.
"""
with transaction.atomic():
# Create an Article.
Article.objects.create(
headline="Test article",
pub_date=datetime.datetime(2010, 9, 4),
reporter=self.r,
)
# Retrieve it from the DB
a = Article.objects.get(headline="Test article")
a.reporter_id = 30
with connection.constraint_checks_disabled():
a.save()
try:
connection.check_constraints(table_names=[Article._meta.db_table])
except IntegrityError:
pass
else:
self.skipTest("This backend does not support integrity checks.")
transaction.set_rollback(True)
def test_check_constraints_sql_keywords(self):
with transaction.atomic():
obj = SQLKeywordsModel.objects.create(reporter=self.r)
obj.refresh_from_db()
obj.reporter_id = 30
with connection.constraint_checks_disabled():
obj.save()
try:
connection.check_constraints(table_names=["order"])
except IntegrityError:
pass
else:
self.skipTest("This backend does not support integrity checks.")
transaction.set_rollback(True)
class ThreadTests(TransactionTestCase):
available_apps = ["backends"]
def test_default_connection_thread_local(self):
"""
The default connection (i.e. django.db.connection) is different for
each thread (#17258).
"""
# Map connections by id because connections with identical aliases
# have the same hash.
connections_dict = {}
with connection.cursor():
pass
connections_dict[id(connection)] = connection
def runner():
# Passing django.db.connection between threads doesn't work while
# connections[DEFAULT_DB_ALIAS] does.
from django.db import connections
connection = connections[DEFAULT_DB_ALIAS]
# Allow thread sharing so the connection can be closed by the
# main thread.
connection.inc_thread_sharing()
with connection.cursor():
pass
connections_dict[id(connection)] = connection
try:
for x in range(2):
t = threading.Thread(target=runner)
t.start()
t.join()
# Each created connection got different inner connection.
self.assertEqual(
len({conn.connection for conn in connections_dict.values()}), 3
)
finally:
# Finish by closing the connections opened by the other threads
# (the connection opened in the main thread will automatically be
# closed on teardown).
for conn in connections_dict.values():
if conn is not connection and conn.allow_thread_sharing:
conn.validate_thread_sharing()
conn._close()
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | true |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/backends/test_ddl_references.py | tests/backends/test_ddl_references.py | from django.db import connection
from django.db.backends.ddl_references import (
Columns,
Expressions,
ForeignKeyName,
IndexName,
Statement,
Table,
)
from django.db.models import ExpressionList, F
from django.db.models.functions import Upper
from django.db.models.indexes import IndexExpression
from django.db.models.sql import Query
from django.test import SimpleTestCase, TransactionTestCase
from .models import Person
class TableTests(SimpleTestCase):
def setUp(self):
self.reference = Table("table", lambda table: table.upper())
def test_references_table(self):
self.assertIs(self.reference.references_table("table"), True)
self.assertIs(self.reference.references_table("other"), False)
def test_rename_table_references(self):
self.reference.rename_table_references("other", "table")
self.assertIs(self.reference.references_table("table"), True)
self.assertIs(self.reference.references_table("other"), False)
self.reference.rename_table_references("table", "other")
self.assertIs(self.reference.references_table("table"), False)
self.assertIs(self.reference.references_table("other"), True)
def test_repr(self):
self.assertEqual(repr(self.reference), "<Table 'TABLE'>")
def test_str(self):
self.assertEqual(str(self.reference), "TABLE")
class ColumnsTests(TableTests):
def setUp(self):
self.reference = Columns(
"table", ["first_column", "second_column"], lambda column: column.upper()
)
def test_references_column(self):
self.assertIs(self.reference.references_column("other", "first_column"), False)
self.assertIs(self.reference.references_column("table", "third_column"), False)
self.assertIs(self.reference.references_column("table", "first_column"), True)
def test_rename_column_references(self):
self.reference.rename_column_references("other", "first_column", "third_column")
self.assertIs(self.reference.references_column("table", "first_column"), True)
self.assertIs(self.reference.references_column("table", "third_column"), False)
self.assertIs(self.reference.references_column("other", "third_column"), False)
self.reference.rename_column_references("table", "third_column", "first_column")
self.assertIs(self.reference.references_column("table", "first_column"), True)
self.assertIs(self.reference.references_column("table", "third_column"), False)
self.reference.rename_column_references("table", "first_column", "third_column")
self.assertIs(self.reference.references_column("table", "first_column"), False)
self.assertIs(self.reference.references_column("table", "third_column"), True)
def test_repr(self):
self.assertEqual(
repr(self.reference), "<Columns 'FIRST_COLUMN, SECOND_COLUMN'>"
)
def test_str(self):
self.assertEqual(str(self.reference), "FIRST_COLUMN, SECOND_COLUMN")
class IndexNameTests(ColumnsTests):
def setUp(self):
def create_index_name(table_name, column_names, suffix):
return ", ".join(
"%s_%s_%s" % (table_name, column_name, suffix)
for column_name in column_names
)
self.reference = IndexName(
"table", ["first_column", "second_column"], "suffix", create_index_name
)
def test_repr(self):
self.assertEqual(
repr(self.reference),
"<IndexName 'table_first_column_suffix, table_second_column_suffix'>",
)
def test_str(self):
self.assertEqual(
str(self.reference), "table_first_column_suffix, table_second_column_suffix"
)
class ForeignKeyNameTests(IndexNameTests):
def setUp(self):
def create_foreign_key_name(table_name, column_names, suffix):
return ", ".join(
"%s_%s_%s" % (table_name, column_name, suffix)
for column_name in column_names
)
self.reference = ForeignKeyName(
"table",
["first_column", "second_column"],
"to_table",
["to_first_column", "to_second_column"],
"%(to_table)s_%(to_column)s_fk",
create_foreign_key_name,
)
def test_references_table(self):
super().test_references_table()
self.assertIs(self.reference.references_table("to_table"), True)
def test_references_column(self):
super().test_references_column()
self.assertIs(
self.reference.references_column("to_table", "second_column"), False
)
self.assertIs(
self.reference.references_column("to_table", "to_second_column"), True
)
def test_rename_table_references(self):
super().test_rename_table_references()
self.reference.rename_table_references("to_table", "other_to_table")
self.assertIs(self.reference.references_table("other_to_table"), True)
self.assertIs(self.reference.references_table("to_table"), False)
def test_rename_column_references(self):
super().test_rename_column_references()
self.reference.rename_column_references(
"to_table", "second_column", "third_column"
)
self.assertIs(self.reference.references_column("table", "second_column"), True)
self.assertIs(
self.reference.references_column("to_table", "to_second_column"), True
)
self.reference.rename_column_references(
"to_table", "to_first_column", "to_third_column"
)
self.assertIs(
self.reference.references_column("to_table", "to_first_column"), False
)
self.assertIs(
self.reference.references_column("to_table", "to_third_column"), True
)
def test_repr(self):
self.assertEqual(
repr(self.reference),
"<ForeignKeyName 'table_first_column_to_table_to_first_column_fk, "
"table_second_column_to_table_to_first_column_fk'>",
)
def test_str(self):
self.assertEqual(
str(self.reference),
"table_first_column_to_table_to_first_column_fk, "
"table_second_column_to_table_to_first_column_fk",
)
class MockReference:
def __init__(
self, representation, referenced_tables, referenced_columns, referenced_indexes
):
self.representation = representation
self.referenced_tables = referenced_tables
self.referenced_columns = referenced_columns
self.referenced_indexes = referenced_indexes
def references_table(self, table):
return table in self.referenced_tables
def references_column(self, table, column):
return (table, column) in self.referenced_columns
def references_index(self, table, index):
return (table, index) in self.referenced_indexes
def rename_table_references(self, old_table, new_table):
if old_table in self.referenced_tables:
self.referenced_tables.remove(old_table)
self.referenced_tables.add(new_table)
def rename_column_references(self, table, old_column, new_column):
column = (table, old_column)
if column in self.referenced_columns:
self.referenced_columns.remove(column)
self.referenced_columns.add((table, new_column))
def __str__(self):
return self.representation
class StatementTests(SimpleTestCase):
def test_references_table(self):
statement = Statement(
"", reference=MockReference("", {"table"}, {}, {}), non_reference=""
)
self.assertIs(statement.references_table("table"), True)
self.assertIs(statement.references_table("other"), False)
def test_references_column(self):
statement = Statement(
"",
reference=MockReference("", {}, {("table", "column")}, {}),
non_reference="",
)
self.assertIs(statement.references_column("table", "column"), True)
self.assertIs(statement.references_column("other", "column"), False)
def test_references_index(self):
statement = Statement(
"",
reference=MockReference("", {}, {}, {("table", "index")}),
non_reference="",
)
self.assertIs(statement.references_index("table", "index"), True)
self.assertIs(statement.references_index("other", "index"), False)
def test_rename_table_references(self):
reference = MockReference("", {"table"}, {}, {})
statement = Statement("", reference=reference, non_reference="")
statement.rename_table_references("table", "other")
self.assertEqual(reference.referenced_tables, {"other"})
def test_rename_column_references(self):
reference = MockReference("", {}, {("table", "column")}, {})
statement = Statement("", reference=reference, non_reference="")
statement.rename_column_references("table", "column", "other")
self.assertEqual(reference.referenced_columns, {("table", "other")})
def test_repr(self):
reference = MockReference("reference", {}, {}, {})
statement = Statement(
"%(reference)s - %(non_reference)s",
reference=reference,
non_reference="non_reference",
)
self.assertEqual(repr(statement), "<Statement 'reference - non_reference'>")
def test_str(self):
reference = MockReference("reference", {}, {}, {})
statement = Statement(
"%(reference)s - %(non_reference)s",
reference=reference,
non_reference="non_reference",
)
self.assertEqual(str(statement), "reference - non_reference")
class ExpressionsTests(TransactionTestCase):
available_apps = []
def setUp(self):
compiler = Person.objects.all().query.get_compiler(connection.alias)
self.editor = connection.schema_editor()
self.expressions = Expressions(
table=Person._meta.db_table,
expressions=ExpressionList(
IndexExpression(F("first_name")),
IndexExpression(F("last_name").desc()),
IndexExpression(Upper("last_name")),
).resolve_expression(compiler.query),
compiler=compiler,
quote_value=self.editor.quote_value,
)
def test_references_table(self):
self.assertIs(self.expressions.references_table(Person._meta.db_table), True)
self.assertIs(self.expressions.references_table("other"), False)
def test_references_column(self):
table = Person._meta.db_table
self.assertIs(self.expressions.references_column(table, "first_name"), True)
self.assertIs(self.expressions.references_column(table, "last_name"), True)
self.assertIs(self.expressions.references_column(table, "other"), False)
def test_rename_table_references(self):
table = Person._meta.db_table
self.expressions.rename_table_references(table, "other")
self.assertIs(self.expressions.references_table(table), False)
self.assertIs(self.expressions.references_table("other"), True)
self.assertIn(
"%s.%s"
% (
self.editor.quote_name("other"),
self.editor.quote_name("first_name"),
),
str(self.expressions),
)
def test_rename_table_references_without_alias(self):
compiler = Query(Person, alias_cols=False).get_compiler(connection=connection)
table = Person._meta.db_table
expressions = Expressions(
table=table,
expressions=ExpressionList(
IndexExpression(Upper("last_name")),
IndexExpression(F("first_name")),
).resolve_expression(compiler.query),
compiler=compiler,
quote_value=self.editor.quote_value,
)
expressions.rename_table_references(table, "other")
self.assertIs(expressions.references_table(table), False)
self.assertIs(expressions.references_table("other"), True)
expected_str = "(UPPER(%s)), %s" % (
self.editor.quote_name("last_name"),
self.editor.quote_name("first_name"),
)
self.assertEqual(str(expressions), expected_str)
def test_rename_column_references(self):
table = Person._meta.db_table
self.expressions.rename_column_references(table, "first_name", "other")
self.assertIs(self.expressions.references_column(table, "other"), True)
self.assertIs(self.expressions.references_column(table, "first_name"), False)
self.assertIn(
"%s.%s" % (self.editor.quote_name(table), self.editor.quote_name("other")),
str(self.expressions),
)
def test_str(self):
table_name = self.editor.quote_name(Person._meta.db_table)
expected_str = "%s.%s, %s.%s DESC, (UPPER(%s.%s))" % (
table_name,
self.editor.quote_name("first_name"),
table_name,
self.editor.quote_name("last_name"),
table_name,
self.editor.quote_name("last_name"),
)
self.assertEqual(str(self.expressions), expected_str)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/backends/oracle/test_operations.py | tests/backends/oracle/test_operations.py | import unittest
from django.core.management.color import no_style
from django.db import connection, models
from django.test import TransactionTestCase
from ..models import Person, Tag
@unittest.skipUnless(connection.vendor == "oracle", "Oracle tests")
class OperationsTests(TransactionTestCase):
available_apps = ["backends"]
def test_sequence_name_truncation(self):
seq_name = connection.ops._get_no_autofield_sequence_name(
"schema_authorwithevenlongee869"
)
self.assertEqual(seq_name, "SCHEMA_AUTHORWITHEVENLOB0B8_SQ")
def test_bulk_batch_size(self):
# Oracle restricts the number of parameters in a query.
objects = range(2**16)
self.assertEqual(connection.ops.bulk_batch_size([], objects), len(objects))
# Each field is a parameter for each object.
first_name_field = Person._meta.get_field("first_name")
last_name_field = Person._meta.get_field("last_name")
self.assertEqual(
connection.ops.bulk_batch_size([first_name_field], objects),
connection.features.max_query_params,
)
self.assertEqual(
connection.ops.bulk_batch_size(
[first_name_field, last_name_field],
objects,
),
connection.features.max_query_params // 2,
)
composite_pk = models.CompositePrimaryKey("first_name", "last_name")
composite_pk.fields = [first_name_field, last_name_field]
self.assertEqual(
connection.ops.bulk_batch_size([composite_pk, first_name_field], objects),
connection.features.max_query_params // 3,
)
def test_sql_flush(self):
statements = connection.ops.sql_flush(
no_style(),
[Person._meta.db_table, Tag._meta.db_table],
)
# The tables and constraints are processed in an unordered set.
self.assertEqual(
statements[0],
'ALTER TABLE "BACKENDS_TAG" DISABLE CONSTRAINT '
'"BACKENDS__CONTENT_T_FD9D7A85_F" KEEP INDEX;',
)
self.assertEqual(
sorted(statements[1:-1]),
[
'TRUNCATE TABLE "BACKENDS_PERSON";',
'TRUNCATE TABLE "BACKENDS_TAG";',
],
)
self.assertEqual(
statements[-1],
'ALTER TABLE "BACKENDS_TAG" ENABLE CONSTRAINT '
'"BACKENDS__CONTENT_T_FD9D7A85_F";',
)
def test_sql_flush_allow_cascade(self):
statements = connection.ops.sql_flush(
no_style(),
[Person._meta.db_table, Tag._meta.db_table],
allow_cascade=True,
)
# The tables and constraints are processed in an unordered set.
self.assertEqual(
statements[0],
'ALTER TABLE "BACKENDS_VERYLONGMODELNAME540F" DISABLE CONSTRAINT '
'"BACKENDS__PERSON_ID_1DD5E829_F" KEEP INDEX;',
)
self.assertEqual(
sorted(statements[1:-1]),
[
'TRUNCATE TABLE "BACKENDS_PERSON";',
'TRUNCATE TABLE "BACKENDS_TAG";',
'TRUNCATE TABLE "BACKENDS_VERYLONGMODELNAME540F";',
],
)
self.assertEqual(
statements[-1],
'ALTER TABLE "BACKENDS_VERYLONGMODELNAME540F" ENABLE CONSTRAINT '
'"BACKENDS__PERSON_ID_1DD5E829_F";',
)
def test_sql_flush_sequences(self):
statements = connection.ops.sql_flush(
no_style(),
[Person._meta.db_table, Tag._meta.db_table],
reset_sequences=True,
)
# The tables and constraints are processed in an unordered set.
self.assertEqual(
statements[0],
'ALTER TABLE "BACKENDS_TAG" DISABLE CONSTRAINT '
'"BACKENDS__CONTENT_T_FD9D7A85_F" KEEP INDEX;',
)
self.assertEqual(
sorted(statements[1:3]),
[
'TRUNCATE TABLE "BACKENDS_PERSON";',
'TRUNCATE TABLE "BACKENDS_TAG";',
],
)
self.assertEqual(
statements[3],
'ALTER TABLE "BACKENDS_TAG" ENABLE CONSTRAINT '
'"BACKENDS__CONTENT_T_FD9D7A85_F";',
)
# Sequences.
self.assertEqual(len(statements[4:]), 2)
self.assertIn("BACKENDS_PERSON_SQ", statements[4])
self.assertIn("BACKENDS_TAG_SQ", statements[5])
def test_sql_flush_sequences_allow_cascade(self):
statements = connection.ops.sql_flush(
no_style(),
[Person._meta.db_table, Tag._meta.db_table],
reset_sequences=True,
allow_cascade=True,
)
# The tables and constraints are processed in an unordered set.
self.assertEqual(
statements[0],
'ALTER TABLE "BACKENDS_VERYLONGMODELNAME540F" DISABLE CONSTRAINT '
'"BACKENDS__PERSON_ID_1DD5E829_F" KEEP INDEX;',
)
self.assertEqual(
sorted(statements[1:4]),
[
'TRUNCATE TABLE "BACKENDS_PERSON";',
'TRUNCATE TABLE "BACKENDS_TAG";',
'TRUNCATE TABLE "BACKENDS_VERYLONGMODELNAME540F";',
],
)
self.assertEqual(
statements[4],
'ALTER TABLE "BACKENDS_VERYLONGMODELNAME540F" ENABLE CONSTRAINT '
'"BACKENDS__PERSON_ID_1DD5E829_F";',
)
# Sequences.
self.assertEqual(len(statements[5:]), 3)
self.assertIn("BACKENDS_PERSON_SQ", statements[5])
self.assertIn("BACKENDS_VERYLONGMODELN7BE2_SQ", statements[6])
self.assertIn("BACKENDS_TAG_SQ", statements[7])
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/backends/oracle/test_creation.py | tests/backends/oracle/test_creation.py | import unittest
from io import StringIO
from unittest import mock
from django.db import DatabaseError, connection
from django.db.backends.oracle.creation import DatabaseCreation
from django.test import TestCase
@unittest.skipUnless(connection.vendor == "oracle", "Oracle tests")
@mock.patch.object(DatabaseCreation, "_maindb_connection", return_value=connection)
@mock.patch("sys.stdout", new_callable=StringIO)
@mock.patch("sys.stderr", new_callable=StringIO)
class DatabaseCreationTests(TestCase):
def _execute_raise_user_already_exists(
self, cursor, statements, parameters, verbosity, allow_quiet_fail=False
):
# Raise "user already exists" only in test user creation
if statements and statements[0].startswith("CREATE USER"):
raise DatabaseError(
"ORA-01920: user name 'string' conflicts with another user or role name"
)
def _execute_raise_tablespace_already_exists(
self, cursor, statements, parameters, verbosity, allow_quiet_fail=False
):
raise DatabaseError("ORA-01543: tablespace 'string' already exists")
def _execute_raise_insufficient_privileges(
self, cursor, statements, parameters, verbosity, allow_quiet_fail=False
):
raise DatabaseError("ORA-01031: insufficient privileges")
def _test_database_passwd(self):
# Mocked to avoid test user password changed
return connection.settings_dict["SAVED_PASSWORD"]
def patch_execute_statements(self, execute_statements):
return mock.patch.object(
DatabaseCreation, "_execute_statements", execute_statements
)
@mock.patch.object(DatabaseCreation, "_test_user_create", return_value=False)
def test_create_test_db(self, *mocked_objects):
creation = DatabaseCreation(connection)
# Simulate test database creation raising "tablespace already exists"
with self.patch_execute_statements(
self._execute_raise_tablespace_already_exists
):
with mock.patch("builtins.input", return_value="no"):
with self.assertRaises(SystemExit):
# SystemExit is raised if the user answers "no" to the
# prompt asking if it's okay to delete the test tablespace.
creation._create_test_db(verbosity=0, keepdb=False)
# "Tablespace already exists" error is ignored when keepdb is on
creation._create_test_db(verbosity=0, keepdb=True)
# Simulate test database creation raising unexpected error
with self.patch_execute_statements(self._execute_raise_insufficient_privileges):
with self.assertRaises(SystemExit):
creation._create_test_db(verbosity=0, keepdb=False)
with self.assertRaises(SystemExit):
creation._create_test_db(verbosity=0, keepdb=True)
@mock.patch.object(DatabaseCreation, "_test_database_create", return_value=False)
def test_create_test_user(self, *mocked_objects):
creation = DatabaseCreation(connection)
with mock.patch.object(
DatabaseCreation, "_test_database_passwd", self._test_database_passwd
):
# Simulate test user creation raising "user already exists"
with self.patch_execute_statements(self._execute_raise_user_already_exists):
with mock.patch("builtins.input", return_value="no"):
with self.assertRaises(SystemExit):
# SystemExit is raised if the user answers "no" to the
# prompt asking if it's okay to delete the test user.
creation._create_test_db(verbosity=0, keepdb=False)
# "User already exists" error is ignored when keepdb is on
creation._create_test_db(verbosity=0, keepdb=True)
# Simulate test user creation raising unexpected error
with self.patch_execute_statements(
self._execute_raise_insufficient_privileges
):
with self.assertRaises(SystemExit):
creation._create_test_db(verbosity=0, keepdb=False)
with self.assertRaises(SystemExit):
creation._create_test_db(verbosity=0, keepdb=True)
def test_oracle_managed_files(self, *mocked_objects):
def _execute_capture_statements(
self, cursor, statements, parameters, verbosity, allow_quiet_fail=False
):
self.tblspace_sqls = statements
creation = DatabaseCreation(connection)
# Simulate test database creation with Oracle Managed File (OMF)
# tablespaces.
with mock.patch.object(
DatabaseCreation, "_test_database_oracle_managed_files", return_value=True
):
with self.patch_execute_statements(_execute_capture_statements):
with connection.cursor() as cursor:
creation._execute_test_db_creation(
cursor, creation._get_test_db_params(), verbosity=0
)
tblspace_sql, tblspace_tmp_sql = creation.tblspace_sqls
# Datafile names shouldn't appear.
self.assertIn("DATAFILE SIZE", tblspace_sql)
self.assertIn("TEMPFILE SIZE", tblspace_tmp_sql)
# REUSE cannot be used with OMF.
self.assertNotIn("REUSE", tblspace_sql)
self.assertNotIn("REUSE", tblspace_tmp_sql)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/backends/oracle/__init__.py | tests/backends/oracle/__init__.py | python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false | |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/backends/oracle/tests.py | tests/backends/oracle/tests.py | import copy
import unittest
from unittest import mock
from django.core.exceptions import ImproperlyConfigured
from django.db import NotSupportedError, ProgrammingError, connection
from django.db.models import BooleanField
from django.test import TestCase, TransactionTestCase
from ..models import VeryLongModelNameZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ
def no_pool_connection(alias=None):
new_connection = connection.copy(alias)
new_connection.settings_dict = copy.deepcopy(connection.settings_dict)
# Ensure that the second connection circumvents the pool, this is kind
# of a hack, but we cannot easily change the pool connections.
new_connection.settings_dict["OPTIONS"]["pool"] = False
return new_connection
@unittest.skipUnless(connection.vendor == "oracle", "Oracle tests")
class Tests(TestCase):
def test_quote_name(self):
"""'%' chars are escaped for query execution."""
name = '"SOME%NAME"'
quoted_name = connection.ops.quote_name(name)
self.assertEqual(quoted_name % (), name)
def test_quote_name_db_table(self):
model = VeryLongModelNameZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ
db_table = model._meta.db_table.upper()
self.assertEqual(
f'"{db_table}"',
connection.ops.quote_name(
"backends_verylongmodelnamezzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz",
),
)
def test_dbms_session(self):
"""A stored procedure can be called through a cursor wrapper."""
with connection.cursor() as cursor:
cursor.callproc("DBMS_SESSION.SET_IDENTIFIER", ["_django_testing!"])
def test_cursor_var(self):
"""Cursor variables can be passed as query parameters."""
with connection.cursor() as cursor:
var = cursor.var(str)
cursor.execute("BEGIN %s := 'X'; END; ", [var])
self.assertEqual(var.getvalue(), "X")
def test_order_of_nls_parameters(self):
"""
An 'almost right' datetime works with configured NLS parameters
(#18465).
"""
suffix = connection.features.bare_select_suffix
with connection.cursor() as cursor:
query = f"SELECT 1{suffix} WHERE '1936-12-29 00:00' < SYSDATE"
# The query succeeds without errors - pre #18465 this
# wasn't the case.
cursor.execute(query)
self.assertEqual(cursor.fetchone()[0], 1)
def test_boolean_constraints(self):
"""Boolean fields have check constraints on their values."""
for field in (BooleanField(), BooleanField(null=True)):
with self.subTest(field=field):
field.set_attributes_from_name("is_nice")
self.assertIn('"IS_NICE" IN (0,1)', field.db_check(connection))
@mock.patch.object(
connection,
"get_database_version",
return_value=(18, 1),
)
def test_check_database_version_supported(self, mocked_get_database_version):
msg = "Oracle 19 or later is required (found 18.1)."
with self.assertRaisesMessage(NotSupportedError, msg):
connection.check_database_version_supported()
self.assertTrue(mocked_get_database_version.called)
def test_pool_set_to_true(self):
new_connection = no_pool_connection(alias="default_pool")
new_connection.settings_dict["OPTIONS"]["pool"] = True
try:
self.assertIsNotNone(new_connection.pool)
finally:
new_connection.close_pool()
def test_pool_reuse(self):
new_connection = no_pool_connection(alias="default_pool")
new_connection.settings_dict["OPTIONS"]["pool"] = {
"min": 0,
"max": 2,
}
self.assertIsNotNone(new_connection.pool)
connections = []
def get_connection():
# copy() reuses the existing alias and as such the same pool.
conn = new_connection.copy()
conn.connect()
connections.append(conn)
return conn
try:
connection_1 = get_connection() # First connection.
get_connection() # Get the second connection.
sql = "select sys_context('userenv', 'sid') from dual"
sids = [conn.cursor().execute(sql).fetchone()[0] for conn in connections]
connection_1.close() # Release back to the pool.
connection_3 = get_connection()
sid = connection_3.cursor().execute(sql).fetchone()[0]
# Reuses the first connection as it is available.
self.assertEqual(sid, sids[0])
finally:
# Release all connections back to the pool.
for conn in connections:
conn.close()
new_connection.close_pool()
def test_cannot_open_new_connection_in_atomic_block(self):
new_connection = no_pool_connection(alias="default_pool")
new_connection.settings_dict["OPTIONS"]["pool"] = True
msg = "Cannot open a new connection in an atomic block."
new_connection.in_atomic_block = True
new_connection.closed_in_transaction = True
with self.assertRaisesMessage(ProgrammingError, msg):
new_connection.ensure_connection()
def test_pooling_not_support_persistent_connections(self):
new_connection = no_pool_connection(alias="default_pool")
new_connection.settings_dict["OPTIONS"]["pool"] = True
new_connection.settings_dict["CONN_MAX_AGE"] = 10
msg = "Pooling doesn't support persistent connections."
with self.assertRaisesMessage(ImproperlyConfigured, msg):
new_connection.pool
@unittest.skipUnless(connection.vendor == "oracle", "Oracle tests")
class TransactionalTests(TransactionTestCase):
available_apps = ["backends"]
def test_password_with_at_sign(self):
from django.db.backends.oracle.base import Database
old_password = connection.settings_dict["PASSWORD"]
connection.settings_dict["PASSWORD"] = "p@ssword"
try:
self.assertIn(
'/"p@ssword"@',
connection.client.connect_string(connection.settings_dict),
)
with self.assertRaises(Database.DatabaseError) as context:
connection.connect()
# Database exception: "ORA-01017: invalid username/password" is
# expected.
self.assertIn("ORA-01017", context.exception.args[0].message)
finally:
connection.settings_dict["PASSWORD"] = old_password
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/backends/oracle/test_introspection.py | tests/backends/oracle/test_introspection.py | import unittest
from django.db import connection
from django.test import TransactionTestCase, skipUnlessDBFeature
from ..models import Person, Square
@unittest.skipUnless(connection.vendor == "oracle", "Oracle tests")
class DatabaseSequenceTests(TransactionTestCase):
available_apps = []
def test_get_sequences(self):
with connection.cursor() as cursor:
seqs = connection.introspection.get_sequences(
cursor, Square._meta.db_table, Square._meta.local_fields
)
self.assertEqual(len(seqs), 1)
self.assertIsNotNone(seqs[0]["name"])
self.assertEqual(seqs[0]["table"], Square._meta.db_table)
self.assertEqual(seqs[0]["column"], "id")
def test_get_sequences_manually_created_index(self):
with connection.cursor() as cursor:
with connection.schema_editor() as editor:
editor._drop_identity(Square._meta.db_table, "id")
seqs = connection.introspection.get_sequences(
cursor, Square._meta.db_table, Square._meta.local_fields
)
self.assertEqual(
seqs, [{"table": Square._meta.db_table, "column": "id"}]
)
# Recreate model, because adding identity is impossible.
editor.delete_model(Square)
editor.create_model(Square)
@skipUnlessDBFeature("supports_collation_on_charfield")
def test_get_table_description_view_default_collation(self):
person_table = connection.introspection.identifier_converter(
Person._meta.db_table
)
first_name_column = connection.ops.quote_name(
Person._meta.get_field("first_name").column
)
person_view = connection.introspection.identifier_converter("TEST_PERSON_VIEW")
with connection.cursor() as cursor:
cursor.execute(
f"CREATE VIEW {person_view} "
f"AS SELECT {first_name_column} FROM {person_table}"
)
try:
columns = connection.introspection.get_table_description(
cursor, person_view
)
self.assertEqual(len(columns), 1)
self.assertIsNone(columns[0].collation)
finally:
cursor.execute(f"DROP VIEW {person_view}")
@skipUnlessDBFeature("supports_collation_on_charfield")
def test_get_table_description_materialized_view_non_default_collation(self):
person_table = connection.introspection.identifier_converter(
Person._meta.db_table
)
first_name_column = connection.ops.quote_name(
Person._meta.get_field("first_name").column
)
person_mview = connection.introspection.identifier_converter(
"TEST_PERSON_MVIEW"
)
collation = connection.features.test_collations.get("ci")
with connection.cursor() as cursor:
cursor.execute(
f"CREATE MATERIALIZED VIEW {person_mview} "
f"DEFAULT COLLATION {collation} "
f"AS SELECT {first_name_column} FROM {person_table}"
)
try:
columns = connection.introspection.get_table_description(
cursor, person_mview
)
self.assertEqual(len(columns), 1)
self.assertIsNotNone(columns[0].collation)
self.assertNotEqual(columns[0].collation, collation)
finally:
cursor.execute(f"DROP MATERIALIZED VIEW {person_mview}")
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/backends/postgresql/test_operations.py | tests/backends/postgresql/test_operations.py | import unittest
from django.core.management.color import no_style
from django.db import connection
from django.db.models.expressions import Col
from django.db.models.functions import Cast
from django.test import SimpleTestCase
from ..models import Author, Book, Person, Tag
@unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL tests.")
class PostgreSQLOperationsTests(SimpleTestCase):
def test_sql_flush(self):
self.assertEqual(
connection.ops.sql_flush(
no_style(),
[Person._meta.db_table, Tag._meta.db_table],
),
['TRUNCATE "backends_person", "backends_tag";'],
)
def test_sql_flush_allow_cascade(self):
self.assertEqual(
connection.ops.sql_flush(
no_style(),
[Person._meta.db_table, Tag._meta.db_table],
allow_cascade=True,
),
['TRUNCATE "backends_person", "backends_tag" CASCADE;'],
)
def test_sql_flush_sequences(self):
self.assertEqual(
connection.ops.sql_flush(
no_style(),
[Person._meta.db_table, Tag._meta.db_table],
reset_sequences=True,
),
['TRUNCATE "backends_person", "backends_tag" RESTART IDENTITY;'],
)
def test_sql_flush_sequences_allow_cascade(self):
self.assertEqual(
connection.ops.sql_flush(
no_style(),
[Person._meta.db_table, Tag._meta.db_table],
reset_sequences=True,
allow_cascade=True,
),
['TRUNCATE "backends_person", "backends_tag" RESTART IDENTITY CASCADE;'],
)
def test_prepare_join_on_clause_same_type(self):
author_table = Author._meta.db_table
author_id_field = Author._meta.get_field("id")
lhs_expr, rhs_expr = connection.ops.prepare_join_on_clause(
author_table,
author_id_field,
author_table,
author_id_field,
)
self.assertEqual(lhs_expr, Col(author_table, author_id_field))
self.assertEqual(rhs_expr, Col(author_table, author_id_field))
def test_prepare_join_on_clause_different_types(self):
author_table = Author._meta.db_table
author_id_field = Author._meta.get_field("id")
book_table = Book._meta.db_table
book_fk_field = Book._meta.get_field("author")
lhs_expr, rhs_expr = connection.ops.prepare_join_on_clause(
author_table,
author_id_field,
book_table,
book_fk_field,
)
self.assertEqual(lhs_expr, Col(author_table, author_id_field))
self.assertEqual(
rhs_expr, Cast(Col(book_table, book_fk_field), author_id_field)
)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/backends/postgresql/test_compilation.py | tests/backends/postgresql/test_compilation.py | import unittest
from datetime import date
from django.db import connection
from django.db.models.expressions import RawSQL
from django.db.utils import DataError
from django.test import TestCase
from ..models import Article, Reporter, Square
@unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL tests")
class BulkCreateUnnestTests(TestCase):
def test_single_object(self):
with self.assertNumQueries(1) as ctx:
Square.objects.bulk_create([Square(root=2, square=4)])
self.assertNotIn("UNNEST", ctx[0]["sql"])
def test_non_literal(self):
with self.assertNumQueries(1) as ctx:
Square.objects.bulk_create(
[Square(root=2, square=RawSQL("%s", (4,))), Square(root=3, square=9)]
)
self.assertNotIn("UNNEST", ctx[0]["sql"])
def test_unnest_eligible(self):
with self.assertNumQueries(1) as ctx:
Square.objects.bulk_create(
[Square(root=2, square=4), Square(root=3, square=9)]
)
self.assertIn("UNNEST", ctx[0]["sql"])
def test_unnest_eligible_db_default(self):
with self.assertNumQueries(1) as ctx:
squares = Square.objects.bulk_create([Square(root=3), Square(root=3)])
self.assertIn("UNNEST", ctx[0]["sql"])
self.assertEqual([square.square for square in squares], [9, 9])
def test_unnest_eligible_foreign_keys(self):
reporter = Reporter.objects.create()
with self.assertNumQueries(1) as ctx:
articles = Article.objects.bulk_create(
[
Article(pub_date=date.today(), reporter=reporter),
Article(pub_date=date.today(), reporter=reporter),
]
)
self.assertIn("UNNEST", ctx[0]["sql"])
self.assertEqual(
[article.reporter for article in articles], [reporter, reporter]
)
def test_parametrized_db_type(self):
with self.assertRaises(DataError):
Reporter.objects.bulk_create(
[
Reporter(),
Reporter(first_name="a" * 31),
]
)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/backends/postgresql/test_creation.py | tests/backends/postgresql/test_creation.py | import unittest
from contextlib import contextmanager
from io import StringIO
from unittest import mock
from django.core.exceptions import ImproperlyConfigured
from django.db import DatabaseError, connection
from django.db.backends.base.creation import BaseDatabaseCreation
from django.test import SimpleTestCase
try:
from django.db.backends.postgresql.psycopg_any import errors
except ImportError:
pass
else:
from django.db.backends.postgresql.creation import DatabaseCreation
@unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL tests")
class DatabaseCreationTests(SimpleTestCase):
@contextmanager
def changed_test_settings(self, **kwargs):
settings = connection.settings_dict["TEST"]
saved_values = {}
for name in kwargs:
if name in settings:
saved_values[name] = settings[name]
for name, value in kwargs.items():
settings[name] = value
try:
yield
finally:
for name in kwargs:
if name in saved_values:
settings[name] = saved_values[name]
else:
del settings[name]
def check_sql_table_creation_suffix(self, settings, expected):
with self.changed_test_settings(**settings):
creation = DatabaseCreation(connection)
suffix = creation.sql_table_creation_suffix()
self.assertEqual(suffix, expected)
def test_sql_table_creation_suffix_with_none_settings(self):
settings = {"CHARSET": None, "TEMPLATE": None}
self.check_sql_table_creation_suffix(settings, "")
def test_sql_table_creation_suffix_with_encoding(self):
settings = {"CHARSET": "UTF8"}
self.check_sql_table_creation_suffix(settings, "WITH ENCODING 'UTF8'")
def test_sql_table_creation_suffix_with_template(self):
settings = {"TEMPLATE": "template0"}
self.check_sql_table_creation_suffix(settings, 'WITH TEMPLATE "template0"')
def test_sql_table_creation_suffix_with_encoding_and_template(self):
settings = {"CHARSET": "UTF8", "TEMPLATE": "template0"}
self.check_sql_table_creation_suffix(
settings, '''WITH ENCODING 'UTF8' TEMPLATE "template0"'''
)
def test_sql_table_creation_raises_with_collation(self):
settings = {"COLLATION": "test"}
msg = (
"PostgreSQL does not support collation setting at database "
"creation time."
)
with self.assertRaisesMessage(ImproperlyConfigured, msg):
self.check_sql_table_creation_suffix(settings, None)
def _execute_raise_database_already_exists(self, cursor, parameters, keepdb=False):
error = errors.DuplicateDatabase(
"database %s already exists" % parameters["dbname"]
)
raise DatabaseError() from error
def _execute_raise_permission_denied(self, cursor, parameters, keepdb=False):
error = errors.InsufficientPrivilege("permission denied to create database")
raise DatabaseError() from error
def patch_test_db_creation(self, execute_create_test_db):
return mock.patch.object(
BaseDatabaseCreation, "_execute_create_test_db", execute_create_test_db
)
@mock.patch("sys.stdout", new_callable=StringIO)
@mock.patch("sys.stderr", new_callable=StringIO)
def test_create_test_db(self, *mocked_objects):
creation = DatabaseCreation(connection)
# Simulate test database creation raising "database already exists"
with self.patch_test_db_creation(self._execute_raise_database_already_exists):
with mock.patch("builtins.input", return_value="no"):
with self.assertRaises(SystemExit):
# SystemExit is raised if the user answers "no" to the
# prompt asking if it's okay to delete the test database.
creation._create_test_db(
verbosity=0, autoclobber=False, keepdb=False
)
# "Database already exists" error is ignored when keepdb is on
creation._create_test_db(verbosity=0, autoclobber=False, keepdb=True)
# Simulate test database creation raising unexpected error
with self.patch_test_db_creation(self._execute_raise_permission_denied):
with mock.patch.object(
DatabaseCreation, "_database_exists", return_value=False
):
with self.assertRaises(SystemExit):
creation._create_test_db(
verbosity=0, autoclobber=False, keepdb=False
)
with self.assertRaises(SystemExit):
creation._create_test_db(
verbosity=0, autoclobber=False, keepdb=True
)
# Simulate test database creation raising "insufficient privileges".
# An error shouldn't appear when keepdb is on and the database already
# exists.
with self.patch_test_db_creation(self._execute_raise_permission_denied):
with mock.patch.object(
DatabaseCreation, "_database_exists", return_value=True
):
creation._create_test_db(verbosity=0, autoclobber=False, keepdb=True)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/backends/postgresql/__init__.py | tests/backends/postgresql/__init__.py | python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false | |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/backends/postgresql/tests.py | tests/backends/postgresql/tests.py | import copy
import unittest
from io import StringIO
from unittest import mock
from django.core.exceptions import ImproperlyConfigured
from django.db import (
DEFAULT_DB_ALIAS,
DatabaseError,
NotSupportedError,
ProgrammingError,
connection,
connections,
)
from django.db.backends.base.base import BaseDatabaseWrapper
from django.test import TestCase, override_settings
try:
from django.db.backends.postgresql.psycopg_any import errors, is_psycopg3
except ImportError:
is_psycopg3 = False
def no_pool_connection(alias=None):
new_connection = connection.copy(alias)
new_connection.settings_dict = copy.deepcopy(connection.settings_dict)
# Ensure that the second connection circumvents the pool, this is kind
# of a hack, but we cannot easily change the pool connections.
new_connection.settings_dict["OPTIONS"]["pool"] = False
return new_connection
@unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL tests")
class Tests(TestCase):
databases = {"default", "other"}
def test_nodb_cursor(self):
"""
The _nodb_cursor() fallbacks to the default connection database when
access to the 'postgres' database is not granted.
"""
orig_connect = BaseDatabaseWrapper.connect
def mocked_connect(self):
if self.settings_dict["NAME"] is None:
raise DatabaseError()
return orig_connect(self)
with connection._nodb_cursor() as cursor:
self.assertIs(cursor.closed, False)
self.assertIsNotNone(cursor.db.connection)
self.assertIsNone(cursor.db.settings_dict["NAME"])
self.assertIs(cursor.closed, True)
self.assertIsNone(cursor.db.connection)
# Now assume the 'postgres' db isn't available
msg = (
"Normally Django will use a connection to the 'postgres' database "
"to avoid running initialization queries against the production "
"database when it's not needed (for example, when running tests). "
"Django was unable to create a connection to the 'postgres' "
"database and will use the first PostgreSQL database instead."
)
with self.assertWarnsMessage(RuntimeWarning, msg):
with mock.patch(
"django.db.backends.base.base.BaseDatabaseWrapper.connect",
side_effect=mocked_connect,
autospec=True,
):
with mock.patch.object(
connection,
"settings_dict",
{**connection.settings_dict, "NAME": "postgres"},
):
with connection._nodb_cursor() as cursor:
self.assertIs(cursor.closed, False)
self.assertIsNotNone(cursor.db.connection)
self.assertIs(cursor.closed, True)
self.assertIsNone(cursor.db.connection)
self.assertIsNotNone(cursor.db.settings_dict["NAME"])
self.assertEqual(
cursor.db.settings_dict["NAME"], connections["other"].settings_dict["NAME"]
)
# Cursor is yielded only for the first PostgreSQL database.
with self.assertWarnsMessage(RuntimeWarning, msg):
with mock.patch(
"django.db.backends.base.base.BaseDatabaseWrapper.connect",
side_effect=mocked_connect,
autospec=True,
):
with connection._nodb_cursor() as cursor:
self.assertIs(cursor.closed, False)
self.assertIsNotNone(cursor.db.connection)
def test_nodb_cursor_raises_postgres_authentication_failure(self):
"""
_nodb_cursor() re-raises authentication failure to the 'postgres' db
when other connection to the PostgreSQL database isn't available.
"""
def mocked_connect(self):
raise DatabaseError()
def mocked_all(self):
test_connection = copy.copy(connections[DEFAULT_DB_ALIAS])
test_connection.settings_dict = copy.deepcopy(connection.settings_dict)
test_connection.settings_dict["NAME"] = "postgres"
return [test_connection]
msg = (
"Normally Django will use a connection to the 'postgres' database "
"to avoid running initialization queries against the production "
"database when it's not needed (for example, when running tests). "
"Django was unable to create a connection to the 'postgres' "
"database and will use the first PostgreSQL database instead."
)
with self.assertWarnsMessage(RuntimeWarning, msg):
mocker_connections_all = mock.patch(
"django.utils.connection.BaseConnectionHandler.all",
side_effect=mocked_all,
autospec=True,
)
mocker_connect = mock.patch(
"django.db.backends.base.base.BaseDatabaseWrapper.connect",
side_effect=mocked_connect,
autospec=True,
)
with mocker_connections_all, mocker_connect:
with self.assertRaises(DatabaseError):
with connection._nodb_cursor():
pass
def test_nodb_cursor_reraise_exceptions(self):
with self.assertRaisesMessage(DatabaseError, "exception"):
with connection._nodb_cursor():
raise DatabaseError("exception")
def test_database_name_too_long(self):
from django.db.backends.postgresql.base import DatabaseWrapper
settings = connection.settings_dict.copy()
max_name_length = connection.ops.max_name_length()
settings["NAME"] = "a" + (max_name_length * "a")
msg = (
"The database name '%s' (%d characters) is longer than "
"PostgreSQL's limit of %s characters. Supply a shorter NAME in "
"settings.DATABASES."
) % (settings["NAME"], max_name_length + 1, max_name_length)
with self.assertRaisesMessage(ImproperlyConfigured, msg):
DatabaseWrapper(settings).get_connection_params()
def test_database_name_empty(self):
from django.db.backends.postgresql.base import DatabaseWrapper
settings = connection.settings_dict.copy()
settings["NAME"] = ""
msg = (
"settings.DATABASES is improperly configured. Please supply the "
"NAME or OPTIONS['service'] value."
)
with self.assertRaisesMessage(ImproperlyConfigured, msg):
DatabaseWrapper(settings).get_connection_params()
def test_service_name(self):
from django.db.backends.postgresql.base import DatabaseWrapper
settings = connection.settings_dict.copy()
settings["OPTIONS"] = {"service": "my_service"}
settings["NAME"] = ""
params = DatabaseWrapper(settings).get_connection_params()
self.assertEqual(params["service"], "my_service")
self.assertNotIn("database", params)
def test_service_name_default_db(self):
# None is used to connect to the default 'postgres' db.
from django.db.backends.postgresql.base import DatabaseWrapper
settings = connection.settings_dict.copy()
settings["NAME"] = None
settings["OPTIONS"] = {"service": "django_test"}
params = DatabaseWrapper(settings).get_connection_params()
self.assertEqual(params["dbname"], "postgres")
self.assertNotIn("service", params)
def test_connect_and_rollback(self):
"""
PostgreSQL shouldn't roll back SET TIME ZONE, even if the first
transaction is rolled back (#17062).
"""
new_connection = no_pool_connection()
try:
# Ensure the database default time zone is different than
# the time zone in new_connection.settings_dict. We can
# get the default time zone by reset & show.
with new_connection.cursor() as cursor:
cursor.execute("RESET TIMEZONE")
cursor.execute("SHOW TIMEZONE")
db_default_tz = cursor.fetchone()[0]
new_tz = "Europe/Paris" if db_default_tz == "UTC" else "UTC"
new_connection.close()
# Invalidate timezone name cache, because the setting_changed
# handler cannot know about new_connection.
del new_connection.timezone_name
# Fetch a new connection with the new_tz as default
# time zone, run a query and rollback.
with self.settings(TIME_ZONE=new_tz):
new_connection.set_autocommit(False)
new_connection.rollback()
# Now let's see if the rollback rolled back the SET TIME ZONE.
with new_connection.cursor() as cursor:
cursor.execute("SHOW TIMEZONE")
tz = cursor.fetchone()[0]
self.assertEqual(new_tz, tz)
finally:
new_connection.close()
def test_connect_non_autocommit(self):
"""
The connection wrapper shouldn't believe that autocommit is enabled
after setting the time zone when AUTOCOMMIT is False (#21452).
"""
new_connection = no_pool_connection()
new_connection.settings_dict["AUTOCOMMIT"] = False
try:
# Open a database connection.
with new_connection.cursor():
self.assertFalse(new_connection.get_autocommit())
finally:
new_connection.close()
@unittest.skipUnless(is_psycopg3, "psycopg3 specific test")
def test_connect_pool(self):
from psycopg_pool import PoolTimeout
new_connection = no_pool_connection(alias="default_pool")
new_connection.settings_dict["OPTIONS"]["pool"] = {
"min_size": 0,
"max_size": 2,
"timeout": 5,
}
self.assertIsNotNone(new_connection.pool)
connections = []
def get_connection():
# copy() reuses the existing alias and as such the same pool.
conn = new_connection.copy()
conn.connect()
connections.append(conn)
return conn
try:
connection_1 = get_connection() # First connection.
connection_1_backend_pid = connection_1.connection.info.backend_pid
get_connection() # Get the second connection.
with self.assertRaises(PoolTimeout):
# The pool has a maximum of 2 connections.
get_connection()
connection_1.close() # Release back to the pool.
connection_3 = get_connection()
# Reuses the first connection as it is available.
self.assertEqual(
connection_3.connection.info.backend_pid, connection_1_backend_pid
)
finally:
# Release all connections back to the pool.
for conn in connections:
conn.close()
new_connection.close_pool()
@unittest.skipUnless(is_psycopg3, "psycopg3 specific test")
def test_connect_pool_set_to_true(self):
new_connection = no_pool_connection(alias="default_pool")
new_connection.settings_dict["OPTIONS"]["pool"] = True
try:
self.assertIsNotNone(new_connection.pool)
finally:
new_connection.close_pool()
@unittest.skipUnless(is_psycopg3, "psycopg3 specific test")
def test_connect_pool_with_timezone(self):
new_time_zone = "Africa/Nairobi"
new_connection = no_pool_connection(alias="default_pool")
try:
with new_connection.cursor() as cursor:
cursor.execute("SHOW TIMEZONE")
tz = cursor.fetchone()[0]
self.assertNotEqual(new_time_zone, tz)
finally:
new_connection.close()
del new_connection.timezone_name
new_connection.settings_dict["OPTIONS"]["pool"] = True
try:
with self.settings(TIME_ZONE=new_time_zone):
with new_connection.cursor() as cursor:
cursor.execute("SHOW TIMEZONE")
tz = cursor.fetchone()[0]
self.assertEqual(new_time_zone, tz)
finally:
new_connection.close()
new_connection.close_pool()
@unittest.skipUnless(is_psycopg3, "psycopg3 specific test")
def test_pooling_health_checks(self):
new_connection = no_pool_connection(alias="default_pool")
new_connection.settings_dict["OPTIONS"]["pool"] = True
new_connection.settings_dict["CONN_HEALTH_CHECKS"] = False
try:
self.assertIsNone(new_connection.pool._check)
finally:
new_connection.close_pool()
new_connection.settings_dict["CONN_HEALTH_CHECKS"] = True
try:
self.assertIsNotNone(new_connection.pool._check)
finally:
new_connection.close_pool()
@unittest.skipUnless(is_psycopg3, "psycopg3 specific test")
def test_cannot_open_new_connection_in_atomic_block(self):
new_connection = no_pool_connection(alias="default_pool")
new_connection.settings_dict["OPTIONS"]["pool"] = True
msg = "Cannot open a new connection in an atomic block."
new_connection.in_atomic_block = True
new_connection.closed_in_transaction = True
with self.assertRaisesMessage(ProgrammingError, msg):
new_connection.ensure_connection()
@unittest.skipUnless(is_psycopg3, "psycopg3 specific test")
def test_pooling_not_support_persistent_connections(self):
new_connection = no_pool_connection(alias="default_pool")
new_connection.settings_dict["OPTIONS"]["pool"] = True
new_connection.settings_dict["CONN_MAX_AGE"] = 10
msg = "Pooling doesn't support persistent connections."
with self.assertRaisesMessage(ImproperlyConfigured, msg):
new_connection.pool
@unittest.skipIf(is_psycopg3, "psycopg2 specific test")
def test_connect_pool_setting_ignored_for_psycopg2(self):
new_connection = no_pool_connection()
new_connection.settings_dict["OPTIONS"]["pool"] = True
msg = "Database pooling requires psycopg >= 3"
with self.assertRaisesMessage(ImproperlyConfigured, msg):
new_connection.connect()
def test_connect_isolation_level(self):
"""
The transaction level can be configured with
DATABASES ['OPTIONS']['isolation_level'].
"""
from django.db.backends.postgresql.psycopg_any import IsolationLevel
# Since this is a django.test.TestCase, a transaction is in progress
# and the isolation level isn't reported as 0. This test assumes that
# PostgreSQL is configured with the default isolation level.
# Check the level on the psycopg connection, not the Django wrapper.
self.assertIsNone(connection.connection.isolation_level)
new_connection = no_pool_connection()
new_connection.settings_dict["OPTIONS"][
"isolation_level"
] = IsolationLevel.SERIALIZABLE
try:
# Start a transaction so the isolation level isn't reported as 0.
new_connection.set_autocommit(False)
# Check the level on the psycopg connection, not the Django
# wrapper.
self.assertEqual(
new_connection.connection.isolation_level,
IsolationLevel.SERIALIZABLE,
)
finally:
new_connection.close()
def test_connect_invalid_isolation_level(self):
self.assertIsNone(connection.connection.isolation_level)
new_connection = no_pool_connection()
new_connection.settings_dict["OPTIONS"]["isolation_level"] = -1
msg = (
"Invalid transaction isolation level -1 specified. Use one of the "
"psycopg.IsolationLevel values."
)
with self.assertRaisesMessage(ImproperlyConfigured, msg):
new_connection.ensure_connection()
def test_connect_role(self):
"""
The session role can be configured with DATABASES
["OPTIONS"]["assume_role"].
"""
try:
custom_role = "django_nonexistent_role"
new_connection = no_pool_connection()
new_connection.settings_dict["OPTIONS"]["assume_role"] = custom_role
msg = f'role "{custom_role}" does not exist'
with self.assertRaisesMessage(errors.InvalidParameterValue, msg):
new_connection.connect()
finally:
new_connection.close()
@unittest.skipUnless(is_psycopg3, "psycopg3 specific test")
def test_connect_server_side_binding(self):
"""
The server-side parameters binding role can be enabled with DATABASES
["OPTIONS"]["server_side_binding"].
"""
from django.db.backends.postgresql.base import ServerBindingCursor
new_connection = no_pool_connection()
new_connection.settings_dict["OPTIONS"]["server_side_binding"] = True
try:
new_connection.connect()
self.assertEqual(
new_connection.connection.cursor_factory,
ServerBindingCursor,
)
finally:
new_connection.close()
def test_connect_custom_cursor_factory(self):
"""
A custom cursor factory can be configured with DATABASES["options"]
["cursor_factory"].
"""
from django.db.backends.postgresql.base import Cursor
class MyCursor(Cursor):
pass
new_connection = no_pool_connection()
new_connection.settings_dict["OPTIONS"]["cursor_factory"] = MyCursor
try:
new_connection.connect()
self.assertEqual(new_connection.connection.cursor_factory, MyCursor)
finally:
new_connection.close()
def test_connect_no_is_usable_checks(self):
new_connection = no_pool_connection()
try:
with mock.patch.object(new_connection, "is_usable") as is_usable:
new_connection.connect()
is_usable.assert_not_called()
finally:
new_connection.close()
def test_client_encoding_utf8_enforce(self):
new_connection = no_pool_connection()
new_connection.settings_dict["OPTIONS"]["client_encoding"] = "iso-8859-2"
try:
new_connection.connect()
if is_psycopg3:
self.assertEqual(new_connection.connection.info.encoding, "utf-8")
else:
self.assertEqual(new_connection.connection.encoding, "UTF8")
finally:
new_connection.close()
def _select(self, val):
with connection.cursor() as cursor:
cursor.execute("SELECT %s::text[]", (val,))
return cursor.fetchone()[0]
def test_select_ascii_array(self):
a = ["awef"]
b = self._select(a)
self.assertEqual(a[0], b[0])
def test_select_unicode_array(self):
a = ["ᄲawef"]
b = self._select(a)
self.assertEqual(a[0], b[0])
def test_lookup_cast(self):
from django.db.backends.postgresql.operations import DatabaseOperations
do = DatabaseOperations(connection=None)
lookups = (
"iexact",
"contains",
"icontains",
"startswith",
"istartswith",
"endswith",
"iendswith",
"regex",
"iregex",
)
for lookup in lookups:
with self.subTest(lookup=lookup):
self.assertIn("::text", do.lookup_cast(lookup))
def test_lookup_cast_isnull_noop(self):
from django.db.backends.postgresql.operations import DatabaseOperations
do = DatabaseOperations(connection=None)
# Using __isnull lookup doesn't require casting.
tests = [
"CharField",
"EmailField",
"TextField",
]
for field_type in tests:
with self.subTest(field_type=field_type):
self.assertEqual(do.lookup_cast("isnull", field_type), "%s")
def test_correct_extraction_psycopg_version(self):
from django.db.backends.postgresql.base import Database, psycopg_version
psycopg_version.cache_clear()
with mock.patch.object(Database, "__version__", "4.2.1 (dt dec pq3 ext lo64)"):
self.addCleanup(psycopg_version.cache_clear)
self.assertEqual(psycopg_version(), (4, 2, 1))
psycopg_version.cache_clear()
with mock.patch.object(
Database, "__version__", "4.2b0.dev1 (dt dec pq3 ext lo64)"
):
self.assertEqual(psycopg_version(), (4, 2))
@override_settings(DEBUG=True)
@unittest.skipIf(is_psycopg3, "psycopg2 specific test")
def test_copy_to_expert_cursors(self):
out = StringIO()
copy_expert_sql = "COPY django_session TO STDOUT (FORMAT CSV, HEADER)"
with connection.cursor() as cursor:
cursor.copy_expert(copy_expert_sql, out)
cursor.copy_to(out, "django_session")
self.assertEqual(
[q["sql"] for q in connection.queries],
[copy_expert_sql, "COPY django_session TO STDOUT"],
)
@override_settings(DEBUG=True)
@unittest.skipUnless(is_psycopg3, "psycopg3 specific test")
def test_copy_cursors(self):
copy_sql = "COPY django_session TO STDOUT (FORMAT CSV, HEADER)"
with connection.cursor() as cursor:
with cursor.copy(copy_sql) as copy:
for row in copy:
pass
self.assertEqual([q["sql"] for q in connection.queries], [copy_sql])
def test_get_database_version(self):
new_connection = no_pool_connection()
new_connection.pg_version = 150009
self.assertEqual(new_connection.get_database_version(), (15, 9))
@mock.patch.object(connection, "get_database_version", return_value=(14,))
def test_check_database_version_supported(self, mocked_get_database_version):
msg = "PostgreSQL 15 or later is required (found 14)."
with self.assertRaisesMessage(NotSupportedError, msg):
connection.check_database_version_supported()
self.assertTrue(mocked_get_database_version.called)
def test_compose_sql_when_no_connection(self):
new_connection = no_pool_connection()
try:
self.assertEqual(
new_connection.ops.compose_sql("SELECT %s", ["test"]),
"SELECT 'test'",
)
finally:
new_connection.close()
def test_bypass_timezone_configuration(self):
from django.db.backends.postgresql.base import DatabaseWrapper
class CustomDatabaseWrapper(DatabaseWrapper):
def _configure_timezone(self, connection):
return False
for Wrapper, commit in [
(DatabaseWrapper, True),
(CustomDatabaseWrapper, False),
]:
with self.subTest(wrapper=Wrapper, commit=commit):
new_connection = no_pool_connection()
self.addCleanup(new_connection.close)
# Set the database default time zone to be different from
# the time zone in new_connection.settings_dict.
with new_connection.cursor() as cursor:
cursor.execute("RESET TIMEZONE")
cursor.execute("SHOW TIMEZONE")
db_default_tz = cursor.fetchone()[0]
new_tz = "Europe/Paris" if db_default_tz == "UTC" else "UTC"
new_connection.timezone_name = new_tz
settings = new_connection.settings_dict.copy()
conn = new_connection.connection
self.assertIs(Wrapper(settings)._configure_connection(conn), commit)
def test_bypass_role_configuration(self):
from django.db.backends.postgresql.base import DatabaseWrapper
class CustomDatabaseWrapper(DatabaseWrapper):
def _configure_role(self, connection):
return False
new_connection = no_pool_connection()
self.addCleanup(new_connection.close)
new_connection.connect()
settings = new_connection.settings_dict.copy()
settings["OPTIONS"]["assume_role"] = "django_nonexistent_role"
conn = new_connection.connection
self.assertIs(
CustomDatabaseWrapper(settings)._configure_connection(conn), False
)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/backends/postgresql/test_introspection.py | tests/backends/postgresql/test_introspection.py | import unittest
from django.db import connection
from django.test import TestCase
from ..models import Person
@unittest.skipUnless(connection.vendor == "postgresql", "Test only for PostgreSQL")
class DatabaseSequenceTests(TestCase):
def test_get_sequences(self):
with connection.cursor() as cursor:
seqs = connection.introspection.get_sequences(cursor, Person._meta.db_table)
self.assertEqual(
seqs,
[
{
"table": Person._meta.db_table,
"column": "id",
"name": "backends_person_id_seq",
}
],
)
cursor.execute("ALTER SEQUENCE backends_person_id_seq RENAME TO pers_seq")
seqs = connection.introspection.get_sequences(cursor, Person._meta.db_table)
self.assertEqual(
seqs,
[{"table": Person._meta.db_table, "column": "id", "name": "pers_seq"}],
)
def test_get_sequences_old_serial(self):
with connection.cursor() as cursor:
cursor.execute("CREATE TABLE testing (serial_field SERIAL);")
seqs = connection.introspection.get_sequences(cursor, "testing")
self.assertEqual(
seqs,
[
{
"table": "testing",
"column": "serial_field",
"name": "testing_serial_field_seq",
}
],
)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/backends/postgresql/test_server_side_cursors.py | tests/backends/postgresql/test_server_side_cursors.py | import operator
import unittest
from collections import namedtuple
from contextlib import contextmanager
from django.db import connection, models
from django.db.utils import ProgrammingError
from django.test import TestCase
from django.test.utils import garbage_collect
from django.utils.version import PYPY
from ..models import Person
try:
from django.db.backends.postgresql.psycopg_any import is_psycopg3
except ImportError:
is_psycopg3 = False
@unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL tests")
class ServerSideCursorsPostgres(TestCase):
cursor_fields = (
"name, statement, is_holdable, is_binary, is_scrollable, creation_time"
)
PostgresCursor = namedtuple("PostgresCursor", cursor_fields)
@classmethod
def setUpTestData(cls):
cls.p0 = Person.objects.create(first_name="a", last_name="a")
cls.p1 = Person.objects.create(first_name="b", last_name="b")
def inspect_cursors(self):
with connection.cursor() as cursor:
cursor.execute(
"SELECT {fields} FROM pg_cursors;".format(fields=self.cursor_fields)
)
cursors = cursor.fetchall()
return [self.PostgresCursor._make(cursor) for cursor in cursors]
@contextmanager
def override_db_setting(self, **kwargs):
for setting in kwargs:
original_value = connection.settings_dict.get(setting)
if setting in connection.settings_dict:
self.addCleanup(
operator.setitem, connection.settings_dict, setting, original_value
)
else:
self.addCleanup(operator.delitem, connection.settings_dict, setting)
connection.settings_dict[setting] = kwargs[setting]
yield
def assertUsesCursor(self, queryset, num_expected=1):
next(queryset) # Open a server-side cursor
cursors = self.inspect_cursors()
self.assertEqual(len(cursors), num_expected)
for cursor in cursors:
self.assertIn("_django_curs_", cursor.name)
self.assertFalse(cursor.is_scrollable)
self.assertFalse(cursor.is_holdable)
self.assertFalse(cursor.is_binary)
def assertNotUsesCursor(self, queryset):
self.assertUsesCursor(queryset, num_expected=0)
def test_server_side_cursor(self):
self.assertUsesCursor(Person.objects.iterator())
def test_values(self):
self.assertUsesCursor(Person.objects.values("first_name").iterator())
def test_values_list(self):
self.assertUsesCursor(Person.objects.values_list("first_name").iterator())
def test_values_list_flat(self):
self.assertUsesCursor(
Person.objects.values_list("first_name", flat=True).iterator()
)
def test_values_list_fields_not_equal_to_names(self):
expr = models.Count("id")
self.assertUsesCursor(
Person.objects.annotate(id__count=expr)
.values_list(expr, "id__count")
.iterator()
)
def test_server_side_cursor_many_cursors(self):
persons = Person.objects.iterator()
persons2 = Person.objects.iterator()
next(persons) # Open a server-side cursor
self.assertUsesCursor(persons2, num_expected=2)
def test_closed_server_side_cursor(self):
persons = Person.objects.iterator()
next(persons) # Open a server-side cursor
del persons
garbage_collect()
cursors = self.inspect_cursors()
self.assertEqual(len(cursors), 0)
@unittest.skipIf(
PYPY,
reason="Cursor not closed properly due to differences in garbage collection.",
)
def test_server_side_cursors_setting(self):
with self.override_db_setting(DISABLE_SERVER_SIDE_CURSORS=False):
persons = Person.objects.iterator()
self.assertUsesCursor(persons)
del persons # Close server-side cursor
# On PyPy, the cursor is left open here and attempting to force garbage
# collection breaks the transaction wrapping the test.
with self.override_db_setting(DISABLE_SERVER_SIDE_CURSORS=True):
self.assertNotUsesCursor(Person.objects.iterator())
@unittest.skipUnless(
is_psycopg3, "The server_side_binding option is only effective on psycopg >= 3."
)
def test_server_side_binding(self):
"""
The ORM still generates SQL that is not suitable for usage as prepared
statements but psycopg >= 3 defaults to using server-side bindings for
server-side cursors which requires some specialized logic when the
`server_side_binding` setting is disabled (default).
"""
def perform_query():
# Generates SQL that is known to be problematic from a server-side
# binding perspective as the parametrized ORDER BY clause doesn't
# use the same binding parameter as the SELECT clause.
qs = (
Person.objects.order_by(
models.functions.Coalesce("first_name", models.Value(""))
)
.distinct()
.iterator()
)
self.assertSequenceEqual(list(qs), [self.p0, self.p1])
with self.override_db_setting(OPTIONS={}):
perform_query()
with self.override_db_setting(OPTIONS={"server_side_binding": False}):
perform_query()
with self.override_db_setting(OPTIONS={"server_side_binding": True}):
# This assertion could start failing the moment the ORM generates
# SQL suitable for usage as prepared statements (#20516) or if
# psycopg >= 3 adapts psycopg.Connection(cursor_factory) machinery
# to allow client-side bindings for named cursors. In the first
# case this whole test could be removed, in the second one it would
# most likely need to be adapted.
with self.assertRaises(ProgrammingError):
perform_query()
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/backends/base/test_operations.py | tests/backends/base/test_operations.py | import decimal
from django.core.management.color import no_style
from django.db import NotSupportedError, connection, transaction
from django.db.backends.base.operations import BaseDatabaseOperations
from django.db.models import DurationField
from django.db.models.expressions import Col
from django.test import (
SimpleTestCase,
TestCase,
TransactionTestCase,
override_settings,
skipIfDBFeature,
)
from django.utils import timezone
from ..models import Author, Book
class SimpleDatabaseOperationTests(SimpleTestCase):
may_require_msg = "subclasses of BaseDatabaseOperations may require a %s() method"
def setUp(self):
self.ops = BaseDatabaseOperations(connection=connection)
def test_deferrable_sql(self):
self.assertEqual(self.ops.deferrable_sql(), "")
def test_end_transaction_rollback(self):
self.assertEqual(self.ops.end_transaction_sql(success=False), "ROLLBACK;")
def test_no_limit_value(self):
with self.assertRaisesMessage(
NotImplementedError, self.may_require_msg % "no_limit_value"
):
self.ops.no_limit_value()
def test_quote_name(self):
with self.assertRaisesMessage(
NotImplementedError, self.may_require_msg % "quote_name"
):
self.ops.quote_name("a")
def test_regex_lookup(self):
with self.assertRaisesMessage(
NotImplementedError, self.may_require_msg % "regex_lookup"
):
self.ops.regex_lookup(lookup_type="regex")
def test_set_time_zone_sql(self):
self.assertEqual(self.ops.set_time_zone_sql(), "")
def test_sql_flush(self):
msg = "subclasses of BaseDatabaseOperations must provide an sql_flush() method"
with self.assertRaisesMessage(NotImplementedError, msg):
self.ops.sql_flush(None, None)
def test_pk_default_value(self):
self.assertEqual(self.ops.pk_default_value(), "DEFAULT")
def test_tablespace_sql(self):
self.assertEqual(self.ops.tablespace_sql(None), "")
def test_sequence_reset_by_name_sql(self):
self.assertEqual(self.ops.sequence_reset_by_name_sql(None, []), [])
def test_adapt_unknown_value_decimal(self):
value = decimal.Decimal("3.14")
self.assertEqual(
self.ops.adapt_unknown_value(value),
self.ops.adapt_decimalfield_value(value),
)
def test_adapt_unknown_value_date(self):
value = timezone.now().date()
self.assertEqual(
self.ops.adapt_unknown_value(value), self.ops.adapt_datefield_value(value)
)
def test_adapt_unknown_value_time(self):
value = timezone.now().time()
self.assertEqual(
self.ops.adapt_unknown_value(value), self.ops.adapt_timefield_value(value)
)
def test_adapt_timefield_value_none(self):
self.assertIsNone(self.ops.adapt_timefield_value(None))
def test_adapt_datetimefield_value_none(self):
self.assertIsNone(self.ops.adapt_datetimefield_value(None))
def test_adapt_timefield_value(self):
msg = "Django does not support timezone-aware times."
with self.assertRaisesMessage(ValueError, msg):
self.ops.adapt_timefield_value(timezone.make_aware(timezone.now()))
@override_settings(USE_TZ=False)
def test_adapt_timefield_value_unaware(self):
now = timezone.now()
self.assertEqual(self.ops.adapt_timefield_value(now), str(now))
def test_format_for_duration_arithmetic(self):
msg = self.may_require_msg % "format_for_duration_arithmetic"
with self.assertRaisesMessage(NotImplementedError, msg):
self.ops.format_for_duration_arithmetic(None)
def test_date_extract_sql(self):
with self.assertRaisesMessage(
NotImplementedError, self.may_require_msg % "date_extract_sql"
):
self.ops.date_extract_sql(None, None, None)
def test_time_extract_sql(self):
with self.assertRaisesMessage(
NotImplementedError, self.may_require_msg % "date_extract_sql"
):
self.ops.time_extract_sql(None, None, None)
def test_date_trunc_sql(self):
with self.assertRaisesMessage(
NotImplementedError, self.may_require_msg % "date_trunc_sql"
):
self.ops.date_trunc_sql(None, None, None)
def test_time_trunc_sql(self):
with self.assertRaisesMessage(
NotImplementedError, self.may_require_msg % "time_trunc_sql"
):
self.ops.time_trunc_sql(None, None, None)
def test_datetime_trunc_sql(self):
with self.assertRaisesMessage(
NotImplementedError, self.may_require_msg % "datetime_trunc_sql"
):
self.ops.datetime_trunc_sql(None, None, None, None)
def test_datetime_cast_date_sql(self):
with self.assertRaisesMessage(
NotImplementedError, self.may_require_msg % "datetime_cast_date_sql"
):
self.ops.datetime_cast_date_sql(None, None, None)
def test_datetime_cast_time_sql(self):
with self.assertRaisesMessage(
NotImplementedError, self.may_require_msg % "datetime_cast_time_sql"
):
self.ops.datetime_cast_time_sql(None, None, None)
def test_datetime_extract_sql(self):
with self.assertRaisesMessage(
NotImplementedError, self.may_require_msg % "datetime_extract_sql"
):
self.ops.datetime_extract_sql(None, None, None, None)
def test_prepare_join_on_clause(self):
author_table = Author._meta.db_table
author_id_field = Author._meta.get_field("id")
book_table = Book._meta.db_table
book_fk_field = Book._meta.get_field("author")
lhs_expr, rhs_expr = self.ops.prepare_join_on_clause(
author_table,
author_id_field,
book_table,
book_fk_field,
)
self.assertEqual(lhs_expr, Col(author_table, author_id_field))
self.assertEqual(rhs_expr, Col(book_table, book_fk_field))
class DatabaseOperationTests(TestCase):
def setUp(self):
self.ops = BaseDatabaseOperations(connection=connection)
def test_last_executed_query_base_fallback(self):
sql = "INVALID SQL"
params = []
with connection.cursor() as cursor:
cursor.close()
try:
cursor.execute(sql, params)
except connection.features.closed_cursor_error_class:
pass
self.assertIsNotNone(
connection.ops.last_executed_query(cursor, sql, params),
)
@skipIfDBFeature("can_distinct_on_fields")
def test_distinct_on_fields(self):
msg = "DISTINCT ON fields is not supported by this database backend"
with self.assertRaisesMessage(NotSupportedError, msg):
self.ops.distinct_sql(["a", "b"], None)
@skipIfDBFeature("supports_temporal_subtraction")
def test_subtract_temporals(self):
duration_field = DurationField()
duration_field_internal_type = duration_field.get_internal_type()
msg = (
"This backend does not support %s subtraction."
% duration_field_internal_type
)
with self.assertRaisesMessage(NotSupportedError, msg):
self.ops.subtract_temporals(duration_field_internal_type, None, None)
class SqlFlushTests(TransactionTestCase):
available_apps = ["backends"]
def test_sql_flush_no_tables(self):
self.assertEqual(connection.ops.sql_flush(no_style(), []), [])
def test_execute_sql_flush_statements(self):
with transaction.atomic():
author = Author.objects.create(name="George Orwell")
Book.objects.create(author=author)
author = Author.objects.create(name="Harper Lee")
Book.objects.create(author=author)
Book.objects.create(author=author)
self.assertIs(Author.objects.exists(), True)
self.assertIs(Book.objects.exists(), True)
sql_list = connection.ops.sql_flush(
no_style(),
[Author._meta.db_table, Book._meta.db_table],
reset_sequences=True,
allow_cascade=True,
)
connection.ops.execute_sql_flush(sql_list)
with transaction.atomic():
self.assertIs(Author.objects.exists(), False)
self.assertIs(Book.objects.exists(), False)
if connection.features.supports_sequence_reset:
author = Author.objects.create(name="F. Scott Fitzgerald")
self.assertEqual(author.pk, 1)
book = Book.objects.create(author=author)
self.assertEqual(book.pk, 1)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/backends/base/test_features.py | tests/backends/base/test_features.py | from django.db import connection
from django.test import SimpleTestCase
class TestDatabaseFeatures(SimpleTestCase):
def test_nonexistent_feature(self):
self.assertFalse(hasattr(connection.features, "nonexistent"))
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/backends/base/test_base.py | tests/backends/base/test_base.py | import gc
from unittest.mock import MagicMock, patch
from django.db import DEFAULT_DB_ALIAS, connection, connections, transaction
from django.db.backends.base.base import BaseDatabaseWrapper
from django.test import (
SimpleTestCase,
TestCase,
TransactionTestCase,
skipUnlessDBFeature,
)
from django.test.runner import DebugSQLTextTestResult
from django.test.utils import CaptureQueriesContext, override_settings
from ..models import Person, Square
class DatabaseWrapperTests(SimpleTestCase):
def test_repr(self):
conn = connections[DEFAULT_DB_ALIAS]
self.assertEqual(
repr(conn),
f"<DatabaseWrapper vendor={connection.vendor!r} alias='default'>",
)
def test_initialization_class_attributes(self):
"""
The "initialization" class attributes like client_class and
creation_class should be set on the class and reflected in the
corresponding instance attributes of the instantiated backend.
"""
conn = connections[DEFAULT_DB_ALIAS]
conn_class = type(conn)
attr_names = [
("client_class", "client"),
("creation_class", "creation"),
("features_class", "features"),
("introspection_class", "introspection"),
("ops_class", "ops"),
("validation_class", "validation"),
]
for class_attr_name, instance_attr_name in attr_names:
class_attr_value = getattr(conn_class, class_attr_name)
self.assertIsNotNone(class_attr_value)
instance_attr_value = getattr(conn, instance_attr_name)
self.assertIsInstance(instance_attr_value, class_attr_value)
def test_initialization_display_name(self):
self.assertEqual(BaseDatabaseWrapper.display_name, "unknown")
self.assertNotEqual(connection.display_name, "unknown")
def test_get_database_version(self):
with patch.object(BaseDatabaseWrapper, "__init__", return_value=None):
msg = (
"subclasses of BaseDatabaseWrapper may require a "
"get_database_version() method."
)
with self.assertRaisesMessage(NotImplementedError, msg):
BaseDatabaseWrapper().get_database_version()
def test_check_database_version_supported_with_none_as_database_version(self):
with patch.object(connection.features, "minimum_database_version", None):
connection.check_database_version_supported()
def test_release_memory_without_garbage_collection(self):
# Schedule the restore of the garbage collection settings.
self.addCleanup(gc.set_debug, 0)
self.addCleanup(gc.enable)
# Disable automatic garbage collection to control when it's triggered,
# then run a full collection cycle to ensure `gc.garbage` is empty.
gc.disable()
gc.collect()
# The garbage list isn't automatically populated to avoid CPU overhead,
# so debugging needs to be enabled to track all unreachable items and
# have them stored in `gc.garbage`.
gc.set_debug(gc.DEBUG_SAVEALL)
# Create a new connection that will be closed during the test, and also
# ensure that a `DatabaseErrorWrapper` is created for this connection.
test_connection = connection.copy()
with test_connection.wrap_database_errors:
self.assertEqual(test_connection.queries, [])
# Close the connection and remove references to it. This will mark all
# objects related to the connection as garbage to be collected.
test_connection.close()
test_connection = None
# Enforce garbage collection to populate `gc.garbage` for inspection.
gc.collect()
self.assertEqual(gc.garbage, [])
class DatabaseWrapperLoggingTests(TransactionTestCase):
available_apps = ["backends"]
@override_settings(DEBUG=True)
def test_commit_debug_log(self):
conn = connections[DEFAULT_DB_ALIAS]
with CaptureQueriesContext(conn):
with self.assertLogs("django.db.backends", "DEBUG") as cm:
with transaction.atomic():
Person.objects.create(first_name="first", last_name="last")
self.assertGreaterEqual(len(conn.queries_log), 3)
self.assertEqual(conn.queries_log[-3]["sql"], "BEGIN")
self.assertRegex(
cm.output[0],
r"DEBUG:django.db.backends:\(\d+.\d{3}\) "
rf"BEGIN; args=None; alias={DEFAULT_DB_ALIAS}",
)
self.assertEqual(conn.queries_log[-1]["sql"], "COMMIT")
self.assertRegex(
cm.output[-1],
r"DEBUG:django.db.backends:\(\d+.\d{3}\) "
rf"COMMIT; args=None; alias={DEFAULT_DB_ALIAS}",
)
@override_settings(DEBUG=True)
def test_rollback_debug_log(self):
conn = connections[DEFAULT_DB_ALIAS]
with CaptureQueriesContext(conn):
with self.assertLogs("django.db.backends", "DEBUG") as cm:
with self.assertRaises(Exception), transaction.atomic():
Person.objects.create(first_name="first", last_name="last")
raise Exception("Force rollback")
self.assertEqual(conn.queries_log[-1]["sql"], "ROLLBACK")
self.assertRegex(
cm.output[-1],
r"DEBUG:django.db.backends:\(\d+.\d{3}\) "
rf"ROLLBACK; args=None; alias={DEFAULT_DB_ALIAS}",
)
def test_no_logs_without_debug(self):
if isinstance(self._outcome.result, DebugSQLTextTestResult):
self.skipTest("--debug-sql interferes with this test")
with self.assertNoLogs("django.db.backends", "DEBUG"):
with self.assertRaises(Exception), transaction.atomic():
Person.objects.create(first_name="first", last_name="last")
raise Exception("Force rollback")
conn = connections[DEFAULT_DB_ALIAS]
self.assertEqual(len(conn.queries_log), 0)
class ExecuteWrapperTests(TestCase):
@staticmethod
def call_execute(connection, params=None):
ret_val = "1" if params is None else "%s"
sql = "SELECT " + ret_val + connection.features.bare_select_suffix
with connection.cursor() as cursor:
cursor.execute(sql, params)
def call_executemany(self, connection, params=None):
# executemany() must use an update query. Make sure it does nothing
# by putting a false condition in the WHERE clause.
sql = "DELETE FROM {} WHERE 0=1 AND 0=%s".format(Square._meta.db_table)
if params is None:
params = [(i,) for i in range(3)]
with connection.cursor() as cursor:
cursor.executemany(sql, params)
@staticmethod
def mock_wrapper():
return MagicMock(side_effect=lambda execute, *args: execute(*args))
def test_wrapper_invoked(self):
wrapper = self.mock_wrapper()
with connection.execute_wrapper(wrapper):
self.call_execute(connection)
self.assertTrue(wrapper.called)
(_, sql, params, many, context), _ = wrapper.call_args
self.assertIn("SELECT", sql)
self.assertIsNone(params)
self.assertIs(many, False)
self.assertEqual(context["connection"], connection)
def test_wrapper_invoked_many(self):
wrapper = self.mock_wrapper()
with connection.execute_wrapper(wrapper):
self.call_executemany(connection)
self.assertTrue(wrapper.called)
(_, sql, param_list, many, context), _ = wrapper.call_args
self.assertIn("DELETE", sql)
self.assertIsInstance(param_list, (list, tuple))
self.assertIs(many, True)
self.assertEqual(context["connection"], connection)
def test_database_queried(self):
wrapper = self.mock_wrapper()
with connection.execute_wrapper(wrapper):
with connection.cursor() as cursor:
sql = "SELECT 17" + connection.features.bare_select_suffix
cursor.execute(sql)
seventeen = cursor.fetchall()
self.assertEqual(list(seventeen), [(17,)])
self.call_executemany(connection)
def test_nested_wrapper_invoked(self):
outer_wrapper = self.mock_wrapper()
inner_wrapper = self.mock_wrapper()
with (
connection.execute_wrapper(outer_wrapper),
connection.execute_wrapper(inner_wrapper),
):
self.call_execute(connection)
self.assertEqual(inner_wrapper.call_count, 1)
self.call_executemany(connection)
self.assertEqual(inner_wrapper.call_count, 2)
def test_outer_wrapper_blocks(self):
def blocker(*args):
pass
wrapper = self.mock_wrapper()
c = connection # This alias shortens the next line.
with (
c.execute_wrapper(wrapper),
c.execute_wrapper(blocker),
c.execute_wrapper(wrapper),
):
with c.cursor() as cursor:
cursor.execute("The database never sees this")
self.assertEqual(wrapper.call_count, 1)
cursor.executemany("The database never sees this %s", [("either",)])
self.assertEqual(wrapper.call_count, 2)
def test_wrapper_gets_sql(self):
wrapper = self.mock_wrapper()
sql = "SELECT 'aloha'" + connection.features.bare_select_suffix
with connection.execute_wrapper(wrapper), connection.cursor() as cursor:
cursor.execute(sql)
(_, reported_sql, _, _, _), _ = wrapper.call_args
self.assertEqual(reported_sql, sql)
def test_wrapper_connection_specific(self):
wrapper = self.mock_wrapper()
with connections["other"].execute_wrapper(wrapper):
self.assertEqual(connections["other"].execute_wrappers, [wrapper])
self.call_execute(connection)
self.assertFalse(wrapper.called)
self.assertEqual(connection.execute_wrappers, [])
self.assertEqual(connections["other"].execute_wrappers, [])
def test_wrapper_debug(self):
def wrap_with_comment(execute, sql, params, many, context):
return execute(f"/* My comment */ {sql}", params, many, context)
with CaptureQueriesContext(connection) as ctx:
with connection.execute_wrapper(wrap_with_comment):
list(Person.objects.all())
last_query = ctx.captured_queries[-1]["sql"]
self.assertTrue(last_query.startswith("/* My comment */"))
class ConnectionHealthChecksTests(SimpleTestCase):
databases = {"default"}
def setUp(self):
# All test cases here need newly configured and created connections.
# Use the default db connection for convenience.
connection.close()
self.addCleanup(connection.close)
def patch_settings_dict(self, conn_health_checks):
self.settings_dict_patcher = patch.dict(
connection.settings_dict,
{
**connection.settings_dict,
"CONN_MAX_AGE": None,
"CONN_HEALTH_CHECKS": conn_health_checks,
},
)
self.settings_dict_patcher.start()
self.addCleanup(self.settings_dict_patcher.stop)
def run_query(self):
with connection.cursor() as cursor:
cursor.execute("SELECT 42" + connection.features.bare_select_suffix)
@skipUnlessDBFeature("test_db_allows_multiple_connections")
def test_health_checks_enabled(self):
self.patch_settings_dict(conn_health_checks=True)
self.assertIsNone(connection.connection)
# Newly created connections are considered healthy without performing
# the health check.
with patch.object(connection, "is_usable", side_effect=AssertionError):
self.run_query()
old_connection = connection.connection
# Simulate request_finished.
connection.close_if_unusable_or_obsolete()
self.assertIs(old_connection, connection.connection)
# Simulate connection health check failing.
with patch.object(
connection, "is_usable", return_value=False
) as mocked_is_usable:
self.run_query()
new_connection = connection.connection
# A new connection is established.
self.assertIsNot(new_connection, old_connection)
# Only one health check per "request" is performed, so the next
# query will carry on even if the health check fails. Next query
# succeeds because the real connection is healthy and only the
# health check failure is mocked.
self.run_query()
self.assertIs(new_connection, connection.connection)
self.assertEqual(mocked_is_usable.call_count, 1)
# Simulate request_finished.
connection.close_if_unusable_or_obsolete()
# The underlying connection is being reused further with health checks
# succeeding.
self.run_query()
self.run_query()
self.assertIs(new_connection, connection.connection)
@skipUnlessDBFeature("test_db_allows_multiple_connections")
def test_health_checks_enabled_errors_occurred(self):
self.patch_settings_dict(conn_health_checks=True)
self.assertIsNone(connection.connection)
# Newly created connections are considered healthy without performing
# the health check.
with patch.object(connection, "is_usable", side_effect=AssertionError):
self.run_query()
old_connection = connection.connection
# Simulate errors_occurred.
connection.errors_occurred = True
# Simulate request_started (the connection is healthy).
connection.close_if_unusable_or_obsolete()
# Persistent connections are enabled.
self.assertIs(old_connection, connection.connection)
# No additional health checks after the one in
# close_if_unusable_or_obsolete() are executed during this "request"
# when running queries.
with patch.object(connection, "is_usable", side_effect=AssertionError):
self.run_query()
@skipUnlessDBFeature("test_db_allows_multiple_connections")
def test_health_checks_disabled(self):
self.patch_settings_dict(conn_health_checks=False)
self.assertIsNone(connection.connection)
# Newly created connections are considered healthy without performing
# the health check.
with patch.object(connection, "is_usable", side_effect=AssertionError):
self.run_query()
old_connection = connection.connection
# Simulate request_finished.
connection.close_if_unusable_or_obsolete()
# Persistent connections are enabled (connection is not).
self.assertIs(old_connection, connection.connection)
# Health checks are not performed.
with patch.object(connection, "is_usable", side_effect=AssertionError):
self.run_query()
# Health check wasn't performed and the connection is unchanged.
self.assertIs(old_connection, connection.connection)
self.run_query()
# The connection is unchanged after the next query either during
# the current "request".
self.assertIs(old_connection, connection.connection)
@skipUnlessDBFeature("test_db_allows_multiple_connections")
def test_set_autocommit_health_checks_enabled(self):
self.patch_settings_dict(conn_health_checks=True)
self.assertIsNone(connection.connection)
# Newly created connections are considered healthy without performing
# the health check.
with patch.object(connection, "is_usable", side_effect=AssertionError):
# Simulate outermost atomic block: changing autocommit for
# a connection.
connection.set_autocommit(False)
self.run_query()
connection.commit()
connection.set_autocommit(True)
old_connection = connection.connection
# Simulate request_finished.
connection.close_if_unusable_or_obsolete()
# Persistent connections are enabled.
self.assertIs(old_connection, connection.connection)
# Simulate connection health check failing.
with patch.object(
connection, "is_usable", return_value=False
) as mocked_is_usable:
# Simulate outermost atomic block: changing autocommit for
# a connection.
connection.set_autocommit(False)
new_connection = connection.connection
self.assertIsNot(new_connection, old_connection)
# Only one health check per "request" is performed, so a query will
# carry on even if the health check fails. This query succeeds
# because the real connection is healthy and only the health check
# failure is mocked.
self.run_query()
connection.commit()
connection.set_autocommit(True)
# The connection is unchanged.
self.assertIs(new_connection, connection.connection)
self.assertEqual(mocked_is_usable.call_count, 1)
# Simulate request_finished.
connection.close_if_unusable_or_obsolete()
# The underlying connection is being reused further with health checks
# succeeding.
connection.set_autocommit(False)
self.run_query()
connection.commit()
connection.set_autocommit(True)
self.assertIs(new_connection, connection.connection)
class MultiDatabaseTests(TestCase):
databases = {"default", "other"}
def test_multi_database_init_connection_state_called_once(self):
for db in self.databases:
with self.subTest(database=db):
with patch.object(connections[db], "commit", return_value=None):
with patch.object(
connections[db],
"check_database_version_supported",
) as mocked_check_database_version_supported:
connections[db].init_connection_state()
after_first_calls = len(
mocked_check_database_version_supported.mock_calls
)
connections[db].init_connection_state()
self.assertEqual(
len(mocked_check_database_version_supported.mock_calls),
after_first_calls,
)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/backends/base/test_creation.py | tests/backends/base/test_creation.py | import copy
import datetime
import os
from unittest import mock
from django.db import DEFAULT_DB_ALIAS, connection, connections
from django.db.backends.base.creation import TEST_DATABASE_PREFIX, BaseDatabaseCreation
from django.test import SimpleTestCase, TransactionTestCase
from django.test.utils import override_settings
from django.utils.deprecation import RemovedInDjango70Warning
from ..models import (
CircularA,
CircularB,
Object,
ObjectReference,
ObjectSelfReference,
SchoolBus,
SchoolClass,
)
def get_connection_copy():
# Get a copy of the default connection. (Can't use django.db.connection
# because it'll modify the default connection itself.)
test_connection = copy.copy(connections[DEFAULT_DB_ALIAS])
test_connection.settings_dict = copy.deepcopy(
connections[DEFAULT_DB_ALIAS].settings_dict
)
return test_connection
class TestDbSignatureTests(SimpleTestCase):
def test_default_name(self):
# A test db name isn't set.
prod_name = "hodor"
test_connection = get_connection_copy()
test_connection.settings_dict["NAME"] = prod_name
test_connection.settings_dict["TEST"] = {"NAME": None}
signature = BaseDatabaseCreation(test_connection).test_db_signature()
self.assertEqual(signature[3], TEST_DATABASE_PREFIX + prod_name)
def test_custom_test_name(self):
# A regular test db name is set.
test_name = "hodor"
test_connection = get_connection_copy()
test_connection.settings_dict["TEST"] = {"NAME": test_name}
signature = BaseDatabaseCreation(test_connection).test_db_signature()
self.assertEqual(signature[3], test_name)
def test_custom_test_name_with_test_prefix(self):
# A test db name prefixed with TEST_DATABASE_PREFIX is set.
test_name = TEST_DATABASE_PREFIX + "hodor"
test_connection = get_connection_copy()
test_connection.settings_dict["TEST"] = {"NAME": test_name}
signature = BaseDatabaseCreation(test_connection).test_db_signature()
self.assertEqual(signature[3], test_name)
@override_settings(INSTALLED_APPS=["backends.base.app_unmigrated"])
@mock.patch.object(connection, "ensure_connection")
@mock.patch.object(connection, "prepare_database")
@mock.patch(
"django.db.migrations.recorder.MigrationRecorder.has_table", return_value=False
)
@mock.patch("django.core.management.commands.migrate.Command.sync_apps")
class TestDbCreationTests(SimpleTestCase):
available_apps = ["backends.base.app_unmigrated"]
@staticmethod
def patch_close_connection(creation):
# If DatabaseCreation.destroy_test_db() closes the database connection,
# that behavior must be disabled to prevent each test from crashing.
if close_method_name := creation.destroy_test_db_connection_close_method:
setattr(creation.connection, close_method_name, mock.Mock())
@mock.patch("django.db.migrations.executor.MigrationExecutor.migrate")
def test_migrate_test_setting_false(
self, mocked_migrate, mocked_sync_apps, *mocked_objects
):
test_connection = get_connection_copy()
test_connection.settings_dict["TEST"]["MIGRATE"] = False
creation = test_connection.creation_class(test_connection)
self.patch_close_connection(creation)
old_database_name = test_connection.settings_dict["NAME"]
try:
with mock.patch.object(creation, "_create_test_db"):
creation.create_test_db(verbosity=0, autoclobber=True)
# Migrations don't run.
mocked_migrate.assert_called()
args, kwargs = mocked_migrate.call_args
self.assertEqual(args, ([],))
self.assertEqual(kwargs["plan"], [])
# App is synced.
mocked_sync_apps.assert_called()
mocked_args, _ = mocked_sync_apps.call_args
self.assertEqual(mocked_args[1], {"app_unmigrated"})
finally:
with mock.patch.object(creation, "_destroy_test_db"):
creation.destroy_test_db(old_database_name, verbosity=0)
@mock.patch("django.db.migrations.executor.MigrationRecorder.ensure_schema")
def test_migrate_test_setting_false_ensure_schema(
self,
mocked_ensure_schema,
mocked_sync_apps,
*mocked_objects,
):
test_connection = get_connection_copy()
test_connection.settings_dict["TEST"]["MIGRATE"] = False
creation = test_connection.creation_class(test_connection)
self.patch_close_connection(creation)
old_database_name = test_connection.settings_dict["NAME"]
try:
with mock.patch.object(creation, "_create_test_db"):
creation.create_test_db(verbosity=0, autoclobber=True)
# The django_migrations table is not created.
mocked_ensure_schema.assert_not_called()
# App is synced.
mocked_sync_apps.assert_called()
mocked_args, _ = mocked_sync_apps.call_args
self.assertEqual(mocked_args[1], {"app_unmigrated"})
finally:
with mock.patch.object(creation, "_destroy_test_db"):
creation.destroy_test_db(old_database_name, verbosity=0)
@mock.patch("django.db.migrations.executor.MigrationExecutor.migrate")
def test_migrate_test_setting_true(
self, mocked_migrate, mocked_sync_apps, *mocked_objects
):
test_connection = get_connection_copy()
test_connection.settings_dict["TEST"]["MIGRATE"] = True
creation = test_connection.creation_class(test_connection)
self.patch_close_connection(creation)
old_database_name = test_connection.settings_dict["NAME"]
try:
with mock.patch.object(creation, "_create_test_db"):
creation.create_test_db(verbosity=0, autoclobber=True)
# Migrations run.
mocked_migrate.assert_called()
args, kwargs = mocked_migrate.call_args
self.assertEqual(args, ([("app_unmigrated", "0001_initial")],))
self.assertEqual(len(kwargs["plan"]), 1)
# App is not synced.
mocked_sync_apps.assert_not_called()
finally:
with mock.patch.object(creation, "_destroy_test_db"):
creation.destroy_test_db(old_database_name, verbosity=0)
@mock.patch.dict(os.environ, {"RUNNING_DJANGOS_TEST_SUITE": ""})
@mock.patch("django.db.migrations.executor.MigrationExecutor.migrate")
@mock.patch.object(BaseDatabaseCreation, "mark_expected_failures_and_skips")
def test_mark_expected_failures_and_skips_call(
self, mark_expected_failures_and_skips, *mocked_objects
):
"""
mark_expected_failures_and_skips() isn't called unless
RUNNING_DJANGOS_TEST_SUITE is 'true'.
"""
test_connection = get_connection_copy()
creation = test_connection.creation_class(test_connection)
self.patch_close_connection(creation)
old_database_name = test_connection.settings_dict["NAME"]
try:
with mock.patch.object(creation, "_create_test_db"):
creation.create_test_db(verbosity=0, autoclobber=True)
self.assertIs(mark_expected_failures_and_skips.called, False)
finally:
with mock.patch.object(creation, "_destroy_test_db"):
creation.destroy_test_db(old_database_name, verbosity=0)
@mock.patch("django.db.migrations.executor.MigrationExecutor.migrate")
@mock.patch.object(BaseDatabaseCreation, "serialize_db_to_string")
def test_serialize_deprecation(self, serialize_db_to_string, *mocked_objects):
test_connection = get_connection_copy()
creation = test_connection.creation_class(test_connection)
self.patch_close_connection(creation)
old_database_name = test_connection.settings_dict["NAME"]
msg = (
"DatabaseCreation.create_test_db(serialize) is deprecated. Call "
"DatabaseCreation.serialize_test_db() once all test databases are set up "
"instead if you need fixtures persistence between tests."
)
try:
with (
self.assertWarnsMessage(RemovedInDjango70Warning, msg) as ctx,
mock.patch.object(creation, "_create_test_db"),
):
creation.create_test_db(verbosity=0, serialize=True)
self.assertEqual(ctx.filename, __file__)
serialize_db_to_string.assert_called_once_with()
finally:
with mock.patch.object(creation, "_destroy_test_db"):
creation.destroy_test_db(old_database_name, verbosity=0)
# Now with `serialize` False.
serialize_db_to_string.reset_mock()
try:
with (
self.assertWarnsMessage(RemovedInDjango70Warning, msg) as ctx,
mock.patch.object(creation, "_create_test_db"),
):
creation.create_test_db(verbosity=0, serialize=False)
self.assertEqual(ctx.filename, __file__)
serialize_db_to_string.assert_not_called()
finally:
with mock.patch.object(creation, "_destroy_test_db"):
creation.destroy_test_db(old_database_name, verbosity=0)
class TestDeserializeDbFromString(TransactionTestCase):
available_apps = ["backends"]
def test_circular_reference(self):
# deserialize_db_from_string() handles circular references.
data = """
[
{
"model": "backends.object",
"pk": 1,
"fields": {"obj_ref": 1, "related_objects": []}
},
{
"model": "backends.objectreference",
"pk": 1,
"fields": {"obj": 1}
}
]
"""
connection.creation.deserialize_db_from_string(data)
obj = Object.objects.get()
obj_ref = ObjectReference.objects.get()
self.assertEqual(obj.obj_ref, obj_ref)
self.assertEqual(obj_ref.obj, obj)
def test_self_reference(self):
# serialize_db_to_string() and deserialize_db_from_string() handles
# self references.
obj_1 = ObjectSelfReference.objects.create(key="X")
obj_2 = ObjectSelfReference.objects.create(key="Y", obj=obj_1)
obj_1.obj = obj_2
obj_1.save()
# Serialize objects.
with mock.patch("django.db.migrations.loader.MigrationLoader") as loader:
# serialize_db_to_string() serializes only migrated apps, so mark
# the backends app as migrated.
loader_instance = loader.return_value
loader_instance.migrated_apps = {"backends"}
data = connection.creation.serialize_db_to_string()
ObjectSelfReference.objects.all().delete()
# Deserialize objects.
connection.creation.deserialize_db_from_string(data)
obj_1 = ObjectSelfReference.objects.get(key="X")
obj_2 = ObjectSelfReference.objects.get(key="Y")
self.assertEqual(obj_1.obj, obj_2)
self.assertEqual(obj_2.obj, obj_1)
def test_circular_reference_with_natural_key(self):
# serialize_db_to_string() and deserialize_db_from_string() handles
# circular references for models with natural keys.
obj_a = CircularA.objects.create(key="A")
obj_b = CircularB.objects.create(key="B", obj=obj_a)
obj_a.obj = obj_b
obj_a.save()
# Serialize objects.
with mock.patch("django.db.migrations.loader.MigrationLoader") as loader:
# serialize_db_to_string() serializes only migrated apps, so mark
# the backends app as migrated.
loader_instance = loader.return_value
loader_instance.migrated_apps = {"backends"}
data = connection.creation.serialize_db_to_string()
CircularA.objects.all().delete()
CircularB.objects.all().delete()
# Deserialize objects.
connection.creation.deserialize_db_from_string(data)
obj_a = CircularA.objects.get()
obj_b = CircularB.objects.get()
self.assertEqual(obj_a.obj, obj_b)
self.assertEqual(obj_b.obj, obj_a)
def test_serialize_db_to_string_base_manager(self):
SchoolClass.objects.create(year=1000, last_updated=datetime.datetime.now())
with mock.patch("django.db.migrations.loader.MigrationLoader") as loader:
# serialize_db_to_string() serializes only migrated apps, so mark
# the backends app as migrated.
loader_instance = loader.return_value
loader_instance.migrated_apps = {"backends"}
data = connection.creation.serialize_db_to_string()
self.assertIn('"model": "backends.schoolclass"', data)
self.assertIn('"year": 1000', data)
def test_serialize_db_to_string_base_manager_with_prefetch_related(self):
sclass = SchoolClass.objects.create(
year=2000, last_updated=datetime.datetime.now()
)
bus = SchoolBus.objects.create(number=1)
bus.schoolclasses.add(sclass)
with mock.patch("django.db.migrations.loader.MigrationLoader") as loader:
# serialize_db_to_string() serializes only migrated apps, so mark
# the backends app as migrated.
loader_instance = loader.return_value
loader_instance.migrated_apps = {"backends"}
data = connection.creation.serialize_db_to_string()
self.assertIn('"model": "backends.schoolbus"', data)
self.assertIn('"model": "backends.schoolclass"', data)
self.assertIn(f'"schoolclasses": [{sclass.pk}]', data)
class SkipTestClass:
def skip_function(self):
pass
def skip_test_function():
pass
def expected_failure_test_function():
pass
class TestMarkTests(SimpleTestCase):
def test_mark_expected_failures_and_skips(self):
test_connection = get_connection_copy()
creation = BaseDatabaseCreation(test_connection)
creation.connection.features.django_test_expected_failures = {
"backends.base.test_creation.expected_failure_test_function",
}
creation.connection.features.django_test_skips = {
"skip test class": {
"backends.base.test_creation.SkipTestClass",
},
"skip test function": {
"backends.base.test_creation.skip_test_function",
},
}
creation.mark_expected_failures_and_skips()
self.assertIs(
expected_failure_test_function.__unittest_expecting_failure__,
True,
)
self.assertIs(SkipTestClass.__unittest_skip__, True)
self.assertEqual(
SkipTestClass.__unittest_skip_why__,
"skip test class",
)
self.assertIs(skip_test_function.__unittest_skip__, True)
self.assertEqual(
skip_test_function.__unittest_skip_why__,
"skip test function",
)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/backends/base/__init__.py | tests/backends/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/backends/base/test_client.py | tests/backends/base/test_client.py | from unittest import mock
from django.db import connection
from django.db.backends.base.client import BaseDatabaseClient
from django.test import SimpleTestCase
class SimpleDatabaseClientTests(SimpleTestCase):
def setUp(self):
self.client = BaseDatabaseClient(connection=connection)
def test_settings_to_cmd_args_env(self):
msg = (
"subclasses of BaseDatabaseClient must provide a "
"settings_to_cmd_args_env() method or override a runshell()."
)
with self.assertRaisesMessage(NotImplementedError, msg):
self.client.settings_to_cmd_args_env(None, None)
def test_runshell_use_environ(self):
for env in [None, {}]:
with self.subTest(env=env):
with mock.patch("subprocess.run") as run:
with mock.patch.object(
BaseDatabaseClient,
"settings_to_cmd_args_env",
return_value=([], env),
):
self.client.runshell(None)
run.assert_called_once_with([], env=None, check=True)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/backends/base/test_schema.py | tests/backends/base/test_schema.py | from django.db import models
from django.db.backends.base.schema import BaseDatabaseSchemaEditor
from django.test import SimpleTestCase
class SchemaEditorTests(SimpleTestCase):
def test_effective_default_callable(self):
"""
SchemaEditor.effective_default() shouldn't call callable defaults.
"""
class MyStr(str):
def __call__(self):
return self
class MyCharField(models.CharField):
def _get_default(self):
return self.default
field = MyCharField(max_length=1, default=MyStr)
self.assertEqual(BaseDatabaseSchemaEditor._effective_default(field), MyStr)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/backends/base/test_introspection.py | tests/backends/base/test_introspection.py | from django.db import connection
from django.db.backends.base.introspection import BaseDatabaseIntrospection
from django.test import SimpleTestCase
class SimpleDatabaseIntrospectionTests(SimpleTestCase):
may_require_msg = (
"subclasses of BaseDatabaseIntrospection may require a %s() method"
)
def setUp(self):
self.introspection = BaseDatabaseIntrospection(connection=connection)
def test_get_table_list(self):
msg = self.may_require_msg % "get_table_list"
with self.assertRaisesMessage(NotImplementedError, msg):
self.introspection.get_table_list(None)
def test_get_table_description(self):
msg = self.may_require_msg % "get_table_description"
with self.assertRaisesMessage(NotImplementedError, msg):
self.introspection.get_table_description(None, None)
def test_get_sequences(self):
msg = self.may_require_msg % "get_sequences"
with self.assertRaisesMessage(NotImplementedError, msg):
self.introspection.get_sequences(None, None)
def test_get_relations(self):
msg = self.may_require_msg % "get_relations"
with self.assertRaisesMessage(NotImplementedError, msg):
self.introspection.get_relations(None, None)
def test_get_constraints(self):
msg = self.may_require_msg % "get_constraints"
with self.assertRaisesMessage(NotImplementedError, msg):
self.introspection.get_constraints(None, None)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/backends/base/app_unmigrated/models.py | tests/backends/base/app_unmigrated/models.py | from django.db import models
class Foo(models.Model):
name = models.CharField(max_length=255)
class Meta:
app_label = "app_unmigrated"
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/backends/base/app_unmigrated/__init__.py | tests/backends/base/app_unmigrated/__init__.py | python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false | |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/backends/base/app_unmigrated/migrations/0001_initial.py | tests/backends/base/app_unmigrated/migrations/0001_initial.py | from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = []
operations = [
migrations.CreateModel(
name="Foo",
fields=[
(
"id",
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("name", models.CharField(max_length=255)),
],
),
]
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/backends/base/app_unmigrated/migrations/__init__.py | tests/backends/base/app_unmigrated/migrations/__init__.py | python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false | |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/backends/sqlite/test_operations.py | tests/backends/sqlite/test_operations.py | import sqlite3
import unittest
from django.core.management.color import no_style
from django.db import connection, models
from django.test import TestCase
from ..models import Person, Tag
@unittest.skipUnless(connection.vendor == "sqlite", "SQLite tests.")
class SQLiteOperationsTests(TestCase):
def test_sql_flush(self):
self.assertEqual(
connection.ops.sql_flush(
no_style(),
[Person._meta.db_table, Tag._meta.db_table],
),
[
'DELETE FROM "backends_person";',
'DELETE FROM "backends_tag";',
],
)
def test_sql_flush_allow_cascade(self):
statements = connection.ops.sql_flush(
no_style(),
[Person._meta.db_table, Tag._meta.db_table],
allow_cascade=True,
)
self.assertEqual(
# The tables are processed in an unordered set.
sorted(statements),
[
'DELETE FROM "backends_person";',
'DELETE FROM "backends_tag";',
'DELETE FROM "backends_verylongmodelnamezzzzzzzzzzzzzzzzzzzzzz'
"zzzzzzzzzzzzzzzzzzzz_m2m_also_quite_long_zzzzzzzzzzzzzzzzzzzz"
'zzzzzzzzzzzzzzzzzzzzzzz";',
],
)
def test_sql_flush_sequences(self):
self.assertEqual(
connection.ops.sql_flush(
no_style(),
[Person._meta.db_table, Tag._meta.db_table],
reset_sequences=True,
),
[
'DELETE FROM "backends_person";',
'DELETE FROM "backends_tag";',
'UPDATE "sqlite_sequence" SET "seq" = 0 WHERE "name" IN '
"('backends_person', 'backends_tag');",
],
)
def test_sql_flush_sequences_allow_cascade(self):
statements = connection.ops.sql_flush(
no_style(),
[Person._meta.db_table, Tag._meta.db_table],
reset_sequences=True,
allow_cascade=True,
)
self.assertEqual(
# The tables are processed in an unordered set.
sorted(statements[:-1]),
[
'DELETE FROM "backends_person";',
'DELETE FROM "backends_tag";',
'DELETE FROM "backends_verylongmodelnamezzzzzzzzzzzzzzzzzzzzzz'
"zzzzzzzzzzzzzzzzzzzz_m2m_also_quite_long_zzzzzzzzzzzzzzzzzzzz"
'zzzzzzzzzzzzzzzzzzzzzzz";',
],
)
self.assertIs(
statements[-1].startswith(
'UPDATE "sqlite_sequence" SET "seq" = 0 WHERE "name" IN ('
),
True,
)
self.assertIn("'backends_person'", statements[-1])
self.assertIn("'backends_tag'", statements[-1])
self.assertIn(
"'backends_verylongmodelnamezzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz"
"zzzz_m2m_also_quite_long_zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz"
"zzz'",
statements[-1],
)
def test_bulk_batch_size(self):
self.assertEqual(connection.ops.bulk_batch_size([], [Person()]), 1)
first_name_field = Person._meta.get_field("first_name")
last_name_field = Person._meta.get_field("last_name")
self.assertEqual(
connection.ops.bulk_batch_size([first_name_field], [Person()]),
connection.features.max_query_params,
)
self.assertEqual(
connection.ops.bulk_batch_size(
[first_name_field, last_name_field], [Person()]
),
connection.features.max_query_params // 2,
)
composite_pk = models.CompositePrimaryKey("first_name", "last_name")
composite_pk.fields = [first_name_field, last_name_field]
self.assertEqual(
connection.ops.bulk_batch_size(
[composite_pk, first_name_field], [Person()]
),
connection.features.max_query_params // 3,
)
def test_bulk_batch_size_respects_variable_limit(self):
first_name_field = Person._meta.get_field("first_name")
last_name_field = Person._meta.get_field("last_name")
limit_name = sqlite3.SQLITE_LIMIT_VARIABLE_NUMBER
current_limit = connection.features.max_query_params
self.assertEqual(
connection.ops.bulk_batch_size(
[first_name_field, last_name_field], [Person()]
),
current_limit // 2,
)
new_limit = min(42, current_limit)
try:
connection.connection.setlimit(limit_name, new_limit)
self.assertEqual(
connection.ops.bulk_batch_size(
[first_name_field, last_name_field], [Person()]
),
new_limit // 2,
)
finally:
connection.connection.setlimit(limit_name, current_limit)
self.assertEqual(
connection.ops.bulk_batch_size(
[first_name_field, last_name_field], [Person()]
),
current_limit // 2,
)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/backends/sqlite/test_features.py | tests/backends/sqlite/test_features.py | import copy
import sqlite3
from unittest import mock, skipUnless
from django.db import OperationalError, connection
from django.test import TestCase
@skipUnless(connection.vendor == "sqlite", "SQLite tests.")
class FeaturesTests(TestCase):
def test_supports_json_field_operational_error(self):
if hasattr(connection.features, "supports_json_field"):
del connection.features.supports_json_field
msg = "unable to open database file"
with mock.patch.object(
connection,
"cursor",
side_effect=OperationalError(msg),
):
with self.assertRaisesMessage(OperationalError, msg):
connection.features.supports_json_field
def test_max_query_params_respects_variable_limit(self):
limit_name = sqlite3.SQLITE_LIMIT_VARIABLE_NUMBER
current_limit = connection.features.max_query_params
new_limit = min(42, current_limit)
try:
connection.connection.setlimit(limit_name, new_limit)
self.assertEqual(connection.features.max_query_params, new_limit)
finally:
connection.connection.setlimit(limit_name, current_limit)
self.assertEqual(connection.features.max_query_params, current_limit)
def test_max_query_params_without_established_connection(self):
new_connection = connection.copy()
new_connection.settings_dict = copy.deepcopy(connection.settings_dict)
self.assertIsNone(new_connection.connection)
try:
result = new_connection.features.max_query_params
self.assertIsInstance(result, int)
finally:
new_connection._close()
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/backends/sqlite/test_functions.py | tests/backends/sqlite/test_functions.py | from django.db.backends.sqlite3._functions import (
_sqlite_date_trunc,
_sqlite_datetime_trunc,
_sqlite_time_trunc,
)
from django.test import SimpleTestCase
class FunctionTests(SimpleTestCase):
def test_sqlite_date_trunc(self):
msg = "Unsupported lookup type: 'unknown-lookup'"
with self.assertRaisesMessage(ValueError, msg):
_sqlite_date_trunc("unknown-lookup", "2005-08-11", None, None)
def test_sqlite_datetime_trunc(self):
msg = "Unsupported lookup type: 'unknown-lookup'"
with self.assertRaisesMessage(ValueError, msg):
_sqlite_datetime_trunc("unknown-lookup", "2005-08-11 1:00:00", None, None)
def test_sqlite_time_trunc(self):
msg = "Unsupported lookup type: 'unknown-lookup'"
with self.assertRaisesMessage(ValueError, msg):
_sqlite_time_trunc("unknown-lookup", "2005-08-11 1:00:00", None, None)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/backends/sqlite/test_creation.py | tests/backends/sqlite/test_creation.py | import copy
import multiprocessing
import unittest
from unittest import mock
from django.db import DEFAULT_DB_ALIAS, NotSupportedError, connection, connections
from django.test import SimpleTestCase
@unittest.skipUnless(connection.vendor == "sqlite", "SQLite tests")
class TestDbSignatureTests(SimpleTestCase):
def test_custom_test_name(self):
test_connection = copy.copy(connections[DEFAULT_DB_ALIAS])
test_connection.settings_dict = copy.deepcopy(
connections[DEFAULT_DB_ALIAS].settings_dict
)
test_connection.settings_dict["NAME"] = None
test_connection.settings_dict["TEST"]["NAME"] = "custom.sqlite.db"
signature = test_connection.creation_class(test_connection).test_db_signature()
self.assertEqual(signature, (None, "custom.sqlite.db"))
def test_get_test_db_clone_settings_name(self):
test_connection = copy.copy(connections[DEFAULT_DB_ALIAS])
test_connection.settings_dict = copy.deepcopy(
connections[DEFAULT_DB_ALIAS].settings_dict,
)
tests = [
("test.sqlite3", "test_1.sqlite3"),
("test", "test_1"),
]
for test_db_name, expected_clone_name in tests:
with self.subTest(test_db_name=test_db_name):
test_connection.settings_dict["NAME"] = test_db_name
test_connection.settings_dict["TEST"]["NAME"] = test_db_name
creation_class = test_connection.creation_class(test_connection)
clone_settings_dict = creation_class.get_test_db_clone_settings("1")
self.assertEqual(clone_settings_dict["NAME"], expected_clone_name)
@mock.patch.object(multiprocessing, "get_start_method", return_value="unsupported")
def test_get_test_db_clone_settings_not_supported(self, *mocked_objects):
msg = "Cloning with start method 'unsupported' is not supported."
with self.assertRaisesMessage(NotSupportedError, msg):
connection.creation.get_test_db_clone_settings(1)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/backends/sqlite/__init__.py | tests/backends/sqlite/__init__.py | python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false | |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/backends/sqlite/tests.py | tests/backends/sqlite/tests.py | import os
import re
import sqlite3
import tempfile
import threading
import unittest
from contextlib import contextmanager
from pathlib import Path
from unittest import mock
from django.core.exceptions import ImproperlyConfigured
from django.db import (
DEFAULT_DB_ALIAS,
NotSupportedError,
connection,
connections,
transaction,
)
from django.db.models import Aggregate, Avg, StdDev, Sum, Variance
from django.db.utils import ConnectionHandler
from django.test import SimpleTestCase, TestCase, TransactionTestCase, override_settings
from django.test.utils import CaptureQueriesContext, isolate_apps
from ..models import Item, Object, Square
@unittest.skipUnless(connection.vendor == "sqlite", "SQLite tests")
class Tests(TestCase):
longMessage = True
def test_aggregation(self):
"""Raise NotSupportedError when aggregating on date/time fields."""
for aggregate in (Sum, Avg, Variance, StdDev):
with self.assertRaises(NotSupportedError):
Item.objects.aggregate(aggregate("time"))
with self.assertRaises(NotSupportedError):
Item.objects.aggregate(aggregate("date"))
with self.assertRaises(NotSupportedError):
Item.objects.aggregate(aggregate("last_modified"))
with self.assertRaises(NotSupportedError):
Item.objects.aggregate(
**{
"complex": aggregate("last_modified")
+ aggregate("last_modified")
}
)
def test_distinct_aggregation(self):
class DistinctAggregate(Aggregate):
allow_distinct = True
aggregate = DistinctAggregate("first", "second", distinct=True)
msg = (
"SQLite doesn't support DISTINCT on aggregate functions accepting "
"multiple arguments."
)
with self.assertRaisesMessage(NotSupportedError, msg):
connection.ops.check_expression_support(aggregate)
def test_distinct_aggregation_multiple_args_no_distinct(self):
# Aggregate functions accept multiple arguments when DISTINCT isn't
# used, e.g. GROUP_CONCAT().
class DistinctAggregate(Aggregate):
allow_distinct = True
aggregate = DistinctAggregate("first", "second", distinct=False)
connection.ops.check_expression_support(aggregate)
def test_memory_db_test_name(self):
"""A named in-memory db should be allowed where supported."""
from django.db.backends.sqlite3.base import DatabaseWrapper
settings_dict = {
"TEST": {
"NAME": "file:memorydb_test?mode=memory&cache=shared",
}
}
creation = DatabaseWrapper(settings_dict).creation
self.assertEqual(
creation._get_test_db_name(),
creation.connection.settings_dict["TEST"]["NAME"],
)
def test_regexp_function(self):
tests = (
("test", r"[0-9]+", False),
("test", r"[a-z]+", True),
("test", None, None),
(None, r"[a-z]+", None),
(None, None, None),
)
for string, pattern, expected in tests:
with self.subTest((string, pattern)):
with connection.cursor() as cursor:
cursor.execute("SELECT %s REGEXP %s", [string, pattern])
value = cursor.fetchone()[0]
value = bool(value) if value in {0, 1} else value
self.assertIs(value, expected)
def test_pathlib_name(self):
with tempfile.TemporaryDirectory() as tmp:
settings_dict = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": Path(tmp) / "test.db",
},
}
connections = ConnectionHandler(settings_dict)
connections["default"].ensure_connection()
connections["default"].close()
self.assertTrue(os.path.isfile(os.path.join(tmp, "test.db")))
@mock.patch.object(connection, "get_database_version", return_value=(3, 36))
def test_check_database_version_supported(self, mocked_get_database_version):
msg = "SQLite 3.37 or later is required (found 3.36)."
with self.assertRaisesMessage(NotSupportedError, msg):
connection.check_database_version_supported()
self.assertTrue(mocked_get_database_version.called)
def test_init_command(self):
settings_dict = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": ":memory:",
"OPTIONS": {
"init_command": "PRAGMA synchronous=3; PRAGMA cache_size=2000;",
},
}
}
connections = ConnectionHandler(settings_dict)
connections["default"].ensure_connection()
try:
with connections["default"].cursor() as cursor:
cursor.execute("PRAGMA synchronous")
value = cursor.fetchone()[0]
self.assertEqual(value, 3)
cursor.execute("PRAGMA cache_size")
value = cursor.fetchone()[0]
self.assertEqual(value, 2000)
finally:
connections["default"]._close()
@unittest.skipUnless(connection.vendor == "sqlite", "SQLite tests")
@isolate_apps("backends")
class SchemaTests(TransactionTestCase):
available_apps = ["backends"]
def test_autoincrement(self):
"""
auto_increment fields are created with the AUTOINCREMENT keyword
in order to be monotonically increasing (#10164).
"""
with connection.schema_editor(collect_sql=True) as editor:
editor.create_model(Square)
statements = editor.collected_sql
match = re.search('"id" ([^,]+),', statements[0])
self.assertIsNotNone(match)
self.assertEqual(
"integer NOT NULL PRIMARY KEY AUTOINCREMENT",
match[1],
"Wrong SQL used to create an auto-increment column on SQLite",
)
def test_disable_constraint_checking_failure_disallowed(self):
"""
SQLite schema editor is not usable within an outer transaction if
foreign key constraint checks are not disabled beforehand.
"""
msg = (
"SQLite schema editor cannot be used while foreign key "
"constraint checks are enabled. Make sure to disable them "
"before entering a transaction.atomic() context because "
"SQLite does not support disabling them in the middle of "
"a multi-statement transaction."
)
with self.assertRaisesMessage(NotSupportedError, msg):
with transaction.atomic(), connection.schema_editor(atomic=True):
pass
def test_constraint_checks_disabled_atomic_allowed(self):
"""
SQLite schema editor is usable within an outer transaction as long as
foreign key constraints checks are disabled beforehand.
"""
def constraint_checks_enabled():
with connection.cursor() as cursor:
return bool(cursor.execute("PRAGMA foreign_keys").fetchone()[0])
with connection.constraint_checks_disabled(), transaction.atomic():
with connection.schema_editor(atomic=True):
self.assertFalse(constraint_checks_enabled())
self.assertFalse(constraint_checks_enabled())
self.assertTrue(constraint_checks_enabled())
@unittest.skipUnless(connection.vendor == "sqlite", "Test only for SQLite")
@override_settings(DEBUG=True)
class LastExecutedQueryTest(TestCase):
def test_no_interpolation(self):
# This shouldn't raise an exception (#17158)
query = "SELECT strftime('%Y', 'now');"
with connection.cursor() as cursor:
cursor.execute(query)
self.assertEqual(connection.queries[-1]["sql"], query)
def test_parameter_quoting(self):
# The implementation of last_executed_queries isn't optimal. It's
# worth testing that parameters are quoted (#14091).
query = "SELECT %s"
params = ["\"'\\"]
with connection.cursor() as cursor:
cursor.execute(query, params)
# Note that the single quote is repeated
substituted = "SELECT '\"''\\'"
self.assertEqual(connection.queries[-1]["sql"], substituted)
def test_parameter_count_exceeds_variable_or_column_limit(self):
sql = "SELECT MAX(%s)" % ", ".join(["%s"] * 1001)
params = list(range(1001))
for label, limit, current_limit in [
(
"variable",
sqlite3.SQLITE_LIMIT_VARIABLE_NUMBER,
connection.features.max_query_params,
),
(
"column",
sqlite3.SQLITE_LIMIT_COLUMN,
connection.connection.getlimit(sqlite3.SQLITE_LIMIT_COLUMN),
),
]:
with self.subTest(limit=label):
connection.connection.setlimit(limit, 1000)
self.addCleanup(connection.connection.setlimit, limit, current_limit)
with connection.cursor() as cursor:
# This should not raise an exception.
cursor.db.ops.last_executed_query(cursor.cursor, sql, params)
connection.connection.setlimit(limit, current_limit)
@unittest.skipUnless(connection.vendor == "sqlite", "SQLite tests")
class EscapingChecks(TestCase):
"""
All tests in this test case are also run with settings.DEBUG=True in
EscapingChecksDebug test case, to also test CursorDebugWrapper.
"""
def test_parameter_escaping(self):
# '%s' escaping support for sqlite3 (#13648).
with connection.cursor() as cursor:
cursor.execute("select strftime('%s', date('now'))")
response = cursor.fetchall()[0][0]
# response should be an non-zero integer
self.assertTrue(int(response))
@unittest.skipUnless(connection.vendor == "sqlite", "SQLite tests")
@override_settings(DEBUG=True)
class EscapingChecksDebug(EscapingChecks):
pass
@unittest.skipUnless(connection.vendor == "sqlite", "SQLite tests")
class ThreadSharing(TransactionTestCase):
available_apps = ["backends"]
def test_database_sharing_in_threads(self):
thread_connections = []
def create_object():
Object.objects.create()
thread_connections.append(connections[DEFAULT_DB_ALIAS].connection)
main_connection = connections[DEFAULT_DB_ALIAS].connection
try:
create_object()
thread = threading.Thread(target=create_object)
thread.start()
thread.join()
self.assertEqual(Object.objects.count(), 2)
finally:
for conn in thread_connections:
if conn is not main_connection:
conn.close()
@unittest.skipUnless(connection.vendor == "sqlite", "SQLite tests")
class TestTransactionMode(SimpleTestCase):
databases = {"default"}
def test_default_transaction_mode(self):
with CaptureQueriesContext(connection) as captured_queries:
with transaction.atomic():
pass
begin_query, commit_query = captured_queries
self.assertEqual(begin_query["sql"], "BEGIN")
self.assertEqual(commit_query["sql"], "COMMIT")
def test_invalid_transaction_mode(self):
msg = (
"settings.DATABASES['default']['OPTIONS']['transaction_mode'] is "
"improperly configured to 'invalid'. Use one of 'DEFERRED', 'EXCLUSIVE', "
"'IMMEDIATE', or None."
)
with self.change_transaction_mode("invalid") as new_connection:
with self.assertRaisesMessage(ImproperlyConfigured, msg):
new_connection.ensure_connection()
def test_valid_transaction_modes(self):
valid_transaction_modes = ("deferred", "immediate", "exclusive")
for transaction_mode in valid_transaction_modes:
with (
self.subTest(transaction_mode=transaction_mode),
self.change_transaction_mode(transaction_mode) as new_connection,
CaptureQueriesContext(new_connection) as captured_queries,
):
new_connection.set_autocommit(
False, force_begin_transaction_with_broken_autocommit=True
)
new_connection.commit()
expected_transaction_mode = transaction_mode.upper()
begin_sql = captured_queries[0]["sql"]
self.assertEqual(begin_sql, f"BEGIN {expected_transaction_mode}")
@contextmanager
def change_transaction_mode(self, transaction_mode):
new_connection = connection.copy()
new_connection.settings_dict["OPTIONS"] = {
**new_connection.settings_dict["OPTIONS"],
"transaction_mode": transaction_mode,
}
try:
yield new_connection
finally:
new_connection._close()
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/backends/sqlite/test_introspection.py | tests/backends/sqlite/test_introspection.py | import unittest
import sqlparse
from django.db import connection
from django.test import TestCase
@unittest.skipUnless(connection.vendor == "sqlite", "SQLite tests")
class IntrospectionTests(TestCase):
def test_get_primary_key_column(self):
"""
Get the primary key column regardless of whether or not it has
quotation.
"""
testable_column_strings = (
("id", "id"),
("[id]", "id"),
("`id`", "id"),
('"id"', "id"),
("[id col]", "id col"),
("`id col`", "id col"),
('"id col"', "id col"),
)
with connection.cursor() as cursor:
for column, expected_string in testable_column_strings:
sql = "CREATE TABLE test_primary (%s int PRIMARY KEY NOT NULL)" % column
with self.subTest(column=column):
try:
cursor.execute(sql)
field = connection.introspection.get_primary_key_column(
cursor, "test_primary"
)
self.assertEqual(field, expected_string)
finally:
cursor.execute("DROP TABLE test_primary")
def test_get_primary_key_column_pk_constraint(self):
sql = """
CREATE TABLE test_primary(
id INTEGER NOT NULL,
created DATE,
PRIMARY KEY(id)
)
"""
with connection.cursor() as cursor:
try:
cursor.execute(sql)
field = connection.introspection.get_primary_key_column(
cursor,
"test_primary",
)
self.assertEqual(field, "id")
finally:
cursor.execute("DROP TABLE test_primary")
@unittest.skipUnless(connection.vendor == "sqlite", "SQLite tests")
class ParsingTests(TestCase):
def parse_definition(self, sql, columns):
"""Parse a column or constraint definition."""
statement = sqlparse.parse(sql)[0]
tokens = (token for token in statement.flatten() if not token.is_whitespace)
with connection.cursor():
return connection.introspection._parse_column_or_constraint_definition(
tokens, set(columns)
)
def assertConstraint(self, constraint_details, cols, unique=False, check=False):
self.assertEqual(
constraint_details,
{
"unique": unique,
"columns": cols,
"primary_key": False,
"foreign_key": None,
"check": check,
"index": False,
},
)
def test_unique_column(self):
tests = (
('"ref" integer UNIQUE,', ["ref"]),
("ref integer UNIQUE,", ["ref"]),
('"customname" integer UNIQUE,', ["customname"]),
("customname integer UNIQUE,", ["customname"]),
)
for sql, columns in tests:
with self.subTest(sql=sql):
constraint, details, check, _ = self.parse_definition(sql, columns)
self.assertIsNone(constraint)
self.assertConstraint(details, columns, unique=True)
self.assertIsNone(check)
def test_unique_constraint(self):
tests = (
('CONSTRAINT "ref" UNIQUE ("ref"),', "ref", ["ref"]),
("CONSTRAINT ref UNIQUE (ref),", "ref", ["ref"]),
(
'CONSTRAINT "customname1" UNIQUE ("customname2"),',
"customname1",
["customname2"],
),
(
"CONSTRAINT customname1 UNIQUE (customname2),",
"customname1",
["customname2"],
),
)
for sql, constraint_name, columns in tests:
with self.subTest(sql=sql):
constraint, details, check, _ = self.parse_definition(sql, columns)
self.assertEqual(constraint, constraint_name)
self.assertConstraint(details, columns, unique=True)
self.assertIsNone(check)
def test_unique_constraint_multicolumn(self):
tests = (
(
'CONSTRAINT "ref" UNIQUE ("ref", "customname"),',
"ref",
["ref", "customname"],
),
("CONSTRAINT ref UNIQUE (ref, customname),", "ref", ["ref", "customname"]),
)
for sql, constraint_name, columns in tests:
with self.subTest(sql=sql):
constraint, details, check, _ = self.parse_definition(sql, columns)
self.assertEqual(constraint, constraint_name)
self.assertConstraint(details, columns, unique=True)
self.assertIsNone(check)
def test_check_column(self):
tests = (
('"ref" varchar(255) CHECK ("ref" != \'test\'),', ["ref"]),
("ref varchar(255) CHECK (ref != 'test'),", ["ref"]),
(
'"customname1" varchar(255) CHECK ("customname2" != \'test\'),',
["customname2"],
),
(
"customname1 varchar(255) CHECK (customname2 != 'test'),",
["customname2"],
),
)
for sql, columns in tests:
with self.subTest(sql=sql):
constraint, details, check, _ = self.parse_definition(sql, columns)
self.assertIsNone(constraint)
self.assertIsNone(details)
self.assertConstraint(check, columns, check=True)
def test_check_constraint(self):
tests = (
('CONSTRAINT "ref" CHECK ("ref" != \'test\'),', "ref", ["ref"]),
("CONSTRAINT ref CHECK (ref != 'test'),", "ref", ["ref"]),
(
'CONSTRAINT "customname1" CHECK ("customname2" != \'test\'),',
"customname1",
["customname2"],
),
(
"CONSTRAINT customname1 CHECK (customname2 != 'test'),",
"customname1",
["customname2"],
),
)
for sql, constraint_name, columns in tests:
with self.subTest(sql=sql):
constraint, details, check, _ = self.parse_definition(sql, columns)
self.assertEqual(constraint, constraint_name)
self.assertIsNone(details)
self.assertConstraint(check, columns, check=True)
def test_check_column_with_operators_and_functions(self):
tests = (
('"ref" integer CHECK ("ref" BETWEEN 1 AND 10),', ["ref"]),
('"ref" varchar(255) CHECK ("ref" LIKE \'test%\'),', ["ref"]),
(
'"ref" varchar(255) CHECK (LENGTH(ref) > "max_length"),',
["ref", "max_length"],
),
)
for sql, columns in tests:
with self.subTest(sql=sql):
constraint, details, check, _ = self.parse_definition(sql, columns)
self.assertIsNone(constraint)
self.assertIsNone(details)
self.assertConstraint(check, columns, check=True)
def test_check_and_unique_column(self):
tests = (
('"ref" varchar(255) CHECK ("ref" != \'test\') UNIQUE,', ["ref"]),
("ref varchar(255) UNIQUE CHECK (ref != 'test'),", ["ref"]),
)
for sql, columns in tests:
with self.subTest(sql=sql):
constraint, details, check, _ = self.parse_definition(sql, columns)
self.assertIsNone(constraint)
self.assertConstraint(details, columns, unique=True)
self.assertConstraint(check, columns, check=True)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/backends/mysql/test_operations.py | tests/backends/mysql/test_operations.py | import unittest
from django.core.management.color import no_style
from django.db import connection
from django.test import SimpleTestCase
from ..models import Person, Tag
@unittest.skipUnless(connection.vendor == "mysql", "MySQL tests.")
class MySQLOperationsTests(SimpleTestCase):
def test_sql_flush(self):
# allow_cascade doesn't change statements on MySQL.
for allow_cascade in [False, True]:
with self.subTest(allow_cascade=allow_cascade):
self.assertEqual(
connection.ops.sql_flush(
no_style(),
[Person._meta.db_table, Tag._meta.db_table],
allow_cascade=allow_cascade,
),
[
"SET FOREIGN_KEY_CHECKS = 0;",
"DELETE FROM `backends_person`;",
"DELETE FROM `backends_tag`;",
"SET FOREIGN_KEY_CHECKS = 1;",
],
)
def test_sql_flush_sequences(self):
# allow_cascade doesn't change statements on MySQL.
for allow_cascade in [False, True]:
with self.subTest(allow_cascade=allow_cascade):
self.assertEqual(
connection.ops.sql_flush(
no_style(),
[Person._meta.db_table, Tag._meta.db_table],
reset_sequences=True,
allow_cascade=allow_cascade,
),
[
"SET FOREIGN_KEY_CHECKS = 0;",
"TRUNCATE `backends_person`;",
"TRUNCATE `backends_tag`;",
"SET FOREIGN_KEY_CHECKS = 1;",
],
)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/backends/mysql/test_features.py | tests/backends/mysql/test_features.py | from unittest import mock, skipUnless
from django.db import connection
from django.db.backends.mysql.features import DatabaseFeatures
from django.test import TestCase
@skipUnless(connection.vendor == "mysql", "MySQL tests")
class TestFeatures(TestCase):
def test_supports_transactions(self):
"""
All storage engines except MyISAM support transactions.
"""
del connection.features.supports_transactions
with mock.patch(
"django.db.connection.features._mysql_storage_engine", "InnoDB"
):
self.assertTrue(connection.features.supports_transactions)
del connection.features.supports_transactions
with mock.patch(
"django.db.connection.features._mysql_storage_engine", "MyISAM"
):
self.assertFalse(connection.features.supports_transactions)
del connection.features.supports_transactions
def test_allows_auto_pk_0(self):
with mock.MagicMock() as _connection:
_connection.sql_mode = {"NO_AUTO_VALUE_ON_ZERO"}
database_features = DatabaseFeatures(_connection)
self.assertIs(database_features.allows_auto_pk_0, True)
def test_allows_group_by_selected_pks(self):
with mock.MagicMock() as _connection:
_connection.mysql_is_mariadb = False
database_features = DatabaseFeatures(_connection)
self.assertIs(database_features.allows_group_by_selected_pks, True)
with mock.MagicMock() as _connection:
_connection.mysql_is_mariadb = False
_connection.sql_mode = {}
database_features = DatabaseFeatures(_connection)
self.assertIs(database_features.allows_group_by_selected_pks, True)
with mock.MagicMock() as _connection:
_connection.mysql_is_mariadb = True
_connection.sql_mode = {"ONLY_FULL_GROUP_BY"}
database_features = DatabaseFeatures(_connection)
self.assertIs(database_features.allows_group_by_selected_pks, False)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/backends/mysql/test_creation.py | tests/backends/mysql/test_creation.py | import subprocess
import unittest
from io import BytesIO, StringIO
from unittest import mock
from django.db import DatabaseError, connection
from django.db.backends.base.creation import BaseDatabaseCreation
from django.db.backends.mysql.creation import DatabaseCreation
from django.test import SimpleTestCase
from django.test.utils import captured_stderr
@unittest.skipUnless(connection.vendor == "mysql", "MySQL tests")
class DatabaseCreationTests(SimpleTestCase):
def _execute_raise_database_exists(self, cursor, parameters, keepdb=False):
raise DatabaseError(
1007, "Can't create database '%s'; database exists" % parameters["dbname"]
)
def _execute_raise_access_denied(self, cursor, parameters, keepdb=False):
raise DatabaseError(1044, "Access denied for user")
def patch_test_db_creation(self, execute_create_test_db):
return mock.patch.object(
BaseDatabaseCreation, "_execute_create_test_db", execute_create_test_db
)
@mock.patch("sys.stdout", new_callable=StringIO)
@mock.patch("sys.stderr", new_callable=StringIO)
def test_create_test_db_database_exists(self, *mocked_objects):
# Simulate test database creation raising "database exists"
creation = DatabaseCreation(connection)
with self.patch_test_db_creation(self._execute_raise_database_exists):
with mock.patch("builtins.input", return_value="no"):
with self.assertRaises(SystemExit):
# SystemExit is raised if the user answers "no" to the
# prompt asking if it's okay to delete the test database.
creation._create_test_db(
verbosity=0, autoclobber=False, keepdb=False
)
# "Database exists" shouldn't appear when keepdb is on
creation._create_test_db(verbosity=0, autoclobber=False, keepdb=True)
@mock.patch("sys.stdout", new_callable=StringIO)
@mock.patch("sys.stderr", new_callable=StringIO)
def test_create_test_db_unexpected_error(self, *mocked_objects):
# Simulate test database creation raising unexpected error
creation = DatabaseCreation(connection)
with self.patch_test_db_creation(self._execute_raise_access_denied):
with self.assertRaises(SystemExit):
creation._create_test_db(verbosity=0, autoclobber=False, keepdb=False)
def test_clone_test_db_database_exists(self):
creation = DatabaseCreation(connection)
with self.patch_test_db_creation(self._execute_raise_database_exists):
with mock.patch.object(DatabaseCreation, "_clone_db") as _clone_db:
creation._clone_test_db("suffix", verbosity=0, keepdb=True)
_clone_db.assert_not_called()
def test_clone_test_db_options_ordering(self):
creation = DatabaseCreation(connection)
mock_subprocess_call = mock.MagicMock()
mock_subprocess_call.returncode = 0
try:
saved_settings = connection.settings_dict
connection.settings_dict = {
"NAME": "source_db",
"USER": "",
"PASSWORD": "",
"PORT": "",
"HOST": "",
"ENGINE": "django.db.backends.mysql",
"OPTIONS": {
"read_default_file": "my.cnf",
},
}
with mock.patch.object(subprocess, "Popen") as mocked_popen:
mocked_popen.return_value.__enter__.return_value = mock_subprocess_call
creation._clone_db("source_db", "target_db")
mocked_popen.assert_has_calls(
[
mock.call(
[
"mysqldump",
"--defaults-file=my.cnf",
"--routines",
"--events",
"source_db",
],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
env=None,
),
]
)
finally:
connection.settings_dict = saved_settings
def test_clone_test_db_subprocess_mysqldump_error(self):
creation = DatabaseCreation(connection)
mock_subprocess_call = mock.MagicMock()
mock_subprocess_call.returncode = 0
# Simulate mysqldump in test database cloning raises an error.
msg = "Couldn't execute 'SELECT ...'"
mock_subprocess_call_error = mock.MagicMock()
mock_subprocess_call_error.returncode = 2
mock_subprocess_call_error.stderr = BytesIO(msg.encode())
with mock.patch.object(subprocess, "Popen") as mocked_popen:
mocked_popen.return_value.__enter__.side_effect = [
mock_subprocess_call_error, # mysqldump mock
mock_subprocess_call, # load mock
]
with captured_stderr() as err, self.assertRaises(SystemExit) as cm:
creation._clone_db("source_db", "target_db")
self.assertEqual(cm.exception.code, 2)
self.assertIn(
f"Got an error on mysqldump when cloning the test database: {msg}",
err.getvalue(),
)
def test_clone_test_db_subprocess_mysql_error(self):
creation = DatabaseCreation(connection)
mock_subprocess_call = mock.MagicMock()
mock_subprocess_call.returncode = 0
# Simulate load in test database cloning raises an error.
msg = "Some error"
mock_subprocess_call_error = mock.MagicMock()
mock_subprocess_call_error.returncode = 3
mock_subprocess_call_error.stderr = BytesIO(msg.encode())
with mock.patch.object(subprocess, "Popen") as mocked_popen:
mocked_popen.return_value.__enter__.side_effect = [
mock_subprocess_call, # mysqldump mock
mock_subprocess_call_error, # load mock
]
with captured_stderr() as err, self.assertRaises(SystemExit) as cm:
creation._clone_db("source_db", "target_db")
self.assertEqual(cm.exception.code, 3)
self.assertIn(f"Got an error cloning the test database: {msg}", err.getvalue())
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/backends/mysql/__init__.py | tests/backends/mysql/__init__.py | python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false | |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/backends/mysql/tests.py | tests/backends/mysql/tests.py | import unittest
from contextlib import contextmanager
from unittest import mock
from django.core.exceptions import ImproperlyConfigured
from django.db import NotSupportedError, connection
from django.test import TestCase, override_settings
@contextmanager
def get_connection():
new_connection = connection.copy()
yield new_connection
new_connection.close()
@override_settings(DEBUG=True)
@unittest.skipUnless(connection.vendor == "mysql", "MySQL tests")
class IsolationLevelTests(TestCase):
read_committed = "read committed"
repeatable_read = "repeatable read"
isolation_values = {
level: level.upper() for level in (read_committed, repeatable_read)
}
@classmethod
def setUpClass(cls):
super().setUpClass()
configured_isolation_level = (
connection.isolation_level or cls.isolation_values[cls.repeatable_read]
)
cls.configured_isolation_level = configured_isolation_level.upper()
cls.other_isolation_level = (
cls.read_committed
if configured_isolation_level != cls.isolation_values[cls.read_committed]
else cls.repeatable_read
)
@staticmethod
def get_isolation_level(connection):
with connection.cursor() as cursor:
cursor.execute(
"SHOW VARIABLES "
"WHERE variable_name IN ('transaction_isolation', 'tx_isolation')"
)
return cursor.fetchone()[1].replace("-", " ")
def test_auto_is_null_auto_config(self):
query = "set sql_auto_is_null = 0"
connection.init_connection_state()
last_query = connection.queries[-1]["sql"].lower()
if connection.features.is_sql_auto_is_null_enabled:
self.assertIn(query, last_query)
else:
self.assertNotIn(query, last_query)
def test_connect_isolation_level(self):
self.assertEqual(
self.get_isolation_level(connection), self.configured_isolation_level
)
def test_setting_isolation_level(self):
with get_connection() as new_connection:
new_connection.settings_dict["OPTIONS"][
"isolation_level"
] = self.other_isolation_level
self.assertEqual(
self.get_isolation_level(new_connection),
self.isolation_values[self.other_isolation_level],
)
def test_uppercase_isolation_level(self):
# Upper case values are also accepted in 'isolation_level'.
with get_connection() as new_connection:
new_connection.settings_dict["OPTIONS"][
"isolation_level"
] = self.other_isolation_level.upper()
self.assertEqual(
self.get_isolation_level(new_connection),
self.isolation_values[self.other_isolation_level],
)
def test_default_isolation_level(self):
# If not specified in settings, the default is read committed.
with get_connection() as new_connection:
new_connection.settings_dict["OPTIONS"].pop("isolation_level", None)
self.assertEqual(
self.get_isolation_level(new_connection),
self.isolation_values[self.read_committed],
)
def test_isolation_level_validation(self):
new_connection = connection.copy()
new_connection.settings_dict["OPTIONS"]["isolation_level"] = "xxx"
msg = (
"Invalid transaction isolation level 'xxx' specified.\n"
"Use one of 'read committed', 'read uncommitted', "
"'repeatable read', 'serializable', or None."
)
with self.assertRaisesMessage(ImproperlyConfigured, msg):
new_connection.cursor()
@unittest.skipUnless(connection.vendor == "mysql", "MySQL tests")
class Tests(TestCase):
@mock.patch.object(connection, "get_database_version")
def test_check_database_version_supported(self, mocked_get_database_version):
if connection.mysql_is_mariadb:
mocked_get_database_version.return_value = (10, 5)
msg = "MariaDB 10.6 or later is required (found 10.5)."
else:
mocked_get_database_version.return_value = (8, 0, 31)
msg = "MySQL 8.4 or later is required (found 8.0.31)."
with self.assertRaisesMessage(NotSupportedError, msg):
connection.check_database_version_supported()
self.assertTrue(mocked_get_database_version.called)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/backends/mysql/test_schema.py | tests/backends/mysql/test_schema.py | import unittest
from django.db import connection
from django.test import TestCase
@unittest.skipUnless(connection.vendor == "mysql", "MySQL tests")
class SchemaEditorTests(TestCase):
def test_quote_value(self):
import MySQLdb
editor = connection.schema_editor()
tested_values = [
("string", "'string'"),
("¿Tú hablas inglés?", "'¿Tú hablas inglés?'"),
(b"bytes", b"'bytes'"),
(42, "42"),
(1.754, "1.754e0" if MySQLdb.version_info >= (1, 3, 14) else "1.754"),
(False, b"0" if MySQLdb.version_info >= (1, 4, 0) else "0"),
]
for value, expected in tested_values:
with self.subTest(value=value):
self.assertEqual(editor.quote_value(value), expected)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/backends/mysql/test_introspection.py | tests/backends/mysql/test_introspection.py | from unittest import skipUnless
from django.db import connection, connections
from django.test import TestCase
@skipUnless(connection.vendor == "mysql", "MySQL tests")
class ParsingTests(TestCase):
def test_parse_constraint_columns(self):
_parse_constraint_columns = connection.introspection._parse_constraint_columns
tests = (
("`height` >= 0", ["height"], ["height"]),
("`cost` BETWEEN 1 AND 10", ["cost"], ["cost"]),
("`ref1` > `ref2`", ["id", "ref1", "ref2"], ["ref1", "ref2"]),
(
"`start` IS NULL OR `end` IS NULL OR `start` < `end`",
["id", "start", "end"],
["start", "end"],
),
("JSON_VALID(`json_field`)", ["json_field"], ["json_field"]),
("CHAR_LENGTH(`name`) > 2", ["name"], ["name"]),
("lower(`ref1`) != 'test'", ["id", "owe", "ref1"], ["ref1"]),
("lower(`ref1`) != 'test'", ["id", "lower", "ref1"], ["ref1"]),
("`name` LIKE 'test%'", ["name"], ["name"]),
)
for check_clause, table_columns, expected_columns in tests:
with self.subTest(check_clause):
check_columns = _parse_constraint_columns(check_clause, table_columns)
self.assertEqual(list(check_columns), expected_columns)
@skipUnless(connection.vendor == "mysql", "MySQL tests")
class StorageEngineTests(TestCase):
databases = {"default", "other"}
def test_get_storage_engine(self):
table_name = "test_storage_engine"
create_sql = "CREATE TABLE %s (id INTEGER) ENGINE = %%s" % table_name
drop_sql = "DROP TABLE %s" % table_name
default_connection = connections["default"]
other_connection = connections["other"]
try:
with default_connection.cursor() as cursor:
cursor.execute(create_sql % "InnoDB")
self.assertEqual(
default_connection.introspection.get_storage_engine(
cursor, table_name
),
"InnoDB",
)
with other_connection.cursor() as cursor:
cursor.execute(create_sql % "MyISAM")
self.assertEqual(
other_connection.introspection.get_storage_engine(
cursor, table_name
),
"MyISAM",
)
finally:
with default_connection.cursor() as cursor:
cursor.execute(drop_sql)
with other_connection.cursor() as cursor:
cursor.execute(drop_sql)
@skipUnless(connection.vendor == "mysql", "MySQL specific SQL")
class TestCrossDatabaseRelations(TestCase):
databases = {"default", "other"}
def test_omit_cross_database_relations(self):
default_connection = connections["default"]
other_connection = connections["other"]
main_table = "cross_schema_get_relations_main_table"
main_table_quoted = default_connection.ops.quote_name(main_table)
other_schema_quoted = other_connection.ops.quote_name(
other_connection.settings_dict["NAME"]
)
rel_table = "cross_schema_get_relations_rel_table"
rel_table_quoted = other_connection.ops.quote_name(rel_table)
rel_column = "cross_schema_get_relations_rel_table_id"
rel_column_quoted = other_connection.ops.quote_name(rel_column)
try:
with other_connection.cursor() as other_cursor:
other_cursor.execute(
f"""
CREATE TABLE {rel_table_quoted} (
id integer AUTO_INCREMENT,
PRIMARY KEY (id)
)
"""
)
with default_connection.cursor() as default_cursor:
# Create table in the default schema with a cross-database
# relation.
default_cursor.execute(
f"""
CREATE TABLE {main_table_quoted} (
id integer AUTO_INCREMENT,
{rel_column_quoted} integer NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY ({rel_column_quoted})
REFERENCES {other_schema_quoted}.{rel_table_quoted}(id)
)
"""
)
relations = default_connection.introspection.get_relations(
default_cursor, main_table
)
constraints = default_connection.introspection.get_constraints(
default_cursor, main_table
)
self.assertEqual(len(relations), 0)
rel_column_fk_constraints = [
spec
for name, spec in constraints.items()
if spec["columns"] == [rel_column] and spec["foreign_key"] is not None
]
self.assertEqual(len(rel_column_fk_constraints), 0)
finally:
with default_connection.cursor() as default_cursor:
default_cursor.execute(f"DROP TABLE IF EXISTS {main_table_quoted}")
with other_connection.cursor() as other_cursor:
other_cursor.execute(f"DROP TABLE IF EXISTS {rel_table_quoted}")
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/servers/test_basehttp.py | tests/servers/test_basehttp.py | from io import BytesIO
from socketserver import ThreadingMixIn
from django.core.handlers.wsgi import WSGIRequest
from django.core.servers.basehttp import WSGIRequestHandler, WSGIServer
from django.test import SimpleTestCase
from django.test.client import RequestFactory
from django.test.utils import captured_stderr
class Stub(ThreadingMixIn):
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
def sendall(self, data):
self.makefile("wb").write(data)
class UnclosableBytesIO(BytesIO):
def close(self):
# WSGIRequestHandler closes the output file; we need to make this a
# no-op so we can still read its contents.
pass
class WSGIRequestHandlerTestCase(SimpleTestCase):
request_factory = RequestFactory()
def test_log_message(self):
request = WSGIRequest(self.request_factory.get("/").environ)
request.makefile = lambda *args, **kwargs: BytesIO()
handler = WSGIRequestHandler(request, "192.168.0.2", None)
level_status_codes = {
"info": [200, 301, 304],
"warning": [400, 403, 404],
"error": [500, 503],
}
for level, status_codes in level_status_codes.items():
for status_code in status_codes:
# The correct level gets the message.
with self.assertLogs("django.server", level.upper()) as cm:
handler.log_message("GET %s %s", "A", str(status_code))
self.assertIn("GET A %d" % status_code, cm.output[0])
# Incorrect levels don't have any messages.
for wrong_level in level_status_codes:
if wrong_level != level:
with self.assertLogs("django.server", "INFO") as cm:
handler.log_message("GET %s %s", "A", str(status_code))
self.assertNotEqual(
cm.records[0].levelname, wrong_level.upper()
)
def test_log_message_escapes_control_sequences(self):
request = WSGIRequest(self.request_factory.get("/").environ)
request.makefile = lambda *args, **kwargs: BytesIO()
handler = WSGIRequestHandler(request, "192.168.0.2", None)
malicious_path = "\x1b[31mALERT\x1b[0m"
with self.assertLogs("django.server", "WARNING") as cm:
handler.log_message("GET %s %s", malicious_path, "404")
log = cm.output[0]
self.assertNotIn("\x1b[31m", log)
self.assertIn("\\x1b[31mALERT\\x1b[0m", log)
def test_https(self):
request = WSGIRequest(self.request_factory.get("/").environ)
request.makefile = lambda *args, **kwargs: BytesIO()
handler = WSGIRequestHandler(request, "192.168.0.2", None)
with self.assertLogs("django.server", "ERROR") as cm:
handler.log_message("GET %s %s", "\x16\x03", "4")
self.assertEqual(
"You're accessing the development server over HTTPS, "
"but it only supports HTTP.",
cm.records[0].getMessage(),
)
def test_strips_underscore_headers(self):
"""WSGIRequestHandler ignores headers containing underscores.
This follows the lead of nginx and Apache 2.4, and is to avoid
ambiguity between dashes and underscores in mapping to WSGI environ,
which can have security implications.
"""
def test_app(environ, start_response):
"""A WSGI app that just reflects its HTTP environ."""
start_response("200 OK", [])
http_environ_items = sorted(
"%s:%s" % (k, v) for k, v in environ.items() if k.startswith("HTTP_")
)
yield (",".join(http_environ_items)).encode()
rfile = BytesIO()
rfile.write(b"GET / HTTP/1.0\r\n")
rfile.write(b"Some-Header: good\r\n")
rfile.write(b"Some_Header: bad\r\n")
rfile.write(b"Other_Header: bad\r\n")
rfile.seek(0)
wfile = UnclosableBytesIO()
def makefile(mode, *a, **kw):
if mode == "rb":
return rfile
elif mode == "wb":
return wfile
request = Stub(makefile=makefile)
server = Stub(base_environ={}, get_app=lambda: test_app)
# Prevent logging from appearing in test output.
with self.assertLogs("django.server", "INFO"):
# instantiating a handler runs the request as side effect
WSGIRequestHandler(request, "192.168.0.2", server)
wfile.seek(0)
body = list(wfile.readlines())[-1]
self.assertEqual(body, b"HTTP_SOME_HEADER:good")
def test_no_body_returned_for_head_requests(self):
hello_world_body = b"<!DOCTYPE html><html><body>Hello World</body></html>"
content_length = len(hello_world_body)
def test_app(environ, start_response):
"""A WSGI app that returns a hello world."""
start_response("200 OK", [])
return [hello_world_body]
rfile = BytesIO(b"GET / HTTP/1.0\r\n")
rfile.seek(0)
wfile = UnclosableBytesIO()
def makefile(mode, *a, **kw):
if mode == "rb":
return rfile
elif mode == "wb":
return wfile
request = Stub(makefile=makefile)
server = Stub(base_environ={}, get_app=lambda: test_app)
# Prevent logging from appearing in test output.
with self.assertLogs("django.server", "INFO"):
# Instantiating a handler runs the request as side effect.
WSGIRequestHandler(request, "192.168.0.2", server)
wfile.seek(0)
lines = list(wfile.readlines())
body = lines[-1]
# The body is returned in a GET response.
self.assertEqual(body, hello_world_body)
self.assertIn(f"Content-Length: {content_length}\r\n".encode(), lines)
self.assertNotIn(b"Connection: close\r\n", lines)
rfile = BytesIO(b"HEAD / HTTP/1.0\r\n")
rfile.seek(0)
wfile = UnclosableBytesIO()
with self.assertLogs("django.server", "INFO"):
WSGIRequestHandler(request, "192.168.0.2", server)
wfile.seek(0)
lines = list(wfile.readlines())
body = lines[-1]
# The body is not returned in a HEAD response.
self.assertEqual(body, b"\r\n")
self.assertIs(
any([line.startswith(b"Content-Length:") for line in lines]), False
)
self.assertNotIn(b"Connection: close\r\n", lines)
def test_non_zero_content_length_set_head_request(self):
hello_world_body = b"<!DOCTYPE html><html><body>Hello World</body></html>"
content_length = len(hello_world_body)
def test_app(environ, start_response):
"""
A WSGI app that returns a hello world with non-zero Content-Length.
"""
start_response("200 OK", [("Content-length", str(content_length))])
return [hello_world_body]
rfile = BytesIO(b"HEAD / HTTP/1.0\r\n")
rfile.seek(0)
wfile = UnclosableBytesIO()
def makefile(mode, *a, **kw):
if mode == "rb":
return rfile
elif mode == "wb":
return wfile
request = Stub(makefile=makefile)
server = Stub(base_environ={}, get_app=lambda: test_app)
# Prevent logging from appearing in test output.
with self.assertLogs("django.server", "INFO"):
# Instantiating a handler runs the request as side effect.
WSGIRequestHandler(request, "192.168.0.2", server)
wfile.seek(0)
lines = list(wfile.readlines())
body = lines[-1]
# The body is not returned in a HEAD response.
self.assertEqual(body, b"\r\n")
# Non-zero Content-Length is not removed.
self.assertEqual(lines[-2], f"Content-length: {content_length}\r\n".encode())
self.assertNotIn(b"Connection: close\r\n", lines)
class WSGIServerTestCase(SimpleTestCase):
request_factory = RequestFactory()
def test_broken_pipe_errors(self):
"""WSGIServer handles broken pipe errors."""
request = WSGIRequest(self.request_factory.get("/").environ)
client_address = ("192.168.2.0", 8080)
msg = f"- Broken pipe from {client_address}"
tests = [
BrokenPipeError,
ConnectionAbortedError,
ConnectionResetError,
]
for exception in tests:
with self.subTest(exception=exception):
try:
server = WSGIServer(("localhost", 0), WSGIRequestHandler)
try:
raise exception()
except Exception:
with captured_stderr() as err:
with self.assertLogs("django.server", "INFO") as cm:
server.handle_error(request, client_address)
self.assertEqual(err.getvalue(), "")
self.assertEqual(cm.records[0].getMessage(), msg)
finally:
server.server_close()
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/servers/views.py | tests/servers/views.py | from urllib.request import urlopen
from django.http import HttpResponse, StreamingHttpResponse
from django.views.decorators.csrf import csrf_exempt
from .models import Person
def example_view(request):
return HttpResponse("example view")
def streaming_example_view(request):
return StreamingHttpResponse((b"I", b"am", b"a", b"stream"))
def model_view(request):
people = Person.objects.all()
return HttpResponse("\n".join(person.name for person in people))
def create_model_instance(request):
person = Person(name="emily")
person.save()
return HttpResponse()
def environ_view(request):
return HttpResponse(
"\n".join("%s: %r" % (k, v) for k, v in request.environ.items())
)
def subview(request):
return HttpResponse("subview")
def subview_calling_view(request):
with urlopen(request.GET["url"] + "/subview/") as response:
return HttpResponse("subview calling view: {}".format(response.read().decode()))
def check_model_instance_from_subview(request):
with urlopen(request.GET["url"] + "/create_model_instance/"):
pass
with urlopen(request.GET["url"] + "/model_view/") as response:
return HttpResponse("subview calling view: {}".format(response.read().decode()))
@csrf_exempt
def method_view(request):
return HttpResponse(request.method)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/servers/models.py | tests/servers/models.py | from django.db import models
class Person(models.Model):
name = models.CharField(max_length=255)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/servers/__init__.py | tests/servers/__init__.py | python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false | |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/servers/tests.py | tests/servers/tests.py | """
Tests for django.core.servers.
"""
import errno
import os
import socket
import threading
import unittest
from http.client import HTTPConnection
from urllib.error import HTTPError
from urllib.parse import urlencode
from urllib.request import urlopen
from django.conf import settings
from django.core.servers.basehttp import ThreadedWSGIServer, WSGIServer
from django.db import DEFAULT_DB_ALIAS, connection, connections
from django.test import LiveServerTestCase, override_settings
from django.test.testcases import LiveServerThread, QuietWSGIRequestHandler
from .models import Person
TEST_ROOT = os.path.dirname(__file__)
TEST_SETTINGS = {
"MEDIA_URL": "media/",
"MEDIA_ROOT": os.path.join(TEST_ROOT, "media"),
"STATIC_URL": "static/",
"STATIC_ROOT": os.path.join(TEST_ROOT, "static"),
}
@override_settings(ROOT_URLCONF="servers.urls", **TEST_SETTINGS)
class LiveServerBase(LiveServerTestCase):
available_apps = [
"servers",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
]
fixtures = ["testdata.json"]
def urlopen(self, url):
return urlopen(self.live_server_url + url)
class CloseConnectionTestServer(ThreadedWSGIServer):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# This event is set right after the first time a request closes its
# database connections.
self._connections_closed = threading.Event()
def _close_connections(self):
super()._close_connections()
self._connections_closed.set()
class CloseConnectionTestLiveServerThread(LiveServerThread):
server_class = CloseConnectionTestServer
def _create_server(self, connections_override=None):
return super()._create_server(connections_override=self.connections_override)
class LiveServerTestCloseConnectionTest(LiveServerBase):
server_thread_class = CloseConnectionTestLiveServerThread
@classmethod
def _make_connections_override(cls):
conn = connections[DEFAULT_DB_ALIAS]
cls.conn = conn
cls.old_conn_max_age = conn.settings_dict["CONN_MAX_AGE"]
# Set the connection's CONN_MAX_AGE to None to simulate the
# CONN_MAX_AGE setting being set to None on the server. This prevents
# Django from closing the connection and allows testing that
# ThreadedWSGIServer closes connections.
conn.settings_dict["CONN_MAX_AGE"] = None
# Pass a database connection through to the server to check it is being
# closed by ThreadedWSGIServer.
return {DEFAULT_DB_ALIAS: conn}
@classmethod
def tearDownConnectionTest(cls):
cls.conn.settings_dict["CONN_MAX_AGE"] = cls.old_conn_max_age
@classmethod
def tearDownClass(cls):
cls.tearDownConnectionTest()
super().tearDownClass()
def test_closes_connections(self):
# The server's request thread sets this event after closing
# its database connections.
closed_event = self.server_thread.httpd._connections_closed
conn = self.conn
# Open a connection to the database.
conn.connect()
self.assertIsNotNone(conn.connection)
with self.urlopen("/model_view/") as f:
# The server can access the database.
self.assertCountEqual(f.read().splitlines(), [b"jane", b"robert"])
# Wait for the server's request thread to close the connection.
# A timeout of 0.1 seconds should be more than enough. If the wait
# times out, the assertion after should fail.
closed_event.wait(timeout=0.1)
self.assertIsNone(conn.connection)
@unittest.skipUnless(connection.vendor == "sqlite", "SQLite specific test.")
class LiveServerInMemoryDatabaseLockTest(LiveServerBase):
def test_in_memory_database_lock(self):
"""
With a threaded LiveServer and an in-memory database, an error can
occur when 2 requests reach the server and try to lock the database
at the same time, if the requests do not share the same database
connection.
"""
conn = self.server_thread.connections_override[DEFAULT_DB_ALIAS]
source_connection = conn.connection
# Open a connection to the database.
conn.connect()
# Create a transaction to lock the database.
cursor = conn.cursor()
cursor.execute("BEGIN IMMEDIATE TRANSACTION")
try:
with self.urlopen("/create_model_instance/") as f:
self.assertEqual(f.status, 200)
except HTTPError:
self.fail("Unexpected error due to a database lock.")
finally:
# Release the transaction.
cursor.execute("ROLLBACK")
source_connection.close()
class FailingLiveServerThread(LiveServerThread):
def _create_server(self, connections_override=None):
raise RuntimeError("Error creating server.")
class LiveServerTestCaseSetupTest(LiveServerBase):
server_thread_class = FailingLiveServerThread
@classmethod
def check_allowed_hosts(cls, expected):
if settings.ALLOWED_HOSTS != expected:
raise RuntimeError(f"{settings.ALLOWED_HOSTS} != {expected}")
@classmethod
def setUpClass(cls):
cls.check_allowed_hosts(["testserver"])
try:
super().setUpClass()
except RuntimeError:
# LiveServerTestCase's change to ALLOWED_HOSTS should be reverted.
cls.doClassCleanups()
cls.check_allowed_hosts(["testserver"])
else:
raise RuntimeError("Server did not fail.")
cls.set_up_called = True
def test_set_up_class(self):
self.assertIs(self.set_up_called, True)
class LiveServerAddress(LiveServerBase):
@classmethod
def setUpClass(cls):
super().setUpClass()
# put it in a list to prevent descriptor lookups in test
cls.live_server_url_test = [cls.live_server_url]
def test_live_server_url_is_class_property(self):
self.assertIsInstance(self.live_server_url_test[0], str)
self.assertEqual(self.live_server_url_test[0], self.live_server_url)
class LiveServerSingleThread(LiveServerThread):
def _create_server(self, connections_override=None):
return WSGIServer(
(self.host, self.port), QuietWSGIRequestHandler, allow_reuse_address=False
)
class SingleThreadLiveServerTestCase(LiveServerTestCase):
server_thread_class = LiveServerSingleThread
class LiveServerViews(LiveServerBase):
def test_protocol(self):
"""Launched server serves with HTTP 1.1."""
with self.urlopen("/example_view/") as f:
self.assertEqual(f.version, 11)
def test_closes_connection_without_content_length(self):
"""
An HTTP 1.1 server is supposed to support keep-alive. Since our
development server is rather simple we support it only in cases where
we can detect a content length from the response. This should be doable
for all simple views and streaming responses where an iterable with
length of one is passed. The latter follows as result of
`set_content_length` from
https://github.com/python/cpython/blob/main/Lib/wsgiref/handlers.py.
If we cannot detect a content length we explicitly set the `Connection`
header to `close` to notify the client that we do not actually support
it.
"""
conn = HTTPConnection(
LiveServerViews.server_thread.host,
LiveServerViews.server_thread.port,
timeout=1,
)
try:
conn.request(
"GET", "/streaming_example_view/", headers={"Connection": "keep-alive"}
)
response = conn.getresponse()
self.assertTrue(response.will_close)
self.assertEqual(response.read(), b"Iamastream")
self.assertEqual(response.status, 200)
self.assertEqual(response.getheader("Connection"), "close")
conn.request(
"GET", "/streaming_example_view/", headers={"Connection": "close"}
)
response = conn.getresponse()
self.assertTrue(response.will_close)
self.assertEqual(response.read(), b"Iamastream")
self.assertEqual(response.status, 200)
self.assertEqual(response.getheader("Connection"), "close")
finally:
conn.close()
def test_keep_alive_on_connection_with_content_length(self):
"""
See `test_closes_connection_without_content_length` for details. This
is a follow up test, which ensure that we do not close the connection
if not needed, hence allowing us to take advantage of keep-alive.
"""
conn = HTTPConnection(
LiveServerViews.server_thread.host, LiveServerViews.server_thread.port
)
try:
conn.request("GET", "/example_view/", headers={"Connection": "keep-alive"})
response = conn.getresponse()
self.assertFalse(response.will_close)
self.assertEqual(response.read(), b"example view")
self.assertEqual(response.status, 200)
self.assertIsNone(response.getheader("Connection"))
conn.request("GET", "/example_view/", headers={"Connection": "close"})
response = conn.getresponse()
self.assertFalse(response.will_close)
self.assertEqual(response.read(), b"example view")
self.assertEqual(response.status, 200)
self.assertIsNone(response.getheader("Connection"))
finally:
conn.close()
def test_keep_alive_connection_clears_previous_request_data(self):
conn = HTTPConnection(
LiveServerViews.server_thread.host, LiveServerViews.server_thread.port
)
try:
conn.request(
"POST", "/method_view/", b"{}", headers={"Connection": "keep-alive"}
)
response = conn.getresponse()
self.assertFalse(response.will_close)
self.assertEqual(response.status, 200)
self.assertEqual(response.read(), b"POST")
conn.request(
"POST", "/method_view/", b"{}", headers={"Connection": "close"}
)
response = conn.getresponse()
self.assertFalse(response.will_close)
self.assertEqual(response.status, 200)
self.assertEqual(response.read(), b"POST")
finally:
conn.close()
def test_404(self):
with self.assertRaises(HTTPError) as err:
self.urlopen("/")
err.exception.close()
self.assertEqual(err.exception.code, 404, "Expected 404 response")
def test_view(self):
with self.urlopen("/example_view/") as f:
self.assertEqual(f.read(), b"example view")
def test_static_files(self):
with self.urlopen("/static/example_static_file.txt") as f:
self.assertEqual(f.read().rstrip(b"\r\n"), b"example static file")
def test_no_collectstatic_emulation(self):
"""
LiveServerTestCase reports a 404 status code when HTTP client
tries to access a static file that isn't explicitly put under
STATIC_ROOT.
"""
with self.assertRaises(HTTPError) as err:
self.urlopen("/static/another_app/another_app_static_file.txt")
err.exception.close()
self.assertEqual(err.exception.code, 404, "Expected 404 response")
def test_media_files(self):
with self.urlopen("/media/example_media_file.txt") as f:
self.assertEqual(f.read().rstrip(b"\r\n"), b"example media file")
def test_environ(self):
with self.urlopen("/environ_view/?%s" % urlencode({"q": "тест"})) as f:
self.assertIn(b"QUERY_STRING: 'q=%D1%82%D0%B5%D1%81%D1%82'", f.read())
@override_settings(ROOT_URLCONF="servers.urls")
class SingleThreadLiveServerViews(SingleThreadLiveServerTestCase):
available_apps = ["servers"]
def test_closes_connection_with_content_length(self):
"""
Contrast to
LiveServerViews.test_keep_alive_on_connection_with_content_length().
Persistent connections require threading server.
"""
conn = HTTPConnection(
SingleThreadLiveServerViews.server_thread.host,
SingleThreadLiveServerViews.server_thread.port,
timeout=1,
)
try:
conn.request("GET", "/example_view/", headers={"Connection": "keep-alive"})
response = conn.getresponse()
self.assertTrue(response.will_close)
self.assertEqual(response.read(), b"example view")
self.assertEqual(response.status, 200)
self.assertEqual(response.getheader("Connection"), "close")
finally:
conn.close()
class LiveServerDatabase(LiveServerBase):
def test_fixtures_loaded(self):
"""
Fixtures are properly loaded and visible to the live server thread.
"""
with self.urlopen("/model_view/") as f:
self.assertCountEqual(f.read().splitlines(), [b"jane", b"robert"])
def test_database_writes(self):
"""
Data written to the database by a view can be read.
"""
with self.urlopen("/create_model_instance/"):
pass
self.assertQuerySetEqual(
Person.objects.order_by("pk"),
["jane", "robert", "emily"],
lambda b: b.name,
)
class LiveServerPort(LiveServerBase):
def test_port_bind(self):
"""
Each LiveServerTestCase binds to a unique port or fails to start a
server thread when run concurrently (#26011).
"""
TestCase = type("TestCase", (LiveServerBase,), {})
try:
TestCase._start_server_thread()
except OSError as e:
if e.errno == errno.EADDRINUSE:
# We're out of ports, LiveServerTestCase correctly fails with
# an OSError.
return
# Unexpected error.
raise
try:
self.assertNotEqual(
self.live_server_url,
TestCase.live_server_url,
f"Acquired duplicate server addresses for server threads: "
f"{self.live_server_url}",
)
finally:
TestCase.doClassCleanups()
def test_specified_port_bind(self):
"""LiveServerTestCase.port customizes the server's port."""
TestCase = type("TestCase", (LiveServerBase,), {})
# Find an open port and tell TestCase to use it.
s = socket.socket()
s.bind(("", 0))
TestCase.port = s.getsockname()[1]
s.close()
TestCase._start_server_thread()
try:
self.assertEqual(
TestCase.port,
TestCase.server_thread.port,
f"Did not use specified port for LiveServerTestCase thread: "
f"{TestCase.port}",
)
finally:
TestCase.doClassCleanups()
class LiveServerThreadedTests(LiveServerBase):
"""If LiveServerTestCase isn't threaded, these tests will hang."""
def test_view_calls_subview(self):
url = "/subview_calling_view/?%s" % urlencode({"url": self.live_server_url})
with self.urlopen(url) as f:
self.assertEqual(f.read(), b"subview calling view: subview")
def test_check_model_instance_from_subview(self):
url = "/check_model_instance_from_subview/?%s" % urlencode(
{
"url": self.live_server_url,
}
)
with self.urlopen(url) as f:
self.assertIn(b"emily", f.read())
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/servers/test_liveserverthread.py | tests/servers/test_liveserverthread.py | from django.db import DEFAULT_DB_ALIAS, connections
from django.test import LiveServerTestCase, TransactionTestCase
from django.test.testcases import LiveServerThread
# Use TransactionTestCase instead of TestCase to run outside of a transaction,
# otherwise closing the connection would implicitly rollback and not set the
# connection to None.
class LiveServerThreadTest(TransactionTestCase):
available_apps = []
def run_live_server_thread(self, connections_override=None):
thread = LiveServerTestCase._create_server_thread(connections_override)
thread.daemon = True
thread.start()
thread.is_ready.wait()
thread.terminate()
def test_closes_connections(self):
conn = connections[DEFAULT_DB_ALIAS]
# Pass a connection to the thread to check they are being closed.
connections_override = {DEFAULT_DB_ALIAS: conn}
# Open a connection to the database.
conn.connect()
conn.inc_thread_sharing()
try:
self.assertIsNotNone(conn.connection)
self.run_live_server_thread(connections_override)
self.assertIsNone(conn.connection)
finally:
conn.dec_thread_sharing()
def test_server_class(self):
class FakeServer:
def __init__(*args, **kwargs):
pass
class MyServerThread(LiveServerThread):
server_class = FakeServer
class MyServerTestCase(LiveServerTestCase):
server_thread_class = MyServerThread
thread = MyServerTestCase._create_server_thread(None)
server = thread._create_server()
self.assertIs(type(server), FakeServer)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/servers/urls.py | tests/servers/urls.py | from django.urls import path
from . import views
urlpatterns = [
path("example_view/", views.example_view),
path("streaming_example_view/", views.streaming_example_view),
path("model_view/", views.model_view),
path("create_model_instance/", views.create_model_instance),
path("environ_view/", views.environ_view),
path("subview_calling_view/", views.subview_calling_view),
path("subview/", views.subview),
path("check_model_instance_from_subview/", views.check_model_instance_from_subview),
path("method_view/", views.method_view),
]
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/servers/another_app/__init__.py | tests/servers/another_app/__init__.py | python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false | |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/inline_formsets/models.py | tests/inline_formsets/models.py | from django.db import models
class School(models.Model):
name = models.CharField(max_length=100)
class Parent(models.Model):
name = models.CharField(max_length=100)
class Child(models.Model):
mother = models.ForeignKey(Parent, models.CASCADE, related_name="mothers_children")
father = models.ForeignKey(Parent, models.CASCADE, related_name="fathers_children")
school = models.ForeignKey(School, models.CASCADE)
name = models.CharField(max_length=100)
class Meta:
constraints = [
models.UniqueConstraint("mother", "father", name="unique_parents"),
]
class Poet(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
class Poem(models.Model):
poet = models.ForeignKey(Poet, models.CASCADE)
name = models.CharField(max_length=100)
class Meta:
unique_together = ("poet", "name")
def __str__(self):
return self.name
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/inline_formsets/__init__.py | tests/inline_formsets/__init__.py | python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false | |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/inline_formsets/tests.py | tests/inline_formsets/tests.py | from django.forms.models import ModelForm, inlineformset_factory
from django.test import TestCase, skipUnlessDBFeature
from .models import Child, Parent, Poem, Poet, School
class DeletionTests(TestCase):
def test_deletion(self):
PoemFormSet = inlineformset_factory(
Poet, Poem, can_delete=True, fields="__all__"
)
poet = Poet.objects.create(name="test")
poem = poet.poem_set.create(name="test poem")
data = {
"poem_set-TOTAL_FORMS": "1",
"poem_set-INITIAL_FORMS": "1",
"poem_set-MAX_NUM_FORMS": "0",
"poem_set-0-id": str(poem.pk),
"poem_set-0-poet": str(poet.pk),
"poem_set-0-name": "test",
"poem_set-0-DELETE": "on",
}
formset = PoemFormSet(data, instance=poet)
formset.save()
self.assertTrue(formset.is_valid())
self.assertEqual(Poem.objects.count(), 0)
def test_add_form_deletion_when_invalid(self):
"""
Make sure that an add form that is filled out, but marked for deletion
doesn't cause validation errors.
"""
PoemFormSet = inlineformset_factory(
Poet, Poem, can_delete=True, fields="__all__"
)
poet = Poet.objects.create(name="test")
data = {
"poem_set-TOTAL_FORMS": "1",
"poem_set-INITIAL_FORMS": "0",
"poem_set-MAX_NUM_FORMS": "0",
"poem_set-0-id": "",
"poem_set-0-poem": "1",
"poem_set-0-name": "x" * 1000,
}
formset = PoemFormSet(data, instance=poet)
# Make sure this form doesn't pass validation.
self.assertIs(formset.is_valid(), False)
self.assertEqual(Poem.objects.count(), 0)
# Then make sure that it *does* pass validation and delete the object,
# even though the data isn't actually valid.
data["poem_set-0-DELETE"] = "on"
formset = PoemFormSet(data, instance=poet)
self.assertIs(formset.is_valid(), True)
formset.save()
self.assertEqual(Poem.objects.count(), 0)
def test_change_form_deletion_when_invalid(self):
"""
Make sure that a change form that is filled out, but marked for
deletion doesn't cause validation errors.
"""
PoemFormSet = inlineformset_factory(
Poet, Poem, can_delete=True, fields="__all__"
)
poet = Poet.objects.create(name="test")
poem = poet.poem_set.create(name="test poem")
data = {
"poem_set-TOTAL_FORMS": "1",
"poem_set-INITIAL_FORMS": "1",
"poem_set-MAX_NUM_FORMS": "0",
"poem_set-0-id": str(poem.id),
"poem_set-0-poem": str(poem.id),
"poem_set-0-name": "x" * 1000,
}
formset = PoemFormSet(data, instance=poet)
# Make sure this form doesn't pass validation.
self.assertIs(formset.is_valid(), False)
self.assertEqual(Poem.objects.count(), 1)
# Then make sure that it *does* pass validation and delete the object,
# even though the data isn't actually valid.
data["poem_set-0-DELETE"] = "on"
formset = PoemFormSet(data, instance=poet)
self.assertIs(formset.is_valid(), True)
formset.save()
self.assertEqual(Poem.objects.count(), 0)
def test_save_new(self):
"""
Make sure inlineformsets respect commit=False
regression for #10750
"""
# exclude some required field from the forms
ChildFormSet = inlineformset_factory(
School, Child, exclude=["father", "mother"]
)
school = School.objects.create(name="test")
mother = Parent.objects.create(name="mother")
father = Parent.objects.create(name="father")
data = {
"child_set-TOTAL_FORMS": "1",
"child_set-INITIAL_FORMS": "0",
"child_set-MAX_NUM_FORMS": "0",
"child_set-0-name": "child",
}
formset = ChildFormSet(data, instance=school)
self.assertIs(formset.is_valid(), True)
objects = formset.save(commit=False)
for obj in objects:
obj.mother = mother
obj.father = father
obj.save()
self.assertEqual(school.child_set.count(), 1)
class InlineFormsetFactoryTest(TestCase):
def test_inline_formset_factory(self):
"""
These should both work without a problem.
"""
inlineformset_factory(Parent, Child, fk_name="mother", fields="__all__")
inlineformset_factory(Parent, Child, fk_name="father", fields="__all__")
def test_exception_on_unspecified_foreign_key(self):
"""
Child has two ForeignKeys to Parent, so if we don't specify which one
to use for the inline formset, we should get an exception.
"""
msg = (
"'inline_formsets.Child' has more than one ForeignKey to "
"'inline_formsets.Parent'."
)
with self.assertRaisesMessage(ValueError, msg):
inlineformset_factory(Parent, Child)
def test_fk_name_not_foreign_key_field_from_child(self):
"""
If we specify fk_name, but it isn't a ForeignKey from the child model
to the parent model, we should get an exception.
"""
msg = "fk_name 'school' is not a ForeignKey to 'inline_formsets.Parent'."
with self.assertRaisesMessage(ValueError, msg):
inlineformset_factory(Parent, Child, fk_name="school")
def test_non_foreign_key_field(self):
"""
If the field specified in fk_name is not a ForeignKey, we should get an
exception.
"""
with self.assertRaisesMessage(
ValueError, "'inline_formsets.Child' has no field named 'test'."
):
inlineformset_factory(Parent, Child, fk_name="test")
def test_any_iterable_allowed_as_argument_to_exclude(self):
# Regression test for #9171.
inlineformset_factory(Parent, Child, exclude=["school"], fk_name="mother")
inlineformset_factory(Parent, Child, exclude=("school",), fk_name="mother")
@skipUnlessDBFeature("allows_auto_pk_0")
def test_zero_primary_key(self):
# Regression test for #21472
poet = Poet.objects.create(id=0, name="test")
poet.poem_set.create(name="test poem")
PoemFormSet = inlineformset_factory(Poet, Poem, fields="__all__", extra=0)
formset = PoemFormSet(None, instance=poet)
self.assertEqual(len(formset.forms), 1)
def test_unsaved_fk_validate_unique(self):
poet = Poet(name="unsaved")
PoemFormSet = inlineformset_factory(Poet, Poem, fields=["name"])
data = {
"poem_set-TOTAL_FORMS": "2",
"poem_set-INITIAL_FORMS": "0",
"poem_set-MAX_NUM_FORMS": "2",
"poem_set-0-name": "Poem",
"poem_set-1-name": "Poem",
}
formset = PoemFormSet(data, instance=poet)
self.assertFalse(formset.is_valid())
self.assertEqual(
formset.non_form_errors(), ["Please correct the duplicate data for name."]
)
def test_fk_not_duplicated_in_form_fields(self):
"""
A foreign key name isn't duplicated in form._meta fields (#21332).
"""
poet = Poet.objects.create(name="test")
poet.poem_set.create(name="first test poem")
poet.poem_set.create(name="second test poem")
poet.poem_set.create(name="third test poem")
PoemFormSet = inlineformset_factory(Poet, Poem, fields=("name",), extra=0)
formset = PoemFormSet(None, instance=poet)
self.assertEqual(len(formset.forms), 3)
self.assertEqual(["name", "poet"], PoemFormSet.form._meta.fields)
def test_fk_in_all_formset_forms(self):
"""
A foreign key field is in Meta for all forms in the formset (#26538).
"""
class PoemModelForm(ModelForm):
def __init__(self, *args, **kwargs):
assert "poet" in self._meta.fields
super().__init__(*args, **kwargs)
poet = Poet.objects.create(name="test")
poet.poem_set.create(name="first test poem")
poet.poem_set.create(name="second test poem")
PoemFormSet = inlineformset_factory(
Poet, Poem, form=PoemModelForm, fields=("name",), extra=0
)
formset = PoemFormSet(None, instance=poet)
formset.forms # Trigger form instantiation to run the assert above.
class InlineFormsetConstraintsValidationTests(TestCase):
def test_constraint_refs_inline_foreignkey_field(self):
"""
Constraints that reference an InlineForeignKeyField should not be
skipped from validation (#35676).
"""
ChildFormSet = inlineformset_factory(
Parent,
Child,
fk_name="mother",
fields="__all__",
extra=1,
)
father = Parent.objects.create(name="James")
school = School.objects.create(name="Hogwarts")
mother = Parent.objects.create(name="Lily")
Child.objects.create(name="Harry", father=father, mother=mother, school=school)
data = {
"mothers_children-TOTAL_FORMS": "1",
"mothers_children-INITIAL_FORMS": "0",
"mothers_children-MIN_NUM_FORMS": "0",
"mothers_children-MAX_NUM_FORMS": "1000",
"mothers_children-0-id": "",
"mothers_children-0-father": str(father.pk),
"mothers_children-0-school": str(school.pk),
"mothers_children-0-name": "Mary",
}
formset = ChildFormSet(instance=mother, data=data, queryset=None)
self.assertFalse(formset.is_valid())
self.assertEqual(
formset.errors,
[{"__all__": ["Constraint “unique_parents” is violated."]}],
)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/view_tests/views.py | tests/view_tests/views.py | import datetime
import decimal
import logging
import sys
from pathlib import Path
from django.core.exceptions import BadRequest, PermissionDenied, SuspiciousOperation
from django.http import Http404, HttpResponse, JsonResponse
from django.shortcuts import render
from django.template import Context, Template, TemplateDoesNotExist
from django.urls import get_resolver
from django.views import View
from django.views.debug import (
ExceptionReporter,
SafeExceptionReporterFilter,
technical_500_response,
)
from django.views.decorators.debug import sensitive_post_parameters, sensitive_variables
TEMPLATES_PATH = Path(__file__).resolve().parent / "templates"
def index_page(request):
"""Dummy index page"""
return HttpResponse("<html><body>Dummy page</body></html>")
def with_parameter(request, parameter):
return HttpResponse("ok")
def raises(request):
# Make sure that a callable that raises an exception in the stack frame's
# local vars won't hijack the technical 500 response (#15025).
def callable():
raise Exception
try:
raise Exception
except Exception:
return technical_500_response(request, *sys.exc_info())
def raises500(request):
# We need to inspect the HTML generated by the fancy 500 debug view but
# the test client ignores it, so we send it explicitly.
try:
raise Exception
except Exception:
return technical_500_response(request, *sys.exc_info())
class Raises500View(View):
def get(self, request):
try:
raise Exception
except Exception:
return technical_500_response(request, *sys.exc_info())
def raises400(request):
raise SuspiciousOperation
def raises400_bad_request(request):
raise BadRequest("Malformed request syntax")
def raises403(request):
raise PermissionDenied("Insufficient Permissions")
def raises404(request):
resolver = get_resolver(None)
resolver.resolve("/not-in-urls")
def technical404(request):
raise Http404("Testing technical 404.")
class Http404View(View):
def get(self, request):
raise Http404("Testing class-based technical 404.")
def template_exception(request):
return render(request, "debug/template_exception.html")
def safestring_in_template_exception(request):
"""
Trigger an exception in the template machinery which causes a SafeString
to be inserted as args[0] of the Exception.
"""
template = Template('{% extends "<script>alert(1);</script>" %}')
try:
template.render(Context())
except Exception:
return technical_500_response(request, *sys.exc_info())
def jsi18n(request):
return render(request, "jsi18n.html")
def jsi18n_multi_catalogs(request):
return render(request, "jsi18n-multi-catalogs.html")
def raises_template_does_not_exist(request, path="i_dont_exist.html"):
# We need to inspect the HTML generated by the fancy 500 debug view but
# the test client ignores it, so we send it explicitly.
try:
return render(request, path)
except TemplateDoesNotExist:
return technical_500_response(request, *sys.exc_info())
def render_no_template(request):
# If we do not specify a template, we need to make sure the debug
# view doesn't blow up.
return render(request, [], {})
def send_log(request, exc_info):
logger = logging.getLogger("django")
# The default logging config has a logging filter to ensure admin emails
# are only sent with DEBUG=False, but since someone might choose to remove
# that filter, we still want to be able to test the behavior of error
# emails with DEBUG=True. So we need to remove the filter temporarily.
admin_email_handler = [
h for h in logger.handlers if h.__class__.__name__ == "AdminEmailHandler"
][0]
orig_filters = admin_email_handler.filters
admin_email_handler.filters = []
admin_email_handler.include_html = True
logger.error(
"Internal Server Error: %s",
request.path,
exc_info=exc_info,
extra={"status_code": 500, "request": request},
)
admin_email_handler.filters = orig_filters
def non_sensitive_view(request):
# Do not just use plain strings for the variables' values in the code
# so that the tests don't return false positives when the function's source
# is displayed in the exception report.
cooked_eggs = "".join(["s", "c", "r", "a", "m", "b", "l", "e", "d"]) # NOQA
sauce = "".join( # NOQA
["w", "o", "r", "c", "e", "s", "t", "e", "r", "s", "h", "i", "r", "e"]
)
try:
raise Exception
except Exception:
exc_info = sys.exc_info()
send_log(request, exc_info)
return technical_500_response(request, *exc_info)
@sensitive_variables("sauce")
@sensitive_post_parameters("bacon-key", "sausage-key")
def sensitive_view(request):
# Do not just use plain strings for the variables' values in the code
# so that the tests don't return false positives when the function's source
# is displayed in the exception report.
cooked_eggs = "".join(["s", "c", "r", "a", "m", "b", "l", "e", "d"]) # NOQA
sauce = "".join( # NOQA
["w", "o", "r", "c", "e", "s", "t", "e", "r", "s", "h", "i", "r", "e"]
)
try:
raise Exception
except Exception:
exc_info = sys.exc_info()
send_log(request, exc_info)
return technical_500_response(request, *exc_info)
@sensitive_variables("sauce")
@sensitive_post_parameters("bacon-key", "sausage-key")
async def async_sensitive_view(request):
# Do not just use plain strings for the variables' values in the code so
# that the tests don't return false positives when the function's source is
# displayed in the exception report.
cooked_eggs = "".join(["s", "c", "r", "a", "m", "b", "l", "e", "d"]) # NOQA
sauce = "".join( # NOQA
["w", "o", "r", "c", "e", "s", "t", "e", "r", "s", "h", "i", "r", "e"]
)
try:
raise Exception
except Exception:
exc_info = sys.exc_info()
send_log(request, exc_info)
return technical_500_response(request, *exc_info)
@sensitive_variables("sauce")
@sensitive_post_parameters("bacon-key", "sausage-key")
async def async_sensitive_function(request):
# Do not just use plain strings for the variables' values in the code so
# that the tests don't return false positives when the function's source is
# displayed in the exception report.
cooked_eggs = "".join(["s", "c", "r", "a", "m", "b", "l", "e", "d"]) # NOQA
sauce = "".join( # NOQA
["w", "o", "r", "c", "e", "s", "t", "e", "r", "s", "h", "i", "r", "e"]
)
raise Exception
async def async_sensitive_view_nested(request):
try:
await async_sensitive_function(request)
except Exception:
exc_info = sys.exc_info()
send_log(request, exc_info)
return technical_500_response(request, *exc_info)
@sensitive_variables()
@sensitive_post_parameters()
def paranoid_view(request):
# Do not just use plain strings for the variables' values in the code
# so that the tests don't return false positives when the function's source
# is displayed in the exception report.
cooked_eggs = "".join(["s", "c", "r", "a", "m", "b", "l", "e", "d"]) # NOQA
sauce = "".join( # NOQA
["w", "o", "r", "c", "e", "s", "t", "e", "r", "s", "h", "i", "r", "e"]
)
try:
raise Exception
except Exception:
exc_info = sys.exc_info()
send_log(request, exc_info)
return technical_500_response(request, *exc_info)
def sensitive_args_function_caller(request):
try:
sensitive_args_function(
"".join(
["w", "o", "r", "c", "e", "s", "t", "e", "r", "s", "h", "i", "r", "e"]
)
)
except Exception:
exc_info = sys.exc_info()
send_log(request, exc_info)
return technical_500_response(request, *exc_info)
@sensitive_variables("sauce")
def sensitive_args_function(sauce):
# Do not just use plain strings for the variables' values in the code
# so that the tests don't return false positives when the function's source
# is displayed in the exception report.
cooked_eggs = "".join(["s", "c", "r", "a", "m", "b", "l", "e", "d"]) # NOQA
raise Exception
def sensitive_kwargs_function_caller(request):
try:
sensitive_kwargs_function(
"".join(
["w", "o", "r", "c", "e", "s", "t", "e", "r", "s", "h", "i", "r", "e"]
)
)
except Exception:
exc_info = sys.exc_info()
send_log(request, exc_info)
return technical_500_response(request, *exc_info)
@sensitive_variables("sauce")
def sensitive_kwargs_function(sauce=None):
# Do not just use plain strings for the variables' values in the code
# so that the tests don't return false positives when the function's source
# is displayed in the exception report.
cooked_eggs = "".join(["s", "c", "r", "a", "m", "b", "l", "e", "d"]) # NOQA
raise Exception
class UnsafeExceptionReporterFilter(SafeExceptionReporterFilter):
"""
Ignores all the filtering done by its parent class.
"""
def get_post_parameters(self, request):
return request.POST
def get_traceback_frame_variables(self, request, tb_frame):
return tb_frame.f_locals.items()
@sensitive_variables()
@sensitive_post_parameters()
def custom_exception_reporter_filter_view(request):
# Do not just use plain strings for the variables' values in the code
# so that the tests don't return false positives when the function's source
# is displayed in the exception report.
cooked_eggs = "".join(["s", "c", "r", "a", "m", "b", "l", "e", "d"]) # NOQA
sauce = "".join( # NOQA
["w", "o", "r", "c", "e", "s", "t", "e", "r", "s", "h", "i", "r", "e"]
)
request.exception_reporter_filter = UnsafeExceptionReporterFilter()
try:
raise Exception
except Exception:
exc_info = sys.exc_info()
send_log(request, exc_info)
return technical_500_response(request, *exc_info)
class CustomExceptionReporter(ExceptionReporter):
custom_traceback_text = "custom traceback text"
def get_traceback_html(self):
return self.custom_traceback_text
class TemplateOverrideExceptionReporter(ExceptionReporter):
html_template_path = TEMPLATES_PATH / "my_technical_500.html"
text_template_path = TEMPLATES_PATH / "my_technical_500.txt"
def custom_reporter_class_view(request):
request.exception_reporter_class = CustomExceptionReporter
try:
raise Exception
except Exception:
exc_info = sys.exc_info()
return technical_500_response(request, *exc_info)
class Klass:
@sensitive_variables("sauce")
def method(self, request):
# Do not just use plain strings for the variables' values in the code
# so that the tests don't return false positives when the function's
# source is displayed in the exception report.
cooked_eggs = "".join(["s", "c", "r", "a", "m", "b", "l", "e", "d"]) # NOQA
sauce = "".join( # NOQA
["w", "o", "r", "c", "e", "s", "t", "e", "r", "s", "h", "i", "r", "e"]
)
try:
raise Exception
except Exception:
exc_info = sys.exc_info()
send_log(request, exc_info)
return technical_500_response(request, *exc_info)
@sensitive_variables("sauce")
async def async_method(self, request):
# Do not just use plain strings for the variables' values in the code
# so that the tests don't return false positives when the function's
# source is displayed in the exception report.
cooked_eggs = "".join(["s", "c", "r", "a", "m", "b", "l", "e", "d"]) # NOQA
sauce = "".join( # NOQA
["w", "o", "r", "c", "e", "s", "t", "e", "r", "s", "h", "i", "r", "e"]
)
try:
raise Exception
except Exception:
exc_info = sys.exc_info()
send_log(request, exc_info)
return technical_500_response(request, *exc_info)
@sensitive_variables("sauce")
async def _async_method_inner(self, request):
# Do not just use plain strings for the variables' values in the code
# so that the tests don't return false positives when the function's
# source is displayed in the exception report.
cooked_eggs = "".join(["s", "c", "r", "a", "m", "b", "l", "e", "d"]) # NOQA
sauce = "".join( # NOQA
["w", "o", "r", "c", "e", "s", "t", "e", "r", "s", "h", "i", "r", "e"]
)
raise Exception
async def async_method_nested(self, request):
try:
await self._async_method_inner(request)
except Exception:
exc_info = sys.exc_info()
send_log(request, exc_info)
return technical_500_response(request, *exc_info)
def sensitive_method_view(request):
return Klass().method(request)
async def async_sensitive_method_view(request):
return await Klass().async_method(request)
async def async_sensitive_method_view_nested(request):
return await Klass().async_method_nested(request)
@sensitive_variables("sauce")
@sensitive_post_parameters("bacon-key", "sausage-key")
def multivalue_dict_key_error(request):
cooked_eggs = "".join(["s", "c", "r", "a", "m", "b", "l", "e", "d"]) # NOQA
sauce = "".join( # NOQA
["w", "o", "r", "c", "e", "s", "t", "e", "r", "s", "h", "i", "r", "e"]
)
try:
request.POST["bar"]
except Exception:
exc_info = sys.exc_info()
send_log(request, exc_info)
return technical_500_response(request, *exc_info)
def json_response_view(request):
return JsonResponse(
{
"a": [1, 2, 3],
"foo": {"bar": "baz"},
# Make sure datetime and Decimal objects would be serialized
# properly
"timestamp": datetime.datetime(2013, 5, 19, 20),
"value": decimal.Decimal("3.14"),
}
)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/view_tests/generic_urls.py | tests/view_tests/generic_urls.py | from django.contrib.auth import views as auth_views
from django.urls import path
from django.views.generic import RedirectView
from . import views
from .models import Article, DateArticle
date_based_info_dict = {
"queryset": Article.objects.all(),
"date_field": "date_created",
"month_format": "%m",
}
object_list_dict = {
"queryset": Article.objects.all(),
"paginate_by": 2,
}
object_list_no_paginate_by = {
"queryset": Article.objects.all(),
}
numeric_days_info_dict = dict(date_based_info_dict, day_format="%d")
date_based_datefield_info_dict = dict(
date_based_info_dict, queryset=DateArticle.objects.all()
)
urlpatterns = [
path("accounts/login/", auth_views.LoginView.as_view(template_name="login.html")),
path("accounts/logout/", auth_views.LogoutView.as_view()),
# Special URLs for particular regression cases.
path("中文/target/", views.index_page),
]
# redirects, both temporary and permanent, with non-ASCII targets
urlpatterns += [
path(
"nonascii_redirect/", RedirectView.as_view(url="/中文/target/", permanent=False)
),
path(
"permanent_nonascii_redirect/",
RedirectView.as_view(url="/中文/target/", permanent=True),
),
]
# json response
urlpatterns += [
path("json/response/", views.json_response_view),
]
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/view_tests/models.py | tests/view_tests/models.py | """
Regression tests for Django built-in views.
"""
from django.db import models
class Author(models.Model):
name = models.CharField(max_length=100)
def get_absolute_url(self):
return "/authors/%s/" % self.id
class BaseArticle(models.Model):
"""
An abstract article Model so that we can create article models with and
without a get_absolute_url method (for create_update generic views tests).
"""
title = models.CharField(max_length=100)
slug = models.SlugField()
author = models.ForeignKey(Author, models.CASCADE)
class Meta:
abstract = True
class Article(BaseArticle):
date_created = models.DateTimeField()
class UrlArticle(BaseArticle):
"""
An Article class with a get_absolute_url defined.
"""
date_created = models.DateTimeField()
def get_absolute_url(self):
return "/urlarticles/%s/" % self.slug
get_absolute_url.purge = True
class DateArticle(BaseArticle):
"""
An article Model with a DateField instead of DateTimeField,
for testing #7602
"""
date_created = models.DateField()
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/view_tests/default_urls.py | tests/view_tests/default_urls.py | from django.contrib import admin
from django.urls import path
urlpatterns = [
# This is the same as in the default project template
path("admin/", 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/view_tests/__init__.py | tests/view_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/view_tests/regression_21530_urls.py | tests/view_tests/regression_21530_urls.py | from django.urls import path
from . import views
urlpatterns = [
path("index/", views.index_page, name="index"),
]
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/view_tests/urls.py | tests/view_tests/urls.py | import os
from functools import partial
from django.conf.urls.i18n import i18n_patterns
from django.urls import include, path, re_path
from django.utils.translation import gettext_lazy as _
from django.views import defaults, i18n, static
from . import views
base_dir = os.path.dirname(os.path.abspath(__file__))
media_dir = os.path.join(base_dir, "media")
locale_dir = os.path.join(base_dir, "locale")
urlpatterns = [
path("", views.index_page),
# Default views
path("nonexistent_url/", partial(defaults.page_not_found, exception=None)),
path("server_error/", defaults.server_error),
# a view that raises an exception for the debug view
path("raises/", views.raises),
path("raises400/", views.raises400),
path("raises400_bad_request/", views.raises400_bad_request),
path("raises403/", views.raises403),
path("raises404/", views.raises404),
path("raises500/", views.raises500),
path("custom_reporter_class_view/", views.custom_reporter_class_view),
path("technical404/", views.technical404, name="my404"),
path("classbased404/", views.Http404View.as_view()),
path("classbased500/", views.Raises500View.as_view()),
# i18n views
path("i18n/", include("django.conf.urls.i18n")),
path("jsi18n/", i18n.JavaScriptCatalog.as_view(packages=["view_tests"])),
path("jsi18n_no_packages/", i18n.JavaScriptCatalog.as_view()),
path("jsi18n/app1/", i18n.JavaScriptCatalog.as_view(packages=["view_tests.app1"])),
path("jsi18n/app2/", i18n.JavaScriptCatalog.as_view(packages=["view_tests.app2"])),
path("jsi18n/app5/", i18n.JavaScriptCatalog.as_view(packages=["view_tests.app5"])),
path(
"jsi18n_english_translation/",
i18n.JavaScriptCatalog.as_view(packages=["view_tests.app0"]),
),
path(
"jsi18n_multi_packages1/",
i18n.JavaScriptCatalog.as_view(packages=["view_tests.app1", "view_tests.app2"]),
),
path(
"jsi18n_multi_packages2/",
i18n.JavaScriptCatalog.as_view(packages=["view_tests.app3", "view_tests.app4"]),
),
path(
"jsi18n_admin/",
i18n.JavaScriptCatalog.as_view(packages=["django.contrib.admin", "view_tests"]),
),
path("jsi18n_template/", views.jsi18n),
path("jsi18n_multi_catalogs/", views.jsi18n_multi_catalogs),
path("jsoni18n/", i18n.JSONCatalog.as_view(packages=["view_tests"])),
# Static views
re_path(
r"^site_media/(?P<path>.*)$",
static.serve,
{"document_root": media_dir, "show_indexes": True},
),
]
urlpatterns += i18n_patterns(
re_path(_(r"^translated/$"), views.index_page, name="i18n_prefixed"),
)
urlpatterns += [
path(
"safestring_exception/",
views.safestring_in_template_exception,
name="safestring_exception",
),
path("template_exception/", views.template_exception, name="template_exception"),
path(
"raises_template_does_not_exist/<path:path>",
views.raises_template_does_not_exist,
name="raises_template_does_not_exist",
),
path("render_no_template/", views.render_no_template, name="render_no_template"),
re_path(
r"^test-setlang/(?P<parameter>[^/]+)/$",
views.with_parameter,
name="with_parameter",
),
# Patterns to test the technical 404.
re_path(r"^regex-post/(?P<pk>[0-9]+)/$", views.index_page, name="regex-post"),
path("path-post/<int:pk>/", views.index_page, name="path-post"),
]
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/view_tests/app3/__init__.py | tests/view_tests/app3/__init__.py | python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false | |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/view_tests/templatetags/__init__.py | tests/view_tests/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/view_tests/templatetags/debugtags.py | tests/view_tests/templatetags/debugtags.py | from django import template
register = template.Library()
@register.simple_tag
def go_boom():
raise Exception("boom")
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/view_tests/tests/test_i18n.py | tests/view_tests/tests/test_i18n.py | import gettext
import json
from os import path
from unittest import mock
from django.conf import settings
from django.test import (
RequestFactory,
SimpleTestCase,
TestCase,
modify_settings,
override_settings,
)
from django.test.selenium import SeleniumTestCase
from django.urls import reverse
from django.utils.translation import get_language, override
from django.views.i18n import JavaScriptCatalog, get_formats
from ..urls import locale_dir
@override_settings(ROOT_URLCONF="view_tests.urls")
class SetLanguageTests(TestCase):
"""Test the django.views.i18n.set_language view."""
def _get_inactive_language_code(self):
"""Return language code for a language which is not activated."""
current_language = get_language()
return [code for code, name in settings.LANGUAGES if code != current_language][
0
]
def test_setlang(self):
"""
The set_language view can be used to change the session language.
The user is redirected to the 'next' argument if provided.
"""
lang_code = self._get_inactive_language_code()
post_data = {"language": lang_code, "next": "/"}
response = self.client.post(
"/i18n/setlang/", post_data, headers={"referer": "/i_should_not_be_used/"}
)
self.assertRedirects(response, "/")
# The language is set in a cookie.
language_cookie = self.client.cookies[settings.LANGUAGE_COOKIE_NAME]
self.assertEqual(language_cookie.value, lang_code)
self.assertEqual(language_cookie["domain"], "")
self.assertEqual(language_cookie["path"], "/")
self.assertEqual(language_cookie["max-age"], "")
self.assertEqual(language_cookie["httponly"], "")
self.assertEqual(language_cookie["samesite"], "")
self.assertEqual(language_cookie["secure"], "")
def test_setlang_unsafe_next(self):
"""
The set_language view only redirects to the 'next' argument if it is
"safe".
"""
lang_code = self._get_inactive_language_code()
post_data = {"language": lang_code, "next": "//unsafe/redirection/"}
response = self.client.post("/i18n/setlang/", data=post_data)
self.assertEqual(response.url, "/")
self.assertEqual(
self.client.cookies[settings.LANGUAGE_COOKIE_NAME].value, lang_code
)
def test_setlang_http_next(self):
"""
The set_language view only redirects to the 'next' argument if it is
"safe" and its scheme is HTTPS if the request was sent over HTTPS.
"""
lang_code = self._get_inactive_language_code()
non_https_next_url = "http://testserver/redirection/"
post_data = {"language": lang_code, "next": non_https_next_url}
# Insecure URL in POST data.
response = self.client.post("/i18n/setlang/", data=post_data, secure=True)
self.assertEqual(response.url, "/")
self.assertEqual(
self.client.cookies[settings.LANGUAGE_COOKIE_NAME].value, lang_code
)
# Insecure URL in HTTP referer.
response = self.client.post(
"/i18n/setlang/", secure=True, headers={"referer": non_https_next_url}
)
self.assertEqual(response.url, "/")
self.assertEqual(
self.client.cookies[settings.LANGUAGE_COOKIE_NAME].value, lang_code
)
def test_setlang_redirect_to_referer(self):
"""
The set_language view redirects to the URL in the referer header when
there isn't a "next" parameter.
"""
lang_code = self._get_inactive_language_code()
post_data = {"language": lang_code}
response = self.client.post(
"/i18n/setlang/", post_data, headers={"referer": "/i18n/"}
)
self.assertRedirects(response, "/i18n/", fetch_redirect_response=False)
self.assertEqual(
self.client.cookies[settings.LANGUAGE_COOKIE_NAME].value, lang_code
)
def test_setlang_default_redirect(self):
"""
The set_language view redirects to '/' when there isn't a referer or
"next" parameter.
"""
lang_code = self._get_inactive_language_code()
post_data = {"language": lang_code}
response = self.client.post("/i18n/setlang/", post_data)
self.assertRedirects(response, "/")
self.assertEqual(
self.client.cookies[settings.LANGUAGE_COOKIE_NAME].value, lang_code
)
def test_setlang_performs_redirect_for_ajax_if_explicitly_requested(self):
"""
The set_language view redirects to the "next" parameter for requests
not accepting HTML response content.
"""
lang_code = self._get_inactive_language_code()
post_data = {"language": lang_code, "next": "/"}
response = self.client.post(
"/i18n/setlang/", post_data, headers={"accept": "application/json"}
)
self.assertRedirects(response, "/")
self.assertEqual(
self.client.cookies[settings.LANGUAGE_COOKIE_NAME].value, lang_code
)
def test_setlang_doesnt_perform_a_redirect_to_referer_for_ajax(self):
"""
The set_language view doesn't redirect to the HTTP referer header if
the request doesn't accept HTML response content.
"""
lang_code = self._get_inactive_language_code()
post_data = {"language": lang_code}
headers = {"HTTP_REFERER": "/", "HTTP_ACCEPT": "application/json"}
response = self.client.post("/i18n/setlang/", post_data, **headers)
self.assertEqual(response.status_code, 204)
self.assertEqual(
self.client.cookies[settings.LANGUAGE_COOKIE_NAME].value, lang_code
)
def test_setlang_doesnt_perform_a_default_redirect_for_ajax(self):
"""
The set_language view returns 204 by default for requests not accepting
HTML response content.
"""
lang_code = self._get_inactive_language_code()
post_data = {"language": lang_code}
response = self.client.post(
"/i18n/setlang/", post_data, headers={"accept": "application/json"}
)
self.assertEqual(response.status_code, 204)
self.assertEqual(
self.client.cookies[settings.LANGUAGE_COOKIE_NAME].value, lang_code
)
def test_setlang_unsafe_next_for_ajax(self):
"""
The fallback to root URL for the set_language view works for requests
not accepting HTML response content.
"""
lang_code = self._get_inactive_language_code()
post_data = {"language": lang_code, "next": "//unsafe/redirection/"}
response = self.client.post(
"/i18n/setlang/", post_data, headers={"accept": "application/json"}
)
self.assertEqual(response.url, "/")
self.assertEqual(
self.client.cookies[settings.LANGUAGE_COOKIE_NAME].value, lang_code
)
def test_setlang_reversal(self):
self.assertEqual(reverse("set_language"), "/i18n/setlang/")
def test_setlang_cookie(self):
# we force saving language to a cookie rather than a session
# by excluding session middleware and those which do require it
test_settings = {
"MIDDLEWARE": ["django.middleware.common.CommonMiddleware"],
"LANGUAGE_COOKIE_NAME": "mylanguage",
"LANGUAGE_COOKIE_AGE": 3600 * 7 * 2,
"LANGUAGE_COOKIE_DOMAIN": ".example.com",
"LANGUAGE_COOKIE_PATH": "/test/",
"LANGUAGE_COOKIE_HTTPONLY": True,
"LANGUAGE_COOKIE_SAMESITE": "Strict",
"LANGUAGE_COOKIE_SECURE": True,
}
with self.settings(**test_settings):
post_data = {"language": "pl", "next": "/views/"}
response = self.client.post("/i18n/setlang/", data=post_data)
language_cookie = response.cookies.get("mylanguage")
self.assertEqual(language_cookie.value, "pl")
self.assertEqual(language_cookie["domain"], ".example.com")
self.assertEqual(language_cookie["path"], "/test/")
self.assertEqual(language_cookie["max-age"], 3600 * 7 * 2)
self.assertIs(language_cookie["httponly"], True)
self.assertEqual(language_cookie["samesite"], "Strict")
self.assertIs(language_cookie["secure"], True)
def test_setlang_decodes_http_referer_url(self):
"""
The set_language view decodes the HTTP_REFERER URL and preserves an
encoded query string.
"""
# The URL & view must exist for this to work as a regression test.
self.assertEqual(
reverse("with_parameter", kwargs={"parameter": "x"}), "/test-setlang/x/"
)
lang_code = self._get_inactive_language_code()
# %C3%A4 decodes to ä, %26 to &.
encoded_url = "/test-setlang/%C3%A4/?foo=bar&baz=alpha%26omega"
response = self.client.post(
"/i18n/setlang/", {"language": lang_code}, headers={"referer": encoded_url}
)
self.assertRedirects(response, encoded_url, fetch_redirect_response=False)
self.assertEqual(
self.client.cookies[settings.LANGUAGE_COOKIE_NAME].value, lang_code
)
@modify_settings(
MIDDLEWARE={
"append": "django.middleware.locale.LocaleMiddleware",
}
)
def test_lang_from_translated_i18n_pattern(self):
response = self.client.post(
"/i18n/setlang/",
data={"language": "nl"},
follow=True,
headers={"referer": "/en/translated/"},
)
self.assertEqual(self.client.cookies[settings.LANGUAGE_COOKIE_NAME].value, "nl")
self.assertRedirects(response, "/nl/vertaald/")
# And reverse
response = self.client.post(
"/i18n/setlang/",
data={"language": "en"},
follow=True,
headers={"referer": "/nl/vertaald/"},
)
self.assertRedirects(response, "/en/translated/")
@override_settings(ROOT_URLCONF="view_tests.urls")
class I18NViewTests(SimpleTestCase):
"""Test django.views.i18n views other than set_language."""
@override_settings(LANGUAGE_CODE="de")
def test_get_formats(self):
formats = get_formats()
# Test 3 possible types in get_formats: integer, string, and list.
self.assertEqual(formats["FIRST_DAY_OF_WEEK"], 1)
self.assertEqual(formats["DECIMAL_SEPARATOR"], ",")
self.assertEqual(
formats["TIME_INPUT_FORMATS"], ["%H:%M:%S", "%H:%M:%S.%f", "%H:%M"]
)
def test_jsi18n(self):
"""The javascript_catalog can be deployed with language settings"""
for lang_code in ["es", "fr", "ru"]:
with override(lang_code):
catalog = gettext.translation("djangojs", locale_dir, [lang_code])
trans_txt = catalog.gettext("this is to be translated")
response = self.client.get("/jsi18n/")
self.assertEqual(
response.headers["Content-Type"], 'text/javascript; charset="utf-8"'
)
# response content must include a line like:
# "this is to be translated": <value of trans_txt Python
# variable> json.dumps() is used to be able to check Unicode
# strings.
self.assertContains(response, json.dumps(trans_txt), 1)
if lang_code == "fr":
# Message with context (msgctxt)
self.assertContains(response, '"month name\\u0004May": "mai"', 1)
@override_settings(USE_I18N=False)
def test_jsi18n_USE_I18N_False(self):
response = self.client.get("/jsi18n/")
# default plural function
self.assertContains(
response,
"django.pluralidx = function(count) { return (count == 1) ? 0 : 1; };",
)
self.assertNotContains(response, "var newcatalog =")
def test_jsoni18n(self):
"""
The json_catalog returns the language catalog and settings as JSON.
"""
with override("de"):
response = self.client.get("/jsoni18n/")
data = json.loads(response.text)
self.assertIn("catalog", data)
self.assertIn("formats", data)
self.assertEqual(
data["formats"]["TIME_INPUT_FORMATS"],
["%H:%M:%S", "%H:%M:%S.%f", "%H:%M"],
)
self.assertEqual(data["formats"]["FIRST_DAY_OF_WEEK"], 1)
self.assertIn("plural", data)
self.assertEqual(data["catalog"]["month name\x04May"], "Mai")
self.assertIn("DATETIME_FORMAT", data["formats"])
self.assertEqual(data["plural"], "(n != 1)")
def test_jsi18n_with_missing_en_files(self):
"""
The javascript_catalog shouldn't load the fallback language in the
case that the current selected language is actually the one translated
from, and hence missing translation files completely.
This happens easily when you're translating from English to other
languages and you've set settings.LANGUAGE_CODE to some other language
than English.
"""
with self.settings(LANGUAGE_CODE="es"), override("en-us"):
response = self.client.get("/jsi18n/")
self.assertNotContains(response, "esto tiene que ser traducido")
def test_jsoni18n_with_missing_en_files(self):
"""
Same as above for the json_catalog view. Here we also check for the
expected JSON format.
"""
with self.settings(LANGUAGE_CODE="es"), override("en-us"):
response = self.client.get("/jsoni18n/")
data = json.loads(response.text)
self.assertIn("catalog", data)
self.assertIn("formats", data)
self.assertIn("plural", data)
self.assertEqual(data["catalog"], {})
self.assertIn("DATETIME_FORMAT", data["formats"])
self.assertIsNone(data["plural"])
def test_jsi18n_fallback_language(self):
"""
Let's make sure that the fallback language is still working properly
in cases where the selected language cannot be found.
"""
with self.settings(LANGUAGE_CODE="fr"), override("fi"):
response = self.client.get("/jsi18n/")
self.assertContains(response, "il faut le traduire")
self.assertNotContains(response, "Untranslated string")
def test_jsi18n_fallback_language_with_custom_locale_dir(self):
"""
The fallback language works when there are several levels of fallback
translation catalogs.
"""
locale_paths = [
path.join(
path.dirname(path.dirname(path.abspath(__file__))),
"custom_locale_path",
),
]
with self.settings(LOCALE_PATHS=locale_paths), override("es_MX"):
response = self.client.get("/jsi18n/")
self.assertContains(
response, "custom_locale_path: esto tiene que ser traducido"
)
response = self.client.get("/jsi18n_no_packages/")
self.assertContains(
response, "custom_locale_path: esto tiene que ser traducido"
)
def test_i18n_fallback_language_plural(self):
"""
The fallback to a language with less plural forms maintains the real
language's number of plural forms and correct translations.
"""
with self.settings(LANGUAGE_CODE="pt"), override("ru"):
response = self.client.get("/jsi18n/")
self.assertEqual(
response.context["catalog"]["{count} plural3"],
["{count} plural3 p3", "{count} plural3 p3s", "{count} plural3 p3t"],
)
self.assertEqual(
response.context["catalog"]["{count} plural2"],
["{count} plural2", "{count} plural2s", ""],
)
with self.settings(LANGUAGE_CODE="ru"), override("pt"):
response = self.client.get("/jsi18n/")
self.assertEqual(
response.context["catalog"]["{count} plural3"],
["{count} plural3", "{count} plural3s"],
)
self.assertEqual(
response.context["catalog"]["{count} plural2"],
["{count} plural2", "{count} plural2s"],
)
def test_i18n_english_variant(self):
with override("en-gb"):
response = self.client.get("/jsi18n/")
self.assertIn(
'"this color is to be translated": "this colour is to be translated"',
response.context["catalog_str"],
)
def test_i18n_language_non_english_default(self):
"""
Check if the JavaScript i18n view returns an empty language catalog
if the default language is non-English, the selected language
is English and there is not 'en' translation available. See #13388,
#3594 and #13726 for more details.
"""
with self.settings(LANGUAGE_CODE="fr"), override("en-us"):
response = self.client.get("/jsi18n/")
self.assertNotContains(response, "Choisir une heure")
@modify_settings(INSTALLED_APPS={"append": "view_tests.app0"})
def test_non_english_default_english_userpref(self):
"""
Same as above with the difference that there IS an 'en' translation
available. The JavaScript i18n view must return a NON empty language
catalog with the proper English translations. See #13726 for more
details.
"""
with self.settings(LANGUAGE_CODE="fr"), override("en-us"):
response = self.client.get("/jsi18n_english_translation/")
self.assertContains(response, "this app0 string is to be translated")
def test_i18n_language_non_english_fallback(self):
"""
Makes sure that the fallback language is still working properly
in cases where the selected language cannot be found.
"""
with self.settings(LANGUAGE_CODE="fr"), override("none"):
response = self.client.get("/jsi18n/")
self.assertContains(response, "Choisir une heure")
def test_escaping(self):
# Force a language via GET otherwise the gettext functions are a noop!
response = self.client.get("/jsi18n_admin/?language=de")
self.assertContains(response, "\\x04")
@modify_settings(INSTALLED_APPS={"append": ["view_tests.app5"]})
def test_non_BMP_char(self):
"""
Non-BMP characters should not break the javascript_catalog (#21725).
"""
with self.settings(LANGUAGE_CODE="en-us"), override("fr"):
response = self.client.get("/jsi18n/app5/")
self.assertContains(response, "emoji")
self.assertContains(response, "\\ud83d\\udca9")
@modify_settings(INSTALLED_APPS={"append": ["view_tests.app1", "view_tests.app2"]})
def test_i18n_language_english_default(self):
"""
Check if the JavaScript i18n view returns a complete language catalog
if the default language is en-us, the selected language has a
translation available and a catalog composed by djangojs domain
translations of multiple Python packages is requested. See #13388,
#3594 and #13514 for more details.
"""
base_trans_string = (
"il faut traduire cette cha\\u00eene de caract\\u00e8res de "
)
app1_trans_string = base_trans_string + "app1"
app2_trans_string = base_trans_string + "app2"
with self.settings(LANGUAGE_CODE="en-us"), override("fr"):
response = self.client.get("/jsi18n_multi_packages1/")
self.assertContains(response, app1_trans_string)
self.assertContains(response, app2_trans_string)
response = self.client.get("/jsi18n/app1/")
self.assertContains(response, app1_trans_string)
self.assertNotContains(response, app2_trans_string)
response = self.client.get("/jsi18n/app2/")
self.assertNotContains(response, app1_trans_string)
self.assertContains(response, app2_trans_string)
@modify_settings(INSTALLED_APPS={"append": ["view_tests.app3", "view_tests.app4"]})
def test_i18n_different_non_english_languages(self):
"""
Similar to above but with neither default or requested language being
English.
"""
with self.settings(LANGUAGE_CODE="fr"), override("es-ar"):
response = self.client.get("/jsi18n_multi_packages2/")
self.assertContains(response, "este texto de app3 debe ser traducido")
def test_i18n_with_locale_paths(self):
extended_locale_paths = settings.LOCALE_PATHS + [
path.join(
path.dirname(path.dirname(path.abspath(__file__))),
"app3",
"locale",
),
]
with self.settings(LANGUAGE_CODE="es-ar", LOCALE_PATHS=extended_locale_paths):
with override("es-ar"):
response = self.client.get("/jsi18n/")
self.assertContains(response, "este texto de app3 debe ser traducido")
def test_i18n_unknown_package_error(self):
view = JavaScriptCatalog.as_view()
request = RequestFactory().get("/")
msg = "Invalid package(s) provided to JavaScriptCatalog: unknown_package"
with self.assertRaisesMessage(ValueError, msg):
view(request, packages="unknown_package")
msg += ",unknown_package2"
with self.assertRaisesMessage(ValueError, msg):
view(request, packages="unknown_package+unknown_package2")
def test_template_encoding(self):
"""
The template is loaded directly, not via a template loader, and should
be opened as utf-8 charset as is the default specified on template
engines.
"""
from django.views.i18n import Path
view = JavaScriptCatalog.as_view()
request = RequestFactory().get("/")
with mock.patch.object(Path, "open") as m:
view(request)
m.assert_called_once_with(encoding="utf-8")
@override_settings(ROOT_URLCONF="view_tests.urls")
class I18nSeleniumTests(SeleniumTestCase):
# The test cases use fixtures & translations from these apps.
available_apps = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"view_tests",
]
@override_settings(LANGUAGE_CODE="de")
def test_javascript_gettext(self):
from selenium.webdriver.common.by import By
self.selenium.get(self.live_server_url + "/jsi18n_template/")
elem = self.selenium.find_element(By.ID, "gettext")
self.assertEqual(elem.text, "Entfernen")
elem = self.selenium.find_element(By.ID, "ngettext_sing")
self.assertEqual(elem.text, "1 Element")
elem = self.selenium.find_element(By.ID, "ngettext_plur")
self.assertEqual(elem.text, "455 Elemente")
elem = self.selenium.find_element(By.ID, "ngettext_onnonplural")
self.assertEqual(elem.text, "Bild")
elem = self.selenium.find_element(By.ID, "pgettext")
self.assertEqual(elem.text, "Kann")
elem = self.selenium.find_element(By.ID, "npgettext_sing")
self.assertEqual(elem.text, "1 Resultat")
elem = self.selenium.find_element(By.ID, "npgettext_plur")
self.assertEqual(elem.text, "455 Resultate")
elem = self.selenium.find_element(By.ID, "formats")
self.assertEqual(
elem.text,
"DATE_INPUT_FORMATS is an object; DECIMAL_SEPARATOR is a string; "
"FIRST_DAY_OF_WEEK is a number;",
)
@modify_settings(INSTALLED_APPS={"append": ["view_tests.app1", "view_tests.app2"]})
@override_settings(LANGUAGE_CODE="fr")
def test_multiple_catalogs(self):
from selenium.webdriver.common.by import By
self.selenium.get(self.live_server_url + "/jsi18n_multi_catalogs/")
elem = self.selenium.find_element(By.ID, "app1string")
self.assertEqual(
elem.text, "il faut traduire cette chaîne de caractères de app1"
)
elem = self.selenium.find_element(By.ID, "app2string")
self.assertEqual(
elem.text, "il faut traduire cette chaîne de caractères de app2"
)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/view_tests/tests/test_specials.py | tests/view_tests/tests/test_specials.py | from django.test import SimpleTestCase, override_settings
@override_settings(ROOT_URLCONF="view_tests.generic_urls")
class URLHandling(SimpleTestCase):
"""
Tests for URL handling in views and responses.
"""
redirect_target = "/%E4%B8%AD%E6%96%87/target/"
def test_nonascii_redirect(self):
"""
A non-ASCII argument to HttpRedirect is handled properly.
"""
response = self.client.get("/nonascii_redirect/")
self.assertRedirects(response, self.redirect_target)
def test_permanent_nonascii_redirect(self):
"""
A non-ASCII argument to HttpPermanentRedirect is handled properly.
"""
response = self.client.get("/permanent_nonascii_redirect/")
self.assertRedirects(response, self.redirect_target, status_code=301)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/view_tests/tests/test_json.py | tests/view_tests/tests/test_json.py | import json
from django.test import SimpleTestCase, override_settings
@override_settings(ROOT_URLCONF="view_tests.generic_urls")
class JsonResponseTests(SimpleTestCase):
def test_json_response(self):
response = self.client.get("/json/response/")
self.assertEqual(response.status_code, 200)
self.assertEqual(response.headers["content-type"], "application/json")
self.assertEqual(
json.loads(response.text),
{
"a": [1, 2, 3],
"foo": {"bar": "baz"},
"timestamp": "2013-05-19T20:00:00",
"value": "3.14",
},
)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/view_tests/tests/test_defaults.py | tests/view_tests/tests/test_defaults.py | import datetime
from django.contrib.sites.models import Site
from django.http import Http404
from django.template import TemplateDoesNotExist
from django.test import RequestFactory, TestCase
from django.test.utils import override_settings
from django.views.defaults import (
bad_request,
page_not_found,
permission_denied,
server_error,
)
from ..models import Article, Author, UrlArticle
@override_settings(ROOT_URLCONF="view_tests.urls")
class DefaultsTests(TestCase):
"""Test django views in django/views/defaults.py"""
nonexistent_urls = [
"/nonexistent_url/", # this is in urls.py
"/other_nonexistent_url/", # this NOT in urls.py
]
request_factory = RequestFactory()
@classmethod
def setUpTestData(cls):
author = Author.objects.create(name="Boris")
Article.objects.create(
title="Old Article",
slug="old_article",
author=author,
date_created=datetime.datetime(2001, 1, 1, 21, 22, 23),
)
Article.objects.create(
title="Current Article",
slug="current_article",
author=author,
date_created=datetime.datetime(2007, 9, 17, 21, 22, 23),
)
Article.objects.create(
title="Future Article",
slug="future_article",
author=author,
date_created=datetime.datetime(3000, 1, 1, 21, 22, 23),
)
cls.urlarticle = UrlArticle.objects.create(
title="Old Article",
slug="old_article",
author=author,
date_created=datetime.datetime(2001, 1, 1, 21, 22, 23),
)
Site(id=1, domain="testserver", name="testserver").save()
def test_page_not_found(self):
"A 404 status is returned by the page_not_found view"
for url in self.nonexistent_urls:
response = self.client.get(url)
self.assertEqual(response.status_code, 404)
self.assertIn(b"<h1>Not Found</h1>", response.content)
self.assertIn(
b"<p>The requested resource was not found on this server.</p>",
response.content,
)
@override_settings(
TEMPLATES=[
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"OPTIONS": {
"loaders": [
(
"django.template.loaders.locmem.Loader",
{
"404.html": "{{ csrf_token }}",
},
),
],
},
}
]
)
def test_csrf_token_in_404(self):
"""
The 404 page should have the csrf_token available in the context
"""
# See ticket #14565
for url in self.nonexistent_urls:
response = self.client.get(url)
self.assertNotEqual(response.content, b"NOTPROVIDED")
self.assertNotEqual(response.content, b"")
def test_server_error(self):
"The server_error view raises a 500 status"
response = self.client.get("/server_error/")
self.assertContains(response, b"<h1>Server Error (500)</h1>", status_code=500)
def test_bad_request(self):
request = self.request_factory.get("/")
response = bad_request(request, Exception())
self.assertContains(response, b"<h1>Bad Request (400)</h1>", status_code=400)
@override_settings(
TEMPLATES=[
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"OPTIONS": {
"loaders": [
(
"django.template.loaders.locmem.Loader",
{
"400.html": (
"This is a test template for a 400 error "
),
},
),
],
},
}
]
)
def test_custom_bad_request_template(self):
response = self.client.get("/raises400/")
self.assertIs(response.wsgi_request, response.context.request)
@override_settings(
TEMPLATES=[
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"OPTIONS": {
"loaders": [
(
"django.template.loaders.locmem.Loader",
{
"404.html": (
"This is a test template for a 404 error "
"(path: {{ request_path }}, "
"exception: {{ exception }})."
),
"500.html": "This is a test template for a 500 error.",
},
),
],
},
}
]
)
def test_custom_templates(self):
"""
404.html and 500.html templates are picked by their respective handler.
"""
response = self.client.get("/server_error/")
self.assertContains(response, "test template for a 500 error", status_code=500)
response = self.client.get("/no_such_url/")
self.assertContains(response, "path: /no_such_url/", status_code=404)
self.assertContains(response, "exception: Resolver404", status_code=404)
response = self.client.get("/technical404/")
self.assertContains(
response, "exception: Testing technical 404.", status_code=404
)
def test_get_absolute_url_attributes(self):
"A model can set attributes on the get_absolute_url method"
self.assertTrue(
getattr(UrlArticle.get_absolute_url, "purge", False),
"The attributes of the original get_absolute_url must be added.",
)
article = UrlArticle.objects.get(pk=self.urlarticle.pk)
self.assertTrue(
getattr(article.get_absolute_url, "purge", False),
"The attributes of the original get_absolute_url must be added.",
)
def test_custom_templates_wrong(self):
"""
Default error views should raise TemplateDoesNotExist when passed a
template that doesn't exist.
"""
request = self.request_factory.get("/")
with self.assertRaises(TemplateDoesNotExist):
bad_request(request, Exception(), template_name="nonexistent")
with self.assertRaises(TemplateDoesNotExist):
permission_denied(request, Exception(), template_name="nonexistent")
with self.assertRaises(TemplateDoesNotExist):
page_not_found(request, Http404(), template_name="nonexistent")
with self.assertRaises(TemplateDoesNotExist):
server_error(request, template_name="nonexistent")
def test_error_pages(self):
request = self.request_factory.get("/")
for response, title in (
(bad_request(request, Exception()), b"Bad Request (400)"),
(permission_denied(request, Exception()), b"403 Forbidden"),
(page_not_found(request, Http404()), b"Not Found"),
(server_error(request), b"Server Error (500)"),
):
with self.subTest(title=title):
self.assertIn(b"<!doctype html>", response.content)
self.assertIn(b'<html lang="en">', response.content)
self.assertIn(b"<head>", response.content)
self.assertIn(b"<title>%s</title>" % title, response.content)
self.assertIn(b"<body>", response.content)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/view_tests/tests/test_csrf.py | tests/view_tests/tests/test_csrf.py | from unittest import mock
from django.template import TemplateDoesNotExist
from django.test import Client, RequestFactory, SimpleTestCase, override_settings
from django.utils.translation import override
from django.views.csrf import CSRF_FAILURE_TEMPLATE_NAME, csrf_failure
@override_settings(ROOT_URLCONF="view_tests.urls")
class CsrfViewTests(SimpleTestCase):
def setUp(self):
super().setUp()
self.client = Client(enforce_csrf_checks=True)
@override_settings(
USE_I18N=True,
MIDDLEWARE=[
"django.middleware.locale.LocaleMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
],
)
def test_translation(self):
"""An invalid request is rejected with a localized error message."""
response = self.client.post("/")
self.assertContains(response, "Forbidden", status_code=403)
self.assertContains(
response, "CSRF verification failed. Request aborted.", status_code=403
)
with self.settings(LANGUAGE_CODE="nl"), override("en-us"):
response = self.client.post("/")
self.assertContains(response, "Verboden", status_code=403)
self.assertContains(
response,
"CSRF-verificatie mislukt. Verzoek afgebroken.",
status_code=403,
)
@override_settings(SECURE_PROXY_SSL_HEADER=("HTTP_X_FORWARDED_PROTO", "https"))
def test_no_referer(self):
"""
Referer header is strictly checked for POST over HTTPS. Trigger the
exception by sending an incorrect referer.
"""
response = self.client.post("/", headers={"x-forwarded-proto": "https"})
self.assertContains(
response,
"You are seeing this message because this HTTPS site requires a "
"“Referer header” to be sent by your web browser, but "
"none was sent.",
status_code=403,
)
self.assertContains(
response,
"If you have configured your browser to disable “Referer” "
"headers, please re-enable them, at least for this site, or for "
"HTTPS connections, or for “same-origin” requests.",
status_code=403,
)
self.assertContains(
response,
"If you are using the <meta name="referrer" "
"content="no-referrer"> tag or including the "
"“Referrer-Policy: no-referrer” header, please remove them.",
status_code=403,
)
def test_no_cookies(self):
"""
The CSRF cookie is checked for POST. Failure to send this cookie should
provide a nice error message.
"""
response = self.client.post("/")
self.assertContains(
response,
"You are seeing this message because this site requires a CSRF "
"cookie when submitting forms. This cookie is required for "
"security reasons, to ensure that your browser is not being "
"hijacked by third parties.",
status_code=403,
)
@override_settings(TEMPLATES=[])
def test_no_django_template_engine(self):
"""
The CSRF view doesn't depend on the TEMPLATES configuration (#24388).
"""
response = self.client.post("/")
self.assertContains(response, "Forbidden", status_code=403)
@override_settings(
TEMPLATES=[
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"OPTIONS": {
"loaders": [
(
"django.template.loaders.locmem.Loader",
{
CSRF_FAILURE_TEMPLATE_NAME: (
"Test template for CSRF failure"
)
},
),
],
},
}
]
)
def test_custom_template(self):
"""A custom CSRF_FAILURE_TEMPLATE_NAME is used."""
response = self.client.post("/")
self.assertContains(response, "Test template for CSRF failure", status_code=403)
self.assertIs(response.wsgi_request, response.context.request)
def test_custom_template_does_not_exist(self):
"""An exception is raised if a nonexistent template is supplied."""
factory = RequestFactory()
request = factory.post("/")
with self.assertRaises(TemplateDoesNotExist):
csrf_failure(request, template_name="nonexistent.html")
def test_template_encoding(self):
"""
The template is loaded directly, not via a template loader, and should
be opened as utf-8 charset as is the default specified on template
engines.
"""
from django.views.csrf import Path
with mock.patch.object(Path, "open") as m:
csrf_failure(mock.MagicMock(), mock.Mock())
m.assert_called_once_with(encoding="utf-8")
@override_settings(DEBUG=True)
@mock.patch("django.views.csrf.get_docs_version", return_value="4.2")
def test_doc_links(self, mocked_get_complete_version):
response = self.client.post("/")
self.assertContains(response, "Forbidden", status_code=403)
self.assertNotContains(
response, "https://docs.djangoproject.com/en/dev/", status_code=403
)
self.assertContains(
response, "https://docs.djangoproject.com/en/4.2/", status_code=403
)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/view_tests/tests/test_static.py | tests/view_tests/tests/test_static.py | import mimetypes
import unittest
from os import path
from unittest import mock
from urllib.parse import quote
from django.conf.urls.static import static
from django.core.exceptions import ImproperlyConfigured
from django.http import FileResponse, HttpResponseNotModified
from django.test import SimpleTestCase, override_settings
from django.utils.http import http_date
from django.views.static import directory_index, was_modified_since
from .. import urls
from ..urls import media_dir
@override_settings(DEBUG=True, ROOT_URLCONF="view_tests.urls")
class StaticTests(SimpleTestCase):
"""Tests django views in django/views/static.py"""
prefix = "site_media"
def test_serve(self):
"The static view can serve static media"
media_files = ["file.txt", "file.txt.gz", "%2F.txt"]
for filename in media_files:
response = self.client.get("/%s/%s" % (self.prefix, quote(filename)))
response_content = b"".join(response)
file_path = path.join(media_dir, filename)
with open(file_path, "rb") as fp:
self.assertEqual(fp.read(), response_content)
self.assertEqual(
len(response_content), int(response.headers["Content-Length"])
)
self.assertEqual(
mimetypes.guess_type(file_path)[1],
response.get("Content-Encoding", None),
)
def test_chunked(self):
"""
The static view should stream files in chunks to avoid large memory
usage
"""
response = self.client.get("/%s/%s" % (self.prefix, "long-line.txt"))
response_iterator = iter(response)
first_chunk = next(response_iterator)
self.assertEqual(len(first_chunk), FileResponse.block_size)
second_chunk = next(response_iterator)
response.close()
# strip() to prevent OS line endings from causing differences
self.assertEqual(len(second_chunk.strip()), 1449)
def test_unknown_mime_type(self):
response = self.client.get("/%s/file.unknown" % self.prefix)
self.assertEqual("application/octet-stream", response.headers["Content-Type"])
response.close()
def test_copes_with_empty_path_component(self):
file_name = "file.txt"
response = self.client.get("/%s//%s" % (self.prefix, file_name))
response_content = b"".join(response)
with open(path.join(media_dir, file_name), "rb") as fp:
self.assertEqual(fp.read(), response_content)
def test_is_modified_since(self):
file_name = "file.txt"
response = self.client.get(
"/%s/%s" % (self.prefix, file_name),
headers={"if-modified-since": "Thu, 1 Jan 1970 00:00:00 GMT"},
)
response_content = b"".join(response)
with open(path.join(media_dir, file_name), "rb") as fp:
self.assertEqual(fp.read(), response_content)
def test_not_modified_since(self):
file_name = "file.txt"
response = self.client.get(
"/%s/%s" % (self.prefix, file_name),
headers={
# This is 24h before max Unix time. Remember to fix Django and
# update this test well before 2038 :)
"if-modified-since": "Mon, 18 Jan 2038 05:14:07 GMT"
},
)
self.assertIsInstance(response, HttpResponseNotModified)
def test_invalid_if_modified_since(self):
"""Handle bogus If-Modified-Since values gracefully
Assume that a file is modified since an invalid timestamp as per RFC
9110 Section 13.1.3.
"""
file_name = "file.txt"
invalid_date = "Mon, 28 May 999999999999 28:25:26 GMT"
response = self.client.get(
"/%s/%s" % (self.prefix, file_name),
headers={"if-modified-since": invalid_date},
)
response_content = b"".join(response)
with open(path.join(media_dir, file_name), "rb") as fp:
self.assertEqual(fp.read(), response_content)
self.assertEqual(len(response_content), int(response.headers["Content-Length"]))
def test_invalid_if_modified_since2(self):
"""Handle even more bogus If-Modified-Since values gracefully
Assume that a file is modified since an invalid timestamp as per RFC
9110 Section 13.1.3.
"""
file_name = "file.txt"
invalid_date = ": 1291108438, Wed, 20 Oct 2010 14:05:00 GMT"
response = self.client.get(
"/%s/%s" % (self.prefix, file_name),
headers={"if-modified-since": invalid_date},
)
response_content = b"".join(response)
with open(path.join(media_dir, file_name), "rb") as fp:
self.assertEqual(fp.read(), response_content)
self.assertEqual(len(response_content), int(response.headers["Content-Length"]))
def test_404(self):
response = self.client.get("/%s/nonexistent_resource" % self.prefix)
self.assertEqual(404, response.status_code)
def test_index(self):
response = self.client.get("/%s/" % self.prefix)
self.assertContains(response, "Index of ./")
# Directories have a trailing slash.
self.assertIn("subdir/", response.context["file_list"])
def test_index_subdir(self):
response = self.client.get("/%s/subdir/" % self.prefix)
self.assertContains(response, "Index of subdir/")
# File with a leading dot (e.g. .hidden) aren't displayed.
self.assertEqual(response.context["file_list"], ["visible"])
@override_settings(
TEMPLATES=[
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"OPTIONS": {
"loaders": [
(
"django.template.loaders.locmem.Loader",
{
"static/directory_index.html": "Test index",
},
),
],
},
}
]
)
def test_index_custom_template(self):
response = self.client.get("/%s/" % self.prefix)
self.assertEqual(response.content, b"Test index")
def test_template_encoding(self):
"""
The template is loaded directly, not via a template loader, and should
be opened as utf-8 charset as is the default specified on template
engines.
"""
from django.views.static import Path
with mock.patch.object(Path, "open") as m:
directory_index(mock.MagicMock(), mock.MagicMock())
m.assert_called_once_with(encoding="utf-8")
class StaticHelperTest(StaticTests):
"""
Test case to make sure the static URL pattern helper works as expected
"""
def setUp(self):
super().setUp()
self._old_views_urlpatterns = urls.urlpatterns[:]
urls.urlpatterns += static("media/", document_root=media_dir)
def tearDown(self):
super().tearDown()
urls.urlpatterns = self._old_views_urlpatterns
def test_prefix(self):
self.assertEqual(static("test")[0].pattern.regex.pattern, "^test(?P<path>.*)$")
@override_settings(DEBUG=False)
def test_debug_off(self):
"""No URLs are served if DEBUG=False."""
self.assertEqual(static("test"), [])
def test_empty_prefix(self):
with self.assertRaisesMessage(
ImproperlyConfigured, "Empty static prefix not permitted"
):
static("")
def test_special_prefix(self):
"""No URLs are served if prefix contains a netloc part."""
self.assertEqual(static("http://example.org"), [])
self.assertEqual(static("//example.org"), [])
class StaticUtilsTests(unittest.TestCase):
def test_was_modified_since_fp(self):
"""
A floating point mtime does not disturb was_modified_since (#18675).
"""
mtime = 1343416141.107817
header = http_date(mtime)
self.assertFalse(was_modified_since(header, mtime))
def test_was_modified_since_empty_string(self):
self.assertTrue(was_modified_since(header="", mtime=1))
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/view_tests/tests/__init__.py | tests/view_tests/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/view_tests/tests/test_debug.py | tests/view_tests/tests/test_debug.py | import importlib
import inspect
import os
import re
import sys
import tempfile
import threading
from io import StringIO
from pathlib import Path
from unittest import mock, skipIf
from asgiref.sync import async_to_sync, iscoroutinefunction
from django.core import mail
from django.core.files.uploadedfile import SimpleUploadedFile
from django.db import DatabaseError, connection
from django.http import Http404, HttpRequest, HttpResponse
from django.shortcuts import render
from django.template import TemplateDoesNotExist
from django.test import RequestFactory, SimpleTestCase, override_settings
from django.test.utils import LoggingCaptureMixin
from django.urls import path, reverse
from django.urls.converters import IntConverter
from django.utils.functional import SimpleLazyObject
from django.utils.regex_helper import _lazy_re_compile
from django.utils.safestring import mark_safe
from django.views.debug import (
CallableSettingWrapper,
ExceptionCycleWarning,
ExceptionReporter,
)
from django.views.debug import Path as DebugPath
from django.views.debug import (
SafeExceptionReporterFilter,
default_urlconf,
get_default_exception_reporter_filter,
technical_404_response,
technical_500_response,
)
from django.views.decorators.debug import sensitive_post_parameters, sensitive_variables
from ..views import (
async_sensitive_method_view,
async_sensitive_method_view_nested,
async_sensitive_view,
async_sensitive_view_nested,
custom_exception_reporter_filter_view,
index_page,
multivalue_dict_key_error,
non_sensitive_view,
paranoid_view,
sensitive_args_function_caller,
sensitive_kwargs_function_caller,
sensitive_method_view,
sensitive_view,
)
class User:
def __str__(self):
return "jacob"
class WithoutEmptyPathUrls:
urlpatterns = [path("url/", index_page, name="url")]
class CallableSettingWrapperTests(SimpleTestCase):
"""Unittests for CallableSettingWrapper"""
def test_repr(self):
class WrappedCallable:
def __repr__(self):
return "repr from the wrapped callable"
def __call__(self):
pass
actual = repr(CallableSettingWrapper(WrappedCallable()))
self.assertEqual(actual, "repr from the wrapped callable")
@override_settings(DEBUG=True, ROOT_URLCONF="view_tests.urls")
class DebugViewTests(SimpleTestCase):
def test_files(self):
with self.assertLogs("django.request", "ERROR"):
response = self.client.get("/raises/")
self.assertEqual(response.status_code, 500)
data = {
"file_data.txt": SimpleUploadedFile("file_data.txt", b"haha"),
}
with self.assertLogs("django.request", "ERROR"):
response = self.client.post("/raises/", data)
self.assertContains(response, "file_data.txt", status_code=500)
self.assertNotContains(response, "haha", status_code=500)
def test_400(self):
# When DEBUG=True, technical_500_template() is called.
with self.assertLogs("django.security", "WARNING"):
response = self.client.get("/raises400/")
self.assertContains(response, '<div class="context" id="', status_code=400)
def test_400_bad_request(self):
# When DEBUG=True, technical_500_template() is called.
with self.assertLogs("django.request", "WARNING") as cm:
response = self.client.get("/raises400_bad_request/")
self.assertContains(response, '<div class="context" id="', status_code=400)
self.assertEqual(
cm.records[0].getMessage(),
"Malformed request syntax: /raises400_bad_request/",
)
# Ensure no 403.html template exists to test the default case.
@override_settings(
TEMPLATES=[
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
}
]
)
def test_403(self):
response = self.client.get("/raises403/")
self.assertContains(response, "<h1>403 Forbidden</h1>", status_code=403)
# Set up a test 403.html template.
@override_settings(
TEMPLATES=[
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"OPTIONS": {
"loaders": [
(
"django.template.loaders.locmem.Loader",
{
"403.html": (
"This is a test template for a 403 error "
"({{ exception }})."
),
},
),
],
},
}
]
)
def test_403_template(self):
response = self.client.get("/raises403/")
self.assertContains(response, "test template", status_code=403)
self.assertContains(response, "(Insufficient Permissions).", status_code=403)
def test_404(self):
response = self.client.get("/raises404/")
self.assertNotContains(
response,
'<pre class="exception_value">',
status_code=404,
)
self.assertContains(
response,
"<p>The current path, <code>not-in-urls</code>, didn’t match any "
"of these.</p>",
status_code=404,
html=True,
)
def test_404_not_in_urls(self):
response = self.client.get("/not-in-urls")
self.assertNotContains(response, "Raised by:", status_code=404)
self.assertNotContains(
response,
'<pre class="exception_value">',
status_code=404,
)
self.assertContains(
response, "Django tried these URL patterns", status_code=404
)
self.assertContains(
response,
"<code>technical404/ [name='my404']</code>",
status_code=404,
html=True,
)
self.assertContains(
response,
"<p>The current path, <code>not-in-urls</code>, didn’t match any "
"of these.</p>",
status_code=404,
html=True,
)
# Pattern and view name of a RegexURLPattern appear.
self.assertContains(
response, r"^regex-post/(?P<pk>[0-9]+)/$", status_code=404
)
self.assertContains(response, "[name='regex-post']", status_code=404)
# Pattern and view name of a RoutePattern appear.
self.assertContains(response, r"path-post/<int:pk>/", status_code=404)
self.assertContains(response, "[name='path-post']", status_code=404)
@override_settings(ROOT_URLCONF=WithoutEmptyPathUrls)
def test_404_empty_path_not_in_urls(self):
response = self.client.get("/")
self.assertContains(
response,
"<p>The empty path didn’t match any of these.</p>",
status_code=404,
html=True,
)
def test_technical_404(self):
response = self.client.get("/technical404/")
self.assertContains(response, '<header id="summary">', status_code=404)
self.assertContains(response, '<main id="info">', status_code=404)
self.assertContains(response, '<footer id="explanation">', status_code=404)
self.assertContains(
response,
'<pre class="exception_value">Testing technical 404.</pre>',
status_code=404,
html=True,
)
self.assertContains(response, "Raised by:", status_code=404)
self.assertContains(
response,
"<td>view_tests.views.technical404</td>",
status_code=404,
)
self.assertContains(
response,
"<p>The current path, <code>technical404/</code>, matched the "
"last one.</p>",
status_code=404,
html=True,
)
def test_classbased_technical_404(self):
response = self.client.get("/classbased404/")
self.assertContains(
response,
'<th scope="row">Raised by:</th><td>view_tests.views.Http404View</td>',
status_code=404,
html=True,
)
def test_technical_500(self):
with self.assertLogs("django.request", "ERROR"):
response = self.client.get("/raises500/")
self.assertContains(response, '<header id="summary">', status_code=500)
self.assertContains(response, '<main id="info">', status_code=500)
self.assertContains(response, '<footer id="explanation">', status_code=500)
self.assertContains(
response,
'<th scope="row">Raised during:</th><td>view_tests.views.raises500</td>',
status_code=500,
html=True,
)
with self.assertLogs("django.request", "ERROR"):
response = self.client.get("/raises500/", headers={"accept": "text/plain"})
self.assertContains(
response,
"Raised during: view_tests.views.raises500",
status_code=500,
)
def test_technical_500_content_type_negotiation(self):
for accepts, content_type in [
("text/plain", "text/plain; charset=utf-8"),
("text/html", "text/html"),
("text/html,text/plain;q=0.9", "text/html"),
("text/plain,text/html;q=0.9", "text/plain; charset=utf-8"),
("text/*", "text/html"),
]:
with self.subTest(accepts=accepts):
with self.assertLogs("django.request", "ERROR"):
response = self.client.get(
"/raises500/", headers={"accept": accepts}
)
self.assertEqual(response.status_code, 500)
self.assertEqual(response["Content-Type"], content_type)
def test_classbased_technical_500(self):
with self.assertLogs("django.request", "ERROR"):
response = self.client.get("/classbased500/")
self.assertContains(
response,
'<th scope="row">Raised during:</th>'
"<td>view_tests.views.Raises500View</td>",
status_code=500,
html=True,
)
with self.assertLogs("django.request", "ERROR"):
response = self.client.get(
"/classbased500/", headers={"accept": "text/plain"}
)
self.assertContains(
response,
"Raised during: view_tests.views.Raises500View",
status_code=500,
)
def test_non_l10ned_numeric_ids(self):
"""
Numeric IDs and fancy traceback context blocks line numbers shouldn't
be localized.
"""
with self.settings(DEBUG=True):
with self.assertLogs("django.request", "ERROR"):
response = self.client.get("/raises500/")
# We look for a HTML fragment of the form
# '<div class="context" id="c38123208">',
# not '<div class="context" id="c38,123,208"'.
self.assertContains(response, '<div class="context" id="', status_code=500)
match = re.search(
b'<div class="context" id="(?P<id>[^"]+)">', response.content
)
self.assertIsNotNone(match)
id_repr = match["id"]
self.assertFalse(
re.search(b"[^c0-9]", id_repr),
"Numeric IDs in debug response HTML page shouldn't be localized "
"(value: %s)." % id_repr.decode(),
)
def test_template_exceptions(self):
with self.assertLogs("django.request", "ERROR"):
try:
self.client.get(reverse("template_exception"))
except Exception:
raising_loc = inspect.trace()[-1][-2][0].strip()
self.assertNotEqual(
raising_loc.find('raise Exception("boom")'),
-1,
"Failed to find 'raise Exception' in last frame of "
"traceback, instead found: %s" % raising_loc,
)
@skipIf(
sys.platform == "win32",
"Raises OSError instead of TemplateDoesNotExist on Windows.",
)
def test_safestring_in_exception(self):
with self.assertLogs("django.request", "ERROR"):
response = self.client.get("/safestring_exception/")
self.assertNotContains(
response,
"<script>alert(1);</script>",
status_code=500,
html=True,
)
self.assertContains(
response,
"<script>alert(1);</script>",
count=3,
status_code=500,
html=True,
)
def test_template_loader_postmortem(self):
"""Tests for not existing file"""
template_name = "notfound.html"
with tempfile.NamedTemporaryFile(prefix=template_name) as tmpfile:
tempdir = os.path.dirname(tmpfile.name)
template_path = os.path.join(tempdir, template_name)
with (
override_settings(
TEMPLATES=[
{
"BACKEND": (
"django.template.backends.django.DjangoTemplates"
),
"DIRS": [tempdir],
}
]
),
self.assertLogs("django.request", "ERROR"),
):
response = self.client.get(
reverse(
"raises_template_does_not_exist", kwargs={"path": template_name}
)
)
self.assertContains(
response,
"%s (Source does not exist)" % template_path,
status_code=500,
count=2,
)
# Assert as HTML.
self.assertContains(
response,
"<li><code>django.template.loaders.filesystem.Loader</code>: "
"%s (Source does not exist)</li>"
% os.path.join(tempdir, "notfound.html"),
status_code=500,
html=True,
)
def test_no_template_source_loaders(self):
"""
Make sure if you don't specify a template, the debug view doesn't blow
up.
"""
with self.assertLogs("django.request", "ERROR"):
with self.assertRaises(TemplateDoesNotExist):
self.client.get("/render_no_template/")
@override_settings(ROOT_URLCONF="view_tests.default_urls")
def test_default_urlconf_template(self):
"""
Make sure that the default URLconf template is shown instead of the
technical 404 page, if the user has not altered their URLconf yet.
"""
response = self.client.get("/")
self.assertContains(
response, "<h1>The install worked successfully! Congratulations!</h1>"
)
@override_settings(
ROOT_URLCONF="view_tests.default_urls", FORCE_SCRIPT_NAME="/FORCED_PREFIX"
)
def test_default_urlconf_script_name(self):
response = self.client.request(**{"path": "/FORCED_PREFIX/"})
self.assertContains(
response, "<h1>The install worked successfully! Congratulations!</h1>"
)
@override_settings(ROOT_URLCONF="view_tests.default_urls")
def test_default_urlconf_technical_404(self):
response = self.client.get("/favicon.ico")
self.assertContains(
response,
"<code>\nadmin/\n[namespace='admin']\n</code>",
status_code=404,
html=True,
)
@override_settings(ROOT_URLCONF="view_tests.regression_21530_urls")
def test_regression_21530(self):
"""
Regression test for bug #21530.
If the admin app include is replaced with exactly one url
pattern, then the technical 404 template should be displayed.
The bug here was that an AttributeError caused a 500 response.
"""
response = self.client.get("/")
self.assertContains(
response, "Page not found <small>(404)</small>", status_code=404
)
def test_template_encoding(self):
"""
The templates are loaded directly, not via a template loader, and
should be opened as utf-8 charset as is the default specified on
template engines.
"""
with mock.patch.object(DebugPath, "open") as m:
default_urlconf(None)
m.assert_called_once_with(encoding="utf-8")
m.reset_mock()
technical_404_response(mock.MagicMock(), mock.Mock())
m.assert_called_once_with(encoding="utf-8")
def test_technical_404_converter_raise_404(self):
with mock.patch.object(IntConverter, "to_python", side_effect=Http404):
response = self.client.get("/path-post/1/")
self.assertContains(response, "Page not found", status_code=404)
def test_exception_reporter_from_request(self):
with self.assertLogs("django.request", "ERROR"):
response = self.client.get("/custom_reporter_class_view/")
self.assertContains(response, "custom traceback text", status_code=500)
@override_settings(
DEFAULT_EXCEPTION_REPORTER="view_tests.views.CustomExceptionReporter"
)
def test_exception_reporter_from_settings(self):
with self.assertLogs("django.request", "ERROR"):
response = self.client.get("/raises500/")
self.assertContains(response, "custom traceback text", status_code=500)
@override_settings(
DEFAULT_EXCEPTION_REPORTER="view_tests.views.TemplateOverrideExceptionReporter"
)
def test_template_override_exception_reporter(self):
with self.assertLogs("django.request", "ERROR"):
response = self.client.get("/raises500/")
self.assertContains(
response,
"<h1>Oh no, an error occurred!</h1>",
status_code=500,
html=True,
)
with self.assertLogs("django.request", "ERROR"):
response = self.client.get("/raises500/", headers={"accept": "text/plain"})
self.assertContains(response, "Oh dear, an error occurred!", status_code=500)
class DebugViewQueriesAllowedTests(SimpleTestCase):
# May need a query to initialize MySQL connection
databases = {"default"}
def test_handle_db_exception(self):
"""
Ensure the debug view works when a database exception is raised by
performing an invalid query and passing the exception to the debug
view.
"""
with connection.cursor() as cursor:
try:
cursor.execute("INVALID SQL")
except DatabaseError:
exc_info = sys.exc_info()
rf = RequestFactory()
response = technical_500_response(rf.get("/"), *exc_info)
self.assertContains(response, "OperationalError at /", status_code=500)
@override_settings(
DEBUG=True,
ROOT_URLCONF="view_tests.urls",
# No template directories are configured, so no templates will be found.
TEMPLATES=[
{
"BACKEND": "django.template.backends.dummy.TemplateStrings",
}
],
)
class NonDjangoTemplatesDebugViewTests(SimpleTestCase):
def test_400(self):
# When DEBUG=True, technical_500_template() is called.
with self.assertLogs("django.security", "WARNING"):
response = self.client.get("/raises400/")
self.assertContains(response, '<div class="context" id="', status_code=400)
def test_400_bad_request(self):
# When DEBUG=True, technical_500_template() is called.
with self.assertLogs("django.request", "WARNING") as cm:
response = self.client.get("/raises400_bad_request/")
self.assertContains(response, '<div class="context" id="', status_code=400)
self.assertEqual(
cm.records[0].getMessage(),
"Malformed request syntax: /raises400_bad_request/",
)
def test_403(self):
response = self.client.get("/raises403/")
self.assertContains(response, "<h1>403 Forbidden</h1>", status_code=403)
def test_404(self):
response = self.client.get("/raises404/")
self.assertEqual(response.status_code, 404)
def test_template_not_found_error(self):
# Raises a TemplateDoesNotExist exception and shows the debug view.
url = reverse(
"raises_template_does_not_exist", kwargs={"path": "notfound.html"}
)
with self.assertLogs("django.request", "ERROR"):
response = self.client.get(url)
self.assertContains(response, '<div class="context" id="', status_code=500)
class ExceptionReporterTests(SimpleTestCase):
rf = RequestFactory()
def test_request_and_exception(self):
"A simple exception report can be generated"
try:
request = self.rf.get("/test_view/")
request.user = User()
raise ValueError("Can't find my keys")
except ValueError:
exc_type, exc_value, tb = sys.exc_info()
reporter = ExceptionReporter(request, exc_type, exc_value, tb)
html = reporter.get_traceback_html()
self.assertInHTML("<h1>ValueError at /test_view/</h1>", html)
self.assertIn(
'<pre class="exception_value">Can't find my keys</pre>', html
)
self.assertIn('<th scope="row">Request Method:</th>', html)
self.assertIn('<th scope="row">Request URL:</th>', html)
self.assertIn('<h3 id="user-info">USER</h3>', html)
self.assertIn("<p>jacob</p>", html)
self.assertIn('<th scope="row">Exception Type:</th>', html)
self.assertIn('<th scope="row">Exception Value:</th>', html)
self.assertIn("<h2>Traceback ", html)
self.assertIn("<h2>Request information</h2>", html)
self.assertNotIn("<p>Request data not supplied</p>", html)
self.assertIn("<p>No POST data</p>", html)
def test_no_request(self):
"An exception report can be generated without request"
try:
raise ValueError("Can't find my keys")
except ValueError:
exc_type, exc_value, tb = sys.exc_info()
reporter = ExceptionReporter(None, exc_type, exc_value, tb)
html = reporter.get_traceback_html()
self.assertInHTML("<h1>ValueError</h1>", html)
self.assertIn(
'<pre class="exception_value">Can't find my keys</pre>', html
)
self.assertNotIn('<th scope="row">Request Method:</th>', html)
self.assertNotIn('<th scope="row">Request URL:</th>', html)
self.assertNotIn('<h3 id="user-info">USER</h3>', html)
self.assertIn('<th scope="row">Exception Type:</th>', html)
self.assertIn('<th scope="row">Exception Value:</th>', html)
self.assertIn("<h2>Traceback ", html)
self.assertIn("<h2>Request information</h2>", html)
self.assertIn("<p>Request data not supplied</p>", html)
def test_sharing_traceback(self):
try:
raise ValueError("Oops")
except ValueError:
exc_type, exc_value, tb = sys.exc_info()
reporter = ExceptionReporter(None, exc_type, exc_value, tb)
html = reporter.get_traceback_html()
self.assertIn(
'<form action="https://dpaste.com/" name="pasteform" '
'id="pasteform" method="post">',
html,
)
def test_eol_support(self):
"""
The ExceptionReporter supports Unix, Windows and Macintosh EOL markers
"""
LINES = ["print %d" % i for i in range(1, 6)]
reporter = ExceptionReporter(None, None, None, None)
for newline in ["\n", "\r\n", "\r"]:
fd, filename = tempfile.mkstemp(text=False)
os.write(fd, (newline.join(LINES) + newline).encode())
os.close(fd)
try:
self.assertEqual(
reporter._get_lines_from_file(filename, 3, 2),
(1, LINES[1:3], LINES[3], LINES[4:]),
)
finally:
os.unlink(filename)
def test_no_exception(self):
"An exception report can be generated for just a request"
request = self.rf.get("/test_view/")
reporter = ExceptionReporter(request, None, None, None)
html = reporter.get_traceback_html()
self.assertInHTML("<h1>Report at /test_view/</h1>", html)
self.assertIn(
'<pre class="exception_value">No exception message supplied</pre>', html
)
self.assertIn('<th scope="row">Request Method:</th>', html)
self.assertIn('<th scope="row">Request URL:</th>', html)
self.assertNotIn('<th scope="row">Exception Type:</th>', html)
self.assertNotIn('<th scope="row">Exception Value:</th>', html)
self.assertNotIn("<h2>Traceback ", html)
self.assertIn("<h2>Request information</h2>", html)
self.assertNotIn("<p>Request data not supplied</p>", html)
def test_suppressed_context(self):
try:
try:
raise RuntimeError("Can't find my keys")
except RuntimeError:
raise ValueError("Can't find my keys") from None
except ValueError:
exc_type, exc_value, tb = sys.exc_info()
reporter = ExceptionReporter(None, exc_type, exc_value, tb)
html = reporter.get_traceback_html()
self.assertInHTML("<h1>ValueError</h1>", html)
self.assertIn(
'<pre class="exception_value">Can't find my keys</pre>', html
)
self.assertIn('<th scope="row">Exception Type:</th>', html)
self.assertIn('<th scope="row">Exception Value:</th>', html)
self.assertIn("<h2>Traceback ", html)
self.assertIn("<h2>Request information</h2>", html)
self.assertIn("<p>Request data not supplied</p>", html)
self.assertNotIn("During handling of the above exception", html)
def test_innermost_exception_without_traceback(self):
try:
try:
raise RuntimeError("Oops")
except Exception as exc:
new_exc = RuntimeError("My context")
exc.__context__ = new_exc
raise
except Exception:
exc_type, exc_value, tb = sys.exc_info()
reporter = ExceptionReporter(None, exc_type, exc_value, tb)
frames = reporter.get_traceback_frames()
self.assertEqual(len(frames), 2)
html = reporter.get_traceback_html()
self.assertInHTML("<h1>RuntimeError</h1>", html)
self.assertIn('<pre class="exception_value">Oops</pre>', html)
self.assertIn('<th scope="row">Exception Type:</th>', html)
self.assertIn('<th scope="row">Exception Value:</th>', html)
self.assertIn("<h2>Traceback ", html)
self.assertIn("<h2>Request information</h2>", html)
self.assertIn("<p>Request data not supplied</p>", html)
self.assertIn(
"During handling of the above exception (My context), another "
"exception occurred",
html,
)
self.assertInHTML('<li class="frame user">None</li>', html)
self.assertIn("Traceback (most recent call last):\n None", html)
text = reporter.get_traceback_text()
self.assertIn("Exception Type: RuntimeError", text)
self.assertIn("Exception Value: Oops", text)
self.assertIn("Traceback (most recent call last):\n None", text)
self.assertIn(
"During handling of the above exception (My context), another "
"exception occurred",
text,
)
def test_exception_with_notes(self):
request = self.rf.get("/test_view/")
try:
try:
raise RuntimeError("Oops")
except Exception as err:
err.add_note("First Note")
err.add_note("Second Note")
err.add_note(mark_safe("<script>alert(1);</script>"))
raise err
except Exception:
exc_type, exc_value, tb = sys.exc_info()
reporter = ExceptionReporter(request, exc_type, exc_value, tb)
html = reporter.get_traceback_html()
self.assertIn(
'<pre class="exception_value">Oops\nFirst Note\nSecond Note\n'
"<script>alert(1);</script></pre>",
html,
)
self.assertIn(
"Exception Value: Oops\nFirst Note\nSecond Note\n"
"<script>alert(1);</script>",
html,
)
text = reporter.get_traceback_text()
self.assertIn(
"Exception Value: Oops\nFirst Note\nSecond Note\n"
"<script>alert(1);</script>",
text,
)
def test_mid_stack_exception_without_traceback(self):
try:
try:
raise RuntimeError("Inner Oops")
except Exception as exc:
new_exc = RuntimeError("My context")
new_exc.__context__ = exc
raise RuntimeError("Oops") from new_exc
except Exception:
exc_type, exc_value, tb = sys.exc_info()
reporter = ExceptionReporter(None, exc_type, exc_value, tb)
html = reporter.get_traceback_html()
self.assertInHTML("<h1>RuntimeError</h1>", html)
self.assertIn('<pre class="exception_value">Oops</pre>', html)
self.assertIn('<th scope="row">Exception Type:</th>', html)
self.assertIn('<th scope="row">Exception Value:</th>', html)
self.assertIn("<h2>Traceback ", html)
self.assertInHTML('<li class="frame user">Traceback: None</li>', html)
self.assertIn(
"During handling of the above exception (Inner Oops), another "
"exception occurred:\n Traceback: None",
html,
)
text = reporter.get_traceback_text()
self.assertIn("Exception Type: RuntimeError", text)
self.assertIn("Exception Value: Oops", text)
self.assertIn("Traceback (most recent call last):", text)
self.assertIn(
"During handling of the above exception (Inner Oops), another "
"exception occurred:\n Traceback: None",
text,
)
def test_reporting_of_nested_exceptions(self):
request = self.rf.get("/test_view/")
try:
try:
raise AttributeError(mark_safe("<p>Top level</p>"))
except AttributeError as explicit:
try:
raise ValueError(mark_safe("<p>Second exception</p>")) from explicit
except ValueError:
raise IndexError(mark_safe("<p>Final exception</p>"))
except Exception:
# Custom exception handler, just pass it into ExceptionReporter
exc_type, exc_value, tb = sys.exc_info()
explicit_exc = (
"The above exception ({0}) was the direct cause of the following exception:"
)
implicit_exc = (
"During handling of the above exception ({0}), another exception occurred:"
)
reporter = ExceptionReporter(request, exc_type, exc_value, tb)
html = reporter.get_traceback_html()
# Both messages are twice on page -- one rendered as html,
# one as plain text (for pastebin)
self.assertEqual(
2, html.count(explicit_exc.format("<p>Top level</p>"))
)
self.assertEqual(
2, html.count(implicit_exc.format("<p>Second exception</p>"))
)
self.assertEqual(10, html.count("<p>Final exception</p>"))
text = reporter.get_traceback_text()
self.assertIn(explicit_exc.format("<p>Top level</p>"), text)
self.assertIn(implicit_exc.format("<p>Second exception</p>"), text)
self.assertEqual(3, text.count("<p>Final exception</p>"))
@skipIf(
sys._xoptions.get("no_debug_ranges", False)
or os.environ.get("PYTHONNODEBUGRANGES", False),
"Fine-grained error locations are disabled.",
)
def test_highlight_error_position(self):
request = self.rf.get("/test_view/")
try:
try:
raise AttributeError("Top level")
except AttributeError as explicit:
try:
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | true |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/view_tests/app0/__init__.py | tests/view_tests/app0/__init__.py | python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false | |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/view_tests/app5/__init__.py | tests/view_tests/app5/__init__.py | python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false | |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/view_tests/app4/__init__.py | tests/view_tests/app4/__init__.py | python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false | |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/view_tests/app2/__init__.py | tests/view_tests/app2/__init__.py | python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false | |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/view_tests/app1/__init__.py | tests/view_tests/app1/__init__.py | python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false | |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/expressions_case/models.py | tests/expressions_case/models.py | from django.db import models
try:
from PIL import Image
except ImportError:
Image = None
class CaseTestModel(models.Model):
integer = models.IntegerField()
integer2 = models.IntegerField(null=True)
string = models.CharField(max_length=100, default="")
big_integer = models.BigIntegerField(null=True)
binary = models.BinaryField(default=b"")
boolean = models.BooleanField(default=False)
date = models.DateField(null=True, db_column="date_field")
date_time = models.DateTimeField(null=True)
decimal = models.DecimalField(
max_digits=2, decimal_places=1, null=True, db_column="decimal_field"
)
duration = models.DurationField(null=True)
email = models.EmailField(default="")
file = models.FileField(null=True, db_column="file_field")
file_path = models.FilePathField(null=True)
float = models.FloatField(null=True, db_column="float_field")
if Image:
image = models.ImageField(null=True)
generic_ip_address = models.GenericIPAddressField(null=True)
null_boolean = models.BooleanField(null=True)
positive_integer = models.PositiveIntegerField(null=True)
positive_small_integer = models.PositiveSmallIntegerField(null=True)
positive_big_integer = models.PositiveSmallIntegerField(null=True)
slug = models.SlugField(default="")
small_integer = models.SmallIntegerField(null=True)
text = models.TextField(default="")
time = models.TimeField(null=True, db_column="time_field")
url = models.URLField(default="")
uuid = models.UUIDField(null=True)
fk = models.ForeignKey("self", models.CASCADE, null=True)
class O2OCaseTestModel(models.Model):
o2o = models.OneToOneField(CaseTestModel, models.CASCADE, related_name="o2o_rel")
integer = models.IntegerField()
class FKCaseTestModel(models.Model):
fk = models.ForeignKey(CaseTestModel, models.CASCADE, related_name="fk_rel")
integer = models.IntegerField()
class Client(models.Model):
REGULAR = "R"
GOLD = "G"
PLATINUM = "P"
ACCOUNT_TYPE_CHOICES = (
(REGULAR, "Regular"),
(GOLD, "Gold"),
(PLATINUM, "Platinum"),
)
name = models.CharField(max_length=50)
registered_on = models.DateField()
account_type = models.CharField(
max_length=1,
choices=ACCOUNT_TYPE_CHOICES,
default=REGULAR,
)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/expressions_case/__init__.py | tests/expressions_case/__init__.py | python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false | |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/expressions_case/tests.py | tests/expressions_case/tests.py | import unittest
from datetime import date, datetime, time, timedelta
from decimal import Decimal
from operator import attrgetter, itemgetter
from uuid import UUID
from django.core.exceptions import FieldError
from django.db import connection
from django.db.models import (
BinaryField,
BooleanField,
Case,
Count,
DecimalField,
F,
GenericIPAddressField,
IntegerField,
Max,
Min,
Q,
Sum,
TextField,
Value,
When,
)
from django.test import SimpleTestCase, TestCase
from .models import CaseTestModel, Client, FKCaseTestModel, O2OCaseTestModel
try:
from PIL import Image
except ImportError:
Image = None
class CaseExpressionTests(TestCase):
@classmethod
def setUpTestData(cls):
o = CaseTestModel.objects.create(integer=1, integer2=1, string="1")
O2OCaseTestModel.objects.create(o2o=o, integer=1)
FKCaseTestModel.objects.create(fk=o, integer=1)
o = CaseTestModel.objects.create(integer=2, integer2=3, string="2")
O2OCaseTestModel.objects.create(o2o=o, integer=2)
FKCaseTestModel.objects.create(fk=o, integer=2)
FKCaseTestModel.objects.create(fk=o, integer=3)
o = CaseTestModel.objects.create(integer=3, integer2=4, string="3")
O2OCaseTestModel.objects.create(o2o=o, integer=3)
FKCaseTestModel.objects.create(fk=o, integer=3)
FKCaseTestModel.objects.create(fk=o, integer=4)
o = CaseTestModel.objects.create(integer=2, integer2=2, string="2")
O2OCaseTestModel.objects.create(o2o=o, integer=2)
FKCaseTestModel.objects.create(fk=o, integer=2)
FKCaseTestModel.objects.create(fk=o, integer=3)
o = CaseTestModel.objects.create(integer=3, integer2=4, string="3")
O2OCaseTestModel.objects.create(o2o=o, integer=3)
FKCaseTestModel.objects.create(fk=o, integer=3)
FKCaseTestModel.objects.create(fk=o, integer=4)
o = CaseTestModel.objects.create(integer=3, integer2=3, string="3")
O2OCaseTestModel.objects.create(o2o=o, integer=3)
FKCaseTestModel.objects.create(fk=o, integer=3)
FKCaseTestModel.objects.create(fk=o, integer=4)
o = CaseTestModel.objects.create(integer=4, integer2=5, string="4")
O2OCaseTestModel.objects.create(o2o=o, integer=1)
FKCaseTestModel.objects.create(fk=o, integer=5)
cls.group_by_fields = [
f.name
for f in CaseTestModel._meta.get_fields()
if not (f.is_relation and f.auto_created)
and (
connection.features.allows_group_by_lob
or not isinstance(f, (BinaryField, TextField))
)
]
def test_annotate(self):
self.assertQuerySetEqual(
CaseTestModel.objects.annotate(
test=Case(
When(integer=1, then=Value("one")),
When(integer=2, then=Value("two")),
default=Value("other"),
)
).order_by("pk"),
[
(1, "one"),
(2, "two"),
(3, "other"),
(2, "two"),
(3, "other"),
(3, "other"),
(4, "other"),
],
transform=attrgetter("integer", "test"),
)
def test_annotate_without_default(self):
self.assertQuerySetEqual(
CaseTestModel.objects.annotate(
test=Case(
When(integer=1, then=1),
When(integer=2, then=2),
)
).order_by("pk"),
[(1, 1), (2, 2), (3, None), (2, 2), (3, None), (3, None), (4, None)],
transform=attrgetter("integer", "test"),
)
def test_annotate_with_expression_as_value(self):
self.assertQuerySetEqual(
CaseTestModel.objects.annotate(
f_test=Case(
When(integer=1, then=F("integer") + 1),
When(integer=2, then=F("integer") + 3),
default="integer",
)
).order_by("pk"),
[(1, 2), (2, 5), (3, 3), (2, 5), (3, 3), (3, 3), (4, 4)],
transform=attrgetter("integer", "f_test"),
)
def test_annotate_with_expression_as_condition(self):
self.assertQuerySetEqual(
CaseTestModel.objects.annotate(
f_test=Case(
When(integer2=F("integer"), then=Value("equal")),
When(integer2=F("integer") + 1, then=Value("+1")),
)
).order_by("pk"),
[
(1, "equal"),
(2, "+1"),
(3, "+1"),
(2, "equal"),
(3, "+1"),
(3, "equal"),
(4, "+1"),
],
transform=attrgetter("integer", "f_test"),
)
def test_annotate_with_join_in_value(self):
self.assertQuerySetEqual(
CaseTestModel.objects.annotate(
join_test=Case(
When(integer=1, then=F("o2o_rel__integer") + 1),
When(integer=2, then=F("o2o_rel__integer") + 3),
default="o2o_rel__integer",
)
).order_by("pk"),
[(1, 2), (2, 5), (3, 3), (2, 5), (3, 3), (3, 3), (4, 1)],
transform=attrgetter("integer", "join_test"),
)
def test_annotate_with_in_clause(self):
fk_rels = FKCaseTestModel.objects.filter(integer__in=[5])
self.assertQuerySetEqual(
CaseTestModel.objects.only("pk", "integer")
.annotate(
in_test=Sum(
Case(
When(fk_rel__in=fk_rels, then=F("fk_rel__integer")),
default=Value(0),
)
)
)
.order_by("pk"),
[(1, 0), (2, 0), (3, 0), (2, 0), (3, 0), (3, 0), (4, 5)],
transform=attrgetter("integer", "in_test"),
)
def test_annotate_with_join_in_condition(self):
self.assertQuerySetEqual(
CaseTestModel.objects.annotate(
join_test=Case(
When(integer2=F("o2o_rel__integer"), then=Value("equal")),
When(integer2=F("o2o_rel__integer") + 1, then=Value("+1")),
default=Value("other"),
)
).order_by("pk"),
[
(1, "equal"),
(2, "+1"),
(3, "+1"),
(2, "equal"),
(3, "+1"),
(3, "equal"),
(4, "other"),
],
transform=attrgetter("integer", "join_test"),
)
def test_annotate_with_join_in_predicate(self):
self.assertQuerySetEqual(
CaseTestModel.objects.annotate(
join_test=Case(
When(o2o_rel__integer=1, then=Value("one")),
When(o2o_rel__integer=2, then=Value("two")),
When(o2o_rel__integer=3, then=Value("three")),
default=Value("other"),
)
).order_by("pk"),
[
(1, "one"),
(2, "two"),
(3, "three"),
(2, "two"),
(3, "three"),
(3, "three"),
(4, "one"),
],
transform=attrgetter("integer", "join_test"),
)
def test_annotate_with_annotation_in_value(self):
self.assertQuerySetEqual(
CaseTestModel.objects.annotate(
f_plus_1=F("integer") + 1,
f_plus_3=F("integer") + 3,
)
.annotate(
f_test=Case(
When(integer=1, then="f_plus_1"),
When(integer=2, then="f_plus_3"),
default="integer",
),
)
.order_by("pk"),
[(1, 2), (2, 5), (3, 3), (2, 5), (3, 3), (3, 3), (4, 4)],
transform=attrgetter("integer", "f_test"),
)
def test_annotate_with_annotation_in_condition(self):
self.assertQuerySetEqual(
CaseTestModel.objects.annotate(
f_plus_1=F("integer") + 1,
)
.annotate(
f_test=Case(
When(integer2=F("integer"), then=Value("equal")),
When(integer2=F("f_plus_1"), then=Value("+1")),
),
)
.order_by("pk"),
[
(1, "equal"),
(2, "+1"),
(3, "+1"),
(2, "equal"),
(3, "+1"),
(3, "equal"),
(4, "+1"),
],
transform=attrgetter("integer", "f_test"),
)
def test_annotate_with_annotation_in_predicate(self):
self.assertQuerySetEqual(
CaseTestModel.objects.annotate(
f_minus_2=F("integer") - 2,
)
.annotate(
test=Case(
When(f_minus_2=-1, then=Value("negative one")),
When(f_minus_2=0, then=Value("zero")),
When(f_minus_2=1, then=Value("one")),
default=Value("other"),
),
)
.order_by("pk"),
[
(1, "negative one"),
(2, "zero"),
(3, "one"),
(2, "zero"),
(3, "one"),
(3, "one"),
(4, "other"),
],
transform=attrgetter("integer", "test"),
)
def test_annotate_with_aggregation_in_value(self):
self.assertQuerySetEqual(
CaseTestModel.objects.values(*self.group_by_fields)
.annotate(
min=Min("fk_rel__integer"),
max=Max("fk_rel__integer"),
)
.annotate(
test=Case(
When(integer=2, then="min"),
When(integer=3, then="max"),
),
)
.order_by("pk"),
[
(1, None, 1, 1),
(2, 2, 2, 3),
(3, 4, 3, 4),
(2, 2, 2, 3),
(3, 4, 3, 4),
(3, 4, 3, 4),
(4, None, 5, 5),
],
transform=itemgetter("integer", "test", "min", "max"),
)
def test_annotate_with_aggregation_in_condition(self):
self.assertQuerySetEqual(
CaseTestModel.objects.values(*self.group_by_fields)
.annotate(
min=Min("fk_rel__integer"),
max=Max("fk_rel__integer"),
)
.annotate(
test=Case(
When(integer2=F("min"), then=Value("min")),
When(integer2=F("max"), then=Value("max")),
),
)
.order_by("pk"),
[
(1, 1, "min"),
(2, 3, "max"),
(3, 4, "max"),
(2, 2, "min"),
(3, 4, "max"),
(3, 3, "min"),
(4, 5, "min"),
],
transform=itemgetter("integer", "integer2", "test"),
)
def test_annotate_with_aggregation_in_predicate(self):
self.assertQuerySetEqual(
CaseTestModel.objects.values(*self.group_by_fields)
.annotate(
max=Max("fk_rel__integer"),
)
.annotate(
test=Case(
When(max=3, then=Value("max = 3")),
When(max=4, then=Value("max = 4")),
default=Value(""),
),
)
.order_by("pk"),
[
(1, 1, ""),
(2, 3, "max = 3"),
(3, 4, "max = 4"),
(2, 3, "max = 3"),
(3, 4, "max = 4"),
(3, 4, "max = 4"),
(4, 5, ""),
],
transform=itemgetter("integer", "max", "test"),
)
def test_annotate_exclude(self):
self.assertQuerySetEqual(
CaseTestModel.objects.annotate(
test=Case(
When(integer=1, then=Value("one")),
When(integer=2, then=Value("two")),
default=Value("other"),
)
)
.exclude(test="other")
.order_by("pk"),
[(1, "one"), (2, "two"), (2, "two")],
transform=attrgetter("integer", "test"),
)
def test_annotate_filter_decimal(self):
obj = CaseTestModel.objects.create(integer=0, decimal=Decimal("1"))
qs = CaseTestModel.objects.annotate(
x=Case(When(integer=0, then=F("decimal"))),
y=Case(When(integer=0, then=Value(Decimal("1")))),
)
self.assertSequenceEqual(qs.filter(Q(x=1) & Q(x=Decimal("1"))), [obj])
self.assertSequenceEqual(qs.filter(Q(y=1) & Q(y=Decimal("1"))), [obj])
def test_annotate_values_not_in_order_by(self):
self.assertEqual(
list(
CaseTestModel.objects.annotate(
test=Case(
When(integer=1, then=Value("one")),
When(integer=2, then=Value("two")),
When(integer=3, then=Value("three")),
default=Value("other"),
)
)
.order_by("test")
.values_list("integer", flat=True)
),
[1, 4, 3, 3, 3, 2, 2],
)
def test_annotate_with_empty_when(self):
objects = CaseTestModel.objects.annotate(
selected=Case(
When(pk__in=[], then=Value("selected")),
default=Value("not selected"),
)
)
self.assertEqual(len(objects), CaseTestModel.objects.count())
self.assertTrue(all(obj.selected == "not selected" for obj in objects))
def test_annotate_with_full_when(self):
objects = CaseTestModel.objects.annotate(
selected=Case(
When(~Q(pk__in=[]), then=Value("selected")),
default=Value("not selected"),
)
)
self.assertEqual(len(objects), CaseTestModel.objects.count())
self.assertTrue(all(obj.selected == "selected" for obj in objects))
def test_combined_expression(self):
self.assertQuerySetEqual(
CaseTestModel.objects.annotate(
test=Case(
When(integer=1, then=2),
When(integer=2, then=1),
default=3,
)
+ 1,
).order_by("pk"),
[(1, 3), (2, 2), (3, 4), (2, 2), (3, 4), (3, 4), (4, 4)],
transform=attrgetter("integer", "test"),
)
def test_in_subquery(self):
self.assertQuerySetEqual(
CaseTestModel.objects.filter(
pk__in=CaseTestModel.objects.annotate(
test=Case(
When(integer=F("integer2"), then="pk"),
When(integer=4, then="pk"),
),
).values("test")
).order_by("pk"),
[(1, 1), (2, 2), (3, 3), (4, 5)],
transform=attrgetter("integer", "integer2"),
)
def test_condition_with_lookups(self):
qs = CaseTestModel.objects.annotate(
test=Case(
When(Q(integer2=1), string="2", then=Value(False)),
When(Q(integer2=1), string="1", then=Value(True)),
default=Value(False),
output_field=BooleanField(),
),
)
self.assertIs(qs.get(integer=1).test, True)
def test_case_reuse(self):
SOME_CASE = Case(
When(pk=0, then=Value("0")),
default=Value("1"),
)
self.assertQuerySetEqual(
CaseTestModel.objects.annotate(somecase=SOME_CASE).order_by("pk"),
CaseTestModel.objects.annotate(somecase=SOME_CASE)
.order_by("pk")
.values_list("pk", "somecase"),
lambda x: (x.pk, x.somecase),
)
def test_aggregate(self):
self.assertEqual(
CaseTestModel.objects.aggregate(
one=Sum(
Case(
When(integer=1, then=1),
)
),
two=Sum(
Case(
When(integer=2, then=1),
)
),
three=Sum(
Case(
When(integer=3, then=1),
)
),
four=Sum(
Case(
When(integer=4, then=1),
)
),
),
{"one": 1, "two": 2, "three": 3, "four": 1},
)
def test_aggregate_with_expression_as_value(self):
self.assertEqual(
CaseTestModel.objects.aggregate(
one=Sum(Case(When(integer=1, then="integer"))),
two=Sum(Case(When(integer=2, then=F("integer") - 1))),
three=Sum(Case(When(integer=3, then=F("integer") + 1))),
),
{"one": 1, "two": 2, "three": 12},
)
def test_aggregate_with_expression_as_condition(self):
self.assertEqual(
CaseTestModel.objects.aggregate(
equal=Sum(
Case(
When(integer2=F("integer"), then=1),
)
),
plus_one=Sum(
Case(
When(integer2=F("integer") + 1, then=1),
)
),
),
{"equal": 3, "plus_one": 4},
)
def test_filter(self):
self.assertQuerySetEqual(
CaseTestModel.objects.filter(
integer2=Case(
When(integer=2, then=3),
When(integer=3, then=4),
default=1,
)
).order_by("pk"),
[(1, 1), (2, 3), (3, 4), (3, 4)],
transform=attrgetter("integer", "integer2"),
)
def test_filter_without_default(self):
self.assertQuerySetEqual(
CaseTestModel.objects.filter(
integer2=Case(
When(integer=2, then=3),
When(integer=3, then=4),
)
).order_by("pk"),
[(2, 3), (3, 4), (3, 4)],
transform=attrgetter("integer", "integer2"),
)
def test_filter_with_expression_as_value(self):
self.assertQuerySetEqual(
CaseTestModel.objects.filter(
integer2=Case(
When(integer=2, then=F("integer") + 1),
When(integer=3, then=F("integer")),
default="integer",
)
).order_by("pk"),
[(1, 1), (2, 3), (3, 3)],
transform=attrgetter("integer", "integer2"),
)
def test_filter_with_expression_as_condition(self):
self.assertQuerySetEqual(
CaseTestModel.objects.filter(
string=Case(
When(integer2=F("integer"), then=Value("2")),
When(integer2=F("integer") + 1, then=Value("3")),
)
).order_by("pk"),
[(3, 4, "3"), (2, 2, "2"), (3, 4, "3")],
transform=attrgetter("integer", "integer2", "string"),
)
def test_filter_with_join_in_value(self):
self.assertQuerySetEqual(
CaseTestModel.objects.filter(
integer2=Case(
When(integer=2, then=F("o2o_rel__integer") + 1),
When(integer=3, then=F("o2o_rel__integer")),
default="o2o_rel__integer",
)
).order_by("pk"),
[(1, 1), (2, 3), (3, 3)],
transform=attrgetter("integer", "integer2"),
)
def test_filter_with_join_in_condition(self):
self.assertQuerySetEqual(
CaseTestModel.objects.filter(
integer=Case(
When(integer2=F("o2o_rel__integer") + 1, then=2),
When(integer2=F("o2o_rel__integer"), then=3),
)
).order_by("pk"),
[(2, 3), (3, 3)],
transform=attrgetter("integer", "integer2"),
)
def test_filter_with_join_in_predicate(self):
self.assertQuerySetEqual(
CaseTestModel.objects.filter(
integer2=Case(
When(o2o_rel__integer=1, then=1),
When(o2o_rel__integer=2, then=3),
When(o2o_rel__integer=3, then=4),
)
).order_by("pk"),
[(1, 1), (2, 3), (3, 4), (3, 4)],
transform=attrgetter("integer", "integer2"),
)
def test_filter_with_annotation_in_value(self):
self.assertQuerySetEqual(
CaseTestModel.objects.annotate(
f=F("integer"),
f_plus_1=F("integer") + 1,
)
.filter(
integer2=Case(
When(integer=2, then="f_plus_1"),
When(integer=3, then="f"),
),
)
.order_by("pk"),
[(2, 3), (3, 3)],
transform=attrgetter("integer", "integer2"),
)
def test_filter_with_annotation_in_condition(self):
self.assertQuerySetEqual(
CaseTestModel.objects.annotate(
f_plus_1=F("integer") + 1,
)
.filter(
integer=Case(
When(integer2=F("integer"), then=2),
When(integer2=F("f_plus_1"), then=3),
),
)
.order_by("pk"),
[(3, 4), (2, 2), (3, 4)],
transform=attrgetter("integer", "integer2"),
)
def test_filter_with_annotation_in_predicate(self):
self.assertQuerySetEqual(
CaseTestModel.objects.annotate(
f_plus_1=F("integer") + 1,
)
.filter(
integer2=Case(
When(f_plus_1=3, then=3),
When(f_plus_1=4, then=4),
default=1,
),
)
.order_by("pk"),
[(1, 1), (2, 3), (3, 4), (3, 4)],
transform=attrgetter("integer", "integer2"),
)
def test_filter_with_aggregation_in_value(self):
self.assertQuerySetEqual(
CaseTestModel.objects.values(*self.group_by_fields)
.annotate(
min=Min("fk_rel__integer"),
max=Max("fk_rel__integer"),
)
.filter(
integer2=Case(
When(integer=2, then="min"),
When(integer=3, then="max"),
),
)
.order_by("pk"),
[(3, 4, 3, 4), (2, 2, 2, 3), (3, 4, 3, 4)],
transform=itemgetter("integer", "integer2", "min", "max"),
)
def test_filter_with_aggregation_in_condition(self):
self.assertQuerySetEqual(
CaseTestModel.objects.values(*self.group_by_fields)
.annotate(
min=Min("fk_rel__integer"),
max=Max("fk_rel__integer"),
)
.filter(
integer=Case(
When(integer2=F("min"), then=2),
When(integer2=F("max"), then=3),
),
)
.order_by("pk"),
[(3, 4, 3, 4), (2, 2, 2, 3), (3, 4, 3, 4)],
transform=itemgetter("integer", "integer2", "min", "max"),
)
def test_filter_with_aggregation_in_predicate(self):
self.assertQuerySetEqual(
CaseTestModel.objects.values(*self.group_by_fields)
.annotate(
max=Max("fk_rel__integer"),
)
.filter(
integer=Case(
When(max=3, then=2),
When(max=4, then=3),
),
)
.order_by("pk"),
[(2, 3, 3), (3, 4, 4), (2, 2, 3), (3, 4, 4), (3, 3, 4)],
transform=itemgetter("integer", "integer2", "max"),
)
def test_update(self):
CaseTestModel.objects.update(
string=Case(
When(integer=1, then=Value("one")),
When(integer=2, then=Value("two")),
default=Value("other"),
),
)
self.assertQuerySetEqual(
CaseTestModel.objects.order_by("pk"),
[
(1, "one"),
(2, "two"),
(3, "other"),
(2, "two"),
(3, "other"),
(3, "other"),
(4, "other"),
],
transform=attrgetter("integer", "string"),
)
def test_update_without_default(self):
CaseTestModel.objects.update(
integer2=Case(
When(integer=1, then=1),
When(integer=2, then=2),
),
)
self.assertQuerySetEqual(
CaseTestModel.objects.order_by("pk"),
[(1, 1), (2, 2), (3, None), (2, 2), (3, None), (3, None), (4, None)],
transform=attrgetter("integer", "integer2"),
)
def test_update_with_expression_as_value(self):
CaseTestModel.objects.update(
integer=Case(
When(integer=1, then=F("integer") + 1),
When(integer=2, then=F("integer") + 3),
default="integer",
),
)
self.assertQuerySetEqual(
CaseTestModel.objects.order_by("pk"),
[("1", 2), ("2", 5), ("3", 3), ("2", 5), ("3", 3), ("3", 3), ("4", 4)],
transform=attrgetter("string", "integer"),
)
def test_update_with_expression_as_condition(self):
CaseTestModel.objects.update(
string=Case(
When(integer2=F("integer"), then=Value("equal")),
When(integer2=F("integer") + 1, then=Value("+1")),
),
)
self.assertQuerySetEqual(
CaseTestModel.objects.order_by("pk"),
[
(1, "equal"),
(2, "+1"),
(3, "+1"),
(2, "equal"),
(3, "+1"),
(3, "equal"),
(4, "+1"),
],
transform=attrgetter("integer", "string"),
)
def test_update_with_join_in_condition_raise_field_error(self):
with self.assertRaisesMessage(
FieldError, "Joined field references are not permitted in this query"
):
CaseTestModel.objects.update(
integer=Case(
When(integer2=F("o2o_rel__integer") + 1, then=2),
When(integer2=F("o2o_rel__integer"), then=3),
),
)
def test_update_with_join_in_predicate_raise_field_error(self):
with self.assertRaisesMessage(
FieldError, "Joined field references are not permitted in this query"
):
CaseTestModel.objects.update(
string=Case(
When(o2o_rel__integer=1, then=Value("one")),
When(o2o_rel__integer=2, then=Value("two")),
When(o2o_rel__integer=3, then=Value("three")),
default=Value("other"),
),
)
def test_update_big_integer(self):
CaseTestModel.objects.update(
big_integer=Case(
When(integer=1, then=1),
When(integer=2, then=2),
),
)
self.assertQuerySetEqual(
CaseTestModel.objects.order_by("pk"),
[(1, 1), (2, 2), (3, None), (2, 2), (3, None), (3, None), (4, None)],
transform=attrgetter("integer", "big_integer"),
)
def test_update_binary(self):
CaseTestModel.objects.update(
binary=Case(
When(integer=1, then=b"one"),
When(integer=2, then=b"two"),
default=b"",
),
)
self.assertQuerySetEqual(
CaseTestModel.objects.order_by("pk"),
[
(1, b"one"),
(2, b"two"),
(3, b""),
(2, b"two"),
(3, b""),
(3, b""),
(4, b""),
],
transform=lambda o: (o.integer, bytes(o.binary)),
)
def test_update_boolean(self):
CaseTestModel.objects.update(
boolean=Case(
When(integer=1, then=True),
When(integer=2, then=True),
default=False,
),
)
self.assertQuerySetEqual(
CaseTestModel.objects.order_by("pk"),
[
(1, True),
(2, True),
(3, False),
(2, True),
(3, False),
(3, False),
(4, False),
],
transform=attrgetter("integer", "boolean"),
)
def test_update_date(self):
CaseTestModel.objects.update(
date=Case(
When(integer=1, then=date(2015, 1, 1)),
When(integer=2, then=date(2015, 1, 2)),
),
)
self.assertQuerySetEqual(
CaseTestModel.objects.order_by("pk"),
[
(1, date(2015, 1, 1)),
(2, date(2015, 1, 2)),
(3, None),
(2, date(2015, 1, 2)),
(3, None),
(3, None),
(4, None),
],
transform=attrgetter("integer", "date"),
)
def test_update_date_time(self):
CaseTestModel.objects.update(
date_time=Case(
When(integer=1, then=datetime(2015, 1, 1)),
When(integer=2, then=datetime(2015, 1, 2)),
),
)
self.assertQuerySetEqual(
CaseTestModel.objects.order_by("pk"),
[
(1, datetime(2015, 1, 1)),
(2, datetime(2015, 1, 2)),
(3, None),
(2, datetime(2015, 1, 2)),
(3, None),
(3, None),
(4, None),
],
transform=attrgetter("integer", "date_time"),
)
def test_update_decimal(self):
CaseTestModel.objects.update(
decimal=Case(
When(integer=1, then=Decimal("1.1")),
When(
integer=2, then=Value(Decimal("2.2"), output_field=DecimalField())
),
),
)
self.assertQuerySetEqual(
CaseTestModel.objects.order_by("pk"),
[
(1, Decimal("1.1")),
(2, Decimal("2.2")),
(3, None),
(2, Decimal("2.2")),
(3, None),
(3, None),
(4, None),
],
transform=attrgetter("integer", "decimal"),
)
def test_update_duration(self):
CaseTestModel.objects.update(
duration=Case(
When(integer=1, then=timedelta(1)),
When(integer=2, then=timedelta(2)),
),
)
self.assertQuerySetEqual(
CaseTestModel.objects.order_by("pk"),
[
(1, timedelta(1)),
(2, timedelta(2)),
(3, None),
(2, timedelta(2)),
(3, None),
(3, None),
(4, None),
],
transform=attrgetter("integer", "duration"),
)
def test_update_email(self):
CaseTestModel.objects.update(
email=Case(
When(integer=1, then=Value("1@example.com")),
When(integer=2, then=Value("2@example.com")),
default=Value(""),
),
)
self.assertQuerySetEqual(
CaseTestModel.objects.order_by("pk"),
[
(1, "1@example.com"),
(2, "2@example.com"),
(3, ""),
(2, "2@example.com"),
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | true |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/multiple_database/models.py | tests/multiple_database/models.py | from django.contrib.auth.models import User
from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
from django.contrib.contenttypes.models import ContentType
from django.db import models
class Review(models.Model):
source = models.CharField(max_length=100)
content_type = models.ForeignKey(ContentType, models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey()
class Meta:
ordering = ("source",)
def __str__(self):
return self.source
class PersonManager(models.Manager):
def get_by_natural_key(self, name):
return self.get(name=name)
class Person(models.Model):
name = models.CharField(max_length=100, unique=True)
objects = PersonManager()
class Meta:
ordering = ("name",)
def __str__(self):
return self.name
# This book manager doesn't do anything interesting; it just
# exists to strip out the 'extra_arg' argument to certain
# calls. This argument is used to establish that the BookManager
# is actually getting used when it should be.
class BookManager(models.Manager):
def create(self, *args, extra_arg=None, **kwargs):
return super().create(*args, **kwargs)
def get_or_create(self, *args, extra_arg=None, **kwargs):
return super().get_or_create(*args, **kwargs)
class Book(models.Model):
title = models.CharField(max_length=100)
published = models.DateField()
authors = models.ManyToManyField(Person)
editor = models.ForeignKey(
Person, models.SET_NULL, null=True, related_name="edited"
)
reviews = GenericRelation(Review)
pages = models.IntegerField(default=100)
objects = BookManager()
class Meta:
ordering = ("title",)
def __str__(self):
return self.title
class Pet(models.Model):
name = models.CharField(max_length=100)
owner = models.ForeignKey(Person, models.CASCADE)
class Meta:
ordering = ("name",)
class UserProfile(models.Model):
user = models.OneToOneField(User, models.SET_NULL, null=True)
flavor = models.CharField(max_length=100)
class Meta:
ordering = ("flavor",)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/multiple_database/__init__.py | tests/multiple_database/__init__.py | python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false | |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/multiple_database/tests.py | tests/multiple_database/tests.py | import datetime
import pickle
from io import StringIO
from operator import attrgetter
from unittest.mock import Mock
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.core import management
from django.db import DEFAULT_DB_ALIAS, router, transaction
from django.db.models import signals
from django.db.utils import ConnectionRouter
from django.test import SimpleTestCase, TestCase, override_settings
from .models import Book, Person, Pet, Review, UserProfile
from .routers import AuthRouter, TestRouter, WriteRouter
class QueryTestCase(TestCase):
databases = {"default", "other"}
def test_db_selection(self):
"Querysets will use the default database by default"
self.assertEqual(Book.objects.db, DEFAULT_DB_ALIAS)
self.assertEqual(Book.objects.all().db, DEFAULT_DB_ALIAS)
self.assertEqual(Book.objects.using("other").db, "other")
self.assertEqual(Book.objects.db_manager("other").db, "other")
self.assertEqual(Book.objects.db_manager("other").all().db, "other")
def test_default_creation(self):
"""
Objects created on the default database don't leak onto other databases
"""
# Create a book on the default database using create()
Book.objects.create(title="Pro Django", published=datetime.date(2008, 12, 16))
# Create a book on the default database using a save
dive = Book()
dive.title = "Dive into Python"
dive.published = datetime.date(2009, 5, 4)
dive.save()
# Book exists on the default database, but not on other database
try:
Book.objects.get(title="Pro Django")
Book.objects.using("default").get(title="Pro Django")
except Book.DoesNotExist:
self.fail('"Pro Django" should exist on default database')
with self.assertRaises(Book.DoesNotExist):
Book.objects.using("other").get(title="Pro Django")
try:
Book.objects.get(title="Dive into Python")
Book.objects.using("default").get(title="Dive into Python")
except Book.DoesNotExist:
self.fail('"Dive into Python" should exist on default database')
with self.assertRaises(Book.DoesNotExist):
Book.objects.using("other").get(title="Dive into Python")
def test_other_creation(self):
"""
Objects created on another database don't leak onto the default
database
"""
# Create a book on the second database
Book.objects.using("other").create(
title="Pro Django", published=datetime.date(2008, 12, 16)
)
# Create a book on the default database using a save
dive = Book()
dive.title = "Dive into Python"
dive.published = datetime.date(2009, 5, 4)
dive.save(using="other")
# Book exists on the default database, but not on other database
try:
Book.objects.using("other").get(title="Pro Django")
except Book.DoesNotExist:
self.fail('"Pro Django" should exist on other database')
with self.assertRaises(Book.DoesNotExist):
Book.objects.get(title="Pro Django")
with self.assertRaises(Book.DoesNotExist):
Book.objects.using("default").get(title="Pro Django")
try:
Book.objects.using("other").get(title="Dive into Python")
except Book.DoesNotExist:
self.fail('"Dive into Python" should exist on other database')
with self.assertRaises(Book.DoesNotExist):
Book.objects.get(title="Dive into Python")
with self.assertRaises(Book.DoesNotExist):
Book.objects.using("default").get(title="Dive into Python")
def test_refresh(self):
dive = Book(title="Dive into Python", published=datetime.date(2009, 5, 4))
dive.save(using="other")
dive2 = Book.objects.using("other").get()
dive2.title = "Dive into Python (on default)"
dive2.save(using="default")
dive.refresh_from_db()
self.assertEqual(dive.title, "Dive into Python")
dive.refresh_from_db(using="default")
self.assertEqual(dive.title, "Dive into Python (on default)")
self.assertEqual(dive._state.db, "default")
def test_refresh_router_instance_hint(self):
router = Mock()
router.db_for_read.return_value = None
book = Book.objects.create(
title="Dive Into Python", published=datetime.date(1957, 10, 12)
)
with self.settings(DATABASE_ROUTERS=[router]):
book.refresh_from_db()
router.db_for_read.assert_called_once_with(Book, instance=book)
def test_basic_queries(self):
"Queries are constrained to a single database"
dive = Book.objects.using("other").create(
title="Dive into Python", published=datetime.date(2009, 5, 4)
)
dive = Book.objects.using("other").get(published=datetime.date(2009, 5, 4))
self.assertEqual(dive.title, "Dive into Python")
with self.assertRaises(Book.DoesNotExist):
Book.objects.using("default").get(published=datetime.date(2009, 5, 4))
dive = Book.objects.using("other").get(title__icontains="dive")
self.assertEqual(dive.title, "Dive into Python")
with self.assertRaises(Book.DoesNotExist):
Book.objects.using("default").get(title__icontains="dive")
dive = Book.objects.using("other").get(title__iexact="dive INTO python")
self.assertEqual(dive.title, "Dive into Python")
with self.assertRaises(Book.DoesNotExist):
Book.objects.using("default").get(title__iexact="dive INTO python")
dive = Book.objects.using("other").get(published__year=2009)
self.assertEqual(dive.title, "Dive into Python")
self.assertEqual(dive.published, datetime.date(2009, 5, 4))
with self.assertRaises(Book.DoesNotExist):
Book.objects.using("default").get(published__year=2009)
years = Book.objects.using("other").dates("published", "year")
self.assertEqual([o.year for o in years], [2009])
years = Book.objects.using("default").dates("published", "year")
self.assertEqual([o.year for o in years], [])
months = Book.objects.using("other").dates("published", "month")
self.assertEqual([o.month for o in months], [5])
months = Book.objects.using("default").dates("published", "month")
self.assertEqual([o.month for o in months], [])
def test_m2m_separation(self):
"M2M fields are constrained to a single database"
# Create a book and author on the default database
pro = Book.objects.create(
title="Pro Django", published=datetime.date(2008, 12, 16)
)
marty = Person.objects.create(name="Marty Alchin")
# Create a book and author on the other database
dive = Book.objects.using("other").create(
title="Dive into Python", published=datetime.date(2009, 5, 4)
)
mark = Person.objects.using("other").create(name="Mark Pilgrim")
# Save the author relations
pro.authors.set([marty])
dive.authors.set([mark])
# Inspect the m2m tables directly.
# There should be 1 entry in each database
self.assertEqual(Book.authors.through.objects.using("default").count(), 1)
self.assertEqual(Book.authors.through.objects.using("other").count(), 1)
# Queries work across m2m joins
self.assertEqual(
list(
Book.objects.using("default")
.filter(authors__name="Marty Alchin")
.values_list("title", flat=True)
),
["Pro Django"],
)
self.assertEqual(
list(
Book.objects.using("other")
.filter(authors__name="Marty Alchin")
.values_list("title", flat=True)
),
[],
)
self.assertEqual(
list(
Book.objects.using("default")
.filter(authors__name="Mark Pilgrim")
.values_list("title", flat=True)
),
[],
)
self.assertEqual(
list(
Book.objects.using("other")
.filter(authors__name="Mark Pilgrim")
.values_list("title", flat=True)
),
["Dive into Python"],
)
# Reget the objects to clear caches
dive = Book.objects.using("other").get(title="Dive into Python")
mark = Person.objects.using("other").get(name="Mark Pilgrim")
# Retrieve related object by descriptor. Related objects should be
# database-bound.
self.assertEqual(
list(dive.authors.values_list("name", flat=True)), ["Mark Pilgrim"]
)
self.assertEqual(
list(mark.book_set.values_list("title", flat=True)),
["Dive into Python"],
)
def test_m2m_forward_operations(self):
"M2M forward manipulations are all constrained to a single DB"
# Create a book and author on the other database
dive = Book.objects.using("other").create(
title="Dive into Python", published=datetime.date(2009, 5, 4)
)
mark = Person.objects.using("other").create(name="Mark Pilgrim")
# Save the author relations
dive.authors.set([mark])
# Add a second author
john = Person.objects.using("other").create(name="John Smith")
self.assertEqual(
list(
Book.objects.using("other")
.filter(authors__name="John Smith")
.values_list("title", flat=True)
),
[],
)
dive.authors.add(john)
self.assertEqual(
list(
Book.objects.using("other")
.filter(authors__name="Mark Pilgrim")
.values_list("title", flat=True)
),
["Dive into Python"],
)
self.assertEqual(
list(
Book.objects.using("other")
.filter(authors__name="John Smith")
.values_list("title", flat=True)
),
["Dive into Python"],
)
# Remove the second author
dive.authors.remove(john)
self.assertEqual(
list(
Book.objects.using("other")
.filter(authors__name="Mark Pilgrim")
.values_list("title", flat=True)
),
["Dive into Python"],
)
self.assertEqual(
list(
Book.objects.using("other")
.filter(authors__name="John Smith")
.values_list("title", flat=True)
),
[],
)
# Clear all authors
dive.authors.clear()
self.assertEqual(
list(
Book.objects.using("other")
.filter(authors__name="Mark Pilgrim")
.values_list("title", flat=True)
),
[],
)
self.assertEqual(
list(
Book.objects.using("other")
.filter(authors__name="John Smith")
.values_list("title", flat=True)
),
[],
)
# Create an author through the m2m interface
dive.authors.create(name="Jane Brown")
self.assertEqual(
list(
Book.objects.using("other")
.filter(authors__name="Mark Pilgrim")
.values_list("title", flat=True)
),
[],
)
self.assertEqual(
list(
Book.objects.using("other")
.filter(authors__name="Jane Brown")
.values_list("title", flat=True)
),
["Dive into Python"],
)
def test_m2m_reverse_operations(self):
"M2M reverse manipulations are all constrained to a single DB"
# Create a book and author on the other database
dive = Book.objects.using("other").create(
title="Dive into Python", published=datetime.date(2009, 5, 4)
)
mark = Person.objects.using("other").create(name="Mark Pilgrim")
# Save the author relations
dive.authors.set([mark])
# Create a second book on the other database
grease = Book.objects.using("other").create(
title="Greasemonkey Hacks", published=datetime.date(2005, 11, 1)
)
# Add a books to the m2m
mark.book_set.add(grease)
self.assertEqual(
list(
Person.objects.using("other")
.filter(book__title="Dive into Python")
.values_list("name", flat=True)
),
["Mark Pilgrim"],
)
self.assertEqual(
list(
Person.objects.using("other")
.filter(book__title="Greasemonkey Hacks")
.values_list("name", flat=True)
),
["Mark Pilgrim"],
)
# Remove a book from the m2m
mark.book_set.remove(grease)
self.assertEqual(
list(
Person.objects.using("other")
.filter(book__title="Dive into Python")
.values_list("name", flat=True)
),
["Mark Pilgrim"],
)
self.assertEqual(
list(
Person.objects.using("other")
.filter(book__title="Greasemonkey Hacks")
.values_list("name", flat=True)
),
[],
)
# Clear the books associated with mark
mark.book_set.clear()
self.assertEqual(
list(
Person.objects.using("other")
.filter(book__title="Dive into Python")
.values_list("name", flat=True)
),
[],
)
self.assertEqual(
list(
Person.objects.using("other")
.filter(book__title="Greasemonkey Hacks")
.values_list("name", flat=True)
),
[],
)
# Create a book through the m2m interface
mark.book_set.create(
title="Dive into HTML5", published=datetime.date(2020, 1, 1)
)
self.assertEqual(
list(
Person.objects.using("other")
.filter(book__title="Dive into Python")
.values_list("name", flat=True)
),
[],
)
self.assertEqual(
list(
Person.objects.using("other")
.filter(book__title="Dive into HTML5")
.values_list("name", flat=True)
),
["Mark Pilgrim"],
)
def test_m2m_cross_database_protection(self):
"""
Operations that involve sharing M2M objects across databases raise an
error
"""
# Create a book and author on the default database
pro = Book.objects.create(
title="Pro Django", published=datetime.date(2008, 12, 16)
)
marty = Person.objects.create(name="Marty Alchin")
# Create a book and author on the other database
dive = Book.objects.using("other").create(
title="Dive into Python", published=datetime.date(2009, 5, 4)
)
mark = Person.objects.using("other").create(name="Mark Pilgrim")
# Set a foreign key set with an object from a different database
msg = (
'Cannot assign "<Person: Marty Alchin>": the current database '
"router prevents this relation."
)
with self.assertRaisesMessage(ValueError, msg):
with transaction.atomic(using="default"):
marty.edited.set([pro, dive])
# Add to an m2m with an object from a different database
msg = (
'Cannot add "<Book: Dive into Python>": instance is on '
'database "default", value is on database "other"'
)
with self.assertRaisesMessage(ValueError, msg):
with transaction.atomic(using="default"):
marty.book_set.add(dive)
# Set a m2m with an object from a different database
with self.assertRaisesMessage(ValueError, msg):
with transaction.atomic(using="default"):
marty.book_set.set([pro, dive])
# Add to a reverse m2m with an object from a different database
msg = (
'Cannot add "<Person: Marty Alchin>": instance is on '
'database "other", value is on database "default"'
)
with self.assertRaisesMessage(ValueError, msg):
with transaction.atomic(using="other"):
dive.authors.add(marty)
# Set a reverse m2m with an object from a different database
with self.assertRaisesMessage(ValueError, msg):
with transaction.atomic(using="other"):
dive.authors.set([mark, marty])
def test_m2m_deletion(self):
"""
Cascaded deletions of m2m relations issue queries on the right database
"""
# Create a book and author on the other database
dive = Book.objects.using("other").create(
title="Dive into Python", published=datetime.date(2009, 5, 4)
)
mark = Person.objects.using("other").create(name="Mark Pilgrim")
dive.authors.set([mark])
# Check the initial state
self.assertEqual(Person.objects.using("default").count(), 0)
self.assertEqual(Book.objects.using("default").count(), 0)
self.assertEqual(Book.authors.through.objects.using("default").count(), 0)
self.assertEqual(Person.objects.using("other").count(), 1)
self.assertEqual(Book.objects.using("other").count(), 1)
self.assertEqual(Book.authors.through.objects.using("other").count(), 1)
# Delete the object on the other database
dive.delete(using="other")
self.assertEqual(Person.objects.using("default").count(), 0)
self.assertEqual(Book.objects.using("default").count(), 0)
self.assertEqual(Book.authors.through.objects.using("default").count(), 0)
# The person still exists ...
self.assertEqual(Person.objects.using("other").count(), 1)
# ... but the book has been deleted
self.assertEqual(Book.objects.using("other").count(), 0)
# ... and the relationship object has also been deleted.
self.assertEqual(Book.authors.through.objects.using("other").count(), 0)
# Now try deletion in the reverse direction. Set up the relation again
dive = Book.objects.using("other").create(
title="Dive into Python", published=datetime.date(2009, 5, 4)
)
dive.authors.set([mark])
# Check the initial state
self.assertEqual(Person.objects.using("default").count(), 0)
self.assertEqual(Book.objects.using("default").count(), 0)
self.assertEqual(Book.authors.through.objects.using("default").count(), 0)
self.assertEqual(Person.objects.using("other").count(), 1)
self.assertEqual(Book.objects.using("other").count(), 1)
self.assertEqual(Book.authors.through.objects.using("other").count(), 1)
# Delete the object on the other database
mark.delete(using="other")
self.assertEqual(Person.objects.using("default").count(), 0)
self.assertEqual(Book.objects.using("default").count(), 0)
self.assertEqual(Book.authors.through.objects.using("default").count(), 0)
# The person has been deleted ...
self.assertEqual(Person.objects.using("other").count(), 0)
# ... but the book still exists
self.assertEqual(Book.objects.using("other").count(), 1)
# ... and the relationship object has been deleted.
self.assertEqual(Book.authors.through.objects.using("other").count(), 0)
def test_foreign_key_separation(self):
"FK fields are constrained to a single database"
# Create a book and author on the default database
pro = Book.objects.create(
title="Pro Django", published=datetime.date(2008, 12, 16)
)
george = Person.objects.create(name="George Vilches")
# Create a book and author on the other database
dive = Book.objects.using("other").create(
title="Dive into Python", published=datetime.date(2009, 5, 4)
)
chris = Person.objects.using("other").create(name="Chris Mills")
# Save the author's favorite books
pro.editor = george
pro.save()
dive.editor = chris
dive.save()
pro = Book.objects.using("default").get(title="Pro Django")
self.assertEqual(pro.editor.name, "George Vilches")
dive = Book.objects.using("other").get(title="Dive into Python")
self.assertEqual(dive.editor.name, "Chris Mills")
# Queries work across foreign key joins
self.assertEqual(
list(
Person.objects.using("default")
.filter(edited__title="Pro Django")
.values_list("name", flat=True)
),
["George Vilches"],
)
self.assertEqual(
list(
Person.objects.using("other")
.filter(edited__title="Pro Django")
.values_list("name", flat=True)
),
[],
)
self.assertEqual(
list(
Person.objects.using("default")
.filter(edited__title="Dive into Python")
.values_list("name", flat=True)
),
[],
)
self.assertEqual(
list(
Person.objects.using("other")
.filter(edited__title="Dive into Python")
.values_list("name", flat=True)
),
["Chris Mills"],
)
# Reget the objects to clear caches
chris = Person.objects.using("other").get(name="Chris Mills")
dive = Book.objects.using("other").get(title="Dive into Python")
# Retrieve related object by descriptor. Related objects should be
# database-bound.
self.assertEqual(
list(chris.edited.values_list("title", flat=True)), ["Dive into Python"]
)
def test_foreign_key_reverse_operations(self):
"FK reverse manipulations are all constrained to a single DB"
dive = Book.objects.using("other").create(
title="Dive into Python", published=datetime.date(2009, 5, 4)
)
chris = Person.objects.using("other").create(name="Chris Mills")
# Save the author relations
dive.editor = chris
dive.save()
# Add a second book edited by chris
html5 = Book.objects.using("other").create(
title="Dive into HTML5", published=datetime.date(2010, 3, 15)
)
self.assertEqual(
list(
Person.objects.using("other")
.filter(edited__title="Dive into HTML5")
.values_list("name", flat=True)
),
[],
)
chris.edited.add(html5)
self.assertEqual(
list(
Person.objects.using("other")
.filter(edited__title="Dive into HTML5")
.values_list("name", flat=True)
),
["Chris Mills"],
)
self.assertEqual(
list(
Person.objects.using("other")
.filter(edited__title="Dive into Python")
.values_list("name", flat=True)
),
["Chris Mills"],
)
# Remove the second editor
chris.edited.remove(html5)
self.assertEqual(
list(
Person.objects.using("other")
.filter(edited__title="Dive into HTML5")
.values_list("name", flat=True)
),
[],
)
self.assertEqual(
list(
Person.objects.using("other")
.filter(edited__title="Dive into Python")
.values_list("name", flat=True)
),
["Chris Mills"],
)
# Clear all edited books
chris.edited.clear()
self.assertEqual(
list(
Person.objects.using("other")
.filter(edited__title="Dive into HTML5")
.values_list("name", flat=True)
),
[],
)
self.assertEqual(
list(
Person.objects.using("other")
.filter(edited__title="Dive into Python")
.values_list("name", flat=True)
),
[],
)
# Create an author through the m2m interface
chris.edited.create(
title="Dive into Water", published=datetime.date(2010, 3, 15)
)
self.assertEqual(
list(
Person.objects.using("other")
.filter(edited__title="Dive into HTML5")
.values_list("name", flat=True)
),
[],
)
self.assertEqual(
list(
Person.objects.using("other")
.filter(edited__title="Dive into Water")
.values_list("name", flat=True)
),
["Chris Mills"],
)
self.assertEqual(
list(
Person.objects.using("other")
.filter(edited__title="Dive into Python")
.values_list("name", flat=True)
),
[],
)
def test_foreign_key_cross_database_protection(self):
"""
Operations that involve sharing FK objects across databases raise an
error
"""
# Create a book and author on the default database
pro = Book.objects.create(
title="Pro Django", published=datetime.date(2008, 12, 16)
)
marty = Person.objects.create(name="Marty Alchin")
# Create a book and author on the other database
dive = Book.objects.using("other").create(
title="Dive into Python", published=datetime.date(2009, 5, 4)
)
# Set a foreign key with an object from a different database
msg = (
'Cannot assign "<Person: Marty Alchin>": the current database '
"router prevents this relation."
)
with self.assertRaisesMessage(ValueError, msg):
dive.editor = marty
# Set a foreign key set with an object from a different database
with self.assertRaisesMessage(ValueError, msg):
with transaction.atomic(using="default"):
marty.edited.set([pro, dive])
# Add to a foreign key set with an object from a different database
with self.assertRaisesMessage(ValueError, msg):
with transaction.atomic(using="default"):
marty.edited.add(dive)
def test_foreign_key_deletion(self):
"""
Cascaded deletions of Foreign Key relations issue queries on the right
database.
"""
mark = Person.objects.using("other").create(name="Mark Pilgrim")
Pet.objects.using("other").create(name="Fido", owner=mark)
# Check the initial state
self.assertEqual(Person.objects.using("default").count(), 0)
self.assertEqual(Pet.objects.using("default").count(), 0)
self.assertEqual(Person.objects.using("other").count(), 1)
self.assertEqual(Pet.objects.using("other").count(), 1)
# Delete the person object, which will cascade onto the pet
mark.delete(using="other")
self.assertEqual(Person.objects.using("default").count(), 0)
self.assertEqual(Pet.objects.using("default").count(), 0)
# Both the pet and the person have been deleted from the right database
self.assertEqual(Person.objects.using("other").count(), 0)
self.assertEqual(Pet.objects.using("other").count(), 0)
def test_foreign_key_validation(self):
"ForeignKey.validate() uses the correct database"
mickey = Person.objects.using("other").create(name="Mickey")
pluto = Pet.objects.using("other").create(name="Pluto", owner=mickey)
self.assertIsNone(pluto.full_clean())
# Any router that accesses `model` in db_for_read() works here.
@override_settings(DATABASE_ROUTERS=[AuthRouter()])
def test_foreign_key_validation_with_router(self):
"""
ForeignKey.validate() passes `model` to db_for_read() even if
model_instance=None.
"""
mickey = Person.objects.create(name="Mickey")
owner_field = Pet._meta.get_field("owner")
self.assertEqual(owner_field.clean(mickey.pk, None), mickey.pk)
def test_o2o_separation(self):
"OneToOne fields are constrained to a single database"
# Create a user and profile on the default database
alice = User.objects.db_manager("default").create_user(
"alice", "alice@example.com"
)
alice_profile = UserProfile.objects.using("default").create(
user=alice, flavor="chocolate"
)
# Create a user and profile on the other database
bob = User.objects.db_manager("other").create_user("bob", "bob@example.com")
bob_profile = UserProfile.objects.using("other").create(
user=bob, flavor="crunchy frog"
)
# Retrieve related objects; queries should be database constrained
alice = User.objects.using("default").get(username="alice")
self.assertEqual(alice.userprofile.flavor, "chocolate")
bob = User.objects.using("other").get(username="bob")
self.assertEqual(bob.userprofile.flavor, "crunchy frog")
# Queries work across joins
self.assertEqual(
list(
User.objects.using("default")
.filter(userprofile__flavor="chocolate")
.values_list("username", flat=True)
),
["alice"],
)
self.assertEqual(
list(
User.objects.using("other")
.filter(userprofile__flavor="chocolate")
.values_list("username", flat=True)
),
[],
)
self.assertEqual(
list(
User.objects.using("default")
.filter(userprofile__flavor="crunchy frog")
.values_list("username", flat=True)
),
[],
)
self.assertEqual(
list(
User.objects.using("other")
.filter(userprofile__flavor="crunchy frog")
.values_list("username", flat=True)
),
["bob"],
)
# Reget the objects to clear caches
alice_profile = UserProfile.objects.using("default").get(flavor="chocolate")
bob_profile = UserProfile.objects.using("other").get(flavor="crunchy frog")
# Retrieve related object by descriptor. Related objects should be
# database-bound.
self.assertEqual(alice_profile.user.username, "alice")
self.assertEqual(bob_profile.user.username, "bob")
def test_o2o_cross_database_protection(self):
"""
Operations that involve sharing FK objects across databases raise an
error
"""
# Create a user and profile on the default database
alice = User.objects.db_manager("default").create_user(
"alice", "alice@example.com"
)
# Create a user and profile on the other database
bob = User.objects.db_manager("other").create_user("bob", "bob@example.com")
# Set a one-to-one relation with an object from a different database
alice_profile = UserProfile.objects.using("default").create(
user=alice, flavor="chocolate"
)
msg = (
'Cannot assign "%r": the current database router prevents this '
"relation." % alice_profile
)
with self.assertRaisesMessage(ValueError, msg):
bob.userprofile = alice_profile
# BUT! if you assign a FK object when the base object hasn't
# been saved yet, you implicitly assign the database for the
# base object.
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | true |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/multiple_database/routers.py | tests/multiple_database/routers.py | from django.db import DEFAULT_DB_ALIAS
class TestRouter:
"""
Vaguely behave like primary/replica, but the databases aren't assumed to
propagate changes.
"""
def db_for_read(self, model, instance=None, **hints):
if instance:
return instance._state.db or "other"
return "other"
def db_for_write(self, model, **hints):
return DEFAULT_DB_ALIAS
def allow_relation(self, obj1, obj2, **hints):
return obj1._state.db in ("default", "other") and obj2._state.db in (
"default",
"other",
)
def allow_migrate(self, db, app_label, **hints):
return True
class AuthRouter:
"""
Control all database operations on models in the contrib.auth application.
"""
def db_for_read(self, model, **hints):
"Point all read operations on auth models to 'default'"
if model._meta.app_label == "auth":
# We use default here to ensure we can tell the difference
# between a read request and a write request for Auth objects
return "default"
return None
def db_for_write(self, model, **hints):
"Point all operations on auth models to 'other'"
if model._meta.app_label == "auth":
return "other"
return None
def allow_relation(self, obj1, obj2, **hints):
"Allow any relation if a model in Auth is involved"
return obj1._meta.app_label == "auth" or obj2._meta.app_label == "auth" or None
def allow_migrate(self, db, app_label, **hints):
"Make sure the auth app only appears on the 'other' db"
if app_label == "auth":
return db == "other"
return None
class WriteRouter:
# A router that only expresses an opinion on writes
def db_for_write(self, model, **hints):
return "writer"
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/many_to_many/models.py | tests/many_to_many/models.py | """
Many-to-many relationships
To define a many-to-many relationship, use ``ManyToManyField()``.
In this example, an ``Article`` can be published in multiple ``Publication``
objects, and a ``Publication`` has multiple ``Article`` objects.
"""
from django.db import models
class Publication(models.Model):
title = models.CharField(max_length=30)
class Meta:
ordering = ("title",)
def __str__(self):
return self.title
class Tag(models.Model):
id = models.BigAutoField(primary_key=True)
name = models.CharField(max_length=50)
def __str__(self):
return self.name
class NoDeletedArticleManager(models.Manager):
def get_queryset(self):
return super().get_queryset().exclude(headline="deleted")
class Article(models.Model):
headline = models.CharField(max_length=100)
# Assign a string as name to make sure the intermediary model is
# correctly created. Refs #20207
publications = models.ManyToManyField(Publication, name="publications")
tags = models.ManyToManyField(Tag, related_name="tags")
authors = models.ManyToManyField("User", through="UserArticle")
objects = NoDeletedArticleManager()
class Meta:
ordering = ("headline",)
def __str__(self):
return self.headline
class User(models.Model):
username = models.CharField(max_length=20, unique=True)
def __str__(self):
return self.username
class UserArticle(models.Model):
user = models.ForeignKey(User, models.CASCADE, to_field="username")
article = models.ForeignKey(Article, models.CASCADE)
# Models to test correct related_name inheritance
class AbstractArticle(models.Model):
class Meta:
abstract = True
publications = models.ManyToManyField(
Publication, name="publications", related_name="+"
)
class InheritedArticleA(AbstractArticle):
pass
class InheritedArticleB(AbstractArticle):
pass
class NullableTargetArticle(models.Model):
headline = models.CharField(max_length=100)
publications = models.ManyToManyField(
Publication, through="NullablePublicationThrough"
)
class NullablePublicationThrough(models.Model):
article = models.ForeignKey(NullableTargetArticle, models.CASCADE)
publication = models.ForeignKey(Publication, models.CASCADE, null=True)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/many_to_many/__init__.py | tests/many_to_many/__init__.py | python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false | |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/many_to_many/tests.py | tests/many_to_many/tests.py | from unittest import mock
from django.db import connection, transaction
from django.db.models import FETCH_PEERS
from django.test import TestCase, skipIfDBFeature, skipUnlessDBFeature
from .models import (
Article,
InheritedArticleA,
InheritedArticleB,
NullablePublicationThrough,
NullableTargetArticle,
Publication,
User,
)
class ManyToManyTests(TestCase):
@classmethod
def setUpTestData(cls):
# Create a couple of Publications.
cls.p1 = Publication.objects.create(title="The Python Journal")
cls.p2 = Publication.objects.create(title="Science News")
cls.p3 = Publication.objects.create(title="Science Weekly")
cls.p4 = Publication.objects.create(title="Highlights for Children")
cls.a1 = Article.objects.create(
headline="Django lets you build web apps easily"
)
cls.a1.publications.add(cls.p1)
cls.a2 = Article.objects.create(headline="NASA uses Python")
cls.a2.publications.add(cls.p1, cls.p2, cls.p3, cls.p4)
cls.a3 = Article.objects.create(headline="NASA finds intelligent life on Earth")
cls.a3.publications.add(cls.p2)
cls.a4 = Article.objects.create(headline="Oxygen-free diet works wonders")
cls.a4.publications.add(cls.p2)
def test_add(self):
# Create an Article.
a5 = Article(headline="Django lets you create web apps easily")
# You can't associate it with a Publication until it's been saved.
msg = (
'"<Article: Django lets you create web apps easily>" needs to have '
'a value for field "id" before this many-to-many relationship can be used.'
)
with self.assertRaisesMessage(ValueError, msg):
getattr(a5, "publications")
# Save it!
a5.save()
# Associate the Article with a Publication.
a5.publications.add(self.p1)
self.assertSequenceEqual(a5.publications.all(), [self.p1])
# Create another Article, and set it to appear in both Publications.
a6 = Article(headline="ESA uses Python")
a6.save()
a6.publications.add(self.p1, self.p2)
a6.publications.add(self.p3)
# Adding a second time is OK
a6.publications.add(self.p3)
self.assertSequenceEqual(
a6.publications.all(),
[self.p2, self.p3, self.p1],
)
# Adding an object of the wrong type raises TypeError
msg = (
"'Publication' instance expected, got <Article: Django lets you create web "
"apps easily>"
)
with self.assertRaisesMessage(TypeError, msg):
with transaction.atomic():
a6.publications.add(a5)
# Add a Publication directly via publications.add by using keyword
# arguments.
p5 = a6.publications.create(title="Highlights for Adults")
self.assertSequenceEqual(
a6.publications.all(),
[p5, self.p2, self.p3, self.p1],
)
def test_add_remove_set_by_pk(self):
a5 = Article.objects.create(headline="Django lets you create web apps easily")
a5.publications.add(self.p1.pk)
self.assertSequenceEqual(a5.publications.all(), [self.p1])
a5.publications.set([self.p2.pk])
self.assertSequenceEqual(a5.publications.all(), [self.p2])
a5.publications.remove(self.p2.pk)
self.assertSequenceEqual(a5.publications.all(), [])
def test_add_remove_set_by_to_field(self):
user_1 = User.objects.create(username="Jean")
user_2 = User.objects.create(username="Joe")
a5 = Article.objects.create(headline="Django lets you create web apps easily")
a5.authors.add(user_1.username)
self.assertSequenceEqual(a5.authors.all(), [user_1])
a5.authors.set([user_2.username])
self.assertSequenceEqual(a5.authors.all(), [user_2])
a5.authors.remove(user_2.username)
self.assertSequenceEqual(a5.authors.all(), [])
def test_related_manager_refresh(self):
user_1 = User.objects.create(username="Jean")
user_2 = User.objects.create(username="Joe")
self.a3.authors.add(user_1.username)
self.assertSequenceEqual(user_1.article_set.all(), [self.a3])
# Change the username on a different instance of the same user.
user_1_from_db = User.objects.get(pk=user_1.pk)
self.assertSequenceEqual(user_1_from_db.article_set.all(), [self.a3])
user_1_from_db.username = "Paul"
self.a3.authors.set([user_2.username])
user_1_from_db.save()
# Assign a different article.
self.a4.authors.add(user_1_from_db.username)
self.assertSequenceEqual(user_1_from_db.article_set.all(), [self.a4])
# Refresh the instance with an evaluated related manager.
user_1.refresh_from_db()
self.assertEqual(user_1.username, "Paul")
self.assertSequenceEqual(user_1.article_set.all(), [self.a4])
def test_add_remove_invalid_type(self):
msg = "Field 'id' expected a number but got 'invalid'."
for method in ["add", "remove"]:
with self.subTest(method), self.assertRaisesMessage(ValueError, msg):
getattr(self.a1.publications, method)("invalid")
def test_reverse_add(self):
# Adding via the 'other' end of an m2m
a5 = Article(headline="NASA finds intelligent life on Mars")
a5.save()
self.p2.article_set.add(a5)
self.assertSequenceEqual(
self.p2.article_set.all(),
[self.a3, a5, self.a2, self.a4],
)
self.assertSequenceEqual(a5.publications.all(), [self.p2])
# Adding via the other end using keywords
a6 = self.p2.article_set.create(headline="Carbon-free diet works wonders")
self.assertSequenceEqual(
self.p2.article_set.all(),
[a6, self.a3, a5, self.a2, self.a4],
)
a6 = self.p2.article_set.all()[3]
self.assertSequenceEqual(
a6.publications.all(),
[self.p4, self.p2, self.p3, self.p1],
)
@skipUnlessDBFeature("supports_ignore_conflicts")
def test_fast_add_ignore_conflicts(self):
"""
A single query is necessary to add auto-created through instances if
the database backend supports bulk_create(ignore_conflicts) and no
m2m_changed signals receivers are connected.
"""
with self.assertNumQueries(1):
self.a1.publications.add(self.p1, self.p2)
@skipIfDBFeature("supports_ignore_conflicts")
def test_add_existing_different_type(self):
# A single SELECT query is necessary to compare existing values to the
# provided one; no INSERT should be attempted.
with self.assertNumQueries(1):
self.a1.publications.add(str(self.p1.pk))
self.assertEqual(self.a1.publications.get(), self.p1)
@skipUnlessDBFeature("supports_ignore_conflicts")
def test_slow_add_ignore_conflicts(self):
manager_cls = self.a1.publications.__class__
# Simulate a race condition between the missing ids retrieval and
# the bulk insertion attempt.
missing_target_ids = {self.p1.id}
# Disable fast-add to test the case where the slow add path is taken.
add_plan = (True, False, False)
with mock.patch.object(
manager_cls, "_get_missing_target_ids", return_value=missing_target_ids
) as mocked:
with mock.patch.object(manager_cls, "_get_add_plan", return_value=add_plan):
self.a1.publications.add(self.p1)
mocked.assert_called_once()
def test_related_sets(self):
# Article objects have access to their related Publication objects.
self.assertSequenceEqual(self.a1.publications.all(), [self.p1])
self.assertSequenceEqual(
self.a2.publications.all(),
[self.p4, self.p2, self.p3, self.p1],
)
# Publication objects have access to their related Article objects.
self.assertSequenceEqual(
self.p2.article_set.all(),
[self.a3, self.a2, self.a4],
)
self.assertSequenceEqual(
self.p1.article_set.all(),
[self.a1, self.a2],
)
self.assertSequenceEqual(
Publication.objects.get(id=self.p4.id).article_set.all(),
[self.a2],
)
def test_selects(self):
# We can perform kwarg queries across m2m relationships
self.assertSequenceEqual(
Article.objects.filter(publications__id__exact=self.p1.id),
[self.a1, self.a2],
)
self.assertSequenceEqual(
Article.objects.filter(publications__pk=self.p1.id),
[self.a1, self.a2],
)
self.assertSequenceEqual(
Article.objects.filter(publications=self.p1.id),
[self.a1, self.a2],
)
self.assertSequenceEqual(
Article.objects.filter(publications=self.p1),
[self.a1, self.a2],
)
self.assertSequenceEqual(
Article.objects.filter(publications__title__startswith="Science"),
[self.a3, self.a2, self.a2, self.a4],
)
self.assertSequenceEqual(
Article.objects.filter(
publications__title__startswith="Science"
).distinct(),
[self.a3, self.a2, self.a4],
)
# The count() function respects distinct() as well.
self.assertEqual(
Article.objects.filter(publications__title__startswith="Science").count(), 4
)
self.assertEqual(
Article.objects.filter(publications__title__startswith="Science")
.distinct()
.count(),
3,
)
self.assertSequenceEqual(
Article.objects.filter(
publications__in=[self.p1.id, self.p2.id]
).distinct(),
[self.a1, self.a3, self.a2, self.a4],
)
self.assertSequenceEqual(
Article.objects.filter(publications__in=[self.p1.id, self.p2]).distinct(),
[self.a1, self.a3, self.a2, self.a4],
)
self.assertSequenceEqual(
Article.objects.filter(publications__in=[self.p1, self.p2]).distinct(),
[self.a1, self.a3, self.a2, self.a4],
)
# Excluding a related item works as you would expect, too (although the
# SQL involved is a little complex).
self.assertSequenceEqual(
Article.objects.exclude(publications=self.p2),
[self.a1],
)
def test_reverse_selects(self):
# Reverse m2m queries are supported (i.e., starting at the table that
# doesn't have a ManyToManyField).
python_journal = [self.p1]
self.assertSequenceEqual(
Publication.objects.filter(id__exact=self.p1.id), python_journal
)
self.assertSequenceEqual(
Publication.objects.filter(pk=self.p1.id), python_journal
)
self.assertSequenceEqual(
Publication.objects.filter(article__headline__startswith="NASA"),
[self.p4, self.p2, self.p2, self.p3, self.p1],
)
self.assertSequenceEqual(
Publication.objects.filter(article__id__exact=self.a1.id), python_journal
)
self.assertSequenceEqual(
Publication.objects.filter(article__pk=self.a1.id), python_journal
)
self.assertSequenceEqual(
Publication.objects.filter(article=self.a1.id), python_journal
)
self.assertSequenceEqual(
Publication.objects.filter(article=self.a1), python_journal
)
self.assertSequenceEqual(
Publication.objects.filter(article__in=[self.a1.id, self.a2.id]).distinct(),
[self.p4, self.p2, self.p3, self.p1],
)
self.assertSequenceEqual(
Publication.objects.filter(article__in=[self.a1.id, self.a2]).distinct(),
[self.p4, self.p2, self.p3, self.p1],
)
self.assertSequenceEqual(
Publication.objects.filter(article__in=[self.a1, self.a2]).distinct(),
[self.p4, self.p2, self.p3, self.p1],
)
def test_delete(self):
# If we delete a Publication, its Articles won't be able to access it.
self.p1.delete()
self.assertSequenceEqual(
Publication.objects.all(),
[self.p4, self.p2, self.p3],
)
self.assertSequenceEqual(self.a1.publications.all(), [])
# If we delete an Article, its Publications won't be able to access it.
self.a2.delete()
self.assertSequenceEqual(
Article.objects.all(),
[self.a1, self.a3, self.a4],
)
self.assertSequenceEqual(
self.p2.article_set.all(),
[self.a3, self.a4],
)
def test_bulk_delete(self):
# Bulk delete some Publications - references to deleted publications
# should go
Publication.objects.filter(title__startswith="Science").delete()
self.assertSequenceEqual(
Publication.objects.all(),
[self.p4, self.p1],
)
self.assertSequenceEqual(
Article.objects.all(),
[self.a1, self.a3, self.a2, self.a4],
)
self.assertSequenceEqual(
self.a2.publications.all(),
[self.p4, self.p1],
)
# Bulk delete some articles - references to deleted objects should go
q = Article.objects.filter(headline__startswith="Django")
self.assertSequenceEqual(q, [self.a1])
q.delete()
# After the delete, the QuerySet cache needs to be cleared,
# and the referenced objects should be gone
self.assertSequenceEqual(q, [])
self.assertSequenceEqual(self.p1.article_set.all(), [self.a2])
def test_remove(self):
# Removing publication from an article:
self.assertSequenceEqual(
self.p2.article_set.all(),
[self.a3, self.a2, self.a4],
)
self.a4.publications.remove(self.p2)
self.assertSequenceEqual(
self.p2.article_set.all(),
[self.a3, self.a2],
)
self.assertSequenceEqual(self.a4.publications.all(), [])
# And from the other end
self.p2.article_set.remove(self.a3)
self.assertSequenceEqual(self.p2.article_set.all(), [self.a2])
self.assertSequenceEqual(self.a3.publications.all(), [])
def test_set(self):
self.p2.article_set.set([self.a4, self.a3])
self.assertSequenceEqual(
self.p2.article_set.all(),
[self.a3, self.a4],
)
self.assertSequenceEqual(self.a4.publications.all(), [self.p2])
self.a4.publications.set([self.p3.id])
self.assertSequenceEqual(self.p2.article_set.all(), [self.a3])
self.assertSequenceEqual(self.a4.publications.all(), [self.p3])
self.p2.article_set.set([])
self.assertSequenceEqual(self.p2.article_set.all(), [])
self.a4.publications.set([])
self.assertSequenceEqual(self.a4.publications.all(), [])
self.p2.article_set.set([self.a4, self.a3], clear=True)
self.assertSequenceEqual(
self.p2.article_set.all(),
[self.a3, self.a4],
)
self.assertSequenceEqual(self.a4.publications.all(), [self.p2])
self.a4.publications.set([self.p3.id], clear=True)
self.assertSequenceEqual(self.p2.article_set.all(), [self.a3])
self.assertSequenceEqual(self.a4.publications.all(), [self.p3])
self.p2.article_set.set([], clear=True)
self.assertSequenceEqual(self.p2.article_set.all(), [])
self.a4.publications.set([], clear=True)
self.assertSequenceEqual(self.a4.publications.all(), [])
def test_set_existing_different_type(self):
# Existing many-to-many relations remain the same for values provided
# with a different type.
ids = set(
Publication.article_set.through.objects.filter(
article__in=[self.a4, self.a3],
publication=self.p2,
).values_list("id", flat=True)
)
self.p2.article_set.set([str(self.a4.pk), str(self.a3.pk)])
new_ids = set(
Publication.article_set.through.objects.filter(
publication=self.p2,
).values_list("id", flat=True)
)
self.assertEqual(ids, new_ids)
def test_assign_forward(self):
msg = (
"Direct assignment to the reverse side of a many-to-many set is "
"prohibited. Use article_set.set() instead."
)
with self.assertRaisesMessage(TypeError, msg):
self.p2.article_set = [self.a4, self.a3]
def test_assign_reverse(self):
msg = (
"Direct assignment to the forward side of a many-to-many "
"set is prohibited. Use publications.set() instead."
)
with self.assertRaisesMessage(TypeError, msg):
self.a1.publications = [self.p1, self.p2]
def test_assign(self):
# Relation sets can be assigned using set().
self.p2.article_set.set([self.a4, self.a3])
self.assertSequenceEqual(
self.p2.article_set.all(),
[self.a3, self.a4],
)
self.assertSequenceEqual(self.a4.publications.all(), [self.p2])
self.a4.publications.set([self.p3.id])
self.assertSequenceEqual(self.p2.article_set.all(), [self.a3])
self.assertSequenceEqual(self.a4.publications.all(), [self.p3])
# An alternate to calling clear() is to set an empty set.
self.p2.article_set.set([])
self.assertSequenceEqual(self.p2.article_set.all(), [])
self.a4.publications.set([])
self.assertSequenceEqual(self.a4.publications.all(), [])
def test_assign_ids(self):
# Relation sets can also be set using primary key values
self.p2.article_set.set([self.a4.id, self.a3.id])
self.assertSequenceEqual(
self.p2.article_set.all(),
[self.a3, self.a4],
)
self.assertSequenceEqual(self.a4.publications.all(), [self.p2])
self.a4.publications.set([self.p3.id])
self.assertSequenceEqual(self.p2.article_set.all(), [self.a3])
self.assertSequenceEqual(self.a4.publications.all(), [self.p3])
def test_forward_assign_with_queryset(self):
# Querysets used in m2m assignments are pre-evaluated so their value
# isn't affected by the clearing operation in ManyRelatedManager.set()
# (#19816).
self.a1.publications.set([self.p1, self.p2])
qs = self.a1.publications.filter(title="The Python Journal")
self.a1.publications.set(qs)
self.assertEqual(1, self.a1.publications.count())
self.assertEqual(1, qs.count())
def test_reverse_assign_with_queryset(self):
# Querysets used in M2M assignments are pre-evaluated so their value
# isn't affected by the clearing operation in ManyRelatedManager.set()
# (#19816).
self.p1.article_set.set([self.a1, self.a2])
qs = self.p1.article_set.filter(
headline="Django lets you build web apps easily"
)
self.p1.article_set.set(qs)
self.assertEqual(1, self.p1.article_set.count())
self.assertEqual(1, qs.count())
def test_clear(self):
# Relation sets can be cleared:
self.p2.article_set.clear()
self.assertSequenceEqual(self.p2.article_set.all(), [])
self.assertSequenceEqual(self.a4.publications.all(), [])
# And you can clear from the other end
self.p2.article_set.add(self.a3, self.a4)
self.assertSequenceEqual(
self.p2.article_set.all(),
[self.a3, self.a4],
)
self.assertSequenceEqual(self.a4.publications.all(), [self.p2])
self.a4.publications.clear()
self.assertSequenceEqual(self.a4.publications.all(), [])
self.assertSequenceEqual(self.p2.article_set.all(), [self.a3])
def test_clear_after_prefetch(self):
a4 = Article.objects.prefetch_related("publications").get(id=self.a4.id)
self.assertSequenceEqual(a4.publications.all(), [self.p2])
a4.publications.clear()
self.assertSequenceEqual(a4.publications.all(), [])
def test_remove_after_prefetch(self):
a4 = Article.objects.prefetch_related("publications").get(id=self.a4.id)
self.assertSequenceEqual(a4.publications.all(), [self.p2])
a4.publications.remove(self.p2)
self.assertSequenceEqual(a4.publications.all(), [])
def test_add_after_prefetch(self):
a4 = Article.objects.prefetch_related("publications").get(id=self.a4.id)
self.assertEqual(a4.publications.count(), 1)
a4.publications.add(self.p1)
self.assertEqual(a4.publications.count(), 2)
def test_create_after_prefetch(self):
a4 = Article.objects.prefetch_related("publications").get(id=self.a4.id)
self.assertSequenceEqual(a4.publications.all(), [self.p2])
p5 = a4.publications.create(title="Django beats")
self.assertCountEqual(a4.publications.all(), [self.p2, p5])
def test_set_after_prefetch(self):
a4 = Article.objects.prefetch_related("publications").get(id=self.a4.id)
self.assertEqual(a4.publications.count(), 1)
a4.publications.set([self.p2, self.p1])
self.assertEqual(a4.publications.count(), 2)
a4.publications.set([self.p1])
self.assertEqual(a4.publications.count(), 1)
def test_add_then_remove_after_prefetch(self):
a4 = Article.objects.prefetch_related("publications").get(id=self.a4.id)
self.assertEqual(a4.publications.count(), 1)
a4.publications.add(self.p1)
self.assertEqual(a4.publications.count(), 2)
a4.publications.remove(self.p1)
self.assertSequenceEqual(a4.publications.all(), [self.p2])
def test_inherited_models_selects(self):
"""
#24156 - Objects from child models where the parent's m2m field uses
related_name='+' should be retrieved correctly.
"""
a = InheritedArticleA.objects.create()
b = InheritedArticleB.objects.create()
a.publications.add(self.p1, self.p2)
self.assertSequenceEqual(
a.publications.all(),
[self.p2, self.p1],
)
self.assertSequenceEqual(b.publications.all(), [])
b.publications.add(self.p3)
self.assertSequenceEqual(
a.publications.all(),
[self.p2, self.p1],
)
self.assertSequenceEqual(b.publications.all(), [self.p3])
def test_custom_default_manager_exists_count(self):
a5 = Article.objects.create(headline="deleted")
a5.publications.add(self.p2)
with self.assertNumQueries(2) as ctx:
self.assertEqual(
self.p2.article_set.count(), self.p2.article_set.all().count()
)
self.assertIn("JOIN", ctx.captured_queries[0]["sql"])
with self.assertNumQueries(2) as ctx:
self.assertEqual(
self.p3.article_set.exists(), self.p3.article_set.all().exists()
)
self.assertIn("JOIN", ctx.captured_queries[0]["sql"])
def test_get_prefetch_querysets_invalid_querysets_length(self):
articles = Article.objects.all()
msg = (
"querysets argument of get_prefetch_querysets() should have a length of 1."
)
with self.assertRaisesMessage(ValueError, msg):
self.a1.publications.get_prefetch_querysets(
instances=articles,
querysets=[Publication.objects.all(), Publication.objects.all()],
)
def test_fetch_mode_copied_forward_fetching_one(self):
a = Article.objects.fetch_mode(FETCH_PEERS).get(pk=self.a1.pk)
self.assertEqual(a._state.fetch_mode, FETCH_PEERS)
p = a.publications.earliest("pk")
self.assertEqual(
p._state.fetch_mode,
FETCH_PEERS,
)
def test_fetch_mode_copied_forward_fetching_many(self):
articles = list(Article.objects.fetch_mode(FETCH_PEERS))
a = articles[0]
self.assertEqual(a._state.fetch_mode, FETCH_PEERS)
publications = list(a.publications.all())
p = publications[0]
self.assertEqual(
p._state.fetch_mode,
FETCH_PEERS,
)
def test_fetch_mode_copied_reverse_fetching_one(self):
p1 = Publication.objects.fetch_mode(FETCH_PEERS).get(pk=self.p1.pk)
self.assertEqual(p1._state.fetch_mode, FETCH_PEERS)
a = p1.article_set.earliest("pk")
self.assertEqual(
a._state.fetch_mode,
FETCH_PEERS,
)
def test_fetch_mode_copied_reverse_fetching_many(self):
publications = list(Publication.objects.fetch_mode(FETCH_PEERS))
p = publications[0]
self.assertEqual(p._state.fetch_mode, FETCH_PEERS)
articles = list(p.article_set.all())
a = articles[0]
self.assertEqual(
a._state.fetch_mode,
FETCH_PEERS,
)
class ManyToManyQueryTests(TestCase):
"""
SQL is optimized to reference the through table without joining against the
related table when using count() and exists() functions on a queryset for
many to many relations. The optimization applies to the case where there
are no filters.
"""
@classmethod
def setUpTestData(cls):
cls.article = Article.objects.create(
headline="Django lets you build Web apps easily"
)
cls.nullable_target_article = NullableTargetArticle.objects.create(
headline="The python is good"
)
NullablePublicationThrough.objects.create(
article=cls.nullable_target_article, publication=None
)
@skipUnlessDBFeature("supports_foreign_keys")
def test_count_join_optimization(self):
with self.assertNumQueries(1) as ctx:
self.article.publications.count()
self.assertNotIn("JOIN", ctx.captured_queries[0]["sql"])
with self.assertNumQueries(1) as ctx:
self.article.publications.count()
self.assertNotIn("JOIN", ctx.captured_queries[0]["sql"])
self.assertEqual(self.nullable_target_article.publications.count(), 0)
def test_count_join_optimization_disabled(self):
with (
mock.patch.object(connection.features, "supports_foreign_keys", False),
self.assertNumQueries(1) as ctx,
):
self.article.publications.count()
self.assertIn("JOIN", ctx.captured_queries[0]["sql"])
@skipUnlessDBFeature("supports_foreign_keys")
def test_exists_join_optimization(self):
with self.assertNumQueries(1) as ctx:
self.article.publications.exists()
self.assertNotIn("JOIN", ctx.captured_queries[0]["sql"])
self.article.publications.prefetch_related()
with self.assertNumQueries(1) as ctx:
self.article.publications.exists()
self.assertNotIn("JOIN", ctx.captured_queries[0]["sql"])
self.assertIs(self.nullable_target_article.publications.exists(), False)
def test_exists_join_optimization_disabled(self):
with (
mock.patch.object(connection.features, "supports_foreign_keys", False),
self.assertNumQueries(1) as ctx,
):
self.article.publications.exists()
self.assertIn("JOIN", ctx.captured_queries[0]["sql"])
def test_prefetch_related_no_queries_optimization_disabled(self):
qs = Article.objects.prefetch_related("publications")
article = qs.get()
with self.assertNumQueries(0):
article.publications.count()
with self.assertNumQueries(0):
article.publications.exists()
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/m2m_and_m2o/models.py | tests/m2m_and_m2o/models.py | """
Many-to-many and many-to-one relationships to the same table
Make sure to set ``related_name`` if you use relationships to the same table.
"""
from django.db import models
class User(models.Model):
username = models.CharField(max_length=20)
class Issue(models.Model):
num = models.IntegerField()
cc = models.ManyToManyField(User, blank=True, related_name="test_issue_cc")
client = models.ForeignKey(User, models.CASCADE, related_name="test_issue_client")
class Meta:
ordering = ("num",)
def __str__(self):
return str(self.num)
class StringReferenceModel(models.Model):
others = models.ManyToManyField("StringReferenceModel")
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/m2m_and_m2o/__init__.py | tests/m2m_and_m2o/__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_and_m2o/tests.py | tests/m2m_and_m2o/tests.py | from django.db.models import Q
from django.test import TestCase
from .models import Issue, StringReferenceModel, User
class RelatedObjectTests(TestCase):
def test_related_objects_have_name_attribute(self):
for field_name in ("test_issue_client", "test_issue_cc"):
obj = User._meta.get_field(field_name)
self.assertEqual(field_name, obj.field.related_query_name())
def test_m2m_and_m2o(self):
r = User.objects.create(username="russell")
g = User.objects.create(username="gustav")
i1 = Issue(num=1)
i1.client = r
i1.save()
i2 = Issue(num=2)
i2.client = r
i2.save()
i2.cc.add(r)
i3 = Issue(num=3)
i3.client = g
i3.save()
i3.cc.add(r)
self.assertQuerySetEqual(
Issue.objects.filter(client=r.id),
[
1,
2,
],
lambda i: i.num,
)
self.assertQuerySetEqual(
Issue.objects.filter(client=g.id),
[
3,
],
lambda i: i.num,
)
self.assertQuerySetEqual(Issue.objects.filter(cc__id__exact=g.id), [])
self.assertQuerySetEqual(
Issue.objects.filter(cc__id__exact=r.id),
[
2,
3,
],
lambda i: i.num,
)
# These queries combine results from the m2m and the m2o relationships.
# They're three ways of saying the same thing.
self.assertQuerySetEqual(
Issue.objects.filter(Q(cc__id__exact=r.id) | Q(client=r.id)),
[
1,
2,
3,
],
lambda i: i.num,
)
self.assertQuerySetEqual(
Issue.objects.filter(cc__id__exact=r.id)
| Issue.objects.filter(client=r.id),
[
1,
2,
3,
],
lambda i: i.num,
)
self.assertQuerySetEqual(
Issue.objects.filter(Q(client=r.id) | Q(cc__id__exact=r.id)),
[
1,
2,
3,
],
lambda i: i.num,
)
class RelatedObjectUnicodeTests(TestCase):
def test_m2m_with_unicode_reference(self):
"""
Regression test for #6045: references to other models can be
strings, providing they are directly convertible to ASCII.
"""
m1 = StringReferenceModel.objects.create()
m2 = StringReferenceModel.objects.create()
m2.others.add(m1) # used to cause an error (see ticket #6045)
m2.save()
list(m2.others.all()) # Force retrieval.
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/template_loader/__init__.py | tests/template_loader/__init__.py | python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false | |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/template_loader/tests.py | tests/template_loader/tests.py | from django.template import TemplateDoesNotExist
from django.template.loader import get_template, render_to_string, select_template
from django.test import SimpleTestCase, override_settings
from django.test.client import RequestFactory
@override_settings(
TEMPLATES=[
{
"BACKEND": "django.template.backends.dummy.TemplateStrings",
"APP_DIRS": True,
},
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"OPTIONS": {
"context_processors": [
"django.template.context_processors.request",
],
"loaders": [
"django.template.loaders.filesystem.Loader",
"django.template.loaders.app_directories.Loader",
],
},
},
]
)
class TemplateLoaderTests(SimpleTestCase):
def test_get_template_first_engine(self):
template = get_template("template_loader/hello.html")
self.assertEqual(template.render(), "Hello! (template strings)\n")
def test_get_template_second_engine(self):
template = get_template("template_loader/goodbye.html")
self.assertEqual(template.render(), "Goodbye! (Django templates)\n")
def test_get_template_using_engine(self):
template = get_template("template_loader/hello.html", using="django")
self.assertEqual(template.render(), "Hello! (Django templates)\n")
def test_get_template_not_found(self):
with self.assertRaises(TemplateDoesNotExist) as e:
get_template("template_loader/unknown.html")
self.assertEqual(
e.exception.chain[-1].tried[0][0].template_name,
"template_loader/unknown.html",
)
self.assertEqual(e.exception.chain[-1].backend.name, "django")
def test_select_template_first_engine(self):
template = select_template(
["template_loader/unknown.html", "template_loader/hello.html"]
)
self.assertEqual(template.render(), "Hello! (template strings)\n")
def test_select_template_second_engine(self):
template = select_template(
["template_loader/unknown.html", "template_loader/goodbye.html"]
)
self.assertEqual(template.render(), "Goodbye! (Django templates)\n")
def test_select_template_using_engine(self):
template = select_template(
["template_loader/unknown.html", "template_loader/hello.html"],
using="django",
)
self.assertEqual(template.render(), "Hello! (Django templates)\n")
def test_select_template_empty(self):
with self.assertRaises(TemplateDoesNotExist):
select_template([])
def test_select_template_string(self):
with self.assertRaisesMessage(
TypeError,
"select_template() takes an iterable of template names but got a "
"string: 'template_loader/hello.html'. Use get_template() if you "
"want to load a single template by name.",
):
select_template("template_loader/hello.html")
def test_select_template_not_found(self):
with self.assertRaises(TemplateDoesNotExist) as e:
select_template(
["template_loader/unknown.html", "template_loader/missing.html"]
)
self.assertEqual(
e.exception.chain[0].tried[0][0].template_name,
"template_loader/unknown.html",
)
self.assertEqual(e.exception.chain[0].backend.name, "dummy")
self.assertEqual(
e.exception.chain[-1].tried[0][0].template_name,
"template_loader/missing.html",
)
self.assertEqual(e.exception.chain[-1].backend.name, "django")
def test_select_template_tries_all_engines_before_names(self):
template = select_template(
["template_loader/goodbye.html", "template_loader/hello.html"]
)
self.assertEqual(template.render(), "Goodbye! (Django templates)\n")
def test_render_to_string_first_engine(self):
content = render_to_string("template_loader/hello.html")
self.assertEqual(content, "Hello! (template strings)\n")
def test_render_to_string_second_engine(self):
content = render_to_string("template_loader/goodbye.html")
self.assertEqual(content, "Goodbye! (Django templates)\n")
def test_render_to_string_with_request(self):
request = RequestFactory().get("/foobar/")
content = render_to_string("template_loader/request.html", request=request)
self.assertEqual(content, "/foobar/\n")
def test_render_to_string_using_engine(self):
content = render_to_string("template_loader/hello.html", using="django")
self.assertEqual(content, "Hello! (Django templates)\n")
def test_render_to_string_not_found(self):
with self.assertRaises(TemplateDoesNotExist) as e:
render_to_string("template_loader/unknown.html")
self.assertEqual(
e.exception.chain[-1].tried[0][0].template_name,
"template_loader/unknown.html",
)
self.assertEqual(e.exception.chain[-1].backend.name, "django")
def test_render_to_string_with_list_first_engine(self):
content = render_to_string(
["template_loader/unknown.html", "template_loader/hello.html"]
)
self.assertEqual(content, "Hello! (template strings)\n")
def test_render_to_string_with_list_second_engine(self):
content = render_to_string(
["template_loader/unknown.html", "template_loader/goodbye.html"]
)
self.assertEqual(content, "Goodbye! (Django templates)\n")
def test_render_to_string_with_list_using_engine(self):
content = render_to_string(
["template_loader/unknown.html", "template_loader/hello.html"],
using="django",
)
self.assertEqual(content, "Hello! (Django templates)\n")
def test_render_to_string_with_list_empty(self):
with self.assertRaises(TemplateDoesNotExist):
render_to_string([])
def test_render_to_string_with_list_not_found(self):
with self.assertRaises(TemplateDoesNotExist) as e:
render_to_string(
["template_loader/unknown.html", "template_loader/missing.html"]
)
self.assertEqual(
e.exception.chain[0].tried[0][0].template_name,
"template_loader/unknown.html",
)
self.assertEqual(e.exception.chain[0].backend.name, "dummy")
self.assertEqual(
e.exception.chain[1].tried[0][0].template_name,
"template_loader/unknown.html",
)
self.assertEqual(e.exception.chain[1].backend.name, "django")
self.assertEqual(
e.exception.chain[2].tried[0][0].template_name,
"template_loader/missing.html",
)
self.assertEqual(e.exception.chain[2].backend.name, "dummy")
self.assertEqual(
e.exception.chain[3].tried[0][0].template_name,
"template_loader/missing.html",
)
self.assertEqual(e.exception.chain[3].backend.name, "django")
def test_render_to_string_with_list_tries_all_engines_before_names(self):
content = render_to_string(
["template_loader/goodbye.html", "template_loader/hello.html"]
)
self.assertEqual(content, "Goodbye! (Django templates)\n")
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/get_object_or_404/models.py | tests/get_object_or_404/models.py | """
DB-API Shortcuts
``get_object_or_404()`` is a shortcut function to be used in view functions for
performing a ``get()`` lookup and raising a ``Http404`` exception if a
``DoesNotExist`` exception was raised during the ``get()`` call.
``get_list_or_404()`` is a shortcut function to be used in view functions for
performing a ``filter()`` lookup and raising a ``Http404`` exception if a
``DoesNotExist`` exception was raised during the ``filter()`` call.
"""
from django.db import models
class Author(models.Model):
name = models.CharField(max_length=50)
class ArticleManager(models.Manager):
def get_queryset(self):
return super().get_queryset().filter(authors__name__icontains="sir")
class AttributeErrorManager(models.Manager):
def get_queryset(self):
raise AttributeError("AttributeErrorManager")
class Article(models.Model):
authors = models.ManyToManyField(Author)
title = models.CharField(max_length=50)
objects = models.Manager()
by_a_sir = ArticleManager()
attribute_error_objects = AttributeErrorManager()
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/get_object_or_404/__init__.py | tests/get_object_or_404/__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_object_or_404/tests.py | tests/get_object_or_404/tests.py | from django.db.models import Q
from django.http import Http404
from django.shortcuts import get_list_or_404, get_object_or_404
from django.test import TestCase
from .models import Article, Author
class GetObjectOr404Tests(TestCase):
def test_get_object_or_404(self):
a1 = Author.objects.create(name="Brave Sir Robin")
a2 = Author.objects.create(name="Patsy")
# No Articles yet, so we should get an Http404 error.
with self.assertRaises(Http404):
get_object_or_404(Article, title="Foo")
article = Article.objects.create(title="Run away!")
article.authors.set([a1, a2])
# get_object_or_404 can be passed a Model to query.
self.assertEqual(get_object_or_404(Article, title__contains="Run"), article)
# We can also use the Article manager through an Author object.
self.assertEqual(
get_object_or_404(a1.article_set, title__contains="Run"), article
)
# No articles containing "Camelot". This should raise an Http404 error.
with self.assertRaises(Http404):
get_object_or_404(a1.article_set, title__contains="Camelot")
# Custom managers can be used too.
self.assertEqual(
get_object_or_404(Article.by_a_sir, title="Run away!"), article
)
# QuerySets can be used too.
self.assertEqual(
get_object_or_404(Article.objects.all(), title__contains="Run"), article
)
# Just as when using a get() lookup, you will get an error if more than
# one object is returned.
with self.assertRaises(Author.MultipleObjectsReturned):
get_object_or_404(Author.objects.all())
# Using an empty QuerySet raises an Http404 error.
with self.assertRaises(Http404):
get_object_or_404(Article.objects.none(), title__contains="Run")
# get_list_or_404 can be used to get lists of objects
self.assertEqual(
get_list_or_404(a1.article_set, title__icontains="Run"), [article]
)
# Http404 is returned if the list is empty.
with self.assertRaises(Http404):
get_list_or_404(a1.article_set, title__icontains="Shrubbery")
# Custom managers can be used too.
self.assertEqual(
get_list_or_404(Article.by_a_sir, title__icontains="Run"), [article]
)
# QuerySets can be used too.
self.assertEqual(
get_list_or_404(Article.objects.all(), title__icontains="Run"), [article]
)
# Q objects.
self.assertEqual(
get_object_or_404(
Article,
Q(title__startswith="Run") | Q(title__startswith="Walk"),
authors__name__contains="Brave",
),
article,
)
self.assertEqual(
get_list_or_404(
Article,
Q(title__startswith="Run") | Q(title__startswith="Walk"),
authors__name="Patsy",
),
[article],
)
def test_bad_class(self):
# Given an argument klass that is not a Model, Manager, or Queryset
# raises a helpful ValueError message
msg = (
"First argument to get_object_or_404() must be a Model, Manager, or "
"QuerySet, not 'str'."
)
with self.assertRaisesMessage(ValueError, msg):
get_object_or_404("Article", title__icontains="Run")
class CustomClass:
pass
msg = (
"First argument to get_object_or_404() must be a Model, Manager, or "
"QuerySet, not 'CustomClass'."
)
with self.assertRaisesMessage(ValueError, msg):
get_object_or_404(CustomClass, title__icontains="Run")
# Works for lists too
msg = (
"First argument to get_list_or_404() must be a Model, Manager, or "
"QuerySet, not 'list'."
)
with self.assertRaisesMessage(ValueError, msg):
get_list_or_404([Article], title__icontains="Run")
def test_get_object_or_404_queryset_attribute_error(self):
"""AttributeError raised by QuerySet.get() isn't hidden."""
with self.assertRaisesMessage(AttributeError, "AttributeErrorManager"):
get_object_or_404(Article.attribute_error_objects, id=42)
def test_get_list_or_404_queryset_attribute_error(self):
"""AttributeError raised by QuerySet.filter() isn't hidden."""
with self.assertRaisesMessage(AttributeError, "AttributeErrorManager"):
get_list_or_404(Article.attribute_error_objects, title__icontains="Run")
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/empty_models/models.py | tests/empty_models/models.py | 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.