prefix stringlengths 512 512 | suffix stringlengths 256 256 | middle stringlengths 14 229 | meta dict |
|---|---|---|---|
_permissions import CustomPermissionsUser
from .custom_user import (
CustomUser,
CustomUserCompositePrimaryKey,
CustomUserWithoutIsActiveField,
ExtensionUser,
)
from .invalid_models import CustomUserNonUniqueUsername
from .is_active import IsActiveTestUser1
from .minimal import MinimalUser
from .no_natu... | CustomUserWithM2MThrough, Organization
from .with_unique_constraint import CustomUserWithUniqueConstraint
__all__ = (
"CustomEmailField",
"CustomPermissionsUser",
"CustomUser",
"CustomUserCompositePrimaryKey",
"CustomUserNoNaturalKey" | Field
from .with_foreign_key import CustomUserWithFK, Email
from .with_integer_username import IntegerUsernameUser
from .with_last_login_attr import UserWithDisabledLastLoginField
from .with_many_to_many import CustomUserWithM2M, | {
"filepath": "tests/auth_tests/models/__init__.py",
"language": "python",
"file_size": 1436,
"cut_index": 524,
"middle_length": 229
} |
jango.contrib.auth.models import AbstractBaseUser, BaseUserManager
from django.db import models
class Organization(models.Model):
name = models.CharField(max_length=255)
class CustomUserWithM2MManager(BaseUserManager):
def create_superuser(self, username, orgs, password):
user = self.model(username=... | hrough(AbstractBaseUser):
username = models.CharField(max_length=30, unique=True)
orgs = models.ManyToManyField(Organization, through="Membership")
custom_objects = CustomUserWithM2MManager()
USERNAME_FIELD = "username"
REQUIRED_FIELD | els.CharField(max_length=30, unique=True)
orgs = models.ManyToManyField(Organization)
custom_objects = CustomUserWithM2MManager()
USERNAME_FIELD = "username"
REQUIRED_FIELDS = ["orgs"]
class CustomUserWithM2MT | {
"filepath": "tests/auth_tests/models/with_many_to_many.py",
"language": "python",
"file_size": 1208,
"cut_index": 518,
"middle_length": 229
} |
ort TestCase
from .models import Comment, Forum, Item, Post, PropertyValue, SystemDetails, SystemInfo
class NullFkTests(TestCase):
def test_null_fk(self):
d = SystemDetails.objects.create(details="First details")
s = SystemInfo.objects.create(system_name="First forum", system_details=d)
f... | vels of
# NULLs (and the things that come after the NULLs, or else data that
# should exist won't). Regression test for #7369.
c = Comment.objects.select_related("post").get(id=c1.id)
self.assertEqual(c.post, p)
self | comment")
c2 = Comment.objects.create(comment_text="My second comment")
# Starting from comment, make sure that a .select_related(...) with a
# specified set of fields will properly LEFT JOIN multiple le | {
"filepath": "tests/null_fk/tests.py",
"language": "python",
"file_size": 2964,
"cut_index": 563,
"middle_length": 229
} |
A custom AdminSite for AdminViewPermissionsTest.test_login_has_permission().
"""
from django.contrib import admin
from django.contrib.auth import get_permission_codename
from django.contrib.auth.forms import AuthenticationForm
from django.core.exceptions import ValidationError
from . import admin as base_admin
from ... | orm = PermissionAdminAuthenticationForm
def has_permission(self, request):
return request.user.is_active and (
request.user.is_staff or request.user.has_perm(PERMISSION_NAME)
)
site = HasPermissionAdmin(name="has_permissi | rm_login_allowed(self, user):
if not user.is_active or not (user.is_staff or user.has_perm(PERMISSION_NAME)):
raise ValidationError("permission denied")
class HasPermissionAdmin(admin.AdminSite):
login_f | {
"filepath": "tests/admin_views/custom_has_permission_admin.py",
"language": "python",
"file_size": 1066,
"cut_index": 515,
"middle_length": 229
} |
eysTestCase(TestCase):
def test_user_natural_key(self):
staff_user = User.objects.create_user(username="staff")
self.assertEqual(User.objects.get_by_natural_key("staff"), staff_user)
self.assertEqual(staff_user.natural_key(), ("staff",))
async def test_auser_natural_key(self):
s... | l_key(self):
users_group = await Group.objects.acreate(name="users")
self.assertEqual(await Group.objects.aget_by_natural_key("users"), users_group)
class LoadDataWithoutNaturalKeysTestCase(TestCase):
fixtures = ["regular.json"]
| key(), ("staff",))
def test_group_natural_key(self):
users_group = Group.objects.create(name="users")
self.assertEqual(Group.objects.get_by_natural_key("users"), users_group)
async def test_agroup_natura | {
"filepath": "tests/auth_tests/test_models.py",
"language": "python",
"file_size": 24678,
"cut_index": 1331,
"middle_length": 229
} |
xceptions import ImproperlyConfigured
from django.test import TestCase
from django.test.utils import override_settings
from .models import CustomEmailField
class MockedPasswordResetTokenGenerator(PasswordResetTokenGenerator):
def __init__(self, now):
self._now_val = now
super().__init__()
de... | the same request
will work correctly.
"""
user = User.objects.create_user("comebackkid", "test3@example.com", "testpw")
user_reload = User.objects.get(username="comebackkid")
p0 = MockedPasswordResetTokenGenerator(da | estpw")
p0 = PasswordResetTokenGenerator()
tk1 = p0.make_token(user)
self.assertIs(p0.check_token(user, tk1), True)
def test_10265(self):
"""
The token generated for a user created in | {
"filepath": "tests/auth_tests/test_tokens.py",
"language": "python",
"file_size": 7569,
"cut_index": 716,
"middle_length": 229
} |
uth.views import (
PasswordChangeDoneView,
PasswordChangeView,
PasswordResetCompleteView,
PasswordResetDoneView,
PasswordResetView,
)
from django.test import RequestFactory, TestCase, override_settings
from django.urls import reverse
from django.utils.http import urlsafe_base64_encode
from .client ... | ory.get("/somepath/")
request.user = user
cls.user, cls.request = user, request
def test_password_reset_view(self):
response = PasswordResetView.as_view(success_url="dummy/")(self.request)
self.assertContains(
|
@classmethod
def setUpTestData(cls):
user = User.objects.create_user("jsmith", "jsmith@example.com", "pass")
user = authenticate(username=user.username, password="pass")
request = cls.request_fact | {
"filepath": "tests/auth_tests/test_templates.py",
"language": "python",
"file_size": 8194,
"cut_index": 716,
"middle_length": 229
} |
ized", "_view")
)
def special_table_only(table_name):
return table_name.startswith("inspectdb_special")
def cursor_execute(*queries):
"""
Execute SQL queries using a new cursor on the default database connection.
"""
results = []
with connection.cursor() as cursor:
for q in queri... | ectdb has examined a table that should have been filtered out."
)
# contrib.contenttypes is one of the apps always installed when running
# the Django test suite, check that one of its tables hasn't been
# inspected
| her = \((.+),\).*")
def test_stealth_table_name_filter_option(self):
out = StringIO()
call_command("inspectdb", table_name_filter=inspectdb_tables_only, stdout=out)
error_message = (
"insp | {
"filepath": "tests/inspectdb/tests.py",
"language": "python",
"file_size": 27761,
"cut_index": 1331,
"middle_length": 229
} |
Group,
Permission,
PermissionsMixin,
UserManager,
)
from django.db import models
# The custom user uses email as the unique identifier, and requires
# that every user provide a date of birth. This lets us test
# changes in username datatype, and non-text required fields.
class CustomUserManager(BaseUs... | rd)
user.save(using=self._db)
return user
async def acreate_user(self, email, date_of_birth, password=None, **fields):
"""See create_user()"""
if not email:
raise ValueError("Users must have an email address | email:
raise ValueError("Users must have an email address")
user = self.model(
email=self.normalize_email(email), date_of_birth=date_of_birth, **fields
)
user.set_password(passwo | {
"filepath": "tests/auth_tests/models/custom_user.py",
"language": "python",
"file_size": 4975,
"cut_index": 614,
"middle_length": 229
} |
r the update() queryset method that allows in-place, multi-object
updates.
"""
from django.db import models
class DataPoint(models.Model):
name = models.CharField(max_length=20)
value = models.CharField(max_length=20)
another_value = models.CharField(max_length=20, blank=True)
is_active = models.Bool... | odels.ForeignKey(A, models.CASCADE)
class Foo(models.Model):
target = models.CharField(max_length=10, unique=True)
class Bar(models.Model):
foo = models.ForeignKey(Foo, models.CASCADE, to_field="target")
o2o_foo = models.OneToOneField(
| odels.IntegerField(default=10)
class B(models.Model):
a = models.ForeignKey(A, models.CASCADE)
y = models.IntegerField(default=10)
class C(models.Model):
y = models.IntegerField(default=10)
class D(C):
a = m | {
"filepath": "tests/update/models.py",
"language": "python",
"file_size": 1311,
"cut_index": 524,
"middle_length": 229
} |
e64", "", included_kwargs),
),
(
"/base64/aGVsbG8=/namespaced/d29ybGQ=/",
("subpattern-base64", "namespaced-base64", included_kwargs),
),
)
@override_settings(ROOT_URLCONF="urlpatterns.path_urls")
class SimplifiedURLTests(SimpleTestCase):
def test_path_lookup_without_parameters(self):
... | "/articles/2015/")
self.assertEqual(match.url_name, "articles-year")
self.assertEqual(match.args, ())
self.assertEqual(match.kwargs, {"year": 2015})
self.assertEqual(match.route, "articles/<int:year>/")
self.assertEq | self.assertEqual(match.route, "articles/2003/")
self.assertEqual(match.captured_kwargs, {})
self.assertEqual(match.extra_kwargs, {})
def test_path_lookup_with_typed_parameters(self):
match = resolve( | {
"filepath": "tests/urlpatterns/tests.py",
"language": "python",
"file_size": 17807,
"cut_index": 1331,
"middle_length": 229
} |
DB-API Shortcuts
``get_object_or_404()`` is a shortcut function to be used in view functions for
performing a ``get()`` lookup and raising a ``Http404`` exception if a
``DoesNotExist`` exception was raised during the ``get()`` call.
``get_list_or_404()`` is a shortcut function to be used in view functions for
perfor... | els.Manager):
def get_queryset(self):
raise AttributeError("AttributeErrorManager")
class Article(models.Model):
authors = models.ManyToManyField(Author)
title = models.CharField(max_length=50)
objects = models.Manager()
by_a_ | Model):
name = models.CharField(max_length=50)
class ArticleManager(models.Manager):
def get_queryset(self):
return super().get_queryset().filter(authors__name__icontains="sir")
class AttributeErrorManager(mod | {
"filepath": "tests/get_object_or_404/models.py",
"language": "python",
"file_size": 1077,
"cut_index": 515,
"middle_length": 229
} |
r_404, get_object_or_404
from django.test import TestCase
from .models import Article, Author
class GetObjectOr404Tests(TestCase):
def test_get_object_or_404(self):
a1 = Author.objects.create(name="Brave Sir Robin")
a2 = Author.objects.create(name="Patsy")
# No Articles yet, so we should... | hor object.
self.assertEqual(
get_object_or_404(a1.article_set, title__contains="Run"), article
)
# No articles containing "Camelot". This should raise an Http404 error.
with self.assertRaises(Http404):
| .authors.set([a1, a2])
# get_object_or_404 can be passed a Model to query.
self.assertEqual(get_object_or_404(Article, title__contains="Run"), article)
# We can also use the Article manager through an Aut | {
"filepath": "tests/get_object_or_404/tests.py",
"language": "python",
"file_size": 4678,
"cut_index": 614,
"middle_length": 229
} |
models.CharField(max_length=100)
class Parent(models.Model):
name = models.CharField(max_length=100)
class Child(models.Model):
mother = models.ForeignKey(Parent, models.CASCADE, related_name="mothers_children")
father = models.ForeignKey(Parent, models.CASCADE, related_name="fathers_children")
scho... | del):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
class Poem(models.Model):
poet = models.ForeignKey(Poet, models.CASCADE)
name = models.CharField(max_length=100)
class Meta:
unique_to | ="unique_parents"),
]
class Poet(models.Mo | {
"filepath": "tests/inline_formsets/models.py",
"language": "python",
"file_size": 965,
"cut_index": 582,
"middle_length": 52
} |
= poet.poem_set.create(name="test poem")
data = {
"poem_set-TOTAL_FORMS": "1",
"poem_set-INITIAL_FORMS": "1",
"poem_set-MAX_NUM_FORMS": "0",
"poem_set-0-id": str(poem.pk),
"poem_set-0-poet": str(poet.pk),
"poem_set-0-name": "test",
... | mSet = inlineformset_factory(
Poet, Poem, can_delete=True, fields="__all__"
)
poet = Poet.objects.create(name="test")
data = {
"poem_set-TOTAL_FORMS": "1",
"poem_set-INITIAL_FORMS": "0",
| jects.count(), 0)
def test_add_form_deletion_when_invalid(self):
"""
Make sure that an add form that is filled out, but marked for deletion
doesn't cause validation errors.
"""
PoemFor | {
"filepath": "tests/inline_formsets/tests.py",
"language": "python",
"file_size": 9941,
"cut_index": 921,
"middle_length": 229
} |
unittest import TestCase
from django.test import SimpleTestCase
from django.test import TestCase as DjangoTestCase
class DjangoCase1(DjangoTestCase):
def test_1(self):
pass
def test_2(self):
pass
class DjangoCase2(DjangoTestCase):
def test_1(self):
pass
def test_2(self):
... | 2(self):
pass
class UnittestCase1(TestCase):
def test_1(self):
pass
def test_2(self):
pass
class UnittestCase2(TestCase):
def test_1(self):
pass
def test_2(self):
pass
def test_3_test(self) |
def test_ | {
"filepath": "tests/test_runner_apps/simple/tests.py",
"language": "python",
"file_size": 802,
"cut_index": 517,
"middle_length": 14
} |
ctest example from the official Python documentation.
https://docs.python.org/library/doctest.html
"""
def factorial(n):
"""Return the factorial of n, an exact integer >= 0.
>>> [factorial(n) for n in range(6)]
[1, 1, 2, 6, 24, 120]
>>> factorial(30) # doctest: +ELLIPSIS
265252859812191058636308... | iculously large:
>>> factorial(1e100)
Traceback (most recent call last):
...
OverflowError: n too large
"""
import math
if not n >= 0:
raise ValueError("n must be >= 0")
if math.floor(n) != n:
raise Val | >>> factorial(30.1)
Traceback (most recent call last):
...
ValueError: n must be exact integer
>>> factorial(30.0) # doctest: +ELLIPSIS
265252859812191058636308480000000...
It must also not be rid | {
"filepath": "tests/test_runner_apps/sample/doctests.py",
"language": "python",
"file_size": 1244,
"cut_index": 518,
"middle_length": 229
} |
ls.translation import gettext_lazy
def add_level_messages(storage):
"""
Add 6 messages from different levels (including a custom one) to a storage
instance.
"""
storage.add(constants.INFO, "A generic info message")
storage.add(29, "Some custom level")
storage.add(constants.DEBUG, "A debugg... | stants.ERROR,
}
@classmethod
def setUpClass(cls):
cls.enterClassContext(
override_settings(
TEMPLATES=[
{
"BACKEND": "django.template.backends.django.DjangoTemplat | lass BaseTests:
storage_class = default_storage
levels = {
"debug": constants.DEBUG,
"info": constants.INFO,
"success": constants.SUCCESS,
"warning": constants.WARNING,
"error": con | {
"filepath": "tests/messages_tests/base.py",
"language": "python",
"file_size": 13980,
"cut_index": 921,
"middle_length": 229
} |
t messages
from django.test import RequestFactory, SimpleTestCase
from .utils import DummyStorage
class ApiTests(SimpleTestCase):
rf = RequestFactory()
def setUp(self):
self.request = self.rf.request()
self.storage = DummyStorage()
def test_ok(self):
msg = "some message"
... | messages.add_message(None, messages.DEBUG, "some message")
self.assertEqual(self.storage.store, [])
def test_middleware_missing(self):
msg = (
"You cannot add messages without installing "
"django.contrib.me | def test_request_is_none(self):
msg = "add_message() argument must be an HttpRequest object, not 'NoneType'."
self.request._messages = self.storage
with self.assertRaisesMessage(TypeError, msg):
| {
"filepath": "tests/messages_tests/test_api.py",
"language": "python",
"file_size": 2016,
"cut_index": 537,
"middle_length": 229
} |
okieStorage,
MessageDecoder,
MessageEncoder,
bisect_keep_left,
bisect_keep_right,
)
from django.test import SimpleTestCase, override_settings
from django.utils.crypto import get_random_string
from django.utils.safestring import SafeData, mark_safe
from .base import BaseTests
def set_cookie_data(stora... | ame: encoded_data}
if hasattr(storage, "_loaded_data"):
del storage._loaded_data
def stored_cookie_messages_count(storage, response):
"""
Return an integer containing the number of messages stored.
"""
# Get a list of cookies, | torage._encode(messages, encode_empty=encode_empty)
if invalid:
# Truncate the first character so that the hash is invalid.
encoded_data = encoded_data[1:]
storage.request.COOKIES = {CookieStorage.cookie_n | {
"filepath": "tests/messages_tests/test_cookie.py",
"language": "python",
"file_size": 8695,
"cut_index": 716,
"middle_length": 229
} |
ypto import get_random_string
from .base import BaseTests
from .test_cookie import set_cookie_data, stored_cookie_messages_count
from .test_session import set_session_data, stored_session_messages_count
class FallbackTests(BaseTests, SimpleTestCase):
storage_class = FallbackStorage
def get_request(self):
... | orage), response)
def stored_session_messages_count(self, storage, response):
return stored_session_messages_count(self.get_session_storage(storage))
def stored_messages_count(self, storage, response):
"""
Return the stora | .storages[-2]
def get_session_storage(self, storage):
return storage.storages[-1]
def stored_cookie_messages_count(self, storage, response):
return stored_cookie_messages_count(self.get_cookie_storage(st | {
"filepath": "tests/messages_tests/test_fallback.py",
"language": "python",
"file_size": 6868,
"cut_index": 716,
"middle_length": 229
} |
m django.core.signing import b64_decode
from django.test import TestCase, override_settings
from django.urls import reverse
from .models import SomeObject
from .urls import ContactFormViewWithMsg, DeleteFormViewWithMsg
@override_settings(ROOT_URLCONF="messages_tests.urls")
class SuccessMessageMixinTests(TestCase):
... | ge % author, value)
def test_set_messages_success_on_delete(self):
object_to_delete = SomeObject.objects.create(name="MyObject")
delete_url = reverse("success_msg_on_delete", args=[object_to_delete.pk])
response = self.client.p | )
# Uncompressed message is stored in the cookie.
value = b64_decode(
req.cookies["messages"].value.split(":")[0].encode(),
).decode()
self.assertIn(ContactFormViewWithMsg.success_messa | {
"filepath": "tests/messages_tests/test_mixins.py",
"language": "python",
"file_size": 1106,
"cut_index": 515,
"middle_length": 229
} |
nts
from django.contrib.messages.storage.session import SessionStorage
from django.core.exceptions import ImproperlyConfigured
from django.http import HttpRequest
from django.test import TestCase
from django.utils.safestring import SafeData, mark_safe
from .base import BaseTests
def set_session_data(storage, message... | sion_key, [])
)
return len(data)
class SessionTests(BaseTests, TestCase):
storage_class = SessionStorage
def get_request(self):
self.session = {}
request = super().get_request()
request.session = self.session
| e_messages(messages)
if hasattr(storage, "_loaded_data"):
del storage._loaded_data
def stored_session_messages_count(storage):
data = storage.deserialize_messages(
storage.request.session.get(storage.ses | {
"filepath": "tests/messages_tests/test_session.py",
"language": "python",
"file_size": 2167,
"cut_index": 563,
"middle_length": 229
} |
trib.messages.storage import base
from django.contrib.messages.test import MessagesTestMixin
from django.test import RequestFactory, SimpleTestCase, override_settings
from .utils import DummyStorage
class MessageTests(SimpleTestCase):
def test_eq(self):
msg_1 = Message(constants.INFO, "Test message 1")
... | constants.ERROR: "",
12: "custom",
}
)
def test_repr(self):
tests = [
(constants.INFO, "thing", "", "Message(level=20, message='thing')"),
(
constants.WARNING,
| k.ANY)
self.assertNotEqual(msg_1, msg_2)
self.assertNotEqual(msg_1, msg_3)
self.assertNotEqual(msg_2, msg_3)
@override_settings(
MESSAGE_TAGS={
constants.WARNING: "caution",
| {
"filepath": "tests/messages_tests/tests.py",
"language": "python",
"file_size": 7779,
"cut_index": 716,
"middle_length": 229
} |
messages
from django.contrib.messages.views import SuccessMessageMixin
from django.http import HttpResponse, HttpResponseRedirect
from django.template import engines
from django.template.response import TemplateResponse
from django.urls import path, re_path, reverse
from django.views.decorators.cache import never_cach... | aults to False if
# unspecified.
fail_silently = request.POST.get("fail_silently", None)
for msg in request.POST.getlist("messages"):
if fail_silently is not None:
getattr(messages, message_type)(request, msg, fail_silently= | if message.tags %} class="{{ message.tags }}"{% endif %}>
{{ message }}
</li>
{% endfor %}
</ul>
{% endif %}
"""
@never_cache
def add(request, message_type):
# Don't default to False here to test that it def | {
"filepath": "tests/messages_tests/urls.py",
"language": "python",
"file_size": 2810,
"cut_index": 563,
"middle_length": 229
} |
ort Image
except ImportError:
Image = None
class CaseTestModel(models.Model):
integer = models.IntegerField()
integer2 = models.IntegerField(null=True)
string = models.CharField(max_length=100, default="")
big_integer = models.BigIntegerField(null=True)
binary = models.BinaryField(default=b""... | le_field")
file_path = models.FilePathField(null=True)
float = models.FloatField(null=True, db_column="float_field")
if Image:
image = models.ImageField(null=True)
generic_ip_address = models.GenericIPAddressField(null=True)
nul | eld(
max_digits=2, decimal_places=1, null=True, db_column="decimal_field"
)
duration = models.DurationField(null=True)
email = models.EmailField(default="")
file = models.FileField(null=True, db_column="fi | {
"filepath": "tests/expressions_case/models.py",
"language": "python",
"file_size": 2366,
"cut_index": 563,
"middle_length": 229
} |
seTestModel.objects.create(fk=o, integer=3)
o = CaseTestModel.objects.create(integer=3, integer2=4, string="3")
O2OCaseTestModel.objects.create(o2o=o, integer=3)
FKCaseTestModel.objects.create(fk=o, integer=3)
FKCaseTestModel.objects.create(fk=o, integer=4)
o = CaseTestModel.ob... | .group_by_fields = [
f.name
for f in CaseTestModel._meta.get_fields()
if not (f.is_relation and f.auto_created)
and (
connection.features.allows_group_by_lob
or not isinstance( | s.create(fk=o, integer=4)
o = CaseTestModel.objects.create(integer=4, integer2=5, string="4")
O2OCaseTestModel.objects.create(o2o=o, integer=1)
FKCaseTestModel.objects.create(fk=o, integer=5)
cls | {
"filepath": "tests/expressions_case/tests.py",
"language": "python",
"file_size": 57531,
"cut_index": 2151,
"middle_length": 229
} |
port register_lookup
from .models import Celebrity, Fan, Staff, StaffTag, Tag
@skipUnlessDBFeature("can_distinct_on_fields")
@skipUnlessDBFeature("supports_nullable_unique_constraints")
class DistinctOnTests(TestCase):
@classmethod
def setUpTestData(cls):
cls.t1 = Tag.objects.create(name="t1")
... | f.objects.create(id=3, name="p3", organisation="o1")
cls.p1_o2 = Staff.objects.create(id=4, name="p1", organisation="o2")
cls.p1_o1.coworkers.add(cls.p2_o1, cls.p3_o1)
cls.st1 = StaffTag.objects.create(staff=cls.p1_o1, tag=cls.t1)
| t5 = Tag.objects.create(name="t5", parent=cls.t3)
cls.p1_o1 = Staff.objects.create(id=1, name="p1", organisation="o1")
cls.p2_o1 = Staff.objects.create(id=2, name="p2", organisation="o1")
cls.p3_o1 = Staf | {
"filepath": "tests/distinct_on_fields/tests.py",
"language": "python",
"file_size": 7866,
"cut_index": 716,
"middle_length": 229
} |
n, connections
from django.test import LiveServerTestCase, override_settings
from django.test.testcases import LiveServerThread, QuietWSGIRequestHandler
from .models import Person
TEST_ROOT = os.path.dirname(__file__)
TEST_SETTINGS = {
"MEDIA_URL": "media/",
"MEDIA_ROOT": os.path.join(TEST_ROOT, "media"),
... | urlopen(self.live_server_url + url)
class CloseConnectionTestServer(ThreadedWSGIServer):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# This event is set right after the first time a request closes its
| available_apps = [
"servers",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
]
fixtures = ["testdata.json"]
def urlopen(self, url):
return | {
"filepath": "tests/servers/tests.py",
"language": "python",
"file_size": 15608,
"cut_index": 921,
"middle_length": 229
} |
create_method_with_get(self):
created = Person.objects.get_or_create(
first_name="John",
last_name="Lennon",
defaults={"birthday": date(1940, 10, 9)},
)[1]
self.assertFalse(created)
self.assertEqual(Person.objects.count(), 1)
def test_get_or_creat... | cond time,
it won't create a Person.
"""
Person.objects.get_or_create(
first_name="George",
last_name="Harrison",
defaults={"birthday": date(1943, 2, 25)},
)
created = Person.objec | 5)},
)[1]
self.assertTrue(created)
self.assertEqual(Person.objects.count(), 2)
def test_get_or_create_redundant_instance(self):
"""
If we execute the exact same statement twice, the se | {
"filepath": "tests/get_or_create/tests.py",
"language": "python",
"file_size": 31523,
"cut_index": 1331,
"middle_length": 229
} |
urls import path, re_path, register_converter
from . import converters, views
register_converter(converters.DynamicConverter, "to_url_value_error")
urlpatterns = [
# Different number of arguments.
path("number_of_args/0/", views.empty_view, name="number_of_args"),
path("number_of_args/1/<value>/", views.... | th("converter/slug/<slug:value>/", views.empty_view, name="converter"),
path("converter/int/<int:value>/", views.empty_view, name="converter"),
path("converter/uuid/<uuid:value>/", views.empty_view, name="converter"),
# Different regular expres | s.empty_view, name="kwargs_names"),
# Different path converters.
path("converter/path/<path:value>/", views.empty_view, name="converter"),
path("converter/str/<str:value>/", views.empty_view, name="converter"),
pa | {
"filepath": "tests/urlpatterns/path_same_name_urls.py",
"language": "python",
"file_size": 1483,
"cut_index": 524,
"middle_length": 229
} |
test.utils import override_settings
from django.urls.resolvers import RegexPattern, RoutePattern, get_resolver
from django.utils.translation import gettext_lazy as _
from . import views
class RegexPatternTests(SimpleTestCase):
def test_str(self):
self.assertEqual(str(RegexPattern(_("^translated/$"))), "^... | , 1)
self.assertEqual(len(RoutePattern(_("translated/<int:foo>")).converters), 1)
def test_match_lazy_route_without_converters(self):
pattern = RoutePattern(_("test/"))
result = pattern.match("test/child/")
self.assertE | ):
self.assertEqual(len(RoutePattern("translated/").converters), 0)
self.assertEqual(len(RoutePattern(_("translated/")).converters), 0)
self.assertEqual(len(RoutePattern("translated/<int:foo>").converters) | {
"filepath": "tests/urlpatterns/test_resolvers.py",
"language": "python",
"file_size": 2461,
"cut_index": 563,
"middle_length": 229
} |
re.exceptions import SuspiciousFileOperation
from django.core.files.storage import Storage
from django.test import SimpleTestCase
class CustomStorage(Storage):
"""Simple Storage subclass implementing the bare minimum for testing."""
def exists(self, name):
return False
def _save(self, name):
... | alid nor safe, fail early.
for name in self.invalid_file_names:
with (
self.subTest(name=name),
mock.patch.object(s, "get_available_name") as mock_get_available_name,
mock.patch.object(s, | "path", "to", "test.file"),
]
error_msg = "Detected path traversal attempt in '%s'"
def test_validate_before_get_available_name(self):
s = CustomStorage()
# The initial name passed to `save` is not v | {
"filepath": "tests/file_storage/test_base.py",
"language": "python",
"file_size": 2799,
"cut_index": 563,
"middle_length": 229
} |
ng(self):
with self.storage.open("file.txt", "w") as fd:
fd.write("hello")
with self.storage.open("file.txt", "r") as fd:
self.assertEqual(fd.read(), "hello")
with self.storage.open("file.dat", "wb") as fd:
fd.write(b"hello")
with self.storage.open("fi... | ("file.dat", "wb") as fd:
fd.write(b"hello")
with self.storage.open("file.dat", "r") as fd:
self.assertEqual(fd.read(), "hello")
def test_open_missing_file(self):
self.assertRaises(FileNotFoundError, self.storag | ack."""
with self.storage.open("file.txt", "w") as fd:
fd.write("hello")
with self.storage.open("file.txt", "rb") as fd:
self.assertEqual(fd.read(), b"hello")
with self.storage.open | {
"filepath": "tests/file_storage/test_inmemory_storage.py",
"language": "python",
"file_size": 11976,
"cut_index": 921,
"middle_length": 229
} |
ns import FieldError
from django.test import TestCase
from .models import Choice, Poll, User
class ReverseLookupTests(TestCase):
@classmethod
def setUpTestData(cls):
john = User.objects.create(name="John Doe")
jim = User.objects.create(name="Jim Bo")
first_poll = Poll.objects.create(
... | question?")
self.assertEqual(u1.name, "John Doe")
u2 = User.objects.get(poll__question__exact="What's the second question?")
self.assertEqual(u2.name, "Jim Bo")
def test_reverse_by_related_name(self):
p1 = Poll.object | Choice.objects.create(
poll=first_poll, related_poll=second_poll, name="This is the answer."
)
def test_reverse_by_field(self):
u1 = User.objects.get(poll__question__exact="What's the first | {
"filepath": "tests/reverse_lookup/tests.py",
"language": "python",
"file_size": 1744,
"cut_index": 537,
"middle_length": 229
} |
del, Employee, Foo
class BasicCustomPKTests(TestCase):
@classmethod
def setUpTestData(cls):
cls.dan = Employee.objects.create(
employee_code=123,
first_name="Dan",
last_name="Jones",
)
cls.fran = Employee.objects.create(
employee_code=456... | enceEqual(Employee.objects.filter(employee_code=123), [self.dan])
self.assertSequenceEqual(
Employee.objects.filter(pk__in=[123, 456]),
[self.fran, self.dan],
)
self.assertSequenceEqual(Employee.objects.all() | def test_querysets(self):
"""
Both pk and custom attribute_name can be used in filter and friends
"""
self.assertSequenceEqual(Employee.objects.filter(pk=123), [self.dan])
self.assertSequ | {
"filepath": "tests/custom_pk/tests.py",
"language": "python",
"file_size": 7427,
"cut_index": 716,
"middle_length": 229
} |
(kwargs)
def sendall(self, data):
self.makefile("wb").write(data)
class UnclosableBytesIO(BytesIO):
def close(self):
# WSGIRequestHandler closes the output file; we need to make this a
# no-op so we can still read its contents.
pass
class WSGIRequestHandlerTestCase(SimpleTes... | }
for level, status_codes in level_status_codes.items():
for status_code in status_codes:
# The correct level gets the message.
with self.assertLogs("django.server", level.upper()) as cm:
| kwargs: BytesIO()
handler = WSGIRequestHandler(request, "192.168.0.2", None)
level_status_codes = {
"info": [200, 301, 304],
"warning": [400, 403, 404],
"error": [500, 503],
| {
"filepath": "tests/servers/test_basehttp.py",
"language": "python",
"file_size": 9217,
"cut_index": 921,
"middle_length": 229
} |
AULT_DB_ALIAS, connections
from django.test import LiveServerTestCase, TransactionTestCase
from django.test.testcases import LiveServerThread
# Use TransactionTestCase instead of TestCase to run outside of a transaction,
# otherwise closing the connection would implicitly rollback and not set the
# connection to None... | # Pass a connection to the thread to check they are being closed.
connections_override = {DEFAULT_DB_ALIAS: conn}
# Open a connection to the database.
conn.connect()
conn.inc_thread_sharing()
try:
self | thread(connections_override)
thread.daemon = True
thread.start()
thread.is_ready.wait()
thread.terminate()
def test_closes_connections(self):
conn = connections[DEFAULT_DB_ALIAS]
| {
"filepath": "tests/servers/test_liveserverthread.py",
"language": "python",
"file_size": 1685,
"cut_index": 537,
"middle_length": 229
} |
els
class Person(models.Model):
first_name = models.CharField(max_length=100, unique=True)
last_name = models.CharField(max_length=100)
birthday = models.DateField()
defaults = models.TextField()
create_defaults = models.TextField()
class DefaultPerson(models.Model):
first_name = models.Char... | d(max_length=255)
tags = models.ManyToManyField(Tag)
@property
def capitalized_name_property(self):
return self.name
@capitalized_name_property.setter
def capitalized_name_property(self, val):
self.name = val.capitaliz | e(models.Model):
person = models.ForeignKey(Person, models.CASCADE, primary_key=True)
class Tag(models.Model):
text = models.CharField(max_length=255, unique=True)
class Thing(models.Model):
name = models.CharFiel | {
"filepath": "tests/get_or_create/models.py",
"language": "python",
"file_size": 1678,
"cut_index": 537,
"middle_length": 229
} |
lass Base64Converter:
regex = r"[a-zA-Z0-9+/]*={0,2}"
def to_python(self, value):
return base64.b64decode(value, validate=True)
def to_url(self, value):
return base64.b64encode(value).decode("ascii")
class DynamicConverter:
_dynamic_to_python = None
_dynamic_to_url = None
@p... | n(value)
def to_url(self, value):
return type(self)._dynamic_to_url(value)
@classmethod
def register_to_python(cls, value):
cls._dynamic_to_python = value
@classmethod
def register_to_url(cls, value):
cls._dyn | value):
return type(self)._dynamic_to_pytho | {
"filepath": "tests/urlpatterns/converters.py",
"language": "python",
"file_size": 857,
"cut_index": 529,
"middle_length": 52
} |
urls import include, path, re_path
from . import views
urlpatterns = [
path("articles/2003/", views.empty_view, name="articles-2003"),
path("articles/<int:year>/", views.empty_view, name="articles-year"),
path(
"articles/<int:year>/<int:month>/", views.empty_view, name="articles-year-month"
),... | "),
path("users/<id>/", views.empty_view, name="user-with-id"),
path("included_urls/", include("urlpatterns.included_urls")),
re_path(r"^regex/(?P<pk>[0-9]+)/$", views.empty_view, name="regex"),
re_path(
r"^regex_optional/(?P<arg1>\ | ue}, name="books-2007"),
path(
"books/<int:year>/<int:month>/<int:day>/",
views.empty_view,
{"extra": True},
name="books-year-month-day",
),
path("users/", views.empty_view, name="users | {
"filepath": "tests/urlpatterns/path_urls.py",
"language": "python",
"file_size": 1378,
"cut_index": 524,
"middle_length": 229
} |
ion": temp_storage_location})
kwargs_orig = {
"location": temp_storage_location,
"base_url": "http://myfiles.example.com/",
}
storage = FileSystemStorage(**kwargs_orig)
path, args, kwargs = storage.deconstruct()
self.assertEqual(kwargs, kwargs_orig)
... | kdtemp()
self.addCleanup(shutil.rmtree, self.temp_dir)
self.storage = self.storage_class(
location=self.temp_dir, base_url="/test_media_url/"
)
def test_empty_location(self):
"""
Makes sure an except | ))
with self.assertRaises(NoReverseMatch):
storage.url(storage.base_url)
class FileStorageTests(SimpleTestCase):
storage_class = FileSystemStorage
def setUp(self):
self.temp_dir = tempfile.m | {
"filepath": "tests/file_storage/tests.py",
"language": "python",
"file_size": 50503,
"cut_index": 2151,
"middle_length": 229
} |
gression tests for proper working of ForeignKey(null=True). Tests these bugs:
* #7512: including a nullable foreign key reference in Meta ordering has
unexpected results
"""
from django.db import models
# The first two models represent a very simple null FK ordering case.
class Author(models.Model):
name =... | tem_info = models.ForeignKey(SystemInfo, models.CASCADE)
forum_name = models.CharField(max_length=32)
class Post(models.Model):
forum = models.ForeignKey(Forum, models.SET_NULL, null=True)
title = models.CharField(max_length=32)
class Comme | :
ordering = ["author__name"]
# These following 4 models represent a far more complex ordering case.
class SystemInfo(models.Model):
system_name = models.CharField(max_length=32)
class Forum(models.Model):
sys | {
"filepath": "tests/null_fk_ordering/models.py",
"language": "python",
"file_size": 1230,
"cut_index": 518,
"middle_length": 229
} |
s.Model):
name = models.CharField(max_length=10)
class Device(models.Model):
building = models.ForeignKey("Building", models.CASCADE)
name = models.CharField(max_length=10)
class Port(models.Model):
device = models.ForeignKey("Device", models.CASCADE)
port_number = models.CharField(max_length=10... | y that exercises code paths similar to the above
# example, but in a slightly different configuration.
class TUser(models.Model):
name = models.CharField(max_length=200)
class Person(models.Model):
user = models.ForeignKey(TUser, models.CASCADE | related_name="connection_start",
unique=True,
)
end = models.ForeignKey(
Port,
models.CASCADE,
related_name="connection_end",
unique=True,
)
# Another non-tree hierarch | {
"filepath": "tests/select_related_regress/models.py",
"language": "python",
"file_size": 3039,
"cut_index": 563,
"middle_length": 229
} |
ib.sessions.backends.base import SessionBase
class SessionStore(SessionBase):
"""
A simple cookie-based session storage implementation.
The session key is actually the session data, pickled and encoded.
This means that saving the session will change the session key.
"""
def __init__(self, se... | = self.encode(self._session)
def delete(self, session_key=None):
self._session_key = self.encode({})
def load(self):
try:
return self.decode(self.session_key)
except Exception:
self.modified = True | (self, must_create=False):
self._session_key | {
"filepath": "tests/test_client_regress/session.py",
"language": "python",
"file_size": 860,
"cut_index": 529,
"middle_length": 52
} |
iews.generic import RedirectView
from . import views
urlpatterns = [
path("", include("test_client.urls")),
path("no_template_view/", views.no_template_view),
path("staff_only/", views.staff_only_view),
path("get_view/", views.get_view),
path("request_data/", views.request_data),
path(
... | edirects/further/", RedirectView.as_view(url="/redirects/further/more/")),
path("redirects/further/more/", RedirectView.as_view(url="/no_template_view/")),
path(
"redirect_to_non_existent_view/",
RedirectView.as_view(url="/non_exist | path("nested_view/", views.nested_view, name="nested_view"),
path("login_protected_redirect_view/", views.login_protected_redirect_view),
path("redirects/", RedirectView.as_view(url="/redirects/further/")),
path("r | {
"filepath": "tests/test_client_regress/urls.py",
"language": "python",
"file_size": 2871,
"cut_index": 563,
"middle_length": 229
} |
ng
from django.db import models
class MyWrapper:
def __init__(self, value):
self.value = value
def __repr__(self):
return "<%s: %s>" % (self.__class__.__name__, self.value)
def __str__(self):
return self.value
def __eq__(self, other):
if isinstance(other, self.__cla... | value = MyWrapper("".join(random.sample(string.ascii_lowercase, 10)))
setattr(instance, self.attname, value)
return value
def to_python(self, value):
if not value:
return
if not isinstance(valu | f __init__(self, *args, **kwargs):
kwargs["max_length"] = 10
super().__init__(*args, **kwargs)
def pre_save(self, instance, add):
value = getattr(instance, self.attname, None)
if not value:
| {
"filepath": "tests/custom_pk/fields.py",
"language": "python",
"file_size": 1914,
"cut_index": 537,
"middle_length": 229
} |
nternal_wsgi_application
from django.core.signals import request_started
from django.core.wsgi import get_wsgi_application
from django.db import close_old_connections
from django.http import FileResponse
from django.test import SimpleTestCase, override_settings
from django.test.client import RequestFactory
@override_... | i_application()
environ = self.request_factory._base_environ(
PATH_INFO="/", CONTENT_TYPE="text/html; charset=utf-8", REQUEST_METHOD="GET"
)
response_data = {}
def start_response(status, headers):
| self.addCleanup(request_started.connect, close_old_connections)
def test_get_wsgi_application(self):
"""
get_wsgi_application() returns a functioning WSGI callable.
"""
application = get_wsg | {
"filepath": "tests/wsgi/tests.py",
"language": "python",
"file_size": 4872,
"cut_index": 614,
"middle_length": 229
} |
jango.db import models
class Tag(models.Model):
name = models.CharField(max_length=10)
parent = models.ForeignKey(
"self",
models.SET_NULL,
blank=True,
null=True,
related_name="children",
)
class Meta:
ordering = ["name"]
def __str__(self):
... | mary_key=True)
name = models.CharField(max_length=50)
organisation = models.CharField(max_length=100)
tags = models.ManyToManyField(Tag, through="StaffTag")
coworkers = models.ManyToManyField("self")
def __str__(self):
return s | =True,
unique=True,
)
def __str__(self):
return self.name
class Fan(models.Model):
fan_of = models.ForeignKey(Celebrity, models.CASCADE)
class Staff(models.Model):
id = models.IntegerField(pri | {
"filepath": "tests/distinct_on_fields/models.py",
"language": "python",
"file_size": 1221,
"cut_index": 518,
"middle_length": 229
} |
tem
``FileField`` and its variations can take a ``storage`` argument to specify how
and where files should be stored.
"""
import random
import tempfile
from pathlib import Path
from django.core.files.storage import FileSystemStorage, default_storage
from django.db import models
from django.utils.functional import La... | age(FileSystemStorage):
def __call__(self):
# no-op implementation.
return self
class LazyTempStorage(LazyObject):
def _setup(self):
self._wrapped = temp_storage
class Storage(models.Model):
def custom_upload_to(self | ge_location = tempfile.mkdtemp()
temp_storage = FileSystemStorage(location=temp_storage_location)
def callable_storage():
return temp_storage
def callable_default_storage():
return default_storage
class CallableStor | {
"filepath": "tests/file_storage/models.py",
"language": "python",
"file_size": 2903,
"cut_index": 563,
"middle_length": 229
} |
estCase
from .models import Article, Author, Comment, Forum, Post, SystemInfo
class NullFkOrderingTests(TestCase):
def test_ordering_across_null_fk(self):
"""
Regression test for #7512
ordering across nullable Foreign Keys shouldn't exclude results
"""
author_1 = Author.o... | rectly (since different databases sort
# NULLs to different ends of the ordering), but we can check that all
# results are returned.
self.assertEqual(len(list(Article.objects.all())), 3)
s = SystemInfo.objects.create(system | author=author_1, title="This article written by Tom Jones"
)
Article.objects.create(
author=author_2, title="This article written by Bob Smith"
)
# We can't compare results di | {
"filepath": "tests/null_fk_ordering/tests.py",
"language": "python",
"file_size": 2013,
"cut_index": 537,
"middle_length": 229
} |
"""
Regression test for bug #7110.
When using select_related(), we must query the
Device and Building tables using two different aliases (each) in order
to differentiate the start and end Connection fields. The net result is
that both the "connections = ..." queries here shou... |
dev3 = Device.objects.create(name="server", building=b)
port1 = Port.objects.create(port_number="4", device=dev1)
port2 = Port.objects.create(port_number="7", device=dev2)
port3 = Port.objects.create(port_number="1", device | d include some unnecessary bonus joins).
"""
b = Building.objects.create(name="101")
dev1 = Device.objects.create(name="router", building=b)
dev2 = Device.objects.create(name="switch", building=b) | {
"filepath": "tests/select_related_regress/tests.py",
"language": "python",
"file_size": 9943,
"cut_index": 921,
"middle_length": 229
} |
ient
from django.test import SimpleTestCase
class MySqlDbshellCommandTestCase(SimpleTestCase):
def settings_to_cmd_args_env(self, settings_dict, parameters=None):
if parameters is None:
parameters = []
return DatabaseClient.settings_to_cmd_args_env(settings_dict, parameters)
def t... | self.assertEqual(
self.settings_to_cmd_args_env(
{
"NAME": "somedbname",
"USER": "someuser",
"PASSWORD": "somepassword",
"HOST": "somehost",
| f):
expected_args = [
"mysql",
"--user=someuser",
"--host=somehost",
"--port=444",
"somedbname",
]
expected_env = {"MYSQL_PWD": "somepassword"}
| {
"filepath": "tests/dbshell/test_mysql.py",
"language": "python",
"file_size": 8213,
"cut_index": 716,
"middle_length": 229
} |
aseClient
from django.test import SimpleTestCase
class PostgreSqlDbshellCommandTestCase(SimpleTestCase):
def settings_to_cmd_args_env(self, settings_dict, parameters=None):
if parameters is None:
parameters = []
settings_dict.setdefault("OPTIONS", {})
return DatabaseClient.sett... | ["psql", "-U", "someuser", "-h", "somehost", "-p", "444", "dbname"],
{"PGPASSWORD": "somepassword"},
),
)
def test_nopass(self):
self.assertEqual(
self.settings_to_cmd_args_env(
| bname",
"USER": "someuser",
"PASSWORD": "somepassword",
"HOST": "somehost",
"PORT": "444",
}
),
(
| {
"filepath": "tests/dbshell/test_postgresql.py",
"language": "python",
"file_size": 6287,
"cut_index": 716,
"middle_length": 229
} |
value != 42:
raise ValidationError(
"This is not the answer to life, universe and everything!", code="not42"
)
class ModelToValidate(models.Model):
name = models.CharField(max_length=100)
created = models.DateTimeField(default=datetime.now)
number = models.IntegerField(db_colu... | f_with_custom_validator = models.IntegerField(
blank=True, null=True, validators=[validate_answer_to_universe]
)
f_with_iterable_of_validators = models.IntegerField(
blank=True, null=True, validators=(validate_answer_to_universe | ls.EmailField(blank=True)
ufm = models.ForeignKey(
"UniqueFieldsModel",
models.SET_NULL,
to_field="unique_charfield",
blank=True,
null=True,
)
url = models.URLField(blank=True)
| {
"filepath": "tests/validation/models.py",
"language": "python",
"file_size": 6655,
"cut_index": 716,
"middle_length": 229
} |
re
from .models import (
ChildProduct,
ChildUniqueConstraintProduct,
Product,
UniqueConstraintConditionProduct,
UniqueConstraintProduct,
)
class PerformConstraintChecksTest(TestCase):
@skipUnlessDBFeature("supports_table_check_constraints")
def test_full_clean_with_check_constraints(self)... | ble_check_constraints")
def test_full_clean_with_check_constraints_on_child_model(self):
product = ChildProduct(price=10, discounted_price=15)
with self.assertRaises(ValidationError) as cm:
product.full_clean()
self. | ption.message_dict,
{
"__all__": [
"Constraint “price_gt_discounted_price_validation” is violated."
]
},
)
@skipUnlessDBFeature("supports_ta | {
"filepath": "tests/validation/test_constraints.py",
"language": "python",
"file_size": 3798,
"cut_index": 614,
"middle_length": 229
} |
(
CustomPKModel,
FlexibleDatePost,
ModelToValidate,
Post,
UniqueErrorsModel,
UniqueFieldsModel,
UniqueForDateModel,
UniqueFuncConstraintModel,
UniqueTogetherModel,
)
class GetUniqueCheckTests(unittest.TestCase):
def test_unique_fields_get_collected(self):
m = UniqueFie... | f):
m = UniqueTogetherModel()
self.assertEqual(
(
[
(UniqueTogetherModel, ("ifield", "cfield")),
(UniqueTogetherModel, ("ifield", "efield")),
(UniqueTog | (UniqueFieldsModel, ("unique_integerfield",)),
],
[],
),
m._get_unique_checks(),
)
def test_unique_together_gets_picked_up_and_converted_to_tuple(sel | {
"filepath": "tests/validation/test_unique.py",
"language": "python",
"file_size": 8152,
"cut_index": 716,
"middle_length": 229
} |
_required_field_raises_error(self):
mtv = ModelToValidate(f_with_custom_validator=42)
self.assertFailsValidation(mtv.full_clean, ["name", "number"])
def test_with_correct_value_model_validates(self):
mtv = ModelToValidate(number=10, name="Some Name")
self.assertIsNone(mtv.full_clean... | "model to validate instance with id %r is not a valid choice."
% mtv.parent_id
],
)
mtv = ModelToValidate(number=10, name="Some Name", ufm_id="Some Name")
self.assertFieldFailsValidationWithMessage(
| alue_raises_error(self):
mtv = ModelToValidate(number=10, name="Some Name", parent_id=3)
self.assertFieldFailsValidationWithMessage(
mtv.full_clean,
"parent",
[
| {
"filepath": "tests/validation/tests.py",
"language": "python",
"file_size": 9648,
"cut_index": 921,
"middle_length": 229
} |
contrib import admin
from django.contrib.admin import sites
from django.test import SimpleTestCase, override_settings
from .sites import CustomAdminSite
@override_settings(
INSTALLED_APPS=[
"admin_default_site.apps.MyCustomAdminConfig",
"django.contrib.auth",
"django.contrib.contenttypes"... | te = sites.site = self._old_site
def test_use_custom_admin_site(self):
self.assertEqual(admin.site.__class__.__name__, "CustomAdminSite")
class DefaultAdminSiteTests(SimpleTestCase):
def test_use_default_admin_site(self):
self.as | Reset admin.site since it may have already been instantiated by
# another test app.
self._old_site = admin.site
admin.site = sites.site = sites.DefaultAdminSite()
def tearDown(self):
admin.si | {
"filepath": "tests/admin_default_site/tests.py",
"language": "python",
"file_size": 1420,
"cut_index": 524,
"middle_length": 229
} |
class RawQueryTests(TestCase):
@classmethod
def setUpTestData(cls):
cls.a1 = Author.objects.create(
first_name="Joe", last_name="Smith", dob=date(1950, 9, 20)
)
cls.a2 = Author.objects.create(
first_name="Jill", last_name="Doe", dob=date(1920, 4, 2)
)
... | s a bright cold day in April and the clocks were striking "
"thirteen."
),
)
cls.b2 = Book.objects.create(
title="The horrible book",
author=cls.a1,
paperback=True,
| t_name="Jones", dob=date(1932, 5, 10)
)
cls.b1 = Book.objects.create(
title="The awesome book",
author=cls.a1,
paperback=False,
opening_line=(
"It wa | {
"filepath": "tests/raw_query/tests.py",
"language": "python",
"file_size": 16751,
"cut_index": 921,
"middle_length": 229
} |
""
Using a custom primary key
By default, Django adds an ``"id"`` field to each model. But you can override
this behavior by explicitly adding ``primary_key=True`` to a field.
"""
from django.db import models
from .fields import MyAutoField, MyWrapperField
class Employee(models.Model):
employee_code = models.I... | ld(Employee)
class Meta:
verbose_name_plural = "businesses"
class Bar(models.Model):
id = MyWrapperField(primary_key=True, db_index=True)
class Foo(models.Model):
bar = models.ForeignKey(Bar, models.CASCADE)
class CustomAutoField | ", "first_name")
def __str__(self):
return "%s %s" % (self.first_name, self.last_name)
class Business(models.Model):
name = models.CharField(max_length=20, primary_key=True)
employees = models.ManyToManyFie | {
"filepath": "tests/custom_pk/models.py",
"language": "python",
"file_size": 1058,
"cut_index": 513,
"middle_length": 229
} |
request import urlopen
from django.http import HttpResponse, StreamingHttpResponse
from django.views.decorators.csrf import csrf_exempt
from .models import Person
def example_view(request):
return HttpResponse("example view")
def streaming_example_view(request):
return StreamingHttpResponse((b"I", b"am", ... | return HttpResponse("subview")
def subview_calling_view(request):
with urlopen(request.GET["url"] + "/subview/") as response:
return HttpResponse("subview calling view: {}".format(response.read().decode()))
def check_model_instance_from | rson = Person(name="emily")
person.save()
return HttpResponse()
def environ_view(request):
return HttpResponse(
"\n".join("%s: %r" % (k, v) for k, v in request.environ.items())
)
def subview(request):
| {
"filepath": "tests/servers/views.py",
"language": "python",
"file_size": 1344,
"cut_index": 524,
"middle_length": 229
} |
refix: Optional prefix to be added to the message in the
second subTest.
:param method_kwargs: Keyword arguments to pass to the method.
Used internally for testing Django's assertions.
"""
with (
self.subTest("without prefix"),
self.ass... | sts(ExtraAssertMixin, SimpleTestCase):
def test_basic_contains_not_contains(self):
response = self.client.get("/no_template_view/")
with self.subTest("assertNotContains"):
self.assertNotContains(response, "never")
| sesMessage(AssertionError, f"{msg_prefix}: {expected_msg}"),
):
method(*method_args, **method_kwargs, msg_prefix=msg_prefix)
@override_settings(ROOT_URLCONF="test_client_regress.urls")
class AssertContainsTe | {
"filepath": "tests/test_client_regress/tests.py",
"language": "python",
"file_size": 57287,
"cut_index": 2151,
"middle_length": 229
} |
django.shortcuts import render
from django.template.loader import render_to_string
from django.test import Client
from django.test.client import CONTENT_TYPE_RE
class CustomTestException(Exception):
pass
def no_template_view(request):
"A simple view that expects a GET request, and returns a rendered templa... | view"
return HttpResponse("Hello world")
def request_data(request, template="base.html", data="sausage"):
"A simple view that returns the request data in the context"
return render(
request,
template,
{
"ge | aff. Non staff members get an
exception
"""
if request.user.is_staff:
return HttpResponse()
else:
raise CustomTestException()
@login_required
def get_view(request):
"A simple login protected | {
"filepath": "tests/test_client_regress/views.py",
"language": "python",
"file_size": 5229,
"cut_index": 716,
"middle_length": 229
} |
thlib import Path
from unittest import mock, skipUnless
from django.core.management import CommandError, call_command
from django.db import connection
from django.db.backends.sqlite3.client import DatabaseClient
from django.test import SimpleTestCase
class SqliteDbshellCommandTestCase(SimpleTestCase):
def settin... | eters(self):
self.assertEqual(
self.settings_to_cmd_args_env({"NAME": "test.db.sqlite3"}, ["-help"]),
(["sqlite3", "test.db.sqlite3", "-help"], None),
)
@skipUnless(connection.vendor == "sqlite", "SQLite test")
| eters)
def test_path_name(self):
self.assertEqual(
self.settings_to_cmd_args_env({"NAME": Path("test.db.sqlite3")}),
(["sqlite3", Path("test.db.sqlite3")], None),
)
def test_param | {
"filepath": "tests/dbshell/test_sqlite.py",
"language": "python",
"file_size": 1691,
"cut_index": 537,
"middle_length": 229
} |
jango.core.exceptions import ValidationError
class PickableValidationErrorTestCase(TestCase):
def test_validationerror_is_picklable(self):
original = ValidationError("a", code="something")
unpickled = pickle.loads(pickle.dumps(original))
self.assertIs(unpickled, unpickled.error_list[0])
... | de)
original = ValidationError(["a", "b"])
unpickled = pickle.loads(pickle.dumps(original))
self.assertEqual(
original.error_list[0].message, unpickled.error_list[0].message
)
self.assertEqual(
| = pickle.loads(pickle.dumps(ValidationError(original)))
self.assertIs(unpickled, unpickled.error_list[0])
self.assertEqual(original.message, unpickled.message)
self.assertEqual(original.code, unpickled.co | {
"filepath": "tests/validation/test_picklable.py",
"language": "python",
"file_size": 2141,
"cut_index": 563,
"middle_length": 229
} |
db import models
class Author(models.Model):
first_name = models.CharField(max_length=255)
last_name = models.CharField(max_length=255)
dob = models.DateField()
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Protect against annotations being passed to __init_... | paperback = models.BooleanField(default=False)
opening_line = models.TextField()
class BookFkAsPk(models.Model):
book = models.ForeignKey(
Book, models.CASCADE, primary_key=True, db_column="not_the_default"
)
class Coffee(models | _meta.fields], (
"Author.__init__ got an unexpected parameter: %s" % k
)
class Book(models.Model):
title = models.CharField(max_length=255)
author = models.ForeignKey(Author, models.CASCADE)
| {
"filepath": "tests/raw_query/models.py",
"language": "python",
"file_size": 1386,
"cut_index": 524,
"middle_length": 229
} |
Foo,
RelatedPoint,
UniqueNumber,
UniqueNumberChild,
)
class SimpleTest(TestCase):
@classmethod
def setUpTestData(cls):
cls.a1 = A.objects.create()
cls.a2 = A.objects.create()
B.objects.bulk_create(B(a=cls.a1) for _ in range(20))
for x in range(20):
... | rows for an empty queryset
"""
num_updated = self.a2.b_set.update(y=100)
self.assertEqual(num_updated, 0)
cnt = B.objects.filter(y=100).count()
self.assertEqual(cnt, 0)
def test_nonempty_update_with_inheritance( | set.update(y=100)
self.assertEqual(num_updated, 20)
cnt = B.objects.filter(y=100).count()
self.assertEqual(cnt, 20)
def test_empty_update(self):
"""
Update changes the right number of | {
"filepath": "tests/update/tests.py",
"language": "python",
"file_size": 15061,
"cut_index": 921,
"middle_length": 229
} |
, skipUnless
from django.db import connection
from django.db.backends.oracle.client import DatabaseClient
from django.test import SimpleTestCase
@skipUnless(connection.vendor == "oracle", "Requires oracledb to be installed")
class OracleDbshellTests(SimpleTestCase):
def settings_to_cmd_args_env(self, settings_di... | .client.connect_string(connection.settings_dict),
]
self.assertEqual(
self.settings_to_cmd_args_env(connection.settings_dict, rlwrap=False),
(expected_args, None),
)
def test_with_rlwrap(self):
e | e None
):
return DatabaseClient.settings_to_cmd_args_env(settings_dict, parameters)
def test_without_rlwrap(self):
expected_args = [
"sqlplus",
"-L",
connection | {
"filepath": "tests/dbshell/test_oracle.py",
"language": "python",
"file_size": 1757,
"cut_index": 537,
"middle_length": 229
} |
impleTestCase
from . import ValidationAssertions
from .models import ModelToValidate
class TestModelsWithValidators(ValidationAssertions, SimpleTestCase):
def test_custom_validator_passes_for_correct_value(self):
mtv = ModelToValidate(
number=10,
name="Some Name",
f_wi... | ean, ["f_with_custom_validator"])
self.assertFieldFailsValidationWithMessage(
mtv.full_clean,
"f_with_custom_validator",
["This is not the answer to life, universe and everything!"],
)
def test_field | ):
mtv = ModelToValidate(
number=10,
name="Some Name",
f_with_custom_validator=12,
f_with_iterable_of_validators=42,
)
self.assertFailsValidation(mtv.full_cl | {
"filepath": "tests/validation/test_validators.py",
"language": "python",
"file_size": 1536,
"cut_index": 537,
"middle_length": 229
} |
e there aren't actual folders but just
keys.
"""
prefix = "mys3folder/"
def _save(self, name, content):
"""
This method is important to test that Storage.save() doesn't replace
'\' with '/' (rather FileSystemStorage.save() does).
"""
return name
def get_val... | impleTestCase):
"""Tests for base Storage's generate_filename method."""
storage_class = Storage
def test_valid_names(self):
storage = self.storage_class()
name = "UnTRIVíAL @fil$ena#me!"
valid_name = storage.get_valid | he method that's important to override when using S3 so that
os.path() isn't called, which would break S3 keys.
"""
return self.prefix + self.get_valid_name(filename)
class StorageGenerateFilenameTests(S | {
"filepath": "tests/file_storage/test_generate_filename.py",
"language": "python",
"file_size": 9421,
"cut_index": 921,
"middle_length": 229
} |
class DataTypesTestCase(TestCase):
def test_boolean_type(self):
d = Donut(name="Apple Fritter")
self.assertFalse(d.is_frosted)
self.assertIsNone(d.has_sprinkles)
d.has_sprinkles = True
self.assertTrue(d.has_sprinkles)
d.save()
d2 = Donut.objects.get(name=... | d.save()
d2 = Donut.objects.get(name="Apple Fritter")
self.assertEqual(d2.baked_date, datetime.date(1938, 6, 4))
self.assertEqual(d2.baked_time, datetime.time(5, 30))
self.assertEqual(d2.consumed_at, datetime.datetime(2007, | datetime.date(year=1938, month=6, day=4)
d.baked_time = datetime.time(hour=5, minute=30)
d.consumed_at = datetime.datetime(
year=2007, month=4, day=20, hour=16, minute=19, second=59
)
| {
"filepath": "tests/datatypes/tests.py",
"language": "python",
"file_size": 4322,
"cut_index": 614,
"middle_length": 229
} |
t models
class ValidationMessagesTest(TestCase):
def _test_validation_messages(self, field, value, expected):
with self.assertRaises(ValidationError) as cm:
field.clean(value, None)
self.assertEqual(cm.exception.messages, expected)
def test_autofield_field_raises_error_message(sel... | _validation_messages(
f, "fõo", ["“fõo” value must be either True or False."]
)
def test_nullable_boolean_field_raises_error_message(self):
f = models.BooleanField(null=True)
self._test_validation_messages(
|
f = models.IntegerField()
self._test_validation_messages(f, "fõo", ["“fõo” value must be an integer."])
def test_boolean_field_raises_error_message(self):
f = models.BooleanField()
self._test | {
"filepath": "tests/validation/test_error_messages.py",
"language": "python",
"file_size": 4463,
"cut_index": 614,
"middle_length": 229
} |
models.FileField(upload_to=upload_to)
class TextEnum(enum.Enum):
A = "a-value"
B = "value-b"
class TextTranslatedEnum(enum.Enum):
A = _("a-value")
B = _("value-b")
class BinaryEnum(enum.Enum):
A = b"a-value"
B = b"value-b"
class IntEnum(enum.IntEnum):
A = 1
B = 2
class IntFlag... | ignature(self):
operation = custom_migration_operations.operations.TestOperation()
buff, imports = OperationWriter(operation, indentation=0).serialize()
self.assertEqual(imports, {"import custom_migration_operations.operations"})
| ction_with_decorator():
pass
@functools.cache
def function_with_cache():
pass
@functools.lru_cache(maxsize=10)
def function_with_lru_cache():
pass
class OperationWriterTests(SimpleTestCase):
def test_empty_s | {
"filepath": "tests/migrations/test_writer.py",
"language": "python",
"file_size": 50082,
"cut_index": 2151,
"middle_length": 229
} |
mport typing
from django.db import models
T = typing.TypeVar("T")
class GenericModel(typing.Generic[T], models.Model):
"""A model inheriting from typing.Generic."""
class GenericModelPEP695[T](models.Model):
"""A model inheriting from typing.Generic via the PEP 695 syntax."""
# Example from Python docs:... | [T1, T2]):
pass
class Parent2(typing.Generic[T1, T2]):
pass
class Child(Parent1[T1, T3], Parent2[T2, T3]):
pass
class CustomGenericModel(Child[T1, T3, T2], models.Model):
"""A model inheriting from a custom subclass of typing.Generic. | typing.Generic | {
"filepath": "tests/migrations/migrations_test_apps/with_generic_model/models.py",
"language": "python",
"file_size": 787,
"cut_index": 513,
"middle_length": 14
} |
mport typing
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
operations = [
migrations.CreateModel(
name="GenericModel",
fields=[
(
"id",
models.AutoField(
... | models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
],
| ,
],
bases=(typing.Generic, models.Model),
),
migrations.CreateModel(
name="GenericModelPEP695",
fields=[
(
"id",
| {
"filepath": "tests/migrations/migrations_test_apps/with_generic_model/migrations/0001_initial.py",
"language": "python",
"file_size": 1058,
"cut_index": 513,
"middle_length": 229
} |
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
operations = [
migrations.CreateModel(
"Author",
[
("id", models.AutoField(primary_key=True)),
("name", models.CharField(max_length=255)),
... | migrations.AddField(
model_name="tribble",
name="bool",
field=models.BooleanField(default=False),
),
migrations.AlterUniqueTogether(
name="author",
unique_together={("name", "slug | ),
migrations.CreateModel(
"Tribble",
[
("id", models.AutoField(primary_key=True)),
("fluffy", models.BooleanField(default=True)),
],
),
| {
"filepath": "tests/migrations/test_migrations/0001_initial.py",
"language": "python",
"file_size": 1019,
"cut_index": 512,
"middle_length": 229
} |
o.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
"Author",
[
("id", models.Aut... | odels.AutoField(primary_key=True)),
(
"author",
models.ForeignKey(
settings.AUTH_USER_MODEL, models.CASCADE, to_field="id"
),
),
| ("id", m | {
"filepath": "tests/migrations/test_migrations_custom_user/0001_initial.py",
"language": "python",
"file_size": 813,
"cut_index": 522,
"middle_length": 14
} |
a_editor):
# Test operation in non-atomic migration is not wrapped in transaction
Publisher = apps.get_model("migrations", "Publisher")
Publisher.objects.create(name="Test Publisher")
raise RuntimeError("Abort migration")
class Migration(migrations.Migration):
atomic = False
operations = [
... | el(
"Book",
[
("title", models.CharField(primary_key=True, max_length=255)),
(
"publisher",
models.ForeignKey(
"migrations.Publisher", m | RunPython(raise_error),
migrations.CreateMod | {
"filepath": "tests/migrations/test_migrations_non_atomic/0001_initial.py",
"language": "python",
"file_size": 990,
"cut_index": 582,
"middle_length": 52
} |
igrations, models
class Migration(migrations.Migration):
initial = True
operations = [
migrations.CreateModel(
name="fakeinitialmodel",
fields=[
("id", models.AutoField(primary_key=True)),
("field", models.CharField(max_length=20)),
... | Field(
"migrations.FakeInitialModel", db_table="m2m_MiXeD_CaSe"
),
),
],
options={
"db_table": "migrations_MiXeD_CaSe_MoDel",
},
),
| initial_mode",
models.ManyToMany | {
"filepath": "tests/migrations/test_fake_initial_case_insensitive/initial/0001_initial.py",
"language": "python",
"file_size": 845,
"cut_index": 535,
"middle_length": 52
} |
odels
class Migration(migrations.Migration):
initial = True
operations = [
migrations.CreateModel(
"fakeinitialmodel",
[
("id", models.AutoField(primary_key=True)),
("field", models.CharField(max_length=20)),
],
options={... | db_column="fIeLd_mIxEd_cAsE"),
),
migrations.AddField(
model_name="fakeinitialmodel",
name="fake_initial_model",
field=models.ManyToManyField(
to="migrations.fakeinitialmodel", db_table=" | ",
field=models.CharField(max_length=20, | {
"filepath": "tests/migrations/test_fake_initial_case_insensitive/fake_initial/0001_initial.py",
"language": "python",
"file_size": 903,
"cut_index": 547,
"middle_length": 52
} |
m django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = []
operations = [
migrations.CreateModel(
name="Project",
fields=[
(
"id",
models.AutoField(
... | e,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
],
),
migrations.AddField(
model_name="projec | ),
],
),
migrations.CreateModel(
name="Task",
fields=[
(
"id",
models.AutoField(
auto_created=Tru | {
"filepath": "tests/migrations/test_add_many_to_many_field_initial/0001_initial.py",
"language": "python",
"file_size": 1100,
"cut_index": 515,
"middle_length": 229
} |
s Migration(migrations.Migration):
initial = False
operations = [
migrations.CreateModel(
"Author",
[
("id", models.AutoField(primary_key=True)),
("name", models.CharField(max_length=255)),
("slug", models.SlugField(null=True)),
... | dels.AutoField(primary_key=True)),
("fluffy", models.BooleanField(default=True)),
],
),
migrations.AlterUniqueTogether(
name="author",
unique_together={("name", "slug")},
),
]
| "Tribble",
[
("id", mo | {
"filepath": "tests/migrations/test_migrations_initial_false/0001_not_initial.py",
"language": "python",
"file_size": 867,
"cut_index": 559,
"middle_length": 52
} |
odels
class Migration(migrations.Migration):
replaces = [
("migrations", "0001_initial"),
("migrations", "0002_second"),
]
operations = [
migrations.CreateModel(
"Author",
[
("id", models.AutoField(primary_key=True)),
("name"... | igrations.CreateModel(
"Book",
[
("id", models.AutoField(primary_key=True)),
(
"author",
models.ForeignKey("migrations.Author", models.SET_NULL, null=True),
| eld(default=0)),
],
),
m | {
"filepath": "tests/migrations/test_migrations_squashed/0001_squashed_0002.py",
"language": "python",
"file_size": 903,
"cut_index": 547,
"middle_length": 52
} |
port migrations, models
class Migration(migrations.Migration):
initial = True
operations = [
migrations.CreateModel(
"Author",
[
("id", models.AutoField(primary_key=True)),
("name", models.CharField(max_length=255)),
("slug", mod... | [
("id", models.AutoField(primary_key=True)),
("fluffy", models.BooleanField(default=True)),
],
),
migrations.AlterUniqueTogether(
name="author",
unique_together={("name" | tions.CreateModel(
"Tribble",
| {
"filepath": "tests/migrations/test_migrations_fake_split_initial/0001_initial.py",
"language": "python",
"file_size": 866,
"cut_index": 529,
"middle_length": 52
} |
db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("migrations", "0002_second"),
]
operations = [
migrations.CreateModel(
name="ModelWithCustomBase",
fields=[
(
"id",
models.... | "id",
models.BigAutoField(
verbose_name="ID",
serialize=False,
auto_created=True,
primary_key=True,
),
| ),
),
],
options={},
bases=(models.Model,),
),
migrations.CreateModel(
name="UnmigratedModel",
fields=[
(
| {
"filepath": "tests/migrations/test_migrations_no_changes/0003_third.py",
"language": "python",
"file_size": 1256,
"cut_index": 524,
"middle_length": 229
} |
m django.urls import NoReverseMatch, reverse_lazy
from .models import UnimportantThing
from .views import params_cbv, params_view, some_cbv, some_view
@override_settings(ROOT_URLCONF="resolve_url.urls")
class ResolveUrlTests(SimpleTestCase):
"""
Tests for the resolve_url() function.
"""
def test_url... | elative/"))
self.assertEqual("./", resolve_url("./"))
self.assertEqual("./relative/", resolve_url("./relative/"))
def test_full_url(self):
"""
Passing a full URL to resolve_url() results in the same url.
"""
| tive_path(self):
"""
Passing a relative URL path to resolve_url() results in the same url.
"""
self.assertEqual("../", resolve_url("../"))
self.assertEqual("../relative/", resolve_url("../r | {
"filepath": "tests/resolve_url/tests.py",
"language": "python",
"file_size": 3576,
"cut_index": 614,
"middle_length": 229
} |
rom django.db import models
class Author(models.Model):
name = models.CharField(max_length=50)
alias = models.CharField(max_length=50, null=True, blank=True)
goes_by = models.CharField(max_length=50, null=True, blank=True)
age = models.PositiveSmallIntegerField(default=30)
class Article(models.Model... | )
class Fan(models.Model):
name = models.CharField(max_length=50)
age = models.PositiveSmallIntegerField(default=30)
author = models.ForeignKey(Author, models.CASCADE, related_name="fans")
fan_since = models.DateTimeField(null=True, blank | ext = models.TextField()
written = models.DateTimeField()
published = models.DateTimeField(null=True, blank=True)
updated = models.DateTimeField(null=True, blank=True)
views = models.PositiveIntegerField(default=0 | {
"filepath": "tests/db_functions/models.py",
"language": "python",
"file_size": 2179,
"cut_index": 563,
"middle_length": 229
} |
r, connection
from django.db.models.functions import UUID4, UUID7
from django.test import TestCase
from django.test.testcases import skipIfDBFeature, skipUnlessDBFeature
from .models import UUIDModel
class TestUUID(TestCase):
@skipUnlessDBFeature("supports_uuid4_function")
def test_uuid4(self):
m1 = ... | s.create()
m2 = UUIDModel.objects.create()
UUIDModel.objects.update(uuid=UUID7())
m1.refresh_from_db()
m2.refresh_from_db()
self.assertIsInstance(m1.uuid, uuid.UUID)
self.assertEqual(m1.uuid.version, 7)
| sInstance(m1.uuid, uuid.UUID)
self.assertEqual(m1.uuid.version, 4)
self.assertNotEqual(m1.uuid, m2.uuid)
@skipUnlessDBFeature("supports_uuid7_function")
def test_uuid7(self):
m1 = UUIDModel.object | {
"filepath": "tests/db_functions/test_uuid.py",
"language": "python",
"file_size": 3940,
"cut_index": 614,
"middle_length": 229
} |
db.models import Value as V
from django.db.models.functions import Coalesce, Length, Upper
from django.test import TestCase
from django.test.utils import register_lookup
from .models import Author
class UpperBilateral(Upper):
bilateral = True
class FunctionTests(TestCase):
def test_nested_function_ordering... | cts.order_by(Length(Coalesce("alias", "name")).desc())
self.assertQuerySetEqual(
authors,
[
"John Smith",
"Rhonda Simpson",
],
lambda a: a.name,
)
def test | "name")))
self.assertQuerySetEqual(
authors,
[
"Rhonda Simpson",
"John Smith",
],
lambda a: a.name,
)
authors = Author.obje | {
"filepath": "tests/db_functions/tests.py",
"language": "python",
"file_size": 2552,
"cut_index": 563,
"middle_length": 229
} |
ort F, IntegerField
from django.db.models.functions import Chr, Left, Ord
from django.test import TestCase
from django.test.utils import register_lookup
from ..models import Author
class ChrTests(TestCase):
@classmethod
def setUpTestData(cls):
cls.john = Author.objects.create(name="John Smith", alias... | ), [self.elena, self.rhonda]
)
def test_non_ascii(self):
authors = Author.objects.annotate(first_initial=Left("name", 1))
self.assertCountEqual(authors.filter(first_initial=Chr(ord("É"))), [self.elena])
self.assertCount | Author.objects.annotate(first_initial=Left("name", 1))
self.assertCountEqual(authors.filter(first_initial=Chr(ord("J"))), [self.john])
self.assertCountEqual(
authors.exclude(first_initial=Chr(ord("J")) | {
"filepath": "tests/db_functions/text/test_chr.py",
"language": "python",
"file_size": 1864,
"cut_index": 537,
"middle_length": 229
} |
ld, TextField
from django.db.models import Value as V
from django.db.models.functions import Concat, ConcatPair, Upper
from django.test import TestCase
from django.utils import timezone
from ..models import Article, Author
lorem_ipsum = """
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod
... | t("alias", "goes_by"))
self.assertQuerySetEqual(
authors.order_by("name"),
[
"",
"smithjJohn",
"Maggie",
"adnohR",
],
lambda a: a.joined | me="John Smith", alias="smithj", goes_by="John")
Author.objects.create(name="Margaret", goes_by="Maggie")
Author.objects.create(name="Rhonda", alias="adnohR")
authors = Author.objects.annotate(joined=Conca | {
"filepath": "tests/db_functions/text/test_concat.py",
"language": "python",
"file_size": 4704,
"cut_index": 614,
"middle_length": 229
} |
db.models import IntegerField, Value
from django.db.models.functions import Left, Lower
from django.test import TestCase
from ..models import Author
class LeftTests(TestCase):
@classmethod
def setUpTestData(cls):
Author.objects.create(name="John Smith", alias="smithj")
Author.objects.create(n... | uerySetEqual(
authors.order_by("name"), ["smithj", "rh"], lambda a: a.alias
)
def test_invalid_length(self):
with self.assertRaisesMessage(ValueError, "'length' must be greater than 0"):
Author.objects.annotate( | "Rhond"], lambda a: a.name_part
)
# If alias is null, set it to the first 2 lower characters of the name.
Author.objects.filter(alias__isnull=True).update(alias=Lower(Left("name", 2)))
self.assertQ | {
"filepath": "tests/db_functions/text/test_left.py",
"language": "python",
"file_size": 1313,
"cut_index": 524,
"middle_length": 229
} |
ort CharField
from django.db.models.functions import Length
from django.test import TestCase
from django.test.utils import register_lookup
from ..models import Author
class LengthTests(TestCase):
def test_basic(self):
Author.objects.create(name="John Smith", alias="smithj")
Author.objects.create(... | ordering(self):
Author.objects.create(name="John Smith", alias="smithj")
Author.objects.create(name="John Smith", alias="smithj1")
Author.objects.create(name="Rhonda", alias="ronny")
authors = Author.objects.order_by(Length( | authors.order_by("name"),
[(10, 6), (6, None)],
lambda a: (a.name_length, a.alias_length),
)
self.assertEqual(authors.filter(alias_length__lte=Length("name")).count(), 1)
def test_ | {
"filepath": "tests/db_functions/text/test_length.py",
"language": "python",
"file_size": 1694,
"cut_index": 537,
"middle_length": 229
} |
db.models import CharField
from django.db.models.functions import Lower
from django.test import TestCase
from django.test.utils import register_lookup
from ..models import Author
class LowerTests(TestCase):
def test_basic(self):
Author.objects.create(name="John Smith", alias="smithj")
Author.obje... | ("rhonda", "rhonda"),
],
lambda a: (a.lower_name, a.name),
)
def test_num_args(self):
with self.assertRaisesMessage(
TypeError, "'Lower' takes exactly 1 argument (2 given)"
):
A | lambda a: a.lower_name
)
Author.objects.update(name=Lower("name"))
self.assertQuerySetEqual(
authors.order_by("name"),
[
("john smith", "john smith"),
| {
"filepath": "tests/db_functions/text/test_lower.py",
"language": "python",
"file_size": 1459,
"cut_index": 524,
"middle_length": 229
} |
nection
from django.db.models import CharField
from django.db.models.functions import MD5
from django.test import TestCase
from django.test.utils import register_lookup
from ..models import Author
class MD5Tests(TestCase):
@classmethod
def setUpTestData(cls):
Author.objects.bulk_create(
[... | order_by("pk")
)
self.assertSequenceEqual(
authors,
[
"6117323d2cabbc17d44c2b44587f682c",
"ca6d48f6772000141e66591aee49d56c",
"bf2c13bc1154e3d2e7df848cbc8be73d",
| ne),
]
)
def test_basic(self):
authors = (
Author.objects.annotate(
md5_alias=MD5("alias"),
)
.values_list("md5_alias", flat=True)
. | {
"filepath": "tests/db_functions/text/test_md5.py",
"language": "python",
"file_size": 1590,
"cut_index": 537,
"middle_length": 229
} |
jango.db.models import CharField, Value
from django.db.models.functions import Left, Ord
from django.test import TestCase
from django.test.utils import register_lookup
from ..models import Author
class OrdTests(TestCase):
@classmethod
def setUpTestData(cls):
cls.john = Author.objects.create(name="Joh... | authors.exclude(name_part__gt=Ord(Value("John"))), [self.john]
)
def test_transform(self):
with register_lookup(CharField, Ord):
authors = Author.objects.annotate(first_initial=Left("name", 1))
self.assertC | authors = Author.objects.annotate(name_part=Ord("name"))
self.assertCountEqual(
authors.filter(name_part__gt=Ord(Value("John"))), [self.elena, self.rhonda]
)
self.assertCountEqual(
| {
"filepath": "tests/db_functions/text/test_ord.py",
"language": "python",
"file_size": 1239,
"cut_index": 518,
"middle_length": 229
} |
els import Value
from django.db.models.functions import Length, LPad, RPad
from django.test import TestCase
from ..models import Author
class PadTests(TestCase):
def test_pad(self):
Author.objects.create(name="John", alias="j")
none_value = (
"" if connection.features.interprets_empty... | tring is longer than length it is truncated.
(LPad("name", 2), "Jo"),
(RPad("name", 2), "Jo"),
(LPad("name", 0), ""),
(RPad("name", 0), ""),
(LPad("name", None), none_value),
(RPad("na | 6, Value("x")), "xxJohn"),
(RPad("name", 6, Value("x")), "Johnxx"),
# The default pad string is a space.
(LPad("name", 6), " John"),
(RPad("name", 6), "John "),
# If s | {
"filepath": "tests/db_functions/text/test_pad.py",
"language": "python",
"file_size": 2298,
"cut_index": 563,
"middle_length": 229
} |
db import connection
from django.db.models import Value
from django.db.models.functions import Length, Repeat
from django.test import TestCase
from ..models import Author
class RepeatTests(TestCase):
def test_basic(self):
Author.objects.create(name="John", alias="xyz")
none_value = (
... | one_value),
)
for function, repeated_text in tests:
with self.subTest(function=function):
authors = Author.objects.annotate(repeated_text=function)
self.assertQuerySetEqual(
au | (Repeat("name", Length("alias")), "JohnJohnJohn"),
(Repeat(Value("x"), 3), "xxx"),
(Repeat("name", None), none_value),
(Repeat(Value(None), 4), none_value),
(Repeat("goes_by", 1), n | {
"filepath": "tests/db_functions/text/test_repeat.py",
"language": "python",
"file_size": 1276,
"cut_index": 524,
"middle_length": 229
} |
b.models.functions import Concat, Replace
from django.test import TestCase
from ..models import Author
class ReplaceTests(TestCase):
@classmethod
def setUpTestData(cls):
Author.objects.create(name="George R. R. Martin")
Author.objects.create(name="J. R. R. Tolkien")
def test_replace_with... | False,
)
def test_case_sensitive(self):
qs = Author.objects.annotate(
same_name=Replace(F("name"), Value("r. r."), Value(""))
)
self.assertQuerySetEqual(
qs,
[
("Georg | qs,
[
("George R. R. Martin", "George Martin"),
("J. R. R. Tolkien", "J. Tolkien"),
],
transform=lambda x: (x.name, x.without_middlename),
ordered= | {
"filepath": "tests/db_functions/text/test_replace.py",
"language": "python",
"file_size": 2604,
"cut_index": 563,
"middle_length": 229
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.