prefix stringlengths 512 512 | suffix stringlengths 256 256 | middle stringlengths 14 229 | meta dict |
|---|---|---|---|
hecks.model_checks.check_all_models])
class DuplicateDBTableTests(SimpleTestCase):
def test_collision_in_same_app(self):
class Model1(models.Model):
class Meta:
db_table = "test_table"
class Model2(models.Model):
class Meta:
db_table = "test_t... | ettings(
DATABASE_ROUTERS=["check_framework.test_model_checks.EmptyRouter"]
)
def test_collision_in_same_app_database_routers_installed(self):
class Model1(models.Model):
class Meta:
db_table = "test_tabl | by multiple models: "
"check_framework.Model1, check_framework.Model2.",
obj="test_table",
id="models.E028",
)
],
)
@override_s | {
"filepath": "tests/check_framework/test_model_checks.py",
"language": "python",
"file_size": 13556,
"cut_index": 921,
"middle_length": 229
} |
t models
from django.test import SimpleTestCase
from django.test.utils import isolate_apps
@isolate_apps("check_framework")
class TestDeprecatedField(SimpleTestCase):
def test_default_details(self):
class MyField(models.Field):
system_check_deprecated_details = {}
class Model(models.M... | els.Field):
system_check_deprecated_details = {
"msg": "This field is deprecated and will be removed soon.",
"hint": "Use something else.",
"id": "fields.W999",
}
class Model( | has been deprecated.",
obj=Model._meta.get_field("name"),
id="fields.WXXX",
)
],
)
def test_user_specified_details(self):
class MyField(mod | {
"filepath": "tests/check_framework/test_model_field_deprecation.py",
"language": "python",
"file_size": 2879,
"cut_index": 563,
"middle_length": 229
} |
from django.db import connections, models
from django.test import SimpleTestCase
from django.test.utils import isolate_apps, override_settings
class TestRouter:
"""
Routes to the 'other' database if the model name starts with 'Other'.
"""
def allow_migrate(self, db, app_label, model_name=None, **hi... | l):
field = models.CharField(max_length=100)
model = Model()
with self._patch_check_field_on("default") as mock_check_field_default:
with self._patch_check_field_on("other") as mock_check_field_other:
| ecks(SimpleTestCase):
def _patch_check_field_on(self, db):
return mock.patch.object(connections[db].validation, "check_field")
def test_checks_called_on_the_default_database(self):
class Model(models.Mode | {
"filepath": "tests/check_framework/test_multi_db.py",
"language": "python",
"file_size": 1726,
"cut_index": 537,
"middle_length": 229
} |
Warn if SESSION_COOKIE_SECURE is off and "django.contrib.sessions" is
in INSTALLED_APPS.
"""
self.assertEqual(sessions.check_session_cookie_secure(None), [sessions.W010])
@override_settings(
SESSION_COOKIE_SECURE="1",
INSTALLED_APPS=["django.contrib.sessions"],
MIDD... | ie_secure_with_middleware(self):
"""
Warn if SESSION_COOKIE_SECURE is off and
"django.contrib.sessions.middleware.SessionMiddleware" is in
MIDDLEWARE.
"""
self.assertEqual(sessions.check_session_cookie_secure | _secure(None), [sessions.W010])
@override_settings(
SESSION_COOKIE_SECURE=False,
INSTALLED_APPS=[],
MIDDLEWARE=["django.contrib.sessions.middleware.SessionMiddleware"],
)
def test_session_cook | {
"filepath": "tests/check_framework/test_security.py",
"language": "python",
"file_size": 30276,
"cut_index": 1331,
"middle_length": 229
} |
o.template.backends.base import BaseEngine
from django.test import SimpleTestCase
from django.test.utils import override_settings
class ErrorEngine(BaseEngine):
def __init__(self, params):
params.pop("OPTIONS")
super().__init__(params)
def check(self, **kwargs):
return [Error("Example... | class CheckTemplateStringIfInvalidTest(SimpleTestCase):
TEMPLATES_STRING_IF_INVALID = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"NAME": "backend_1",
"OPTIONS": {
"strin | {"BACKEND": f"{__name__}.{ErrorEngine.__qualname__}", "NAME": "backend_2"},
]
)
def test_errors_aggregated(self):
errors = check_templates(None)
self.assertEqual(errors, [Error("Example")] * 2)
| {
"filepath": "tests/check_framework/test_templates.py",
"language": "python",
"file_size": 7755,
"cut_index": 716,
"middle_length": 229
} |
ettings_consistent,
check_setting_language_code,
check_setting_languages,
check_setting_languages_bidi,
)
from django.test import SimpleTestCase, override_settings
class TranslationCheckTests(SimpleTestCase):
def setUp(self):
self.valid_tags = (
"en", # language
"mas",... | 123, # invalid type: int.
b"en", # invalid type: bytes.
"eü", # non-latin characters.
"en_US", # locale format.
"en--us", # empty subtag.
"-en", # leading separator.
"en-", | ca-ES-valencia", # language+region+variant
# FIXME: The following should be invalid:
"sr@latin", # language+script
)
self.invalid_tags = (
None, # invalid type: None.
| {
"filepath": "tests/check_framework/test_translation.py",
"language": "python",
"file_size": 4795,
"cut_index": 614,
"middle_length": 229
} |
version import PY314
class CheckUrlConfigTests(SimpleTestCase):
@override_settings(ROOT_URLCONF="check_framework.urls.no_warnings")
def test_no_warnings(self):
result = check_url_config(None)
self.assertEqual(result, [])
@override_settings(ROOT_URLCONF="check_framework.urls.no_warnings_i1... | 0]
self.assertEqual(warning.id, "urls.W001")
@override_settings(ROOT_URLCONF="check_framework.urls.include_with_dollar")
def test_include_with_dollar(self):
result = check_url_config(None)
self.assertEqual(len(result), 1)
| k_resolver_recursive(self):
# The resolver is checked recursively (examining URL patterns in
# include()).
result = check_url_config(None)
self.assertEqual(len(result), 1)
warning = result[ | {
"filepath": "tests/check_framework/test_urls.py",
"language": "python",
"file_size": 14484,
"cut_index": 921,
"middle_length": 229
} |
ror
from django.db import models
from django.test import SimpleTestCase
from django.test.utils import isolate_apps, override_settings, override_system_checks
from .models import SimpleModel, my_check
class DummyObj:
def __repr__(self):
return "obj"
class SystemCheckFrameworkTests(SimpleTestCase):
d... | ", deploy=True)(f3)
# test register as function
registry2 = CheckRegistry()
registry2.register(f)
registry2.register(f2, "tag1", "tag2")
registry2.register(f3, "tag2", deploy=True)
# check results
e | s):
return [5]
calls = [0]
# test register as decorator
registry = CheckRegistry()
registry.register()(f)
registry.register("tag1", "tag2")(f2)
registry.register("tag2 | {
"filepath": "tests/check_framework/tests.py",
"language": "python",
"file_size": 14205,
"cut_index": 921,
"middle_length": 229
} |
ngo.urls import include, path
common_url_patterns = (
[
path("app-ns1/", include([])),
path("app-url/", include([])),
],
"common",
)
nested_url_patterns = (
[
path("common/", include(common_url_patterns, namespace="nested")),
],
"nested",
)
urlpatterns = [
path("ap... | ", include(nested_url_patterns, namespace="nested-1")),
path("app-ns1-3/", include(nested_url_patterns, namespace="nested-2")),
# namespaced URLs inside non-namespaced URLs.
path("app-ns1-4/", include([path("abc/", include(common_url_patterns)) | paced by nested-1 and nested-2.
path("app-ns1-2/ | {
"filepath": "tests/check_framework/urls/unique_namespaces.py",
"language": "python",
"file_size": 835,
"cut_index": 520,
"middle_length": 52
} |
relationship between a model and itself, use
``ForeignKey('self', ...)``.
In this example, a ``Category`` is related to itself. That is, each
``Category`` has a parent ``Category``.
Set ``related_name`` to designate what the reverse relationship is called.
"""
from django.db import models
class Category(models.Mo... | ):
full_name = models.CharField(max_length=20)
mother = models.ForeignKey(
"self", models.SET_NULL, null=True, related_name="mothers_child_set"
)
father = models.ForeignKey(
"self", models.SET_NULL, null=True, related_name=" | return self.name
class Person(models.Model | {
"filepath": "tests/m2o_recursive/models.py",
"language": "python",
"file_size": 969,
"cut_index": 582,
"middle_length": 52
} |
estCase
from .models import Category, Person
class ManyToOneRecursiveTests(TestCase):
@classmethod
def setUpTestData(cls):
cls.r = Category.objects.create(id=None, name="Root category", parent=None)
cls.c = Category.objects.create(id=None, name="Child category", parent=cls.r)
def test_m2... | s):
cls.dad = Person.objects.create(
full_name="John Smith Senior", mother=None, father=None
)
cls.mom = Person.objects.create(
full_name="Jane Smith", mother=None, father=None
)
cls.kid = Per | IsNone(self.r.parent)
self.assertSequenceEqual(self.c.child_set.all(), [])
self.assertEqual(self.c.parent.id, self.r.id)
class MultipleManyToOneRecursiveTests(TestCase):
@classmethod
def setUpTestData(cl | {
"filepath": "tests/m2o_recursive/tests.py",
"language": "python",
"file_size": 1578,
"cut_index": 537,
"middle_length": 229
} |
est_override(self):
self.assertEqual(settings.ITEMS, ["b", "c", "d"])
self.assertEqual(settings.ITEMS_OUTER, [1, 2, 3])
self.assertEqual(settings.TEST, "override")
self.assertEqual(settings.TEST_OUTER, "outer")
@modify_settings(
ITEMS={
"append": ["e", "f"],
... | ide_no_ops(self):
self.assertEqual(settings.ITEMS, ["b", "d"])
@modify_settings(
ITEMS={
"append": "e",
"prepend": "a",
"remove": "c",
}
)
def test_method_list_override_strings(self): | .assertEqual(settings.ITEMS_OUTER, [1, 2, 3])
@modify_settings(
ITEMS={
"append": ["b"],
"prepend": ["d"],
"remove": ["a", "c", "e"],
}
)
def test_method_list_overr | {
"filepath": "tests/settings_tests/tests.py",
"language": "python",
"file_size": 24364,
"cut_index": 1331,
"middle_length": 229
} |
)
name = models.CharField(max_length=50)
class Country(models.Model):
id = models.SmallAutoField(primary_key=True)
name = models.CharField(max_length=50)
class District(models.Model):
city = models.ForeignKey(City, models.CASCADE, primary_key=True)
name = models.CharField(max_length=50)
class ... | e(models.Model):
headline = models.CharField(max_length=100)
pub_date = models.DateField()
body = models.TextField(default="")
reporter = models.ForeignKey(Reporter, models.CASCADE)
response_to = models.ForeignKey("self", models.SET_NUL | rField(null=True)
raw_data = models.BinaryField(null=True)
small_int = models.SmallIntegerField()
interval = models.DurationField()
class Meta:
unique_together = ("first_name", "last_name")
class Articl | {
"filepath": "tests/introspection/models.py",
"language": "python",
"file_size": 4085,
"cut_index": 614,
"middle_length": 229
} |
t()." % Reporter._meta.db_table,
)
self.assertIn(
Article._meta.db_table,
tl,
"'%s' isn't in table_list()." % Article._meta.db_table,
)
def test_django_table_names(self):
with connection.cursor() as cursor:
cursor.execute("CREATE TABLE... | #15216
tl = connection.introspection.django_table_names(only_existing=True)
self.assertIs(type(tl), list)
tl = connection.introspection.django_table_names(only_existing=False)
self.assertIs(type(tl), list)
def test_tab | In(
"django_ixn_test_table",
tl,
"django_table_names() returned a non-Django table",
)
def test_django_table_names_retval_type(self):
# Table name is a list | {
"filepath": "tests/introspection/tests.py",
"language": "python",
"file_size": 18258,
"cut_index": 1331,
"middle_length": 229
} |
ngo.db import connection, models
from django.test import TestCase, skipIfDBFeature, skipUnlessDBFeature
from .models import (
Anchor,
AutoNowDateTimeData,
BigIntegerData,
BinaryData,
BooleanData,
BooleanPKData,
CharData,
CharPKData,
DateData,
DatePKData,
DateTimeData,
Da... | ta,
IntegerPKData,
Intermediate,
LengthModel,
M2MData,
M2MIntermediateData,
M2MSelfData,
ModifyingSaveData,
O2OData,
PositiveBigIntegerData,
PositiveIntegerData,
PositiveIntegerPKData,
PositiveSmallIntegerDat | d,
FKDataToO2O,
FKSelfData,
FKToUUID,
FloatData,
FloatPKData,
GenericData,
GenericIPAddressData,
GenericIPAddressPKData,
ImageData,
InheritAbstractModel,
InheritBaseModel,
IntegerDa | {
"filepath": "tests/serializers/test_data.py",
"language": "python",
"file_size": 17153,
"cut_index": 921,
"middle_length": 229
} |
lizers.json import Deserializer as JsonDeserializer
from django.core.serializers.jsonl import Deserializer as JsonlDeserializer
from django.core.serializers.python import Deserializer
from django.core.serializers.xml_serializer import Deserializer as XMLDeserializer
from django.test import SimpleTestCase
from .models ... | ct_list)
self.jane = Author(name="Jane", pk=1)
self.joe = Author(name="Joe", pk=2)
def test_deserialized_object_repr(self):
deserial_obj = DeserializedObject(obj=self.jane)
self.assertEqual(
repr(deserial_ob | t = [
{"pk": 1, "model": "serializers.author", "fields": {"name": "Jane"}},
{"pk": 2, "model": "serializers.author", "fields": {"name": "Joe"}},
]
self.deserializer = Deserializer(self.obje | {
"filepath": "tests/serializers/test_deserialization.py",
"language": "python",
"file_size": 5224,
"cut_index": 716,
"middle_length": 229
} |
ide
from .models import Score
from .tests import SerializersTestBase, SerializersTransactionTestBase
class JsonSerializerTestCase(SerializersTestBase, TestCase):
serializer_name = "json"
pkless_str = """[
{
"pk": null,
"model": "serializers.category",
"fields": {"name": "Reference... | ata": [],
"topics": []
}
}
]
"""
@staticmethod
def _validate_output(serial_str):
try:
json.loads(serial_str)
except Exception:
return False
else:
return True
@staticmethod
| k)s,
"fields": {
"author": %(author_pk)s,
"headline": "Poker has no place on ESPN",
"pub_date": "2006-06-16T11:00:00",
"categories": [
%(first_category_pk)s,
%(second_category_pk)s
],
"meta_d | {
"filepath": "tests/serializers/test_json.py",
"language": "python",
"file_size": 10634,
"cut_index": 921,
"middle_length": 229
} |
se, TestCase):
serializer_name = "jsonl"
pkless_str = [
'{"pk": null,"model": "serializers.category","fields": {"name": "Reference"}}',
'{"model": "serializers.category","fields": {"name": "Non-fiction"}}',
]
pkless_str = "\n".join([s.replace("\n", "") for s in pkless_str])
mapping_... | ):
try:
for line in serial_str.split("\n"):
if line:
json.loads(line)
except Exception:
return False
else:
return True
@staticmethod
def _get_pk_values | '"pub_date": "2006-06-16T11:00:00",'
'"categories": [%(first_category_pk)s,%(second_category_pk)s],'
'"meta_data": [],'
'"topics": []}}\n'
)
@staticmethod
def _validate_output(serial_str | {
"filepath": "tests/serializers/test_jsonl.py",
"language": "python",
"file_size": 9911,
"cut_index": 921,
"middle_length": 229
} |
User,
)
from .tests import register_tests
class NaturalKeySerializerTests(TestCase):
pass
def natural_key_serializer_test(self, format):
# Create all the objects defined in the test data
with connection.constraint_checks_disabled():
objects = [
NaturalKeyAnchor.objects.create(id=1100... | ert that the deserialized data is the same
# as the original source
for obj in objects:
instance = obj.__class__.objects.get(id=obj.pk)
self.assertEqual(
obj.data,
instance.data,
"Objects with PK= | the test database
serialized_data = serializers.serialize(
format, objects, indent=2, use_natural_foreign_keys=True
)
for obj in serializers.deserialize(format, serialized_data):
obj.save()
# Ass | {
"filepath": "tests/serializers/test_natural.py",
"language": "python",
"file_size": 13659,
"cut_index": 921,
"middle_length": 229
} |
ango.core.exceptions import ImproperlyConfigured
from django.test import override_settings
from .tests import AdminDocsTestCase, TestDataMixin
class XViewMiddlewareTest(TestDataMixin, AdminDocsTestCase):
def test_xview_func(self):
user = User.objects.get(username="super")
response = self.client.h... | , response)
user.is_staff = True
user.is_active = False
user.save()
response = self.client.head("/xview/func/")
self.assertNotIn("X-View", response)
def test_xview_class(self):
user = User.objects.get(us | ew", response)
self.assertEqual(response.headers["X-View"], "admin_docs.views.xview")
user.is_staff = False
user.save()
response = self.client.head("/xview/func/")
self.assertNotIn("X-View" | {
"filepath": "tests/admin_docs/test_middleware.py",
"language": "python",
"file_size": 2413,
"cut_index": 563,
"middle_length": 229
} |
tils installed.")
class AdminDocViewTests(TestDataMixin, AdminDocsTestCase):
def setUp(self):
self.client.force_login(self.superuser)
def test_index(self):
response = self.client.get(reverse("django-admindocs-docroot"))
self.assertContains(response, "<h1>Documentation</h1>", html=True)
... | )
def test_bookmarklets(self):
response = self.client.get(reverse("django-admindocs-bookmarklets"))
self.assertContains(response, "/admindocs/views/")
def test_templatetag_index(self):
response = self.client.get(rev | = self.client.get(reverse("django-admindocs-docroot"), follow=True)
# Should display the login screen
self.assertContains(
response, '<input type="hidden" name="next" value="/admindocs/">', html=True
| {
"filepath": "tests/admin_docs/test_views.py",
"language": "python",
"file_size": 29073,
"cut_index": 1331,
"middle_length": 229
} |
model, are m2m "
"fields, primary keys, or are non-concrete fields: %s"
)
def test_update_fields_basic(self):
s = Person.objects.create(name="Sara", gender="F")
self.assertEqual(s.gender, "F")
s.gender = "M"
s.name = "Ian"
s.save(update_fields=["name"])
... | s1.save()
s2 = Person.objects.get(pk=s1.pk)
self.assertEqual(s2.name, "Emily")
self.assertEqual(s2.gender, "M")
def test_update_fields_only_1(self):
s = Person.objects.create(name="Sara", gender="F")
| ame="Sara", gender="F", pid=22)
self.assertEqual(s.gender, "F")
s1 = Person.objects.defer("gender", "pid").get(pk=s.pk)
s1.name = "Emily"
s1.gender = "M"
with self.assertNumQueries(1):
| {
"filepath": "tests/update_only_fields/tests.py",
"language": "python",
"file_size": 12141,
"cut_index": 921,
"middle_length": 229
} |
"followers_abstract",
"followers_base",
"followers_concrete",
"following_abstract",
"following_base",
"following_inherited",
"friends_abstract",
"friends_base",
"friends_inherited",
"generic_relation_abstract... | BasePerson: [
"content_type_abstract",
"content_type_abstract_id",
"content_type_base",
"content_type_base_id",
"data_abstract",
"data_base",
"data_not_concrete_abs | "object_id_abstract",
"object_id_base",
"object_id_concrete",
"relating_basepeople",
"relating_baseperson",
"relating_people",
"relating_person",
],
| {
"filepath": "tests/model_meta/results.py",
"language": "python",
"file_size": 31141,
"cut_index": 1331,
"middle_length": 229
} |
tractPerson,
BasePerson,
Child,
CommonAncestor,
FirstParent,
Person,
ProxyPerson,
Relating,
Relation,
SecondParent,
Swappable,
)
from .results import TEST_RESULTS
class OptionsBaseTests(SimpleTestCase):
def _map_related_query_names(self, res):
return tuple((o.name, ... | if model == current_model:
model = None
field = relation if direct else relation.field
return (
relation,
model,
direct,
bool(field.many_to_many),
) # many_to_man | del
return None if model == current_model else model
def _details(self, current_model, relation):
direct = isinstance(relation, (Field, GenericForeignKey))
model = relation.model._meta.concrete_model
| {
"filepath": "tests/model_meta/tests.py",
"language": "python",
"file_size": 15100,
"cut_index": 921,
"middle_length": 229
} |
ort models
from django.utils.translation import gettext_lazy as _
class Site(models.Model):
domain = models.CharField(max_length=100)
def __str__(self):
return self.domain
class Article(models.Model):
"""
A simple Article model for testing
"""
site = models.ForeignKey(Site, models.... | xpect")
def test_from_model_with_override(self):
return "nothing"
class ArticleProxy(Article):
class Meta:
proxy = True
class Cascade(models.Model):
num = models.PositiveSmallIntegerField()
parent = models.ForeignKey("se | ("History help text"),
)
created = models.DateTimeField(null=True)
def __str__(self):
return self.title
def test_from_model(self):
return "nothing"
@admin.display(description="not What you E | {
"filepath": "tests/admin_utils/models.py",
"language": "python",
"file_size": 2201,
"cut_index": 563,
"middle_length": 229
} |
mats import localize
from django.utils.safestring import mark_safe
from .models import (
Article,
Car,
Cascade,
DBCascade,
Event,
EventGuide,
Location,
Site,
Vehicle,
)
class NestedObjectsTests(TestCase):
"""
Tests for ``NestedObject`` utility collection.
"""
casc... | lf, *indices):
self.n.collect([self.objs[i] for i in indices])
def test_unrelated_roots(self):
self._connect(2, 1)
self._collect(0)
self._collect(1)
self._check([0, 1, [2]])
def test_siblings(self):
| ge(5)]
def _check(self, target):
self.assertEqual(self.n.nested(lambda obj: obj.num), target)
def _connect(self, i, j):
self.objs[i].parent = self.objs[j]
self.objs[i].save()
def _collect(se | {
"filepath": "tests/admin_utils/tests.py",
"language": "python",
"file_size": 18614,
"cut_index": 1331,
"middle_length": 229
} |
s as the ``default`` parameter to a field. When
the object is created without an explicit value passed in, Django will call
the method to determine the default value.
This example uses ``datetime.datetime.now`` as the default for the ``pub_date``
field.
"""
from datetime import datetime
from decimal import Decimal
f... | xpressions can be passed as the db_default parameter to a field.
When the object is created without an explicit value passed in, the
database will insert the default value automatically.
"""
headline = models.CharField(max_length=100, db_d | models.CharField(max_length=100, default="Default headline")
pub_date = models.DateTimeField(default=datetime.now)
def __str__(self):
return self.headline
class DBArticle(models.Model):
"""
Values or e | {
"filepath": "tests/field_defaults/models.py",
"language": "python",
"file_size": 2217,
"cut_index": 563,
"middle_length": 229
} |
rator(view):
view.is_decorated = True
return view
class DecoratedDispatchView(SimpleView):
@decorator
def dispatch(self, request, *args, **kwargs):
return super().dispatch(request, *args, **kwargs)
class AboutTemplateView(TemplateView):
def get(self, request):
return self.render_... | Factory()
def _assert_simple(self, response):
self.assertEqual(response.status_code, 200)
self.assertEqual(response.content, b"This is a simple view")
def test_no_init_kwargs(self):
"""
A view can't be accidentally |
def get(self, request):
return self.render_to_response(context={})
class InstanceView(View):
def get(self, request):
return self
class ViewTest(LoggingAssertionMixin, SimpleTestCase):
rf = Request | {
"filepath": "tests/generic_views/test_base.py",
"language": "python",
"file_size": 25722,
"cut_index": 1331,
"middle_length": 229
} |
@override_settings(ROOT_URLCONF="generic_views.urls")
class DetailViewTest(TestCase):
@classmethod
def setUpTestData(cls):
cls.artist1 = Artist.objects.create(name="Rene Magritte")
cls.author1 = Author.objects.create(
name="Roberto Bolaño", slug="roberto-bolano"
)
c... | pubdate=datetime.date(2006, 5, 1),
)
cls.page1 = Page.objects.create(
content="I was once bitten by a moose.",
template="generic_views/page_template.html",
)
def test_simple_object(self):
| 0, pubdate=datetime.date(2008, 10, 1)
)
cls.book1.authors.add(cls.author1)
cls.book2 = Book.objects.create(
name="Dreaming in Code",
slug="dreaming-in-code",
pages=300,
| {
"filepath": "tests/generic_views/test_detail.py",
"language": "python",
"file_size": 9548,
"cut_index": 921,
"middle_length": 229
} |
te")
cls.author1 = Author.objects.create(
name="Roberto Bolaño", slug="roberto-bolano"
)
cls.author2 = Author.objects.create(
name="Scott Rosenberg", slug="scott-rosenberg"
)
cls.book1 = Book.objects.create(
name="2066", slug="2066", pages=800,... | mplate.html",
)
def test_items(self):
res = self.client.get("/list/dict/")
self.assertEqual(res.status_code, 200)
self.assertTemplateUsed(res, "generic_views/list.html")
self.assertEqual(res.context["object_list | g-in-code",
pages=300,
pubdate=datetime.date(2006, 5, 1),
)
cls.page1 = Page.objects.create(
content="I was once bitten by a moose.",
template="generic_views/page_te | {
"filepath": "tests/generic_views/test_list.py",
"language": "python",
"file_size": 12689,
"cut_index": 921,
"middle_length": 229
} |
m django.views import generic
from .forms import AuthorForm, ConfirmDeleteForm, ContactForm
from .models import Artist, Author, Book, BookSigning, Page
class CustomTemplateView(generic.TemplateView):
template_name = "generic_views/about.html"
def get_context_data(self, **kwargs):
context = super().g... | eneric.DetailView):
template_name = "generic_views/author_detail.html"
queryset = Author.objects.all()
def get(self, request, *args, **kwargs):
# Ensures get_context_object_name() doesn't reference self.object.
author = self.ge | _object(self):
return {"foo": "bar"}
class ArtistDetail(generic.DetailView):
queryset = Artist.objects.all()
class AuthorDetail(generic.DetailView):
queryset = Author.objects.all()
class AuthorCustomDetail(g | {
"filepath": "tests/generic_views/views.py",
"language": "python",
"file_size": 8620,
"cut_index": 716,
"middle_length": 229
} |
tes.requests import RequestSite
from django.contrib.sites.shortcuts import get_current_site
from django.core import checks
from django.core.exceptions import ObjectDoesNotExist, ValidationError
from django.db.models.signals import post_migrate
from django.http import HttpRequest, HttpResponse
from django.test import Si... | self):
Site.objects.clear_cache()
self.addCleanup(Site.objects.clear_cache)
def test_site_manager(self):
# Make sure that get_current() does not return a deleted Site object.
s = Site.objects.get_current()
self. | orkTests(TestCase):
databases = {"default", "other"}
@classmethod
def setUpTestData(cls):
cls.site = Site(id=settings.SITE_ID, domain="example.com", name="example.com")
cls.site.save()
def setUp( | {
"filepath": "tests/sites_tests/tests.py",
"language": "python",
"file_size": 13842,
"cut_index": 921,
"middle_length": 229
} |
from django.core import checks
from django.core.checks import Error
from django.test import SimpleTestCase
from django.test.utils import isolate_apps, override_settings, override_system_checks
@isolate_apps("check_framework.custom_commands_app", attr_name="apps")
@override_settings(INSTALLED_APPS=["check_framework.cu... | is int, but "
"migrate.Command.autodetector is MigrationAutodetector."
),
id="commands.E001",
)
self.assertEqual(
checks.run_checks(app_configs=self.apps.get_app_configs()),
| ector_different(self):
expected_error = Error(
"The migrate and makemigrations commands must have the same "
"autodetector.",
hint=(
"makemigrations.Command.autodetector | {
"filepath": "tests/check_framework/test_commands.py",
"language": "python",
"file_size": 1025,
"cut_index": 512,
"middle_length": 229
} |
ngo.core.checks.database import check_database_backends
from django.db import connection, connections
from django.test import TestCase
class DatabaseCheckTests(TestCase):
databases = {"default", "other"}
@mock.patch("django.db.backends.base.validation.BaseDatabaseValidation.check")
def test_database_chec... | hasattr(connections[alias], "sql_mode"):
del connections[alias].sql_mode
_clean_sql_mode()
good_sql_modes = [
"STRICT_TRANS_TABLES,STRICT_ALL_TABLES",
"STRICT_TRANS_TABLES",
"STRICT_ | (mocked_check.called)
@unittest.skipUnless(connection.vendor == "mysql", "Test only for MySQL")
def test_mysql_strict_mode(self):
def _clean_sql_mode():
for alias in self.databases:
if | {
"filepath": "tests/check_framework/test_database.py",
"language": "python",
"file_size": 2150,
"cut_index": 563,
"middle_length": 229
} |
ort Value as V
from django.db.models.functions import Lower, StrIndex, Substr, Upper
from django.test import TestCase
from ..models import Author
class SubstrTests(TestCase):
def test_basic(self):
Author.objects.create(name="John Smith", alias="smithj")
Author.objects.create(name="Rhonda")
... | first 5 lower characters of the name.
Author.objects.filter(alias__isnull=True).update(
alias=Lower(Substr("name", 1, 5)),
)
self.assertQuerySetEqual(
authors.order_by("name"), ["smithj", "rhond"], lambda a: | authors = Author.objects.annotate(name_part=Substr("name", 2))
self.assertQuerySetEqual(
authors.order_by("name"), ["ohn Smith", "honda"], lambda a: a.name_part
)
# If alias is null, set to | {
"filepath": "tests/db_functions/text/test_substr.py",
"language": "python",
"file_size": 1918,
"cut_index": 537,
"middle_length": 229
} |
mpleTestCase
@unittest.skipUnless(docutils_is_available, "no docutils installed.")
class TestUtils(AdminDocsSimpleTestCase):
"""
This __doc__ output is required for testing. I copied this example from
`admindocs` documentation. (TITLE)
Display an individual :model:`myapp.MyModel`.
**Context**
... | tput is required for testing. I copied this example from\n"
"`admindocs` documentation. (TITLE)"
)
docstring_description = (
"Display an individual :model:`myapp.MyModel`.\n\n"
"**Context**\n\n``RequestCo | """
def setUp(self):
self.docstring = self.__doc__
def test_parse_docstring(self):
title, description, metadata = parse_docstring(self.docstring)
docstring_title = (
"This __doc__ ou | {
"filepath": "tests/admin_docs/test_utils.py",
"language": "python",
"file_size": 5629,
"cut_index": 716,
"middle_length": 229
} |
rt gettext_lazy as _
class Relation(models.Model):
pass
class InstanceOnlyDescriptor:
def __get__(self, instance, cls=None):
if instance is None:
raise AttributeError("Instance only")
return 1
class AbstractPerson(models.Model):
# DATA fields
data_abstract = models.Char... |
)
# VIRTUAL fields
data_not_concrete_abstract = models.ForeignObject(
Relation,
on_delete=models.CASCADE,
from_fields=["abstract_non_concrete_id"],
to_fields=["id"],
related_name="fo_abstract_rel",
| ation, related_name="m2m_abstract_rel")
friends_abstract = models.ManyToManyField("self", symmetrical=True)
following_abstract = models.ManyToManyField(
"self", related_name="followers_abstract", symmetrical=False | {
"filepath": "tests/model_meta/models.py",
"language": "python",
"file_size": 5710,
"cut_index": 716,
"middle_length": 229
} |
= Site.objects.create(domain="example.org")
cls.a1 = Article.objects.create(
site=cls.site,
title="Title",
created=datetime(2008, 3, 12, 11, 54),
)
cls.a2 = Article.objects.create(
site=cls.site,
title="Title 2",
created=dat... | r)
self.signals = []
pre_save.connect(self.pre_save_listener, sender=LogEntry)
self.addCleanup(pre_save.disconnect, self.pre_save_listener, sender=LogEntry)
post_save.connect(self.post_save_listener, sender=LogEntry)
| )
LogEntry.objects.log_actions(
cls.user.pk,
[cls.a1],
CHANGE,
change_message="Changed something",
)
def setUp(self):
self.client.force_login(self.use | {
"filepath": "tests/admin_utils/test_logentry.py",
"language": "python",
"file_size": 18195,
"cut_index": 1331,
"middle_length": 229
} |
, FloatField, Value, When
from django.db.models.expressions import (
Expression,
ExpressionList,
ExpressionWrapper,
Func,
OrderByList,
RawSQL,
)
from django.db.models.functions import Collate
from django.db.models.lookups import GreaterThan
from django.test import SimpleTestCase, TestCase, skipU... | seconds, 5)
@skipUnlessDBFeature("supports_expression_defaults")
def test_field_db_defaults_returning(self):
a = DBArticle()
a.save()
self.assertIsInstance(a.id, int)
expected_num_queries = (
0 if connec | ld_defaults(self):
a = Article()
now = datetime.now()
a.save()
self.assertIsInstance(a.id, int)
self.assertEqual(a.headline, "Default headline")
self.assertLess((now - a.pub_date). | {
"filepath": "tests/field_defaults/tests.py",
"language": "python",
"file_size": 8846,
"cut_index": 716,
"middle_length": 229
} |
(self):
"""Test prefix can be set (see #18872)"""
test_string = "test"
get_request = self.request_factory.get("/")
class TestFormMixin(FormMixin):
request = get_request
default_kwargs = TestFormMixin().get_form_kwargs()
self.assertIsNone(default_kwargs.get(... | .Form,
"get_form() should use provided form class.",
)
class FormClassTestFormMixin(TestFormMixin):
form_class = forms.Form
self.assertIsInstance(
FormClassTestFormMixin().get_form(),
| efix"))
def test_get_form(self):
class TestFormMixin(FormMixin):
request = self.request_factory.get("/")
self.assertIsInstance(
TestFormMixin().get_form(forms.Form),
forms | {
"filepath": "tests/generic_views/test_edit.py",
"language": "python",
"file_size": 19555,
"cut_index": 1331,
"middle_length": 229
} |
from django.core.checks import Error
from django.core.checks.compatibility.django_4_0 import check_csrf_trusted_origins
from django.test import SimpleTestCase
from django.test.utils import override_settings
class CheckCSRFTrustedOrigins(SimpleTestCase):
@override_settings(CSRF_TRUSTED_ORIGINS=["example.com"])
... | id="4_0.E001",
)
],
)
@override_settings(
CSRF_TRUSTED_ORIGINS=["http://example.com", "https://example.com"],
)
def test_valid_urls(self):
self.assertEqual(check_csrf_trusted_origins(N | he CSRF_TRUSTED_ORIGINS "
"setting must start with a scheme (usually http:// or "
"https://) but found example.com. See the release notes for "
"details.",
| {
"filepath": "tests/check_framework/test_4_0_compatibility.py",
"language": "python",
"file_size": 1007,
"cut_index": 512,
"middle_length": 229
} |
athlib import Path
from django.core.checks import Error
from django.core.checks.files import check_setting_file_upload_temp_dir
from django.test import SimpleTestCase
class FilesCheckTests(SimpleTestCase):
def test_file_upload_temp_dir(self):
tests = [
None,
"",
Path.c... | EMP_DIR=setting):
self.assertEqual(
check_setting_file_upload_temp_dir(None),
[
Error(
"The FILE_UPLOAD_TEMP_DIR setting refers to the "
| (check_setting_file_upload_temp_dir(None), [])
def test_file_upload_temp_dir_nonexistent(self):
for setting in ["nonexistent", Path("nonexistent")]:
with self.subTest(setting), self.settings(FILE_UPLOAD_T | {
"filepath": "tests/check_framework/test_files.py",
"language": "python",
"file_size": 1173,
"cut_index": 518,
"middle_length": 229
} |
nctions import JSONObject, Lower
from django.test import TestCase
from django.test.testcases import skipIfDBFeature, skipUnlessDBFeature
from django.utils import timezone
from ..models import Article, Author
@skipUnlessDBFeature("has_json_object_function")
class JSONObjectTests(TestCase):
@classmethod
def se... | tate(json_object=JSONObject(name="name")).first()
self.assertEqual(obj.json_object, {"name": "Ivan Ivanov"})
def test_expressions(self):
obj = Author.objects.annotate(
json_object=JSONObject(
name=Lower("nam | ]
)
def test_empty(self):
obj = Author.objects.annotate(json_object=JSONObject()).first()
self.assertEqual(obj.json_object, {})
def test_basic(self):
obj = Author.objects.anno | {
"filepath": "tests/db_functions/json/test_json_object.py",
"language": "python",
"file_size": 3653,
"cut_index": 614,
"middle_length": 229
} |
rt Article, Bar, Base, Child, Foo, Whiz
class StringLookupTests(TestCase):
def test_string_form_referencing(self):
"""
Regression test for #1661 and #1662
String form referencing of models works, both as pre and post
reference, on all RelatedField types.
"""
f1 = ... | 1", parent=base1)
child1.save()
self.assertEqual(child1.parent, base1)
def test_unicode_chars_in_queries(self):
"""
Regression tests for #3937
make sure we can use unicode characters in queries.
If the |
b1.save()
self.assertEqual(b1.normal, f1)
self.assertEqual(b1.fwd, w1)
self.assertEqual(b1.back, f2)
base1 = Base(name="Base1")
base1.save()
child1 = Child(name="Child | {
"filepath": "tests/string_lookup/tests.py",
"language": "python",
"file_size": 2448,
"cut_index": 563,
"middle_length": 229
} |
db import models
from django.db.models import QuerySet
from django.db.models.manager import BaseManager
from django.urls import reverse
class Artist(models.Model):
name = models.CharField(max_length=100)
class Meta:
ordering = ["name"]
verbose_name = "professional artist"
verbose_name... | def get(self, *args, **kwargs):
raise Author.DoesNotExist
DoesNotExistBookManager = BaseManager.from_queryset(DoesNotExistQuerySet)
class Book(models.Model):
name = models.CharField(max_length=255)
slug = models.SlugField()
pages = | r(models.Model):
name = models.CharField(max_length=100)
slug = models.SlugField()
class Meta:
ordering = ["name"]
def __str__(self):
return self.name
class DoesNotExistQuerySet(QuerySet):
| {
"filepath": "tests/generic_views/models.py",
"language": "python",
"file_size": 1470,
"cut_index": 524,
"middle_length": 229
} |
late/login_required/", login_required(TemplateView.as_view())),
path(
"template/simple/<foo>/",
TemplateView.as_view(template_name="generic_views/about.html"),
),
path(
"template/custom/<foo>/",
views.CustomTemplateView.as_view(template_name="generic_views/about.html"),
)... | _views/about.html", extra_context={"title": "Title"}
),
),
# DetailView
path("detail/obj/", views.ObjectDetail.as_view()),
path("detail/artist/<int:pk>/", views.ArtistDetail.as_view(), name="artist_detail"),
path("detail/author/ | "template/cached/<foo>/",
cache_page(2)(TemplateView.as_view(template_name="generic_views/about.html")),
),
path(
"template/extra_context/",
TemplateView.as_view(
template_name="generic | {
"filepath": "tests/generic_views/urls.py",
"language": "python",
"file_size": 15118,
"cut_index": 921,
"middle_length": 229
} |
m django.db import models
class Account(models.Model):
num = models.IntegerField()
class Person(models.Model):
GENDER_CHOICES = (
("M", "Male"),
("F", "Female"),
)
name = models.CharField(max_length=20)
gender = models.CharField(max_length=1, choices=GENDER_CHOICES)
pid = mod... | def get_attname_column(self):
attname, _ = super().get_attname_column()
return attname, None
class Profile(models.Model):
name = models.CharField(max_length=200)
salary = models.FloatField(default=1000.0)
non_concrete = NonCo | ed_name="profiles", null=True
)
accounts = models.ManyToManyField("Account", related_name="employees", blank=True)
class NonConcreteField(models.IntegerField):
def db_type(self, connection):
return None
| {
"filepath": "tests/update_only_fields/models.py",
"language": "python",
"file_size": 1084,
"cut_index": 515,
"middle_length": 229
} |
es.status_code, 200)
self.assertEqual(
list(res.context["date_list"]),
list(Book.objects.dates("pubdate", "year", "DESC")),
)
self.assertEqual(list(res.context["latest"]), list(Book.objects.all()))
self.assertTemplateUsed(res, "generic_views/book_archive.html")
... | test", res.context)
self.assertTemplateUsed(res, "generic_views/book_archive.html")
def test_empty_archive_view(self):
Book.objects.all().delete()
res = self.client.get("/dates/books/")
self.assertEqual(res.status_code, | list(res.context["date_list"]),
list(Book.objects.dates("pubdate", "year", "DESC")),
)
self.assertEqual(list(res.context["thingies"]), list(Book.objects.all()))
self.assertNotIn("la | {
"filepath": "tests/generic_views/test_dates.py",
"language": "python",
"file_size": 40388,
"cut_index": 2151,
"middle_length": 229
} |
ache_is_absolute,
)
from django.test import SimpleTestCase
from django.test.utils import override_settings
class CheckCacheSettingsAppDirsTest(SimpleTestCase):
VALID_CACHES_CONFIGURATION = {
"default": {
"BACKEND": "django.core.cache.backends.locmem.LocMemCache",
},
}
INVALID_C... | =INVALID_CACHES_CONFIGURATION)
def test_default_cache_not_included(self):
"""
Error if 'default' not present in CACHES setting.
"""
self.assertEqual(check_default_cache_is_configured(None), [E001])
class CheckCacheLoca | def test_default_cache_included(self):
"""
Don't error if 'default' is present in CACHES setting.
"""
self.assertEqual(check_default_cache_is_configured(None), [])
@override_settings(CACHES | {
"filepath": "tests/check_framework/test_caches.py",
"language": "python",
"file_size": 6218,
"cut_index": 716,
"middle_length": 229
} |
port models
class Foo(models.Model):
name = models.CharField(max_length=50)
friend = models.CharField(max_length=50, blank=True)
class Bar(models.Model):
name = models.CharField(max_length=50)
normal = models.ForeignKey(Foo, models.CASCADE, related_name="normal_foo")
fwd = models.ForeignKey("Whi... | els.CharField(max_length=50)
class Base(models.Model):
name = models.CharField(max_length=50)
class Article(models.Model):
name = models.CharField(max_length=50)
text = models.TextField()
submitted_from = models.GenericIPAddressField(bl | OneToOneField("Base", models.CASCADE)
name = mod | {
"filepath": "tests/string_lookup/models.py",
"language": "python",
"file_size": 858,
"cut_index": 529,
"middle_length": 52
} |
se, TestCase, TransactionTestCase
from .models import Author
from .tests import SerializersTestBase, SerializersTransactionTestBase
try:
import yaml
HAS_YAML = True
except ImportError:
HAS_YAML = False
YAML_IMPORT_ERROR_MESSAGE = r"No module named yaml"
class YamlImportModuleMock:
"""Provides a wr... | #12756
"""
def __init__(self):
self._import_module = importlib.import_module
def import_module(self, module_path):
if module_path == serializers.BUILTIN_SERIALIZERS["yaml"]:
raise ImportError(YAML_IMPORT_ERROR_MES | django CI server),
mock import_module, so that it raises an ImportError when the yaml
serializer is being imported. The importlib.import_module() call is
being made in the serializers.register_serializer().
Refs: | {
"filepath": "tests/serializers/test_yaml.py",
"language": "python",
"file_size": 5495,
"cut_index": 716,
"middle_length": 229
} |
"json2": "django.core.serializers.json",
}
)
class SerializerRegistrationTests(SimpleTestCase):
def setUp(self):
self.old_serializers = serializers._serializers
serializers._serializers = {}
def tearDown(self):
serializers._serializers = self.old_serializers
def test_registe... | "
Unregistering a serializer doesn't cause the registry to be
repopulated.
"""
serializers.unregister_serializer("xml")
serializers.register_serializer("json3", "django.core.serializers.json")
public_formats | s = serializers.get_public_serializer_formats()
self.assertIn("json3", public_formats)
self.assertIn("json2", public_formats)
self.assertIn("xml", public_formats)
def test_unregister(self):
"" | {
"filepath": "tests/serializers/tests.py",
"language": "python",
"file_size": 20916,
"cut_index": 1331,
"middle_length": 229
} |
ser
from django.db import models
class NaturalKeyAnchorManager(models.Manager):
def get_by_natural_key(self, data):
return self.get(data=data)
class NaturalKeyAnchor(models.Model):
data = models.CharField(max_length=100, unique=True)
title = models.CharField(max_length=100, null=True)
objec... | models.ManyToManyField(
"NaturalKeyThing", related_name="thing_m2m_set"
)
class Manager(models.Manager):
def get_by_natural_key(self, key):
return self.get(key=key)
objects = Manager()
def natural_key(self):
| ull=True)
class NaturalKeyThing(models.Model):
key = models.CharField(max_length=100, unique=True)
other_thing = models.ForeignKey(
"NaturalKeyThing", on_delete=models.CASCADE, null=True
)
other_things = | {
"filepath": "tests/serializers/models/natural.py",
"language": "python",
"file_size": 3380,
"cut_index": 614,
"middle_length": 229
} |
rom .models import Choice, Inner, OuterA, OuterB, Poll
class NullQueriesTests(TestCase):
def test_none_as_null(self):
"""
Regression test for the use of None as a query value.
None is interpreted as an SQL NULL, but only in __exact and __iexact
queries.
Set up some initial... | # The same behavior for iexact query.
self.assertSequenceEqual(Choice.objects.filter(choice__iexact=None), [])
# Excluding the previous result returns everything.
self.assertSequenceEqual(
Choice.objects.exclude(choi | ot?")
c2.save()
# Exact query with value None returns nothing ("is NULL" in sql,
# but every 'id' field has a value).
self.assertSequenceEqual(Choice.objects.filter(choice__exact=None), [])
| {
"filepath": "tests/null_queries/tests.py",
"language": "python",
"file_size": 3421,
"cut_index": 614,
"middle_length": 229
} |
te_apps("contenttypes_tests", attr_name="apps")
class GenericForeignKeyTests(SimpleTestCase):
databases = "__all__"
def test_missing_content_type_field(self):
class TaggedItem(models.Model):
# no content_type field
object_id = models.PositiveIntegerField()
content_ob... | est_invalid_content_type_field(self):
class Model(models.Model):
content_type = models.IntegerField() # should be ForeignKey
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey("content_ | erences the nonexistent "
"field 'TaggedItem.content_type'.",
obj=field,
id="contenttypes.E002",
)
]
self.assertEqual(field.check(), expected)
def t | {
"filepath": "tests/contenttypes_tests/test_checks.py",
"language": "python",
"file_size": 10822,
"cut_index": 921,
"middle_length": 229
} |
ype
from django.core.management import call_command
from django.test import TestCase, modify_settings
from django.test.utils import captured_stdout
from .models import ModelWithNullFKToSite, Post
@modify_settings(INSTALLED_APPS={"append": ["empty_models", "no_models"]})
class RemoveStaleContentTypesTests(TestCase):
... | clude_stale_apps=True,
verbosity=2,
)
cls.before_count = ContentType.objects.count()
cls.content_type = ContentType.objects.create(
app_label="contenttypes_tests", model="Fake"
)
def setU | ntrib.contenttypes",
]
@classmethod
def setUpTestData(cls):
with captured_stdout():
call_command(
"remove_stale_contenttypes",
interactive=False,
in | {
"filepath": "tests/contenttypes_tests/test_management.py",
"language": "python",
"file_size": 5365,
"cut_index": 716,
"middle_length": 229
} |
alizer import DTDForbidden
from django.test import TestCase, TransactionTestCase
from .tests import SerializersTestBase, SerializersTransactionTestBase
class XmlSerializerTestCase(SerializersTestBase, TestCase):
serializer_name = "xml"
pkless_str = """<?xml version="1.0" encoding="utf-8"?>
<django-objects ve... | le_pk)s">
<field name="author" rel="ManyToOneRel" to="serializers.author">%(author_pk)s</field>
<field name="headline" type="CharField">Poker has no place on ESPN</field>
<field name="pub_date" type="DateTimeField">2006-06-16T11:00:00</field>
| ="CharField" name="name">Non-fiction</field>
</object>
</django-objects>"""
mapping_ordering_str = """<?xml version="1.0" encoding="utf-8"?>
<django-objects version="1.0">
<object model="serializers.article" pk="%(artic | {
"filepath": "tests/serializers/test_xml.py",
"language": "python",
"file_size": 4719,
"cut_index": 614,
"middle_length": 229
} |
bjects to and from "flat" data (i.e. strings).
"""
from decimal import Decimal
from django.db import models
class CategoryMetaDataManager(models.Manager):
def get_by_natural_key(self, kind, name):
return self.get(kind=kind, name=name)
class CategoryMetaData(models.Model):
kind = models.CharField(m... | x_length=20)
meta_data = models.ForeignKey(
CategoryMetaData, models.SET_NULL, null=True, default=None
)
class Meta:
ordering = ("name",)
def __str__(self):
return self.name
class Author(models.Model):
name = | , "name"),)
def __str__(self):
return "[%s:%s]=%s" % (self.kind, self.name, self.value)
def natural_key(self):
return (self.kind, self.name)
class Category(models.Model):
name = models.CharField(ma | {
"filepath": "tests/serializers/models/base.py",
"language": "python",
"file_size": 4210,
"cut_index": 614,
"middle_length": 229
} |
o import conf
from django.core import mail
from django.core.mail.backends import console
from django.test import SimpleTestCase
from django.test.utils import extend_sys_path
class TestStartProjectSettings(SimpleTestCase):
def setUp(self):
self.temp_dir = tempfile.TemporaryDirectory()
self.addClean... | nsure headers sent by the default MIDDLEWARE don't inadvertently
change. For example, we never want "Vary: Cookie" to appear in the list
since it prevents the caching of responses.
"""
with extend_sys_path(self.temp_dir.name | ings.py-tpl",
)
test_settings_py = os.path.join(self.temp_dir.name, "test_settings.py")
shutil.copyfile(template_settings_py, test_settings_py)
def test_middleware_headers(self):
"""
E | {
"filepath": "tests/project_template/test_settings.py",
"language": "python",
"file_size": 2058,
"cut_index": 563,
"middle_length": 229
} |
ignKey, GenericRelation
from django.contrib.contenttypes.models import ContentType
from django.contrib.sites.models import SiteManager
from django.db import models
class Site(models.Model):
domain = models.CharField(max_length=100)
objects = SiteManager()
class Author(models.Model):
name = models.CharFi... | eturn self.url
class ConcreteModel(models.Model):
name = models.CharField(max_length=10)
class ProxyModel(ConcreteModel):
class Meta:
proxy = True
class FooWithoutUrl(models.Model):
"""
Fake model not defining ``get_absolute_u | ield()
author = models.ForeignKey(Author, models.CASCADE)
date_created = models.DateTimeField()
class SchemeIncludedURL(models.Model):
url = models.URLField(max_length=100)
def get_absolute_url(self):
r | {
"filepath": "tests/contenttypes_tests/models.py",
"language": "python",
"file_size": 3150,
"cut_index": 614,
"middle_length": 229
} |
from django.test.utils import isolate_apps
from .models import Answer, Post, Question
@isolate_apps("contenttypes_tests")
class GenericForeignKeyTests(TestCase):
def test_str(self):
class Model(models.Model):
field = GenericForeignKey()
field = Model._meta.get_field("field")
... | ts.create(text="Who?")
post = Post.objects.create(title="Answer", parent=question)
question_pk = question.pk
Question.objects.all().delete()
post = Post.objects.get(pk=post.pk)
with self.assertNumQueries(1):
| aisesMessage(
Exception, "Impossible arguments to GFK.get_content_type!"
):
field.get_content_type()
def test_get_object_cache_respects_deleted_objects(self):
question = Question.objec | {
"filepath": "tests/contenttypes_tests/test_fields.py",
"language": "python",
"file_size": 5265,
"cut_index": 716,
"middle_length": 229
} |
ddleware.csrf import get_token, rotate_token
from django.template import Context, RequestContext, Template
from django.template.context_processors import csrf
from django.utils.decorators import decorator_from_middleware
from django.utils.deprecation import MiddlewareMixin
from django.views.decorators.csrf import csrf_... | self._cookies_set = []
def set_cookie(self, key, value, **kwargs):
super().set_cookie(key, value, **kwargs)
self._cookies_set.append(value)
class _CsrfCookieRotator(MiddlewareMixin):
def process_response(self, request, response): | S=False.
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# This is a list of the cookie values passed to set_cookie() over
# the course of the request-response.
| {
"filepath": "tests/csrf_tests/views.py",
"language": "python",
"file_size": 2590,
"cut_index": 563,
"middle_length": 229
} |
1:47 GMT"
ETAG = '"b4246ffc4f62314ca13147c9d4f76974"'
WEAK_ETAG = 'W/"b4246ffc4f62314ca13147c9d4f76974"' # weak match to ETAG
EXPIRED_ETAG = '"7fae4cd4b0f81e7d2914700043aa8ed6"'
@override_settings(ROOT_URLCONF="conditional_processing.urls")
class ConditionalGet(SimpleTestCase):
def assertFullResponse(self, respo... | onse.headers["ETag"], ETAG)
else:
self.assertNotIn("Last-Modified", response.headers)
self.assertNotIn("ETag", response.headers)
def assertNotModified(self, response):
self.assertEqual(response.status_code, 304) | est["REQUEST_METHOD"] in ("GET", "HEAD"):
if check_last_modified:
self.assertEqual(response.headers["Last-Modified"], LAST_MODIFIED_STR)
if check_etag:
self.assertEqual(resp | {
"filepath": "tests/conditional_processing/tests.py",
"language": "python",
"file_size": 12853,
"cut_index": 921,
"middle_length": 229
} |
http import HttpResponse
from django.views.decorators.http import condition, etag, last_modified
from .tests import ETAG, FULL_RESPONSE, LAST_MODIFIED, WEAK_ETAG
@condition(lambda r: ETAG, lambda r: LAST_MODIFIED)
def index(request):
return HttpResponse(FULL_RESPONSE)
@condition(last_modified_func=lambda r: LA... | r: ETAG.strip('"'))
def etag_view_unquoted(request):
"""
Use an etag_func() that returns an unquoted ETag.
"""
return HttpResponse(FULL_RESPONSE)
@condition(etag_func=lambda r: WEAK_ETAG)
def etag_view_weak(request):
"""
Use an e | ESPONSE)
@condition(etag_func=lambda r: ETAG)
def etag_view1(request):
return HttpResponse(FULL_RESPONSE)
@etag(lambda r: ETAG)
def etag_view2(request):
return HttpResponse(FULL_RESPONSE)
@condition(etag_func=lambda | {
"filepath": "tests/conditional_processing/views.py",
"language": "python",
"file_size": 1296,
"cut_index": 524,
"middle_length": 229
} |
els
class CurrentTranslation(models.ForeignObject):
"""
Creates virtual relation to the translation with model cache enabled.
"""
# Avoid validation
requires_unique_target = False
def __init__(self, to, on_delete, from_fields, to_fields, **kwargs):
# Disable reverse relation
... |
language = models.CharField(max_length=10, unique=True)
content = models.TextField()
class Article(models.Model):
headline = models.CharField(max_length=100)
pub_date = models.DateTimeField()
published = models.BooleanField(default=F | leTranslation(models.Model):
article = models.ForeignKey("indexes.Article", models.CASCADE)
article_no_constraint = models.ForeignKey(
"indexes.Article", models.CASCADE, db_constraint=False, related_name="+"
) | {
"filepath": "tests/indexes/models.py",
"language": "python",
"file_size": 1678,
"cut_index": 537,
"middle_length": 229
} |
table_name=Article._meta.db_table,
column_names=("c1",),
suffix="123",
)
self.assertEqual(index_name, "indexes_article_c1_a52bd80b123")
def test_index_name(self):
"""
Index names on the built-in database backends::
* Are truncated as needed.
... | _c1_c2_looooooooooooooooooo_255179b2ix",
"oracle": "indexes_a_c1_c2_loo_255179b2ix",
"postgresql": "indexes_article_c1_c2_loooooooooooooooooo_255179b2ix",
"sqlite": "indexes_article_c1_c2_l%sng_255179b2ix" % ("o" * 100), | ndex_name = editor._create_index_name(
table_name=Article._meta.db_table,
column_names=("c1", "c2", long_name),
suffix="ix",
)
expected = {
"mysql": "indexes_article | {
"filepath": "tests/indexes/tests.py",
"language": "python",
"file_size": 27143,
"cut_index": 1331,
"middle_length": 229
} |
` follows all relationships and pre-caches any foreign key
values so that complex trees can be fetched in a single query. However, this
isn't always a good idea, so the ``depth`` argument control how many "levels"
the select-related behavior will traverse.
"""
from django.contrib.contenttypes.fields import GenericFore... | 50)
kingdom = models.ForeignKey(Kingdom, models.CASCADE)
class Klass(models.Model):
name = models.CharField(max_length=50)
phylum = models.ForeignKey(Phylum, models.CASCADE)
class Order(models.Model):
name = models.CharField(max_length= | odels.CharField(max_length=50)
class Kingdom(models.Model):
name = models.CharField(max_length=50)
domain = models.ForeignKey(Domain, models.CASCADE)
class Phylum(models.Model):
name = models.CharField(max_length= | {
"filepath": "tests/select_related/models.py",
"language": "python",
"file_size": 2411,
"cut_index": 563,
"middle_length": 229
} |
Pizza,
Species,
TaggedItem,
)
class SelectRelatedTests(TestCase):
@classmethod
def create_tree(cls, stringtree):
"""
Helper to create a complete tree.
"""
names = stringtree.split()
models = [Domain, Kingdom, Phylum, Klass, Order, Family, Genus, Species]
... | classmethod
def setUpTestData(cls):
cls.create_tree(
"Eukaryota Animalia Anthropoda Insecta Diptera Drosophilidae Drosophila "
"melanogaster"
)
cls.create_tree(
"Eukaryota Animalia Chordata Ma | )
except model.DoesNotExist:
obj = model(name=name)
if parent:
setattr(obj, parent.__class__.__name__.lower(), parent)
obj.save()
parent = obj
@ | {
"filepath": "tests/select_related/tests.py",
"language": "python",
"file_size": 12472,
"cut_index": 921,
"middle_length": 229
} |
e(self):
uf = UploadedFile(name="¿Cómo?", content_type="text")
self.assertIs(type(repr(uf)), str)
def test_unicode_file_name(self):
f = File(None, "djángö")
self.assertIs(type(repr(f)), str)
def test_context_manager(self):
orig_file = tempfile.TemporaryFile()
ba... | , b"content")
def test_open_reopens_closed_file_and_returns_context_manager(self):
temporary_file = tempfile.NamedTemporaryFile(delete=False)
file = File(temporary_file)
try:
file.close()
with file.open( | orig_file.closed)
def test_open_resets_opened_file_to_start_and_returns_context_manager(self):
file = File(BytesIO(b"content"))
file.read()
with file.open() as f:
self.assertEqual(f.read() | {
"filepath": "tests/files/tests.py",
"language": "python",
"file_size": 19882,
"cut_index": 1331,
"middle_length": 229
} |
onError(message_dict)
self.assertEqual(sorted(exception.messages), ["E1", "E2"])
message_dict["field2"] = ["E3", "E4"]
exception = ValidationError(message_dict)
self.assertEqual(sorted(exception.messages), ["E1", "E2", "E3", "E4"])
def test_eq(self):
error1 = ValidationError... | "message"})
error7 = ValidationError(
[
ValidationError({"field1": "field error", "field2": "other"}),
"message",
]
)
self.assertEqual(error1, ValidationError("message"))
| m1)s %(parm2)s",
code="my_code1",
params={"parm1": "val1", "parm2": "val2"},
)
error5 = ValidationError({"field1": "message", "field2": "other"})
error6 = ValidationError({"field1": | {
"filepath": "tests/test_exceptions/test_validation_error.py",
"language": "python",
"file_size": 12403,
"cut_index": 921,
"middle_length": 229
} |
rectly from the table of their base class table rather
than using a new table of their own. This allows them to act as simple proxies,
providing a modified interface to the data from the base class.
"""
from django.db import models
# A couple of managers for testing managing overriding in proxy model cases.
class P... | return self.name
class Abstract(models.Model):
"""
A simple abstract base class, to be used for error checking.
"""
data = models.CharField(max_length=10)
class Meta:
abstract = True
class MyPerson(Person):
"""
| urn super().get_queryset().exclude(name="wilma")
class Person(models.Model):
"""
A simple concrete base class.
"""
name = models.CharField(max_length=50)
objects = PersonManager()
def __str__(self):
| {
"filepath": "tests/proxy_models/models.py",
"language": "python",
"file_size": 4635,
"cut_index": 614,
"middle_length": 229
} |
verse
from .admin import admin as force_admin_model_registration # NOQA
from .models import (
Abstract,
BaseUser,
Bug,
Country,
Improvement,
Issue,
LowerStatusPerson,
MultiUserProxy,
MyPerson,
MyPersonProxy,
OtherPerson,
Person,
ProxyBug,
ProxyImprovement,
P... | MyPerson.other.all().query.get_compiler(DEFAULT_DB_ALIAS).as_sql()
)
person_sql = (
Person.objects.order_by("name")
.query.get_compiler(DEFAULT_DB_ALIAS)
.as_sql()
)
self.assertE | _same_manager_queries(self):
"""
The MyPerson model should be generating the same database queries as
the Person model (when the same manager is used in each case).
"""
my_person_sql = (
| {
"filepath": "tests/proxy_models/tests.py",
"language": "python",
"file_size": 17011,
"cut_index": 921,
"middle_length": 229
} |
Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
friends = models.ManyToManyField("self", blank=True)
class Publisher(models.Model):
name = models.CharField(max_length=255)
num_awards = models.IntegerField()
class Book(models.Model):
isbn = models.CharField(max_len... | re(models.Model):
name = models.CharField(max_length=255)
books = models.ManyToManyField(Book)
original_opening = models.DateTimeField()
friday_night_closing = models.TimeField()
area = models.IntegerField(null=True, db_column="surface" | s = models.ManyToManyField(Author)
contact = models.ForeignKey(Author, models.CASCADE, related_name="book_contact_set")
publisher = models.ForeignKey(Publisher, models.CASCADE)
pubdate = models.DateField()
class Sto | {
"filepath": "tests/annotations/models.py",
"language": "python",
"file_size": 2233,
"cut_index": 563,
"middle_length": 229
} |
J. Chun", age=25)
cls.a8 = Author.objects.create(name="Peter Norvig", age=57)
cls.a9 = Author.objects.create(name="Stuart Russell", age=46)
cls.a1.friends.add(cls.a2, cls.a4)
cls.a2.friends.add(cls.a1, cls.a7)
cls.a4.friends.add(cls.a1)
cls.a5.friends.add(cls.a6, cls.a7)... | eate(name="Morgan Kaufmann", num_awards=9)
cls.p5 = Publisher.objects.create(name="Jonno's House of Books", num_awards=0)
cls.b1 = Book.objects.create(
isbn="159059725",
name="The Definitive Guide to Django: Web Dev | .objects.create(name="Apress", num_awards=3)
cls.p2 = Publisher.objects.create(name="Sams", num_awards=1)
cls.p3 = Publisher.objects.create(name="Prentice Hall", num_awards=7)
cls.p4 = Publisher.objects.cr | {
"filepath": "tests/annotations/tests.py",
"language": "python",
"file_size": 56817,
"cut_index": 2151,
"middle_length": 229
} |
ames
If your database column name is different than your model attribute, use the
``db_column`` parameter. Note that you'll use the field's name, not its column
name, in API usage.
If your database table name is different than your model name, use the
``db_table`` Meta attribute. This has no effect on the API used to... | max_length=30, db_column="firstname")
last_name = models.CharField(max_length=30, db_column="last")
class Meta:
db_table = "my_author_table"
ordering = ("last_name", "first_name")
def __str__(self):
return "%s %s" % (s | his has no effect on the API for querying the database.
"""
from django.db import models
class Author(models.Model):
Author_ID = models.AutoField(primary_key=True, db_column="Author ID")
first_name = models.CharField( | {
"filepath": "tests/custom_columns/models.py",
"language": "python",
"file_size": 1555,
"cut_index": 537,
"middle_length": 229
} |
ticle, Author
class CustomColumnsTests(TestCase):
@classmethod
def setUpTestData(cls):
cls.a1 = Author.objects.create(first_name="John", last_name="Smith")
cls.a2 = Author.objects.create(first_name="Peter", last_name="Jones")
cls.authors = [cls.a1, cls.a2]
cls.article = Articl... |
)
def test_filter_first_name(self):
self.assertSequenceEqual(
Author.objects.filter(first_name__exact="John"),
[self.a1],
)
def test_field_error(self):
msg = (
"Cannot resolve k | uthors(self):
self.assertSequenceEqual(Author.objects.all(), [self.a2, self.a1])
def test_get_first_name(self):
self.assertEqual(
Author.objects.get(first_name__exact="John"),
self.a1, | {
"filepath": "tests/custom_columns/tests.py",
"language": "python",
"file_size": 3723,
"cut_index": 614,
"middle_length": 229
} |
l with callback tracking is
to verify that the behavior of the two match in all tested cases.
"""
available_apps = ["transaction_hooks"]
def setUp(self):
self.notified = []
def notify(self, id_):
if id_ == "error":
raise ForcedError()
self.notified.append(id_)
... | st_executes_immediately_if_no_transaction(self):
self.do(1)
self.assertDone([1])
def test_robust_if_no_transaction(self):
def robust_callback():
raise ForcedError("robust callback")
with self.assertLogs("dj | Done(self, nums):
self.assertNotified(nums)
self.assertEqual(sorted(t.num for t in Thing.objects.all()), sorted(nums))
def assertNotified(self, nums):
self.assertEqual(self.notified, nums)
def te | {
"filepath": "tests/transaction_hooks/tests.py",
"language": "python",
"file_size": 10828,
"cut_index": 921,
"middle_length": 229
} |
ort 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, ... | elf.assertQuerySetEqual(
Issue.objects.filter(client=r.id),
[
1,
2,
],
lambda i: i.num,
)
self.assertQuerySetEqual(
Issue.objects.filter(client=g.id | 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)
s | {
"filepath": "tests/m2m_and_m2o/tests.py",
"language": "python",
"file_size": 2767,
"cut_index": 563,
"middle_length": 229
} |
easons you might want to customize a ``Manager``: to add extra
``Manager`` methods, and/or to modify the initial ``QuerySet`` the ``Manager``
returns.
"""
from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
from django.db import models
class PersonManager(models.Manager):
def get_fu... | )
class CustomQuerySet(models.QuerySet):
def filter(self, *args, **kwargs):
queryset = super().filter(fun=True)
queryset._filter_CustomQuerySet = True
return queryset
def public_method(self, *args, **kwargs):
ret |
class AnnotatedBookManager(models.Manager):
def get_queryset(self):
return (
super()
.get_queryset()
.annotate(favorite_avg=models.Avg("favorite_books__favorite_thing_id"))
| {
"filepath": "tests/custom_managers/models.py",
"language": "python",
"file_size": 6569,
"cut_index": 716,
"middle_length": 229
} |
r="Albert Einstein", is_published=False
)
cls.p1 = Person.objects.create(first_name="Bugs", last_name="Bunny", fun=True)
cls.droopy = Person.objects.create(
first_name="Droopy", last_name="Dog", fun=False
)
def test_custom_manager_basic(self):
"""
Test a... | nager = getattr(Person, manager_name)
# Public methods are copied
manager.public_method()
# Private methods are not copied
with self.assertRaises(AttributeError):
manager. | he methods of a custom QuerySet are properly copied onto the
default Manager.
"""
for manager_name in self.custom_manager_names:
with self.subTest(manager_name=manager_name):
ma | {
"filepath": "tests/custom_managers/tests.py",
"language": "python",
"file_size": 26938,
"cut_index": 1331,
"middle_length": 229
} |
return self.name
class BetterAuthor(Author):
write_speed = models.IntegerField()
class Book(models.Model):
author = models.ForeignKey(Author, models.CASCADE)
title = models.CharField(max_length=100)
class Meta:
unique_together = (("author", "title"),)
ordering = ["id"]
de... | return "%s: %s" % (self.my_pk, self.title)
class Editor(models.Model):
name = models.CharField(max_length=100)
class BookWithOptionalAltEditor(models.Model):
author = models.ForeignKey(Author, models.CASCADE)
# Optional secondary author
| PK(models.Model):
my_pk = models.DecimalField(max_digits=5, decimal_places=0, primary_key=True)
author = models.ForeignKey(Author, models.CASCADE)
title = models.CharField(max_length=100)
def __str__(self):
| {
"filepath": "tests/model_formsets/models.py",
"language": "python",
"file_size": 7156,
"cut_index": 716,
"middle_length": 229
} |
mport (
AutoPKChildOfUUIDPKParent,
AutoPKParent,
ChildRelatedViaAK,
ChildWithEditablePK,
ParentWithUUIDAlternateKey,
UUIDPKChild,
UUIDPKChildOfAutoPKParent,
UUIDPKParent,
)
class InlineFormsetTests(TestCase):
def test_inlineformset_factory_nulls_default_pks(self):
"""
... | 0].fields["parent"].initial)
def test_inlineformset_factory_ignores_default_pks_on_submit(self):
"""
#24377 - Inlines with a model field default should ignore that default
value to avoid triggering validation on empty forms.
| e case where both the parent and child have a UUID primary key.
"""
FormSet = inlineformset_factory(UUIDPKParent, UUIDPKChild, fields="__all__")
formset = FormSet()
self.assertIsNone(formset.forms[ | {
"filepath": "tests/model_formsets/test_uuid.py",
"language": "python",
"file_size": 4727,
"cut_index": 614,
"middle_length": 229
} |
on doesn't cause validation errors.
"""
PoetFormSet = modelformset_factory(Poet, fields="__all__", can_delete=True)
poet = Poet.objects.create(name="test")
data = {
"form-TOTAL_FORMS": "1",
"form-INITIAL_FORMS": "1",
"form-MAX_NUM_FORMS": "0",
... | lly valid.
data["form-0-DELETE"] = "on"
formset = PoetFormSet(data, queryset=Poet.objects.all())
self.assertIs(formset.is_valid(), True)
formset.save()
self.assertEqual(Poet.objects.count(), 0)
def test_outdated | dation.
self.assertIs(formset.is_valid(), False)
self.assertEqual(Poet.objects.count(), 1)
# Then make sure that it *does* pass validation and delete the object,
# even though the data isn't actua | {
"filepath": "tests/model_formsets/tests.py",
"language": "python",
"file_size": 99012,
"cut_index": 3790,
"middle_length": 229
} |
eware
from django.contrib.redirects.models import Redirect
from django.contrib.sites.models import Site
from django.core.exceptions import ImproperlyConfigured
from django.http import HttpResponse, HttpResponseForbidden, HttpResponseRedirect
from django.test import TestCase, modify_settings, override_settings
@modify... | old_path="/initial", new_path="/new_target"
)
self.assertEqual(str(r1), "/initial ---> /new_target")
def test_redirect(self):
Redirect.objects.create(
site=self.site, old_path="/initial", new_path="/new_target"
| ")
class RedirectTests(TestCase):
@classmethod
def setUpTestData(cls):
cls.site = Site.objects.get(pk=settings.SITE_ID)
def test_model(self):
r1 = Redirect.objects.create(
site=self.site, | {
"filepath": "tests/redirects_tests/tests.py",
"language": "python",
"file_size": 4277,
"cut_index": 614,
"middle_length": 229
} |
import SimpleTestCase, override_settings
from django.test.utils import isolate_apps
class MyBigAutoField(models.BigAutoField):
pass
@isolate_apps("model_options")
class TestDefaultPK(SimpleTestCase):
def test_default_value_of_default_auto_field_setting(self):
"""django.conf.global_settings defaults ... | d not be "
"imported."
)
with self.assertRaisesMessage(ImproperlyConfigured, msg):
class Model(models.Model):
pass
@isolate_apps("model_options.apps.ModelPKNonexistentConfig")
def test_app_d | ngo.db.models.NonexistentAutoField")
def test_default_auto_field_setting_nonexistent(self):
msg = (
"DEFAULT_AUTO_FIELD refers to the module "
"'django.db.models.NonexistentAutoField' that coul | {
"filepath": "tests/model_options/test_default_pk.py",
"language": "python",
"file_size": 4676,
"cut_index": 614,
"middle_length": 229
} |
mport (
Article,
ArticleRef,
Authors,
Reviewers,
Scientist,
ScientistRef,
)
def sql_for_table(model):
with connection.schema_editor(collect_sql=True) as editor:
editor.create_model(model)
return editor.collected_sql[0]
def sql_for_index(model):
return "\n".join(
s... | models need to be removed after the test in order to
# prevent bad interactions with the flush operation in other tests.
self._old_models = apps.app_configs["model_options"].models.copy()
for model in Article, Authors, Reviewers, | e model class is defined. As a consequence,
# @override_settings doesn't work, and the tests depend
class TablespacesTests(TransactionTestCase):
available_apps = ["model_options"]
def setUp(self):
# The unmanaged | {
"filepath": "tests/model_options/test_tablespaces.py",
"language": "python",
"file_size": 5441,
"cut_index": 716,
"middle_length": 229
} |
els
# Since the test database doesn't have tablespaces, it's impossible for Django
# to create the tables for models where db_tablespace is set. To avoid this
# problem, we mark the models as unmanaged, and temporarily revert them to
# managed during each test. We also set them to use the same tables as the
# "referen... | = models.ManyToManyField(
ScientistRef, related_name="articles_reviewed_set"
)
class Scientist(models.Model):
name = models.CharField(max_length=50)
class Meta:
db_table = "model_options_scientistref"
db_tablespace = | odels.Model):
title = models.CharField(max_length=50, unique=True)
code = models.CharField(max_length=50, unique=True)
authors = models.ManyToManyField(ScientistRef, related_name="articles_written_set")
reviewers | {
"filepath": "tests/model_options/models/tablespaces.py",
"language": "python",
"file_size": 1881,
"cut_index": 537,
"middle_length": 229
} |
ib import import_module
from django.apps import apps
from django.contrib.auth.models import Permission
from django.contrib.contenttypes.models import ContentType
from django.db import DEFAULT_DB_ALIAS, connections
from django.test import TransactionTestCase
remove_content_type_name = import_module(
"django.contri... | lt database to distinct
# from which database they are fetched.
Permission.objects.all().delete()
ContentType.objects.all().delete()
# ContentType.name in the current version is a property and cannot be
# set, so an | ntrib.auth", "django.contrib.contenttypes"]
def test_add_legacy_name_other_database(self):
# add_legacy_name() should update ContentType objects in the specified
# database. Remove ContentTypes from the defau | {
"filepath": "tests/contenttypes_tests/test_migrations.py",
"language": "python",
"file_size": 1442,
"cut_index": 524,
"middle_length": 229
} |
ithUrl, ProxyModel
class ContentTypesTests(TestCase):
def setUp(self):
ContentType.objects.clear_cache()
self.addCleanup(ContentType.objects.clear_cache)
def test_lookup_cache(self):
"""
The content type cache (see ContentTypeManager) works correctly.
Lookups for a par... | Queries(0):
ct = ContentType.objects.get_for_model(ContentType)
with self.assertNumQueries(0):
ContentType.objects.get_for_id(ct.id)
with self.assertNumQueries(0):
ContentType.objects.get_by_natural_key(" | DB
with self.assertNumQueries(1):
ContentType.objects.get_for_model(ContentType)
# A second hit, though, won't hit the DB, nor will a lookup by ID
# or natural key
with self.assertNum | {
"filepath": "tests/contenttypes_tests/test_models.py",
"language": "python",
"file_size": 14256,
"cut_index": 921,
"middle_length": 229
} |
ort ( # isort:skip
Article,
Author,
FooWithBrokenAbsoluteUrl,
FooWithoutUrl,
FooWithUrl,
ModelWithM2MToSite,
ModelWithNullFKToSite,
SchemeIncludedURL,
Site as MockSite,
UUIDModel,
)
@override_settings(ROOT_URLCONF="contenttypes_tests.urls")
class ContentTypesViewsTests(TestCas... | )
cls.article1 = Article.objects.create(
title="Old Article",
slug="old_article",
author=cls.author1,
date_created=datetime.datetime(2001, 1, 1, 21, 22, 23),
)
cls.article2 = Article.o | h
# remote URLs (got http://example.com/authors/1/)."
cls.site1 = Site(pk=settings.SITE_ID, domain="testserver", name="testserver")
cls.site1.save()
cls.author1 = Author.objects.create(name="Boris" | {
"filepath": "tests/contenttypes_tests/test_views.py",
"language": "python",
"file_size": 11209,
"cut_index": 921,
"middle_length": 229
} |
.management import CommandError
from django.test import TestCase
from .models import Article
class SampleTestCase(TestCase):
fixtures = ["model_package_fixture1.json", "model_package_fixture2.json"]
def test_class_fixtures(self):
"Test cases can load fixture objects into models defined in packages"
... | oad fixture 1. Single JSON file, with two objects
management.call_command("loaddata", "model_package_fixture1.json", verbosity=0)
self.assertQuerySetEqual(
Article.objects.all(),
[
"Time to reform cop | "Poker has no place on ESPN",
],
lambda a: a.headline,
)
class FixtureTestCase(TestCase):
def test_loaddata(self):
"Fixtures can load data into models defined in packages"
# L | {
"filepath": "tests/fixtures_model_package/tests.py",
"language": "python",
"file_size": 2148,
"cut_index": 563,
"middle_length": 229
} |
ON_PICKLE_KEY, models
from django.utils.translation import gettext_lazy as _
def standalone_number():
return 1
class Numbers:
@staticmethod
def get_static_number():
return 2
class PreviousDjangoVersionQuerySet(models.QuerySet):
def __getstate__(self):
state = super().__getstate__()... | jangoVersionQuerySet.as_manager()
missing_django_version_objects = MissingDjangoVersionQuerySet.as_manager()
class Event(models.Model):
title = models.CharField(max_length=100)
group = models.ForeignKey(Group, models.CASCADE, limit_choices_to |
del state[DJANGO_VERSION_PICKLE_KEY]
return state
class Group(models.Model):
name = models.CharField(_("name"), max_length=100)
objects = models.Manager()
previous_django_version_objects = PreviousD | {
"filepath": "tests/queryset_pickle/models.py",
"language": "python",
"file_size": 2194,
"cut_index": 563,
"middle_length": 229
} |
jango.db import models
class Reporter(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
email = models.EmailField()
def __str__(self):
return "%s %s" % (self.first_name, self.last_name)
class Article(models.Model):
headline = models.... | country = models.ForeignKey(
Country, models.CASCADE, related_name="cities", null=True
)
name = models.CharField(max_length=50)
class District(models.Model):
city = models.ForeignKey(City, models.CASCADE, related_name="districts", |
return self.headline
class Country(models.Model):
id = models.SmallAutoField(primary_key=True)
name = models.CharField(max_length=50)
class City(models.Model):
id = models.BigAutoField(primary_key=True)
| {
"filepath": "tests/many_to_one/models.py",
"language": "python",
"file_size": 3529,
"cut_index": 614,
"middle_length": 229
} |
els
class User(models.Model):
username = models.CharField(max_length=100)
email = models.EmailField()
class UserProfile(models.Model):
user = models.OneToOneField(User, models.CASCADE)
city = models.CharField(max_length=100)
state = models.CharField(max_length=2)
class UserStatResult(models.Mo... | at):
karma = models.IntegerField()
class Image(models.Model):
name = models.CharField(max_length=100)
class Product(models.Model):
name = models.CharField(max_length=100)
image = models.OneToOneField(Image, models.SET_NULL, null=True)
| results = models.ForeignKey(UserStatResult, models.CASCADE)
class StatDetails(models.Model):
base_stats = models.OneToOneField(UserStat, models.CASCADE)
comments = models.IntegerField()
class AdvancedUserStat(UserSt | {
"filepath": "tests/select_related_onetoone/models.py",
"language": "python",
"file_size": 1817,
"cut_index": 537,
"middle_length": 229
} |
ation), 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... | e_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")
| on.atomic
def make_reporter():
Reporter.objects.create(first_name="Haddock")
raise Exception("Oops, that's his last name")
with self.assertRaisesMessage(Exception, "Oops"):
mak | {
"filepath": "tests/transactions/tests.py",
"language": "python",
"file_size": 25785,
"cut_index": 1331,
"middle_length": 229
} |
def test_duplicate_pk(self):
"""
This is a regression test for ticket #3790.
"""
# Load a fixture that uses PK=1
management.call_command(
"loaddata",
"sequence",
verbosity=0,
)
# Create a new animal. Without a sequence reset,... | raised for entries in
the serialized data for fields that have been removed
from the database when not ignored.
"""
test_fixtures = [
"sequence_extra",
"sequence_extra_jsonl",
]
if HA | count=2,
weight=2.2,
)
animal.save()
self.assertGreater(animal.id, 1)
def test_loaddata_not_found_fields_not_ignore(self):
"""
Test for ticket #9279 -- Error is | {
"filepath": "tests/fixtures_regress/tests.py",
"language": "python",
"file_size": 34365,
"cut_index": 2151,
"middle_length": 229
} |
rder_by in tests:
with self.subTest(order_by=order_by):
qs = Employee.objects.annotate(
rank=Window(expression=DenseRank(), order_by=order_by),
)
self.assertQuerySetEqual(
qs,
[
... | ("Smith", 38000, "Marketing", datetime.date(2009, 10, 1), 4),
("Brown", 53000, "Sales", datetime.date(2009, 9, 1), 4),
("Williams", 37000, "Accounting", datetime.date(2009, 6, 1), 4),
| 00, "Management", datetime.date(2005, 7, 1), 1),
("Smith", 55000, "Sales", datetime.date(2007, 6, 1), 2),
("Jenson", 45000, "Accounting", datetime.date(2008, 4, 1), 3),
| {
"filepath": "tests/expressions_window/tests.py",
"language": "python",
"file_size": 83458,
"cut_index": 3790,
"middle_length": 229
} |
_fields_list_hashable(self):
reverse_m2m = Person._meta.get_field("events_invited")
self.assertEqual(reverse_m2m.through_fields, ["event", "invitee"])
inherited_reverse_m2m = PersonChild._meta.get_field("events_invited")
self.assertEqual(inherited_reverse_m2m.through_fields, ["event", "i... | diate_model(self):
Membership.objects.create(person=self.jane, group=self.rock)
queryset = Membership.objects.get(person=self.jane, group=self.rock)
self.assertEqual(repr(queryset), "<Membership: Jane is a member of Rock>")
d | f.rock)
Membership.objects.create(person=self.jane, group=self.rock)
expected = ["Jane", "Jim"]
self.assertQuerySetEqual(self.rock.members.all(), expected, attrgetter("name"))
def test_get_on_interme | {
"filepath": "tests/m2m_through/tests.py",
"language": "python",
"file_size": 22898,
"cut_index": 1331,
"middle_length": 229
} |
contenttypes.models import ContentType
from django.db import models
class Author(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
friends = models.ManyToManyField("self", blank=True)
class Publisher(models.Model):
name = models.CharField(max_length=255)
num_awar... | Field()
rating = models.FloatField()
price = models.DecimalField(decimal_places=2, max_digits=6)
authors = models.ManyToManyField(Author)
contact = models.ForeignKey(Author, models.CASCADE, related_name="book_contact_set")
publisher = m | sitiveIntegerField()
content_object = GenericForeignKey("content_type", "object_id")
class Book(models.Model):
isbn = models.CharField(max_length=9)
name = models.CharField(max_length=255)
pages = models.Integer | {
"filepath": "tests/aggregation_regress/models.py",
"language": "python",
"file_size": 3903,
"cut_index": 614,
"middle_length": 229
} |
ns import FieldError
from django.test import TestCase
from .models.default_related_name import Author, Book, Editor
class DefaultRelatedNameTests(TestCase):
@classmethod
def setUpTestData(cls):
cls.author = Author.objects.create(first_name="Dave", last_name="Loper")
cls.editor = Editor.object... | [self.book])
def test_default_related_name_in_queryset_lookup(self):
self.assertEqual(Author.objects.get(books=self.book), self.author)
def test_model_name_not_available_in_queryset_lookup(self):
msg = "Cannot resolve keyword 'boo | s.author)
def test_no_default_related_name(self):
self.assertEqual(list(self.author.editor_set.all()), [self.editor])
def test_default_related_name(self):
self.assertEqual(list(self.author.books.all()), | {
"filepath": "tests/model_options/test_default_related_name.py",
"language": "python",
"file_size": 1598,
"cut_index": 537,
"middle_length": 229
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.