prefix stringlengths 512 512 | suffix stringlengths 256 256 | middle stringlengths 14 229 | meta dict |
|---|---|---|---|
els import CharField, Value
from django.db.models.functions import Length, Reverse, Trim
from django.test import TestCase
from django.test.utils import register_lookup
from ..models import Author
class ReverseTests(TestCase):
@classmethod
def setUpTestData(cls):
cls.john = Author.objects.create(name=... | as_nulls else None,
)
def test_basic(self):
authors = Author.objects.annotate(
backward=Reverse("name"),
constant=Reverse(Value("static string")),
)
self.assertQuerySetEqual(
authors, | author = Author.objects.annotate(backward=Reverse("alias")).get(
pk=self.python.pk
)
self.assertEqual(
author.backward,
"" if connection.features.interprets_empty_strings_ | {
"filepath": "tests/db_functions/text/test_reverse.py",
"language": "python",
"file_size": 2394,
"cut_index": 563,
"middle_length": 229
} |
nection
from django.db.models import IntegerField, Value
from django.db.models.functions import Length, Lower, Right
from django.test import TestCase
from ..models import Author
class RightTests(TestCase):
@classmethod
def setUpTestData(cls):
Author.objects.create(name="John Smith", alias="smithj")
... | name", 2)))
self.assertQuerySetEqual(
authors.order_by("name"), ["smithj", "da"], lambda a: a.alias
)
def test_invalid_length(self):
with self.assertRaisesMessage(ValueError, "'length' must be greater than 0"):
| rs.order_by("name"), ["Smith", "honda"], 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(Right(" | {
"filepath": "tests/db_functions/text/test_right.py",
"language": "python",
"file_size": 1848,
"cut_index": 537,
"middle_length": 229
} |
nection
from django.db.models import CharField
from django.db.models.functions import SHA1
from django.test import TestCase
from django.test.utils import register_lookup
from ..models import Author
class SHA1Tests(TestCase):
@classmethod
def setUpTestData(cls):
Author.objects.bulk_create(
... | .order_by("pk")
)
self.assertSequenceEqual(
authors,
[
"e61a3587b3f7a142b8c7b9263c82f8119398ecb7",
"0781e0745a2503e6ded05ed5bc554c421d781b0c",
"198d15ea139de04060ca | None),
]
)
def test_basic(self):
authors = (
Author.objects.annotate(
sha1_alias=SHA1("alias"),
)
.values_list("sha1_alias", flat=True)
| {
"filepath": "tests/db_functions/text/test_sha1.py",
"language": "python",
"file_size": 1645,
"cut_index": 537,
"middle_length": 229
} |
Error, connection
from django.db.models import CharField
from django.db.models.functions import SHA224
from django.test import TestCase
from django.test.utils import register_lookup
from ..models import Author
class SHA224Tests(TestCase):
@classmethod
def setUpTestData(cls):
Author.objects.bulk_creat... | flat=True)
.order_by("pk")
)
self.assertSequenceEqual(
authors,
[
"a61303c220731168452cb6acf3759438b1523e768f464e3704e12f70",
"2297904883e78183cb118fc3dc21a610d60daada7b6e | Author(alias=None),
]
)
def test_basic(self):
authors = (
Author.objects.annotate(
sha224_alias=SHA224("alias"),
)
.values_list("sha224_alias", | {
"filepath": "tests/db_functions/text/test_sha224.py",
"language": "python",
"file_size": 2156,
"cut_index": 563,
"middle_length": 229
} |
nection
from django.db.models import CharField
from django.db.models.functions import SHA256
from django.test import TestCase
from django.test.utils import register_lookup
from ..models import Author
class SHA256Tests(TestCase):
@classmethod
def setUpTestData(cls):
Author.objects.bulk_create(
... | )
.order_by("pk")
)
self.assertSequenceEqual(
authors,
[
"ef61a579c907bbed674c0dbcbcf7f7af8f851538eef7b8e58c5bee0b8cfdac4a",
"6e4cce20cd83fc7c202f21a8b2452a68509cf24d1c272a | ias=None),
]
)
def test_basic(self):
authors = (
Author.objects.annotate(
sha256_alias=SHA256("alias"),
)
.values_list("sha256_alias", flat=True | {
"filepath": "tests/db_functions/text/test_sha256.py",
"language": "python",
"file_size": 1843,
"cut_index": 537,
"middle_length": 229
} |
Migration):
operations = [
migrations.CreateModel(
name="MyModel1",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=Fal... | models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
| ds=[
(
"id",
| {
"filepath": "tests/migrations/test_migrations_squashed_partially_applied/0001_initial.py",
"language": "python",
"file_size": 967,
"cut_index": 582,
"middle_length": 52
} |
els import CharField
from django.db.models.functions import SHA384
from django.test import TestCase
from django.test.utils import register_lookup
from ..models import Author
class SHA384Tests(TestCase):
@classmethod
def setUpTestData(cls):
Author.objects.bulk_create(
[
Aut... | k")
)
self.assertSequenceEqual(
authors,
[
"9df976bfbcf96c66fbe5cba866cd4deaa8248806f15b69c4010a404112906e4ca7b57e"
"53b9967b80d77d4f5c2982cbc8",
"72202c8005492016cc670 | )
def test_basic(self):
authors = (
Author.objects.annotate(
sha384_alias=SHA384("alias"),
)
.values_list("sha384_alias", flat=True)
.order_by("p | {
"filepath": "tests/db_functions/text/test_sha384.py",
"language": "python",
"file_size": 2157,
"cut_index": 563,
"middle_length": 229
} |
rom django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("mutate_state_b", "0001_initial"),
]
operations = [
migrations.SeparateDatabaseAndState(
[],
[
migrations.CreateModel(
name="A",
... | verbose_name="ID",
auto_created=True,
primary_key=True,
),
),
],
),
],
)
| {
"filepath": "tests/migrations/migrations_test_apps/mutate_state_a/migrations/0001_initial.py",
"language": "python",
"file_size": 785,
"cut_index": 513,
"middle_length": 14
} | |
rls import include, path, re_path
from django.utils.translation import gettext_lazy as _
from django.views import defaults, i18n, static
from . import views
base_dir = os.path.dirname(os.path.abspath(__file__))
media_dir = os.path.join(base_dir, "media")
locale_dir = os.path.join(base_dir, "locale")
urlpatterns = [
... | path("raises404/", views.raises404),
path("raises500/", views.raises500),
path("custom_reporter_class_view/", views.custom_reporter_class_view),
path("technical404/", views.technical404, name="my404"),
path("classbased404/", views.Http4 | ew that raises an exception for the debug view
path("raises/", views.raises),
path("raises400/", views.raises400),
path("raises400_bad_request/", views.raises400_bad_request),
path("raises403/", views.raises403),
| {
"filepath": "tests/view_tests/urls.py",
"language": "python",
"file_size": 3461,
"cut_index": 614,
"middle_length": 229
} |
tils.translation import override
from django.views.csrf import CSRF_FAILURE_TEMPLATE_NAME, csrf_failure
@override_settings(ROOT_URLCONF="view_tests.urls")
class CsrfViewTests(SimpleTestCase):
def setUp(self):
super().setUp()
self.client = Client(enforce_csrf_checks=True)
@override_settings(
... | orbidden", status_code=403)
self.assertContains(
response, "CSRF verification failed. Request aborted.", status_code=403
)
with self.settings(LANGUAGE_CODE="nl"), override("en-us"):
response = self.client.po | .CsrfViewMiddleware",
],
)
def test_translation(self):
"""An invalid request is rejected with a localized error message."""
response = self.client.post("/")
self.assertContains(response, "F | {
"filepath": "tests/view_tests/tests/test_csrf.py",
"language": "python",
"file_size": 6900,
"cut_index": 716,
"middle_length": 229
} |
self):
# When DEBUG=True, technical_500_template() is called.
with self.assertLogs("django.request", "WARNING") as cm:
response = self.client.get("/raises400_bad_request/")
self.assertContains(response, '<div class="context" id="', status_code=400)
self.assertEqual(
... | self.assertContains(response, "<h1>403 Forbidden</h1>", status_code=403)
# Set up a test 403.html template.
@override_settings(
TEMPLATES=[
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
| ings(
TEMPLATES=[
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
}
]
)
def test_403(self):
response = self.client.get("/raises403/")
| {
"filepath": "tests/view_tests/tests/test_debug.py",
"language": "python",
"file_size": 85464,
"cut_index": 3790,
"middle_length": 229
} |
gured
from django.http import FileResponse, HttpResponseNotModified
from django.test import SimpleTestCase, override_settings
from django.utils.http import http_date
from django.views.static import directory_index, was_modified_since
from .. import urls
from ..urls import media_dir
@override_settings(DEBUG=True, ROO... | e_content = b"".join(response)
file_path = path.join(media_dir, filename)
with open(file_path, "rb") as fp:
self.assertEqual(fp.read(), response_content)
self.assertEqual(
len(response_con | view can serve static media"
media_files = ["file.txt", "file.txt.gz", "%2F.txt"]
for filename in media_files:
response = self.client.get("/%s/%s" % (self.prefix, quote(filename)))
respons | {
"filepath": "tests/view_tests/tests/test_static.py",
"language": "python",
"file_size": 8236,
"cut_index": 716,
"middle_length": 229
} |
dels.Model):
name = models.CharField(max_length=20)
slug = models.SlugField(max_length=20)
url = models.CharField("The URL", max_length=40)
class Meta:
ordering = ("pk",)
def __str__(self):
return self.name
def __repr__(self):
return self.__str__()
class WriterManage... | n self.name
class Article(models.Model):
ARTICLE_STATUS = (
(1, "Draft"),
(2, "Pending"),
(3, "Live"),
)
headline = models.CharField(max_length=50)
slug = models.SlugField()
pub_date = models.DateField()
cr | =50, help_text="Use both first and last names.")
archived = models.BooleanField(default=False, editable=False)
objects = WriterManager()
class Meta:
ordering = ("name",)
def __str__(self):
retur | {
"filepath": "tests/model_forms/models.py",
"language": "python",
"file_size": 16282,
"cut_index": 921,
"middle_length": 229
} |
t to null=False and
required=False should be valid.
"""
class FormForTestingIsValid(forms.ModelForm):
class Meta:
model = Student
fields = "__all__"
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
... | lid())
f2 = FormForTestingIsValid(data2)
self.assertTrue(f2.is_valid())
obj = f2.save()
self.assertEqual(obj.character, char)
def test_blank_false_with_null_true_foreign_key_field(self):
"""
A ModelForm | study": "Engineering"}
data2 = {"study": "Engineering", "character": char.pk}
# form is valid because required=False for field 'character'
f1 = FormForTestingIsValid(data)
self.assertTrue(f1.is_va | {
"filepath": "tests/model_forms/tests.py",
"language": "python",
"file_size": 138126,
"cut_index": 7068,
"middle_length": 229
} |
ckends.util
import datetime
import unittest
from django.db.backends import utils as typecasts
TEST_CASES = {
"typecast_date": (
("", None),
(None, None),
("2005-08-11", datetime.date(2005, 8, 11)),
("1990-01-01", datetime.date(1990, 1, 1)),
),
"typecast_time": (
("... | 0, 12)),
("00:00:12.5", datetime.time(0, 0, 12, 500000)),
("7:22:13.312", datetime.time(7, 22, 13, 312000)),
("12:45:30.126631", datetime.time(12, 45, 30, 126631)),
("12:45:30.126630", datetime.time(12, 45, 30, 126630)),
| me(8, 50)),
("12:00:00", datetime.time(12, 00)),
("12:30:00", datetime.time(12, 30)),
("13:00:00", datetime.time(13, 00)),
("23:59:00", datetime.time(23, 59)),
("00:00:12", datetime.time(0, | {
"filepath": "tests/db_typecasts/tests.py",
"language": "python",
"file_size": 2994,
"cut_index": 563,
"middle_length": 229
} |
migration.name,
self.repr_changes(changes),
)
)
operation = migration.operations[operation_position]
if not hasattr(operation, "field"):
self.fail(
"No field attribute for %s.%s op #%s."
% (
... |
app_label,
migration.name,
operation_position,
attr,
value,
getattr(field, attr, None),
| ):
if getattr(field, attr, None) != value:
self.fail(
"Field attribute mismatch for %s.%s op #%s, field.%s (expected %r, "
"got %r):\n%s"
% ( | {
"filepath": "tests/migrations/test_autodetector.py",
"language": "python",
"file_size": 211969,
"cut_index": 7068,
"middle_length": 229
} |
grated_app_syncdb")
@override_settings(
MIGRATION_MODULES={"migrations": "migrations.test_migrations_clashing_prefix"}
)
def test_ambiguous_prefix(self):
msg = (
"More than one migration matches 'a' in app 'migrations'. Please "
"be more specific."
)
... | (
"migrate", app_label="migrations", migration_name="nonexistent"
)
@override_settings(
MIGRATION_MODULES={"migrations": "migrations.test_migrations_initial_false"}
)
def test_migrate_initial_false(self):
| ations.test_migrations"})
def test_unknown_prefix(self):
msg = "Cannot find a migration matching 'nonexistent' from app 'migrations'."
with self.assertRaisesMessage(CommandError, msg):
call_command | {
"filepath": "tests/migrations/test_commands.py",
"language": "python",
"file_size": 153222,
"cut_index": 7068,
"middle_length": 229
} |
loader.graph.nodes["migrations", "0001_initial"], False),
(executor.loader.graph.nodes["migrations", "0002_second"], False),
],
)
# Were the tables there before?
self.assertTableNotExists("migrations_author")
self.assertTableNotExists("migrations_book")
... | None)])
self.assertEqual(
plan,
[
(executor.loader.graph.nodes["migrations", "0002_second"], True),
(executor.loader.graph.nodes["migrations", "0001_initial"], True),
],
)
| .assertTableExists("migrations_book")
# Rebuild the graph to reflect the new DB state
executor.loader.build_graph()
# Alright, let's undo what we did
plan = executor.migration_plan([("migrations", | {
"filepath": "tests/migrations/test_executor.py",
"language": "python",
"file_size": 39668,
"cut_index": 2151,
"middle_length": 229
} |
corder = MigrationRecorder(connection)
self.assertEqual(
{(x, y) for (x, y) in recorder.applied_migrations() if x == "myapp"},
set(),
)
recorder.record_applied("myapp", "0432_ponies")
self.assertEqual(
{(x, y) for (x, y) in recorder.applied_migrations(... | (
{(x, y) for (x, y) in recorder.applied_migrations() if x == "myapp"},
set(),
)
def test_has_table_cached(self):
"""
The has_table() method caches a positive result and not continually
query for | "])
self.assertEqual(
{(x, y) for (x, y) in recorder_other.applied_migrations() if x == "myapp"},
set(),
)
recorder.record_unapplied("myapp", "0432_ponies")
self.assertEqual | {
"filepath": "tests/migrations/test_loader.py",
"language": "python",
"file_size": 29448,
"cut_index": 1331,
"middle_length": 229
} |
cRouter:
"""
A router that doesn't have an opinion regarding migrating.
"""
def allow_migrate(self, db, app_label, **hints):
return None
class MigrateNothingRouter:
"""
A router that doesn't allow migrating.
"""
def allow_migrate(self, db, app_label, **hints):
return ... | databases = {"default", "other"}
def _test_create_model(self, app_label, should_run):
"""
CreateModel honors multi-db settings.
"""
operation = migrations.CreateModel(
"Pony",
[("id", models.Auto | ooRouter:
"""
A router that allows migrating depending on a hint.
"""
def allow_migrate(self, db, app_label, **hints):
return hints.get("foo", False)
class MultiDBOperationTests(OperationTestBase):
| {
"filepath": "tests/migrations/test_multidb.py",
"language": "python",
"file_size": 7040,
"cut_index": 716,
"middle_length": 229
} |
port OutputWrapper
from django.db.migrations.questioner import (
InteractiveMigrationQuestioner,
MigrationQuestioner,
)
from django.db.models import NOT_PROVIDED
from django.test import SimpleTestCase
from django.test.utils import override_settings
class QuestionerTests(SimpleTestCase):
@override_settings... | on("field_name", "model_name")
)
@mock.patch("builtins.input", return_value="2")
def test_ask_not_null_alteration_not_provided(self, mock):
questioner = InteractiveMigrationQuestioner(
prompt_output=OutputWrapper(String | ()
self.assertIs(False, questioner.ask_initial("migrations"))
def test_ask_not_null_alteration(self):
questioner = MigrationQuestioner()
self.assertIsNone(
questioner.ask_not_null_alterati | {
"filepath": "tests/migrations/test_questioner.py",
"language": "python",
"file_size": 5021,
"cut_index": 614,
"middle_length": 229
} |
ew_apps
project_state = ProjectState.from_apps(new_apps)
author_state = project_state.models["migrations", "author"]
author_proxy_state = project_state.models["migrations", "authorproxy"]
sub_author_state = project_state.models["migrations", "subauthor"]
book_state = project_sta... | book_index = models.Index(fields=["title"])
book_index.set_name_with_model(Book)
self.assertEqual(author_state.app_label, "migrations")
self.assertEqual(author_state.name, "Author")
self.assertEqual(list(author_state.f | od_no_default_manager_state = project_state.models[
"migrations", "foodnodefaultmanager"
]
food_order_manager_state = project_state.models[
"migrations", "foodorderedmanagers"
]
| {
"filepath": "tests/migrations/test_state.py",
"language": "python",
"file_size": 81574,
"cut_index": 3790,
"middle_length": 229
} |
django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("lookuperror_c", "0002_c2"),
("lookuperror_b", "0002_b2"),
("lookuperror_a", "0002_a2"),
]
operations = [
migrations.CreateModel(
name="A3",
fields=[
... | verbose_name="ID",
),
),
("b2", models.ForeignKey("lookuperror_b.B2", models.CASCADE)),
("c2", models.ForeignKey("lookuperror_c.C2", models.CASCADE)),
],
| key=True,
| {
"filepath": "tests/migrations/migrations_test_apps/lookuperror_a/migrations/0003_a3.py",
"language": "python",
"file_size": 802,
"cut_index": 517,
"middle_length": 14
} |
contrib.auth import views as auth_views
from django.urls import path
from django.views.generic import RedirectView
from . import views
from .models import Article, DateArticle
date_based_info_dict = {
"queryset": Article.objects.all(),
"date_field": "date_created",
"month_format": "%m",
}
object_list_dic... | path("accounts/logout/", auth_views.LogoutView.as_view()),
# Special URLs for particular regression cases.
path("中文/target/", views.index_page),
]
# redirects, both temporary and permanent, with non-ASCII targets
urlpatterns += [
path(
| t, day_format="%d")
date_based_datefield_info_dict = dict(
date_based_info_dict, queryset=DateArticle.objects.all()
)
urlpatterns = [
path("accounts/login/", auth_views.LoginView.as_view(template_name="login.html")),
| {
"filepath": "tests/view_tests/generic_urls.py",
"language": "python",
"file_size": 1324,
"cut_index": 524,
"middle_length": 229
} |
go.views.defaults import (
bad_request,
page_not_found,
permission_denied,
server_error,
)
from ..models import Article, Author, UrlArticle
@override_settings(ROOT_URLCONF="view_tests.urls")
class DefaultsTests(TestCase):
"""Test django views in django/views/defaults.py"""
nonexistent_urls =... | e(2001, 1, 1, 21, 22, 23),
)
Article.objects.create(
title="Current Article",
slug="current_article",
author=author,
date_created=datetime.datetime(2007, 9, 17, 21, 22, 23),
)
| Data(cls):
author = Author.objects.create(name="Boris")
Article.objects.create(
title="Old Article",
slug="old_article",
author=author,
date_created=datetime.datetim | {
"filepath": "tests/view_tests/tests/test_defaults.py",
"language": "python",
"file_size": 7727,
"cut_index": 716,
"middle_length": 229
} |
def test_basics(self):
f = forms.ModelChoiceField(Category.objects.all())
self.assertEqual(
list(f.choices),
[
("", get_blank_choice_label()),
(self.c1.pk, "Entertainment"),
(self.c2.pk, "A test"),
(self.c3.pk, ... | tRaises(ValidationError):
f.clean([{"foo": "bar"}])
self.assertEqual(f.clean(self.c2.id).name, "A test")
self.assertEqual(f.clean(self.c3.id).name, "Third")
# Add a Category object *after* the ModelChoiceField has alre | ith self.assertRaises(ValidationError):
f.clean(0)
# Invalid types that require TypeError to be caught.
with self.assertRaises(ValidationError):
f.clean([["fail"]])
with self.asser | {
"filepath": "tests/model_forms/test_modelchoicefield.py",
"language": "python",
"file_size": 17834,
"cut_index": 1331,
"middle_length": 229
} |
import Apps
from django.db import models
class CustomModelBase(models.base.ModelBase):
pass
class ModelWithCustomBase(models.Model, metaclass=CustomModelBase):
pass
class UnicodeModel(models.Model):
title = models.CharField("ÚÑÍ¢ÓÐÉ", max_length=20, default="“Ðjáñgó”")
class Meta:
# Disa... | serializable())
class Meta:
# Disable auto loading of this model as we load it on our own
apps = Apps()
class UnmigratedModel(models.Model):
"""
A model that is in a migration-less app (which this app is
if its migrations | return self.title
class Unserializable:
"""
An object that migration doesn't know how to serialize.
"""
pass
class UnserializableModel(models.Model):
title = models.CharField(max_length=20, default=Un | {
"filepath": "tests/migrations/models.py",
"language": "python",
"file_size": 1558,
"cut_index": 537,
"middle_length": 229
} |
imizer import MigrationOptimizer
from django.db.migrations.recorder import MigrationRecorder
from django.db.migrations.serializer import serializer_factory
from django.db.migrations.state import ProjectState
from django.test import SimpleTestCase, TransactionTestCase
from django.test.utils import extend_sys_path
from d... | tions[db])
recorder.migration_qs.filter(app="migrations").delete()
def get_table_description(self, table, using="default"):
with connections[using].cursor() as cursor:
return connections[using].introspection.get_table_d | """
available_apps = ["migrations"]
databases = {"default", "other"}
def tearDown(self):
# Reset applied-migrations state.
for db in self.databases:
recorder = MigrationRecorder(connec | {
"filepath": "tests/migrations/test_base.py",
"language": "python",
"file_size": 17066,
"cut_index": 921,
"middle_length": 229
} |
app_b", "0002"), None)
graph.add_dependency("app_a.0004", ("app_a", "0004"), ("app_a", "0003"))
graph.add_dependency("app_a.0003", ("app_a", "0003"), ("app_a", "0002"))
graph.add_dependency("app_a.0002", ("app_a", "0002"), ("app_a", "0001"))
graph.add_dependency("app_a.0003", ("app_a", "... | ,
)
# Test whole graph
self.assertEqual(
graph.forwards_plan(("app_a", "0004")),
[
("app_b", "0001"),
("app_b", "0002"),
("app_a", "0001"),
("ap | rds_plan(("app_a", "0001")),
[("app_a", "0001")],
)
# Test branch B only
self.assertEqual(
graph.forwards_plan(("app_b", "0002")),
[("app_b", "0001"), ("app_b", "0002")] | {
"filepath": "tests/migrations/test_graph.py",
"language": "python",
"file_size": 18986,
"cut_index": 1331,
"middle_length": 229
} |
options={"verbose_name": "Foo"},
bases=(UnicodeModel,),
managers=managers,
),
migrations.RenameModel("Foo", "Bar"),
],
[
migrations.CreateModel(
"Bar",
[("name",... | "),
migrations.RenameModel("Baa", "Bar"),
],
[
migrations.RenameModel("Foo", "Bar"),
],
)
def test_create_alter_model_options(self):
self.assertOptimizesTo(
| ],
)
def test_rename_model_self(self):
"""
RenameModels should absorb themselves.
"""
self.assertOptimizesTo(
[
migrations.RenameModel("Foo", "Baa | {
"filepath": "tests/migrations/test_optimizer.py",
"language": "python",
"file_size": 52246,
"cut_index": 2151,
"middle_length": 229
} |
Regression tests for Django built-in views.
"""
from django.db import models
class Author(models.Model):
name = models.CharField(max_length=100)
def get_absolute_url(self):
return "/authors/%s/" % self.id
class BaseArticle(models.Model):
"""
An abstract article Model so that we can create... | h a get_absolute_url defined.
"""
date_created = models.DateTimeField()
def get_absolute_url(self):
return "/urlarticles/%s/" % self.slug
get_absolute_url.purge = True
class DateArticle(BaseArticle):
"""
An article Mode | author = models.ForeignKey(Author, models.CASCADE)
class Meta:
abstract = True
class Article(BaseArticle):
date_created = models.DateTimeField()
class UrlArticle(BaseArticle):
"""
An Article class wit | {
"filepath": "tests/view_tests/models.py",
"language": "python",
"file_size": 1114,
"cut_index": 515,
"middle_length": 229
} |
ANGUAGES if code != current_language][
0
]
def test_setlang(self):
"""
The set_language view can be used to change the session language.
The user is redirected to the 'next' argument if provided.
"""
lang_code = self._get_inactive_language_code()
... | ssertEqual(language_cookie["domain"], "")
self.assertEqual(language_cookie["path"], "/")
self.assertEqual(language_cookie["max-age"], "")
self.assertEqual(language_cookie["httponly"], "")
self.assertEqual(language_cookie["sa | self.assertRedirects(response, "/")
# The language is set in a cookie.
language_cookie = self.client.cookies[settings.LANGUAGE_COOKIE_NAME]
self.assertEqual(language_cookie.value, lang_code)
self.a | {
"filepath": "tests/view_tests/tests/test_i18n.py",
"language": "python",
"file_size": 24654,
"cut_index": 1331,
"middle_length": 229
} |
o.test import SimpleTestCase, override_settings
@override_settings(ROOT_URLCONF="view_tests.generic_urls")
class URLHandling(SimpleTestCase):
"""
Tests for URL handling in views and responses.
"""
redirect_target = "/%E4%B8%AD%E6%96%87/target/"
def test_nonascii_redirect(self):
"""
... | permanent_nonascii_redirect(self):
"""
A non-ASCII argument to HttpPermanentRedirect is handled properly.
"""
response = self.client.get("/permanent_nonascii_redirect/")
self.assertRedirects(response, self.redirect_t |
def test_ | {
"filepath": "tests/view_tests/tests/test_specials.py",
"language": "python",
"file_size": 816,
"cut_index": 522,
"middle_length": 14
} |
tate alteration
operation = migrations.CreateModel(
"ShetlandPony",
[
(
"pony_ptr",
models.OneToOneField(
"test_crmoih.Pony",
models.CASCADE,
auto_created=True,... | els)
# Test the database alteration
self.assertTableNotExists("test_crmoih_shetlandpony")
with connection.schema_editor() as editor:
operation.database_forwards("test_crmoih", editor, project_state, new_state)
se | , models.IntegerField(default=1)),
],
)
new_state = project_state.clone()
operation.state_forwards("test_crmoih", new_state)
self.assertIn(("test_crmoih", "shetlandpony"), new_state.mod | {
"filepath": "tests/migrations/test_operations.py",
"language": "python",
"file_size": 295607,
"cut_index": 13624,
"middle_length": 229
} |
import forms
from django.core.exceptions import ValidationError
from django.test import TestCase
from .models import UUIDPK
class UUIDPKForm(forms.ModelForm):
class Meta:
model = UUIDPK
fields = "__all__"
class ModelFormBaseTest(TestCase):
def test_create_save_error(self):
form = UU... | not be changed because the data didn't validate."
with self.assertRaisesMessage(ValueError, msg):
form.save()
def test_model_multiple_choice_field_uuid_pk(self):
f = forms.ModelMultipleChoiceField(UUIDPK.objects.all())
|
form.save()
def test_update_save_error(self):
obj = UUIDPK.objects.create(name="foo")
form = UUIDPKForm({}, instance=obj)
self.assertFalse(form.is_valid())
msg = "The UUIDPK could | {
"filepath": "tests/model_forms/test_uuid.py",
"language": "python",
"file_size": 1505,
"cut_index": 524,
"middle_length": 229
} |
o.views.debug import (
ExceptionReporter,
SafeExceptionReporterFilter,
technical_500_response,
)
from django.views.decorators.debug import sensitive_post_parameters, sensitive_variables
TEMPLATES_PATH = Path(__file__).resolve().parent / "templates"
def index_page(request):
"""Dummy index page"""
... | cal_500_response(request, *sys.exc_info())
def raises500(request):
# We need to inspect the HTML generated by the fancy 500 debug view but
# the test client ignores it, so we send it explicitly.
try:
raise Exception
except Excepti | raises an exception in the stack frame's
# local vars won't hijack the technical 500 response (#15025).
def callable():
raise Exception
try:
raise Exception
except Exception:
return techni | {
"filepath": "tests/view_tests/views.py",
"language": "python",
"file_size": 14203,
"cut_index": 921,
"middle_length": 229
} |
from django.test import override_settings
from .test_base import MigrationTestBase
class Tests(MigrationTestBase):
"""
Deprecated model fields should still be usable in historic migrations.
"""
@override_settings(
MIGRATION_MODULES={"migrations": "migrations.deprecated_field_migrations"}
... | xist
self.assertTableExists("migrations_ipaddressfield")
# Unmigrate everything
call_command("migrate", "migrations", "zero", verbosity=0)
# Make sure it's all gone
self.assertTableNotExists("migrations_ipaddressfiel | verbosity=0)
# Make sure the right tables e | {
"filepath": "tests/migrations/test_deprecated_fields.py",
"language": "python",
"file_size": 871,
"cut_index": 559,
"middle_length": 52
} |
db.models import CharField
from django.db.models.functions import Upper
from django.test import TestCase
from django.test.utils import register_lookup
from ..models import Author
class UpperTests(TestCase):
def test_basic(self):
Author.objects.create(name="John Smith", alias="smithj")
Author.obje... | [
("JOHN SMITH", "JOHN SMITH"),
("RHONDA", "RHONDA"),
],
lambda a: (a.upper_name, a.name),
)
def test_transform(self):
with register_lookup(CharField, Upper):
| "JOHN SMITH",
"RHONDA",
],
lambda a: a.upper_name,
)
Author.objects.update(name=Upper("name"))
self.assertQuerySetEqual(
authors.order_by("name"),
| {
"filepath": "tests/db_functions/text/test_upper.py",
"language": "python",
"file_size": 1393,
"cut_index": 524,
"middle_length": 229
} |
om django.test.utils import register_lookup
from ..models import DecimalModel, FloatModel, IntegerModel
class RoundTests(TestCase):
def test_null(self):
IntegerModel.objects.create()
obj = IntegerModel.objects.annotate(null_round=Round("normal")).first()
self.assertIsNone(obj.null_round)
... | def test_decimal(self):
DecimalModel.objects.create(n1=Decimal("-12.9"), n2=Decimal("0.6"))
obj = DecimalModel.objects.annotate(
n1_round=Round("n1"), n2_round=Round("n2")
).first()
self.assertIsInstance(obj.n1 | null_round)
def test_null_with_negative_precision(self):
IntegerModel.objects.create()
obj = IntegerModel.objects.annotate(null_round=Round("normal", -1)).first()
self.assertIsNone(obj.null_round)
| {
"filepath": "tests/db_functions/math/test_round.py",
"language": "python",
"file_size": 5737,
"cut_index": 716,
"middle_length": 229
} |
import DecimalField
from django.db.models.functions import Sign
from django.test import TestCase
from django.test.utils import register_lookup
from ..models import DecimalModel, FloatModel, IntegerModel
class SignTests(TestCase):
def test_null(self):
IntegerModel.objects.create()
obj = IntegerMod... | self.assertEqual(obj.n1_sign, Decimal("-1"))
self.assertEqual(obj.n2_sign, Decimal("1"))
def test_float(self):
FloatModel.objects.create(f1=-27.5, f2=0.33)
obj = FloatModel.objects.annotate(
f1_sign=Sign("f1"), | "0.6"))
obj = DecimalModel.objects.annotate(
n1_sign=Sign("n1"), n2_sign=Sign("n2")
).first()
self.assertIsInstance(obj.n1_sign, Decimal)
self.assertIsInstance(obj.n2_sign, Decimal)
| {
"filepath": "tests/db_functions/math/test_sign.py",
"language": "python",
"file_size": 2194,
"cut_index": 563,
"middle_length": 229
} |
o.db.models import DecimalField
from django.db.models.functions import Sin
from django.test import TestCase
from django.test.utils import register_lookup
from ..models import DecimalModel, FloatModel, IntegerModel
class SinTests(TestCase):
def test_null(self):
IntegerModel.objects.create()
obj = ... | tEqual(obj.n1_sin, Decimal(math.sin(obj.n1)))
self.assertAlmostEqual(obj.n2_sin, Decimal(math.sin(obj.n2)))
def test_float(self):
FloatModel.objects.create(f1=-27.5, f2=0.33)
obj = FloatModel.objects.annotate(f1_sin=Sin("f1"), | ecimal("0.6"))
obj = DecimalModel.objects.annotate(n1_sin=Sin("n1"), n2_sin=Sin("n2")).first()
self.assertIsInstance(obj.n1_sin, Decimal)
self.assertIsInstance(obj.n2_sin, Decimal)
self.assertAlmos | {
"filepath": "tests/db_functions/math/test_sin.py",
"language": "python",
"file_size": 2264,
"cut_index": 563,
"middle_length": 229
} |
o.db.models import DecimalField
from django.db.models.functions import Sqrt
from django.test import TestCase
from django.test.utils import register_lookup
from ..models import DecimalModel, FloatModel, IntegerModel
class SqrtTests(TestCase):
def test_null(self):
IntegerModel.objects.create()
obj ... | ecimal)
self.assertAlmostEqual(obj.n1_sqrt, Decimal(math.sqrt(obj.n1)))
self.assertAlmostEqual(obj.n2_sqrt, Decimal(math.sqrt(obj.n2)))
def test_float(self):
FloatModel.objects.create(f1=27.5, f2=0.33)
obj = FloatModel. | n2=Decimal("0.6"))
obj = DecimalModel.objects.annotate(
n1_sqrt=Sqrt("n1"), n2_sqrt=Sqrt("n2")
).first()
self.assertIsInstance(obj.n1_sqrt, Decimal)
self.assertIsInstance(obj.n2_sqrt, D | {
"filepath": "tests/db_functions/math/test_sqrt.py",
"language": "python",
"file_size": 2346,
"cut_index": 563,
"middle_length": 229
} |
o.db.models import DecimalField
from django.db.models.functions import Tan
from django.test import TestCase
from django.test.utils import register_lookup
from ..models import DecimalModel, FloatModel, IntegerModel
class TanTests(TestCase):
def test_null(self):
IntegerModel.objects.create()
obj = ... | tEqual(obj.n1_tan, Decimal(math.tan(obj.n1)))
self.assertAlmostEqual(obj.n2_tan, Decimal(math.tan(obj.n2)))
def test_float(self):
FloatModel.objects.create(f1=-27.5, f2=0.33)
obj = FloatModel.objects.annotate(f1_tan=Tan("f1"), | ecimal("0.6"))
obj = DecimalModel.objects.annotate(n1_tan=Tan("n1"), n2_tan=Tan("n2")).first()
self.assertIsInstance(obj.n1_tan, Decimal)
self.assertIsInstance(obj.n2_tan, Decimal)
self.assertAlmos | {
"filepath": "tests/db_functions/math/test_tan.py",
"language": "python",
"file_size": 2266,
"cut_index": 563,
"middle_length": 229
} |
eModel(
name="Author",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
... | fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbo | goes_by", models.CharField(max_length=50, null=True, blank=True)),
("age", models.PositiveSmallIntegerField(default=30)),
],
),
migrations.CreateModel(
name="Article",
| {
"filepath": "tests/db_functions/migrations/0002_create_test_models.py",
"language": "python",
"file_size": 6135,
"cut_index": 716,
"middle_length": 229
} |
(max_length=50)
address = models.CharField(max_length=80)
class Meta:
ordering = ("name",)
class Restaurant(Place):
serves_hot_dogs = models.BooleanField(default=False)
serves_pizza = models.BooleanField(default=False)
class ItalianRestaurant(Restaurant):
serves_gnocchi = models.Boolean... | t = models.OneToOneField(Place, models.CASCADE, parent_link=True)
class ParkingLot4(models.Model):
# Test parent_link connector can be discovered in abstract classes.
parent = models.OneToOneField(Place, models.CASCADE, parent_link=True)
cla | ary_key=True, parent_link=True
)
capacity = models.IntegerField()
class ParkingLot3(Place):
# The parent_link connector need not be the pk on the model.
primary_key = models.AutoField(primary_key=True)
paren | {
"filepath": "tests/model_inheritance_regress/models.py",
"language": "python",
"file_size": 4536,
"cut_index": 614,
"middle_length": 229
} |
tion,
User,
Wholesaler,
)
class ModelInheritanceTest(TestCase):
def test_model_inheritance(self):
# Regression for #7350, #7202
# When you create a Parent object with a specific reference to an
# existent child instance, saving the Parent doesn't duplicate the
# child. This... | serves_hot_dogs=True,
serves_pizza=False,
)
restaurant.save_base(raw=True)
italian_restaurant = ItalianRestaurant(
restaurant_ptr=restaurant, serves_gnocchi=True
)
italian_restaurant. | # Create a child-parent-grandparent chain
place1 = Place(name="Guido's House of Pasta", address="944 W. Fullerton")
place1.save_base(raw=True)
restaurant = Restaurant(
place_ptr=place1,
| {
"filepath": "tests/model_inheritance_regress/tests.py",
"language": "python",
"file_size": 25921,
"cut_index": 1331,
"middle_length": 229
} |
igner(key="predictable-secret")
signer2 = signing.Signer(key="predictable-secret2")
for s in (
b"hello",
b"3098247:529:087:",
"\u2019".encode(),
):
self.assertEqual(
signer.signature(s),
signing.base64_hmac(
... | ignature("hello"),
signing.base64_hmac(
"extra-salt" + "signer",
"hello",
"predictable-secret",
algorithm=signer.algorithm,
),
)
self.assertNotEqual(
| self.assertNotEqual(signer.signature(s), signer2.signature(s))
def test_signature_with_salt(self):
signer = signing.Signer(key="predictable-secret", salt="extra-salt")
self.assertEqual(
signer.s | {
"filepath": "tests/signing/tests.py",
"language": "python",
"file_size": 9397,
"cut_index": 921,
"middle_length": 229
} |
he database API.
"""
from django.db import models
from django.db.models.lookups import IsNull
class Alarm(models.Model):
desc = models.CharField(max_length=100)
time = models.TimeField()
def __str__(self):
return "%s (%s)" % (self.time, self.desc)
class Author(models.Model):
name = models.... | rue, null=True)
class Meta:
ordering = ("-pub_date", "headline")
def __str__(self):
return self.headline
class Tag(models.Model):
articles = models.ManyToManyField(Article)
name = models.CharField(max_length=100)
cl | (models.Model):
headline = models.CharField(max_length=100)
pub_date = models.DateTimeField()
author = models.ForeignKey(Author, models.SET_NULL, blank=True, null=True)
slug = models.SlugField(unique=True, blank=T | {
"filepath": "tests/lookup/models.py",
"language": "python",
"file_size": 2848,
"cut_index": 563,
"middle_length": 229
} |
db.models import F, Sum
from django.test import TestCase
from .models import Product, Stock
class DecimalFieldLookupTests(TestCase):
@classmethod
def setUpTestData(cls):
cls.p1 = Product.objects.create(name="Product1", qty_target=10)
Stock.objects.create(product=cls.p1, qty_available=5)
... | ct=cls.p3, qty_available=4)
cls.queryset = Product.objects.annotate(
qty_available_sum=Sum("stock__qty_available"),
).annotate(qty_needed=F("qty_target") - F("qty_available_sum"))
def test_gt(self):
qs = self.querys | Stock.objects.create(product=cls.p2, qty_available=5)
cls.p3 = Product.objects.create(name="Product3", qty_target=10)
Stock.objects.create(product=cls.p3, qty_available=5)
Stock.objects.create(produ | {
"filepath": "tests/lookup/test_decimalfield.py",
"language": "python",
"file_size": 1467,
"cut_index": 524,
"middle_length": 229
} |
mock
from django.db.models import DateTimeField, Value
from django.db.models.lookups import Lookup, YearLookup
from django.test import SimpleTestCase
class CustomLookup(Lookup):
pass
class LookupTests(SimpleTestCase):
def test_equality(self):
lookup = Lookup(Value(1), Value(2))
self.assertE... | "Lookup(Value(1), Value('a'))"),
(
YearLookup(
Value(datetime(2010, 1, 1, 0, 0, 0)),
Value(datetime(2010, 1, 1, 23, 59, 59)),
),
"YearLookup("
| ))
self.assertNotEqual(lookup, Lookup(Value(3), lookup.rhs))
self.assertNotEqual(lookup, CustomLookup(lookup.lhs, lookup.rhs))
def test_repr(self):
tests = [
(Lookup(Value(1), Value("a")), | {
"filepath": "tests/lookup/test_lookups.py",
"language": "python",
"file_size": 2345,
"cut_index": 563,
"middle_length": 229
} |
TestCase
from .models import Alarm
class TimeFieldLookupTests(TestCase):
@classmethod
def setUpTestData(self):
# Create a few Alarms
self.al1 = Alarm.objects.create(desc="Early", time="05:30")
self.al2 = Alarm.objects.create(desc="Late", time="10:00")
self.al3 = Alarm.objects... | rtSequenceEqual(
Alarm.objects.filter(time__minute=30),
[self.al1],
)
def test_second_lookups(self):
self.assertSequenceEqual(
Alarm.objects.filter(time__second=56),
[self.al3],
) | def test_minute_lookups(self):
self.asse | {
"filepath": "tests/lookup/test_timefield.py",
"language": "python",
"file_size": 844,
"cut_index": 535,
"middle_length": 52
} |
Article.objects.filter(id__iexact=str(self.a1.id)),
[self.a1],
)
@skipUnlessDBFeature("supports_date_lookup_using_string")
def test_lookup_date_as_str(self):
# A date lookup can be performed using a string search
self.assertSequenceEqual(
Article.objects... | rticle.objects.iterator(),
[
"Article 5",
"Article 6",
"Article 4",
"Article 2",
"Article 3",
"Article 7",
"Article 1",
| (), which is a generator that "lazily"
# returns results using database-level iteration.
self.assertIsInstance(Article.objects.iterator(), collections.abc.Iterator)
self.assertQuerySetEqual(
A | {
"filepath": "tests/lookup/tests.py",
"language": "python",
"file_size": 76504,
"cut_index": 3790,
"middle_length": 229
} |
.db import models
from django.db.models.query_utils import DeferredAttribute
class CustomTypedField(models.TextField):
def db_type(self, connection):
return "custom_field"
class CustomDeferredAttribute(DeferredAttribute):
def __get__(self, instance, cls=None):
self._count_call(instance, "get... | count_attr = "_%s_%s_count" % (self.field.attname, get_or_set)
count = getattr(instance, count_attr, 0)
setattr(instance, count_attr, count + 1)
class CustomDescriptorField(models.CharField):
descriptor_class = CustomDeferredAttribute | ef _count_call(self, instance, get_or_set):
| {
"filepath": "tests/field_subclassing/fields.py",
"language": "python",
"file_size": 832,
"cut_index": 523,
"middle_length": 52
} |
jango.db import connection, models
from django.test import SimpleTestCase
from .fields import CustomDescriptorField, CustomTypedField
class TestDbType(SimpleTestCase):
def test_db_parameters_respects_db_type(self):
f = CustomTypedField()
self.assertEqual(f.db_parameters(connection)["type"], "cust... | e = "foo"
self.assertFalse(hasattr(m, "_name_get_count"))
self.assertEqual(m._name_set_count, 2)
self.assertEqual(m.name, "foo")
self.assertEqual(m._name_get_count, 1)
self.assertEqual(m._name_set_count, 2)
m | gth=32)
m = CustomDescriptorModel()
self.assertFalse(hasattr(m, "_name_get_count"))
# The field is set to its default in the model constructor.
self.assertEqual(m._name_set_count, 1)
m.nam | {
"filepath": "tests/field_subclassing/tests.py",
"language": "python",
"file_size": 1245,
"cut_index": 518,
"middle_length": 229
} |
t (
RECURSIVE_RELATIONSHIP_CONSTANT,
ManyToManyDescriptor,
RelatedField,
create_many_to_many_intermediary_model,
)
class CustomManyToManyField(RelatedField):
"""
Ticket #24104 - Need to have a custom ManyToManyField,
which is not an inheritor of ManyToManyField.
"""
many_to_many =... | gs["rel"] = models.ManyToManyRel(
self,
to,
related_name=related_name,
related_query_name=related_query_name,
limit_choices_to=limit_choices_to,
symmetrical=(
symmetric | ,
symmetrical=None,
through=None,
through_fields=None,
db_table=None,
**kwargs,
):
try:
to._meta
except AttributeError:
to = str(to)
kwar | {
"filepath": "tests/schema/fields.py",
"language": "python",
"file_size": 3311,
"cut_index": 614,
"middle_length": 229
} |
main test
# runner doesn't migrate them.
new_apps = Apps()
class Author(models.Model):
name = models.CharField(max_length=255)
height = models.PositiveIntegerField(null=True, blank=True)
weight = models.IntegerField(null=True, blank=True)
uuid = models.UUIDField(null=True)
class Meta:
a... | tiveIntegerField(null=True, blank=True, default=42)
class Meta:
apps = new_apps
class AuthorWithEvenLongerName(models.Model):
name = models.CharField(max_length=255)
height = models.PositiveIntegerField(null=True, blank=True)
cl | ithIndex(models.Model):
text_field = models.TextField(db_index=True)
class Meta:
apps = new_apps
class AuthorWithDefaultHeight(models.Model):
name = models.CharField(max_length=255)
height = models.Posi | {
"filepath": "tests/schema/models.py",
"language": "python",
"file_size": 5136,
"cut_index": 716,
"middle_length": 229
} |
"
Get the constraints on a table using a new cursor.
"""
with connection.cursor() as cursor:
return connection.introspection.get_constraints(cursor, table)
def get_constraints_for_column(self, model, column_name):
constraints = self.get_constraints(model._meta.db_table)
... | s AS oc
JOIN pg_index as i on oc.oid = ANY(i.indclass)
JOIN pg_class as c on c.oid = i.indexrelid
WHERE c.relname = %s
"""
cursor.execute(sql, [constraint_name])
return [ro | return sorted(constraints_for_column)
def get_constraint_opclasses(self, constraint_name):
with connection.cursor() as cursor:
sql = """
SELECT opcname
FROM pg_opclas | {
"filepath": "tests/schema/tests.py",
"language": "python",
"file_size": 247095,
"cut_index": 7068,
"middle_length": 229
} |
rom unittest import mock
from django.core.checks import Error
from django.db import connections, models
from django.test import SimpleTestCase
from django.test.utils import isolate_apps
def dummy_allow_migrate(db, app_label, **hints):
# Prevent checks from being run on the 'other' database, which doesn't have
... | field = models.IntegerField()
field = Model._meta.get_field("field")
with mock.patch.object(
connections["default"].validation, "check_field", return_value=[error]
):
self.assertEqual(field.check(da | .models.fields.router.allow_migrate", new=dummy_allow_migrate)
def test_check_field(self):
"""Test if backend specific checks are performed."""
error = Error("an error")
class Model(models.Model):
| {
"filepath": "tests/invalid_models_tests/test_backend_specific.py",
"language": "python",
"file_size": 1029,
"cut_index": 513,
"middle_length": 229
} |
@isolate_apps("invalid_models_tests")
class DeprecatedFieldsTests(SimpleTestCase):
def test_IPAddressField_deprecated(self):
class IPAddressModel(models.Model):
ip = models.IPAddressField()
model = IPAddressModel()
self.assertEqual(
model.check(),
[
... | class CommaSeparatedIntegerModel(models.Model):
csi = models.CommaSeparatedIntegerField(max_length=64)
model = CommaSeparatedIntegerModel()
self.assertEqual(
model.check(),
[
checks.Err | ressField instead.",
obj=IPAddressModel._meta.get_field("ip"),
id="fields.E900",
)
],
)
def test_CommaSeparatedIntegerField_deprecated(self):
| {
"filepath": "tests/invalid_models_tests/test_deprecated_fields.py",
"language": "python",
"file_size": 5689,
"cut_index": 716,
"middle_length": 229
} |
class Meta:
unique_together = [["m2m"]]
self.assertEqual(
Model.check(),
[
Error(
"'unique_together' refers to a ManyToManyField 'm2m', but "
"ManyToManyFields are not permitted in 'unique_together'.",
... | e=models.CASCADE, related_name="bar_2"
)
class Meta:
unique_together = [["foo_1_id", "foo_2"]]
self.assertEqual(Bar.check(), [])
def test_pointing_to_composite_primary_key(self):
class Model(mo | pass
class Bar(models.Model):
foo_1 = models.ForeignKey(
Foo, on_delete=models.CASCADE, related_name="bar_1"
)
foo_2 = models.ForeignKey(
Foo, on_delet | {
"filepath": "tests/invalid_models_tests/test_models.py",
"language": "python",
"file_size": 104949,
"cut_index": 3790,
"middle_length": 229
} |
auto = models.AutoField(primary_key=True, max_length=2)
field = Model._meta.get_field("auto")
self.assertEqual(
field.check(),
[
DjangoWarning(
"'max_length' is ignored when used with %s."
% field.__class__.__name__,
... | d(default=None)
for field_name in ("field1", "field2"):
field = Model._meta.get_field(field_name)
self.assertEqual(field.check(), [])
def test_str_default_value(self):
class Model(models.Model):
fie | lid_models_tests")
class BinaryFieldTests(SimpleTestCase):
def test_valid_default_value(self):
class Model(models.Model):
field1 = models.BinaryField(default=b"test")
field2 = models.BinaryFiel | {
"filepath": "tests/invalid_models_tests/test_ordinary_fields.py",
"language": "python",
"file_size": 53194,
"cut_index": 2151,
"middle_length": 229
} |
.Model):
many_to_many_rel = models.ManyToManyField(OtherModel)
class O2OModel(models.Model):
one_to_one_rel = models.OneToOneField(
"invalid_models_tests.M2MModel_many_to_many_rel",
on_delete=models.CASCADE,
)
field = O2OModel._meta.g... | field = ModelM2M._meta.get_field("m2m")
self.assertEqual(
ModelM2M.check(),
[
DjangoWarning(
"null has no effect on ManyToManyField.",
obj=field,
| name = models.CharField(max_length=20)
class ModelM2M(models.Model):
m2m = models.ManyToManyField(
Model, null=True, validators=[lambda x: x], db_comment="Column comment"
)
| {
"filepath": "tests/invalid_models_tests/test_relative_fields.py",
"language": "python",
"file_size": 93353,
"cut_index": 3790,
"middle_length": 229
} |
d_model_traverse(self):
a1 = Article.objects.create(
title="First one",
pub_date=datetime.datetime(2005, 7, 28, 9, 0, 0),
)
a2 = Article.objects.create(
title="Another one",
pub_date=datetime.datetime(2010, 7, 28, 10, 0, 0),
)
a3 = ... | a2.comments.create(
text="LMAO",
pub_date=datetime.datetime(2010, 7, 28, 10, 10, 10),
)
a3.comments.create(
text="+1",
pub_date=datetime.datetime(2005, 8, 29, 10, 10, 10),
)
| "Im the HULK!",
pub_date=datetime.datetime(2005, 7, 28, 9, 30, 0),
)
a1.comments.create(
text="HULK SMASH!",
pub_date=datetime.datetime(2005, 7, 29, 1, 30, 0),
)
| {
"filepath": "tests/datetimes/tests.py",
"language": "python",
"file_size": 7391,
"cut_index": 716,
"middle_length": 229
} |
nals" for WarnAboutExternalUseTests.
#
# Every function in this module ends up calling deprecated_function(), which
# calls warn_about_external_use(). The other functions provide various stack
# depths and qualnames for test purposes. All functions pass their arguments
# through to warn_about_external_use().
#
# The te... | category=None, **kwargs):
kwargs.setdefault("internal_modules", (__name__,))
warn_about_external_use(
message or "Message",
category or RemovedInNextVersionWarning,
**kwargs,
)
def one_indirection(*args, **kwargs):
| other modules "internal."
from django.utils.deprecation import (
RemovedAfterNextVersionWarning,
RemovedInNextVersionWarning,
deprecate_posargs,
warn_about_external_use,
)
def deprecated_function(message=None, | {
"filepath": "tests/deprecation/internal.py",
"language": "python",
"file_size": 1975,
"cut_index": 537,
"middle_length": 229
} |
# don't need to be updated each release. In actual use, you must substitute
# a specific RemovedInDjangoXXWarning.
def assertDeprecated(self, params, name):
msg = (
"Passing positional argument(s) {0} to {1}() is deprecated. Use keyword "
"arguments instead."
)
r... | cted args"),
self.assertDeprecated("'a', 'b'", "some_func"),
):
result = some_func(10, 20)
self.assertEqual(result, (10, 20))
with (
self.subTest("One affected arg"),
self.assertD | re remapped to keyword-only arguments."""
@deprecate_posargs(RemovedAfterNextVersionWarning, ["a", "b"])
def some_func(*, a=1, b=2):
return a, b
with (
self.subTest("Multiple affe | {
"filepath": "tests/deprecation/test_deprecate_posargs.py",
"language": "python",
"file_size": 15258,
"cut_index": 921,
"middle_length": 229
} |
onMiddleware,
LoginRequiredMiddleware,
)
from django.contrib.flatpages.middleware import FlatpageFallbackMiddleware
from django.contrib.messages.middleware import MessageMiddleware
from django.contrib.redirects.middleware import RedirectFallbackMiddleware
from django.contrib.sessions.middleware import SessionMiddle... | nLinkEmailsMiddleware, CommonMiddleware
from django.middleware.csrf import CsrfViewMiddleware
from django.middleware.gzip import GZipMiddleware
from django.middleware.http import ConditionalGetMiddleware
from django.middleware.locale import LocaleMiddlewar | e
from django.middleware.cache import (
CacheMiddleware,
FetchFromCacheMiddleware,
UpdateCacheMiddleware,
)
from django.middleware.clickjacking import XFrameOptionsMiddleware
from django.middleware.common import Broke | {
"filepath": "tests/deprecation/test_middleware_mixin.py",
"language": "python",
"file_size": 5358,
"cut_index": 716,
"middle_length": 229
} |
rom types import ModuleType
from django.conf import (
USE_BLANK_CHOICE_DASH_DEPRECATED_MSG,
LazySettings,
Settings,
settings,
)
from django.test import SimpleTestCase
from django.utils.deprecation import RemovedInDjango70Warning
# RemovedInDjango70Warning.
class UseBlankChoiceDashDeprecationTests(Sim... | gs_module.USE_BLANK_CHOICE_DASH = True
sys.modules["fake_settings_module"] = settings_module
try:
with self.assertRaisesMessage(RemovedInDjango70Warning, self.msg):
Settings("fake_settings_module")
finall | with self.settings(USE_BLANK_CHOICE_DASH=True):
pass
def test_settings_init_warning(self):
settings_module = ModuleType("fake_settings_module")
settings_module.USE_TZ = False
settin | {
"filepath": "tests/deprecation/test_use_blank_choice_dash.py",
"language": "python",
"file_size": 1407,
"cut_index": 524,
"middle_length": 229
} |
rnal
class WarnAboutExternalUseTests(SimpleTestCase):
@contextmanager
def assertNotWarns(self, category, **kwargs):
with warnings.catch_warnings(record=True) as caught_warnings:
warnings.filterwarnings("always", category=category, **kwargs)
yield caught_warnings
self.as... | ssertWarnsMessage(RemovedInNextVersionWarning, msg) as warning:
internal.deprecated_function(msg, RemovedInNextVersionWarning)
self.assertWarningPointsHere(warning)
def test_internal_use_does_not_warn(self):
with self.asser | sertEqual(warning.filename, caller_frame.f_code.co_filename)
self.assertEqual(warning.lineno, caller_frame.f_lineno + offset)
def test_external_use_warns(self):
msg = "This is deprecated."
with self.a | {
"filepath": "tests/deprecation/test_warn_about_external_use.py",
"language": "python",
"file_size": 8134,
"cut_index": 716,
"middle_length": 229
} |
django_file_prefixes,
)
class DjangoFilePrefixesTests(SimpleTestCase):
def setUp(self):
django_file_prefixes.cache_clear()
self.addCleanup(django_file_prefixes.cache_clear)
def test_no_file(self):
orig_file = django.__file__
try:
# Depending on the cwd, Python m... | IsInstance(prefixes, tuple)
self.assertEqual(len(prefixes), 1)
self.assertTrue(prefixes[0].endswith(f"{os.path.sep}django{os.path.sep}"))
def test_does_not_match_packages_prefixed_with_django(self):
other_file = Path(django.__f | del django.__file__
self.assertEqual(django_file_prefixes(), ())
finally:
django.__file__ = orig_file
def test_with_file(self):
prefixes = django_file_prefixes()
self.assert | {
"filepath": "tests/deprecation/tests.py",
"language": "python",
"file_size": 7112,
"cut_index": 716,
"middle_length": 229
} |
o.contrib.admindocs app.
"""
from django.db import models
from django.utils.functional import cached_property
class Company(models.Model):
name = models.CharField(max_length=200)
class Group(models.Model):
name = models.CharField(max_length=200)
class Family(models.Model):
"""
Links with differen... | .Model):
"""
Stores information about a person, related to :model:`myapp.Company`.
**Notes**
Use ``save_changes()`` when saving this object.
``company``
Field storing :model:`myapp.Company` where the person works.
(DESCR | Index>`
This is a line with template :template:`index template <Index.html>`
This is a line with filter :filter:`example filter <filtername>`
"""
last_name = models.CharField(max_length=200)
class Person(models | {
"filepath": "tests/admin_docs/models.py",
"language": "python",
"file_size": 2759,
"cut_index": 563,
"middle_length": 229
} |
go.db import connection
from django.db.models import TextField
from django.db.models.functions import Cast, Now
from django.test import TestCase
from django.utils import timezone
from ..models import Article
lorem_ipsum = """
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod
tempor incid... | rticle.objects.filter(id=a1.id, published=None).update(
published=Now()
)
self.assertEqual(num_updated, 1)
num_updated = Article.objects.filter(id=a1.id, published=None).update(
published=Now()
)
| ipsum,
written=timezone.now(),
)
a2 = Article.objects.create(
title="How to Time Travel",
text=lorem_ipsum,
written=timezone.now(),
)
num_updated = A | {
"filepath": "tests/db_functions/datetime/test_now.py",
"language": "python",
"file_size": 2104,
"cut_index": 563,
"middle_length": 229
} |
r
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
tempor incididunt ut labore et dolore magna aliqua."""
class CoalesceTests(TestCase):
def test_basic(self):
... | r, "Coalesce must take at least two expressions"
):
Author.objects.annotate(display_name=Coalesce("alias"))
def test_mixed_values(self):
a1 = Author.objects.create(name="John Smith", alias="smithj")
a2 = Author.obje | self.assertQuerySetEqual(
authors.order_by("name"), ["smithj", "Rhonda"], lambda a: a.display_name
)
def test_gt_two_expressions(self):
with self.assertRaisesMessage(
ValueErro | {
"filepath": "tests/db_functions/comparison/test_coalesce.py",
"language": "python",
"file_size": 3249,
"cut_index": 614,
"middle_length": 229
} |
from django.db import connection
from django.db.models.expressions import RawSQL
from django.db.models.functions import Coalesce, Greatest
from django.test import TestCase, skipIfDBFeature, skipUnlessDBFeature
from django.utils import timezone
from ..models import Article, Author, DecimalModel, Fan
class GreatestTes... | re("greatest_least_ignores_nulls")
def test_ignores_null(self):
now = timezone.now()
Article.objects.create(title="Testing with Django", written=now)
articles = Article.objects.annotate(
last_updated=Greatest("writte | before, published=now
)
articles = Article.objects.annotate(
last_updated=Greatest("written", "published")
)
self.assertEqual(articles.first().last_updated, now)
@skipUnlessDBFeatu | {
"filepath": "tests/db_functions/comparison/test_greatest.py",
"language": "python",
"file_size": 3887,
"cut_index": 614,
"middle_length": 229
} |
Unless
from django.db import connection
from django.db.models import Value
from django.db.models.functions import NullIf
from django.test import TestCase
from ..models import Author
class NullIfTests(TestCase):
@classmethod
def setUpTestData(cls):
Author.objects.create(name="John Smith", alias="smit... | nterprets_empty_strings_as_nulls
else None
),
),
],
)
def test_null_argument(self):
authors = Author.objects.annotate(
nullif=NullIf("name", Value(None | "nullif"
)
self.assertCountEqual(
authors,
[
("smithj",),
(
(
""
if connection.features.i | {
"filepath": "tests/db_functions/comparison/test_nullif.py",
"language": "python",
"file_size": 1718,
"cut_index": 537,
"middle_length": 229
} |
test import TestCase
from django.test.testcases import skipIfDBFeature, skipUnlessDBFeature
from django.utils import timezone
from ..models import Article, Author
@skipUnlessDBFeature("supports_json_field")
class JSONArrayTests(TestCase):
@classmethod
def setUpTestData(cls):
Author.objects.create(nam... | obj = Author.objects.annotate(
json_array=JSONArray(
Lower("name"),
F("alias"),
F("goes_by"),
Value(30000.15),
F("age") * 2,
)
).first()
| sic(self):
obj = Author.objects.annotate(
json_array=JSONArray(Value("name"), F("name"))
).first()
self.assertEqual(obj.json_array, ["name", "Ivan Ivanov"])
def test_expressions(self):
| {
"filepath": "tests/db_functions/json/test_json_array.py",
"language": "python",
"file_size": 5714,
"cut_index": 716,
"middle_length": 229
} |
import DecimalField
from django.db.models.functions import Abs
from django.test import TestCase
from django.test.utils import register_lookup
from ..models import DecimalModel, FloatModel, IntegerModel
class AbsTests(TestCase):
def test_null(self):
IntegerModel.objects.create()
obj = IntegerModel... | .n1_abs)
self.assertEqual(obj.n2, obj.n2_abs)
def test_float(self):
obj = FloatModel.objects.create(f1=-0.5, f2=12)
obj = FloatModel.objects.annotate(f1_abs=Abs("f1"), f2_abs=Abs("f2")).first()
self.assertIsInstance(obj | )
obj = DecimalModel.objects.annotate(n1_abs=Abs("n1"), n2_abs=Abs("n2")).first()
self.assertIsInstance(obj.n1_abs, Decimal)
self.assertIsInstance(obj.n2_abs, Decimal)
self.assertEqual(obj.n1, -obj | {
"filepath": "tests/db_functions/math/test_abs.py",
"language": "python",
"file_size": 2123,
"cut_index": 563,
"middle_length": 229
} |
o.db.models import DecimalField
from django.db.models.functions import ASin
from django.test import TestCase
from django.test.utils import register_lookup
from ..models import DecimalModel, FloatModel, IntegerModel
class ASinTests(TestCase):
def test_null(self):
IntegerModel.objects.create()
obj ... | cimal)
self.assertAlmostEqual(obj.n1_asin, Decimal(math.asin(obj.n1)))
self.assertAlmostEqual(obj.n2_asin, Decimal(math.asin(obj.n2)))
def test_float(self):
FloatModel.objects.create(f1=-0.5, f2=0.87)
obj = FloatModel.o | 2=Decimal("0.6"))
obj = DecimalModel.objects.annotate(
n1_asin=ASin("n1"), n2_asin=ASin("n2")
).first()
self.assertIsInstance(obj.n1_asin, Decimal)
self.assertIsInstance(obj.n2_asin, De | {
"filepath": "tests/db_functions/math/test_asin.py",
"language": "python",
"file_size": 2344,
"cut_index": 563,
"middle_length": 229
} |
o.db.models import DecimalField
from django.db.models.functions import ATan
from django.test import TestCase
from django.test.utils import register_lookup
from ..models import DecimalModel, FloatModel, IntegerModel
class ATanTests(TestCase):
def test_null(self):
IntegerModel.objects.create()
obj ... | Decimal)
self.assertAlmostEqual(obj.n1_atan, Decimal(math.atan(obj.n1)))
self.assertAlmostEqual(obj.n2_atan, Decimal(math.atan(obj.n2)))
def test_float(self):
FloatModel.objects.create(f1=-27.5, f2=0.33)
obj = FloatMode | n2=Decimal("0.6"))
obj = DecimalModel.objects.annotate(
n1_atan=ATan("n1"), n2_atan=ATan("n2")
).first()
self.assertIsInstance(obj.n1_atan, Decimal)
self.assertIsInstance(obj.n2_atan, | {
"filepath": "tests/db_functions/math/test_atan.py",
"language": "python",
"file_size": 2351,
"cut_index": 563,
"middle_length": 229
} |
o.db.models import DecimalField
from django.db.models.functions import Ceil
from django.test import TestCase
from django.test.utils import register_lookup
from ..models import DecimalModel, FloatModel, IntegerModel
class CeilTests(TestCase):
def test_null(self):
IntegerModel.objects.create()
obj ... | ecimal)
self.assertEqual(obj.n1_ceil, Decimal(math.ceil(obj.n1)))
self.assertEqual(obj.n2_ceil, Decimal(math.ceil(obj.n2)))
def test_float(self):
FloatModel.objects.create(f1=-12.5, f2=21.33)
obj = FloatModel.objects.an | n2=Decimal("0.6"))
obj = DecimalModel.objects.annotate(
n1_ceil=Ceil("n1"), n2_ceil=Ceil("n2")
).first()
self.assertIsInstance(obj.n1_ceil, Decimal)
self.assertIsInstance(obj.n2_ceil, D | {
"filepath": "tests/db_functions/math/test_ceil.py",
"language": "python",
"file_size": 2306,
"cut_index": 563,
"middle_length": 229
} |
o.db.models import DecimalField
from django.db.models.functions import Cot
from django.test import TestCase
from django.test.utils import register_lookup
from ..models import DecimalModel, FloatModel, IntegerModel
class CotTests(TestCase):
def test_null(self):
IntegerModel.objects.create()
obj = ... | tEqual(obj.n1_cot, Decimal(1 / math.tan(obj.n1)))
self.assertAlmostEqual(obj.n2_cot, Decimal(1 / math.tan(obj.n2)))
def test_float(self):
FloatModel.objects.create(f1=-27.5, f2=0.33)
obj = FloatModel.objects.annotate(f1_cot=Cot | ecimal("0.6"))
obj = DecimalModel.objects.annotate(n1_cot=Cot("n1"), n2_cot=Cot("n2")).first()
self.assertIsInstance(obj.n1_cot, Decimal)
self.assertIsInstance(obj.n2_cot, Decimal)
self.assertAlmos | {
"filepath": "tests/db_functions/math/test_cot.py",
"language": "python",
"file_size": 2292,
"cut_index": 563,
"middle_length": 229
} |
o.db.models import DecimalField
from django.db.models.functions import Degrees
from django.test import TestCase
from django.test.utils import register_lookup
from ..models import DecimalModel, FloatModel, IntegerModel
class DegreesTests(TestCase):
def test_null(self):
IntegerModel.objects.create()
... | assertIsInstance(obj.n2_degrees, Decimal)
self.assertAlmostEqual(obj.n1_degrees, Decimal(math.degrees(obj.n1)))
self.assertAlmostEqual(obj.n2_degrees, Decimal(math.degrees(obj.n2)))
def test_float(self):
FloatModel.objects.crea | cimal("-12.9"), n2=Decimal("0.6"))
obj = DecimalModel.objects.annotate(
n1_degrees=Degrees("n1"), n2_degrees=Degrees("n2")
).first()
self.assertIsInstance(obj.n1_degrees, Decimal)
self. | {
"filepath": "tests/db_functions/math/test_degrees.py",
"language": "python",
"file_size": 2476,
"cut_index": 563,
"middle_length": 229
} |
import Decimal
from django.db.models.functions import Log
from django.test import TestCase
from ..models import DecimalModel, FloatModel, IntegerModel
class LogTests(TestCase):
def test_null(self):
IntegerModel.objects.create(big=100)
obj = IntegerModel.objects.annotate(
null_log_sma... | otate(n_log=Log("n1", "n2")).first()
self.assertIsInstance(obj.n_log, Decimal)
self.assertAlmostEqual(obj.n_log, Decimal(math.log(obj.n2, obj.n1)))
def test_float(self):
FloatModel.objects.create(f1=2.0, f2=4.0)
obj = F | self.assertIsNone(obj.null_log_normal)
self.assertIsNone(obj.null_log_big)
def test_decimal(self):
DecimalModel.objects.create(n1=Decimal("12.9"), n2=Decimal("3.6"))
obj = DecimalModel.objects.ann | {
"filepath": "tests/db_functions/math/test_log.py",
"language": "python",
"file_size": 1858,
"cut_index": 537,
"middle_length": 229
} |
import Decimal
from django.db.models.functions import Mod
from django.test import TestCase
from ..models import DecimalModel, FloatModel, IntegerModel
class ModTests(TestCase):
def test_null(self):
IntegerModel.objects.create(big=100)
obj = IntegerModel.objects.annotate(
null_mod_sma... | self.assertAlmostEqual(obj.n_mod, Decimal(math.fmod(obj.n1, obj.n2)))
def test_float(self):
FloatModel.objects.create(f1=-25, f2=0.33)
obj = FloatModel.objects.annotate(f_mod=Mod("f1", "f2")).first()
self.assertIsInstance(o | def test_decimal(self):
DecimalModel.objects.create(n1=Decimal("-9.9"), n2=Decimal("4.6"))
obj = DecimalModel.objects.annotate(n_mod=Mod("n1", "n2")).first()
self.assertIsInstance(obj.n_mod, Decimal)
| {
"filepath": "tests/db_functions/math/test_mod.py",
"language": "python",
"file_size": 1767,
"cut_index": 537,
"middle_length": 229
} |
els import CharField
from django.db.models.functions import SHA512
from django.test import TestCase
from django.test.utils import register_lookup
from ..models import Author
class SHA512Tests(TestCase):
@classmethod
def setUpTestData(cls):
Author.objects.bulk_create(
[
Aut... | k")
)
self.assertSequenceEqual(
authors,
[
"ed014a19bb67a85f9c8b1d81e04a0e7101725be8627d79d02ca4f3bd803f33cf"
"3b8fed53e80d2a12c0d0e426824d99d110f0919298a5055efff040a3fc091518",
| )
def test_basic(self):
authors = (
Author.objects.annotate(
sha512_alias=SHA512("alias"),
)
.values_list("sha512_alias", flat=True)
.order_by("p | {
"filepath": "tests/db_functions/text/test_sha512.py",
"language": "python",
"file_size": 2372,
"cut_index": 563,
"middle_length": 229
} |
o.db.models import DecimalField
from django.db.models.functions import Floor
from django.test import TestCase
from django.test.utils import register_lookup
from ..models import DecimalModel, FloatModel, IntegerModel
class FloorTests(TestCase):
def test_null(self):
IntegerModel.objects.create()
ob... | .n2_floor, Decimal)
self.assertEqual(obj.n1_floor, Decimal(math.floor(obj.n1)))
self.assertEqual(obj.n2_floor, Decimal(math.floor(obj.n2)))
def test_float(self):
FloatModel.objects.create(f1=-27.5, f2=0.33)
obj = FloatM | .9"), n2=Decimal("0.6"))
obj = DecimalModel.objects.annotate(
n1_floor=Floor("n1"), n2_floor=Floor("n2")
).first()
self.assertIsInstance(obj.n1_floor, Decimal)
self.assertIsInstance(obj | {
"filepath": "tests/db_functions/math/test_floor.py",
"language": "python",
"file_size": 2344,
"cut_index": 563,
"middle_length": 229
} |
db.models import CharField
from django.db.models.functions import LTrim, RTrim, Trim
from django.test import TestCase
from django.test.utils import register_lookup
from ..models import Author
class TrimTests(TestCase):
def test_trim(self):
Author.objects.create(name=" John ", alias="j")
Author.o... | rim, a.trim),
)
def test_trim_transform(self):
Author.objects.create(name=" John ")
Author.objects.create(name="Rhonda")
tests = (
(LTrim, "John "),
(RTrim, " John"),
(Trim, "John") | self.assertQuerySetEqual(
authors.order_by("alias"),
[
("John ", " John", "John"),
("Rhonda", "Rhonda", "Rhonda"),
],
lambda a: (a.ltrim, a.rt | {
"filepath": "tests/db_functions/text/test_trim.py",
"language": "python",
"file_size": 1416,
"cut_index": 524,
"middle_length": 229
} |
from django.test.utils import CaptureQueriesContext
from ..models import Author, DTModel, Fan, FloatModel
class CastTests(TestCase):
@classmethod
def setUpTestData(self):
Author.objects.create(name="Bob", age=1, alias="1")
def test_cast_from_value(self):
numbers = Author.objects.annotate... | numbers = Author.objects.annotate(cast_string=Cast("age", models.CharField()))
self.assertEqual(numbers.get().cast_string, "1")
# Silence "Truncated incorrect CHAR(1) value: 'Bob'".
@ignore_warnings(module="django.db.backends.mysql.bas | = Author.objects.annotate(
cast_string=Cast("age", models.CharField(max_length=255)),
)
self.assertEqual(numbers.get().cast_string, "1")
def test_cast_to_char_field_without_max_length(self):
| {
"filepath": "tests/db_functions/comparison/test_cast.py",
"language": "python",
"file_size": 7604,
"cut_index": 716,
"middle_length": 229
} |
from django.db import connection
from django.db.models.expressions import RawSQL
from django.db.models.functions import Coalesce, Least
from django.test import TestCase, skipIfDBFeature, skipUnlessDBFeature
from django.utils import timezone
from ..models import Article, Author, DecimalModel, Fan
class LeastTests(Tes... | _nulls")
def test_ignores_null(self):
now = timezone.now()
Article.objects.create(title="Testing with Django", written=now)
articles = Article.objects.annotate(
first_updated=Least("written", "published"),
)
| , published=now
)
articles = Article.objects.annotate(first_updated=Least("written", "published"))
self.assertEqual(articles.first().first_updated, before)
@skipUnlessDBFeature("greatest_least_ignores | {
"filepath": "tests/db_functions/comparison/test_least.py",
"language": "python",
"file_size": 3810,
"cut_index": 614,
"middle_length": 229
} |
ctions import Lag, Lead, NthValue, Ntile
from django.test import SimpleTestCase
class ValidationTests(SimpleTestCase):
def test_nth_negative_nth_value(self):
msg = "NthValue requires a positive integer as for nth"
with self.assertRaisesMessage(ValueError, msg):
NthValue(expression="sal... | def test_lead_negative_offset(self):
msg = "Lead requires a positive integer for the offset"
with self.assertRaisesMessage(ValueError, msg):
Lead(expression="salary", offset=-1)
def test_null_source_lead(self):
| ue(expression=None)
def test_lag_negative_offset(self):
msg = "Lag requires a positive integer for the offset"
with self.assertRaisesMessage(ValueError, msg):
Lag(expression="salary", offset=-1)
| {
"filepath": "tests/db_functions/window/test_validation.py",
"language": "python",
"file_size": 1536,
"cut_index": 537,
"middle_length": 229
} |
import Decimal
from django.db.models.functions import ATan2
from django.test import TestCase
from ..models import DecimalModel, FloatModel, IntegerModel
class ATan2Tests(TestCase):
def test_null(self):
IntegerModel.objects.create(big=100)
obj = IntegerModel.objects.annotate(
null_ata... | ts.annotate(n_atan2=ATan2("n1", "n2")).first()
self.assertIsInstance(obj.n_atan2, Decimal)
self.assertAlmostEqual(obj.n_atan2, Decimal(math.atan2(obj.n1, obj.n2)))
def test_float(self):
FloatModel.objects.create(f1=-25, f2=0.33 | n)
self.assertIsNone(obj.null_atan2_nb)
self.assertIsNone(obj.null_atan2_bn)
def test_decimal(self):
DecimalModel.objects.create(n1=Decimal("-9.9"), n2=Decimal("4.6"))
obj = DecimalModel.objec | {
"filepath": "tests/db_functions/math/test_atan2.py",
"language": "python",
"file_size": 1730,
"cut_index": 537,
"middle_length": 229
} |
o.db.models import DecimalField
from django.db.models.functions import Cos
from django.test import TestCase
from django.test.utils import register_lookup
from ..models import DecimalModel, FloatModel, IntegerModel
class CosTests(TestCase):
def test_null(self):
IntegerModel.objects.create()
obj = ... | tEqual(obj.n1_cos, Decimal(math.cos(obj.n1)))
self.assertAlmostEqual(obj.n2_cos, Decimal(math.cos(obj.n2)))
def test_float(self):
FloatModel.objects.create(f1=-27.5, f2=0.33)
obj = FloatModel.objects.annotate(f1_cos=Cos("f1"), | ecimal("0.6"))
obj = DecimalModel.objects.annotate(n1_cos=Cos("n1"), n2_cos=Cos("n2")).first()
self.assertIsInstance(obj.n1_cos, Decimal)
self.assertIsInstance(obj.n2_cos, Decimal)
self.assertAlmos | {
"filepath": "tests/db_functions/math/test_cos.py",
"language": "python",
"file_size": 2270,
"cut_index": 563,
"middle_length": 229
} |
o.db.models import DecimalField
from django.db.models.functions import Ln
from django.test import TestCase
from django.test.utils import register_lookup
from ..models import DecimalModel, FloatModel, IntegerModel
class LnTests(TestCase):
def test_null(self):
IntegerModel.objects.create()
obj = In... | 1_ln, Decimal(math.log(obj.n1)))
self.assertAlmostEqual(obj.n2_ln, Decimal(math.log(obj.n2)))
def test_float(self):
FloatModel.objects.create(f1=27.5, f2=0.33)
obj = FloatModel.objects.annotate(f1_ln=Ln("f1"), f2_ln=Ln("f2")).f | ("0.6"))
obj = DecimalModel.objects.annotate(n1_ln=Ln("n1"), n2_ln=Ln("n2")).first()
self.assertIsInstance(obj.n1_ln, Decimal)
self.assertIsInstance(obj.n2_ln, Decimal)
self.assertAlmostEqual(obj.n | {
"filepath": "tests/db_functions/math/test_ln.py",
"language": "python",
"file_size": 2227,
"cut_index": 563,
"middle_length": 229
} |
o.db.models import DecimalField
from django.db.models.functions import Radians
from django.test import TestCase
from django.test.utils import register_lookup
from ..models import DecimalModel, FloatModel, IntegerModel
class RadiansTests(TestCase):
def test_null(self):
IntegerModel.objects.create()
... | assertIsInstance(obj.n2_radians, Decimal)
self.assertAlmostEqual(obj.n1_radians, Decimal(math.radians(obj.n1)))
self.assertAlmostEqual(obj.n2_radians, Decimal(math.radians(obj.n2)))
def test_float(self):
FloatModel.objects.crea | cimal("-12.9"), n2=Decimal("0.6"))
obj = DecimalModel.objects.annotate(
n1_radians=Radians("n1"), n2_radians=Radians("n2")
).first()
self.assertIsInstance(obj.n1_radians, Decimal)
self. | {
"filepath": "tests/db_functions/math/test_radians.py",
"language": "python",
"file_size": 2477,
"cut_index": 563,
"middle_length": 229
} |
odels.functions import StrIndex
from django.test import TestCase
from django.utils import timezone
from ..models import Article, Author
class StrIndexTests(TestCase):
def test_annotate_charfield(self):
Author.objects.create(name="George. R. R. Martin")
Author.objects.create(name="J. R. R. Tolkien... | written=timezone.now(),
)
Article.objects.create(
title="How to Tango",
text="Won't find anything here.",
written=timezone.now(),
)
articles = Article.objects.annotate(title_pos=StrIndex(" | .order_by("name"), [9, 4, 0], lambda a: a.fullstop
)
def test_annotate_textfield(self):
Article.objects.create(
title="How to Django",
text="This is about How to Django.",
| {
"filepath": "tests/db_functions/text/test_strindex.py",
"language": "python",
"file_size": 2694,
"cut_index": 563,
"middle_length": 229
} |
els import F, Value
from django.db.models.functions import Collate
from django.test import TestCase
from ..models import Author
class CollateTests(TestCase):
@classmethod
def setUpTestData(cls):
cls.author1 = Author.objects.create(alias="a", name="Jones 1")
cls.author2 = Author.objects.create... | connection.features.test_collations.get("cs")
if not collation:
self.skipTest("This backend does not support case-sensitive collations.")
qs = Author.objects.order_by(Collate("alias", collation))
self.assertSequenceEqual | ackend does not support case-insensitive collations.")
qs = Author.objects.filter(alias=Collate(Value("a"), collation))
self.assertEqual(qs.count(), 2)
def test_collate_order_by_cs(self):
collation = | {
"filepath": "tests/db_functions/comparison/test_collate.py",
"language": "python",
"file_size": 2084,
"cut_index": 563,
"middle_length": 229
} |
o.db.models import DecimalField
from django.db.models.functions import ACos
from django.test import TestCase
from django.test.utils import register_lookup
from ..models import DecimalModel, FloatModel, IntegerModel
class ACosTests(TestCase):
def test_null(self):
IntegerModel.objects.create()
obj ... | ecimal)
self.assertAlmostEqual(obj.n1_acos, Decimal(math.acos(obj.n1)))
self.assertAlmostEqual(obj.n2_acos, Decimal(math.acos(obj.n2)))
def test_float(self):
FloatModel.objects.create(f1=-0.5, f2=0.33)
obj = FloatModel. | n2=Decimal("0.6"))
obj = DecimalModel.objects.annotate(
n1_acos=ACos("n1"), n2_acos=ACos("n2")
).first()
self.assertIsInstance(obj.n1_acos, Decimal)
self.assertIsInstance(obj.n2_acos, D | {
"filepath": "tests/db_functions/math/test_acos.py",
"language": "python",
"file_size": 2346,
"cut_index": 563,
"middle_length": 229
} |
o.db.models import DecimalField
from django.db.models.functions import Exp
from django.test import TestCase
from django.test.utils import register_lookup
from ..models import DecimalModel, FloatModel, IntegerModel
class ExpTests(TestCase):
def test_null(self):
IntegerModel.objects.create()
obj = ... | tEqual(obj.n1_exp, Decimal(math.exp(obj.n1)))
self.assertAlmostEqual(obj.n2_exp, Decimal(math.exp(obj.n2)))
def test_float(self):
FloatModel.objects.create(f1=-27.5, f2=0.33)
obj = FloatModel.objects.annotate(f1_exp=Exp("f1"), | ecimal("0.6"))
obj = DecimalModel.objects.annotate(n1_exp=Exp("n1"), n2_exp=Exp("n2")).first()
self.assertIsInstance(obj.n1_exp, Decimal)
self.assertIsInstance(obj.n2_exp, Decimal)
self.assertAlmos | {
"filepath": "tests/db_functions/math/test_exp.py",
"language": "python",
"file_size": 2268,
"cut_index": 563,
"middle_length": 229
} |
al
from django.db.models.functions import Power
from django.test import TestCase
from ..models import DecimalModel, FloatModel, IntegerModel
class PowerTests(TestCase):
def test_null(self):
IntegerModel.objects.create(big=100)
obj = IntegerModel.objects.annotate(
null_power_small=Pow... | bjects.annotate(n_power=Power("n1", "n2")).first()
self.assertIsInstance(obj.n_power, Decimal)
self.assertAlmostEqual(obj.n_power, Decimal(obj.n1**obj.n2))
def test_float(self):
FloatModel.objects.create(f1=2.3, f2=1.1)
| )
self.assertIsNone(obj.null_power_normal)
self.assertIsNone(obj.null_power_big)
def test_decimal(self):
DecimalModel.objects.create(n1=Decimal("1.0"), n2=Decimal("-0.6"))
obj = DecimalModel.o | {
"filepath": "tests/db_functions/math/test_power.py",
"language": "python",
"file_size": 1870,
"cut_index": 537,
"middle_length": 229
} |
end_datetime=end_datetime,
start_date=start_datetime.date() if start_datetime else None,
end_date=end_datetime.date() if end_datetime else None,
start_time=start_datetime.time() if start_datetime else None,
end_time=end_datetime.time() if end_datetime else None,
... | = datetime.datetime(2016, 6, 15, 14, 10)
if settings.USE_TZ:
start_datetime = timezone.make_aware(start_datetime)
end_datetime = timezone.make_aware(end_datetime)
self.create_model(start_datetime, end_datetime)
| _exact_lookup(self):
"""
Extract year uses a BETWEEN filter to compare the year to allow indexes
to be used.
"""
start_datetime = datetime.datetime(2015, 6, 15, 14, 10)
end_datetime | {
"filepath": "tests/db_functions/datetime/test_extract_trunc.py",
"language": "python",
"file_size": 80924,
"cut_index": 3790,
"middle_length": 229
} |
import forms
from django.contrib import admin
from .models import Article, ArticleProxy, Site
class ArticleAdminForm(forms.ModelForm):
nolabel_form_field = forms.BooleanField(required=False)
class Meta:
model = Article
fields = ["title"]
@property
def changed_data(self):
dat... | "admin")
site.register(Article)
site.register(ArticleProxy)
site.register(Site, SiteAdmin)
class CustomAdminSite(admin.AdminSite):
def get_log_entries(self, request):
from django.contrib.contenttypes.models import ContentType
log_ent | return data
class ArticleInline(admin.TabularInline):
model = Article
fields = ["title"]
form = ArticleAdminForm
class SiteAdmin(admin.ModelAdmin):
inlines = [ArticleInline]
site = admin.AdminSite(name= | {
"filepath": "tests/admin_utils/admin.py",
"language": "python",
"file_size": 1304,
"cut_index": 524,
"middle_length": 229
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.