prefix stringlengths 512 512 | suffix stringlengths 256 256 | middle stringlengths 14 229 | meta dict |
|---|---|---|---|
nittest 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... | with mock.patch("subprocess.run") as run:
with mock.patch.object(
BaseDatabaseClient,
"settings_to_cmd_args_env",
return_value=([], env),
| 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):
| {
"filepath": "tests/backends/base/test_client.py",
"language": "python",
"file_size": 1139,
"cut_index": 518,
"middle_length": 229
} |
els 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 =... | _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) | SignatureTests(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 | {
"filepath": "tests/backends/base/test_creation.py",
"language": "python",
"file_size": 15378,
"cut_index": 921,
"middle_length": 229
} |
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)... | Message(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):
| rtRaisesMessage(NotImplementedError, msg):
self.introspection.get_table_list(None)
def test_get_table_description(self):
msg = self.may_require_msg % "get_table_description"
with self.assertRaises | {
"filepath": "tests/backends/base/test_introspection.py",
"language": "python",
"file_size": 1489,
"cut_index": 524,
"middle_length": 229
} |
skipIfDBFeature,
skipUnlessDBFeature,
)
from django.utils import timezone
from ..models import Author, Book, Person
class SimpleDatabaseOperationTests(SimpleTestCase):
may_require_msg = "subclasses of BaseDatabaseOperations may require a %s() method"
def setUp(self):
self.ops = BaseDatabaseOpera... | 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):
| 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"
):
| {
"filepath": "tests/backends/base/test_operations.py",
"language": "python",
"file_size": 10796,
"cut_index": 921,
"middle_length": 229
} |
go.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_... | 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_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 | {
"filepath": "tests/backends/sqlite/test_creation.py",
"language": "python",
"file_size": 4515,
"cut_index": 614,
"middle_length": 229
} |
3
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, "sup... | riable_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_li | rsor",
side_effect=OperationalError(msg),
):
with self.assertRaisesMessage(OperationalError, msg):
connection.features.supports_json_field
def test_max_query_params_respects_va | {
"filepath": "tests/backends/sqlite/test_features.py",
"language": "python",
"file_size": 1689,
"cut_index": 537,
"middle_length": 229
} |
ort TestCase
from .models import Comment, Tenant, User
class CompositePKOrderByTests(TestCase):
maxDiff = None
@classmethod
def setUpTestData(cls):
cls.tenant_1 = Tenant.objects.create()
cls.tenant_2 = Tenant.objects.create()
cls.tenant_3 = Tenant.objects.create()
cls.use... | cls.comment_1 = Comment.objects.create(id=1, user=cls.user_1)
cls.comment_2 = Comment.objects.create(id=2, user=cls.user_1)
cls.comment_3 = Comment.objects.create(id=3, user=cls.user_2)
cls.comment_4 = Comment.objects.create( | ls.tenant_1,
id=2,
email="user0002@example.com",
)
cls.user_3 = User.objects.create(
tenant=cls.tenant_2,
id=3,
email="user0003@example.com",
)
| {
"filepath": "tests/composite_pk/test_order_by.py",
"language": "python",
"file_size": 2372,
"cut_index": 563,
"middle_length": 229
} |
from django.test import SimpleTestCase
from django.utils import regex_helper
class NormalizeTests(unittest.TestCase):
def test_empty(self):
pattern = r""
expected = [("", [])]
result = regex_helper.normalize(pattern)
self.assertEqual(result, expected)
def test_escape(self):
... | ing(self):
pattern = r"(?:non-capturing)"
expected = [("non-capturing", [])]
result = regex_helper.normalize(pattern)
self.assertEqual(result, expected)
def test_group_named(self):
pattern = r"(?P<first_group_na | group_positional(self):
pattern = r"(.*)-(.+)"
expected = [("%(_0)s-%(_1)s", ["_0", "_1"])]
result = regex_helper.normalize(pattern)
self.assertEqual(result, expected)
def test_group_noncaptur | {
"filepath": "tests/utils_tests/test_regex_helper.py",
"language": "python",
"file_size": 2004,
"cut_index": 537,
"middle_length": 229
} |
db import models
class Tenant(models.Model):
name = models.CharField(max_length=10, default="", blank=True)
class Token(models.Model):
pk = models.CompositePrimaryKey("tenant_id", "id")
tenant = models.ForeignKey(Tenant, on_delete=models.CASCADE, related_name="tokens")
id = models.SmallIntegerField(... | el):
pk = models.CompositePrimaryKey("tenant", "id")
tenant = models.ForeignKey(
Tenant,
on_delete=models.CASCADE,
related_name="comments",
)
id = models.SmallIntegerField(unique=True, db_column="comment_id")
use | (Tenant, on_delete=models.CASCADE)
email = models.EmailField(unique=True)
id = models.SmallIntegerField(unique=True)
class Meta:
abstract = True
class User(AbstractUser):
pass
class Comment(models.Mod | {
"filepath": "tests/composite_pk/models/tenant.py",
"language": "python",
"file_size": 1832,
"cut_index": 537,
"middle_length": 229
} |
ort get_fixed_timezone
class FeedgeneratorTests(SimpleTestCase):
"""
Tests for the low-level syndication feed framework.
"""
def test_get_tag_uri(self):
"""
get_tag_uri() correctly generates TagURIs.
"""
self.assertEqual(
feedgenerator.get_tag_uri(
... | 11/14/django#headline",
datetime.datetime(2008, 11, 14, 13, 37, 0),
),
"tag:www.example.org,2008-11-14:/2008/11/14/django/headline",
)
def test_rfc2822_date(self):
"""
rfc2822_date() corr | ort(self):
"""
get_tag_uri() correctly generates TagURIs from URLs with port numbers.
"""
self.assertEqual(
feedgenerator.get_tag_uri(
"http://www.example.org:8000/2008/ | {
"filepath": "tests/utils_tests/test_feedgenerator.py",
"language": "python",
"file_size": 6240,
"cut_index": 716,
"middle_length": 229
} |
jango.test import SimpleTestCase
from django.utils.hashable import make_hashable
class TestHashable(SimpleTestCase):
def test_equal(self):
tests = (
([], ()),
(["a", 1], ("a", 1)),
({}, ()),
({"a"}, ("a",)),
(frozenset({"a"}), {"a"}),
... | : 1, "b": ["a", 1]}, (("a", 1), ("b", ("a", 1)))),
({"a": 1, "b": ("a", [1, 2])}, (("a", 1), ("b", ("a", (1, 2))))),
)
for value, expected in tests:
with self.subTest(value=value):
self.assertCountEqu | )),
)
for value, expected in tests:
with self.subTest(value=value):
self.assertEqual(make_hashable(value), expected)
def test_count_equal(self):
tests = (
({"a" | {
"filepath": "tests/utils_tests/test_hashable.py",
"language": "python",
"file_size": 1248,
"cut_index": 518,
"middle_length": 229
} |
self.assertEqual(urlencode((("a", 1), ("b", 2), ("c", 3))), "a=1&b=2&c=3")
def test_dict(self):
result = urlencode({"a": 1, "b": 2, "c": 3})
self.assertEqual(result, "a=1&b=2&c=3")
def test_dict_containing_sequence_not_doseq(self):
self.assertEqual(urlencode({"a": [1, 2]}, dose... | rableWithStr()}, doseq=False), "a=custom")
def test_dict_containing_sequence_doseq(self):
self.assertEqual(urlencode({"a": [1, 2]}, doseq=True), "a=1&a=2")
def test_dict_containing_empty_sequence_doseq(self):
self.assertEqual(urle | _not_doseq(self):
class IterableWithStr:
def __str__(self):
return "custom"
def __iter__(self):
yield from range(0, 3)
self.assertEqual(urlencode({"a": Ite | {
"filepath": "tests/utils_tests/test_http.py",
"language": "python",
"file_size": 21276,
"cut_index": 1331,
"middle_length": 229
} |
from django.core.exceptions import ValidationError
from django.test import SimpleTestCase
from django.utils.ipv6 import (
MAX_IPV6_ADDRESS_LENGTH,
clean_ipv6_address,
is_valid_ipv6_address,
)
class TestUtilsIPv6(SimpleTestCase):
def test_validates_correct_plain_address(self):
self.assertTrue... | ssertTrue(is_valid_ipv6_address("::ffff:254.42.16.14"))
self.assertTrue(is_valid_ipv6_address("::ffff:0a0a:0a0a"))
def test_validates_correct_with_ipv6_instance(self):
cases = [
IPv6Address("::ffff:2.125.160.216"),
| self.assertTrue(is_valid_ipv6_address("::"))
self.assertTrue(is_valid_ipv6_address("::a"))
self.assertTrue(is_valid_ipv6_address("2::"))
def test_validates_correct_with_v4mapping(self):
self.a | {
"filepath": "tests/utils_tests/test_ipv6.py",
"language": "python",
"file_size": 5060,
"cut_index": 614,
"middle_length": 229
} |
ons import UserList, defaultdict
from datetime import datetime
from decimal import Decimal
from django.test import SimpleTestCase
from django.utils.json import normalize_json
class JSONNormalizeTestCase(SimpleTestCase):
def test_converts_json_types(self):
for test_case, expected in [
(None, "... | ), "{}"),
(float("nan"), "NaN"),
(float("inf"), "Infinity"),
(float("-inf"), "-Infinity"),
]:
with self.subTest(test_case):
normalized = normalize_json(test_case)
# Ens | o", '"hello"'),
([], "[]"),
(UserList([1, 2]), "[1, 2]"),
({}, "{}"),
({1: "a"}, '{"1": "a"}'),
({"foo": (1, 2, 3)}, '{"foo": [1, 2, 3]}'),
(defaultdict(list | {
"filepath": "tests/utils_tests/test_json.py",
"language": "python",
"file_size": 1597,
"cut_index": 537,
"middle_length": 229
} |
orTests(unittest.TestCase):
def test_empty_string(self):
self.assertEqual(parse_color_setting(""), PALETTES[DEFAULT_PALETTE])
def test_simple_palette(self):
self.assertEqual(parse_color_setting("light"), PALETTES[LIGHT_PALETTE])
self.assertEqual(parse_color_setting("dark"), PALETTES[DAR... | ": "blue"}),
)
def test_fg_opts(self):
self.assertEqual(
parse_color_setting("error=green,blink"),
dict(PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green", "opts": ("blink",)}),
)
self.assertEqual(
| S[NOCOLOR_PALETTE], ERROR={"fg": "green"}),
)
def test_fg_bg(self):
self.assertEqual(
parse_color_setting("error=green/blue"),
dict(PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green", "bg | {
"filepath": "tests/utils_tests/test_termcolors.py",
"language": "python",
"file_size": 8257,
"cut_index": 716,
"middle_length": 229
} |
self):
self.assertIsInstance(timezone.get_default_timezone(), zoneinfo.ZoneInfo)
def test_now(self):
with override_settings(USE_TZ=True):
self.assertTrue(timezone.is_aware(timezone.now()))
with override_settings(USE_TZ=False):
self.assertTrue(timezone.is_naive(timezo... | ve, timezone=EAT)
aware = datetime.datetime(2015, 1, 1, 0, 0, 1, tzinfo=ICT)
self.assertEqual(
timezone.localdate(aware, timezone=EAT), datetime.date(2014, 12, 31)
)
with timezone.override(EAT):
self | o a naive datetime"
):
timezone.localdate(naive)
with self.assertRaisesMessage(
ValueError, "localtime() cannot be applied to a naive datetime"
):
timezone.localdate(nai | {
"filepath": "tests/utils_tests/test_timezone.py",
"language": "python",
"file_size": 9650,
"cut_index": 921,
"middle_length": 229
} |
de
class NodeTests(unittest.TestCase):
def setUp(self):
self.node1_children = [("a", 1), ("b", 2)]
self.node1 = Node(self.node1_children)
self.node2 = Node()
def test_str(self):
self.assertEqual(str(self.node1), "(DEFAULT: ('a', 1), ('b', 2))")
self.assertEqual(str(sel... | ", 2]])
node7 = Node([("a", [1, 2])])
node8 = Node([("a", (1, 2))])
self.assertNotEqual(hash(self.node1), hash(self.node2))
self.assertNotEqual(hash(self.node1), hash(node3))
self.assertNotEqual(hash(self.node1), has | LT: )>")
def test_hash(self):
node3 = Node(self.node1_children, negated=True)
node4 = Node(self.node1_children, connector="OTHER")
node5 = Node(self.node1_children)
node6 = Node([["a", 1], ["b | {
"filepath": "tests/utils_tests/test_tree.py",
"language": "python",
"file_size": 4828,
"cut_index": 614,
"middle_length": 229
} |
o.db.backends.utils import truncate_name
from django.test import TestCase
from .models.article import Article, Site
from .models.publication import Publication
class Advertisement(models.Model):
customer = models.CharField(max_length=100)
publications = models.ManyToManyField("model_package.Publication", bla... | a.sites.add(site)
a = Article.objects.get(id=a.pk)
self.assertEqual(a.id, a.pk)
self.assertEqual(a.sites.count(), 1)
def test_models_in_the_test_package(self):
"""
Regression for #12245 - Models can exist i | tables.
"""
p = Publication.objects.create(title="FooBar")
site = Site.objects.create(name="example.com")
a = Article.objects.create(headline="a foo headline")
a.publications.add(p)
| {
"filepath": "tests/model_package/tests.py",
"language": "python",
"file_size": 2624,
"cut_index": 563,
"middle_length": 229
} |
sponse
from django.middleware.csrf import (
CSRF_TOKEN_LENGTH,
CsrfViewMiddleware,
_unmask_cipher_token,
get_token,
)
from django.template import TemplateDoesNotExist, TemplateSyntaxError
from django.template.backends.dummy import TemplateStrings
from django.test import SimpleTestCase
class TemplateSt... | template = self.engine.from_string("Hello!\n")
content = template.render()
self.assertEqual(content, "Hello!\n")
def test_get_template(self):
template = self.engine.get_template("template_backends/hello.html")
content | s = {
"DIRS": [],
"APP_DIRS": True,
"NAME": cls.backend_name,
"OPTIONS": cls.options,
}
cls.engine = cls.engine_class(params)
def test_from_string(self):
| {
"filepath": "tests/template_backends/test_dummy.py",
"language": "python",
"file_size": 4088,
"cut_index": 614,
"middle_length": 229
} |
om .test_dummy import TemplateStringsTests
try:
import jinja2
except ImportError:
jinja2 = None
Jinja2 = None
else:
from django.template.backends.jinja2 import Jinja2
@skipIf(jinja2 is None, "this test requires jinja2")
class Jinja2Tests(TemplateStringsTests):
engine_class = Jinja2
backend_na... | s/hello.html")
def test_origin_from_string(self):
template = self.engine.from_string("Hello!\n")
self.assertEqual(template.origin.name, "<template>")
self.assertIsNone(template.origin.template_name)
def test_self_context(s | gin(self):
template = self.engine.get_template("template_backends/hello.html")
self.assertTrue(template.origin.name.endswith("hello.html"))
self.assertEqual(template.origin.template_name, "template_backend | {
"filepath": "tests/template_backends/test_jinja2.py",
"language": "python",
"file_size": 6568,
"cut_index": 716,
"middle_length": 229
} |
ort TestCase
from .models import Number
class XorLookupsTests(TestCase):
@classmethod
def setUpTestData(cls):
cls.numbers = [Number.objects.create(num=i) for i in range(10)]
def test_filter(self):
self.assertCountEqual(
Number.objects.filter(num__lte=7) ^ Number.objects.filte... | ^ Q(num__gte=9)
)
self.assertCountEqual(
qs,
self.numbers[1:3] + self.numbers[5:7] + self.numbers[9:],
)
self.assertCountEqual(
qs.values_list("num", flat=True),
[
| ers[:3] + self.numbers[8:],
)
def test_filter_multiple(self):
qs = Number.objects.filter(
Q(num__gte=1)
^ Q(num__gte=3)
^ Q(num__gte=5)
^ Q(num__gte=7)
| {
"filepath": "tests/xor_lookups/tests.py",
"language": "python",
"file_size": 2746,
"cut_index": 563,
"middle_length": 229
} |
t_format_number(self):
self.assertEqual(nformat(1234, "."), "1234")
self.assertEqual(nformat(1234.2, "."), "1234.2")
self.assertEqual(nformat(1234, ".", decimal_pos=2), "1234.00")
self.assertEqual(nformat(1234, ".", grouping=2, thousand_sep=","), "1234")
self.assertEqual(
... | "1234"
)
self.assertEqual(
nformat(1234, ".", grouping=3, thousand_sep=",", use_l10n=True), "1,234"
)
def test_format_string(self):
self.assertEqual(nformat("1234", "."), "1234")
sel | The use_l10n parameter can force thousand grouping behavior.
with self.settings(USE_THOUSAND_SEPARATOR=True):
self.assertEqual(
nformat(1234, ".", grouping=3, thousand_sep=",", use_l10n=False), | {
"filepath": "tests/utils_tests/test_numberformat.py",
"language": "python",
"file_size": 7440,
"cut_index": 716,
"middle_length": 229
} |
.safestring import SafeData, SafeString, mark_safe
from django.utils.translation import gettext_lazy
class customescape(str):
def __html__(self):
# Implement specific and wrong escaping in order to be able to detect
# when it runs.
return self.replace("<", "<<").replace(">", ">>")
class ... | tr(self):
"""
Calling str() on a SafeString instance doesn't lose the safe status.
"""
s = mark_safe("a&b")
self.assertIsInstance(str(s), type(s))
def test_mark_safe_object_implementing_dunder_html(self):
| ntext), expected)
def test_mark_safe(self):
s = mark_safe("a&b")
self.assertRenderEqual("{{ s }}", "a&b", s=s)
self.assertRenderEqual("{{ s|force_escape }}", "a&b", s=s)
def test_mark_safe_s | {
"filepath": "tests/utils_tests/test_safestring.py",
"language": "python",
"file_size": 6334,
"cut_index": 716,
"middle_length": 229
} |
t"""
class Base:
def base_method(self):
pass
class Klazz(Base):
pass
t = lazy(lambda: Klazz(), Klazz)()
self.assertIn("base_method", dir(t))
def test_lazy_base_class_override(self):
"""lazy finds the correct (overridden) method impl... | ef __bytes__(self):
return b"\xc3\x8e am \xc4\x81 binary \xc7\xa8l\xc3\xa2zz."
t = lazy(lambda: Klazz(), Klazz)()
self.assertEqual(str(t), "Î am ā Ǩlâzz.")
self.assertEqual(bytes(t), b"\xc3\x8e am \xc4\x81 binary \x | t = lazy(lambda: Klazz(), Base)()
self.assertEqual(t.method(), "Klazz")
def test_lazy_object_to_string(self):
class Klazz:
def __str__(self):
return "Î am ā Ǩlâzz."
d | {
"filepath": "tests/utils_tests/test_functional.py",
"language": "python",
"file_size": 10550,
"cut_index": 921,
"middle_length": 229
} |
G:
from django.utils.safestring import SafeString
class Person:
def no_arguments(self):
return None
def one_argument(self, something):
return something
def just_args(self, *args):
return args
def all_kinds(self, name, address="home", age=25, *args, **kwargs):
ret... | spect._get_callable_parameters(Person().no_arguments),
inspect._get_callable_parameters(Person().no_arguments),
)
def test_get_func_full_args_no_arguments(self):
self.assertEqual(inspect.get_func_full_args(Person.no_argumen | llable_parameters(self):
self.assertIs(
inspect._get_callable_parameters(Person.no_arguments),
inspect._get_callable_parameters(Person.no_arguments),
)
self.assertIs(
in | {
"filepath": "tests/utils_tests/test_inspect.py",
"language": "python",
"file_size": 6200,
"cut_index": 716,
"middle_length": 229
} |
.assertEqual(text.get_text_list(["a", "b", "c"]), "a، b أو c")
def test_smart_split(self):
testdata = [
('This is "a person" test.', ["This", "is", '"a person"', "test."]),
('This is "a person\'s" test.', ["This", "is", '"a person\'s"', "test."]),
('This is "a person\\"s... | ge", "words='something else'"],
),
(
'url search_page words "something else"',
["url", "search_page", "words", '"something else"'],
),
(
'url search_page words- | 'url search_page words="something else"',
["url", "search_page", 'words="something else"'],
),
(
"url search_page words='something else'",
["url", "search_pa | {
"filepath": "tests/utils_tests/test_text.py",
"language": "python",
"file_size": 18870,
"cut_index": 1331,
"middle_length": 229
} |
self.onemicrosecond = datetime.timedelta(microseconds=1)
self.onesecond = datetime.timedelta(seconds=1)
self.oneminute = datetime.timedelta(minutes=1)
self.onehour = datetime.timedelta(hours=1)
self.oneday = datetime.timedelta(days=1)
self.oneweek = datetime.timedelta(days=7)
... | ertEqual(
timesince(self.t, self.t + self.onemicrosecond), "0\xa0minutes"
)
self.assertEqual(timesince(self.t, self.t + self.onesecond), "0\xa0minutes")
def test_other_units(self):
"""Test other units."""
se | avoids wrapping between value and unit
self.assertEqual(timesince(self.t, self.t), "0\xa0minutes")
def test_ignore_microseconds_and_seconds(self):
"""Microseconds and seconds are ignored."""
self.ass | {
"filepath": "tests/utils_tests/test_timesince.py",
"language": "python",
"file_size": 12599,
"cut_index": 921,
"middle_length": 229
} |
oTemplates
from django.template.library import InvalidTemplateLibrary
from django.test import RequestFactory, override_settings
from .test_dummy import TemplateStringsTests
class DjangoTemplatesTests(TemplateStringsTests):
engine_class = DjangoTemplates
backend_name = "django"
request_factory = RequestFa... | from_string("{{ processors }}")
request = self.request_factory.get("/")
# Context processors run
content = template.render({}, request)
self.assertEqual(content, "yes")
# Context overrides context processors
| "APP_DIRS": False,
"NAME": "django",
"OPTIONS": {
"context_processors": [test_processor_name],
},
}
)
template = engine. | {
"filepath": "tests/template_backends/test_django.py",
"language": "python",
"file_size": 7310,
"cut_index": 716,
"middle_length": 229
} |
import extend_sys_path
class EggLoadingTest(SimpleTestCase):
def setUp(self):
self.egg_dir = "%s/eggs" % os.path.dirname(__file__)
self.addCleanup(apps.clear_cache)
def test_egg1(self):
"""Models module can be loaded from an app in an egg"""
egg_name = "%s/modelapp.egg" % self... | error).
"""
egg_name = "%s/nomodelapp.egg" % self.egg_dir
with extend_sys_path(egg_name):
with self.settings(INSTALLED_APPS=["app_no_models"]):
models_module = apps.get_app_config("app_no_models").m | ls_module
self.assertIsNotNone(models_module)
del apps.all_models["app_with_models"]
def test_egg2(self):
"""
Loading an app from an egg that has no models returns no models (and no
| {
"filepath": "tests/app_loading/tests.py",
"language": "python",
"file_size": 3071,
"cut_index": 614,
"middle_length": 229
} |
_path
from django.utils.module_loading import (
autodiscover_modules,
import_string,
module_has_submodule,
)
class DefaultLoader(unittest.TestCase):
def test_loader(self):
"Normal module existence can be tested"
test_module = import_module("utils_tests.test_module")
test_no_sub... | odule"))
with self.assertRaises(ImportError):
import_module("utils_tests.test_module.bad_module")
# A child that doesn't exist
self.assertFalse(module_has_submodule(test_module, "no_such_module"))
with self.asse | ils_tests.test_module.good_module")
self.assertEqual(mod.content, "Good Module")
# A child that exists, but will generate an import error if loaded
self.assertTrue(module_has_submodule(test_module, "bad_m | {
"filepath": "tests/utils_tests/test_module_loading.py",
"language": "python",
"file_size": 9118,
"cut_index": 716,
"middle_length": 229
} |
"
function(value) equals output. If output is None, function(value)
equals value.
"""
if output is None:
output = value
self.assertEqual(function(value), output)
def test_escape(self):
items = (
("&", "&"),
("<", "<"),
... | rn):
self.check_output(escape, pattern % value, pattern % output)
self.check_output(
escape, lazystr(pattern % value), pattern % output
)
# | %s1", "1%sb")
for value, output in items:
with self.subTest(value=value, output=output):
for pattern in patterns:
with self.subTest(value=value, output=output, pattern=patte | {
"filepath": "tests/utils_tests/test_html.py",
"language": "python",
"file_size": 20950,
"cut_index": 1331,
"middle_length": 229
} |
many relationships between the same two tables
In this example, a ``Person`` can have many friends, who are also ``Person``
objects. Friendship is a symmetrical relationship - if I am your friend, you
are my friend. Here, ``friends`` is an example of a symmetrical
``ManyToManyField``.
A ``Person`` can also have many ... | ango.db import models
class Person(models.Model):
name = models.CharField(max_length=20)
friends = models.ManyToManyField("self")
colleagues = models.ManyToManyField("self", symmetrical=True, through="Colleague")
idols = models.ManyToMany | non-symmetrical, and they are symmetrical by default.
This test validates that the many-to-many table is created using a mangled name
if there is a name clash, and tests that symmetry is preserved where
appropriate.
"""
from dj | {
"filepath": "tests/m2m_recursive/models.py",
"language": "python",
"file_size": 1312,
"cut_index": 524,
"middle_length": 229
} |
ns import ImproperlyConfigured
from django.template import engines
from django.test import SimpleTestCase, override_settings
class TemplateUtilsTests(SimpleTestCase):
@override_settings(TEMPLATES=[{"BACKEND": "raise.import.error"}])
def test_backend_import_error(self):
"""
Failing to import a ... | ,
# Incorrect: APP_DIRS and loaders are mutually incompatible.
"APP_DIRS": True,
"OPTIONS": {"loaders": []},
}
]
)
def test_backend_improperly_configured(self):
"""
| th self.assertRaisesMessage(ImportError, "No module named 'raise"):
engines.all()
@override_settings(
TEMPLATES=[
{
"BACKEND": "django.template.backends.django.DjangoTemplates" | {
"filepath": "tests/template_backends/test_utils.py",
"language": "python",
"file_size": 1959,
"cut_index": 537,
"middle_length": 229
} |
to_path
class SafeMakeDirsTests(unittest.TestCase):
def setUp(self):
tmp = tempfile.TemporaryDirectory()
self.base = tmp.name
self.addCleanup(tmp.cleanup)
def assertDirMode(self, path, expected):
self.assertIs(os.path.isdir(path), True)
if sys.platform == "win32":
... | self.assertEqual(stat.S_IMODE(os.stat(path).st_mode), expected)
def test_creates_directory_hierarchy_with_permissions(self):
path = os.path.join(self.base, "a", "b", "c")
safe_makedirs(path, mode=0o755)
self.assertDirM | # create directories with modes like 0o755 and 0o700, which don't have
# group/world write bits, so a typical umask doesn't change the final
# permissions. On unexpected failures, check whether umask has changed.
| {
"filepath": "tests/utils_tests/test_os_utils.py",
"language": "python",
"file_size": 7203,
"cut_index": 716,
"middle_length": 229
} |
st.TestCase):
def lazy_wrap(self, wrapped_object):
"""
Wrap the given object into a LazyObject
"""
class AdHocLazyObject(LazyObject):
def _setup(self):
self._wrapped = wrapped_object
return AdHocLazyObject()
def test_getattribute(self):
... | tFalse(hasattr(obj, attr))
setattr(foo, attr, attr)
obj_with_attr = self.lazy_wrap(foo)
self.assertTrue(hasattr(obj_with_attr, attr))
self.assertEqual(getattr(obj_with_attr, attr), attr)
| "__iter__",
"__len__",
"__contains__",
]
foo = Foo()
obj = self.lazy_wrap(foo)
for attr in attrs:
with self.subTest(attr):
self.asser | {
"filepath": "tests/utils_tests/test_lazyobject.py",
"language": "python",
"file_size": 16152,
"cut_index": 921,
"middle_length": 229
} |
ibute and gives a nice error
message upon test failure.
"""
got = getattr(paginator, name)
if coerce is not None:
got = coerce(got)
self.assertEqual(
expected,
got,
"For '%s', expected %s but got %s. Paginator parameters were: %s"
... | get_test_cases_for_test_paginator(self):
nine = [1, 2, 3, 4, 5, 6, 7, 8, 9]
ten = nine + [10]
eleven = ten + [11]
return (
# Each item is 2-tuple:
# First tuple is Paginator parameters - object_l | ginator, name)
self.assertEqual(
expected,
await got(),
"For '%s', expected %s but got %s. Paginator parameters were: %s"
% (name, expected, got, params),
)
def | {
"filepath": "tests/pagination/tests.py",
"language": "python",
"file_size": 42438,
"cut_index": 2151,
"middle_length": 229
} |
s(TestCase):
@classmethod
def setUpTestData(cls):
cls.a, cls.b, cls.c, cls.d = [
Person.objects.create(name=name)
for name in ["Anne", "Bill", "Chuck", "David"]
]
cls.a.friends.add(cls.b, cls.c)
# Add m2m for Anne and Chuck in reverse direction.
cl... | verse_add(self):
# Add m2m for Anne in reverse direction.
self.b.friends.add(self.a)
self.assertSequenceEqual(self.a.friends.all(), [self.b, self.c, self.d])
self.assertSequenceEqual(self.b.friends.all(), [self.a])
def | (self.c, [self.a, self.d]),
(self.d, [self.a, self.c]),
):
with self.subTest(person=person):
self.assertSequenceEqual(person.friends.all(), friends)
def test_recursive_m2m_re | {
"filepath": "tests/m2m_recursive/tests.py",
"language": "python",
"file_size": 4912,
"cut_index": 614,
"middle_length": 229
} |
me_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... | :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) | qlite_datetime_trunc("unknown-lookup", "2005-08-11 1 | {
"filepath": "tests/backends/sqlite/test_functions.py",
"language": "python",
"file_size": 915,
"cut_index": 606,
"middle_length": 52
} |
t_intersection")
def test_intersection_with_values(self):
ReservedName.objects.create(name="a", order=2)
qs1 = ReservedName.objects.all()
reserved_name = qs1.intersection(qs1).values("name", "order", "id").get()
self.assertEqual(reserved_name["name"], "a")
self.assertEqual(re... | =False)
def test_union_distinct(self):
qs1 = Number.objects.all()
qs2 = Number.objects.all()
self.assertEqual(len(list(qs1.union(qs2, all=True))), 20)
self.assertEqual(len(list(qs1.union(qs2))), 10)
def test_union_ | "supports_select_difference")
def test_simple_difference(self):
qs1 = Number.objects.filter(num__lte=5)
qs2 = Number.objects.filter(num__lte=4)
self.assertNumbersEqual(qs1.difference(qs2), [5], ordered | {
"filepath": "tests/queries/test_qs_combinators.py",
"language": "python",
"file_size": 34542,
"cut_index": 2151,
"middle_length": 229
} |
dels.expressions import (
Col,
Exists,
ExpressionWrapper,
Func,
RawSQL,
Value,
)
from django.db.models.fields.related_lookups import RelatedIsNull
from django.db.models.functions import Lower
from django.db.models.lookups import Exact, GreaterThan, IsNull, LessThan
from django.db.models.sql.cons... | where = query.build_where(Q(num__gt=2))
lookup = where.children[0]
self.assertIsInstance(lookup, GreaterThan)
self.assertEqual(lookup.rhs, 2)
self.assertEqual(lookup.lhs.target, Author._meta.get_field("num"))
def | TestCase, skipUnlessDBFeature
from django.test.utils import register_lookup
from .models import Author, Item, ObjectC, Ranking
class TestQuery(SimpleTestCase):
def test_simple_query(self):
query = Query(Author)
| {
"filepath": "tests/queries/test_query.py",
"language": "python",
"file_size": 9069,
"cut_index": 716,
"middle_length": 229
} |
FAULT_DB_ALIAS, DatabaseError, connection
from django.db.models.sql import Query
from django.db.models.sql.compiler import SQLCompiler
from django.test import TestCase
from django.utils.deprecation import RemovedInDjango70Warning
from .models import Item
class SQLCompilerTest(TestCase):
def test_repr(self):
... | Item)
compiler = SQLCompiler(query, connection, None)
cursor = mock.MagicMock()
# When execution fails, the cursor may have been closed.
# Django's attempt to close it again will fail, and needs catching.
execute_er | on="
f"<DatabaseWrapper vendor={connection.vendor!r} alias='default'> "
f"using='default'>",
)
def test_execute_sql_suppresses_cursor_closing_failure_on_exception(self):
query = Query( | {
"filepath": "tests/queries/test_sqlcompiler.py",
"language": "python",
"file_size": 2255,
"cut_index": 563,
"middle_length": 229
} |
quenceEqual(
Author.objects.filter(item=self.i2) & Author.objects.filter(item=self.i3),
[self.a2],
)
def test_ticket2306(self):
# Checking that no join types are "left outer" joins.
query = Item.objects.filter(tags=self.t2).query
self.assertNotIn(LOUTER, [x.j... | Q(creator__name="fred") | Q(tags=self.t2)
),
[self.i1],
)
# Each filter call is processed "at once" against a single table, so
# this is different from the previous example as it tries to fin | self.assertSequenceEqual(
Item.objects.filter(Q(tags=self.t1)).filter(Q(tags=self.t2)),
[self.i1],
)
self.assertSequenceEqual(
Item.objects.filter(Q(tags=self.t1)).filter(
| {
"filepath": "tests/queries/tests.py",
"language": "python",
"file_size": 184540,
"cut_index": 7068,
"middle_length": 229
} |
db import models
class Author(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
friends = models.ManyToManyField("self", blank=True)
rating = models.FloatField(null=True)
def __str__(self):
return self.name
class Publisher(models.Model):
name = model... | gits=6)
authors = models.ManyToManyField(Author)
contact = models.ForeignKey(Author, models.CASCADE, related_name="book_contact_set")
publisher = models.ForeignKey(Publisher, models.CASCADE)
pubdate = models.DateField()
def __str__(sel | Book(models.Model):
isbn = models.CharField(max_length=9)
name = models.CharField(max_length=255)
pages = models.IntegerField()
rating = models.FloatField()
price = models.DecimalField(decimal_places=2, max_di | {
"filepath": "tests/aggregation/models.py",
"language": "python",
"file_size": 1443,
"cut_index": 524,
"middle_length": 229
} |
When,
)
from django.test import TestCase
from django.test.utils import Approximate
from .models import Author, Book, Publisher
class FilteredAggregateTests(TestCase):
@classmethod
def setUpTestData(cls):
cls.a1 = Author.objects.create(name="test", age=40)
cls.a2 = Author.objects.create(na... | ce=Decimal("30.00"),
contact=cls.a1,
publisher=cls.p1,
pubdate=datetime.date(2007, 12, 6),
)
cls.b2 = Book.objects.create(
isbn="067232959",
name="Sams Teach Yourself Django in 24 | a(days=1)
)
cls.b1 = Book.objects.create(
isbn="159059725",
name="The Definitive Guide to Django: Web Development Done Right",
pages=447,
rating=4.5,
pri | {
"filepath": "tests/aggregation/test_filter_argument.py",
"language": "python",
"file_size": 8805,
"cut_index": 716,
"middle_length": 229
} |
4.5,
price=Decimal("30.00"),
contact=cls.a1,
publisher=cls.p1,
pubdate=datetime.date(2007, 12, 6),
)
cls.b2 = Book.objects.create(
isbn="067232959",
name="Sams Teach Yourself Django in 24 Hours",
pages=528,
r... | pubdate=datetime.date(2008, 6, 23),
)
cls.b4 = Book.objects.create(
isbn="013235613",
name="Python Web Development with Django",
pages=350,
rating=4.0,
price=Decimal("29.69 | create(
isbn="159059996",
name="Practical Django Projects",
pages=300,
rating=4.0,
price=Decimal("29.69"),
contact=cls.a4,
publisher=cls.p1,
| {
"filepath": "tests/aggregation/tests.py",
"language": "python",
"file_size": 105746,
"cut_index": 3790,
"middle_length": 229
} |
aising_test(self):
self._pre_setup.assert_called_once_with()
raise Exception("debug() bubbles up exceptions before cleanup.")
def simple_test(self):
self._pre_setup.assert_called_once_with()
@unittest.skip("Skip condition.")
def skipped_test(self):
pass
@mock.patch.dict(o... | reviousClass(None, result)
test_suite._handleModuleTearDown(result)
def test_run_cleanup(self, _pre_setup, _post_teardown):
"""Simple test run: catches errors and runs cleanup."""
test_suite = unittest.TestSuite()
test_ | unner(self):
return unittest.TextTestRunner(stream=StringIO())
def isolate_debug_test(self, test_suite, result):
# Suite teardown needs to be manually called to isolate failures.
test_suite._tearDownP | {
"filepath": "tests/test_utils/test_simpletestcase.py",
"language": "python",
"file_size": 6465,
"cut_index": 716,
"middle_length": 229
} |
baseOperationForbidden,
SimpleTestCase,
TestData,
is_pickable,
)
from .models import Car, Person, PossessedCar
class UnpicklableObject:
def __getstate__(self):
raise pickle.PickleError("cannot be pickled for testing reasons")
class TestSimpleTestCase(SimpleTestCase):
def test_is_picklab... | @skipUnlessDBFeature("can_defer_constraint_checks")
@skipUnlessDBFeature("supports_foreign_keys")
def test_fixture_teardown_checks_constraints(self):
rollback_atomics = self._rollback_atomics
self._rollback_atomics = lambda connec | loads(pickle.dumps(self)))
def test_is_picklable_with_non_picklable_object(self):
unpicklable_obj = UnpicklableObject()
self.assertEqual(is_pickable(unpicklable_obj), False)
class TestTestCase(TestCase):
| {
"filepath": "tests/test_utils/test_testcase.py",
"language": "python",
"file_size": 6358,
"cut_index": 716,
"middle_length": 229
} |
nnections
from django.test import TestCase, TransactionTestCase, override_settings
from django.test.testcases import DatabaseOperationForbidden
from .models import Car, Person
class TestSerializedRollbackInhibitsPostMigrate(TransactionTestCase):
"""
TransactionTestCase._fixture_teardown() inhibits the post_m... | def test(self, call_command):
# with a mocked call_command(), this doesn't have any effect.
self._fixture_teardown()
call_command.assert_called_with(
"flush",
interactive=False,
allow_cascade=F | s must be None to test the serialized_rollback
# condition.
self.available_apps = None
def tearDown(self):
self.available_apps = ["test_utils"]
@mock.patch("django.test.testcases.call_command")
| {
"filepath": "tests/test_utils/test_transactiontestcase.py",
"language": "python",
"file_size": 2727,
"cut_index": 563,
"middle_length": 229
} |
ts."
"SkippingTestCase.test_skip_unless_db_feature.<locals>.SkipTestCase."
"test_foo) as SkippingTestCase.test_skip_unless_db_feature.<locals>."
"SkipTestCase doesn't allow queries against the 'default' database.",
)
def test_skip_if_db_feature(self):
"""
... | def test_func4():
raise ValueError
@skipIfDBFeature("notprovided", "notprovided")
def test_func5():
raise ValueError
self._assert_skipping(test_func, unittest.SkipTest)
self._assert_skipping(test_f | ded")
def test_func2():
raise ValueError
@skipIfDBFeature("__class__", "__class__")
def test_func3():
raise ValueError
@skipIfDBFeature("__class__", "notprovided")
| {
"filepath": "tests/test_utils/tests.py",
"language": "python",
"file_size": 94256,
"cut_index": 3790,
"middle_length": 229
} |
esponse
from django.template import engines
from django.template.response import TemplateResponse
from django.utils.decorators import (
async_only_middleware,
sync_and_async_middleware,
sync_only_middleware,
)
log = []
class BaseMiddleware:
def __init__(self, get_response):
self.get_response ... | ync def process_exception(self, request, exception):
return HttpResponse("Exception caught")
class ProcessExceptionLogMiddleware(BaseMiddleware):
def process_exception(self, request, exception):
log.append("process-exception")
class | ocessExceptionMiddleware(BaseMiddleware):
def process_exception(self, request, exception):
return HttpResponse("Exception caught")
@async_only_middleware
class AsyncProcessExceptionMiddleware(BaseMiddleware):
as | {
"filepath": "tests/middleware_exceptions/middleware.py",
"language": "python",
"file_size": 4186,
"cut_index": 614,
"middle_length": 229
} |
MIDDLEWARE=["middleware_exceptions.middleware.ProcessViewNoneMiddleware"]
)
def test_process_view_return_none(self):
response = self.client.get("/middleware_exceptions/view/")
self.assertEqual(mw.log, ["processed view normal_view"])
self.assertEqual(response.content, b"OK")
@overrid... | "middleware_exceptions.middleware.LogMiddleware",
]
)
def test_templateresponse_from_process_view_rendered(self):
"""
TemplateResponses returned from process_view() must be rendered before
being passed to an | _exceptions/view/")
self.assertEqual(response.content, b"Processed view normal_view")
@override_settings(
MIDDLEWARE=[
"middleware_exceptions.middleware.ProcessViewTemplateResponseMiddleware",
| {
"filepath": "tests/middleware_exceptions/tests.py",
"language": "python",
"file_size": 15707,
"cut_index": 921,
"middle_length": 229
} |
rom django.core.exceptions import PermissionDenied
from django.http import HttpResponse
from django.template import engines
from django.template.response import TemplateResponse
def normal_view(request):
return HttpResponse("OK")
def template_response(request):
template = engines["django"].from_string(
... | sponse.render()")
return CustomHttpResponse("Error")
async def async_exception_in_render(request):
class CustomHttpResponse(HttpResponse):
async def render(self):
raise Exception("Exception in HttpResponse.render()")
ret | r in view")
def permission_denied(request):
raise PermissionDenied()
def exception_in_render(request):
class CustomHttpResponse(HttpResponse):
def render(self):
raise Exception("Exception in HttpRe | {
"filepath": "tests/middleware_exceptions/views.py",
"language": "python",
"file_size": 1030,
"cut_index": 513,
"middle_length": 229
} |
m django.db import models
class Article(models.Model):
headline = models.CharField(max_length=100)
pub_date = models.DateField()
expire_date = models.DateField()
class Meta:
get_latest_by = "pub_date"
class Person(models.Model):
name = models.CharField(max_length=30)
birthday = mode... | an intentionally broken QuerySet.__iter__ method.
class IndexErrorQuerySet(models.QuerySet):
"""
Emulates the case when some internal code raises an unexpected
IndexError.
"""
def __iter__(self):
raise IndexError
class Ind | models.PositiveIntegerField()
class OrderedArticle(models.Model):
headline = models.CharField(max_length=100)
pub_date = models.DateField()
class Meta:
ordering = ["headline"]
# Ticket #23555 - model with | {
"filepath": "tests/get_earliest_or_latest/models.py",
"language": "python",
"file_size": 1071,
"cut_index": 515,
"middle_length": 229
} |
et_latest_by = Article._meta.get_latest_by
def tearDown(self):
Article._meta.get_latest_by = self._article_get_latest_by
def test_earliest(self):
# Because no Articles exist yet, earliest() raises ArticleDoesNotExist.
with self.assertRaises(Article.DoesNotExist):
Article.ob... | rticle 3",
pub_date=datetime(2005, 7, 28),
expire_date=datetime(2005, 8, 27),
)
a4 = Article.objects.create(
headline="Article 4",
pub_date=datetime(2005, 7, 28),
expire_date=datet | a2 = Article.objects.create(
headline="Article 2",
pub_date=datetime(2005, 7, 27),
expire_date=datetime(2005, 7, 28),
)
a3 = Article.objects.create(
headline="A | {
"filepath": "tests/get_earliest_or_latest/tests.py",
"language": "python",
"file_size": 10962,
"cut_index": 921,
"middle_length": 229
} |
rage(temp_storage_dir)
test_collation = SimpleLazyObject(
lambda: connection.features.test_collations["virtual"]
)
class Foo(models.Model):
a = models.CharField(max_length=10)
d = models.DecimalField(max_digits=5, decimal_places=3)
def get_foo():
return Foo.objects.get(id=1).pk
class Bar(models.M... | ld(choices=CHOICES, null=True)
class WhizDelayed(models.Model):
c = models.IntegerField(choices=(), null=True)
# Contrived way of adding choices later.
WhizDelayed._meta.get_field("c").choices = Whiz.CHOICES
class WhizIter(models.Model):
c = | ": {
1: "First",
2: "Second",
},
"Group 2": (
(3, "Third"),
(4, "Fourth"),
),
0: "Other",
5: _("translated"),
}
c = models.IntegerFie | {
"filepath": "tests/model_fields/models.py",
"language": "python",
"file_size": 21666,
"cut_index": 1331,
"middle_length": 229
} |
db import models
from django.test import SimpleTestCase
from .models import AutoModel, BigAutoModel, SmallAutoModel
from .test_integerfield import (
BigIntegerFieldTests,
IntegerFieldTests,
SmallIntegerFieldTests,
)
class AutoFieldTests(IntegerFieldTests):
model = AutoModel
rel_db_type_class = mo... | oField):
with self.subTest(field.__name__):
self.assertIsInstance(field(), models.AutoField)
def test_issubclass_of_autofield(self):
class MyBigAutoField(models.BigAutoField):
pass
class MySmall | model = SmallAutoModel
rel_db_type_class = models.SmallIntegerField
class AutoFieldInheritanceTests(SimpleTestCase):
def test_isinstance_of_autofield(self):
for field in (models.BigAutoField, models.SmallAut | {
"filepath": "tests/model_fields/test_autofield.py",
"language": "python",
"file_size": 1359,
"cut_index": 524,
"middle_length": 229
} |
from django.db import models
from django.test import TestCase
from .models import DataModel
class BinaryFieldTests(TestCase):
binary_data = b"\x00\x46\xfe"
def test_set_and_retrieve(self):
data_set = (
self.binary_data,
bytearray(self.binary_data),
memoryview(self... | elf.assertEqual(bytes(dm.data), bytes(bdata))
# Test default value
self.assertEqual(bytes(dm.short_data), b"\x08")
def test_max_length(self):
dm = DataModel(short_data=self.binary_data * 4)
with self.ass | = DataModel.objects.get(pk=dm.pk)
self.assertEqual(bytes(dm.data), bytes(bdata))
# Resave (=update)
dm.save()
dm = DataModel.objects.get(pk=dm.pk)
s | {
"filepath": "tests/model_fields/test_binaryfield.py",
"language": "python",
"file_size": 2546,
"cut_index": 563,
"middle_length": 229
} |
test import SimpleTestCase, TestCase
from django.test.utils import ignore_warnings
from django.utils.deprecation import RemovedInDjango70Warning
from .models import BooleanModel, FksToBooleans, NullBooleanModel
class BooleanFieldTests(TestCase):
def _test_get_prep_value(self, f):
self.assertIs(f.get_prep... | ertIs(f.to_python(0), False)
def test_booleanfield_get_prep_value(self):
self._test_get_prep_value(models.BooleanField())
def test_nullbooleanfield_get_prep_value(self):
self._test_get_prep_value(models.BooleanField(null=True))
| tIs(f.get_prep_value("0"), False)
self.assertIs(f.get_prep_value(0), False)
self.assertIsNone(f.get_prep_value(None))
def _test_to_python(self, f):
self.assertIs(f.to_python(1), True)
self.ass | {
"filepath": "tests/model_fields/test_booleanfield.py",
"language": "python",
"file_size": 5161,
"cut_index": 716,
"middle_length": 229
} |
t SimpleTestCase, TestCase
from .models import Post
class TestCharField(TestCase):
def test_max_length_passed_to_formfield(self):
"""
CharField passes its max_length attribute to form fields created using
the formfield() method.
"""
cf1 = models.CharField()
cf2 = m... | le 😀")
def test_assignment_from_choice_enum(self):
class Event(models.TextChoices):
C = "Carnival!"
F = "Festival!"
p1 = Post.objects.create(title=Event.C, body=Event.F)
p1.refresh_from_db()
sel | ):
self.assertEqual(Post.objects.filter(title=9).count(), 0)
def test_emoji(self):
p = Post.objects.create(title="Smile 😀", body="Whatever.")
p.refresh_from_db()
self.assertEqual(p.title, "Smi | {
"filepath": "tests/model_fields/test_charfield.py",
"language": "python",
"file_size": 3859,
"cut_index": 614,
"middle_length": 229
} |
de_settings, skipUnlessDBFeature
from django.test.utils import requires_tz_support
from django.utils import timezone
from .models import DateTimeModel
class DateTimeFieldTests(TestCase):
def test_datetimefield_to_python_microseconds(self):
"""DateTimeField.to_python() supports microseconds."""
f ... | roseconds."""
f = models.TimeField()
self.assertEqual(f.to_python("01:02:03.000004"), datetime.time(1, 2, 3, 4))
self.assertEqual(f.to_python("01:02:03.999999"), datetime.time(1, 2, 3, 999999))
def test_datetimes_save_completel | ual(
f.to_python("2001-01-02 03:04:05.999999"),
datetime.datetime(2001, 1, 2, 3, 4, 5, 999999),
)
def test_timefield_to_python_microseconds(self):
"""TimeField.to_python() supports mic | {
"filepath": "tests/model_fields/test_datetimefield.py",
"language": "python",
"file_size": 3387,
"cut_index": 614,
"middle_length": 229
} |
o.db.models import Max
from django.test import TestCase
from .models import BigD, Foo
class DecimalFieldTests(TestCase):
def test_to_python(self):
f = models.DecimalField(max_digits=4, decimal_places=2)
self.assertEqual(f.to_python(3), Decimal("3"))
self.assertEqual(f.to_python("3.14"), D... | lf):
field = models.DecimalField(max_digits=4, decimal_places=2)
msg = "“%s” value must be a decimal number."
tests = [
(),
[],
{},
set(),
object(),
complex(),
| Decimal("2.400"))
# Uses default rounding of ROUND_HALF_EVEN.
self.assertEqual(f.to_python(2.0625), Decimal("2.062"))
self.assertEqual(f.to_python(2.1875), Decimal("2.188"))
def test_invalid_value(se | {
"filepath": "tests/model_fields/test_decimalfield.py",
"language": "python",
"file_size": 6602,
"cut_index": 716,
"middle_length": 229
} |
ms
from django.core import exceptions, serializers
from django.db import models
from django.test import SimpleTestCase, TestCase
from .models import DurationModel, NullDurationModel
class TestSaveLoad(TestCase):
def test_simple_roundtrip(self):
duration = datetime.timedelta(microseconds=8999999999999999)... | onModel.objects.create(field=value)
d.refresh_from_db()
self.assertEqual(d.field, value)
class TestQuerying(TestCase):
@classmethod
def setUpTestData(cls):
cls.objs = [
DurationModel.objects.create(field=dateti | llDurationModel.objects.create()
loaded = NullDurationModel.objects.get()
self.assertIsNone(loaded.field)
def test_fractional_seconds(self):
value = datetime.timedelta(seconds=2.05)
d = Durati | {
"filepath": "tests/model_fields/test_durationfield.py",
"language": "python",
"file_size": 2949,
"cut_index": 563,
"middle_length": 229
} |
ls.ForeignObject,
models.ManyToManyField,
GenericForeignKey,
GenericRelation,
)
NON_EDITABLE_FIELDS = (
models.BinaryField,
GenericForeignKey,
GenericRelation,
)
RELATION_FIELDS = (
models.ForeignKey,
models.ForeignObject,
models.ManyToManyField,
models.OneToOneField,
Gener... | "model",
"hidden",
"one_to_many",
"many_to_one",
"many_to_many",
"one_to_one",
"related_model",
)
FLAG_PROPERTIES_FOR_RELATIONS = (
"one_to_many",
"many_to_one",
"many_to_many",
"one_to_one",
)
class FieldFlagsTe |
ONE_TO_MANY_CLASSES = {
models.ForeignObjectRel,
models.ManyToOneRel,
GenericRelation,
}
ONE_TO_ONE_CLASSES = {
models.OneToOneField,
}
FLAG_PROPERTIES = (
"concrete",
"editable",
"is_relation",
| {
"filepath": "tests/model_fields/test_field_flags.py",
"language": "python",
"file_size": 7314,
"cut_index": 716,
"middle_length": 229
} |
from django.core.files.base import ContentFile
from django.core.files.uploadedfile import TemporaryUploadedFile
from django.db import IntegrityError, models
from django.test import TestCase, override_settings
from django.test.utils import isolate_apps
from .models import Document, DocumentWithTimestamp
class FileFi... | ):
"""
FileField.save_form_data() considers None to mean "no change" rather
than "clear".
"""
d = Document(myfile="something.txt")
self.assertEqual(d.myfile, "something.txt")
field = d._meta.get_field | nt(myfile="something.txt")
self.assertEqual(d.myfile, "something.txt")
field = d._meta.get_field("myfile")
field.save_form_data(d, False)
self.assertEqual(d.myfile, "")
def test_unchanged(self | {
"filepath": "tests/model_fields/test_filefield.py",
"language": "python",
"file_size": 8545,
"cut_index": 716,
"middle_length": 229
} |
nsaction
from django.test import TestCase
from .models import FloatModel
class TestFloatField(TestCase):
def test_float_validates_object(self):
instance = FloatModel(size=2.5)
# Try setting float field to unsaved object
instance.size = instance
with transaction.atomic():
... | e with FloatField."
) % instance
with transaction.atomic():
with self.assertRaisesMessage(TypeError, msg):
instance.save()
# Try setting field to object on retrieved object
obj = FloatModel.object | .id)
# Set field to object on saved instance
instance.size = instance
msg = (
"Tried to update field model_fields.FloatModel.size with a model "
"instance, %r. Use a value compatibl | {
"filepath": "tests/model_fields/test_floatfield.py",
"language": "python",
"file_size": 1776,
"cut_index": 537,
"middle_length": 229
} |
DBFeature
from django.test.utils import isolate_apps
from .models import Bar, FkToChar, Foo, PrimaryKeyCharModel
class ForeignKeyTests(TestCase):
def test_callable_default(self):
"""A lazy callable may be used for ForeignKey.default."""
a = Foo.objects.create(id=1, a="abc", d=Decimal("12.34"))
... | fk_model_empty = FkToChar.objects.select_related("out").get(
id=fk_model_empty.pk
)
self.assertEqual(fk_model_empty.out, char_model_empty)
@isolate_apps("model_fields")
def test_warning_when_unique_true_on_fk(self):
| strings foreign key values don't get converted to None (#19299).
"""
char_model_empty = PrimaryKeyCharModel.objects.create(string="")
fk_model_empty = FkToChar.objects.create(out=char_model_empty)
| {
"filepath": "tests/model_fields/test_foreignkey.py",
"language": "python",
"file_size": 5921,
"cut_index": 716,
"middle_length": 229
} |
django.test.utils import isolate_apps
from .models import (
Foo,
GeneratedModel,
GeneratedModelCheckConstraint,
GeneratedModelCheckConstraintVirtual,
GeneratedModelFieldWithConverters,
GeneratedModelNonAutoPk,
GeneratedModelNull,
GeneratedModelNullVirtual,
GeneratedModelOutputField... | eneratedField(
expression=Lower("name"),
output_field=CharField(max_length=255),
editable=True,
db_persist=False,
)
@isolate_apps("model_fields")
def test_contribute_to_cl | irtual,
GeneratedModelVirtual,
)
class BaseGeneratedFieldTests(SimpleTestCase):
def test_editable_unsupported(self):
with self.assertRaisesMessage(ValueError, "GeneratedField cannot be editable."):
G | {
"filepath": "tests/model_fields/test_generatedfield.py",
"language": "python",
"file_size": 16513,
"cut_index": 921,
"middle_length": 229
} |
core.exceptions import ValidationError
from django.db import models
from django.test import TestCase
from .models import GenericIPAddress
class GenericIPAddressFieldTests(TestCase):
def test_genericipaddressfield_formfield_protocol(self):
"""
GenericIPAddressField with a specified protocol does n... | ):
form_field.clean("127.0.0.1")
def test_null_value(self):
"""
Null values should be resolved to None.
"""
GenericIPAddress.objects.create()
o = GenericIPAddress.objects.get()
self.assertIsN | lf.assertRaises(ValidationError):
form_field.clean("::1")
model_field = models.GenericIPAddressField(protocol="IPv6")
form_field = model_field.formfield()
with self.assertRaises(ValidationError | {
"filepath": "tests/model_fields/test_genericipaddressfield.py",
"language": "python",
"file_size": 1474,
"cut_index": 524,
"middle_length": 229
} |
sonDimensionsFirst = Person
PersonTwoImages = PersonNoReadImage = Person
class ImageFieldTestMixin(SerializeMixin):
"""
Mixin class to provide common functionality to ImageField test classes.
"""
lockfile = __file__
# Person model to use for tests.
PersonModel = PersonWithHeightAndWidth
... | emp_storage_dir)
self.addCleanup(shutil.rmtree, temp_storage_dir)
file_path1 = os.path.join(os.path.dirname(__file__), "4x8.png")
self.file1 = self.File(open(file_path1, "rb"), name="4x8.png")
self.addCleanup(self.file1.clos | sts) that the model uses as its storage directory.
Sets up two ImageFile instances for use in tests.
"""
if os.path.exists(temp_storage_dir):
shutil.rmtree(temp_storage_dir)
os.mkdir(t | {
"filepath": "tests/model_fields/test_imagefield.py",
"language": "python",
"file_size": 18228,
"cut_index": 1331,
"middle_length": 229
} |
erFieldTests(TestCase):
model = IntegerModel
documented_range = (-2147483648, 2147483647)
rel_db_type_class = models.IntegerField
@property
def backend_range(self):
field = self.model._meta.get_field("value")
internal_type = field.get_internal_type()
return connection.ops.in... | te=min_value)
self.assertEqual(qs.count(), 1)
self.assertEqual(qs[0].value, min_value)
instance = self.model(value=max_value)
instance.full_clean()
instance.save()
qs = self.model.objects.filter(value__gte=m | ut corruption.
"""
min_value, max_value = self.documented_range
instance = self.model(value=min_value)
instance.full_clean()
instance.save()
qs = self.model.objects.filter(value__l | {
"filepath": "tests/model_fields/test_integerfield.py",
"language": "python",
"file_size": 13108,
"cut_index": 921,
"middle_length": 229
} |
t connection
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(),
... | self.assertEqual(
# The tables are processed in an unordered set.
sorted(statements),
[
'DELETE FROM "backends_person";',
'DELETE FROM "backends_tag";',
'DELETE FROM | ,
)
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,
)
| {
"filepath": "tests/backends/sqlite/test_operations.py",
"language": "python",
"file_size": 4180,
"cut_index": 614,
"middle_length": 229
} |
irectBase
from django.shortcuts import redirect
from django.test import SimpleTestCase, override_settings
from django.test.utils import require_jinja2
from django.utils.http import MAX_URL_REDIRECT_LENGTH
@override_settings(ROOT_URLCONF="shortcuts.urls")
class RenderTests(SimpleTestCase):
def test_render(self):
... | r/multiple_templates/")
self.assertEqual(response.status_code, 200)
self.assertEqual(response.content, b"FOO.BAR../render/multiple_templates/\n")
def test_render_with_content_type(self):
response = self.client.get("/render/cont | sponse.headers["Content-Type"], "text/html; charset=utf-8")
self.assertFalse(hasattr(response.context.request, "current_app"))
def test_render_with_multiple_templates(self):
response = self.client.get("/rende | {
"filepath": "tests/shortcuts/tests.py",
"language": "python",
"file_size": 3481,
"cut_index": 614,
"middle_length": 229
} |
ango.db import models
# Forward declared intermediate model
class Membership(models.Model):
person = models.ForeignKey("Person", models.CASCADE)
group = models.ForeignKey("Group", models.CASCADE)
price = models.IntegerField(default=100)
# using custom id column to test ticket #11107
class UserMembership... | (max_length=128)
# Membership object defined as a class
members = models.ManyToManyField(Person, through=Membership)
user_members = models.ManyToManyField(User, through="UserMembership")
def __str__(self):
return self.name
# Usin | ADE)
price = models.IntegerField(default=100)
class Person(models.Model):
name = models.CharField(max_length=128)
def __str__(self):
return self.name
class Group(models.Model):
name = models.CharField | {
"filepath": "tests/m2m_through_regress/models.py",
"language": "python",
"file_size": 2574,
"cut_index": 563,
"middle_length": 229
} |
)
cls.rock = Group.objects.create(name="Rock")
cls.roll = Group.objects.create(name="Roll")
cls.frank = User.objects.create_user("frank", "frank@example.com", "password")
cls.jane = User.objects.create_user("jane", "jane@example.com", "password")
# normal intermediate model
... | frank, group=cls.rock)
cls.frank_roll = UserMembership.objects.create(user=cls.frank, group=cls.roll)
cls.jane_rock = UserMembership.objects.create(user=cls.jane, group=cls.rock)
def test_retrieve_reverse_m2m_items(self):
self. | cls.jim_rock = Membership.objects.create(
person=cls.jim, group=cls.rock, price=50
)
# intermediate model with custom id column
cls.frank_rock = UserMembership.objects.create(user=cls. | {
"filepath": "tests/m2m_through_regress/tests.py",
"language": "python",
"file_size": 9621,
"cut_index": 921,
"middle_length": 229
} |
ent-type/object-id field. A ``GenericForeignKey`` field can point to any
object, be it animal, vegetable, or mineral.
The canonical example is tags (although this example implementation is *far*
from complete).
"""
from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
from django.contrib.c... | lf.tag
class ValuableTaggedItem(TaggedItem):
value = models.PositiveIntegerField()
class AbstractComparison(models.Model):
comparative = models.CharField(max_length=50)
content_type1 = models.ForeignKey(
ContentType, models.CASCADE | Key(ContentType, models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey()
class Meta:
ordering = ["tag", "content_type__model"]
def __str__(self):
return se | {
"filepath": "tests/generic_relations/models.py",
"language": "python",
"file_size": 4142,
"cut_index": 614,
"middle_length": 229
} |
def wraps_decorator(f):
@wraps(f)
def wrapper(*args, **kwargs):
value = f(*args, **kwargs)
return f"{value} -- decorated by @wraps."
return wrapper
def common_decorator(f):
def wrapper(*args, **kwargs):
value = f(*args, **kwargs)
return f"{value} -- common decorated."
... | ms(self):
return Entry.objects.all()
def item_description(self, item):
return "Overridden description: %s" % item
def item_pubdate(self, item):
return item.published
def item_updateddate(self, item):
return it | author_name = "Sally Smith"
author_email = "test@example.com"
author_link = "http://www.example.com/"
categories = ("python", "django")
feed_copyright = "Copyright (c) 2007, Sally Smith"
ttl = 600
def ite | {
"filepath": "tests/syndication_tests/feeds.py",
"language": "python",
"file_size": 8104,
"cut_index": 716,
"middle_length": 229
} |
urlpatterns = [
path("syndication/rss2/", feeds.TestRss2Feed()),
path(
"syndication/rss2/with-callable-object/", feeds.TestRss2FeedWithCallableObject()
),
path(
"syndication/rss2/with-decorated-methods/",
feeds.TestRss2FeedWithDecoratedMethod(),
),
path(
"syndicat... | ),
path("syndication/rss091/", feeds.TestRss091Feed()),
path("syndication/no_pubdate/", feeds.TestNoPubdateFeed()),
path("syndication/atom/", feeds.TestAtomFeed()),
path("syndication/latest/", feeds.TestLatestFeed()),
path("syndicat | (
"syndication/rss2/guid_ispermalink_true/",
feeds.TestRss2FeedWithGuidIsPermaLinkTrue(),
),
path(
"syndication/rss2/guid_ispermalink_false/",
feeds.TestRss2FeedWithGuidIsPermaLinkFalse(),
| {
"filepath": "tests/syndication_tests/urls.py",
"language": "python",
"file_size": 2065,
"cut_index": 563,
"middle_length": 229
} |
override_settings
APP_CONFIG = apps.get_app_config("migrate_signals")
SIGNAL_ARGS = [
"app_config",
"verbosity",
"interactive",
"using",
"stdout",
"plan",
"apps",
]
MIGRATE_DATABASE = "default"
MIGRATE_VERBOSITY = 0
MIGRATE_INTERACTIVE = False
class Receiver:
def __init__(self, signal... | f, signal):
self.signal = signal
self.call_counter = 0
self.call_args = None
self.signal.connect(self, sender=APP_CONFIG)
def __call__(self, signal, sender, **kwargs):
# Although test runner calls migrate for se |
self.call_args = kwargs
class OneTimeReceiver:
"""
Special receiver for handle the fact that test runner calls migrate for
several databases and several times for some of them.
"""
def __init__(sel | {
"filepath": "tests/migrate_signals/tests.py",
"language": "python",
"file_size": 6308,
"cut_index": 716,
"middle_length": 229
} |
f.assertEqual(repr(media_type), "<MediaType: >")
def test_str(self):
self.assertEqual(str(MediaType("*/*; q=0.8")), "*/*; q=0.8")
self.assertEqual(str(MediaType("application/xml")), "application/xml")
self.assertEqual(
str(MediaType("application/xml;type=madeup;q=42")),
... | (" */* ", "application/json"),
("application/*", "application/json"),
("application/*", "application/*"),
("application/xml", "application/xml"),
(" application/xml ", "application/xml"),
("appli | repr(MediaType("application/xml")),
"<MediaType: application/xml>",
)
def test_match(self):
tests = [
("*/*; q=0.8", "*/*"),
("*/*", "application/json"),
| {
"filepath": "tests/requests_tests/test_accept_header.py",
"language": "python",
"file_size": 15241,
"cut_index": 921,
"middle_length": 229
} |
request.POST.urlencode(), "")
# and FILES should be MultiValueDict
self.assertEqual(request.FILES.getlist("foo"), [])
self.assertIsNone(request.content_type)
self.assertIsNone(request.content_params)
def test_httprequest_full_path(self):
request = HttpRequest()
req... | h_with_query_string_and_fragment(self):
request = HttpRequest()
request.path_info = "/foo#bar"
request.path = "/prefix" + request.path_info
request.META["QUERY_STRING"] = "baz#quux"
self.assertEqual(request.get_full_ | some/%3Fawful/%3Dpath/foo:bar/?;some=query&+query=string"
self.assertEqual(request.get_full_path_info(), expected)
self.assertEqual(request.get_full_path(), "/prefix" + expected)
def test_httprequest_full_pat | {
"filepath": "tests/requests_tests/tests.py",
"language": "python",
"file_size": 62687,
"cut_index": 2151,
"middle_length": 229
} |
an initialize a model instance using positional arguments,
which should match the field order as defined in the model.
"""
a = Article(None, "Second article", datetime(2005, 7, 29))
a.save()
self.assertEqual(a.headline, "Second article")
self.assertEqual(a.pub_date, date... | lf):
a1 = Article.objects.create(
headline="First", pub_date=datetime(2005, 7, 30, 0, 0)
)
a2 = Article.objects.create(
headline="First", pub_date=datetime(2005, 7, 30, 0, 0)
)
a3 = Article.ob | 5, 7, 30),
)
a.save()
self.assertEqual(a.headline, "Third article")
self.assertEqual(a.pub_date, datetime(2005, 7, 30, 0, 0))
def test_autofields_generate_different_values_for_each_instance(se | {
"filepath": "tests/basic/tests.py",
"language": "python",
"file_size": 41428,
"cut_index": 2151,
"middle_length": 229
} |
self.assertEqual(models.Index.suffix, "idx")
def test_repr(self):
index = models.Index(fields=["title"])
named_index = models.Index(fields=["title"], name="title_idx")
multi_col_index = models.Index(fields=["title", "author"])
partial_index = models.Index(
fields=... |
func_index = models.Index(Lower("title"), "subtitle", name="book_func_idx")
tablespace_index = models.Index(
fields=["title"],
db_tablespace="idx_tbls",
name="book_tablespace_idx",
)
self | nclude=["author", "pages"],
)
opclasses_index = models.Index(
fields=["headline", "body"],
name="opclasses_idx",
opclasses=["varchar_pattern_ops", "text_pattern_ops"],
) | {
"filepath": "tests/model_indexes/tests.py",
"language": "python",
"file_size": 14735,
"cut_index": 921,
"middle_length": 229
} |
ustomPk,
Detail,
Food,
Individual,
JSONFieldNullable,
Member,
Note,
Number,
Order,
Paragraph,
RelatedObject,
SingleObject,
SpecialCategory,
Tag,
Valid,
)
class WriteToOtherRouter:
def db_for_write(self, model, **hints):
return "other"
class BulkUpd... | cts.bulk_update(self.notes, ["note"])
self.assertCountEqual(
Note.objects.values_list("note", flat=True),
[cat.note for cat in self.notes],
)
def test_multiple_fields(self):
for note in self.notes:
| self.tags = [Tag.objects.create(name=str(i)) for i in range(10)]
def test_simple(self):
for note in self.notes:
note.note = "test-%s" % note.id
with self.assertNumQueries(1):
Note.obje | {
"filepath": "tests/queries/test_bulk_update.py",
"language": "python",
"file_size": 14309,
"cut_index": 921,
"middle_length": 229
} |
rom django.test import TestCase, skipUnlessDBFeature
from django.test.utils import CaptureQueriesContext
from .models import DumbCategory, NonIntegerPKReturningModel, ReturningModel
@skipUnlessDBFeature("can_return_columns_from_insert")
class ReturningValuesTests(TestCase):
def test_insert_returning(self):
... | turning_non_integer(self):
obj = NonIntegerPKReturningModel.objects.create()
self.assertTrue(obj.created)
self.assertIsInstance(obj.created, datetime.datetime)
def test_insert_returning_non_integer_from_literal_value(self):
| nnection.ops.quote_name(DumbCategory._meta.db_table),
connection.ops.quote_name(DumbCategory._meta.get_field("id").column),
),
captured_queries[-1]["sql"],
)
def test_insert_re | {
"filepath": "tests/queries/test_db_returning.py",
"language": "python",
"file_size": 2660,
"cut_index": 563,
"middle_length": 229
} |
ure, skipUnlessDBFeature
from django.test.utils import CaptureQueriesContext
from .models import Tag
@skipUnlessDBFeature("supports_explaining_query_execution")
class ExplainTests(TestCase):
def test_basic(self):
querysets = [
Tag.objects.filter(name="test"),
Tag.objects.filter(na... | e="test"))
)
if connection.features.has_select_for_update:
querysets.append(Tag.objects.select_for_update().filter(name="test"))
supported_formats = connection.features.supported_explain_formats
all_formats = | Tag.objects.filter(name="test").values_list("name"),
]
if connection.features.supports_select_union:
querysets.append(
Tag.objects.order_by().union(Tag.objects.order_by().filter(nam | {
"filepath": "tests/queries/test_explain.py",
"language": "python",
"file_size": 8407,
"cut_index": 716,
"middle_length": 229
} |
:
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"),
("[... | )
field = connection.introspection.get_primary_key_column(
cursor, "test_primary"
)
self.assertEqual(field, expected_string)
finally:
| stable_column_strings:
sql = "CREATE TABLE test_primary (%s int PRIMARY KEY NOT NULL)" % column
with self.subTest(column=column):
try:
cursor.execute(sql | {
"filepath": "tests/backends/sqlite/test_introspection.py",
"language": "python",
"file_size": 7848,
"cut_index": 716,
"middle_length": 229
} |
m django.shortcuts import render
def render_view(request):
return render(
request,
"shortcuts/render_test.html",
{
"foo": "FOO",
"bar": "BAR",
},
)
def render_view_with_multiple_templates(request):
return render(
request,
[
... | def render_view_with_status(request):
return render(
request,
"shortcuts/render_test.html",
{
"foo": "FOO",
"bar": "BAR",
},
status=403,
)
def render_view_with_using(request):
us | h_content_type(request):
return render(
request,
"shortcuts/render_test.html",
{
"foo": "FOO",
"bar": "BAR",
},
content_type="application/x-rendertest",
)
| {
"filepath": "tests/shortcuts/views.py",
"language": "python",
"file_size": 1095,
"cut_index": 515,
"middle_length": 229
} |
(forms.TextInput):
pass
class TaggedItemForm(forms.ModelForm):
class Meta:
model = TaggedItem
fields = "__all__"
widgets = {"tag": CustomWidget}
class GenericInlineFormsetTests(TestCase):
def test_output(self):
GenericFormSet = generic_inlineformset_factory(TaggedItem, ex... | _relations-taggeditem-content_type-object_id-0-tag"
maxlength="50"></p>
<p><label
for="id_generic_relations-taggeditem-content_type-object_id-0-DELETE">
Delete:</label>
<input type="checkb | d_generic_relations-taggeditem-content_type-object_id-0-tag">
Tag:</label>
<input id="id_generic_relations-taggeditem-content_type-object_id-0-tag"
type="text"
name="generic | {
"filepath": "tests/generic_relations/test_forms.py",
"language": "python",
"file_size": 14919,
"cut_index": 921,
"middle_length": 229
} |
etime.datetime(1980, 1, 1, 12, 30),
published=datetime.datetime(1986, 9, 25, 20, 15, 00),
)
cls.e2 = Entry.objects.create(
title="My second entry",
updated=datetime.datetime(2008, 1, 2, 12, 30),
published=datetime.datetime(2006, 3, 17, 18, 0),
)
... | cls.e5 = Entry.objects.create(
title="My last entry",
updated=datetime.datetime(2013, 1, 20, 0, 0),
published=datetime.datetime(2013, 3, 25, 20, 0),
)
cls.a1 = Article.objects.create(
title=" | ,
)
cls.e4 = Entry.objects.create(
title="A & B < C > D",
updated=datetime.datetime(2008, 1, 3, 13, 30),
published=datetime.datetime(2005, 11, 25, 12, 11, 23),
)
| {
"filepath": "tests/syndication_tests/tests.py",
"language": "python",
"file_size": 31865,
"cut_index": 1331,
"middle_length": 229
} |
st.client import RequestFactory
@override_settings(
TEMPLATES=[
{
"BACKEND": "django.template.backends.dummy.TemplateStrings",
"APP_DIRS": True,
},
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"OPTIONS": {
"... | 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.a | .Loader",
"django.template.loaders.app_directories.Loader",
],
},
},
]
)
class TemplateLoaderTests(SimpleTestCase):
def test_get_template_first_engine(self):
| {
"filepath": "tests/template_loader/tests.py",
"language": "python",
"file_size": 7483,
"cut_index": 716,
"middle_length": 229
} |
db import models
class Article(models.Model):
headline = models.CharField(max_length=100, default="Default headline")
pub_date = models.DateTimeField()
class Meta:
ordering = ("pub_date", "headline")
def __str__(self):
return self.headline
class FeaturedArticle(models.Model):
a... | ll=True, blank=True)
article_cited = models.ForeignKey(
Article, models.SET_NULL, null=True, blank=True, related_name="cited"
)
def __str__(self):
# This method intentionally doesn't work for all cases - part
# of the t | SelfRef(models.Model):
selfref = models.ForeignKey(
"self",
models.SET_NULL,
null=True,
blank=True,
related_name="+",
)
article = models.ForeignKey(Article, models.SET_NULL, nu | {
"filepath": "tests/basic/models.py",
"language": "python",
"file_size": 1612,
"cut_index": 537,
"middle_length": 229
} |
self.name
class Note(models.Model):
note = models.CharField(max_length=100)
misc = models.CharField(max_length=25)
tag = models.ForeignKey(Tag, models.SET_NULL, blank=True, null=True)
negate = models.BooleanField(default=True)
class Meta:
ordering = ["note"]
def __str__(self):
... | odel):
info = models.CharField(max_length=100)
note = models.ForeignKey(Note, models.CASCADE, null=True)
value = models.IntegerField(null=True)
date = models.ForeignKey(DateTimePK, models.SET_NULL, null=True)
filterable = models.Boolean | ef __str__(self):
return self.name
class DateTimePK(models.Model):
date = models.DateTimeField(primary_key=True, default=datetime.datetime.now)
class Meta:
ordering = ["date"]
class ExtraInfo(models.M | {
"filepath": "tests/queries/models.py",
"language": "python",
"file_size": 18586,
"cut_index": 1331,
"middle_length": 229
} |
ngo.db import connections
from django.db.models.sql.compiler import cursor_iter
from django.test import TestCase
from .models import Article
class QuerySetIteratorTests(TestCase):
itersize_index_in_mock_args = 3
@classmethod
def setUpTestData(cls):
Article.objects.create(name="Article 1", create... | e=size)
def test_default_iterator_chunk_size(self):
qs = Article.objects.iterator()
with mock.patch(
"django.db.models.sql.compiler.cursor_iter", side_effect=cursor_iter
) as cursor_iter_mock:
next(qs)
| with self.subTest(size=size):
with self.assertRaisesMessage(
ValueError, "Chunk size must be strictly positive."
):
Article.objects.iterator(chunk_siz | {
"filepath": "tests/queries/test_iterator.py",
"language": "python",
"file_size": 2229,
"cut_index": 563,
"middle_length": 229
} |
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... | Message(NotSupportedError, msg):
Item.objects.aggregate(aggregate("time"))
with self.assertRaisesMessage(NotSupportedError, msg):
Item.objects.aggregate(aggregate("date"))
with self.assertRaisesMessag | , Variance, StdDev):
msg = (
f"SQLite does not support {aggregate.__name__} on date or "
"time fields, because they are stored as text."
)
with self.assertRaises | {
"filepath": "tests/backends/sqlite/tests.py",
"language": "python",
"file_size": 13442,
"cut_index": 921,
"middle_length": 229
} |
await self.bacon.tags.acreate(tag="orange")
self.assertEqual(await self.bacon.tags.acount(), 3)
def test_generic_update_or_create_when_created(self):
"""
Should be able to use update_or_create from the generic related manager
to create a tag. Refs #23611.
"""
... | ist create
# a "juicy" tag.
create_defaults={"tag": "juicy"},
defaults={"tag": "uncured"},
tag="stinky",
)
self.assertEqual(tag.tag, "juicy")
self.assertIs(created, True)
self. | ())
def test_generic_update_or_create_when_created_with_create_defaults(self):
count = self.bacon.tags.count()
tag, created = self.bacon.tags.update_or_create(
# Since, the "stinky" tag doesn't ex | {
"filepath": "tests/generic_relations/tests.py",
"language": "python",
"file_size": 38126,
"cut_index": 2151,
"middle_length": 229
} |
SimpleTestCase
from django.test.client import FakePayload
TOO_MANY_FIELDS_MSG = (
"The number of GET/POST parameters exceeded settings.DATA_UPLOAD_MAX_NUMBER_FIELDS."
)
TOO_MANY_FILES_MSG = (
"The number of files exceeded settings.DATA_UPLOAD_MAX_NUMBER_FILES."
)
TOO_MUCH_DATA_MSG = "Request body exceeded set... | }
)
def test_size_exceeded(self):
with self.settings(DATA_UPLOAD_MAX_MEMORY_SIZE=12):
with self.assertRaisesMessage(RequestDataTooBig, TOO_MUCH_DATA_MSG):
self.request._load_post_and_files()
def | SGIRequest(
{
"REQUEST_METHOD": "POST",
"CONTENT_TYPE": "application/x-www-form-urlencoded",
"CONTENT_LENGTH": len(payload),
"wsgi.input": payload,
| {
"filepath": "tests/requests_tests/test_data_upload_settings.py",
"language": "python",
"file_size": 9116,
"cut_index": 716,
"middle_length": 229
} |
m django.db import models
class Book(models.Model):
title = models.CharField(max_length=50)
author = models.CharField(max_length=50)
pages = models.IntegerField(db_column="page_count")
shortcut = models.CharField(max_length=50, db_tablespace="idx_tbls")
isbn = models.CharField(max_length=50, db_ta... | models.CharField(max_length=3)
class Meta:
abstract = True
indexes = [
models.Index(fields=["name"]),
models.Index(fields=["shortcut"], name="%(app_label)s_%(class)s_idx"),
]
class ChildModel1(Abstrac | "]),
models.Index(
fields=["barcode"], name="%(app_label)s_%(class)s_barcode_idx"
),
]
class AbstractModel(models.Model):
name = models.CharField(max_length=50)
shortcut = | {
"filepath": "tests/model_indexes/models.py",
"language": "python",
"file_size": 1063,
"cut_index": 515,
"middle_length": 229
} |
rt (
CompetingTeam,
Event,
Group,
IndividualCompetitor,
Membership,
Person,
)
class MultiTableTests(TestCase):
@classmethod
def setUpTestData(cls):
cls.alice = Person.objects.create(name="Alice")
cls.bob = Person.objects.create(name="Bob")
cls.chris = Person.obj... | .chris)
IndividualCompetitor.objects.create(event=cls.event, person=cls.dan)
CompetingTeam.objects.create(event=cls.event, team=cls.team_alpha)
def test_m2m_query(self):
result = self.event.teams.all()
self.assertCountE | oup=cls.team_alpha)
Membership.objects.create(person=cls.bob, group=cls.team_alpha)
cls.event = Event.objects.create(name="Exposition Match")
IndividualCompetitor.objects.create(event=cls.event, person=cls | {
"filepath": "tests/m2m_through_regress/test_multitable.py",
"language": "python",
"file_size": 2297,
"cut_index": 563,
"middle_length": 229
} |
TestCase
from .models import Person
class PropertyTests(TestCase):
@classmethod
def setUpTestData(cls):
cls.a = Person.objects.create(first_name="John", last_name="Lennon")
def test_getter(self):
self.assertEqual(self.a.full_name, "John Lennon")
def test_setter(self):
# The... | es(AttributeError):
Person(full_name="Paul McCartney")
# But "full_name_2" has, and it can be used to initialize the class.
a2 = Person(full_name_2="Paul McCartney")
a2.save()
self.assertEqual(a2.first_name, "Pa | o initialize the class.
with self.assertRais | {
"filepath": "tests/properties/tests.py",
"language": "python",
"file_size": 848,
"cut_index": 535,
"middle_length": 52
} |
Exact,
IntegerFieldExact,
IntegerLessThanOrEqual,
IsNull,
)
from django.db.models.sql.where import NothingNode
from django.test import SimpleTestCase, TestCase
from .models import Tag
class QTests(SimpleTestCase):
def test_combine_and_empty(self):
q = Q(x=1)
self.assertEqual(q & Q... | l(q | Q(), q)
self.assertEqual(Q() | q, q)
def test_combine_xor_empty(self):
q = Q(x=1)
self.assertEqual(q ^ Q(), q)
self.assertEqual(Q() ^ q, q)
q = Q(x__in={}.keys())
self.assertEqual(q ^ Q(), q)
| :
self.assertEqual(Q() & Q(), Q())
def test_combine_or_empty(self):
q = Q(x=1)
self.assertEqual(q | Q(), q)
self.assertEqual(Q() | q, q)
q = Q(x__in={}.keys())
self.assertEqua | {
"filepath": "tests/queries/test_q.py",
"language": "python",
"file_size": 13242,
"cut_index": 921,
"middle_length": 229
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.