prefix
stringlengths
512
512
suffix
stringlengths
256
256
middle
stringlengths
14
229
meta
dict
rt DumbCategory, NamedCategory, ProxyCategory class ContainsTests(TestCase): @classmethod def setUpTestData(cls): cls.category = DumbCategory.objects.create() cls.proxy_category = ProxyCategory.objects.create() def test_unsaved_obj(self): msg = "QuerySet.contains() cannot be used ...
_list()." with self.assertRaisesMessage(TypeError, msg): DumbCategory.objects.values_list("pk").contains(self.category) with self.assertRaisesMessage(TypeError, msg): DumbCategory.objects.values("pk").contains(self.c
e a model instance." with self.assertRaisesMessage(TypeError, msg): DumbCategory.objects.contains(object()) def test_values(self): msg = "Cannot call QuerySet.contains() after .values() or .values
{ "filepath": "tests/queries/test_contains.py", "language": "python", "file_size": 2532, "cut_index": 563, "middle_length": 229 }
pUnlessDBFeature from django.utils.deprecation import RemovedInDjango70Warning from .models import Company, Employee, JSONFieldModel class ValuesExpressionsTests(TestCase): @classmethod def setUpTestData(cls): Company.objects.create( name="Example Inc.", num_employees=2300, ...
oyees=32, num_chairs=1, ceo=Employee.objects.create( firstname="Max", lastname="Mustermann", salary=30 ), ) def test_values_expression(self): self.assertSequenceEqual( Com
num_employees=3, num_chairs=4, ceo=Employee.objects.create(firstname="Frank", lastname="Meyer", salary=20), ) Company.objects.create( name="Test GmbH", num_empl
{ "filepath": "tests/expressions/test_queryset_values.py", "language": "python", "file_size": 4681, "cut_index": 614, "middle_length": 229 }
ontrib.flatpages.models import FlatPage from django.contrib.sites.models import Site from django.test import TestCase, modify_settings, override_settings from django.utils import translation @modify_settings(INSTALLED_APPS={"append": ["django.contrib.flatpages"]}) class FlatpageAdminFormTests(TestCase): def setUp...
self.assertTrue( FlatpageForm(data=dict(url="/new_flatpage/", **self.form_data)).is_valid() ) self.assertTrue( FlatpageForm( data=dict(url="/some.special~chars/", **self.form_data) ).is_v
"A test page", "content": "This is a test", "sites": [settings.SITE_ID], } def test_flatpage_admin_form_url_validation(self): "The flatpage admin form correctly validates urls"
{ "filepath": "tests/flatpages_tests/test_forms.py", "language": "python", "file_size": 5016, "cut_index": 614, "middle_length": 229 }
ase, modify_settings, override_settings from .settings import FLATPAGES_TEMPLATES class TestDataMixin: @classmethod def setUpTestData(cls): cls.site1 = Site.objects.get() cls.fp1 = FlatPage.objects.create( url="/flatpage/", title="A Flatpage", content="Isn'...
cls.fp3 = FlatPage.objects.create( url="/sekrit/", title="Sekrit Flatpage", content="Isn't it sekrit!", enable_comments=False, template_name="", registration_required=True, )
cation/flatpage/", title="A Nested Flatpage", content="Isn't it flat and deep!", enable_comments=False, template_name="", registration_required=False, )
{ "filepath": "tests/flatpages_tests/test_middleware.py", "language": "python", "file_size": 8011, "cut_index": 716, "middle_length": 229 }
contrib.flatpages.models import FlatPage from django.test import SimpleTestCase, override_settings from django.test.utils import override_script_prefix class FlatpageModelTests(SimpleTestCase): def setUp(self): self.page = FlatPage(title="Café!", url="/café/") def test_get_absolute_url_urlencodes(sel...
_url_include(self): self.assertEqual(self.page.get_absolute_url(), "/flatpage_root/caf%C3%A9/") @override_settings(ROOT_URLCONF="flatpages_tests.no_slash_urls") def test_get_absolute_url_include_no_slash(self): self.assertEqual(sel
Equal(self.page.get_absolute_url(), "/prefix/caf%C3%A9/") def test_str(self): self.assertEqual(str(self.page), "/café/ -- Café!") @override_settings(ROOT_URLCONF="flatpages_tests.urls") def test_get_absolute
{ "filepath": "tests/flatpages_tests/test_models.py", "language": "python", "file_size": 1306, "cut_index": 524, "middle_length": 229 }
apps import apps from django.contrib.sites.models import Site from django.test import TestCase from django.test.utils import modify_settings, override_settings @override_settings(ROOT_URLCONF="flatpages_tests.urls") @modify_settings( INSTALLED_APPS={ "append": ["django.contrib.sitemaps", "django.contrib.f...
urrent() current_site.flatpage_set.create(url="/foo/", title="foo") current_site.flatpage_set.create( url="/private-foo/", title="private foo", registration_required=True ) def test_flatpage_sitemap(self): r
he # makes tests interfere with each other, see #11505 Site.objects.clear_cache() @classmethod def setUpTestData(cls): Site = apps.get_model("sites.Site") current_site = Site.objects.get_c
{ "filepath": "tests/flatpages_tests/test_sitemaps.py", "language": "python", "file_size": 1356, "cut_index": 524, "middle_length": 229 }
TemplateSyntaxError from django.test import TestCase class FlatpageTemplateTagTests(TestCase): @classmethod def setUpTestData(cls): cls.site1 = Site.objects.get() cls.fp1 = FlatPage.objects.create( url="/flatpage/", title="A Flatpage", content="Isn't it flat...
FlatPage.objects.create( url="/sekrit/", title="Sekrit Flatpage", content="Isn't it sekrit!", enable_comments=False, template_name="", registration_required=True, ) cl
atpage/", title="A Nested Flatpage", content="Isn't it flat and deep!", enable_comments=False, template_name="", registration_required=False, ) cls.fp3 =
{ "filepath": "tests/flatpages_tests/test_templatetags.py", "language": "python", "file_size": 6794, "cut_index": 716, "middle_length": 229 }
ase, modify_settings, override_settings from .settings import FLATPAGES_TEMPLATES class TestDataMixin: @classmethod def setUpTestData(cls): cls.site1 = Site.objects.get() cls.fp1 = FlatPage.objects.create( url="/flatpage/", title="A Flatpage", content="Isn'...
cls.fp3 = FlatPage.objects.create( url="/sekrit/", title="Sekrit Flatpage", content="Isn't it sekrit!", enable_comments=False, template_name="", registration_required=True, )
cation/flatpage/", title="A Nested Flatpage", content="Isn't it flat and deep!", enable_comments=False, template_name="", registration_required=False, )
{ "filepath": "tests/flatpages_tests/test_views.py", "language": "python", "file_size": 6891, "cut_index": 716, "middle_length": 229 }
import call_command from django.template import Context, Template from django.test import SimpleTestCase, override_settings from .settings import TEST_SETTINGS class BaseStaticFilesMixin: """ Test case with a couple utility assertions. """ def assertFileContains(self, filepath, text): self.a...
*kwargs)).strip() def static_template_snippet(self, path, asvar=False): if asvar: return ( "{%% load static from static %%}{%% static '%s' as var %%}{{ var }}" % path ) return "{%
ertRaises(OSError): self._get_file(filepath) def render_template(self, template, **kwargs): if isinstance(template, str): template = Template(template) return template.render(Context(*
{ "filepath": "tests/staticfiles_tests/cases.py", "language": "python", "file_size": 4557, "cut_index": 614, "middle_length": 229 }
ort os.path from pathlib import Path TEST_ROOT = os.path.dirname(__file__) TEST_SETTINGS = { "MEDIA_URL": "media/", "STATIC_URL": "static/", "MEDIA_ROOT": os.path.join(TEST_ROOT, "project", "site_media", "media"), "STATIC_ROOT": os.path.join(TEST_ROOT, "project", "site_media", "static"), "STATICFI...
], "INSTALLED_APPS": [ "django.contrib.staticfiles", "staticfiles_tests", "staticfiles_tests.apps.test", "staticfiles_tests.apps.no_label", ], # In particular, AuthenticationMiddleware can't be used because
, "STATICFILES_FINDERS": [ "django.contrib.staticfiles.finders.FileSystemFinder", "django.contrib.staticfiles.finders.AppDirectoriesFinder", "django.contrib.staticfiles.finders.DefaultStorageFinder",
{ "filepath": "tests/staticfiles_tests/settings.py", "language": "python", "file_size": 1066, "cut_index": 515, "middle_length": 229 }
elta from django.conf import settings from django.contrib.staticfiles.storage import ManifestStaticFilesStorage from django.core.files import storage class DummyStorage(storage.Storage): """ A storage class that implements get_modified_time() but raises NotImplementedError for path(). """ def _s...
def exists(self, name): return os.path.exists(self._path(name)) def listdir(self, path): path = self._path(path) directories, files = [], [] with os.scandir(path) as entries: for entry in entries:
time(1970, 1, 1, tzinfo=UTC) class PathNotImplementedStorage(storage.Storage): def _save(self, name, content): return "dummy" def _path(self, name): return os.path.join(settings.STATIC_ROOT, name)
{ "filepath": "tests/staticfiles_tests/storage.py", "language": "python", "file_size": 2661, "cut_index": 563, "middle_length": 229 }
eck_storages from django.contrib.staticfiles.finders import BaseFinder, get_finder from django.core.checks import Error, Warning from django.test import SimpleTestCase, override_settings from .cases import CollectionTestCase from .settings import TEST_ROOT class FindersCheckTests(CollectionTestCase): run_collect...
errors.""" error1 = Error("1") error2 = Error("2") error3 = Error("3") def get_finders(): class Finder1(BaseFinder): def check(self, **kwargs): return [error1] cl
finder is " "configured correctly." ) with self.assertRaisesMessage(NotImplementedError, msg): finder.check() def test_check_finders(self): """check_finders() concatenates all
{ "filepath": "tests/staticfiles_tests/test_checks.py", "language": "python", "file_size": 5631, "cut_index": 716, "middle_length": 229 }
om django.core.exceptions import ImproperlyConfigured from django.test import SimpleTestCase, override_settings from .cases import StaticFilesTestCase from .settings import TEST_ROOT class TestFinders: """ Base finder test mixin. On Windows, sometimes the case of the path we ask the finders for and the ...
os.path.normcase(f) for f in found] dst = [os.path.normcase(d) for d in dst] self.assertEqual(found, dst) class TestFileSystemFinder(TestFinders, StaticFilesTestCase): """ Test FileSystemFinder. """ def setUp(self):
self.finder.find(src) self.assertEqual(os.path.normcase(found), os.path.normcase(dst)) def test_find_all(self): src, dst = self.find_all found = self.finder.find(src, find_all=True) found = [
{ "filepath": "tests/staticfiles_tests/test_finders.py", "language": "python", "file_size": 4362, "cut_index": 614, "middle_length": 229 }
urljoin from django.conf import STATICFILES_STORAGE_ALIAS from django.contrib.staticfiles import storage from django.forms import Media from django.templatetags.static import static from django.test import SimpleTestCase, override_settings class StaticTestStorage(storage.StaticFilesStorage): def url(self, name):...
olute_url(self): m = Media( css={"all": ("path/to/css1", "/path/to/css2")}, js=( "/path/to/js1", "http://media.other.com/path/to/js2", "https://secure.other.com/path/to/js3",
"BACKEND": "staticfiles_tests.test_forms.StaticTestStorage", "OPTIONS": {"location": "http://media.example.com/static/"}, } }, ) class StaticFilesFormsMediaTestCase(SimpleTestCase): def test_abs
{ "filepath": "tests/staticfiles_tests/test_forms.py", "language": "python", "file_size": 1629, "cut_index": 537, "middle_length": 229 }
cfiles.handlers import ASGIStaticFilesHandler from django.core.handlers.asgi import ASGIHandler from django.test import AsyncRequestFactory from .cases import StaticFilesTestCase class MockApplication: """ASGI application that returns a string indicating that it was called.""" async def __call__(self, scope...
) self.assertEqual(response.status_code, 200) async def test_get_async_response_not_found(self): request = self.async_request_factory.get("/static/test/not-found.txt") handler = ASGIStaticFilesHandler(ASGIHandler()) res
esponse(self): request = self.async_request_factory.get("/static/test/file.txt") handler = ASGIStaticFilesHandler(ASGIHandler()) response = await handler.get_response_async(request) response.close(
{ "filepath": "tests/staticfiles_tests/test_handlers.py", "language": "python", "file_size": 1621, "cut_index": 537, "middle_length": 229 }
ercising django.contrib.staticfiles.testing.StaticLiveServerTestCase instead of django.test.LiveServerTestCase. """ import os from urllib.request import urlopen from django.contrib.staticfiles.testing import StaticLiveServerTestCase from django.core.exceptions import ImproperlyConfigured from django.test import modif...
cls.enterClassContext(override_settings(**TEST_SETTINGS)) super().setUpClass() class StaticLiveServerChecks(LiveServerBase): @classmethod def setUpClass(cls): # If contrib.staticfiles isn't configured properly, the exception
t", "site_media", "media"), "STATIC_ROOT": os.path.join(TEST_ROOT, "project", "site_media", "static"), } class LiveServerBase(StaticLiveServerTestCase): available_apps = [] @classmethod def setUpClass(cls):
{ "filepath": "tests/staticfiles_tests/test_liveserver.py", "language": "python", "file_size": 2653, "cut_index": 563, "middle_length": 229 }
e, TestDefaults from .settings import TEST_ROOT, TEST_SETTINGS from .storage import DummyStorage class TestNoFilesCreated: def test_no_files_created(self): """ Make sure no files were create in the destination directory. """ self.assertEqual(os.listdir(settings.STATIC_ROOT), []) ...
def test_404_response(self): command = runserver.Command() handler = command.get_handler(use_static_handler=True, insecure_serving=True) missing_static_file = os.path.join(settings.STATIC_URL, "unknown.css") req = Reques
server.Command() with mock.patch("django.middleware.common.CommonMiddleware") as mocked: command.get_handler(use_static_handler=True, insecure_serving=True) self.assertEqual(mocked.call_count, 1)
{ "filepath": "tests/staticfiles_tests/test_management.py", "language": "python", "file_size": 27195, "cut_index": 1331, "middle_length": 229 }
ticRenders("path/", "/static/path/") self.assertStaticRenders("path/?query", "/static/path/?query") self.assertPostCondition() def test_template_tag_simple_content(self): relpath = self.hashed_file_path("cached/styles.css") self.assertEqual(relpath, "cached/styles.5e0040571e1a.css")...
ored.0e15ac4a4fb4.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertIn(b"#foobar", content) self.assertIn(b"http:foobar", content) self.assertIn(b"ht
other.d41d8cd98f00.css", content) self.assertPostCondition() def test_path_ignored_completely(self): relpath = self.hashed_file_path("cached/css/ignored.css") self.assertEqual(relpath, "cached/css/ign
{ "filepath": "tests/staticfiles_tests/test_storage.py", "language": "python", "file_size": 40679, "cut_index": 2151, "middle_length": 229 }
m django.conf import STATICFILES_STORAGE_ALIAS from django.test import override_settings from .cases import StaticFilesTestCase class TestTemplateTag(StaticFilesTestCase): def test_template_tag(self): self.assertStaticRenders("does/not/exist.png", "/static/does/not/exist.png") self.assertStaticRe...
Storage.url() should return an encoded path and might be overridden to also include a querystring. {% static %} escapes the URL to avoid raw '&', for example. """ self.assertStaticRenders("a.html", "a.html?a=b&c=d")
gs( STORAGES={ STATICFILES_STORAGE_ALIAS: { "BACKEND": "staticfiles_tests.storage.QueryStringStorage" }, } ) def test_template_tag_escapes(self): """
{ "filepath": "tests/staticfiles_tests/test_templatetags.py", "language": "python", "file_size": 1076, "cut_index": 515, "middle_length": 229 }
django.contrib.sites.models import Site from django.test import Client, TestCase, modify_settings, override_settings from .settings import FLATPAGES_TEMPLATES @modify_settings(INSTALLED_APPS={"append": "django.contrib.flatpages"}) @override_settings( LOGIN_URL="/accounts/login/", MIDDLEWARE=[ "django...
URE_VIEW="django.views.csrf.csrf_failure", TEMPLATES=FLATPAGES_TEMPLATES, ) class FlatpageCSRFTests(TestCase): @classmethod def setUpTestData(cls): cls.site1 = Site.objects.get() cls.fp1 = FlatPage.objects.create( ur
re.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.contrib.flatpages.middleware.FlatpageFallbackMiddleware", ], ROOT_URLCONF="flatpages_tests.urls", CSRF_FAIL
{ "filepath": "tests/flatpages_tests/test_csrf.py", "language": "python", "file_size": 4736, "cut_index": 614, "middle_length": 229 }
Case from django.test.utils import isolate_apps from .models import ManyToMany class ManyToManyFieldTests(SimpleTestCase): def test_abstract_model_pending_operations(self): """ Many-to-many fields declared on abstract models should not add lazy relations to resolve relationship declared a...
pending_operations.items()), "Pending lookup added for a many-to-many field on an abstract model", ) @isolate_apps("model_fields", "model_fields.tests") def test_abstract_model_app_relative_foreign_key(self): class Abst
sing.FK", models.CASCADE) class Meta: abstract = True self.assertIs(AbstractManyToManyModel._meta.apps, apps) self.assertEqual( pending_ops_before, list(apps._
{ "filepath": "tests/model_fields/test_manytomanyfield.py", "language": "python", "file_size": 3762, "cut_index": 614, "middle_length": 229 }
from django.db import models from django.test import SimpleTestCase, TestCase from .models import Post class TextFieldTests(TestCase): def test_max_length_passed_to_formfield(self): """ TextField passes its max_length attribute to form fields created using their formfield() method. ...
widget, forms.Select) def test_to_python(self): """TextField.to_python() should return a string.""" f = models.TextField() self.assertEqual(f.to_python(1), "1") def test_lookup_integer_in_textfield(self): self.asse
length) def test_choices_generates_select_widget(self): """A TextField with choices uses a Select widget.""" f = models.TextField(choices=[("A", "A"), ("B", "B")]) self.assertIsInstance(f.formfield().
{ "filepath": "tests/model_fields/test_textfield.py", "language": "python", "file_size": 1606, "cut_index": 537, "middle_length": 229 }
field = models.Field(choices=choices) form_field = model_field.formfield(show_hidden_initial=True) self.assertTrue(form_field.show_hidden_initial) form_field = model_field.formfield(show_hidden_initial=False) self.assertFalse(form_field.show_hidden_initial) def test_field_repr(self...
assertEqual(repr(Nested.Field()), "<model_fields.tests.Nested.Field>") def test_field_name(self): """ A defined field name (name="fieldname") is used instead of the model model's attribute name (modelname). """
f = models.fields.CharField() self.assertEqual(repr(f), "<django.db.models.fields.CharField>") def test_field_repr_nested(self): """__repr__() uses __qualname__ for nested class support.""" self.
{ "filepath": "tests/model_fields/tests.py", "language": "python", "file_size": 18764, "cut_index": 1331, "middle_length": 229 }
ngo.test import TestCase from .models import PersonWithCustomMaxLengths, PersonWithDefaultMaxLengths class MaxLengthArgumentsTests(unittest.TestCase): def verify_max_length(self, model, field, length): self.assertEqual(model._meta.get_field(field).max_length, length) def test_default_max_lengths(sel...
self.verify_max_length(PersonWithCustomMaxLengths, "vcard", 250) self.verify_max_length(PersonWithCustomMaxLengths, "homepage", 250) self.verify_max_length(PersonWithCustomMaxLengths, "avatar", 250) class MaxLengthORMTests(TestCase):
hDefaultMaxLengths, "homepage", 200) self.verify_max_length(PersonWithDefaultMaxLengths, "avatar", 100) def test_custom_max_lengths(self): self.verify_max_length(PersonWithCustomMaxLengths, "email", 250)
{ "filepath": "tests/max_lengths/tests.py", "language": "python", "file_size": 1604, "cut_index": 537, "middle_length": 229 }
models import Permission from django.contrib.contenttypes.models import ContentType from django.core import management from django.test import TestCase, override_settings from .models import Article class SwappableModelTests(TestCase): # Limit memory usage when calling 'migrate'. available_apps = [ "...
e() ContentType.objects.filter(app_label="swappable_models").delete() # Re-run migrate. This will re-build the permissions and content types. management.call_command("migrate", interactive=False, verbosity=0) # Content typ
rated_data(self): "Permissions and content types are not created for a swapped model" # Delete all permissions and content_types Permission.objects.filter(content_type__app_label="swappable_models").delet
{ "filepath": "tests/swappable_models/tests.py", "language": "python", "file_size": 1895, "cut_index": 537, "middle_length": 229 }
ger(models.Model): name = models.CharField(max_length=50) secretary = models.ForeignKey( "Employee", models.CASCADE, null=True, related_name="managers" ) class Employee(models.Model): firstname = models.CharField(max_length=50) lastname = models.CharField(max_length=50) salary = models...
sitiveIntegerField() num_chairs = models.PositiveIntegerField() ceo = models.ForeignKey( Employee, models.CASCADE, related_name="company_ceo_set", ) point_of_contact = models.ForeignKey( Employee, mod
turn "%s %s" % (self.firstname, self.lastname) class RemoteEmployee(Employee): adjusted_salary = models.IntegerField() class Company(models.Model): name = models.CharField(max_length=100) num_employees = models.Po
{ "filepath": "tests/expressions/models.py", "language": "python", "file_size": 3324, "cut_index": 614, "middle_length": 229 }
from django.tasks import TaskContext, task @task() def noop_task(*args, **kwargs): return None @task def noop_task_from_bare_decorator(*args, **kwargs): return None @task() async def noop_task_async(*args, **kwargs): return None @task() def calculate_meaning_of_life(): return 42 @task() def f...
turn_value(): # Return something which isn't JSON serializable nor picklable. return lambda: True @task() def exit_task(): exit(1) @task() def hang(): """ Do nothing for 5 minutes """ time.sleep(300) @task() def sleep_for(
sk() def failing_task_keyboard_interrupt(): raise KeyboardInterrupt("This Task failed due to KeyboardInterrupt") @task() def complex_exception(): raise ValueError(ValueError("This task failed")) @task() def complex_re
{ "filepath": "tests/tasks/tasks.py", "language": "python", "file_size": 1277, "cut_index": 524, "middle_length": 229 }
ask, default_task_backend, task, task_backends from django.tasks.backends.base import BaseTaskBackend from django.tasks.exceptions import InvalidTask from django.test import SimpleTestCase, override_settings from . import tasks as test_tasks class CustomBackend(BaseTaskBackend): def __init__(self, alias, params)...
Backend(BaseTaskBackend): task_class = CustomTask supports_priority = True def enqueue(self, task, args, kwargs): pass @override_settings( TASKS={ "default": { "BACKEND": f"{CustomBackend.__module__}.{CustomBa
ger.info(f"{self.prefix}Task enqueued.") class CustomBackendNoEnqueue(BaseTaskBackend): pass @dataclass(frozen=True, slots=True, kw_only=True) class CustomTask(Task): foo: int = 3 bar: int = 300 class CustomTask
{ "filepath": "tests/tasks/test_custom_backend.py", "language": "python", "file_size": 4271, "cut_index": 614, "middle_length": 229 }
"default": { "BACKEND": "django.tasks.backends.immediate.ImmediateBackend", "QUEUES": [], } } ) class ImmediateBackendTestCase(SimpleTestCase): def test_using_correct_backend(self): self.assertEqual(default_task_backend, task_backends["default"]) self.assertIsI...
sultStatus.SUCCESSFUL) self.assertIs(result.is_finished, True) self.assertIsNotNone(result.started_at) self.assertIsNotNone(result.last_attempted_at) self.assertIsNotNone(result.finished_at)
ueue_task(self): for task in [test_tasks.noop_task, test_tasks.noop_task_async]: with self.subTest(task): result = task.enqueue(1, two=3) self.assertEqual(result.status, TaskRe
{ "filepath": "tests/tasks/test_immediate_backend.py", "language": "python", "file_size": 12136, "cut_index": 921, "middle_length": 229 }
tions import ( InvalidTask, InvalidTaskBackend, TaskResultDoesNotExist, TaskResultMismatch, ) from django.test import SimpleTestCase, override_settings from django.utils import timezone from django.utils.module_loading import import_string from . import tasks as test_tasks @override_settings( TAS...
default_task_backend.clear() def test_using_correct_backend(self): self.assertEqual(default_task_backend, task_backends["default"]) self.assertIsInstance(task_backends["default"], DummyBackend) def test_task_decorator(self):
D": "django.tasks.backends.immediate.ImmediateBackend", "QUEUES": [], }, "missing": {"BACKEND": "does.not.exist"}, }, USE_TZ=True, ) class TaskTestCase(SimpleTestCase): def setUp(self):
{ "filepath": "tests/tasks/test_tasks.py", "language": "python", "file_size": 12673, "cut_index": 921, "middle_length": 229 }
AULT_DB_ALIAS class TestRouter: """ Vaguely behave like primary/replica, but the databases aren't assumed to propagate changes. """ def db_for_read(self, model, instance=None, **hints): if instance: return instance._state.db or "other" return "other" def db_for_wr...
n. """ def db_for_read(self, model, **hints): "Point all read operations on auth models to 'default'" if model._meta.app_label == "auth": # We use default here to ensure we can tell the difference # between
"default", "other", ) def allow_migrate(self, db, app_label, **hints): return True class AuthRouter: """ Control all database operations on models in the contrib.auth applicatio
{ "filepath": "tests/multiple_database/routers.py", "language": "python", "file_size": 1864, "cut_index": 537, "middle_length": 229 }
http import HttpRequest, HttpResponse, StreamingHttpResponse from django.test import SimpleTestCase from django.test.client import conditional_content_removal class ConditionalContentTests(SimpleTestCase): def test_conditional_content_removal(self): """ Content is removed from regular and streamin...
, b"abc") # Strip content for some status codes. for status_code in (100, 150, 199, 204, 304): res = HttpResponse("abc", status=status_code) conditional_content_removal(req, res) self.assertEqual(res.con
"abc") conditional_content_removal(req, res) self.assertEqual(res.content, b"abc") res = StreamingHttpResponse(["abc"]) conditional_content_removal(req, res) self.assertEqual(b"".join(res)
{ "filepath": "tests/test_client/test_conditional_content_removal.py", "language": "python", "file_size": 1957, "cut_index": 537, "middle_length": 229 }
eric import RedirectView from . import views urlpatterns = [ path("upload_view/", views.upload_view, name="upload_view"), path("get_view/", views.get_view, name="get_view"), path("cbv_view/", views.CBView.as_view()), path("post_view/", views.post_view), path("post_then_get_view/", views.post_then_...
ew, ), path("redirect_view_308/", views.method_saving_308_redirect_view), path( "redirect_view_308_query_string/", views.method_saving_308_redirect_query_string_view, ), path( "redirect_to_different_hostname/",
path("redirect_view/", views.redirect_view), path("redirect_view_307/", views.method_saving_307_redirect_view), path( "redirect_view_307_query_string/", views.method_saving_307_redirect_query_string_vi
{ "filepath": "tests/test_client/urls.py", "language": "python", "file_size": 3569, "cut_index": 614, "middle_length": 229 }
item() with self.assertRaises(AttributeError): q.clear() def test_immutable_get_with_default(self): q = QueryDict() self.assertEqual(q.get("foo", "default"), "default") def test_immutable_basic_operations(self): q = QueryDict() self.assertEqual(q.getlist("fo...
y/value pair""" q = QueryDict("foo=bar") self.assertEqual(q["foo"], "bar") with self.assertRaises(KeyError): q.__getitem__("bar") with self.assertRaises(AttributeError): q.__setitem__("something", "b
tEqual(list(q.keys()), []) self.assertEqual(list(q.values()), []) self.assertEqual(len(q), 0) self.assertEqual(q.urlencode(), "") def test_single_key_value(self): """Test QueryDict with one ke
{ "filepath": "tests/httpwrappers/tests.py", "language": "python", "file_size": 41124, "cut_index": 2151, "middle_length": 229 }
) cls.a2 = Article.objects.create( headline="Article 2", pub_date=datetime(2005, 7, 27) ) cls.a3 = Article.objects.create( headline="Article 3", pub_date=datetime(2005, 7, 27) ) cls.a4 = Article.objects.create( headline="Article 4", pub_...
Article.objects.all(), [ "Article 4", "Article 2", "Article 3", "Article 1", ], attrgetter("headline"), ) # Getting a single i
Author.objects.create() def test_default_ordering(self): """ By default, Article.objects.all() orders by pub_date descending, then headline ascending. """ self.assertQuerySetEqual(
{ "filepath": "tests/ordering/tests.py", "language": "python", "file_size": 26003, "cut_index": 1331, "middle_length": 229 }
lds.mixins import FieldCacheMixin from django.test import SimpleTestCase from django.utils.functional import cached_property from .models import Foo class Example(FieldCacheMixin): @cached_property def cache_name(self): return "example" class FieldCacheMixinTests(SimpleTestCase): def setUp(self...
elf.field.get_cached_value(self.instance) def test_get_cached_value_default(self): default = object() result = self.field.get_cached_value(self.instance, default=default) self.assertIs(result, default) def test_get_cached_
().cache_name def test_cache_name(self): result = Example().cache_name self.assertEqual(result, "example") def test_get_cached_value_missing(self): with self.assertRaises(KeyError): s
{ "filepath": "tests/model_fields/test_mixins.py", "language": "python", "file_size": 1760, "cut_index": 537, "middle_length": 229 }
eld, FileField, FilePathField, FloatField, GenericIPAddressField, ImageField, IntegerField, IPAddressField, PositiveBigIntegerField, PositiveIntegerField, PositiveSmallIntegerField, SlugField, SmallIntegerField, TextField, TimeField, URLField, ) from django.te...
lue(lazy_func()), bytes) def test_BooleanField(self): lazy_func = lazy(lambda: True, bool) self.assertIsInstance(BooleanField().get_prep_value(lazy_func()), bool) def test_CharField(self): lazy_func = lazy(lambda: "", str)
tIsInstance( AutoField(primary_key=True).get_prep_value(lazy_func()), int ) def test_BinaryField(self): lazy_func = lazy(lambda: b"", bytes) self.assertIsInstance(BinaryField().get_prep_va
{ "filepath": "tests/model_fields/test_promises.py", "language": "python", "file_size": 5427, "cut_index": 716, "middle_length": 229 }
low different TestCase # subclasses to be used. backend = None # subclasses must specify def setUp(self): self.session = self.backend() # NB: be careful to delete any sessions created; stale sessions fill up # the /tmp (with some backends) and eventually overwhelm it after lots ...
lf): self.session["cat"] = "dog" self.assertIs(self.session.modified, True) self.assertEqual(self.session.pop("cat"), "dog") async def test_store_async(self): await self.session.aset("cat", "dog") self.assertIs(
ession.accessed, False) def test_get_empty(self): self.assertIsNone(self.session.get("cat")) async def test_get_empty_async(self): self.assertIsNone(await self.session.aget("cat")) def test_store(se
{ "filepath": "tests/sessions_tests/tests.py", "language": "python", "file_size": 54332, "cut_index": 2151, "middle_length": 229 }
z=None): if tz is None or tz.utcoffset(now) is None: return now else: # equals now.replace(tzinfo=utc) return now.replace(tzinfo=tz) + tz.utcoffset(now) @modify_settings(INSTALLED_APPS={"append": "django.contrib.humanize"}) class HumanizeTests(SimpleTestCase): d...
, normalize_result_func(result), msg="%s test failed, produced '%s', should've produced '%s'" % (method, rendered, result), ) def test_ordinal(self): test_list = (
Test(test_content): t = Template("{%% load humanize %%}{{ test_content|%s }}" % method) rendered = t.render(Context(locals())).strip() self.assertEqual( rendered
{ "filepath": "tests/humanize_tests/tests.py", "language": "python", "file_size": 21462, "cut_index": 1331, "middle_length": 229 }
DummyBackend from django.tasks.base import Task from django.tasks.exceptions import InvalidTask, TaskResultDoesNotExist from django.test import SimpleTestCase, TransactionTestCase, override_settings from . import tasks as test_tasks @override_settings( TASKS={ "default": { "BACKEND": "django....
"default") self.assertEqual(default_task_backend.options, {}) def test_enqueue_task(self): for task in [test_tasks.noop_task, test_tasks.noop_task_async]: with self.subTest(task): result = cast(Task, task).e
est_using_correct_backend(self): self.assertEqual(default_task_backend, task_backends["default"]) self.assertIsInstance(task_backends["default"], DummyBackend) self.assertEqual(default_task_backend.alias,
{ "filepath": "tests/tasks/test_dummy_backend.py", "language": "python", "file_size": 7659, "cut_index": 716, "middle_length": 229 }
ango.contrib.contenttypes.fields import GenericForeignKey, GenericRelation from django.contrib.contenttypes.models import ContentType from django.db import models class Review(models.Model): source = models.CharField(max_length=100) content_type = models.ForeignKey(ContentType, models.CASCADE) object_id =...
ordering = ("name",) def __str__(self): return self.name # This book manager doesn't do anything interesting; it just # exists to strip out the 'extra_arg' argument to certain # calls. This argument is used to establish that the BookM
(models.Manager): def get_by_natural_key(self, name): return self.get(name=name) class Person(models.Model): name = models.CharField(max_length=100, unique=True) objects = PersonManager() class Meta:
{ "filepath": "tests/multiple_database/models.py", "language": "python", "file_size": 2187, "cut_index": 563, "middle_length": 229 }
st): request.urlconf = "test_client.urls_middleware_urlconf" return await get_response(request) return middleware @override_settings( ROOT_URLCONF="test_client.urls", MAILERS={"default": {"BACKEND": "django.core.mail.backends.locmem.EmailBackend"}}, ) class ClientTest(TestCase): @clas...
response = self.client.get("/get_view/", data) # Check some response details self.assertContains(response, "This is a test") self.assertEqual(response.context["var"], "\xf2") self.assertEqual(response.templates[0].na
ive", password="password", is_active=False ) def test_get_view(self): "GET a view" # The data is ignored, but let's check it doesn't crash the system # anyway. data = {"var": "\xf2"}
{ "filepath": "tests/test_client/tests.py", "language": "python", "file_size": 57446, "cut_index": 2151, "middle_length": 229 }
should be a list or tuple of field names. This tells Django how to order ``QuerySet`` results. If a field name in ``ordering`` starts with a hyphen, that field will be ordered in descending order. Otherwise, it'll be ordered in ascending order. The special-case field name ``"?"`` specifies random order. The ordering ...
ls.SET_NULL, null=True) second_author = models.ForeignKey( Author, models.SET_NULL, null=True, related_name="+" ) headline = models.CharField(max_length=100) pub_date = models.DateTimeField() class Meta: ordering = (
Field(max_length=63, null=True, blank=True) editor = models.ForeignKey("self", models.CASCADE, null=True) class Meta: ordering = ("-pk",) class Article(models.Model): author = models.ForeignKey(Author, mode
{ "filepath": "tests/ordering/models.py", "language": "python", "file_size": 3222, "cut_index": 614, "middle_length": 229 }
Model, RelatedToUUIDModel, UUIDGrandchild, UUIDModel, ) class TestSaveLoad(TestCase): def test_uuid_instance(self): instance = UUIDModel.objects.create(field=uuid.uuid4()) loaded = UUIDModel.objects.get() self.assertEqual(loaded.field, instance.field) def test_str_instance...
uuid.UUID("550e8400e29b41d4a716446655440000")) def test_str_instance_bad_hyphens(self): UUIDModel.objects.create(field="550e84-00-e29b-41d4-a716-4-466-55440000") loaded = UUIDModel.objects.get() self.assertEqual(loaded.field,
0e29b41d4a716446655440000")) def test_str_instance_hyphens(self): UUIDModel.objects.create(field="550e8400-e29b-41d4-a716-446655440000") loaded = UUIDModel.objects.get() self.assertEqual(loaded.field,
{ "filepath": "tests/model_fields/test_uuid.py", "language": "python", "file_size": 12129, "cut_index": 921, "middle_length": 229 }
test_decimal_division_literal_value(self): """ Division with a literal Decimal value preserves precision. """ num = Number.objects.create(integer=2) obj = Number.objects.annotate( val=F("integer") / Value(Decimal("3.0"), output_field=DecimalField()) ).get(pk=n...
.gmbh], ) def test_annotate_values_count(self): companies = Company.objects.annotate(foo=RawSQL("%s", ["value"])) self.assertEqual(companies.count(), 3) @skipUnlessDBFeature("supports_boolean_expr_in_select_clause") de
foo=RawSQL("%s", ["value"]), ) .filter(foo="value") .order_by("name") ) self.assertSequenceEqual( companies, [self.example_inc, self.foobar_ltd, self
{ "filepath": "tests/expressions/tests.py", "language": "python", "file_size": 118037, "cut_index": 3790, "middle_length": 229 }
eration class TestOperation(Operation): def __init__(self): pass def deconstruct(self): return (self.__class__.__name__, [], {}) @property def reversible(self): return True def state_forwards(self, app_label, state): pass def database_forwards(self, app_labe...
f.__class__.__name__, [self.arg1, self.arg2], {}) class KwargsOperation(TestOperation): def __init__(self, kwarg1=None, kwarg2=None): self.kwarg1, self.kwarg2 = kwarg1, kwarg2 def deconstruct(self): kwargs = {} if self.kw
state): pass class CreateModel(TestOperation): pass class ArgsOperation(TestOperation): def __init__(self, arg1, arg2): self.arg1, self.arg2 = arg1, arg2 def deconstruct(self): return (sel
{ "filepath": "tests/custom_migration_operations/operations.py", "language": "python", "file_size": 2171, "cut_index": 563, "middle_length": 229 }
owed, HttpResponseNotFound, HttpResponseRedirect, ) from django.shortcuts import render from django.template import Context, Template from django.test import Client from django.utils.decorators import method_decorator from django.views.generic import TemplateView def get_view(request): "A simple view that...
TRACE requests should not have an entity; the view will return a 400 status response if it is present. """ if request.method.upper() != "TRACE": return HttpResponseNotAllowed("TRACE") elif request.body: return HttpResponseB
return HttpResponse(t.render(c)) async def async_get_view(request): return HttpResponse(b"GET content.") def trace_view(request): """ A simple view that expects a TRACE request and echoes its status line.
{ "filepath": "tests/test_client/views.py", "language": "python", "file_size": 12900, "cut_index": 921, "middle_length": 229 }
is custom Session model adds an extra column to store an account ID. In real-world applications, it gives you the option of querying the database for all active sessions for a particular account. """ from django.contrib.sessions.backends.db import SessionStore as DBStore from django.contrib.sessions.base_session impor...
umn inside the custom session model. """ @classmethod def get_model_class(cls): return CustomSession def create_model_instance(self, data): obj = super().create_model_instance(data) try: account_id
egerField(null=True, db_index=True) @classmethod def get_session_store_class(cls): return SessionStore class SessionStore(DBStore): """ A database session store, that handles updating the account ID col
{ "filepath": "tests/sessions_tests/models.py", "language": "python", "file_size": 1242, "cut_index": 518, "middle_length": 229 }
ertRaises(Book.DoesNotExist): Book.objects.using("default").get(title="Pro Django") try: Book.objects.using("other").get(title="Dive into Python") except Book.DoesNotExist: self.fail('"Dive into Python" should exist on other database') with self.assertRaises...
into Python (on default)" dive2.save(using="default") dive.refresh_from_db() self.assertEqual(dive.title, "Dive into Python") dive.refresh_from_db(using="default") self.assertEqual(dive.title, "Dive into Python (on
thon") def test_refresh(self): dive = Book(title="Dive into Python", published=datetime.date(2009, 5, 4)) dive.save(using="other") dive2 = Book.objects.using("other").get() dive2.title = "Dive
{ "filepath": "tests/multiple_database/tests.py", "language": "python", "file_size": 98424, "cut_index": 3790, "middle_length": 229 }
} ) def test_custom_encoder_decoder(self): value = {"uuid": uuid.UUID("{d85e2076-b67c-4ee7-8c3a-2bf5a2cc2475}")} obj = NullableJSONModel(value_custom=value) obj.clean_fields() obj.save() obj.refresh_from_db() self.assertEqual(obj.value_custom, v...
.JSONField() name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.JSONField") self.assertEqual(args, []) self.assertEqual(kwargs, {}) def test_deconstruct_custom_encoder_decoder(self):
th self.assertRaises((IntegrityError, DataError, OperationalError)): NullableJSONModel.objects.create(value_custom=value) class TestMethods(SimpleTestCase): def test_deconstruct(self): field = models
{ "filepath": "tests/model_fields/test_jsonfield.py", "language": "python", "file_size": 55482, "cut_index": 2151, "middle_length": 229 }
path from urllib.parse import quote from django.conf import settings from django.test import override_settings from .cases import StaticFilesTestCase, TestDefaults @override_settings(ROOT_URLCONF="staticfiles_tests.urls.default") class TestServeStatic(StaticFilesTestCase): """ Test static asset serving view...
eStatic): """ Test serving static files disabled when DEBUG is False. """ def test_disabled_serving(self): self.assertFileNotFound("test.txt") @override_settings(DEBUG=True) class TestServeStaticWithDefaultURL(TestDefaults, TestS
lf.assertContains(self._response(filepath), text) def assertFileNotFound(self, filepath): self.assertEqual(self._response(filepath).status_code, 404) @override_settings(DEBUG=False) class TestServeDisabled(TestServ
{ "filepath": "tests/staticfiles_tests/test_views.py", "language": "python", "file_size": 1341, "cut_index": 524, "middle_length": 229 }
runner import DiscoverRunner class CustomOptionsTestRunner(DiscoverRunner): def __init__( self, verbosity=1, interactive=True, failfast=True, option_a=None, option_b=None, option_c=None, **kwargs, ): super().__init__( verbosit...
nt("--option_a", "-a", default="1") parser.add_argument("--option_b", "-b", default="2") parser.add_argument("--option_c", "-c", default="3") def run_tests(self, test_labels, **kwargs): print("%s:%s:%s" % (self.option_a, self.o
dd_arguments(cls, parser): parser.add_argume
{ "filepath": "tests/test_runner/runner.py", "language": "python", "file_size": 862, "cut_index": 529, "middle_length": 52 }
s(patterns): original_patterns = DiscoverRunner.test_loader.testNamePatterns DiscoverRunner.test_loader.testNamePatterns = patterns try: yield finally: DiscoverRunner.test_loader.testNamePatterns = original_patterns # Isolate from the real environment. @mock.patch.dict(os.environ, {}, ...
parser) return parser def test_parallel_default(self, *mocked_objects): result = self.get_parser().parse_args([]) self.assertEqual(result.parallel, 0) def test_parallel_flag(self, *mocked_objects): result = self.ge
k.patch.object(multiprocessing, "get_start_method", return_value="fork") class DiscoverRunnerParallelArgumentTests(SimpleTestCase): def get_parser(self): parser = ArgumentParser() DiscoverRunner.add_arguments(
{ "filepath": "tests/test_runner/test_discover_runner.py", "language": "python", "file_size": 33218, "cut_index": 1331, "middle_length": 229 }
ler class ShufflerTests(SimpleTestCase): def test_hash_text(self): actual = Shuffler._hash_text("abcd") self.assertEqual(actual, "e2fc714c4727ee9395f324cd2e7f331f") def test_hash_text_hash_algorithm(self): class MyShuffler(Shuffler): hash_algorithm = "sha1" actual...
ertEqual(shuffler.seed, 200) self.assertEqual(shuffler.seed_source, "generated") def test_init_no_seed_argument(self): with mock.patch("random.randint", return_value=300): shuffler = Shuffler() self.assertEqual(shuf
l(shuffler.seed, 100) self.assertEqual(shuffler.seed_source, "given") def test_init_none_seed(self): with mock.patch("random.randint", return_value=200): shuffler = Shuffler(None) self.ass
{ "filepath": "tests/test_runner/test_shuffler.py", "language": "python", "file_size": 3783, "cut_index": 614, "middle_length": 229 }
.query import ModelIterable from django.utils.functional import cached_property class Author(models.Model): name = models.CharField(max_length=50, unique=True) first_book = models.ForeignKey( "Book", models.CASCADE, related_name="first_time_authors" ) favorite_authors = models.ManyToManyField(...
uthor = models.ForeignKey( Author, models.CASCADE, to_field="name", related_name="i_like" ) likes_author = models.ForeignKey( Author, models.CASCADE, to_field="name", related_name="likes_me" ) is_active = models.BooleanField
s AuthorWithAge(Author): author = models.OneToOneField(Author, models.CASCADE, parent_link=True) age = models.IntegerField() class AuthorWithAgeChild(AuthorWithAge): pass class FavoriteAuthors(models.Model): a
{ "filepath": "tests/prefetch_related/models.py", "language": "python", "file_size": 8965, "cut_index": 716, "middle_length": 229 }
tchRelated(TestCase): def test_prefetch_related_from_uuid_model(self): Pet.objects.create(name="Fifi").people.add( Person.objects.create(name="Ellen"), Person.objects.create(name="George"), ) with self.assertNumQueries(2): pet = Pet.objects.prefetch_relat...
ated("pets").get(name="Bella") with self.assertNumQueries(0): self.assertEqual(2, len(person.pets.all())) def test_prefetch_related_from_uuid_model_to_uuid_model(self): fleas = [Flea.objects.create() for i in range(3)]
bjects.create(name="Bella").pets.add( Pet.objects.create(name="Socks"), Pet.objects.create(name="Coffee"), ) with self.assertNumQueries(2): person = Person.objects.prefetch_rel
{ "filepath": "tests/prefetch_related/test_uuid.py", "language": "python", "file_size": 4965, "cut_index": 614, "middle_length": 229 }
te_session_auth_hash, ) from django.contrib.auth.models import AnonymousUser, User from django.http import HttpRequest from django.test import TestCase, override_settings class AsyncAuthTest(TestCase): @classmethod def setUpTestData(cls): cls.test_user = User.objects.create_user( "testuser...
def test_alogin(self): request = HttpRequest() request.session = await self.client.asession() await alogin(request, self.test_user) user = await aget_user(request) self.assertIsInstance(user, User) self.asser
, User) self.assertEqual(user.username, self.test_user.username) user.is_active = False await user.asave() self.assertIsNone(await aauthenticate(username="testuser", password="testpw")) async
{ "filepath": "tests/async/test_async_auth.py", "language": "python", "file_size": 4677, "cut_index": 614, "middle_length": 229 }
stData(cls): cls.s1 = SimpleModel.objects.create( field=1, created=datetime(2022, 1, 1, 0, 0, 0), ) cls.s2 = SimpleModel.objects.create( field=2, created=datetime(2022, 1, 1, 0, 0, 1), ) cls.s3 = SimpleModel.objects.create( ...
tion. Connection access is thread sensitive and cannot # be passed across sync/async boundaries. return getattr(connection_.features, feature_name) async def test_async_iteration(self): results = [] async for m in Simpl
) cls.r3 = RelatedModel.objects.create(simple=cls.s3) @staticmethod def _get_db_feature(connection_, feature_name): # Wrapper to avoid accessing connection attributes until inside # coroutine func
{ "filepath": "tests/async/test_async_queryset.py", "language": "python", "file_size": 10079, "cut_index": 921, "middle_length": 229 }
: raise ValueError("woops") except ValueError: return sys.exc_info() class ExceptionThatFailsUnpickling(Exception): """ After pickling, this class fails unpickling with an error about incorrect arguments passed to __init__(). """ def __init__(self, arg): super().__init...
when running tests in parallel using the --parallel option, though it doesn't hurt to run them not in parallel. """ def test_subtest(self): """ Passing subtests work. """ for i in range(2): with
needed behavior for test_pickle_errors_detection. return (self.__class__, ()) class ParallelTestRunnerTest(SimpleTestCase): """ End-to-end tests of the parallel test runner. These tests are only meaningful
{ "filepath": "tests/test_runner/test_parallel.py", "language": "python", "file_size": 11213, "cut_index": 921, "middle_length": 229 }
s.version from django import get_version from django.test import SimpleTestCase from django.utils.version import ( get_complete_version, get_git_changeset, get_version_tuple, ) class VersionTests(SimpleTestCase): def test_development(self): get_git_changeset.cache_clear() ver_tuple = (...
in a frozen environments", ) def test_development_no_file(self): get_git_changeset.cache_clear() version_file = django.utils.version.__file__ try: del django.utils.version.__file__ self.test_developm
tuple) self.assertRegex(ver_string, r"1\.4(\.dev[0-9]+)?") @skipUnless( hasattr(django.utils.version, "__file__"), "test_development() checks the same when __file__ is already missing, " "e.g.
{ "filepath": "tests/version/tests.py", "language": "python", "file_size": 2244, "cut_index": 563, "middle_length": 229 }
def setUpTestData(cls): cls.book1 = Book.objects.create(title="Poems") cls.book2 = Book.objects.create(title="Jane Eyre") cls.book3 = Book.objects.create(title="Wuthering Heights") cls.book4 = Book.objects.create(title="Sense and Sensibility") cls.author1 = Author.objects.create...
(cls.author3) cls.book4.authors.add(cls.author4) cls.reader1 = Reader.objects.create(name="Amy") cls.reader2 = Reader.objects.create(name="Belinda") cls.reader1.books_read.add(cls.book1, cls.book4) cls.reader2.book
.book1) cls.author4 = Author.objects.create(name="Jane", first_book=cls.book4) cls.book1.authors.add(cls.author1, cls.author2, cls.author3) cls.book2.authors.add(cls.author1) cls.book3.authors.add
{ "filepath": "tests/prefetch_related/test_prefetch_related_objects.py", "language": "python", "file_size": 9680, "cut_index": 921, "middle_length": 229 }
super().setUp() self.format_sql_calls = [] def new_format_sql(self, sql): # Use time() to introduce some uniqueness. formatted = "Formatted! %s at %s" % (sql.upper(), time()) self.format_sql_calls.append({sql: formatted}) return formatted def make_handler(self, ...
er.removeHandler, handler) return handler def do_log(self, msg, *logger_args, alias=DEFAULT_DB_ALIAS, extra=None): if extra is None: extra = {} if alias and "alias" not in extra: extra["alias"] = alias
atter(formatter) original_level = logger.getEffectiveLevel() logger.setLevel(logging.DEBUG) self.addCleanup(logger.setLevel, original_level) logger.addHandler(handler) self.addCleanup(logg
{ "filepath": "tests/test_runner/test_debug_sql.py", "language": "python", "file_size": 11849, "cut_index": 921, "middle_length": 229 }
ch_related("first_book") ] normal_books = [a.first_book for a in Author.objects.all()] self.assertEqual(books, normal_books) def test_fetch_mode_copied_fetching_one(self): author = ( Author.objects.fetch_mode(FETCH_PEERS) .prefetch_related("first_book") ...
s[0]._state.fetch_mode, FETCH_PEERS) self.assertEqual( authors[0].first_book._state.fetch_mode, FETCH_PEERS, ) def test_fetch_mode_raise(self): authors = list(Author.objects.fetch_mode(RAISE).prefetch_re
FETCH_PEERS, ) def test_fetch_mode_copied_fetching_many(self): authors = list( Author.objects.fetch_mode(FETCH_PEERS).prefetch_related("first_book") ) self.assertEqual(author
{ "filepath": "tests/prefetch_related/tests.py", "language": "python", "file_size": 90296, "cut_index": 3790, "middle_length": 229 }
jango.test import TestCase from .models import SimpleModel class AsyncModelOperationTest(TestCase): @classmethod def setUpTestData(cls): cls.s1 = SimpleModel.objects.create(field=0) async def test_asave(self): self.s1.field = 10 await self.s1.asave() refetched = await Sim...
20) async def test_arefresh_from_db_from_queryset(self): await SimpleModel.objects.filter(pk=self.s1.pk).aupdate(field=20) with self.assertRaises(SimpleModel.DoesNotExist): await self.s1.arefresh_from_db( f
self.assertEqual(count, 0) async def test_arefresh_from_db(self): await SimpleModel.objects.filter(pk=self.s1.pk).aupdate(field=20) await self.s1.arefresh_from_db() self.assertEqual(self.s1.field,
{ "filepath": "tests/async/test_async_model_methods.py", "language": "python", "file_size": 1226, "cut_index": 518, "middle_length": 229 }
subsuite.addTest(test) suite.addTest(subsuite) return suite def make_test_suite(self, suite=None, suite_class=None): class Tests1(unittest.TestCase): def test1(self): pass def test2(self): pass class Tests2(unittes...
t_cases.<locals>.Tests1.test1". # It suffices to check only the last two parts. names = [".".join(test.id().split(".")[-2:]) for test in tests] self.assertEqual(names, expected) def test_iter_test_cases_basic(self): sui
suite=suite, suite_class=suite_class, ) def assertTestNames(self, tests, expected): # Each test.id() has a form like the following: # "test_runner.tests.IterTestCasesTests.test_iter_tes
{ "filepath": "tests/test_runner/tests.py", "language": "python", "file_size": 38046, "cut_index": 2151, "middle_length": 229 }
DJANGO_VERSION_PICKLE_KEY, models from django.test import SimpleTestCase class ModelPickleTests(SimpleTestCase): def test_missing_django_version_unpickling(self): """ #21430 -- Verifies a warning is raised for models that are unpickled without a Django version """ class Mi...
with self.assertRaisesMessage(RuntimeWarning, msg): pickle.loads(pickle.dumps(p)) def test_unsupported_unpickle(self): """ #21430 -- Verifies a warning is raised for models that are unpickled with a differe
= reduce_list[-1] del data[DJANGO_VERSION_PICKLE_KEY] return reduce_list p = MissingDjangoVersion(title="FooBar") msg = "Pickled model instance's Django version is not specified."
{ "filepath": "tests/model_regress/test_pickle.py", "language": "python", "file_size": 2300, "cut_index": 563, "middle_length": 229 }
Case from .models import ( Band, DynOrderingBandAdmin, Song, SongInlineDefaultOrdering, SongInlineNewOrdering, ) class MockRequest: pass class MockSuperUser: def has_perm(self, perm, obj=None): return True def has_module_perms(self, module): return True request = ...
Band(name="Aerosmith", bio="", rank=3), Band(name="Radiohead", bio="", rank=1), Band(name="Van Halen", bio="", rank=2), ] ) def test_default_ordering(self): """ The defa
in ModelAdmin rather that ordering defined in the model's inner Meta class. """ request_factory = RequestFactory() @classmethod def setUpTestData(cls): Band.objects.bulk_create( [
{ "filepath": "tests/admin_ordering/tests.py", "language": "python", "file_size": 7244, "cut_index": 716, "middle_length": 229 }
ls import translation from django.utils.version import PY314, PY315 from .management.commands import dance from .utils import AssertFormatterFailureCaughtContext class OutputWrapperTests(SimpleTestCase): def test_unhandled_exceptions(self): cases = [ StringIO("Hello world"), TextI...
atch.object(sys, "unraisablehook", unraisablehook): del wrapper self.assertEqual(unraisable_exceptions, []) # A minimal set of apps to avoid system checks running on all apps. @override_settings( INSTALLED_APPS=[
unraisable_exceptions = [] def unraisablehook(unraisable): unraisable_exceptions.append(unraisable) sys.__unraisablehook__(unraisable) with mock.p
{ "filepath": "tests/user_commands/tests.py", "language": "python", "file_size": 24496, "cut_index": 1331, "middle_length": 229 }
ass Command(BaseCommand): help = "Dance around like a madman." args = "" requires_system_checks = "__all__" def add_arguments(self, parser): parser.add_argument("integer", nargs="?", type=int, default=0) parser.add_argument("-s", "--style", default="Rock'n'Roll") parser.add_argu...
rncode=3) if options["verbosity"] > 0: self.stdout.write("I don't feel like dancing %s." % options["style"]) self.stdout.write(",".join(options)) if options["integer"] > 0: self.stdout.write(
mple == "raise": raise CommandError(retu
{ "filepath": "tests/user_commands/management/commands/dance.py", "language": "python", "file_size": 971, "cut_index": 582, "middle_length": 52 }
m django.core.management.base import BaseCommand, CommandError class Command(BaseCommand): help = "Useless command." def add_arguments(self, parser): parser.add_argument( "args", metavar="app_label", nargs="*", help="Specify the app label(s) to works on...
# raise an error if some --parameter is flowing from options to args for app_label in app_labels: if app_label.startswith("--"): raise CommandError("Sorry, Dave, I can't let you do that.") self.stdout.w
tions["empty"]: self.stdout.write() self.stdout.write("Dave, I can't do that.") return if not app_labels: raise CommandError("I'm sorry Dave, I'm afraid I can't do that.")
{ "filepath": "tests/user_commands/management/commands/hal.py", "language": "python", "file_size": 1062, "cut_index": 515, "middle_length": 229 }
port BaseCommand class Command(BaseCommand): def add_arguments(self, parser): group = parser.add_mutually_exclusive_group(required=True) group.add_argument("--foo-id", type=int, nargs="?", default=None) group.add_argument("--foo-name", type=str, nargs="?", default=None) group.add_a...
group.add_argument("--flag_false", action="store_false") group.add_argument("--flag_true", action="store_true") def handle(self, *args, **options): for option, value in options.items(): if value is not None:
group.add_argument("--count", action="count")
{ "filepath": "tests/user_commands/management/commands/mutually_exclusive_required.py", "language": "python", "file_size": 910, "cut_index": 547, "middle_length": 52 }
ator from django.views.decorators.cache import cache_control, cache_page, never_cache class HttpRequestProxy: def __init__(self, request): self._request = request def __getattr__(self, attr): """Proxy to the underlying HttpRequest object.""" return getattr(self._request, attr) class...
Response() wrapped_view = cache_control()(async_view) self.assertIs(iscoroutinefunction(wrapped_view), True) def test_cache_control_decorator_http_request(self): class MyClass: @cache_control(a="b") def
ed_view = cache_control()(sync_view) self.assertIs(iscoroutinefunction(wrapped_view), False) def test_wrapped_async_function_is_coroutine_function(self): async def async_view(request): return Http
{ "filepath": "tests/decorators/test_cache.py", "language": "python", "file_size": 8381, "cut_index": 716, "middle_length": 229 }
.middleware.clickjacking import XFrameOptionsMiddleware from django.test import SimpleTestCase from django.views.decorators.clickjacking import ( xframe_options_deny, xframe_options_exempt, xframe_options_sameorigin, ) class XFrameOptionsDenyTests(SimpleTestCase): def test_wrapped_sync_function_is_not...
ssertIs(iscoroutinefunction(wrapped_view), True) def test_decorator_sets_x_frame_options_to_deny(self): @xframe_options_deny def a_view(request): return HttpResponse() response = a_view(HttpRequest()) self.
apped_view), False) def test_wrapped_async_function_is_coroutine_function(self): async def async_view(request): return HttpResponse() wrapped_view = xframe_options_deny(async_view) self.a
{ "filepath": "tests/decorators/test_clickjacking.py", "language": "python", "file_size": 4562, "cut_index": 614, "middle_length": 229 }
import iscoroutinefunction from django.http import HttpRequest, HttpResponse from django.test import SimpleTestCase from django.views.decorators.common import no_append_slash class NoAppendSlashTests(SimpleTestCase): def test_wrapped_sync_function_is_not_coroutine_function(self): def sync_view(request):...
append_slash_decorator(self): @no_append_slash def sync_view(request): return HttpResponse() self.assertIs(sync_view.should_append_slash, False) self.assertIsInstance(sync_view(HttpRequest()), HttpResponse)
routine_function(self): async def async_view(request): return HttpResponse() wrapped_view = no_append_slash(async_view) self.assertIs(iscoroutinefunction(wrapped_view), True) def test_no_
{ "filepath": "tests/decorators/test_common.py", "language": "python", "file_size": 1306, "cut_index": 524, "middle_length": 229 }
uest, HttpResponse from django.test import SimpleTestCase from django.utils.csp import CSP from django.views.decorators.csp import csp_override, csp_report_only_override basic_config = { "default-src": [CSP.SELF], } class CSPOverrideDecoratorTest(SimpleTestCase): def test_wrapped_sync_function_is_not_corouti...
utinefunction(wrapped_view), True) def test_decorator_requires_mapping(self): for config, decorator in product( [None, 0, False, [], [1, 2, 3], 42, {4, 5}], (csp_override, csp_report_only_override), ):
, False) def test_wrapped_async_function_is_coroutine_function(self): async def async_view(request): return HttpResponse() wrapped_view = csp_override({})(async_view) self.assertIs(iscoro
{ "filepath": "tests/decorators/test_csp.py", "language": "python", "file_size": 3426, "cut_index": 614, "middle_length": 229 }
( csrf_exempt, csrf_protect, ensure_csrf_cookie, requires_csrf_token, ) CSRF_TOKEN = "1bcdefghij2bcdefghij3bcdefghij4bcdefghij5bcdefghij6bcdefghijABCD" class CsrfTestMixin: def get_request(self, token=CSRF_TOKEN): request = HttpRequest() request.method = "POST" if token: ...
(wrapped_view), False) def test_wrapped_async_function_is_coroutine_function(self): async def async_view(request): return HttpResponse() wrapped_view = csrf_protect(async_view) self.assertIs(iscoroutinefunction(wra
ase): def test_wrapped_sync_function_is_not_coroutine_function(self): def sync_view(request): return HttpResponse() wrapped_view = csrf_protect(sync_view) self.assertIs(iscoroutinefunction
{ "filepath": "tests/decorators/test_csrf.py", "language": "python", "file_size": 6808, "cut_index": 716, "middle_length": 229 }
o.http import HttpRequest, HttpResponse, StreamingHttpResponse from django.test import SimpleTestCase from django.views.decorators.gzip import gzip_page class GzipPageTests(SimpleTestCase): # Gzip ignores content that is too short. content = "Content " * 100 def test_wrapped_sync_function_is_not_coroutin...
rapped_view), True) def test_gzip_page_decorator(self): @gzip_page def sync_view(request): return HttpResponse(content=self.content) request = HttpRequest() request.META["HTTP_ACCEPT_ENCODING"] = "gzip"
def test_wrapped_async_function_is_coroutine_function(self): async def async_view(request): return HttpResponse() wrapped_view = gzip_page(async_view) self.assertIs(iscoroutinefunction(w
{ "filepath": "tests/decorators/test_gzip.py", "language": "python", "file_size": 2837, "cut_index": 563, "middle_length": 229 }
import ( condition, conditional_page, require_http_methods, require_safe, ) class RequireHttpMethodsTest(SimpleTestCase): def test_wrapped_sync_function_is_not_coroutine_function(self): def sync_view(request): return HttpResponse() wrapped_view = require_http_methods([...
p_methods(["GET", "PUT"]) def my_view(request): return HttpResponse("OK") request = HttpRequest() request.method = "GET" self.assertIsInstance(my_view(request), HttpResponse) request.method = "PUT"
return HttpResponse() wrapped_view = require_http_methods(["GET"])(async_view) self.assertIs(iscoroutinefunction(wrapped_view), True) def test_require_http_methods_methods(self): @require_htt
{ "filepath": "tests/decorators/test_http.py", "language": "python", "file_size": 7526, "cut_index": 716, "middle_length": 229 }
o.http import HttpRequest, HttpResponse from django.test import SimpleTestCase from django.views.decorators.vary import vary_on_cookie, vary_on_headers class VaryOnHeadersTests(SimpleTestCase): def test_wrapped_sync_function_is_not_coroutine_function(self): def sync_view(request): return HttpR...
r(self): @vary_on_headers("Header", "Another-header") def sync_view(request): return HttpResponse() response = sync_view(HttpRequest()) self.assertEqual(response.get("Vary"), "Header, Another-header") async
async def async_view(request): return HttpResponse() wrapped_view = vary_on_headers()(async_view) self.assertIs(iscoroutinefunction(wrapped_view), True) def test_vary_on_headers_decorato
{ "filepath": "tests/decorators/test_vary.py", "language": "python", "file_size": 2404, "cut_index": 563, "middle_length": 229 }
vary_on_cookie, vary_on_headers def fully_decorated(request): """Expected __doc__""" return HttpResponse("<html><body>dummy</body></html>") fully_decorated.anything = "Expected __dict__" def compose(*functions): # compose(f, g)(*args, **kwargs) == f(g(*args, **kwargs)) functions = list(reversed(f...
rs.vary vary_on_headers("Accept-language"), vary_on_cookie, # django.views.decorators.cache cache_page(60 * 15), cache_control(private=True), never_cache, # django.contrib.auth.decorators # Apply user_passes_test twice to ch
ner full_decorator = compose( # django.views.decorators.http require_http_methods(["GET"]), require_GET, require_POST, require_safe, condition(lambda r: None, lambda r: None), # django.views.decorato
{ "filepath": "tests/decorators/tests.py", "language": "python", "file_size": 20717, "cut_index": 1331, "middle_length": 229 }
rted at # the top of the file. github_links = None class GitHubLinkTests(SimpleTestCase): @classmethod def setUpClass(cls): # The file implementing the code under test is in the docs folder and # is not part of the Django package. This means it cannot be imported # through standard mea...
is as a valid import. import github_links as _github_links global github_links github_links = _github_links def test_code_locator(self): locator = github_links.CodeLocator.from_code(""" from a import b, c from .d impor
resolve()) sys.path.insert(0, cls.ext_path) cls.addClassCleanup(sys.path.remove, cls.ext_path) cls.addClassCleanup(sys.modules.pop, "github_links", None) # Linters/IDEs may not be able to detect th
{ "filepath": "tests/sphinx/test_github_links.py", "language": "python", "file_size": 7176, "cut_index": 716, "middle_length": 229 }
for forcing insert and update queries (instead of Django's normal automatic behavior). """ from django.db import models class Counter(models.Model): name = models.CharField(max_length=10) value = models.IntegerField() class InheritedCounter(Counter): tag = models.CharField(max_length=10) class ProxyC...
mary_key=True) value = models.IntegerField() class OtherSubCounter(Counter): other_counter_ptr = models.OneToOneField( Counter, primary_key=True, parent_link=True, on_delete=models.CASCADE ) class DiamondSubSubCounter(SubCounter, Ot
tegerField(pri
{ "filepath": "tests/force_insert_update/models.py", "language": "python", "file_size": 817, "cut_index": 522, "middle_length": 14 }
dSubSubCounter, InheritedCounter, OtherSubCounter, ProxyCounter, SubCounter, SubSubCounter, WithCustomPK, ) class ForceTests(TestCase): def test_force_update(self): c = Counter.objects.create(name="one", value=1) # The normal case c.value = 2 c.save() ...
doesn't have a primary key in the first # place. c1 = Counter(name="two", value=2) msg = "Cannot force an update in save() with no primary key." with self.assertRaisesMessage(ValueError, msg): with transaction.a
e = 4 msg = "Cannot force both insert and updating in model saving." with self.assertRaisesMessage(ValueError, msg): c.save(force_insert=True, force_update=True) # Try to update something that
{ "filepath": "tests/force_insert_update/tests.py", "language": "python", "file_size": 7956, "cut_index": 716, "middle_length": 229 }
ForeignKey, GenericRelation from django.contrib.contenttypes.models import ContentType from django.db import models class OnlyFred(models.Manager): def get_queryset(self): return super().get_queryset().filter(name="fred") class OnlyBarney(models.Manager): def get_queryset(self): return super...
value = models.IntegerField() class Meta: abstract = True # Custom manager restricted = Value42() # No custom manager on this class to make sure the default case doesn't break. class AbstractBase3(models.Model): comment = m
name = models.CharField(max_length=50) class Meta: abstract = True # Custom managers manager1 = OnlyFred() manager2 = OnlyBarney() objects = models.Manager() class AbstractBase2(models.Model):
{ "filepath": "tests/managers_regress/models.py", "language": "python", "file_size": 3127, "cut_index": 614, "middle_length": 229 }
essionTests(TestCase): def test_managers(self): a1 = Child1.objects.create(name="fred", data="a1") a2 = Child1.objects.create(name="barney", data="a2") b1 = Child2.objects.create(name="fred", data="b1", value=1) b2 = Child2.objects.create(name="barney", data="b2", value=42) c...
ame="fred", data="f1", value=42) f2 = Child6.objects.create(name="barney", data="f2", value=42) fred2 = Child7.objects.create(name="fred") barney = Child7.objects.create(name="barney") self.assertSequenceEqual(Child1.manage
="d1") d2 = Child4.objects.create(name="barney", data="d2") fred1 = Child5.objects.create(name="fred", comment="yes") Child5.objects.create(name="barney", comment="no") f1 = Child6.objects.create(n
{ "filepath": "tests/managers_regress/tests.py", "language": "python", "file_size": 10947, "cut_index": 921, "middle_length": 229 }
contenttypes.models import ContentType from django.db import models class Author(models.Model): name = models.CharField(max_length=50, unique=True) favorite_books = models.ManyToManyField( "Book", related_name="preferred_by_authors", related_query_name="preferred_by_authors", ) ...
rved"), (RENTED, "Rented"), ) title = models.CharField(max_length=255) author = models.ForeignKey( Author, models.CASCADE, related_name="books", related_query_name="book", ) editor = models.Foreig
Model): name = models.CharField(max_length=255) class Book(models.Model): AVAILABLE = "available" RESERVED = "reserved" RENTED = "rented" STATES = ( (AVAILABLE, "Available"), (RESERVED, "rese
{ "filepath": "tests/filtered_relation/models.py", "language": "python", "file_size": 3382, "cut_index": 614, "middle_length": 229 }
) cls.author1.favorite_books.add(cls.book2) cls.author1.favorite_books.add(cls.book3) def test_select_related(self): qs = ( Author.objects.annotate( book_join=FilteredRelation("book"), ) .select_related("book_join__editor") ...
uthor2, self.book3, self.editor_b, self.author2), ], lambda x: (x, x.book_join, x.book_join.editor, x.book_join.author), ) def test_select_related_multiple(self): qs = ( Book.objects.anno
hor1, self.book1, self.editor_a, self.author1), (self.author1, self.book4, self.editor_a, self.author1), (self.author2, self.book2, self.editor_b, self.author2), (self.a
{ "filepath": "tests/filtered_relation/tests.py", "language": "python", "file_size": 42765, "cut_index": 2151, "middle_length": 229 }
db import migrations, models class Migration(migrations.Migration): replaces = [ ("migrations2", "0001_initial"), ("migrations2", "0002_second"), ] operations = [ migrations.CreateModel( "OtherAuthor", [ ("id", models.AutoField(primary_key=T...
imary_key=True)), ( "author", models.ForeignKey( "migrations2.OtherAuthor", models.SET_NULL, null=True ), ), ], ), ]
s.AutoField(pr
{ "filepath": "tests/migrations2/test_migrations_2_squashed_with_replaces/0001_squashed_0002.py", "language": "python", "file_size": 795, "cut_index": 524, "middle_length": 14 }
odels.functions import Now from django.utils import timezone try: from PIL import Image except ImportError: Image = None class Country(models.Model): name = models.CharField(max_length=255) iso_two_letter = models.CharField(max_length=2) description = models.TextField() class Meta: c...
: class Meta: proxy = True class Place(models.Model): name = models.CharField(max_length=100) class Meta: abstract = True class Restaurant(Place): pass class Pizzeria(Restaurant): pass class State(models.Model):
ntry(Country): class Meta: proxy = True class ProxyProxyCountry(ProxyCountry): class Meta: proxy = True class ProxyMultiCountry(ProxyCountry): pass class ProxyMultiProxyCountry(ProxyMultiCountry)
{ "filepath": "tests/bulk_create/models.py", "language": "python", "file_size": 4824, "cut_index": 614, "middle_length": 229 }
zech Republic", ], attrgetter("name"), ) created = Country.objects.bulk_create([]) self.assertEqual(created, []) self.assertEqual(Country.objects.count(), 4) @skipUnlessDBFeature("has_bulk_insert") def test_efficiency(self): with self.assertNumQu...
lf.assertEqual(Country.objects.count(), 1) @skipUnlessDBFeature("has_bulk_insert") def test_long_and_short_text(self): Country.objects.bulk_create( [ Country(description="a" * 4001, iso_two_letter="A"),
with a length in the range 2001 to 4000 characters, i.e. 4002 to 8000 bytes, must be set as a CLOB on Oracle (#22144). """ Country.objects.bulk_create([Country(description="Ж" * 3000)]) se
{ "filepath": "tests/bulk_create/tests.py", "language": "python", "file_size": 36761, "cut_index": 2151, "middle_length": 229 }
""" Test the RequireDebugTrue filter class. """ filter_ = RequireDebugTrue() with self.settings(DEBUG=True): self.assertIs(filter_.filter("record is not used"), True) with self.settings(DEBUG=False): self.assertIs(filter_.filter("record is not us...
ly output anything when DEBUG=True. """ self.logger.error("Hey, this is an error.") self.assertEqual(self.logger_output.getvalue(), "") with self.settings(DEBUG=True): self.logger.error("Hey, this is an error.")
anup(logging.config.dictConfig, settings.LOGGING) class DefaultLoggingTests( SetupDefaultLoggingMixin, LoggingCaptureMixin, SimpleTestCase ): def test_django_logger(self): """ The 'django' base logger on
{ "filepath": "tests/logging_tests/tests.py", "language": "python", "file_size": 34012, "cut_index": 2151, "middle_length": 229 }
rom django.core.exceptions import DisallowedHost, PermissionDenied, SuspiciousOperation from django.http import ( Http404, HttpResponse, HttpResponseRedirect, HttpResponseServerError, ) from django.http.multipartparser import MultiPartParserError def innocent(request): return HttpResponse("innocen...
eturn HttpResponseServerError("Server Error", status=int(status)) def permission_denied(request): raise PermissionDenied() def multi_part_parser_error(request): raise MultiPartParserError("parsing error") def does_not_exist_raised(request):
dubious") class UncaughtException(Exception): pass def uncaught_exception(request): raise UncaughtException("Uncaught exception") def internal_server_error(request): status = request.GET.get("status", 500) r
{ "filepath": "tests/logging_tests/views.py", "language": "python", "file_size": 1028, "cut_index": 513, "middle_length": 229 }
nttypes.fields import GenericForeignKey, GenericRelation from django.contrib.contenttypes.models import ContentType from django.db import models class Episode(models.Model): name = models.CharField(max_length=100) length = models.CharField(max_length=100, blank=True) author = models.CharField(max_length=1...
_str__(self): return self.url # # Generic inline with unique_together # class Category(models.Model): name = models.CharField(max_length=50) class PhoneNumber(models.Model): content_type = models.ForeignKey(ContentType, models.CASCADE)
els.PositiveIntegerField() content_object = GenericForeignKey() url = models.URLField() description = models.CharField(max_length=100, blank=True) keywords = models.CharField(max_length=100, blank=True) def _
{ "filepath": "tests/generic_inline_admin/models.py", "language": "python", "file_size": 1693, "cut_index": 537, "middle_length": 229 }
, password="secret", email="super@example.com" ) @override_settings(ROOT_URLCONF="generic_inline_admin.urls") class GenericAdminViewTest(TestDataMixin, TestCase): def setUp(self): self.client.force_login(self.superuser) e = Episode.objects.create(name="This Week in Django") self.e...
e("admin:generic_inline_admin_episode_add")) self.assertEqual(response.status_code, 200) def test_basic_edit_GET(self): """ A smoke test to ensure GET on the change_view works. """ response = self.client.get(
ample.com/logo.png") m.save() self.png_media_pk = m.pk def test_basic_add_GET(self): """ A smoke test to ensure GET on the add_view works. """ response = self.client.get(revers
{ "filepath": "tests/generic_inline_admin/tests.py", "language": "python", "file_size": 21294, "cut_index": 1331, "middle_length": 229 }
contenttypes.models import ContentType from django.db import models __all__ = ( "Link", "Place", "Restaurant", "Person", "Address", "CharLink", "TextLink", "OddRelation1", "OddRelation2", "Contact", "Organization", "Note", "Company", ) class Link(models.Model): ...
pass class Cafe(Restaurant): pass class Address(models.Model): street = models.CharField(max_length=80) city = models.CharField(max_length=50) state = models.CharField(max_length=2) zipcode = models.CharField(max_length=5) con
proxy = True class Place(models.Model): name = models.CharField(max_length=100) links = GenericRelation(Link, related_query_name="places") link_proxy = GenericRelation(LinkProxy) class Restaurant(Place):
{ "filepath": "tests/generic_relations_regress/models.py", "language": "python", "file_size": 4890, "cut_index": 614, "middle_length": 229 }
OddRelation1, OddRelation2, Organization, Person, Place, Related, Restaurant, Tag, Team, TextLink, ) class GenericRelationTests(TestCase): def test_inherited_models_content_type(self): """ GenericRelations on inherited classes use the correct content type. ...
he primary key on the originating model of a query. See #12664. """ p = Person.objects.create(account=23, name="Chef") Address.objects.create( street="123 Anywhere Place", city="Conifer",
s.create(content_object=r) self.assertEqual(list(p.links.all()), [l1]) self.assertEqual(list(r.links.all()), [l2]) def test_reverse_relation_pk(self): """ The correct column name is used for t
{ "filepath": "tests/generic_relations_regress/tests.py", "language": "python", "file_size": 13936, "cut_index": 921, "middle_length": 229 }
cls.r = Reporter(name="John Smith") cls.r.save() # Create an Article. cls.a = Article(headline="First", reporter=cls.r) cls.a.save() # Create an Article via the Reporter object. cls.a2 = cls.r.article_set.create(headline="Second") # Create an Article with no Repo...
ir related Reporter objects. r = self.a.reporter self.assertEqual(r.id, self.r.id) def test_created_via_related_set(self): self.assertEqual(self.a2.reporter.id, self.r.id) def test_related_set(self): # Reporter obj
aul Jones") cls.r2.save() cls.a4 = cls.r2.article_set.create(headline="Fourth") def test_get_related(self): self.assertEqual(self.a.reporter.id, self.r.id) # Article objects have access to the
{ "filepath": "tests/many_to_one_null/tests.py", "language": "python", "file_size": 7476, "cut_index": 716, "middle_length": 229 }
Model1, Model2, Model3, NonAutoPK, Party, Worker, ) class ModelTests(TestCase): def test_model_init_too_many_args(self): msg = "Number of args exceeds number of fields" with self.assertRaisesMessage(IndexError, msg): Worker(1, 2, 3, 4) # The bug is that the f...
partment__lte=0) def test_sql_insert_compiler_return_id_attribute(self): """ Regression test for #14019: SQLInsertCompiler.as_sql() failure """ db = router.db_for_write(Party) query = InsertQuery(Party)
lookups. """ Worker.objects.filter(department__gte=0) def test_related_lte_lookup(self): """ Regression test for #10153: foreign key __lte lookups. """ Worker.objects.filter(de
{ "filepath": "tests/model_regress/tests.py", "language": "python", "file_size": 10103, "cut_index": 921, "middle_length": 229 }
copy import datetime from django.contrib.auth.models import User from django.db import models class RevisionableModel(models.Model): base = models.ForeignKey("self", models.SET_NULL, null=True) title = models.CharField(blank=True, max_length=255) when = models.DateTimeField(default=datetime.datetime.now...
lass Order(models.Model): created_by = models.ForeignKey(User, models.CASCADE) text = models.TextField() class TestObject(models.Model): first = models.CharField(max_length=20) second = models.CharField(max_length=20) third = models.C
) if not self.base: self.base = self super().save(*args, **kwargs) def new_revision(self): new_revision = copy.copy(self) new_revision.pk = None return new_revision c
{ "filepath": "tests/extra_regress/models.py", "language": "python", "file_size": 1129, "cut_index": 518, "middle_length": 229 }
ort attrgetter from django.test.testcases import TestCase from .models import Address, Contact, Customer class TestLookupQuery(TestCase): @classmethod def setUpTestData(cls): cls.address = Address.objects.create(company=1, customer_id=20) cls.customer1 = Customer.objects.create(company=1, cu...
[self.address.id], attrgetter("id"), ) def test_deep_mixed_backward(self): self.assertQuerySetEqual( Contact.objects.filter(customer__address=self.address), [self.contact1.id], attr
cts.filter(customer__contacts=self.contact1),
{ "filepath": "tests/foreign_object/test_agnostic_order_trimjoin.py", "language": "python", "file_size": 861, "cut_index": 529, "middle_length": 52 }