hash
stringlengths
64
64
content
stringlengths
0
1.51M
135922913d4e82e60ec39ba023779f4c71a966f914fc8f8dad536e3697ff2f77
from django.urls import include, path from . import urlconf_inner urlpatterns = [ path("test/me/", urlconf_inner.inner_view, name="outer"), path("inner_urlconf/", include(urlconf_inner.__name__)), ]
607a9b85ec2504b3aac8f613366fd50aa97a976b08ba407bdccbad593d031ac0
from django.urls import include, path from django.views import View def view1(request): pass def view2(request): pass class View3(View): pass nested = ( [ path("view1/", view1, name="view1"), path("view3/", View3.as_view(), name="view3"), ], "backend", ) urlpatterns = [ path("some/path/", include(nested, namespace="nested")), path("view2/", view2, name="view2"), ]
5de07f1f6a0eaf01026e7306ebb411a67a1f545c21ce5f31648acfa1abf00fbb
from django.core.exceptions import FieldError from django.test import TestCase from .models import Choice, Poll, User class ReverseLookupTests(TestCase): @classmethod def setUpTestData(cls): john = User.objects.create(name="John Doe") jim = User.objects.create(name="Jim Bo") first_poll = Poll.objects.create( question="What's the first question?", creator=john ) second_poll = Poll.objects.create( question="What's the second question?", creator=jim ) Choice.objects.create( poll=first_poll, related_poll=second_poll, name="This is the answer." ) def test_reverse_by_field(self): u1 = User.objects.get(poll__question__exact="What's the first question?") self.assertEqual(u1.name, "John Doe") u2 = User.objects.get(poll__question__exact="What's the second question?") self.assertEqual(u2.name, "Jim Bo") def test_reverse_by_related_name(self): p1 = Poll.objects.get(poll_choice__name__exact="This is the answer.") self.assertEqual(p1.question, "What's the first question?") p2 = Poll.objects.get(related_choice__name__exact="This is the answer.") self.assertEqual(p2.question, "What's the second question?") def test_reverse_field_name_disallowed(self): """ If a related_name is given you can't use the field name instead """ msg = ( "Cannot resolve keyword 'choice' into field. Choices are: " "creator, creator_id, id, poll_choice, question, related_choice" ) with self.assertRaisesMessage(FieldError, msg): Poll.objects.get(choice__name__exact="This is the answer")
527f0e58d0e92b0bc550c88f658b8c4c35fecad588cc6101b66f6826243d4dc5
""" Reverse lookups This demonstrates the reverse lookup features of the database API. """ from django.db import models class User(models.Model): name = models.CharField(max_length=200) class Poll(models.Model): question = models.CharField(max_length=200) creator = models.ForeignKey(User, models.CASCADE) class Choice(models.Model): name = models.CharField(max_length=100) poll = models.ForeignKey(Poll, models.CASCADE, related_name="poll_choice") related_poll = models.ForeignKey( Poll, models.CASCADE, related_name="related_choice" )
d5340113c2214426c7e912965790ca452580a51f19ccb5db3dcc44fc5d709a2c
import posixpath 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. """ def _response(self, filepath): return self.client.get(quote(posixpath.join(settings.STATIC_URL, filepath))) def assertFileContains(self, filepath, text): self.assertContains(self._response(filepath), text) def assertFileNotFound(self, filepath): self.assertEqual(self._response(filepath).status_code, 404) @override_settings(DEBUG=False) class TestServeDisabled(TestServeStatic): """ 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, TestServeStatic): """ Test static asset serving view with manually configured URLconf. """ @override_settings(DEBUG=True, ROOT_URLCONF="staticfiles_tests.urls.helper") class TestServeStaticWithURLHelper(TestDefaults, TestServeStatic): """ Test static asset serving view with staticfiles_urlpatterns helper. """
8dd338a81f6b639bba79b4e46cdb577ca5af8b0ce32a6dfbb02bb3d6eacd7b5a
from django.contrib.staticfiles.utils import check_settings from django.core.exceptions import ImproperlyConfigured from django.test import SimpleTestCase, override_settings class CheckSettingsTests(SimpleTestCase): @override_settings(DEBUG=True, MEDIA_URL="static/media/", STATIC_URL="static/") def test_media_url_in_static_url(self): msg = "runserver can't serve media if MEDIA_URL is within STATIC_URL." with self.assertRaisesMessage(ImproperlyConfigured, msg): check_settings() with self.settings(DEBUG=False): # Check disabled if DEBUG=False. check_settings()
74fccd2b12449a462363021f53258fd8c63ffcd66ea093bed8b4a797d146f03d
from django.contrib.staticfiles.handlers import ASGIStaticFilesHandler from django.core.handlers.asgi import ASGIHandler from django.test import AsyncRequestFactory from .cases import StaticFilesTestCase class TestASGIStaticFilesHandler(StaticFilesTestCase): async_request_factory = AsyncRequestFactory() async def test_get_async_response(self): request = self.async_request_factory.get("/static/test/file.txt") handler = ASGIStaticFilesHandler(ASGIHandler()) response = await handler.get_response_async(request) response.close() 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()) response = await handler.get_response_async(request) self.assertEqual(response.status_code, 404)
db395e1a07dc287a834c43e478dd809912f1de18815b3140573d33b8488e4c73
import datetime import os import shutil import tempfile import unittest from io import StringIO from pathlib import Path from unittest import mock from admin_scripts.tests import AdminScriptTestCase from django.conf import settings from django.contrib.staticfiles import storage from django.contrib.staticfiles.management.commands import collectstatic, runserver from django.core.exceptions import ImproperlyConfigured from django.core.management import CommandError, call_command from django.core.management.base import SystemCheckError from django.test import RequestFactory, override_settings from django.test.utils import extend_sys_path from django.utils import timezone from django.utils._os import symlinks_supported from django.utils.functional import empty from .cases import CollectionTestCase, StaticFilesTestCase, 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), []) class TestRunserver(StaticFilesTestCase): @override_settings(MIDDLEWARE=["django.middleware.common.CommonMiddleware"]) def test_middleware_loaded_only_once(self): command = runserver.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) 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 = RequestFactory().get(missing_static_file) with override_settings(DEBUG=False): response = handler.get_response(req) self.assertEqual(response.status_code, 404) with override_settings(DEBUG=True): response = handler.get_response(req) self.assertEqual(response.status_code, 404) class TestFindStatic(TestDefaults, CollectionTestCase): """ Test ``findstatic`` management command. """ def _get_file(self, filepath): path = call_command( "findstatic", filepath, all=False, verbosity=0, stdout=StringIO() ) with open(path, encoding="utf-8") as f: return f.read() def test_all_files(self): """ findstatic returns all candidate files if run without --first and -v1. """ result = call_command( "findstatic", "test/file.txt", verbosity=1, stdout=StringIO() ) lines = [line.strip() for line in result.split("\n")] self.assertEqual( len(lines), 3 ) # three because there is also the "Found <file> here" line self.assertIn("project", lines[1]) self.assertIn("apps", lines[2]) def test_all_files_less_verbose(self): """ findstatic returns all candidate files if run without --first and -v0. """ result = call_command( "findstatic", "test/file.txt", verbosity=0, stdout=StringIO() ) lines = [line.strip() for line in result.split("\n")] self.assertEqual(len(lines), 2) self.assertIn("project", lines[0]) self.assertIn("apps", lines[1]) def test_all_files_more_verbose(self): """ findstatic returns all candidate files if run without --first and -v2. Also, test that findstatic returns the searched locations with -v2. """ result = call_command( "findstatic", "test/file.txt", verbosity=2, stdout=StringIO() ) lines = [line.strip() for line in result.split("\n")] self.assertIn("project", lines[1]) self.assertIn("apps", lines[2]) self.assertIn("Looking in the following locations:", lines[3]) searched_locations = ", ".join(lines[4:]) # AppDirectoriesFinder searched locations self.assertIn( os.path.join("staticfiles_tests", "apps", "test", "static"), searched_locations, ) self.assertIn( os.path.join("staticfiles_tests", "apps", "no_label", "static"), searched_locations, ) # FileSystemFinder searched locations self.assertIn(TEST_SETTINGS["STATICFILES_DIRS"][1][1], searched_locations) self.assertIn(TEST_SETTINGS["STATICFILES_DIRS"][0], searched_locations) self.assertIn(str(TEST_SETTINGS["STATICFILES_DIRS"][2]), searched_locations) # DefaultStorageFinder searched locations self.assertIn( os.path.join("staticfiles_tests", "project", "site_media", "media"), searched_locations, ) class TestConfiguration(StaticFilesTestCase): def test_location_empty(self): msg = "without having set the STATIC_ROOT setting to a filesystem path" err = StringIO() for root in ["", None]: with override_settings(STATIC_ROOT=root): with self.assertRaisesMessage(ImproperlyConfigured, msg): call_command( "collectstatic", interactive=False, verbosity=0, stderr=err ) def test_local_storage_detection_helper(self): staticfiles_storage = storage.staticfiles_storage try: storage.staticfiles_storage._wrapped = empty with self.settings( STATICFILES_STORAGE=( "django.contrib.staticfiles.storage.StaticFilesStorage" ) ): command = collectstatic.Command() self.assertTrue(command.is_local_storage()) storage.staticfiles_storage._wrapped = empty with self.settings( STATICFILES_STORAGE="staticfiles_tests.storage.DummyStorage" ): command = collectstatic.Command() self.assertFalse(command.is_local_storage()) collectstatic.staticfiles_storage = storage.FileSystemStorage() command = collectstatic.Command() self.assertTrue(command.is_local_storage()) collectstatic.staticfiles_storage = DummyStorage() command = collectstatic.Command() self.assertFalse(command.is_local_storage()) finally: staticfiles_storage._wrapped = empty collectstatic.staticfiles_storage = staticfiles_storage storage.staticfiles_storage = staticfiles_storage @override_settings(STATICFILES_DIRS=("test")) def test_collectstatis_check(self): msg = "The STATICFILES_DIRS setting is not a tuple or list." with self.assertRaisesMessage(SystemCheckError, msg): call_command("collectstatic", skip_checks=False) class TestCollectionHelpSubcommand(AdminScriptTestCase): @override_settings(STATIC_ROOT=None) def test_missing_settings_dont_prevent_help(self): """ Even if the STATIC_ROOT setting is not set, one can still call the `manage.py help collectstatic` command. """ self.write_settings("settings.py", apps=["django.contrib.staticfiles"]) out, err = self.run_manage(["help", "collectstatic"]) self.assertNoOutput(err) class TestCollection(TestDefaults, CollectionTestCase): """ Test ``collectstatic`` management command. """ def test_ignore(self): """ -i patterns are ignored. """ self.assertFileNotFound("test/test.ignoreme") def test_common_ignore_patterns(self): """ Common ignore patterns (*~, .*, CVS) are ignored. """ self.assertFileNotFound("test/.hidden") self.assertFileNotFound("test/backup~") self.assertFileNotFound("test/CVS") def test_pathlib(self): self.assertFileContains("pathlib.txt", "pathlib") class TestCollectionPathLib(TestCollection): def mkdtemp(self): tmp_dir = super().mkdtemp() return Path(tmp_dir) class TestCollectionVerbosity(CollectionTestCase): copying_msg = "Copying " run_collectstatic_in_setUp = False post_process_msg = "Post-processed" staticfiles_copied_msg = "static files copied to" def test_verbosity_0(self): stdout = StringIO() self.run_collectstatic(verbosity=0, stdout=stdout) self.assertEqual(stdout.getvalue(), "") def test_verbosity_1(self): stdout = StringIO() self.run_collectstatic(verbosity=1, stdout=stdout) output = stdout.getvalue() self.assertIn(self.staticfiles_copied_msg, output) self.assertNotIn(self.copying_msg, output) def test_verbosity_2(self): stdout = StringIO() self.run_collectstatic(verbosity=2, stdout=stdout) output = stdout.getvalue() self.assertIn(self.staticfiles_copied_msg, output) self.assertIn(self.copying_msg, output) @override_settings( STATICFILES_STORAGE=( "django.contrib.staticfiles.storage.ManifestStaticFilesStorage" ) ) def test_verbosity_1_with_post_process(self): stdout = StringIO() self.run_collectstatic(verbosity=1, stdout=stdout, post_process=True) self.assertNotIn(self.post_process_msg, stdout.getvalue()) @override_settings( STATICFILES_STORAGE=( "django.contrib.staticfiles.storage.ManifestStaticFilesStorage" ) ) def test_verbosity_2_with_post_process(self): stdout = StringIO() self.run_collectstatic(verbosity=2, stdout=stdout, post_process=True) self.assertIn(self.post_process_msg, stdout.getvalue()) class TestCollectionClear(CollectionTestCase): """ Test the ``--clear`` option of the ``collectstatic`` management command. """ def run_collectstatic(self, **kwargs): clear_filepath = os.path.join(settings.STATIC_ROOT, "cleared.txt") with open(clear_filepath, "w") as f: f.write("should be cleared") super().run_collectstatic(clear=True) def test_cleared_not_found(self): self.assertFileNotFound("cleared.txt") def test_dir_not_exists(self, **kwargs): shutil.rmtree(settings.STATIC_ROOT) super().run_collectstatic(clear=True) @override_settings( STATICFILES_STORAGE="staticfiles_tests.storage.PathNotImplementedStorage" ) def test_handle_path_notimplemented(self): self.run_collectstatic() self.assertFileNotFound("cleared.txt") class TestInteractiveMessages(CollectionTestCase): overwrite_warning_msg = "This will overwrite existing files!" delete_warning_msg = "This will DELETE ALL FILES in this location!" files_copied_msg = "static files copied" @staticmethod def mock_input(stdout): def _input(msg): stdout.write(msg) return "yes" return _input def test_warning_when_clearing_staticdir(self): stdout = StringIO() self.run_collectstatic() with mock.patch("builtins.input", side_effect=self.mock_input(stdout)): call_command("collectstatic", interactive=True, clear=True, stdout=stdout) output = stdout.getvalue() self.assertNotIn(self.overwrite_warning_msg, output) self.assertIn(self.delete_warning_msg, output) def test_warning_when_overwriting_files_in_staticdir(self): stdout = StringIO() self.run_collectstatic() with mock.patch("builtins.input", side_effect=self.mock_input(stdout)): call_command("collectstatic", interactive=True, stdout=stdout) output = stdout.getvalue() self.assertIn(self.overwrite_warning_msg, output) self.assertNotIn(self.delete_warning_msg, output) def test_no_warning_when_staticdir_does_not_exist(self): stdout = StringIO() shutil.rmtree(settings.STATIC_ROOT) call_command("collectstatic", interactive=True, stdout=stdout) output = stdout.getvalue() self.assertNotIn(self.overwrite_warning_msg, output) self.assertNotIn(self.delete_warning_msg, output) self.assertIn(self.files_copied_msg, output) def test_no_warning_for_empty_staticdir(self): stdout = StringIO() with tempfile.TemporaryDirectory( prefix="collectstatic_empty_staticdir_test" ) as static_dir: with override_settings(STATIC_ROOT=static_dir): call_command("collectstatic", interactive=True, stdout=stdout) output = stdout.getvalue() self.assertNotIn(self.overwrite_warning_msg, output) self.assertNotIn(self.delete_warning_msg, output) self.assertIn(self.files_copied_msg, output) def test_cancelled(self): self.run_collectstatic() with mock.patch("builtins.input", side_effect=lambda _: "no"): with self.assertRaisesMessage( CommandError, "Collecting static files cancelled" ): call_command("collectstatic", interactive=True) class TestCollectionNoDefaultIgnore(TestDefaults, CollectionTestCase): """ The ``--no-default-ignore`` option of the ``collectstatic`` management command. """ def run_collectstatic(self): super().run_collectstatic(use_default_ignore_patterns=False) def test_no_common_ignore_patterns(self): """ With --no-default-ignore, common ignore patterns (*~, .*, CVS) are not ignored. """ self.assertFileContains("test/.hidden", "should be ignored") self.assertFileContains("test/backup~", "should be ignored") self.assertFileContains("test/CVS", "should be ignored") @override_settings( INSTALLED_APPS=[ "staticfiles_tests.apps.staticfiles_config.IgnorePatternsAppConfig", "staticfiles_tests.apps.test", ] ) class TestCollectionCustomIgnorePatterns(CollectionTestCase): def test_custom_ignore_patterns(self): """ A custom ignore_patterns list, ['*.css', '*/vendor/*.js'] in this case, can be specified in an AppConfig definition. """ self.assertFileNotFound("test/nonascii.css") self.assertFileContains("test/.hidden", "should be ignored") self.assertFileNotFound(os.path.join("test", "vendor", "module.js")) class TestCollectionDryRun(TestNoFilesCreated, CollectionTestCase): """ Test ``--dry-run`` option for ``collectstatic`` management command. """ def run_collectstatic(self): super().run_collectstatic(dry_run=True) @override_settings( STATICFILES_STORAGE="django.contrib.staticfiles.storage.ManifestStaticFilesStorage" ) class TestCollectionDryRunManifestStaticFilesStorage(TestCollectionDryRun): pass class TestCollectionFilesOverride(CollectionTestCase): """ Test overriding duplicated files by ``collectstatic`` management command. Check for proper handling of apps order in installed apps even if file modification dates are in different order: 'staticfiles_test_app', 'staticfiles_tests.apps.no_label', """ def setUp(self): self.temp_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, self.temp_dir) # get modification and access times for no_label/static/file2.txt self.orig_path = os.path.join( TEST_ROOT, "apps", "no_label", "static", "file2.txt" ) self.orig_mtime = os.path.getmtime(self.orig_path) self.orig_atime = os.path.getatime(self.orig_path) # prepare duplicate of file2.txt from a temporary app # this file will have modification time older than no_label/static/file2.txt # anyway it should be taken to STATIC_ROOT because the temporary app is before # 'no_label' app in installed apps self.temp_app_path = os.path.join(self.temp_dir, "staticfiles_test_app") self.testfile_path = os.path.join(self.temp_app_path, "static", "file2.txt") os.makedirs(self.temp_app_path) with open(os.path.join(self.temp_app_path, "__init__.py"), "w+"): pass os.makedirs(os.path.dirname(self.testfile_path)) with open(self.testfile_path, "w+") as f: f.write("duplicate of file2.txt") os.utime(self.testfile_path, (self.orig_atime - 1, self.orig_mtime - 1)) self.settings_with_test_app = self.modify_settings( INSTALLED_APPS={"prepend": "staticfiles_test_app"}, ) with extend_sys_path(self.temp_dir): self.settings_with_test_app.enable() super().setUp() def tearDown(self): super().tearDown() self.settings_with_test_app.disable() def test_ordering_override(self): """ Test if collectstatic takes files in proper order """ self.assertFileContains("file2.txt", "duplicate of file2.txt") # run collectstatic again self.run_collectstatic() self.assertFileContains("file2.txt", "duplicate of file2.txt") # The collectstatic test suite already has conflicting files since both # project/test/file.txt and apps/test/static/test/file.txt are collected. To # properly test for the warning not happening unless we tell it to explicitly, # we remove the project directory and will add back a conflicting file later. @override_settings(STATICFILES_DIRS=[]) class TestCollectionOverwriteWarning(CollectionTestCase): """ Test warning in ``collectstatic`` output when a file is skipped because a previous file was already written to the same path. """ # If this string is in the collectstatic output, it means the warning we're # looking for was emitted. warning_string = "Found another file" def _collectstatic_output(self, **kwargs): """ Run collectstatic, and capture and return the output. We want to run the command at highest verbosity, which is why we can't just call e.g. BaseCollectionTestCase.run_collectstatic() """ out = StringIO() call_command( "collectstatic", interactive=False, verbosity=3, stdout=out, **kwargs ) return out.getvalue() def test_no_warning(self): """ There isn't a warning if there isn't a duplicate destination. """ output = self._collectstatic_output(clear=True) self.assertNotIn(self.warning_string, output) def test_warning(self): """ There is a warning when there are duplicate destinations. """ with tempfile.TemporaryDirectory() as static_dir: duplicate = os.path.join(static_dir, "test", "file.txt") os.mkdir(os.path.dirname(duplicate)) with open(duplicate, "w+") as f: f.write("duplicate of file.txt") with self.settings(STATICFILES_DIRS=[static_dir]): output = self._collectstatic_output(clear=True) self.assertIn(self.warning_string, output) os.remove(duplicate) # Make sure the warning went away again. with self.settings(STATICFILES_DIRS=[static_dir]): output = self._collectstatic_output(clear=True) self.assertNotIn(self.warning_string, output) @override_settings(STATICFILES_STORAGE="staticfiles_tests.storage.DummyStorage") class TestCollectionNonLocalStorage(TestNoFilesCreated, CollectionTestCase): """ Tests for a Storage that implements get_modified_time() but not path() (#15035). """ def test_storage_properties(self): # Properties of the Storage as described in the ticket. storage = DummyStorage() self.assertEqual( storage.get_modified_time("name"), datetime.datetime(1970, 1, 1, tzinfo=timezone.utc), ) with self.assertRaisesMessage( NotImplementedError, "This backend doesn't support absolute paths." ): storage.path("name") class TestCollectionNeverCopyStorage(CollectionTestCase): @override_settings( STATICFILES_STORAGE="staticfiles_tests.storage.NeverCopyRemoteStorage" ) def test_skips_newer_files_in_remote_storage(self): """ collectstatic skips newer files in a remote storage. run_collectstatic() in setUp() copies the static files, then files are always skipped after NeverCopyRemoteStorage is activated since NeverCopyRemoteStorage.get_modified_time() returns a datetime in the future to simulate an unmodified file. """ stdout = StringIO() self.run_collectstatic(stdout=stdout, verbosity=2) output = stdout.getvalue() self.assertIn("Skipping 'test.txt' (not modified)", output) @unittest.skipUnless(symlinks_supported(), "Must be able to symlink to run this test.") class TestCollectionLinks(TestDefaults, CollectionTestCase): """ Test ``--link`` option for ``collectstatic`` management command. Note that by inheriting ``TestDefaults`` we repeat all the standard file resolving tests here, to make sure using ``--link`` does not change the file-selection semantics. """ def run_collectstatic(self, clear=False, link=True, **kwargs): super().run_collectstatic(link=link, clear=clear, **kwargs) def test_links_created(self): """ With ``--link``, symbolic links are created. """ self.assertTrue(os.path.islink(os.path.join(settings.STATIC_ROOT, "test.txt"))) def test_broken_symlink(self): """ Test broken symlink gets deleted. """ path = os.path.join(settings.STATIC_ROOT, "test.txt") os.unlink(path) self.run_collectstatic() self.assertTrue(os.path.islink(path)) def test_symlinks_and_files_replaced(self): """ Running collectstatic in non-symlink mode replaces symlinks with files, while symlink mode replaces files with symlinks. """ path = os.path.join(settings.STATIC_ROOT, "test.txt") self.assertTrue(os.path.islink(path)) self.run_collectstatic(link=False) self.assertFalse(os.path.islink(path)) self.run_collectstatic(link=True) self.assertTrue(os.path.islink(path)) def test_clear_broken_symlink(self): """ With ``--clear``, broken symbolic links are deleted. """ nonexistent_file_path = os.path.join(settings.STATIC_ROOT, "nonexistent.txt") broken_symlink_path = os.path.join(settings.STATIC_ROOT, "symlink.txt") os.symlink(nonexistent_file_path, broken_symlink_path) self.run_collectstatic(clear=True) self.assertFalse(os.path.lexists(broken_symlink_path)) @override_settings( STATICFILES_STORAGE="staticfiles_tests.storage.PathNotImplementedStorage" ) def test_no_remote_link(self): with self.assertRaisesMessage( CommandError, "Can't symlink to a remote destination." ): self.run_collectstatic()
dc34614f8c27c7070b7e624ee17fffd280046cab0f967f613a1e77f8108e040d
import os from django.conf import settings from django.contrib.staticfiles import finders, storage from 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 path(s) they find can differ. Compare them using os.path.normcase() to avoid false negatives. """ def test_find_first(self): src, dst = self.find_first found = 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, all=True) found = [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): super().setUp() self.finder = finders.FileSystemFinder() test_file_path = os.path.join( TEST_ROOT, "project", "documents", "test", "file.txt" ) self.find_first = (os.path.join("test", "file.txt"), test_file_path) self.find_all = (os.path.join("test", "file.txt"), [test_file_path]) class TestAppDirectoriesFinder(TestFinders, StaticFilesTestCase): """ Test AppDirectoriesFinder. """ def setUp(self): super().setUp() self.finder = finders.AppDirectoriesFinder() test_file_path = os.path.join( TEST_ROOT, "apps", "test", "static", "test", "file1.txt" ) self.find_first = (os.path.join("test", "file1.txt"), test_file_path) self.find_all = (os.path.join("test", "file1.txt"), [test_file_path]) class TestDefaultStorageFinder(TestFinders, StaticFilesTestCase): """ Test DefaultStorageFinder. """ def setUp(self): super().setUp() self.finder = finders.DefaultStorageFinder( storage=storage.StaticFilesStorage(location=settings.MEDIA_ROOT) ) test_file_path = os.path.join(settings.MEDIA_ROOT, "media-file.txt") self.find_first = ("media-file.txt", test_file_path) self.find_all = ("media-file.txt", [test_file_path]) @override_settings( STATICFILES_FINDERS=["django.contrib.staticfiles.finders.FileSystemFinder"], STATICFILES_DIRS=[os.path.join(TEST_ROOT, "project", "documents")], ) class TestMiscFinder(SimpleTestCase): """ A few misc finder tests. """ def test_get_finder(self): self.assertIsInstance( finders.get_finder("django.contrib.staticfiles.finders.FileSystemFinder"), finders.FileSystemFinder, ) def test_get_finder_bad_classname(self): with self.assertRaises(ImportError): finders.get_finder("django.contrib.staticfiles.finders.FooBarFinder") def test_get_finder_bad_module(self): with self.assertRaises(ImportError): finders.get_finder("foo.bar.FooBarFinder") def test_cache(self): finders.get_finder.cache_clear() for n in range(10): finders.get_finder("django.contrib.staticfiles.finders.FileSystemFinder") cache_info = finders.get_finder.cache_info() self.assertEqual(cache_info.hits, 9) self.assertEqual(cache_info.currsize, 1) def test_searched_locations(self): finders.find("spam") self.assertEqual( finders.searched_locations, [os.path.join(TEST_ROOT, "project", "documents")], ) @override_settings(MEDIA_ROOT="") def test_location_empty(self): msg = ( "The storage backend of the staticfiles finder " "<class 'django.contrib.staticfiles.finders.DefaultStorageFinder'> " "doesn't have a valid location." ) with self.assertRaisesMessage(ImproperlyConfigured, msg): finders.DefaultStorageFinder()
c599aa712258a1ecfe986b0abb6f244e29e57b1fc1fe5ca821619cc2637926f9
import os import shutil import tempfile from django.conf import settings from django.core.management 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.assertIn( text, self._get_file(filepath), "'%s' not in '%s'" % (text, filepath), ) def assertFileNotFound(self, filepath): with self.assertRaises(OSError): self._get_file(filepath) def render_template(self, template, **kwargs): if isinstance(template, str): template = Template(template) return template.render(Context(**kwargs)).strip() def static_template_snippet(self, path, asvar=False): if asvar: return ( "{%% load static from static %%}{%% static '%s' as var %%}{{ var }}" % path ) return "{%% load static from static %%}{%% static '%s' %%}" % path def assertStaticRenders(self, path, result, asvar=False, **kwargs): template = self.static_template_snippet(path, asvar) self.assertEqual(self.render_template(template, **kwargs), result) def assertStaticRaises(self, exc, path, result, asvar=False, **kwargs): with self.assertRaises(exc): self.assertStaticRenders(path, result, **kwargs) @override_settings(**TEST_SETTINGS) class StaticFilesTestCase(BaseStaticFilesMixin, SimpleTestCase): pass @override_settings(**TEST_SETTINGS) class CollectionTestCase(BaseStaticFilesMixin, SimpleTestCase): """ Tests shared by all file finding features (collectstatic, findstatic, and static serve view). This relies on the asserts defined in BaseStaticFilesTestCase, but is separated because some test cases need those asserts without all these tests. """ run_collectstatic_in_setUp = True def setUp(self): super().setUp() temp_dir = self.mkdtemp() # Override the STATIC_ROOT for all tests from setUp to tearDown # rather than as a context manager self.patched_settings = self.settings(STATIC_ROOT=temp_dir) self.patched_settings.enable() if self.run_collectstatic_in_setUp: self.run_collectstatic() # Same comment as in runtests.teardown. self.addCleanup(shutil.rmtree, temp_dir) def tearDown(self): self.patched_settings.disable() super().tearDown() def mkdtemp(self): return tempfile.mkdtemp() def run_collectstatic(self, *, verbosity=0, **kwargs): call_command( "collectstatic", interactive=False, verbosity=verbosity, ignore_patterns=["*.ignoreme"], **kwargs, ) def _get_file(self, filepath): assert filepath, "filepath is empty." filepath = os.path.join(settings.STATIC_ROOT, filepath) with open(filepath, encoding="utf-8") as f: return f.read() class TestDefaults: """ A few standard test cases. """ def test_staticfiles_dirs(self): """ Can find a file in a STATICFILES_DIRS directory. """ self.assertFileContains("test.txt", "Can we find") self.assertFileContains(os.path.join("prefix", "test.txt"), "Prefix") def test_staticfiles_dirs_subdir(self): """ Can find a file in a subdirectory of a STATICFILES_DIRS directory. """ self.assertFileContains("subdir/test.txt", "Can we find") def test_staticfiles_dirs_priority(self): """ File in STATICFILES_DIRS has priority over file in app. """ self.assertFileContains("test/file.txt", "STATICFILES_DIRS") def test_app_files(self): """ Can find a file in an app static/ directory. """ self.assertFileContains("test/file1.txt", "file1 in the app dir") def test_nonascii_filenames(self): """ Can find a file with non-ASCII character in an app static/ directory. """ self.assertFileContains("test/⊗.txt", "⊗ in the app dir") def test_camelcase_filenames(self): """ Can find a file with capital letters. """ self.assertFileContains("test/camelCase.txt", "camelCase") def test_filename_with_percent_sign(self): self.assertFileContains("test/%2F.txt", "%2F content")
e2c664e0acc3e995d324527e79a81962da1263292e5205c90f49222eec80defa
""" A subset of the tests in tests/servers/tests exercising 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 modify_settings, override_settings 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"), } class LiveServerBase(StaticLiveServerTestCase): available_apps = [] @classmethod def setUpClass(cls): # Override settings cls.settings_override = override_settings(**TEST_SETTINGS) cls.settings_override.enable() cls.addClassCleanup(cls.settings_override.disable) super().setUpClass() class StaticLiveServerChecks(LiveServerBase): @classmethod def setUpClass(cls): # If contrib.staticfiles isn't configured properly, the exception # should bubble up to the main thread. old_STATIC_URL = TEST_SETTINGS["STATIC_URL"] TEST_SETTINGS["STATIC_URL"] = None try: cls.raises_exception() finally: TEST_SETTINGS["STATIC_URL"] = old_STATIC_URL @classmethod def tearDownClass(cls): # skip it, as setUpClass doesn't call its parent either pass @classmethod def raises_exception(cls): try: super().setUpClass() except ImproperlyConfigured: # This raises ImproperlyConfigured("You're using the staticfiles # app without having set the required STATIC_URL setting.") pass else: raise Exception("setUpClass() should have raised an exception.") def test_test_test(self): # Intentionally empty method so that the test is picked up by the # test runner and the overridden setUpClass() method is executed. pass class StaticLiveServerView(LiveServerBase): def urlopen(self, url): return urlopen(self.live_server_url + url) # The test is going to access a static file stored in this application. @modify_settings(INSTALLED_APPS={"append": "staticfiles_tests.apps.test"}) def test_collectstatic_emulation(self): """ StaticLiveServerTestCase use of staticfiles' serve() allows it to discover app's static assets without having to collectstatic first. """ with self.urlopen("/static/test/file.txt") as f: self.assertEqual(f.read().rstrip(b"\r\n"), b"In static directory.")
0eb8a1d66239bc000486ada7a4ad811911a0c6ce72dde6bfc598383135799ff0
from pathlib import Path from unittest import mock from django.conf import settings from django.contrib.staticfiles.checks import check_finders from django.contrib.staticfiles.finders import BaseFinder, get_finder from django.core.checks import Error, Warning from django.test import override_settings from .cases import CollectionTestCase from .settings import TEST_ROOT class FindersCheckTests(CollectionTestCase): run_collectstatic_in_setUp = False def test_base_finder_check_not_implemented(self): finder = BaseFinder() msg = ( "subclasses may provide a check() method to verify the finder is " "configured correctly." ) with self.assertRaisesMessage(NotImplementedError, msg): finder.check() def test_check_finders(self): """check_finders() concatenates all errors.""" error1 = Error("1") error2 = Error("2") error3 = Error("3") def get_finders(): class Finder1(BaseFinder): def check(self, **kwargs): return [error1] class Finder2(BaseFinder): def check(self, **kwargs): return [] class Finder3(BaseFinder): def check(self, **kwargs): return [error2, error3] class Finder4(BaseFinder): pass return [Finder1(), Finder2(), Finder3(), Finder4()] with mock.patch("django.contrib.staticfiles.checks.get_finders", get_finders): errors = check_finders(None) self.assertEqual(errors, [error1, error2, error3]) def test_no_errors_with_test_settings(self): self.assertEqual(check_finders(None), []) @override_settings(STATICFILES_DIRS="a string") def test_dirs_not_tuple_or_list(self): self.assertEqual( check_finders(None), [ Error( "The STATICFILES_DIRS setting is not a tuple or list.", hint="Perhaps you forgot a trailing comma?", id="staticfiles.E001", ) ], ) def test_dirs_contains_static_root(self): with self.settings(STATICFILES_DIRS=[settings.STATIC_ROOT]): self.assertEqual( check_finders(None), [ Error( "The STATICFILES_DIRS setting should not contain the " "STATIC_ROOT setting.", id="staticfiles.E002", ) ], ) def test_dirs_contains_static_root_in_tuple(self): with self.settings(STATICFILES_DIRS=[("prefix", settings.STATIC_ROOT)]): self.assertEqual( check_finders(None), [ Error( "The STATICFILES_DIRS setting should not contain the " "STATIC_ROOT setting.", id="staticfiles.E002", ) ], ) def test_prefix_contains_trailing_slash(self): static_dir = Path(TEST_ROOT) / "project" / "documents" with self.settings(STATICFILES_DIRS=[("prefix/", static_dir)]): self.assertEqual( check_finders(None), [ Error( "The prefix 'prefix/' in the STATICFILES_DIRS setting must " "not end with a slash.", id="staticfiles.E003", ), ], ) def test_nonexistent_directories(self): with self.settings( STATICFILES_DIRS=[ "/fake/path", ("prefix", "/fake/prefixed/path"), ] ): self.assertEqual( check_finders(None), [ Warning( "The directory '/fake/path' in the STATICFILES_DIRS " "setting does not exist.", id="staticfiles.W004", ), Warning( "The directory '/fake/prefixed/path' in the " "STATICFILES_DIRS setting does not exist.", id="staticfiles.W004", ), ], ) # Nonexistent directories are skipped. finder = get_finder("django.contrib.staticfiles.finders.FileSystemFinder") self.assertEqual(list(finder.list(None)), [])
28c517a841a1103d43455f542009a21e70829c15b8086d6eace48aba9715d40a
import 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"), "STATICFILES_DIRS": [ os.path.join(TEST_ROOT, "project", "documents"), ("prefix", os.path.join(TEST_ROOT, "project", "prefixed")), Path(TEST_ROOT) / "project" / "pathlib", ], "STATICFILES_FINDERS": [ "django.contrib.staticfiles.finders.FileSystemFinder", "django.contrib.staticfiles.finders.AppDirectoriesFinder", "django.contrib.staticfiles.finders.DefaultStorageFinder", ], "INSTALLED_APPS": [ "django.contrib.staticfiles", "staticfiles_tests", "staticfiles_tests.apps.test", "staticfiles_tests.apps.no_label", ], # In particular, AuthenticationMiddleware can't be used because # contrib.auth isn't in INSTALLED_APPS. "MIDDLEWARE": [], }
28f5d6b5c5450adaf93f4f23e00c9dbb604b2913130b2802b339d96a47ef237f
from urllib.parse import urljoin 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): return urljoin("https://example.com/assets/", name) @override_settings( STATIC_URL="http://media.example.com/static/", INSTALLED_APPS=("django.contrib.staticfiles",), STATICFILES_STORAGE="staticfiles_tests.test_forms.StaticTestStorage", ) class StaticFilesFormsMediaTestCase(SimpleTestCase): def test_absolute_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", static("relative/path/to/js4"), ), ) self.assertEqual( str(m), """<link href="https://example.com/assets/path/to/css1" media="all" rel="stylesheet"> <link href="/path/to/css2" media="all" rel="stylesheet"> <script src="/path/to/js1"></script> <script src="http://media.other.com/path/to/js2"></script> <script src="https://secure.other.com/path/to/js3"></script> <script src="https://example.com/assets/relative/path/to/js4"></script>""", )
0429fcff8e543f965a1bba13b7ce88695fb8ca2628ef4f820d75f209d89a1d51
import json import os import shutil import sys import tempfile import unittest from io import StringIO from pathlib import Path from unittest import mock from django.conf import settings from django.contrib.staticfiles import finders, storage from django.contrib.staticfiles.management.commands.collectstatic import ( Command as CollectstaticCommand, ) from django.core.management import call_command from django.test import SimpleTestCase, override_settings from .cases import CollectionTestCase from .settings import TEST_ROOT def hashed_file_path(test, path): fullpath = test.render_template(test.static_template_snippet(path)) return fullpath.replace(settings.STATIC_URL, "") class TestHashedFiles: hashed_file_path = hashed_file_path def tearDown(self): # Clear hashed files to avoid side effects among tests. storage.staticfiles_storage.hashed_files.clear() def assertPostCondition(self): """ Assert post conditions for a test are met. Must be manually called at the end of each test. """ pass def test_template_tag_return(self): self.assertStaticRaises( ValueError, "does/not/exist.png", "/static/does/not/exist.png" ) self.assertStaticRenders("test/file.txt", "/static/test/file.dad0999e4f8f.txt") self.assertStaticRenders( "test/file.txt", "/static/test/file.dad0999e4f8f.txt", asvar=True ) self.assertStaticRenders( "cached/styles.css", "/static/cached/styles.5e0040571e1a.css" ) self.assertStaticRenders("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") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"cached/other.css", content) self.assertIn(b"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/ignored.554da52152af.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"https:foobar", content) self.assertIn(b"data:foobar", content) self.assertIn(b"chrome:foobar", content) self.assertIn(b"//foobar", content) self.assertPostCondition() def test_path_with_querystring(self): relpath = self.hashed_file_path("cached/styles.css?spam=eggs") self.assertEqual(relpath, "cached/styles.5e0040571e1a.css?spam=eggs") with storage.staticfiles_storage.open( "cached/styles.5e0040571e1a.css" ) as relfile: content = relfile.read() self.assertNotIn(b"cached/other.css", content) self.assertIn(b"other.d41d8cd98f00.css", content) self.assertPostCondition() def test_path_with_fragment(self): relpath = self.hashed_file_path("cached/styles.css#eggs") self.assertEqual(relpath, "cached/styles.5e0040571e1a.css#eggs") with storage.staticfiles_storage.open( "cached/styles.5e0040571e1a.css" ) as relfile: content = relfile.read() self.assertNotIn(b"cached/other.css", content) self.assertIn(b"other.d41d8cd98f00.css", content) self.assertPostCondition() def test_path_with_querystring_and_fragment(self): relpath = self.hashed_file_path("cached/css/fragments.css") self.assertEqual(relpath, "cached/css/fragments.a60c0e74834f.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertIn(b"fonts/font.b9b105392eb8.eot?#iefix", content) self.assertIn(b"fonts/font.b8d603e42714.svg#webfontIyfZbseF", content) self.assertIn( b"fonts/font.b8d603e42714.svg#path/to/../../fonts/font.svg", content ) self.assertIn( b"data:font/woff;charset=utf-8;" b"base64,d09GRgABAAAAADJoAA0AAAAAR2QAAQAAAAAAAAAAAAA", content, ) self.assertIn(b"#default#VML", content) self.assertPostCondition() def test_template_tag_absolute(self): relpath = self.hashed_file_path("cached/absolute.css") self.assertEqual(relpath, "cached/absolute.eb04def9f9a4.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"/static/cached/styles.css", content) self.assertIn(b"/static/cached/styles.5e0040571e1a.css", content) self.assertNotIn(b"/static/styles_root.css", content) self.assertIn(b"/static/styles_root.401f2509a628.css", content) self.assertIn(b"/static/cached/img/relative.acae32e4532b.png", content) self.assertPostCondition() def test_template_tag_absolute_root(self): """ Like test_template_tag_absolute, but for a file in STATIC_ROOT (#26249). """ relpath = self.hashed_file_path("absolute_root.css") self.assertEqual(relpath, "absolute_root.f821df1b64f7.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"/static/styles_root.css", content) self.assertIn(b"/static/styles_root.401f2509a628.css", content) self.assertPostCondition() def test_template_tag_relative(self): relpath = self.hashed_file_path("cached/relative.css") self.assertEqual(relpath, "cached/relative.c3e9e1ea6f2e.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"../cached/styles.css", content) self.assertNotIn(b'@import "styles.css"', content) self.assertNotIn(b"url(img/relative.png)", content) self.assertIn(b'url("img/relative.acae32e4532b.png")', content) self.assertIn(b"../cached/styles.5e0040571e1a.css", content) self.assertPostCondition() def test_import_replacement(self): "See #18050" relpath = self.hashed_file_path("cached/import.css") self.assertEqual(relpath, "cached/import.f53576679e5a.css") with storage.staticfiles_storage.open(relpath) as relfile: self.assertIn(b"""import url("styles.5e0040571e1a.css")""", relfile.read()) self.assertPostCondition() def test_template_tag_deep_relative(self): relpath = self.hashed_file_path("cached/css/window.css") self.assertEqual(relpath, "cached/css/window.5d5c10836967.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"url(img/window.png)", content) self.assertIn(b'url("img/window.acae32e4532b.png")', content) self.assertPostCondition() def test_template_tag_url(self): relpath = self.hashed_file_path("cached/url.css") self.assertEqual(relpath, "cached/url.902310b73412.css") with storage.staticfiles_storage.open(relpath) as relfile: self.assertIn(b"https://", relfile.read()) self.assertPostCondition() @override_settings( STATICFILES_DIRS=[os.path.join(TEST_ROOT, "project", "loop")], STATICFILES_FINDERS=["django.contrib.staticfiles.finders.FileSystemFinder"], ) def test_import_loop(self): finders.get_finder.cache_clear() err = StringIO() with self.assertRaisesMessage(RuntimeError, "Max post-process passes exceeded"): call_command("collectstatic", interactive=False, verbosity=0, stderr=err) self.assertEqual("Post-processing 'All' failed!\n\n", err.getvalue()) self.assertPostCondition() def test_post_processing(self): """ post_processing behaves correctly. Files that are alterable should always be post-processed; files that aren't should be skipped. collectstatic has already been called once in setUp() for this testcase, therefore we check by verifying behavior on a second run. """ collectstatic_args = { "interactive": False, "verbosity": 0, "link": False, "clear": False, "dry_run": False, "post_process": True, "use_default_ignore_patterns": True, "ignore_patterns": ["*.ignoreme"], } collectstatic_cmd = CollectstaticCommand() collectstatic_cmd.set_options(**collectstatic_args) stats = collectstatic_cmd.collect() self.assertIn( os.path.join("cached", "css", "window.css"), stats["post_processed"] ) self.assertIn( os.path.join("cached", "css", "img", "window.png"), stats["unmodified"] ) self.assertIn(os.path.join("test", "nonascii.css"), stats["post_processed"]) # No file should be yielded twice. self.assertCountEqual(stats["post_processed"], set(stats["post_processed"])) self.assertPostCondition() def test_css_import_case_insensitive(self): relpath = self.hashed_file_path("cached/styles_insensitive.css") self.assertEqual(relpath, "cached/styles_insensitive.3fa427592a53.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"cached/other.css", content) self.assertIn(b"other.d41d8cd98f00.css", content) self.assertPostCondition() def test_css_source_map(self): relpath = self.hashed_file_path("cached/source_map.css") self.assertEqual(relpath, "cached/source_map.b2fceaf426aa.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"/*# sourceMappingURL=source_map.css.map */", content) self.assertIn( b"/*# sourceMappingURL=source_map.css.99914b932bd3.map */", content, ) self.assertPostCondition() def test_css_source_map_sensitive(self): relpath = self.hashed_file_path("cached/source_map_sensitive.css") self.assertEqual(relpath, "cached/source_map_sensitive.456683f2106f.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertIn(b"/*# sOuRcEMaPpInGURL=source_map.css.map */", content) self.assertNotIn( b"/*# sourceMappingURL=source_map.css.99914b932bd3.map */", content, ) self.assertPostCondition() def test_js_source_map(self): relpath = self.hashed_file_path("cached/source_map.js") self.assertEqual(relpath, "cached/source_map.cd45b8534a87.js") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"//# sourceMappingURL=source_map.js.map", content) self.assertIn( b"//# sourceMappingURL=source_map.js.99914b932bd3.map", content, ) self.assertPostCondition() def test_js_source_map_sensitive(self): relpath = self.hashed_file_path("cached/source_map_sensitive.js") self.assertEqual(relpath, "cached/source_map_sensitive.5da96fdd3cb3.js") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertIn(b"//# sOuRcEMaPpInGURL=source_map.js.map", content) self.assertNotIn( b"//# sourceMappingURL=source_map.js.99914b932bd3.map", content, ) self.assertPostCondition() @override_settings( STATICFILES_DIRS=[os.path.join(TEST_ROOT, "project", "faulty")], STATICFILES_FINDERS=["django.contrib.staticfiles.finders.FileSystemFinder"], ) def test_post_processing_failure(self): """ post_processing indicates the origin of the error when it fails. """ finders.get_finder.cache_clear() err = StringIO() with self.assertRaises(Exception): call_command("collectstatic", interactive=False, verbosity=0, stderr=err) self.assertEqual("Post-processing 'faulty.css' failed!\n\n", err.getvalue()) self.assertPostCondition() @override_settings(STATICFILES_STORAGE="staticfiles_tests.storage.ExtraPatternsStorage") class TestExtraPatternsStorage(CollectionTestCase): def setUp(self): storage.staticfiles_storage.hashed_files.clear() # avoid cache interference super().setUp() def cached_file_path(self, path): fullpath = self.render_template(self.static_template_snippet(path)) return fullpath.replace(settings.STATIC_URL, "") def test_multi_extension_patterns(self): """ With storage classes having several file extension patterns, only the files matching a specific file pattern should be affected by the substitution (#19670). """ # CSS files shouldn't be touched by JS patterns. relpath = self.cached_file_path("cached/import.css") self.assertEqual(relpath, "cached/import.f53576679e5a.css") with storage.staticfiles_storage.open(relpath) as relfile: self.assertIn(b'import url("styles.5e0040571e1a.css")', relfile.read()) # Confirm JS patterns have been applied to JS files. relpath = self.cached_file_path("cached/test.js") self.assertEqual(relpath, "cached/test.388d7a790d46.js") with storage.staticfiles_storage.open(relpath) as relfile: self.assertIn(b'JS_URL("import.f53576679e5a.css")', relfile.read()) @override_settings( STATICFILES_STORAGE="django.contrib.staticfiles.storage.ManifestStaticFilesStorage", ) class TestCollectionManifestStorage(TestHashedFiles, CollectionTestCase): """ Tests for the Cache busting storage """ def setUp(self): super().setUp() temp_dir = tempfile.mkdtemp() os.makedirs(os.path.join(temp_dir, "test")) self._clear_filename = os.path.join(temp_dir, "test", "cleared.txt") with open(self._clear_filename, "w") as f: f.write("to be deleted in one test") self.patched_settings = self.settings( STATICFILES_DIRS=settings.STATICFILES_DIRS + [temp_dir], ) self.patched_settings.enable() self.addCleanup(shutil.rmtree, temp_dir) self._manifest_strict = storage.staticfiles_storage.manifest_strict def tearDown(self): self.patched_settings.disable() if os.path.exists(self._clear_filename): os.unlink(self._clear_filename) storage.staticfiles_storage.manifest_strict = self._manifest_strict super().tearDown() def assertPostCondition(self): hashed_files = storage.staticfiles_storage.hashed_files # The in-memory version of the manifest matches the one on disk # since a properly created manifest should cover all filenames. if hashed_files: manifest = storage.staticfiles_storage.load_manifest() self.assertEqual(hashed_files, manifest) def test_manifest_exists(self): filename = storage.staticfiles_storage.manifest_name path = storage.staticfiles_storage.path(filename) self.assertTrue(os.path.exists(path)) def test_manifest_does_not_exist(self): storage.staticfiles_storage.manifest_name = "does.not.exist.json" self.assertIsNone(storage.staticfiles_storage.read_manifest()) def test_manifest_does_not_ignore_permission_error(self): with mock.patch("builtins.open", side_effect=PermissionError): with self.assertRaises(PermissionError): storage.staticfiles_storage.read_manifest() def test_loaded_cache(self): self.assertNotEqual(storage.staticfiles_storage.hashed_files, {}) manifest_content = storage.staticfiles_storage.read_manifest() self.assertIn( '"version": "%s"' % storage.staticfiles_storage.manifest_version, manifest_content, ) def test_parse_cache(self): hashed_files = storage.staticfiles_storage.hashed_files manifest = storage.staticfiles_storage.load_manifest() self.assertEqual(hashed_files, manifest) def test_clear_empties_manifest(self): cleared_file_name = storage.staticfiles_storage.clean_name( os.path.join("test", "cleared.txt") ) # collect the additional file self.run_collectstatic() hashed_files = storage.staticfiles_storage.hashed_files self.assertIn(cleared_file_name, hashed_files) manifest_content = storage.staticfiles_storage.load_manifest() self.assertIn(cleared_file_name, manifest_content) original_path = storage.staticfiles_storage.path(cleared_file_name) self.assertTrue(os.path.exists(original_path)) # delete the original file form the app, collect with clear os.unlink(self._clear_filename) self.run_collectstatic(clear=True) self.assertFileNotFound(original_path) hashed_files = storage.staticfiles_storage.hashed_files self.assertNotIn(cleared_file_name, hashed_files) manifest_content = storage.staticfiles_storage.load_manifest() self.assertNotIn(cleared_file_name, manifest_content) def test_missing_entry(self): missing_file_name = "cached/missing.css" configured_storage = storage.staticfiles_storage self.assertNotIn(missing_file_name, configured_storage.hashed_files) # File name not found in manifest with self.assertRaisesMessage( ValueError, "Missing staticfiles manifest entry for '%s'" % missing_file_name, ): self.hashed_file_path(missing_file_name) configured_storage.manifest_strict = False # File doesn't exist on disk err_msg = "The file '%s' could not be found with %r." % ( missing_file_name, configured_storage._wrapped, ) with self.assertRaisesMessage(ValueError, err_msg): self.hashed_file_path(missing_file_name) content = StringIO() content.write("Found") configured_storage.save(missing_file_name, content) # File exists on disk self.hashed_file_path(missing_file_name) def test_intermediate_files(self): cached_files = os.listdir(os.path.join(settings.STATIC_ROOT, "cached")) # Intermediate files shouldn't be created for reference. self.assertEqual( len( [ cached_file for cached_file in cached_files if cached_file.startswith("relative.") ] ), 2, ) @override_settings(STATICFILES_STORAGE="staticfiles_tests.storage.NoneHashStorage") class TestCollectionNoneHashStorage(CollectionTestCase): hashed_file_path = hashed_file_path def test_hashed_name(self): relpath = self.hashed_file_path("cached/styles.css") self.assertEqual(relpath, "cached/styles.css") @override_settings( STATICFILES_STORAGE="staticfiles_tests.storage.NoPostProcessReplacedPathStorage" ) class TestCollectionNoPostProcessReplacedPaths(CollectionTestCase): run_collectstatic_in_setUp = False def test_collectstatistic_no_post_process_replaced_paths(self): stdout = StringIO() self.run_collectstatic(verbosity=1, stdout=stdout) self.assertIn("post-processed", stdout.getvalue()) @override_settings(STATICFILES_STORAGE="staticfiles_tests.storage.SimpleStorage") class TestCollectionSimpleStorage(CollectionTestCase): hashed_file_path = hashed_file_path def setUp(self): storage.staticfiles_storage.hashed_files.clear() # avoid cache interference super().setUp() def test_template_tag_return(self): self.assertStaticRaises( ValueError, "does/not/exist.png", "/static/does/not/exist.png" ) self.assertStaticRenders("test/file.txt", "/static/test/file.deploy12345.txt") self.assertStaticRenders( "cached/styles.css", "/static/cached/styles.deploy12345.css" ) self.assertStaticRenders("path/", "/static/path/") self.assertStaticRenders("path/?query", "/static/path/?query") def test_template_tag_simple_content(self): relpath = self.hashed_file_path("cached/styles.css") self.assertEqual(relpath, "cached/styles.deploy12345.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"cached/other.css", content) self.assertIn(b"other.deploy12345.css", content) class CustomManifestStorage(storage.ManifestStaticFilesStorage): def __init__(self, *args, manifest_storage=None, **kwargs): manifest_storage = storage.StaticFilesStorage( location=kwargs.pop("manifest_location"), ) super().__init__(*args, manifest_storage=manifest_storage, **kwargs) class TestCustomManifestStorage(SimpleTestCase): def setUp(self): self.manifest_path = Path(tempfile.mkdtemp()) self.addCleanup(shutil.rmtree, self.manifest_path) self.staticfiles_storage = CustomManifestStorage( manifest_location=self.manifest_path, ) self.manifest_file = self.manifest_path / self.staticfiles_storage.manifest_name # Manifest without paths. self.manifest = {"version": self.staticfiles_storage.manifest_version} with self.manifest_file.open("w") as manifest_file: json.dump(self.manifest, manifest_file) def test_read_manifest(self): self.assertEqual( self.staticfiles_storage.read_manifest(), json.dumps(self.manifest), ) def test_read_manifest_nonexistent(self): os.remove(self.manifest_file) self.assertIsNone(self.staticfiles_storage.read_manifest()) def test_save_manifest_override(self): self.assertIs(self.manifest_file.exists(), True) self.staticfiles_storage.save_manifest() self.assertIs(self.manifest_file.exists(), True) new_manifest = json.loads(self.staticfiles_storage.read_manifest()) self.assertIn("paths", new_manifest) self.assertNotEqual(new_manifest, self.manifest) def test_save_manifest_create(self): os.remove(self.manifest_file) self.staticfiles_storage.save_manifest() self.assertIs(self.manifest_file.exists(), True) new_manifest = json.loads(self.staticfiles_storage.read_manifest()) self.assertIn("paths", new_manifest) self.assertNotEqual(new_manifest, self.manifest) class CustomStaticFilesStorage(storage.StaticFilesStorage): """ Used in TestStaticFilePermissions """ def __init__(self, *args, **kwargs): kwargs["file_permissions_mode"] = 0o640 kwargs["directory_permissions_mode"] = 0o740 super().__init__(*args, **kwargs) @unittest.skipIf(sys.platform == "win32", "Windows only partially supports chmod.") class TestStaticFilePermissions(CollectionTestCase): command_params = { "interactive": False, "verbosity": 0, "ignore_patterns": ["*.ignoreme"], } def setUp(self): self.umask = 0o027 self.old_umask = os.umask(self.umask) super().setUp() def tearDown(self): os.umask(self.old_umask) super().tearDown() # Don't run collectstatic command in this test class. def run_collectstatic(self, **kwargs): pass @override_settings( FILE_UPLOAD_PERMISSIONS=0o655, FILE_UPLOAD_DIRECTORY_PERMISSIONS=0o765, ) def test_collect_static_files_permissions(self): call_command("collectstatic", **self.command_params) static_root = Path(settings.STATIC_ROOT) test_file = static_root / "test.txt" file_mode = test_file.stat().st_mode & 0o777 self.assertEqual(file_mode, 0o655) tests = [ static_root / "subdir", static_root / "nested", static_root / "nested" / "css", ] for directory in tests: with self.subTest(directory=directory): dir_mode = directory.stat().st_mode & 0o777 self.assertEqual(dir_mode, 0o765) @override_settings( FILE_UPLOAD_PERMISSIONS=None, FILE_UPLOAD_DIRECTORY_PERMISSIONS=None, ) def test_collect_static_files_default_permissions(self): call_command("collectstatic", **self.command_params) static_root = Path(settings.STATIC_ROOT) test_file = static_root / "test.txt" file_mode = test_file.stat().st_mode & 0o777 self.assertEqual(file_mode, 0o666 & ~self.umask) tests = [ static_root / "subdir", static_root / "nested", static_root / "nested" / "css", ] for directory in tests: with self.subTest(directory=directory): dir_mode = directory.stat().st_mode & 0o777 self.assertEqual(dir_mode, 0o777 & ~self.umask) @override_settings( FILE_UPLOAD_PERMISSIONS=0o655, FILE_UPLOAD_DIRECTORY_PERMISSIONS=0o765, STATICFILES_STORAGE="staticfiles_tests.test_storage.CustomStaticFilesStorage", ) def test_collect_static_files_subclass_of_static_storage(self): call_command("collectstatic", **self.command_params) static_root = Path(settings.STATIC_ROOT) test_file = static_root / "test.txt" file_mode = test_file.stat().st_mode & 0o777 self.assertEqual(file_mode, 0o640) tests = [ static_root / "subdir", static_root / "nested", static_root / "nested" / "css", ] for directory in tests: with self.subTest(directory=directory): dir_mode = directory.stat().st_mode & 0o777 self.assertEqual(dir_mode, 0o740) @override_settings( STATICFILES_STORAGE="django.contrib.staticfiles.storage.ManifestStaticFilesStorage", ) class TestCollectionHashedFilesCache(CollectionTestCase): """ Files referenced from CSS use the correct final hashed name regardless of the order in which the files are post-processed. """ hashed_file_path = hashed_file_path def setUp(self): super().setUp() self._temp_dir = temp_dir = tempfile.mkdtemp() os.makedirs(os.path.join(temp_dir, "test")) self.addCleanup(shutil.rmtree, temp_dir) def _get_filename_path(self, filename): return os.path.join(self._temp_dir, "test", filename) def test_file_change_after_collectstatic(self): # Create initial static files. file_contents = ( ("foo.png", "foo"), ("bar.css", 'url("foo.png")\nurl("xyz.png")'), ("xyz.png", "xyz"), ) for filename, content in file_contents: with open(self._get_filename_path(filename), "w") as f: f.write(content) with self.modify_settings(STATICFILES_DIRS={"append": self._temp_dir}): finders.get_finder.cache_clear() err = StringIO() # First collectstatic run. call_command("collectstatic", interactive=False, verbosity=0, stderr=err) relpath = self.hashed_file_path("test/bar.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertIn(b"foo.acbd18db4cc2.png", content) self.assertIn(b"xyz.d16fb36f0911.png", content) # Change the contents of the png files. for filename in ("foo.png", "xyz.png"): with open(self._get_filename_path(filename), "w+b") as f: f.write(b"new content of file to change its hash") # The hashes of the png files in the CSS file are updated after # a second collectstatic. call_command("collectstatic", interactive=False, verbosity=0, stderr=err) relpath = self.hashed_file_path("test/bar.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertIn(b"foo.57a5cb9ba68d.png", content) self.assertIn(b"xyz.57a5cb9ba68d.png", content)
09963ad9cb25a1f533f63c830f3a332a80c4fca80fb6b24190deb4098d6c5cae
import os from datetime import datetime, timedelta from django.conf import settings from django.contrib.staticfiles.storage import ManifestStaticFilesStorage from django.core.files import storage from django.utils import timezone class DummyStorage(storage.Storage): """ A storage class that implements get_modified_time() but raises NotImplementedError for path(). """ def _save(self, name, content): return "dummy" def delete(self, name): pass def exists(self, name): pass def get_modified_time(self, name): return datetime(1970, 1, 1, tzinfo=timezone.utc) class PathNotImplementedStorage(storage.Storage): def _save(self, name, content): return "dummy" def _path(self, name): return os.path.join(settings.STATIC_ROOT, name) 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: if entry.is_dir(): directories.append(entry.name) else: files.append(entry.name) return directories, files def delete(self, name): name = self._path(name) try: os.remove(name) except FileNotFoundError: pass def path(self, name): raise NotImplementedError class NeverCopyRemoteStorage(PathNotImplementedStorage): """ Return a future modified time for all files so that nothing is collected. """ def get_modified_time(self, name): return datetime.now() + timedelta(days=30) class QueryStringStorage(storage.Storage): def url(self, path): return path + "?a=b&c=d" class SimpleStorage(ManifestStaticFilesStorage): def file_hash(self, name, content=None): return "deploy12345" class ExtraPatternsStorage(ManifestStaticFilesStorage): """ A storage class to test pattern substitutions with more than one pattern entry. The added pattern rewrites strings like "url(...)" to JS_URL("..."). """ patterns = tuple(ManifestStaticFilesStorage.patterns) + ( ( "*.js", ( ( r"""(?P<matched>url\(['"]{0,1}\s*(?P<url>.*?)["']{0,1}\))""", 'JS_URL("%(url)s")', ), ), ), ) class NoneHashStorage(ManifestStaticFilesStorage): def file_hash(self, name, content=None): return None class NoPostProcessReplacedPathStorage(ManifestStaticFilesStorage): max_post_process_passes = 0
347165d1a4b7cd40a3b251619e312842c79f6eb25992740a6ad51940cc5b56d8
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.assertStaticRenders("testfile.txt", "/static/testfile.txt") self.assertStaticRenders( "special?chars&quoted.html", "/static/special%3Fchars%26quoted.html" ) @override_settings( STATICFILES_STORAGE="staticfiles_tests.storage.QueryStringStorage" ) def test_template_tag_escapes(self): """ 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&amp;c=d") self.assertStaticRenders("a.html", "a.html?a=b&c=d", autoescape=False)
37a00cd74b01933996b2670dd9e5b12acf9e4599fe5967a8bb4a1dd78b32c903
import unittest from datetime import date, datetime, time, timedelta from decimal import Decimal from operator import attrgetter, itemgetter from uuid import UUID from django.core.exceptions import FieldError from django.db import connection from django.db.models import ( BinaryField, BooleanField, Case, Count, DecimalField, F, GenericIPAddressField, IntegerField, Max, Min, Q, Sum, TextField, Value, When, ) from django.test import SimpleTestCase, TestCase from .models import CaseTestModel, Client, FKCaseTestModel, O2OCaseTestModel try: from PIL import Image except ImportError: Image = None class CaseExpressionTests(TestCase): @classmethod def setUpTestData(cls): o = CaseTestModel.objects.create(integer=1, integer2=1, string="1") O2OCaseTestModel.objects.create(o2o=o, integer=1) FKCaseTestModel.objects.create(fk=o, integer=1) o = CaseTestModel.objects.create(integer=2, integer2=3, string="2") O2OCaseTestModel.objects.create(o2o=o, integer=2) FKCaseTestModel.objects.create(fk=o, integer=2) FKCaseTestModel.objects.create(fk=o, integer=3) o = CaseTestModel.objects.create(integer=3, integer2=4, string="3") O2OCaseTestModel.objects.create(o2o=o, integer=3) FKCaseTestModel.objects.create(fk=o, integer=3) FKCaseTestModel.objects.create(fk=o, integer=4) o = CaseTestModel.objects.create(integer=2, integer2=2, string="2") O2OCaseTestModel.objects.create(o2o=o, integer=2) FKCaseTestModel.objects.create(fk=o, integer=2) FKCaseTestModel.objects.create(fk=o, integer=3) o = CaseTestModel.objects.create(integer=3, integer2=4, string="3") O2OCaseTestModel.objects.create(o2o=o, integer=3) FKCaseTestModel.objects.create(fk=o, integer=3) FKCaseTestModel.objects.create(fk=o, integer=4) o = CaseTestModel.objects.create(integer=3, integer2=3, string="3") O2OCaseTestModel.objects.create(o2o=o, integer=3) FKCaseTestModel.objects.create(fk=o, integer=3) FKCaseTestModel.objects.create(fk=o, integer=4) o = CaseTestModel.objects.create(integer=4, integer2=5, string="4") O2OCaseTestModel.objects.create(o2o=o, integer=1) FKCaseTestModel.objects.create(fk=o, integer=5) cls.group_by_fields = [ f.name for f in CaseTestModel._meta.get_fields() if not (f.is_relation and f.auto_created) and ( connection.features.allows_group_by_lob or not isinstance(f, (BinaryField, TextField)) ) ] def test_annotate(self): self.assertQuerysetEqual( CaseTestModel.objects.annotate( test=Case( When(integer=1, then=Value("one")), When(integer=2, then=Value("two")), default=Value("other"), ) ).order_by("pk"), [ (1, "one"), (2, "two"), (3, "other"), (2, "two"), (3, "other"), (3, "other"), (4, "other"), ], transform=attrgetter("integer", "test"), ) def test_annotate_without_default(self): self.assertQuerysetEqual( CaseTestModel.objects.annotate( test=Case( When(integer=1, then=1), When(integer=2, then=2), ) ).order_by("pk"), [(1, 1), (2, 2), (3, None), (2, 2), (3, None), (3, None), (4, None)], transform=attrgetter("integer", "test"), ) def test_annotate_with_expression_as_value(self): self.assertQuerysetEqual( CaseTestModel.objects.annotate( f_test=Case( When(integer=1, then=F("integer") + 1), When(integer=2, then=F("integer") + 3), default="integer", ) ).order_by("pk"), [(1, 2), (2, 5), (3, 3), (2, 5), (3, 3), (3, 3), (4, 4)], transform=attrgetter("integer", "f_test"), ) def test_annotate_with_expression_as_condition(self): self.assertQuerysetEqual( CaseTestModel.objects.annotate( f_test=Case( When(integer2=F("integer"), then=Value("equal")), When(integer2=F("integer") + 1, then=Value("+1")), ) ).order_by("pk"), [ (1, "equal"), (2, "+1"), (3, "+1"), (2, "equal"), (3, "+1"), (3, "equal"), (4, "+1"), ], transform=attrgetter("integer", "f_test"), ) def test_annotate_with_join_in_value(self): self.assertQuerysetEqual( CaseTestModel.objects.annotate( join_test=Case( When(integer=1, then=F("o2o_rel__integer") + 1), When(integer=2, then=F("o2o_rel__integer") + 3), default="o2o_rel__integer", ) ).order_by("pk"), [(1, 2), (2, 5), (3, 3), (2, 5), (3, 3), (3, 3), (4, 1)], transform=attrgetter("integer", "join_test"), ) def test_annotate_with_in_clause(self): fk_rels = FKCaseTestModel.objects.filter(integer__in=[5]) self.assertQuerysetEqual( CaseTestModel.objects.only("pk", "integer") .annotate( in_test=Sum( Case( When(fk_rel__in=fk_rels, then=F("fk_rel__integer")), default=Value(0), ) ) ) .order_by("pk"), [(1, 0), (2, 0), (3, 0), (2, 0), (3, 0), (3, 0), (4, 5)], transform=attrgetter("integer", "in_test"), ) def test_annotate_with_join_in_condition(self): self.assertQuerysetEqual( CaseTestModel.objects.annotate( join_test=Case( When(integer2=F("o2o_rel__integer"), then=Value("equal")), When(integer2=F("o2o_rel__integer") + 1, then=Value("+1")), default=Value("other"), ) ).order_by("pk"), [ (1, "equal"), (2, "+1"), (3, "+1"), (2, "equal"), (3, "+1"), (3, "equal"), (4, "other"), ], transform=attrgetter("integer", "join_test"), ) def test_annotate_with_join_in_predicate(self): self.assertQuerysetEqual( CaseTestModel.objects.annotate( join_test=Case( When(o2o_rel__integer=1, then=Value("one")), When(o2o_rel__integer=2, then=Value("two")), When(o2o_rel__integer=3, then=Value("three")), default=Value("other"), ) ).order_by("pk"), [ (1, "one"), (2, "two"), (3, "three"), (2, "two"), (3, "three"), (3, "three"), (4, "one"), ], transform=attrgetter("integer", "join_test"), ) def test_annotate_with_annotation_in_value(self): self.assertQuerysetEqual( CaseTestModel.objects.annotate( f_plus_1=F("integer") + 1, f_plus_3=F("integer") + 3, ) .annotate( f_test=Case( When(integer=1, then="f_plus_1"), When(integer=2, then="f_plus_3"), default="integer", ), ) .order_by("pk"), [(1, 2), (2, 5), (3, 3), (2, 5), (3, 3), (3, 3), (4, 4)], transform=attrgetter("integer", "f_test"), ) def test_annotate_with_annotation_in_condition(self): self.assertQuerysetEqual( CaseTestModel.objects.annotate( f_plus_1=F("integer") + 1, ) .annotate( f_test=Case( When(integer2=F("integer"), then=Value("equal")), When(integer2=F("f_plus_1"), then=Value("+1")), ), ) .order_by("pk"), [ (1, "equal"), (2, "+1"), (3, "+1"), (2, "equal"), (3, "+1"), (3, "equal"), (4, "+1"), ], transform=attrgetter("integer", "f_test"), ) def test_annotate_with_annotation_in_predicate(self): self.assertQuerysetEqual( CaseTestModel.objects.annotate( f_minus_2=F("integer") - 2, ) .annotate( test=Case( When(f_minus_2=-1, then=Value("negative one")), When(f_minus_2=0, then=Value("zero")), When(f_minus_2=1, then=Value("one")), default=Value("other"), ), ) .order_by("pk"), [ (1, "negative one"), (2, "zero"), (3, "one"), (2, "zero"), (3, "one"), (3, "one"), (4, "other"), ], transform=attrgetter("integer", "test"), ) def test_annotate_with_aggregation_in_value(self): self.assertQuerysetEqual( CaseTestModel.objects.values(*self.group_by_fields) .annotate( min=Min("fk_rel__integer"), max=Max("fk_rel__integer"), ) .annotate( test=Case( When(integer=2, then="min"), When(integer=3, then="max"), ), ) .order_by("pk"), [ (1, None, 1, 1), (2, 2, 2, 3), (3, 4, 3, 4), (2, 2, 2, 3), (3, 4, 3, 4), (3, 4, 3, 4), (4, None, 5, 5), ], transform=itemgetter("integer", "test", "min", "max"), ) def test_annotate_with_aggregation_in_condition(self): self.assertQuerysetEqual( CaseTestModel.objects.values(*self.group_by_fields) .annotate( min=Min("fk_rel__integer"), max=Max("fk_rel__integer"), ) .annotate( test=Case( When(integer2=F("min"), then=Value("min")), When(integer2=F("max"), then=Value("max")), ), ) .order_by("pk"), [ (1, 1, "min"), (2, 3, "max"), (3, 4, "max"), (2, 2, "min"), (3, 4, "max"), (3, 3, "min"), (4, 5, "min"), ], transform=itemgetter("integer", "integer2", "test"), ) def test_annotate_with_aggregation_in_predicate(self): self.assertQuerysetEqual( CaseTestModel.objects.values(*self.group_by_fields) .annotate( max=Max("fk_rel__integer"), ) .annotate( test=Case( When(max=3, then=Value("max = 3")), When(max=4, then=Value("max = 4")), default=Value(""), ), ) .order_by("pk"), [ (1, 1, ""), (2, 3, "max = 3"), (3, 4, "max = 4"), (2, 3, "max = 3"), (3, 4, "max = 4"), (3, 4, "max = 4"), (4, 5, ""), ], transform=itemgetter("integer", "max", "test"), ) def test_annotate_exclude(self): self.assertQuerysetEqual( CaseTestModel.objects.annotate( test=Case( When(integer=1, then=Value("one")), When(integer=2, then=Value("two")), default=Value("other"), ) ) .exclude(test="other") .order_by("pk"), [(1, "one"), (2, "two"), (2, "two")], transform=attrgetter("integer", "test"), ) def test_annotate_filter_decimal(self): obj = CaseTestModel.objects.create(integer=0, decimal=Decimal("1")) qs = CaseTestModel.objects.annotate( x=Case(When(integer=0, then=F("decimal"))), y=Case(When(integer=0, then=Value(Decimal("1")))), ) self.assertSequenceEqual(qs.filter(Q(x=1) & Q(x=Decimal("1"))), [obj]) self.assertSequenceEqual(qs.filter(Q(y=1) & Q(y=Decimal("1"))), [obj]) def test_annotate_values_not_in_order_by(self): self.assertEqual( list( CaseTestModel.objects.annotate( test=Case( When(integer=1, then=Value("one")), When(integer=2, then=Value("two")), When(integer=3, then=Value("three")), default=Value("other"), ) ) .order_by("test") .values_list("integer", flat=True) ), [1, 4, 3, 3, 3, 2, 2], ) def test_annotate_with_empty_when(self): objects = CaseTestModel.objects.annotate( selected=Case( When(pk__in=[], then=Value("selected")), default=Value("not selected"), ) ) self.assertEqual(len(objects), CaseTestModel.objects.count()) self.assertTrue(all(obj.selected == "not selected" for obj in objects)) def test_combined_expression(self): self.assertQuerysetEqual( CaseTestModel.objects.annotate( test=Case( When(integer=1, then=2), When(integer=2, then=1), default=3, ) + 1, ).order_by("pk"), [(1, 3), (2, 2), (3, 4), (2, 2), (3, 4), (3, 4), (4, 4)], transform=attrgetter("integer", "test"), ) def test_in_subquery(self): self.assertQuerysetEqual( CaseTestModel.objects.filter( pk__in=CaseTestModel.objects.annotate( test=Case( When(integer=F("integer2"), then="pk"), When(integer=4, then="pk"), ), ).values("test") ).order_by("pk"), [(1, 1), (2, 2), (3, 3), (4, 5)], transform=attrgetter("integer", "integer2"), ) def test_condition_with_lookups(self): qs = CaseTestModel.objects.annotate( test=Case( When(Q(integer2=1), string="2", then=Value(False)), When(Q(integer2=1), string="1", then=Value(True)), default=Value(False), output_field=BooleanField(), ), ) self.assertIs(qs.get(integer=1).test, True) def test_case_reuse(self): SOME_CASE = Case( When(pk=0, then=Value("0")), default=Value("1"), ) self.assertQuerysetEqual( CaseTestModel.objects.annotate(somecase=SOME_CASE).order_by("pk"), CaseTestModel.objects.annotate(somecase=SOME_CASE) .order_by("pk") .values_list("pk", "somecase"), lambda x: (x.pk, x.somecase), ) def test_aggregate(self): self.assertEqual( CaseTestModel.objects.aggregate( one=Sum( Case( When(integer=1, then=1), ) ), two=Sum( Case( When(integer=2, then=1), ) ), three=Sum( Case( When(integer=3, then=1), ) ), four=Sum( Case( When(integer=4, then=1), ) ), ), {"one": 1, "two": 2, "three": 3, "four": 1}, ) def test_aggregate_with_expression_as_value(self): self.assertEqual( CaseTestModel.objects.aggregate( one=Sum(Case(When(integer=1, then="integer"))), two=Sum(Case(When(integer=2, then=F("integer") - 1))), three=Sum(Case(When(integer=3, then=F("integer") + 1))), ), {"one": 1, "two": 2, "three": 12}, ) def test_aggregate_with_expression_as_condition(self): self.assertEqual( CaseTestModel.objects.aggregate( equal=Sum( Case( When(integer2=F("integer"), then=1), ) ), plus_one=Sum( Case( When(integer2=F("integer") + 1, then=1), ) ), ), {"equal": 3, "plus_one": 4}, ) def test_filter(self): self.assertQuerysetEqual( CaseTestModel.objects.filter( integer2=Case( When(integer=2, then=3), When(integer=3, then=4), default=1, ) ).order_by("pk"), [(1, 1), (2, 3), (3, 4), (3, 4)], transform=attrgetter("integer", "integer2"), ) def test_filter_without_default(self): self.assertQuerysetEqual( CaseTestModel.objects.filter( integer2=Case( When(integer=2, then=3), When(integer=3, then=4), ) ).order_by("pk"), [(2, 3), (3, 4), (3, 4)], transform=attrgetter("integer", "integer2"), ) def test_filter_with_expression_as_value(self): self.assertQuerysetEqual( CaseTestModel.objects.filter( integer2=Case( When(integer=2, then=F("integer") + 1), When(integer=3, then=F("integer")), default="integer", ) ).order_by("pk"), [(1, 1), (2, 3), (3, 3)], transform=attrgetter("integer", "integer2"), ) def test_filter_with_expression_as_condition(self): self.assertQuerysetEqual( CaseTestModel.objects.filter( string=Case( When(integer2=F("integer"), then=Value("2")), When(integer2=F("integer") + 1, then=Value("3")), ) ).order_by("pk"), [(3, 4, "3"), (2, 2, "2"), (3, 4, "3")], transform=attrgetter("integer", "integer2", "string"), ) def test_filter_with_join_in_value(self): self.assertQuerysetEqual( CaseTestModel.objects.filter( integer2=Case( When(integer=2, then=F("o2o_rel__integer") + 1), When(integer=3, then=F("o2o_rel__integer")), default="o2o_rel__integer", ) ).order_by("pk"), [(1, 1), (2, 3), (3, 3)], transform=attrgetter("integer", "integer2"), ) def test_filter_with_join_in_condition(self): self.assertQuerysetEqual( CaseTestModel.objects.filter( integer=Case( When(integer2=F("o2o_rel__integer") + 1, then=2), When(integer2=F("o2o_rel__integer"), then=3), ) ).order_by("pk"), [(2, 3), (3, 3)], transform=attrgetter("integer", "integer2"), ) def test_filter_with_join_in_predicate(self): self.assertQuerysetEqual( CaseTestModel.objects.filter( integer2=Case( When(o2o_rel__integer=1, then=1), When(o2o_rel__integer=2, then=3), When(o2o_rel__integer=3, then=4), ) ).order_by("pk"), [(1, 1), (2, 3), (3, 4), (3, 4)], transform=attrgetter("integer", "integer2"), ) def test_filter_with_annotation_in_value(self): self.assertQuerysetEqual( CaseTestModel.objects.annotate( f=F("integer"), f_plus_1=F("integer") + 1, ) .filter( integer2=Case( When(integer=2, then="f_plus_1"), When(integer=3, then="f"), ), ) .order_by("pk"), [(2, 3), (3, 3)], transform=attrgetter("integer", "integer2"), ) def test_filter_with_annotation_in_condition(self): self.assertQuerysetEqual( CaseTestModel.objects.annotate( f_plus_1=F("integer") + 1, ) .filter( integer=Case( When(integer2=F("integer"), then=2), When(integer2=F("f_plus_1"), then=3), ), ) .order_by("pk"), [(3, 4), (2, 2), (3, 4)], transform=attrgetter("integer", "integer2"), ) def test_filter_with_annotation_in_predicate(self): self.assertQuerysetEqual( CaseTestModel.objects.annotate( f_plus_1=F("integer") + 1, ) .filter( integer2=Case( When(f_plus_1=3, then=3), When(f_plus_1=4, then=4), default=1, ), ) .order_by("pk"), [(1, 1), (2, 3), (3, 4), (3, 4)], transform=attrgetter("integer", "integer2"), ) def test_filter_with_aggregation_in_value(self): self.assertQuerysetEqual( CaseTestModel.objects.values(*self.group_by_fields) .annotate( min=Min("fk_rel__integer"), max=Max("fk_rel__integer"), ) .filter( integer2=Case( When(integer=2, then="min"), When(integer=3, then="max"), ), ) .order_by("pk"), [(3, 4, 3, 4), (2, 2, 2, 3), (3, 4, 3, 4)], transform=itemgetter("integer", "integer2", "min", "max"), ) def test_filter_with_aggregation_in_condition(self): self.assertQuerysetEqual( CaseTestModel.objects.values(*self.group_by_fields) .annotate( min=Min("fk_rel__integer"), max=Max("fk_rel__integer"), ) .filter( integer=Case( When(integer2=F("min"), then=2), When(integer2=F("max"), then=3), ), ) .order_by("pk"), [(3, 4, 3, 4), (2, 2, 2, 3), (3, 4, 3, 4)], transform=itemgetter("integer", "integer2", "min", "max"), ) def test_filter_with_aggregation_in_predicate(self): self.assertQuerysetEqual( CaseTestModel.objects.values(*self.group_by_fields) .annotate( max=Max("fk_rel__integer"), ) .filter( integer=Case( When(max=3, then=2), When(max=4, then=3), ), ) .order_by("pk"), [(2, 3, 3), (3, 4, 4), (2, 2, 3), (3, 4, 4), (3, 3, 4)], transform=itemgetter("integer", "integer2", "max"), ) def test_update(self): CaseTestModel.objects.update( string=Case( When(integer=1, then=Value("one")), When(integer=2, then=Value("two")), default=Value("other"), ), ) self.assertQuerysetEqual( CaseTestModel.objects.order_by("pk"), [ (1, "one"), (2, "two"), (3, "other"), (2, "two"), (3, "other"), (3, "other"), (4, "other"), ], transform=attrgetter("integer", "string"), ) def test_update_without_default(self): CaseTestModel.objects.update( integer2=Case( When(integer=1, then=1), When(integer=2, then=2), ), ) self.assertQuerysetEqual( CaseTestModel.objects.order_by("pk"), [(1, 1), (2, 2), (3, None), (2, 2), (3, None), (3, None), (4, None)], transform=attrgetter("integer", "integer2"), ) def test_update_with_expression_as_value(self): CaseTestModel.objects.update( integer=Case( When(integer=1, then=F("integer") + 1), When(integer=2, then=F("integer") + 3), default="integer", ), ) self.assertQuerysetEqual( CaseTestModel.objects.order_by("pk"), [("1", 2), ("2", 5), ("3", 3), ("2", 5), ("3", 3), ("3", 3), ("4", 4)], transform=attrgetter("string", "integer"), ) def test_update_with_expression_as_condition(self): CaseTestModel.objects.update( string=Case( When(integer2=F("integer"), then=Value("equal")), When(integer2=F("integer") + 1, then=Value("+1")), ), ) self.assertQuerysetEqual( CaseTestModel.objects.order_by("pk"), [ (1, "equal"), (2, "+1"), (3, "+1"), (2, "equal"), (3, "+1"), (3, "equal"), (4, "+1"), ], transform=attrgetter("integer", "string"), ) def test_update_with_join_in_condition_raise_field_error(self): with self.assertRaisesMessage( FieldError, "Joined field references are not permitted in this query" ): CaseTestModel.objects.update( integer=Case( When(integer2=F("o2o_rel__integer") + 1, then=2), When(integer2=F("o2o_rel__integer"), then=3), ), ) def test_update_with_join_in_predicate_raise_field_error(self): with self.assertRaisesMessage( FieldError, "Joined field references are not permitted in this query" ): CaseTestModel.objects.update( string=Case( When(o2o_rel__integer=1, then=Value("one")), When(o2o_rel__integer=2, then=Value("two")), When(o2o_rel__integer=3, then=Value("three")), default=Value("other"), ), ) def test_update_big_integer(self): CaseTestModel.objects.update( big_integer=Case( When(integer=1, then=1), When(integer=2, then=2), ), ) self.assertQuerysetEqual( CaseTestModel.objects.order_by("pk"), [(1, 1), (2, 2), (3, None), (2, 2), (3, None), (3, None), (4, None)], transform=attrgetter("integer", "big_integer"), ) def test_update_binary(self): CaseTestModel.objects.update( binary=Case( When(integer=1, then=b"one"), When(integer=2, then=b"two"), default=b"", ), ) self.assertQuerysetEqual( CaseTestModel.objects.order_by("pk"), [ (1, b"one"), (2, b"two"), (3, b""), (2, b"two"), (3, b""), (3, b""), (4, b""), ], transform=lambda o: (o.integer, bytes(o.binary)), ) def test_update_boolean(self): CaseTestModel.objects.update( boolean=Case( When(integer=1, then=True), When(integer=2, then=True), default=False, ), ) self.assertQuerysetEqual( CaseTestModel.objects.order_by("pk"), [ (1, True), (2, True), (3, False), (2, True), (3, False), (3, False), (4, False), ], transform=attrgetter("integer", "boolean"), ) def test_update_date(self): CaseTestModel.objects.update( date=Case( When(integer=1, then=date(2015, 1, 1)), When(integer=2, then=date(2015, 1, 2)), ), ) self.assertQuerysetEqual( CaseTestModel.objects.order_by("pk"), [ (1, date(2015, 1, 1)), (2, date(2015, 1, 2)), (3, None), (2, date(2015, 1, 2)), (3, None), (3, None), (4, None), ], transform=attrgetter("integer", "date"), ) def test_update_date_time(self): CaseTestModel.objects.update( date_time=Case( When(integer=1, then=datetime(2015, 1, 1)), When(integer=2, then=datetime(2015, 1, 2)), ), ) self.assertQuerysetEqual( CaseTestModel.objects.order_by("pk"), [ (1, datetime(2015, 1, 1)), (2, datetime(2015, 1, 2)), (3, None), (2, datetime(2015, 1, 2)), (3, None), (3, None), (4, None), ], transform=attrgetter("integer", "date_time"), ) def test_update_decimal(self): CaseTestModel.objects.update( decimal=Case( When(integer=1, then=Decimal("1.1")), When( integer=2, then=Value(Decimal("2.2"), output_field=DecimalField()) ), ), ) self.assertQuerysetEqual( CaseTestModel.objects.order_by("pk"), [ (1, Decimal("1.1")), (2, Decimal("2.2")), (3, None), (2, Decimal("2.2")), (3, None), (3, None), (4, None), ], transform=attrgetter("integer", "decimal"), ) def test_update_duration(self): CaseTestModel.objects.update( duration=Case( When(integer=1, then=timedelta(1)), When(integer=2, then=timedelta(2)), ), ) self.assertQuerysetEqual( CaseTestModel.objects.order_by("pk"), [ (1, timedelta(1)), (2, timedelta(2)), (3, None), (2, timedelta(2)), (3, None), (3, None), (4, None), ], transform=attrgetter("integer", "duration"), ) def test_update_email(self): CaseTestModel.objects.update( email=Case( When(integer=1, then=Value("[email protected]")), When(integer=2, then=Value("[email protected]")), default=Value(""), ), ) self.assertQuerysetEqual( CaseTestModel.objects.order_by("pk"), [ (1, "[email protected]"), (2, "[email protected]"), (3, ""), (2, "[email protected]"), (3, ""), (3, ""), (4, ""), ], transform=attrgetter("integer", "email"), ) def test_update_file(self): CaseTestModel.objects.update( file=Case( When(integer=1, then=Value("~/1")), When(integer=2, then=Value("~/2")), ), ) self.assertQuerysetEqual( CaseTestModel.objects.order_by("pk"), [(1, "~/1"), (2, "~/2"), (3, ""), (2, "~/2"), (3, ""), (3, ""), (4, "")], transform=lambda o: (o.integer, str(o.file)), ) def test_update_file_path(self): CaseTestModel.objects.update( file_path=Case( When(integer=1, then=Value("~/1")), When(integer=2, then=Value("~/2")), default=Value(""), ), ) self.assertQuerysetEqual( CaseTestModel.objects.order_by("pk"), [(1, "~/1"), (2, "~/2"), (3, ""), (2, "~/2"), (3, ""), (3, ""), (4, "")], transform=attrgetter("integer", "file_path"), ) def test_update_float(self): CaseTestModel.objects.update( float=Case( When(integer=1, then=1.1), When(integer=2, then=2.2), ), ) self.assertQuerysetEqual( CaseTestModel.objects.order_by("pk"), [(1, 1.1), (2, 2.2), (3, None), (2, 2.2), (3, None), (3, None), (4, None)], transform=attrgetter("integer", "float"), ) @unittest.skipUnless(Image, "Pillow not installed") def test_update_image(self): CaseTestModel.objects.update( image=Case( When(integer=1, then=Value("~/1")), When(integer=2, then=Value("~/2")), ), ) self.assertQuerysetEqual( CaseTestModel.objects.order_by("pk"), [(1, "~/1"), (2, "~/2"), (3, ""), (2, "~/2"), (3, ""), (3, ""), (4, "")], transform=lambda o: (o.integer, str(o.image)), ) def test_update_generic_ip_address(self): CaseTestModel.objects.update( generic_ip_address=Case( When(integer=1, then=Value("1.1.1.1")), When(integer=2, then=Value("2.2.2.2")), output_field=GenericIPAddressField(), ), ) self.assertQuerysetEqual( CaseTestModel.objects.order_by("pk"), [ (1, "1.1.1.1"), (2, "2.2.2.2"), (3, None), (2, "2.2.2.2"), (3, None), (3, None), (4, None), ], transform=attrgetter("integer", "generic_ip_address"), ) def test_update_null_boolean(self): CaseTestModel.objects.update( null_boolean=Case( When(integer=1, then=True), When(integer=2, then=False), ), ) self.assertQuerysetEqual( CaseTestModel.objects.order_by("pk"), [ (1, True), (2, False), (3, None), (2, False), (3, None), (3, None), (4, None), ], transform=attrgetter("integer", "null_boolean"), ) def test_update_positive_big_integer(self): CaseTestModel.objects.update( positive_big_integer=Case( When(integer=1, then=1), When(integer=2, then=2), ), ) self.assertQuerysetEqual( CaseTestModel.objects.order_by("pk"), [(1, 1), (2, 2), (3, None), (2, 2), (3, None), (3, None), (4, None)], transform=attrgetter("integer", "positive_big_integer"), ) def test_update_positive_integer(self): CaseTestModel.objects.update( positive_integer=Case( When(integer=1, then=1), When(integer=2, then=2), ), ) self.assertQuerysetEqual( CaseTestModel.objects.order_by("pk"), [(1, 1), (2, 2), (3, None), (2, 2), (3, None), (3, None), (4, None)], transform=attrgetter("integer", "positive_integer"), ) def test_update_positive_small_integer(self): CaseTestModel.objects.update( positive_small_integer=Case( When(integer=1, then=1), When(integer=2, then=2), ), ) self.assertQuerysetEqual( CaseTestModel.objects.order_by("pk"), [(1, 1), (2, 2), (3, None), (2, 2), (3, None), (3, None), (4, None)], transform=attrgetter("integer", "positive_small_integer"), ) def test_update_slug(self): CaseTestModel.objects.update( slug=Case( When(integer=1, then=Value("1")), When(integer=2, then=Value("2")), default=Value(""), ), ) self.assertQuerysetEqual( CaseTestModel.objects.order_by("pk"), [(1, "1"), (2, "2"), (3, ""), (2, "2"), (3, ""), (3, ""), (4, "")], transform=attrgetter("integer", "slug"), ) def test_update_small_integer(self): CaseTestModel.objects.update( small_integer=Case( When(integer=1, then=1), When(integer=2, then=2), ), ) self.assertQuerysetEqual( CaseTestModel.objects.order_by("pk"), [(1, 1), (2, 2), (3, None), (2, 2), (3, None), (3, None), (4, None)], transform=attrgetter("integer", "small_integer"), ) def test_update_string(self): CaseTestModel.objects.filter(string__in=["1", "2"]).update( string=Case( When(integer=1, then=Value("1")), When(integer=2, then=Value("2")), ), ) self.assertQuerysetEqual( CaseTestModel.objects.filter(string__in=["1", "2"]).order_by("pk"), [(1, "1"), (2, "2"), (2, "2")], transform=attrgetter("integer", "string"), ) def test_update_text(self): CaseTestModel.objects.update( text=Case( When(integer=1, then=Value("1")), When(integer=2, then=Value("2")), default=Value(""), ), ) self.assertQuerysetEqual( CaseTestModel.objects.order_by("pk"), [(1, "1"), (2, "2"), (3, ""), (2, "2"), (3, ""), (3, ""), (4, "")], transform=attrgetter("integer", "text"), ) def test_update_time(self): CaseTestModel.objects.update( time=Case( When(integer=1, then=time(1)), When(integer=2, then=time(2)), ), ) self.assertQuerysetEqual( CaseTestModel.objects.order_by("pk"), [ (1, time(1)), (2, time(2)), (3, None), (2, time(2)), (3, None), (3, None), (4, None), ], transform=attrgetter("integer", "time"), ) def test_update_url(self): CaseTestModel.objects.update( url=Case( When(integer=1, then=Value("http://1.example.com/")), When(integer=2, then=Value("http://2.example.com/")), default=Value(""), ), ) self.assertQuerysetEqual( CaseTestModel.objects.order_by("pk"), [ (1, "http://1.example.com/"), (2, "http://2.example.com/"), (3, ""), (2, "http://2.example.com/"), (3, ""), (3, ""), (4, ""), ], transform=attrgetter("integer", "url"), ) def test_update_uuid(self): CaseTestModel.objects.update( uuid=Case( When(integer=1, then=UUID("11111111111111111111111111111111")), When(integer=2, then=UUID("22222222222222222222222222222222")), ), ) self.assertQuerysetEqual( CaseTestModel.objects.order_by("pk"), [ (1, UUID("11111111111111111111111111111111")), (2, UUID("22222222222222222222222222222222")), (3, None), (2, UUID("22222222222222222222222222222222")), (3, None), (3, None), (4, None), ], transform=attrgetter("integer", "uuid"), ) def test_update_fk(self): obj1, obj2 = CaseTestModel.objects.all()[:2] CaseTestModel.objects.update( fk=Case( When(integer=1, then=obj1.pk), When(integer=2, then=obj2.pk), ), ) self.assertQuerysetEqual( CaseTestModel.objects.order_by("pk"), [ (1, obj1.pk), (2, obj2.pk), (3, None), (2, obj2.pk), (3, None), (3, None), (4, None), ], transform=attrgetter("integer", "fk_id"), ) def test_lookup_in_condition(self): self.assertQuerysetEqual( CaseTestModel.objects.annotate( test=Case( When(integer__lt=2, then=Value("less than 2")), When(integer__gt=2, then=Value("greater than 2")), default=Value("equal to 2"), ), ).order_by("pk"), [ (1, "less than 2"), (2, "equal to 2"), (3, "greater than 2"), (2, "equal to 2"), (3, "greater than 2"), (3, "greater than 2"), (4, "greater than 2"), ], transform=attrgetter("integer", "test"), ) def test_lookup_different_fields(self): self.assertQuerysetEqual( CaseTestModel.objects.annotate( test=Case( When(integer=2, integer2=3, then=Value("when")), default=Value("default"), ), ).order_by("pk"), [ (1, 1, "default"), (2, 3, "when"), (3, 4, "default"), (2, 2, "default"), (3, 4, "default"), (3, 3, "default"), (4, 5, "default"), ], transform=attrgetter("integer", "integer2", "test"), ) def test_combined_q_object(self): self.assertQuerysetEqual( CaseTestModel.objects.annotate( test=Case( When(Q(integer=2) | Q(integer2=3), then=Value("when")), default=Value("default"), ), ).order_by("pk"), [ (1, 1, "default"), (2, 3, "when"), (3, 4, "default"), (2, 2, "when"), (3, 4, "default"), (3, 3, "when"), (4, 5, "default"), ], transform=attrgetter("integer", "integer2", "test"), ) def test_order_by_conditional_implicit(self): self.assertQuerysetEqual( CaseTestModel.objects.filter(integer__lte=2) .annotate( test=Case( When(integer=1, then=2), When(integer=2, then=1), default=3, ) ) .order_by("test", "pk"), [(2, 1), (2, 1), (1, 2)], transform=attrgetter("integer", "test"), ) def test_order_by_conditional_explicit(self): self.assertQuerysetEqual( CaseTestModel.objects.filter(integer__lte=2) .annotate( test=Case( When(integer=1, then=2), When(integer=2, then=1), default=3, ) ) .order_by(F("test").asc(), "pk"), [(2, 1), (2, 1), (1, 2)], transform=attrgetter("integer", "test"), ) def test_join_promotion(self): o = CaseTestModel.objects.create(integer=1, integer2=1, string="1") # Testing that: # 1. There isn't any object on the remote side of the fk_rel # relation. If the query used inner joins, then the join to fk_rel # would remove o from the results. So, in effect we are testing that # we are promoting the fk_rel join to a left outer join here. # 2. The default value of 3 is generated for the case expression. self.assertQuerysetEqual( CaseTestModel.objects.filter(pk=o.pk).annotate( foo=Case( When(fk_rel__pk=1, then=2), default=3, ), ), [(o, 3)], lambda x: (x, x.foo), ) # Now 2 should be generated, as the fk_rel is null. self.assertQuerysetEqual( CaseTestModel.objects.filter(pk=o.pk).annotate( foo=Case( When(fk_rel__isnull=True, then=2), default=3, ), ), [(o, 2)], lambda x: (x, x.foo), ) def test_join_promotion_multiple_annotations(self): o = CaseTestModel.objects.create(integer=1, integer2=1, string="1") # Testing that: # 1. There isn't any object on the remote side of the fk_rel # relation. If the query used inner joins, then the join to fk_rel # would remove o from the results. So, in effect we are testing that # we are promoting the fk_rel join to a left outer join here. # 2. The default value of 3 is generated for the case expression. self.assertQuerysetEqual( CaseTestModel.objects.filter(pk=o.pk).annotate( foo=Case( When(fk_rel__pk=1, then=2), default=3, ), bar=Case( When(fk_rel__pk=1, then=4), default=5, ), ), [(o, 3, 5)], lambda x: (x, x.foo, x.bar), ) # Now 2 should be generated, as the fk_rel is null. self.assertQuerysetEqual( CaseTestModel.objects.filter(pk=o.pk).annotate( foo=Case( When(fk_rel__isnull=True, then=2), default=3, ), bar=Case( When(fk_rel__isnull=True, then=4), default=5, ), ), [(o, 2, 4)], lambda x: (x, x.foo, x.bar), ) def test_m2m_exclude(self): CaseTestModel.objects.create(integer=10, integer2=1, string="1") qs = ( CaseTestModel.objects.values_list("id", "integer") .annotate( cnt=Sum( Case(When(~Q(fk_rel__integer=1), then=1), default=2), ), ) .order_by("integer") ) # The first o has 2 as its fk_rel__integer=1, thus it hits the # default=2 case. The other ones have 2 as the result as they have 2 # fk_rel objects, except for integer=4 and integer=10 (created above). # The integer=4 case has one integer, thus the result is 1, and # integer=10 doesn't have any and this too generates 1 (instead of 0) # as ~Q() also matches nulls. self.assertQuerysetEqual( qs, [(1, 2), (2, 2), (2, 2), (3, 2), (3, 2), (3, 2), (4, 1), (10, 1)], lambda x: x[1:], ) def test_m2m_reuse(self): CaseTestModel.objects.create(integer=10, integer2=1, string="1") # Need to use values before annotate so that Oracle will not group # by fields it isn't capable of grouping by. qs = ( CaseTestModel.objects.values_list("id", "integer") .annotate( cnt=Sum( Case(When(~Q(fk_rel__integer=1), then=1), default=2), ), ) .annotate( cnt2=Sum( Case(When(~Q(fk_rel__integer=1), then=1), default=2), ), ) .order_by("integer") ) self.assertEqual(str(qs.query).count(" JOIN "), 1) self.assertQuerysetEqual( qs, [ (1, 2, 2), (2, 2, 2), (2, 2, 2), (3, 2, 2), (3, 2, 2), (3, 2, 2), (4, 1, 1), (10, 1, 1), ], lambda x: x[1:], ) def test_aggregation_empty_cases(self): tests = [ # Empty cases and default. (Case(output_field=IntegerField()), None), # Empty cases and a constant default. (Case(default=Value("empty")), "empty"), # Empty cases and column in the default. (Case(default=F("url")), ""), ] for case, value in tests: with self.subTest(case=case): self.assertQuerysetEqual( CaseTestModel.objects.values("string") .annotate( case=case, integer_sum=Sum("integer"), ) .order_by("string"), [ ("1", value, 1), ("2", value, 4), ("3", value, 9), ("4", value, 4), ], transform=itemgetter("string", "case", "integer_sum"), ) class CaseDocumentationExamples(TestCase): @classmethod def setUpTestData(cls): Client.objects.create( name="Jane Doe", account_type=Client.REGULAR, registered_on=date.today() - timedelta(days=36), ) Client.objects.create( name="James Smith", account_type=Client.GOLD, registered_on=date.today() - timedelta(days=5), ) Client.objects.create( name="Jack Black", account_type=Client.PLATINUM, registered_on=date.today() - timedelta(days=10 * 365), ) def test_simple_example(self): self.assertQuerysetEqual( Client.objects.annotate( discount=Case( When(account_type=Client.GOLD, then=Value("5%")), When(account_type=Client.PLATINUM, then=Value("10%")), default=Value("0%"), ), ).order_by("pk"), [("Jane Doe", "0%"), ("James Smith", "5%"), ("Jack Black", "10%")], transform=attrgetter("name", "discount"), ) def test_lookup_example(self): a_month_ago = date.today() - timedelta(days=30) a_year_ago = date.today() - timedelta(days=365) self.assertQuerysetEqual( Client.objects.annotate( discount=Case( When(registered_on__lte=a_year_ago, then=Value("10%")), When(registered_on__lte=a_month_ago, then=Value("5%")), default=Value("0%"), ), ).order_by("pk"), [("Jane Doe", "5%"), ("James Smith", "0%"), ("Jack Black", "10%")], transform=attrgetter("name", "discount"), ) def test_conditional_update_example(self): a_month_ago = date.today() - timedelta(days=30) a_year_ago = date.today() - timedelta(days=365) Client.objects.update( account_type=Case( When(registered_on__lte=a_year_ago, then=Value(Client.PLATINUM)), When(registered_on__lte=a_month_ago, then=Value(Client.GOLD)), default=Value(Client.REGULAR), ), ) self.assertQuerysetEqual( Client.objects.order_by("pk"), [("Jane Doe", "G"), ("James Smith", "R"), ("Jack Black", "P")], transform=attrgetter("name", "account_type"), ) def test_conditional_aggregation_example(self): Client.objects.create( name="Jean Grey", account_type=Client.REGULAR, registered_on=date.today(), ) Client.objects.create( name="James Bond", account_type=Client.PLATINUM, registered_on=date.today(), ) Client.objects.create( name="Jane Porter", account_type=Client.PLATINUM, registered_on=date.today(), ) self.assertEqual( Client.objects.aggregate( regular=Count("pk", filter=Q(account_type=Client.REGULAR)), gold=Count("pk", filter=Q(account_type=Client.GOLD)), platinum=Count("pk", filter=Q(account_type=Client.PLATINUM)), ), {"regular": 2, "gold": 1, "platinum": 3}, ) # This was the example before the filter argument was added. self.assertEqual( Client.objects.aggregate( regular=Sum( Case( When(account_type=Client.REGULAR, then=1), ) ), gold=Sum( Case( When(account_type=Client.GOLD, then=1), ) ), platinum=Sum( Case( When(account_type=Client.PLATINUM, then=1), ) ), ), {"regular": 2, "gold": 1, "platinum": 3}, ) def test_filter_example(self): a_month_ago = date.today() - timedelta(days=30) a_year_ago = date.today() - timedelta(days=365) self.assertQuerysetEqual( Client.objects.filter( registered_on__lte=Case( When(account_type=Client.GOLD, then=a_month_ago), When(account_type=Client.PLATINUM, then=a_year_ago), ), ), [("Jack Black", "P")], transform=attrgetter("name", "account_type"), ) def test_hash(self): expression_1 = Case( When(account_type__in=[Client.REGULAR, Client.GOLD], then=1), default=2, output_field=IntegerField(), ) expression_2 = Case( When(account_type__in=(Client.REGULAR, Client.GOLD), then=1), default=2, output_field=IntegerField(), ) expression_3 = Case( When(account_type__in=[Client.REGULAR, Client.GOLD], then=1), default=2 ) expression_4 = Case( When(account_type__in=[Client.PLATINUM, Client.GOLD], then=2), default=1 ) self.assertEqual(hash(expression_1), hash(expression_2)) self.assertNotEqual(hash(expression_2), hash(expression_3)) self.assertNotEqual(hash(expression_1), hash(expression_4)) self.assertNotEqual(hash(expression_3), hash(expression_4)) class CaseWhenTests(SimpleTestCase): def test_only_when_arguments(self): msg = "Positional arguments must all be When objects." with self.assertRaisesMessage(TypeError, msg): Case(When(Q(pk__in=[])), object()) def test_invalid_when_constructor_args(self): msg = ( "When() supports a Q object, a boolean expression, or lookups as " "a condition." ) with self.assertRaisesMessage(TypeError, msg): When(condition=object()) with self.assertRaisesMessage(TypeError, msg): When(condition=Value(1)) with self.assertRaisesMessage(TypeError, msg): When(Value(1), string="1") with self.assertRaisesMessage(TypeError, msg): When() def test_empty_q_object(self): msg = "An empty Q() can't be used as a When() condition." with self.assertRaisesMessage(ValueError, msg): When(Q(), then=Value(True))
37aad57c9fbf5b59699eb37db96d4bcd5a4a4ae01ce0535f0a2516d664142bcf
from django.db import models try: from PIL import Image except ImportError: Image = None class CaseTestModel(models.Model): integer = models.IntegerField() integer2 = models.IntegerField(null=True) string = models.CharField(max_length=100, default="") big_integer = models.BigIntegerField(null=True) binary = models.BinaryField(default=b"") boolean = models.BooleanField(default=False) date = models.DateField(null=True, db_column="date_field") date_time = models.DateTimeField(null=True) decimal = models.DecimalField( max_digits=2, decimal_places=1, null=True, db_column="decimal_field" ) duration = models.DurationField(null=True) email = models.EmailField(default="") file = models.FileField(null=True, db_column="file_field") file_path = models.FilePathField(null=True) float = models.FloatField(null=True, db_column="float_field") if Image: image = models.ImageField(null=True) generic_ip_address = models.GenericIPAddressField(null=True) null_boolean = models.BooleanField(null=True) positive_integer = models.PositiveIntegerField(null=True) positive_small_integer = models.PositiveSmallIntegerField(null=True) positive_big_integer = models.PositiveSmallIntegerField(null=True) slug = models.SlugField(default="") small_integer = models.SmallIntegerField(null=True) text = models.TextField(default="") time = models.TimeField(null=True, db_column="time_field") url = models.URLField(default="") uuid = models.UUIDField(null=True) fk = models.ForeignKey("self", models.CASCADE, null=True) class O2OCaseTestModel(models.Model): o2o = models.OneToOneField(CaseTestModel, models.CASCADE, related_name="o2o_rel") integer = models.IntegerField() class FKCaseTestModel(models.Model): fk = models.ForeignKey(CaseTestModel, models.CASCADE, related_name="fk_rel") integer = models.IntegerField() class Client(models.Model): REGULAR = "R" GOLD = "G" PLATINUM = "P" ACCOUNT_TYPE_CHOICES = ( (REGULAR, "Regular"), (GOLD, "Gold"), (PLATINUM, "Platinum"), ) name = models.CharField(max_length=50) registered_on = models.DateField() account_type = models.CharField( max_length=1, choices=ACCOUNT_TYPE_CHOICES, default=REGULAR, )
cdde39f7f6c05d90d2f3ddbf69dced83d1219c7c2fdd8fa5965aa9c1319cd0b7
import time from datetime import datetime, timedelta from http import cookies from django.http import HttpResponse from django.test import SimpleTestCase from django.test.utils import freeze_time from django.utils.http import http_date from django.utils.timezone import utc class SetCookieTests(SimpleTestCase): def test_near_expiration(self): """Cookie will expire when a near expiration time is provided.""" response = HttpResponse() # There's a timing weakness in this test; The expected result for # max-age requires that there be a very slight difference between the # evaluated expiration time and the time evaluated in set_cookie(). If # this difference doesn't exist, the cookie time will be 1 second # larger. The sleep guarantees that there will be a time difference. expires = datetime.now(tz=utc).replace(tzinfo=None) + timedelta(seconds=10) time.sleep(0.001) response.set_cookie("datetime", expires=expires) datetime_cookie = response.cookies["datetime"] self.assertEqual(datetime_cookie["max-age"], 10) def test_aware_expiration(self): """set_cookie() accepts an aware datetime as expiration time.""" response = HttpResponse() expires = datetime.now(tz=utc) + timedelta(seconds=10) time.sleep(0.001) response.set_cookie("datetime", expires=expires) datetime_cookie = response.cookies["datetime"] self.assertEqual(datetime_cookie["max-age"], 10) def test_create_cookie_after_deleting_cookie(self): """Setting a cookie after deletion clears the expiry date.""" response = HttpResponse() response.set_cookie("c", "old-value") self.assertEqual(response.cookies["c"]["expires"], "") response.delete_cookie("c") self.assertEqual( response.cookies["c"]["expires"], "Thu, 01 Jan 1970 00:00:00 GMT" ) response.set_cookie("c", "new-value") self.assertEqual(response.cookies["c"]["expires"], "") def test_far_expiration(self): """Cookie will expire when a distant expiration time is provided.""" response = HttpResponse() response.set_cookie("datetime", expires=datetime(2038, 1, 1, 4, 5, 6)) datetime_cookie = response.cookies["datetime"] self.assertIn( datetime_cookie["expires"], # assertIn accounts for slight time dependency (#23450) ("Fri, 01 Jan 2038 04:05:06 GMT", "Fri, 01 Jan 2038 04:05:07 GMT"), ) def test_max_age_expiration(self): """Cookie will expire if max_age is provided.""" response = HttpResponse() set_cookie_time = time.time() with freeze_time(set_cookie_time): response.set_cookie("max_age", max_age=10) max_age_cookie = response.cookies["max_age"] self.assertEqual(max_age_cookie["max-age"], 10) self.assertEqual(max_age_cookie["expires"], http_date(set_cookie_time + 10)) def test_max_age_int(self): response = HttpResponse() response.set_cookie("max_age", max_age=10.6) self.assertEqual(response.cookies["max_age"]["max-age"], 10) def test_httponly_cookie(self): response = HttpResponse() response.set_cookie("example", httponly=True) example_cookie = response.cookies["example"] self.assertIn( "; %s" % cookies.Morsel._reserved["httponly"], str(example_cookie) ) self.assertIs(example_cookie["httponly"], True) def test_unicode_cookie(self): """HttpResponse.set_cookie() works with Unicode data.""" response = HttpResponse() cookie_value = "清風" response.set_cookie("test", cookie_value) self.assertEqual(response.cookies["test"].value, cookie_value) def test_samesite(self): response = HttpResponse() response.set_cookie("example", samesite="None") self.assertEqual(response.cookies["example"]["samesite"], "None") response.set_cookie("example", samesite="Lax") self.assertEqual(response.cookies["example"]["samesite"], "Lax") response.set_cookie("example", samesite="strict") self.assertEqual(response.cookies["example"]["samesite"], "strict") def test_invalid_samesite(self): msg = 'samesite must be "lax", "none", or "strict".' with self.assertRaisesMessage(ValueError, msg): HttpResponse().set_cookie("example", samesite="invalid") class DeleteCookieTests(SimpleTestCase): def test_default(self): response = HttpResponse() response.delete_cookie("c") cookie = response.cookies["c"] self.assertEqual(cookie["expires"], "Thu, 01 Jan 1970 00:00:00 GMT") self.assertEqual(cookie["max-age"], 0) self.assertEqual(cookie["path"], "/") self.assertEqual(cookie["secure"], "") self.assertEqual(cookie["domain"], "") self.assertEqual(cookie["samesite"], "") def test_delete_cookie_secure_prefix(self): """ delete_cookie() sets the secure flag if the cookie name starts with __Host- or __Secure- (without that, browsers ignore cookies with those prefixes). """ response = HttpResponse() for prefix in ("Secure", "Host"): with self.subTest(prefix=prefix): cookie_name = "__%s-c" % prefix response.delete_cookie(cookie_name) self.assertIs(response.cookies[cookie_name]["secure"], True) def test_delete_cookie_secure_samesite_none(self): # delete_cookie() sets the secure flag if samesite='none'. response = HttpResponse() response.delete_cookie("c", samesite="none") self.assertIs(response.cookies["c"]["secure"], True) def test_delete_cookie_samesite(self): response = HttpResponse() response.delete_cookie("c", samesite="lax") self.assertEqual(response.cookies["c"]["samesite"], "lax")
d07a882fea96b5230c3f2085f5d6ea88051ccd58a2d94ac3e523865b7a867c3d
import io import itertools import os import sys import tempfile from unittest import skipIf from django.core.files.base import ContentFile from django.http import FileResponse from django.test import SimpleTestCase class UnseekableBytesIO(io.BytesIO): def seekable(self): return False class FileResponseTests(SimpleTestCase): def test_content_length_file(self): response = FileResponse(open(__file__, "rb")) response.close() self.assertEqual( response.headers["Content-Length"], str(os.path.getsize(__file__)) ) def test_content_length_buffer(self): response = FileResponse(io.BytesIO(b"binary content")) self.assertEqual(response.headers["Content-Length"], "14") def test_content_length_nonzero_starting_position_file(self): file = open(__file__, "rb") file.seek(10) response = FileResponse(file) response.close() self.assertEqual( response.headers["Content-Length"], str(os.path.getsize(__file__) - 10) ) def test_content_length_nonzero_starting_position_buffer(self): test_tuples = ( ("BytesIO", io.BytesIO), ("UnseekableBytesIO", UnseekableBytesIO), ) for buffer_class_name, BufferClass in test_tuples: with self.subTest(buffer_class_name=buffer_class_name): buffer = BufferClass(b"binary content") buffer.seek(10) response = FileResponse(buffer) self.assertEqual(response.headers["Content-Length"], "4") def test_content_length_nonzero_starting_position_file_seekable_no_tell(self): class TestFile: def __init__(self, path, *args, **kwargs): self._file = open(path, *args, **kwargs) def read(self, n_bytes=-1): return self._file.read(n_bytes) def seek(self, offset, whence=io.SEEK_SET): return self._file.seek(offset, whence) def seekable(self): return True @property def name(self): return self._file.name def close(self): if self._file: self._file.close() self._file = None def __enter__(self): return self def __exit__(self, e_type, e_val, e_tb): self.close() file = TestFile(__file__, "rb") file.seek(10) response = FileResponse(file) response.close() self.assertEqual( response.headers["Content-Length"], str(os.path.getsize(__file__) - 10) ) def test_content_type_file(self): response = FileResponse(open(__file__, "rb")) response.close() self.assertIn(response.headers["Content-Type"], ["text/x-python", "text/plain"]) def test_content_type_buffer(self): response = FileResponse(io.BytesIO(b"binary content")) self.assertEqual(response.headers["Content-Type"], "application/octet-stream") def test_content_type_buffer_explicit(self): response = FileResponse( io.BytesIO(b"binary content"), content_type="video/webm" ) self.assertEqual(response.headers["Content-Type"], "video/webm") def test_content_type_buffer_explicit_default(self): response = FileResponse(io.BytesIO(b"binary content"), content_type="text/html") self.assertEqual(response.headers["Content-Type"], "text/html") def test_content_type_buffer_named(self): test_tuples = ( (__file__, ["text/x-python", "text/plain"]), (__file__ + "nosuchfile", ["application/octet-stream"]), ("test_fileresponse.py", ["text/x-python", "text/plain"]), ("test_fileresponse.pynosuchfile", ["application/octet-stream"]), ) for filename, content_types in test_tuples: with self.subTest(filename=filename): buffer = io.BytesIO(b"binary content") buffer.name = filename response = FileResponse(buffer) self.assertIn(response.headers["Content-Type"], content_types) def test_content_disposition_file(self): filenames = ( ("", "test_fileresponse.py"), ("custom_name.py", "custom_name.py"), ) dispositions = ( (False, "inline"), (True, "attachment"), ) for (filename, header_filename), ( as_attachment, header_disposition, ) in itertools.product(filenames, dispositions): with self.subTest(filename=filename, disposition=header_disposition): response = FileResponse( open(__file__, "rb"), filename=filename, as_attachment=as_attachment ) response.close() self.assertEqual( response.headers["Content-Disposition"], '%s; filename="%s"' % (header_disposition, header_filename), ) def test_content_disposition_buffer(self): response = FileResponse(io.BytesIO(b"binary content")) self.assertFalse(response.has_header("Content-Disposition")) def test_content_disposition_buffer_attachment(self): response = FileResponse(io.BytesIO(b"binary content"), as_attachment=True) self.assertEqual(response.headers["Content-Disposition"], "attachment") def test_content_disposition_buffer_explicit_filename(self): dispositions = ( (False, "inline"), (True, "attachment"), ) for as_attachment, header_disposition in dispositions: response = FileResponse( io.BytesIO(b"binary content"), as_attachment=as_attachment, filename="custom_name.py", ) self.assertEqual( response.headers["Content-Disposition"], '%s; filename="custom_name.py"' % header_disposition, ) def test_response_buffer(self): response = FileResponse(io.BytesIO(b"binary content")) self.assertEqual(list(response), [b"binary content"]) def test_response_nonzero_starting_position(self): test_tuples = ( ("BytesIO", io.BytesIO), ("UnseekableBytesIO", UnseekableBytesIO), ) for buffer_class_name, BufferClass in test_tuples: with self.subTest(buffer_class_name=buffer_class_name): buffer = BufferClass(b"binary content") buffer.seek(10) response = FileResponse(buffer) self.assertEqual(list(response), [b"tent"]) def test_buffer_explicit_absolute_filename(self): """ Headers are set correctly with a buffer when an absolute filename is provided. """ response = FileResponse(io.BytesIO(b"binary content"), filename=__file__) self.assertEqual(response.headers["Content-Length"], "14") self.assertEqual( response.headers["Content-Disposition"], 'inline; filename="test_fileresponse.py"', ) @skipIf(sys.platform == "win32", "Named pipes are Unix-only.") def test_file_from_named_pipe_response(self): with tempfile.TemporaryDirectory() as temp_dir: pipe_file = os.path.join(temp_dir, "named_pipe") os.mkfifo(pipe_file) pipe_for_read = os.open(pipe_file, os.O_RDONLY | os.O_NONBLOCK) with open(pipe_file, "wb") as pipe_for_write: pipe_for_write.write(b"binary content") response = FileResponse(os.fdopen(pipe_for_read, mode="rb")) response_content = list(response) response.close() self.assertEqual(response_content, [b"binary content"]) self.assertFalse(response.has_header("Content-Length")) def test_compressed_response(self): """ If compressed responses are served with the uncompressed Content-Type and a compression Content-Encoding, browsers might automatically uncompress the file, which is most probably not wanted. """ test_tuples = ( (".tar.gz", "application/gzip"), (".tar.bz2", "application/x-bzip"), (".tar.xz", "application/x-xz"), ) for extension, mimetype in test_tuples: with self.subTest(ext=extension): with tempfile.NamedTemporaryFile(suffix=extension) as tmp: response = FileResponse(tmp) self.assertEqual(response.headers["Content-Type"], mimetype) self.assertFalse(response.has_header("Content-Encoding")) def test_unicode_attachment(self): response = FileResponse( ContentFile(b"binary content", name="祝您平安.odt"), as_attachment=True, content_type="application/vnd.oasis.opendocument.text", ) self.assertEqual( response.headers["Content-Type"], "application/vnd.oasis.opendocument.text", ) self.assertEqual( response.headers["Content-Disposition"], "attachment; filename*=utf-8''%E7%A5%9D%E6%82%A8%E5%B9%B3%E5%AE%89.odt", ) def test_repr(self): response = FileResponse(io.BytesIO(b"binary content")) self.assertEqual( repr(response), '<FileResponse status_code=200, "application/octet-stream">', )
6427dd23509f8a350a65bcf0ac3ccb1cc0b6474fc3120c9997c1b67de0fc4ab2
import io from django.conf import settings from django.core.cache import cache from django.http import HttpResponse from django.http.response import HttpResponseBase from django.test import SimpleTestCase UTF8 = "utf-8" ISO88591 = "iso-8859-1" class HttpResponseBaseTests(SimpleTestCase): def test_closed(self): r = HttpResponseBase() self.assertIs(r.closed, False) r.close() self.assertIs(r.closed, True) def test_write(self): r = HttpResponseBase() self.assertIs(r.writable(), False) with self.assertRaisesMessage( OSError, "This HttpResponseBase instance is not writable" ): r.write("asdf") with self.assertRaisesMessage( OSError, "This HttpResponseBase instance is not writable" ): r.writelines(["asdf\n", "qwer\n"]) def test_tell(self): r = HttpResponseBase() with self.assertRaisesMessage( OSError, "This HttpResponseBase instance cannot tell its position" ): r.tell() def test_setdefault(self): """ HttpResponseBase.setdefault() should not change an existing header and should be case insensitive. """ r = HttpResponseBase() r.headers["Header"] = "Value" r.setdefault("header", "changed") self.assertEqual(r.headers["header"], "Value") r.setdefault("x-header", "DefaultValue") self.assertEqual(r.headers["X-Header"], "DefaultValue") class HttpResponseTests(SimpleTestCase): def test_status_code(self): resp = HttpResponse(status=503) self.assertEqual(resp.status_code, 503) self.assertEqual(resp.reason_phrase, "Service Unavailable") def test_change_status_code(self): resp = HttpResponse() resp.status_code = 503 self.assertEqual(resp.status_code, 503) self.assertEqual(resp.reason_phrase, "Service Unavailable") def test_valid_status_code_string(self): resp = HttpResponse(status="100") self.assertEqual(resp.status_code, 100) resp = HttpResponse(status="404") self.assertEqual(resp.status_code, 404) resp = HttpResponse(status="599") self.assertEqual(resp.status_code, 599) def test_invalid_status_code(self): must_be_integer = "HTTP status code must be an integer." must_be_integer_in_range = ( "HTTP status code must be an integer from 100 to 599." ) with self.assertRaisesMessage(TypeError, must_be_integer): HttpResponse(status=object()) with self.assertRaisesMessage(TypeError, must_be_integer): HttpResponse(status="J'attendrai") with self.assertRaisesMessage(ValueError, must_be_integer_in_range): HttpResponse(status=99) with self.assertRaisesMessage(ValueError, must_be_integer_in_range): HttpResponse(status=600) def test_reason_phrase(self): reason = "I'm an anarchist coffee pot on crack." resp = HttpResponse(status=419, reason=reason) self.assertEqual(resp.status_code, 419) self.assertEqual(resp.reason_phrase, reason) def test_charset_detection(self): """HttpResponse should parse charset from content_type.""" response = HttpResponse("ok") self.assertEqual(response.charset, settings.DEFAULT_CHARSET) response = HttpResponse(charset=ISO88591) self.assertEqual(response.charset, ISO88591) self.assertEqual( response.headers["Content-Type"], "text/html; charset=%s" % ISO88591 ) response = HttpResponse( content_type="text/plain; charset=%s" % UTF8, charset=ISO88591 ) self.assertEqual(response.charset, ISO88591) response = HttpResponse(content_type="text/plain; charset=%s" % ISO88591) self.assertEqual(response.charset, ISO88591) response = HttpResponse(content_type='text/plain; charset="%s"' % ISO88591) self.assertEqual(response.charset, ISO88591) response = HttpResponse(content_type="text/plain; charset=") self.assertEqual(response.charset, settings.DEFAULT_CHARSET) response = HttpResponse(content_type="text/plain") self.assertEqual(response.charset, settings.DEFAULT_CHARSET) def test_response_content_charset(self): """HttpResponse should encode based on charset.""" content = "Café :)" utf8_content = content.encode(UTF8) iso_content = content.encode(ISO88591) response = HttpResponse(utf8_content) self.assertContains(response, utf8_content) response = HttpResponse( iso_content, content_type="text/plain; charset=%s" % ISO88591 ) self.assertContains(response, iso_content) response = HttpResponse(iso_content) self.assertContains(response, iso_content) response = HttpResponse(iso_content, content_type="text/plain") self.assertContains(response, iso_content) def test_repr(self): response = HttpResponse(content="Café :)".encode(UTF8), status=201) expected = '<HttpResponse status_code=201, "text/html; charset=utf-8">' self.assertEqual(repr(response), expected) def test_repr_no_content_type(self): response = HttpResponse(status=204) del response.headers["Content-Type"] self.assertEqual(repr(response), "<HttpResponse status_code=204>") def test_wrap_textiowrapper(self): content = "Café :)" r = HttpResponse() with io.TextIOWrapper(r, UTF8) as buf: buf.write(content) self.assertEqual(r.content, content.encode(UTF8)) def test_generator_cache(self): generator = (str(i) for i in range(10)) response = HttpResponse(content=generator) self.assertEqual(response.content, b"0123456789") with self.assertRaises(StopIteration): next(generator) cache.set("my-response-key", response) response = cache.get("my-response-key") self.assertEqual(response.content, b"0123456789")
1614c734a52ed2f140080fbaf77e504c11a58971059e64393230219ce4cd2ee0
from django.test import TestCase from .models import ( CompetingTeam, Event, Group, IndividualCompetitor, Membership, Person, ) class MultiTableTests(TestCase): @classmethod def setUpTestData(cls): cls.alice = Person.objects.create(name="Alice") cls.bob = Person.objects.create(name="Bob") cls.chris = Person.objects.create(name="Chris") cls.dan = Person.objects.create(name="Dan") cls.team_alpha = Group.objects.create(name="Alpha") Membership.objects.create(person=cls.alice, group=cls.team_alpha) Membership.objects.create(person=cls.bob, group=cls.team_alpha) cls.event = Event.objects.create(name="Exposition Match") IndividualCompetitor.objects.create(event=cls.event, person=cls.chris) IndividualCompetitor.objects.create(event=cls.event, person=cls.dan) CompetingTeam.objects.create(event=cls.event, team=cls.team_alpha) def test_m2m_query(self): result = self.event.teams.all() self.assertCountEqual(result, [self.team_alpha]) def test_m2m_reverse_query(self): result = self.chris.event_set.all() self.assertCountEqual(result, [self.event]) def test_m2m_query_proxied(self): result = self.event.special_people.all() self.assertCountEqual(result, [self.chris, self.dan]) def test_m2m_reverse_query_proxied(self): result = self.chris.special_event_set.all() self.assertCountEqual(result, [self.event]) def test_m2m_prefetch_proxied(self): result = Event.objects.filter(name="Exposition Match").prefetch_related( "special_people" ) with self.assertNumQueries(2): self.assertCountEqual(result, [self.event]) self.assertEqual( sorted(p.name for p in result[0].special_people.all()), ["Chris", "Dan"] ) def test_m2m_prefetch_reverse_proxied(self): result = Person.objects.filter(name="Dan").prefetch_related("special_event_set") with self.assertNumQueries(2): self.assertCountEqual(result, [self.dan]) self.assertEqual( [event.name for event in result[0].special_event_set.all()], ["Exposition Match"], )
986525c1fe086017784dfcc65694a900363d96c4ae3224fefc439ddc493632b7
from io import StringIO from django.contrib.auth.models import User from django.core import management from django.test import TestCase from .models import Car, CarDriver, Driver, Group, Membership, Person, UserMembership class M2MThroughTestCase(TestCase): @classmethod def setUpTestData(cls): cls.bob = Person.objects.create(name="Bob") cls.jim = Person.objects.create(name="Jim") cls.rock = Group.objects.create(name="Rock") cls.roll = Group.objects.create(name="Roll") cls.frank = User.objects.create_user("frank", "[email protected]", "password") cls.jane = User.objects.create_user("jane", "[email protected]", "password") # normal intermediate model cls.bob_rock = Membership.objects.create(person=cls.bob, group=cls.rock) cls.bob_roll = Membership.objects.create( person=cls.bob, group=cls.roll, price=50 ) cls.jim_rock = Membership.objects.create( person=cls.jim, group=cls.rock, price=50 ) # intermediate model with custom id column cls.frank_rock = UserMembership.objects.create(user=cls.frank, group=cls.rock) cls.frank_roll = UserMembership.objects.create(user=cls.frank, group=cls.roll) cls.jane_rock = UserMembership.objects.create(user=cls.jane, group=cls.rock) def test_retrieve_reverse_m2m_items(self): self.assertCountEqual(self.bob.group_set.all(), [self.rock, self.roll]) def test_retrieve_forward_m2m_items(self): self.assertSequenceEqual(self.roll.members.all(), [self.bob]) def test_retrieve_reverse_m2m_items_via_custom_id_intermediary(self): self.assertCountEqual(self.frank.group_set.all(), [self.rock, self.roll]) def test_retrieve_forward_m2m_items_via_custom_id_intermediary(self): self.assertSequenceEqual(self.roll.user_members.all(), [self.frank]) def test_join_trimming_forwards(self): """ Too many copies of the intermediate table aren't involved when doing a join (#8046, #8254). """ self.assertSequenceEqual( self.rock.members.filter(membership__price=50), [self.jim], ) def test_join_trimming_reverse(self): self.assertSequenceEqual( self.bob.group_set.filter(membership__price=50), [self.roll], ) class M2MThroughSerializationTestCase(TestCase): @classmethod def setUpTestData(cls): cls.bob = Person.objects.create(name="Bob") cls.roll = Group.objects.create(name="Roll") cls.bob_roll = Membership.objects.create(person=cls.bob, group=cls.roll) def test_serialization(self): "m2m-through models aren't serialized as m2m fields. Refs #8134" pks = { "p_pk": self.bob.pk, "g_pk": self.roll.pk, "m_pk": self.bob_roll.pk, "app_label": "m2m_through_regress", } out = StringIO() management.call_command( "dumpdata", "m2m_through_regress", format="json", stdout=out ) self.assertJSONEqual( out.getvalue().strip(), '[{"pk": %(m_pk)s, "model": "m2m_through_regress.membership", ' '"fields": {"person": %(p_pk)s, "price": 100, "group": %(g_pk)s}}, ' '{"pk": %(p_pk)s, "model": "m2m_through_regress.person", ' '"fields": {"name": "Bob"}}, ' '{"pk": %(g_pk)s, "model": "m2m_through_regress.group", ' '"fields": {"name": "Roll"}}]' % pks, ) out = StringIO() management.call_command( "dumpdata", "m2m_through_regress", format="xml", indent=2, stdout=out ) self.assertXMLEqual( out.getvalue().strip(), """ <?xml version="1.0" encoding="utf-8"?> <django-objects version="1.0"> <object pk="%(m_pk)s" model="%(app_label)s.membership"> <field to="%(app_label)s.person" name="person" rel="ManyToOneRel">%(p_pk)s</field> <field to="%(app_label)s.group" name="group" rel="ManyToOneRel">%(g_pk)s</field> <field type="IntegerField" name="price">100</field> </object> <object pk="%(p_pk)s" model="%(app_label)s.person"> <field type="CharField" name="name">Bob</field> </object> <object pk="%(g_pk)s" model="%(app_label)s.group"> <field type="CharField" name="name">Roll</field> </object> </django-objects> """.strip() % pks, ) class ToFieldThroughTests(TestCase): @classmethod def setUpTestData(cls): cls.car = Car.objects.create(make="Toyota") cls.driver = Driver.objects.create(name="Ryan Briscoe") CarDriver.objects.create(car=cls.car, driver=cls.driver) # We are testing if wrong objects get deleted due to using wrong # field value in m2m queries. So, it is essential that the pk # numberings do not match. # Create one intentionally unused driver to mix up the autonumbering cls.unused_driver = Driver.objects.create(name="Barney Gumble") # And two intentionally unused cars. cls.unused_car1 = Car.objects.create(make="Trabant") cls.unused_car2 = Car.objects.create(make="Wartburg") def test_to_field(self): self.assertSequenceEqual(self.car.drivers.all(), [self.driver]) def test_to_field_reverse(self): self.assertSequenceEqual(self.driver.car_set.all(), [self.car]) def test_to_field_clear_reverse(self): self.driver.car_set.clear() self.assertSequenceEqual(self.driver.car_set.all(), []) def test_to_field_clear(self): self.car.drivers.clear() self.assertSequenceEqual(self.car.drivers.all(), []) # Low level tests for _add_items and _remove_items. We test these methods # because .add/.remove aren't available for m2m fields with through, but # through is the only way to set to_field currently. We do want to make # sure these methods are ready if the ability to use .add or .remove with # to_field relations is added some day. def test_add(self): self.assertSequenceEqual(self.car.drivers.all(), [self.driver]) # Yikes - barney is going to drive... self.car.drivers._add_items("car", "driver", self.unused_driver) self.assertSequenceEqual( self.car.drivers.all(), [self.unused_driver, self.driver], ) def test_m2m_relations_unusable_on_null_to_field(self): nullcar = Car(make=None) msg = ( '"<Car: None>" needs to have a value for field "make" before this ' "many-to-many relationship can be used." ) with self.assertRaisesMessage(ValueError, msg): nullcar.drivers.all() def test_m2m_relations_unusable_on_null_pk_obj(self): msg = ( "'Car' instance needs to have a primary key value before a " "many-to-many relationship can be used." ) with self.assertRaisesMessage(ValueError, msg): Car(make="Ford").drivers.all() def test_add_related_null(self): nulldriver = Driver.objects.create(name=None) msg = 'Cannot add "<Driver: None>": the value for field "driver" is None' with self.assertRaisesMessage(ValueError, msg): self.car.drivers._add_items("car", "driver", nulldriver) def test_add_reverse(self): car2 = Car.objects.create(make="Honda") self.assertCountEqual(self.driver.car_set.all(), [self.car]) self.driver.car_set._add_items("driver", "car", car2) self.assertCountEqual(self.driver.car_set.all(), [self.car, car2]) def test_add_null_reverse(self): nullcar = Car.objects.create(make=None) msg = 'Cannot add "<Car: None>": the value for field "car" is None' with self.assertRaisesMessage(ValueError, msg): self.driver.car_set._add_items("driver", "car", nullcar) def test_add_null_reverse_related(self): nulldriver = Driver.objects.create(name=None) msg = ( '"<Driver: None>" needs to have a value for field "name" before ' "this many-to-many relationship can be used." ) with self.assertRaisesMessage(ValueError, msg): nulldriver.car_set._add_items("driver", "car", self.car) def test_remove(self): self.assertSequenceEqual(self.car.drivers.all(), [self.driver]) self.car.drivers._remove_items("car", "driver", self.driver) self.assertSequenceEqual(self.car.drivers.all(), []) def test_remove_reverse(self): self.assertSequenceEqual(self.driver.car_set.all(), [self.car]) self.driver.car_set._remove_items("driver", "car", self.car) self.assertSequenceEqual(self.driver.car_set.all(), []) class ThroughLoadDataTestCase(TestCase): fixtures = ["m2m_through"] def test_sequence_creation(self): """ Sequences on an m2m_through are created for the through model, not a phantom auto-generated m2m table (#11107). """ out = StringIO() management.call_command( "dumpdata", "m2m_through_regress", format="json", stdout=out ) self.assertJSONEqual( out.getvalue().strip(), '[{"pk": 1, "model": "m2m_through_regress.usermembership", ' '"fields": {"price": 100, "group": 1, "user": 1}}, ' '{"pk": 1, "model": "m2m_through_regress.person", ' '"fields": {"name": "Guido"}}, ' '{"pk": 1, "model": "m2m_through_regress.group", ' '"fields": {"name": "Python Core Group"}}]', )
cc58a048ca49b81a636820d2a0ba333f0b92851727e281d97162721686620a7c
from django.contrib.auth.models import User from django.db import models # Forward declared intermediate model class Membership(models.Model): person = models.ForeignKey("Person", models.CASCADE) group = models.ForeignKey("Group", models.CASCADE) price = models.IntegerField(default=100) # using custom id column to test ticket #11107 class UserMembership(models.Model): id = models.AutoField(db_column="usermembership_id", primary_key=True) user = models.ForeignKey(User, models.CASCADE) group = models.ForeignKey("Group", models.CASCADE) price = models.IntegerField(default=100) class Person(models.Model): name = models.CharField(max_length=128) def __str__(self): return self.name class Group(models.Model): name = models.CharField(max_length=128) # Membership object defined as a class members = models.ManyToManyField(Person, through=Membership) user_members = models.ManyToManyField(User, through="UserMembership") def __str__(self): return self.name # Using to_field on the through model class Car(models.Model): make = models.CharField(max_length=20, unique=True, null=True) drivers = models.ManyToManyField("Driver", through="CarDriver") def __str__(self): return str(self.make) class Driver(models.Model): name = models.CharField(max_length=20, unique=True, null=True) class Meta: ordering = ("name",) def __str__(self): return str(self.name) class CarDriver(models.Model): car = models.ForeignKey("Car", models.CASCADE, to_field="make") driver = models.ForeignKey("Driver", models.CASCADE, to_field="name") def __str__(self): return "pk=%s car=%s driver=%s" % (str(self.pk), self.car, self.driver) # Through models using multi-table inheritance class Event(models.Model): name = models.CharField(max_length=50, unique=True) people = models.ManyToManyField("Person", through="IndividualCompetitor") special_people = models.ManyToManyField( "Person", through="ProxiedIndividualCompetitor", related_name="special_event_set", ) teams = models.ManyToManyField("Group", through="CompetingTeam") class Competitor(models.Model): event = models.ForeignKey(Event, models.CASCADE) class IndividualCompetitor(Competitor): person = models.ForeignKey(Person, models.CASCADE) class CompetingTeam(Competitor): team = models.ForeignKey(Group, models.CASCADE) class ProxiedIndividualCompetitor(IndividualCompetitor): class Meta: proxy = True
25c07a4723987edb2e4b33114c2911f3f0ca814e6b060e3ebc56313fee6a4f79
import datetime from unittest import mock from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.views import shortcut from django.contrib.sites.models import Site from django.contrib.sites.shortcuts import get_current_site from django.http import Http404, HttpRequest from django.test import TestCase, override_settings from .models import ( Article, Author, FooWithBrokenAbsoluteUrl, FooWithoutUrl, FooWithUrl, ModelWithM2MToSite, ModelWithNullFKToSite, SchemeIncludedURL, ) from .models import Site as MockSite @override_settings(ROOT_URLCONF="contenttypes_tests.urls") class ContentTypesViewsTests(TestCase): @classmethod def setUpTestData(cls): # Don't use the manager to ensure the site exists with pk=1, regardless # of whether or not it already exists. cls.site1 = Site(pk=1, domain="testserver", name="testserver") cls.site1.save() cls.author1 = Author.objects.create(name="Boris") cls.article1 = Article.objects.create( title="Old Article", slug="old_article", author=cls.author1, date_created=datetime.datetime(2001, 1, 1, 21, 22, 23), ) cls.article2 = Article.objects.create( title="Current Article", slug="current_article", author=cls.author1, date_created=datetime.datetime(2007, 9, 17, 21, 22, 23), ) cls.article3 = Article.objects.create( title="Future Article", slug="future_article", author=cls.author1, date_created=datetime.datetime(3000, 1, 1, 21, 22, 23), ) cls.scheme1 = SchemeIncludedURL.objects.create( url="http://test_scheme_included_http/" ) cls.scheme2 = SchemeIncludedURL.objects.create( url="https://test_scheme_included_https/" ) cls.scheme3 = SchemeIncludedURL.objects.create( url="//test_default_scheme_kept/" ) def setUp(self): Site.objects.clear_cache() def test_shortcut_with_absolute_url(self): "Can view a shortcut for an Author object that has a get_absolute_url method" for obj in Author.objects.all(): with self.subTest(obj=obj): short_url = "/shortcut/%s/%s/" % ( ContentType.objects.get_for_model(Author).id, obj.pk, ) response = self.client.get(short_url) self.assertRedirects( response, "http://testserver%s" % obj.get_absolute_url(), target_status_code=404, ) def test_shortcut_with_absolute_url_including_scheme(self): """ Can view a shortcut when object's get_absolute_url returns a full URL the tested URLs are: "http://...", "https://..." and "//..." """ for obj in SchemeIncludedURL.objects.all(): with self.subTest(obj=obj): short_url = "/shortcut/%s/%s/" % ( ContentType.objects.get_for_model(SchemeIncludedURL).id, obj.pk, ) response = self.client.get(short_url) self.assertRedirects( response, obj.get_absolute_url(), fetch_redirect_response=False ) def test_shortcut_no_absolute_url(self): """ Shortcuts for an object that has no get_absolute_url() method raise 404. """ for obj in Article.objects.all(): with self.subTest(obj=obj): short_url = "/shortcut/%s/%s/" % ( ContentType.objects.get_for_model(Article).id, obj.pk, ) response = self.client.get(short_url) self.assertEqual(response.status_code, 404) def test_wrong_type_pk(self): short_url = "/shortcut/%s/%s/" % ( ContentType.objects.get_for_model(Author).id, "nobody/expects", ) response = self.client.get(short_url) self.assertEqual(response.status_code, 404) def test_shortcut_bad_pk(self): short_url = "/shortcut/%s/%s/" % ( ContentType.objects.get_for_model(Author).id, "42424242", ) response = self.client.get(short_url) self.assertEqual(response.status_code, 404) def test_nonint_content_type(self): an_author = Author.objects.all()[0] short_url = "/shortcut/%s/%s/" % ("spam", an_author.pk) response = self.client.get(short_url) self.assertEqual(response.status_code, 404) def test_bad_content_type(self): an_author = Author.objects.all()[0] short_url = "/shortcut/%s/%s/" % (42424242, an_author.pk) response = self.client.get(short_url) self.assertEqual(response.status_code, 404) @override_settings(ROOT_URLCONF="contenttypes_tests.urls") class ContentTypesViewsSiteRelTests(TestCase): def setUp(self): Site.objects.clear_cache() @classmethod def setUpTestData(cls): cls.site_2 = Site.objects.create(domain="example2.com", name="example2.com") cls.site_3 = Site.objects.create(domain="example3.com", name="example3.com") @mock.patch("django.apps.apps.get_model") def test_shortcut_view_with_null_site_fk(self, get_model): """ The shortcut view works if a model's ForeignKey to site is None. """ get_model.side_effect = ( lambda *args, **kwargs: MockSite if args[0] == "sites.Site" else ModelWithNullFKToSite ) obj = ModelWithNullFKToSite.objects.create(title="title") url = "/shortcut/%s/%s/" % ( ContentType.objects.get_for_model(ModelWithNullFKToSite).id, obj.pk, ) response = self.client.get(url) expected_url = "http://example.com%s" % obj.get_absolute_url() self.assertRedirects(response, expected_url, fetch_redirect_response=False) @mock.patch("django.apps.apps.get_model") def test_shortcut_view_with_site_m2m(self, get_model): """ When the object has a ManyToManyField to Site, redirect to the current site if it's attached to the object or to the domain of the first site found in the m2m relationship. """ get_model.side_effect = ( lambda *args, **kwargs: MockSite if args[0] == "sites.Site" else ModelWithM2MToSite ) # get_current_site() will lookup a Site object, so these must match the # domains in the MockSite model. MockSite.objects.bulk_create( [ MockSite(pk=1, domain="example.com"), MockSite(pk=self.site_2.pk, domain=self.site_2.domain), MockSite(pk=self.site_3.pk, domain=self.site_3.domain), ] ) ct = ContentType.objects.get_for_model(ModelWithM2MToSite) site_3_obj = ModelWithM2MToSite.objects.create( title="Not Linked to Current Site" ) site_3_obj.sites.add(MockSite.objects.get(pk=self.site_3.pk)) expected_url = "http://%s%s" % ( self.site_3.domain, site_3_obj.get_absolute_url(), ) with self.settings(SITE_ID=self.site_2.pk): # Redirects to the domain of the first Site found in the m2m # relationship (ordering is arbitrary). response = self.client.get("/shortcut/%s/%s/" % (ct.pk, site_3_obj.pk)) self.assertRedirects(response, expected_url, fetch_redirect_response=False) obj_with_sites = ModelWithM2MToSite.objects.create( title="Linked to Current Site" ) obj_with_sites.sites.set(MockSite.objects.all()) shortcut_url = "/shortcut/%s/%s/" % (ct.pk, obj_with_sites.pk) expected_url = "http://%s%s" % ( self.site_2.domain, obj_with_sites.get_absolute_url(), ) with self.settings(SITE_ID=self.site_2.pk): # Redirects to the domain of the Site matching the current site's # domain. response = self.client.get(shortcut_url) self.assertRedirects(response, expected_url, fetch_redirect_response=False) with self.settings(SITE_ID=None, ALLOWED_HOSTS=[self.site_2.domain]): # Redirects to the domain of the Site matching the request's host # header. response = self.client.get(shortcut_url, SERVER_NAME=self.site_2.domain) self.assertRedirects(response, expected_url, fetch_redirect_response=False) class ShortcutViewTests(TestCase): def setUp(self): self.request = HttpRequest() self.request.META = {"SERVER_NAME": "Example.com", "SERVER_PORT": "80"} @override_settings(ALLOWED_HOSTS=["example.com"]) def test_not_dependent_on_sites_app(self): """ The view returns a complete URL regardless of whether the sites framework is installed. """ user_ct = ContentType.objects.get_for_model(FooWithUrl) obj = FooWithUrl.objects.create(name="john") with self.modify_settings(INSTALLED_APPS={"append": "django.contrib.sites"}): response = shortcut(self.request, user_ct.id, obj.id) self.assertEqual( "http://%s/users/john/" % get_current_site(self.request).domain, response.headers.get("location"), ) with self.modify_settings(INSTALLED_APPS={"remove": "django.contrib.sites"}): response = shortcut(self.request, user_ct.id, obj.id) self.assertEqual( "http://Example.com/users/john/", response.headers.get("location") ) def test_model_without_get_absolute_url(self): """The view returns 404 when Model.get_absolute_url() isn't defined.""" user_ct = ContentType.objects.get_for_model(FooWithoutUrl) obj = FooWithoutUrl.objects.create(name="john") with self.assertRaises(Http404): shortcut(self.request, user_ct.id, obj.id) def test_model_with_broken_get_absolute_url(self): """ The view doesn't catch an AttributeError raised by Model.get_absolute_url() (#8997). """ user_ct = ContentType.objects.get_for_model(FooWithBrokenAbsoluteUrl) obj = FooWithBrokenAbsoluteUrl.objects.create(name="john") with self.assertRaises(AttributeError): shortcut(self.request, user_ct.id, obj.id)
006a2b877fcf0962177a6c429778560f675e1c4e19cc774a3f5847ee9399f6b6
from django.contrib.contenttypes.models import ContentType, ContentTypeManager from django.db import models from django.test import TestCase, override_settings from django.test.utils import isolate_apps from .models import Author, ConcreteModel, FooWithUrl, ProxyModel class ContentTypesTests(TestCase): def setUp(self): ContentType.objects.clear_cache() def tearDown(self): ContentType.objects.clear_cache() def test_lookup_cache(self): """ The content type cache (see ContentTypeManager) works correctly. Lookups for a particular content type -- by model, ID, or natural key -- should hit the database only on the first lookup. """ # At this point, a lookup for a ContentType should hit the DB with self.assertNumQueries(1): ContentType.objects.get_for_model(ContentType) # A second hit, though, won't hit the DB, nor will a lookup by ID # or natural key with self.assertNumQueries(0): ct = ContentType.objects.get_for_model(ContentType) with self.assertNumQueries(0): ContentType.objects.get_for_id(ct.id) with self.assertNumQueries(0): ContentType.objects.get_by_natural_key("contenttypes", "contenttype") # Once we clear the cache, another lookup will again hit the DB ContentType.objects.clear_cache() with self.assertNumQueries(1): ContentType.objects.get_for_model(ContentType) # The same should happen with a lookup by natural key ContentType.objects.clear_cache() with self.assertNumQueries(1): ContentType.objects.get_by_natural_key("contenttypes", "contenttype") # And a second hit shouldn't hit the DB with self.assertNumQueries(0): ContentType.objects.get_by_natural_key("contenttypes", "contenttype") def test_get_for_models_creation(self): ContentType.objects.all().delete() with self.assertNumQueries(4): cts = ContentType.objects.get_for_models( ContentType, FooWithUrl, ProxyModel, ConcreteModel ) self.assertEqual( cts, { ContentType: ContentType.objects.get_for_model(ContentType), FooWithUrl: ContentType.objects.get_for_model(FooWithUrl), ProxyModel: ContentType.objects.get_for_model(ProxyModel), ConcreteModel: ContentType.objects.get_for_model(ConcreteModel), }, ) def test_get_for_models_empty_cache(self): # Empty cache. with self.assertNumQueries(1): cts = ContentType.objects.get_for_models( ContentType, FooWithUrl, ProxyModel, ConcreteModel ) self.assertEqual( cts, { ContentType: ContentType.objects.get_for_model(ContentType), FooWithUrl: ContentType.objects.get_for_model(FooWithUrl), ProxyModel: ContentType.objects.get_for_model(ProxyModel), ConcreteModel: ContentType.objects.get_for_model(ConcreteModel), }, ) def test_get_for_models_partial_cache(self): # Partial cache ContentType.objects.get_for_model(ContentType) with self.assertNumQueries(1): cts = ContentType.objects.get_for_models(ContentType, FooWithUrl) self.assertEqual( cts, { ContentType: ContentType.objects.get_for_model(ContentType), FooWithUrl: ContentType.objects.get_for_model(FooWithUrl), }, ) def test_get_for_models_full_cache(self): # Full cache ContentType.objects.get_for_model(ContentType) ContentType.objects.get_for_model(FooWithUrl) with self.assertNumQueries(0): cts = ContentType.objects.get_for_models(ContentType, FooWithUrl) self.assertEqual( cts, { ContentType: ContentType.objects.get_for_model(ContentType), FooWithUrl: ContentType.objects.get_for_model(FooWithUrl), }, ) @isolate_apps("contenttypes_tests") def test_get_for_model_create_contenttype(self): """ ContentTypeManager.get_for_model() creates the corresponding content type if it doesn't exist in the database. """ class ModelCreatedOnTheFly(models.Model): name = models.CharField() ct = ContentType.objects.get_for_model(ModelCreatedOnTheFly) self.assertEqual(ct.app_label, "contenttypes_tests") self.assertEqual(ct.model, "modelcreatedonthefly") self.assertEqual(str(ct), "modelcreatedonthefly") def test_get_for_concrete_model(self): """ Make sure the `for_concrete_model` kwarg correctly works with concrete, proxy and deferred models """ concrete_model_ct = ContentType.objects.get_for_model(ConcreteModel) self.assertEqual( concrete_model_ct, ContentType.objects.get_for_model(ProxyModel) ) self.assertEqual( concrete_model_ct, ContentType.objects.get_for_model(ConcreteModel, for_concrete_model=False), ) proxy_model_ct = ContentType.objects.get_for_model( ProxyModel, for_concrete_model=False ) self.assertNotEqual(concrete_model_ct, proxy_model_ct) # Make sure deferred model are correctly handled ConcreteModel.objects.create(name="Concrete") DeferredConcreteModel = ConcreteModel.objects.only("pk").get().__class__ DeferredProxyModel = ProxyModel.objects.only("pk").get().__class__ self.assertEqual( concrete_model_ct, ContentType.objects.get_for_model(DeferredConcreteModel) ) self.assertEqual( concrete_model_ct, ContentType.objects.get_for_model( DeferredConcreteModel, for_concrete_model=False ), ) self.assertEqual( concrete_model_ct, ContentType.objects.get_for_model(DeferredProxyModel) ) self.assertEqual( proxy_model_ct, ContentType.objects.get_for_model( DeferredProxyModel, for_concrete_model=False ), ) def test_get_for_concrete_models(self): """ Make sure the `for_concrete_models` kwarg correctly works with concrete, proxy and deferred models. """ concrete_model_ct = ContentType.objects.get_for_model(ConcreteModel) cts = ContentType.objects.get_for_models(ConcreteModel, ProxyModel) self.assertEqual( cts, { ConcreteModel: concrete_model_ct, ProxyModel: concrete_model_ct, }, ) proxy_model_ct = ContentType.objects.get_for_model( ProxyModel, for_concrete_model=False ) cts = ContentType.objects.get_for_models( ConcreteModel, ProxyModel, for_concrete_models=False ) self.assertEqual( cts, { ConcreteModel: concrete_model_ct, ProxyModel: proxy_model_ct, }, ) # Make sure deferred model are correctly handled ConcreteModel.objects.create(name="Concrete") DeferredConcreteModel = ConcreteModel.objects.only("pk").get().__class__ DeferredProxyModel = ProxyModel.objects.only("pk").get().__class__ cts = ContentType.objects.get_for_models( DeferredConcreteModel, DeferredProxyModel ) self.assertEqual( cts, { DeferredConcreteModel: concrete_model_ct, DeferredProxyModel: concrete_model_ct, }, ) cts = ContentType.objects.get_for_models( DeferredConcreteModel, DeferredProxyModel, for_concrete_models=False ) self.assertEqual( cts, { DeferredConcreteModel: concrete_model_ct, DeferredProxyModel: proxy_model_ct, }, ) def test_cache_not_shared_between_managers(self): with self.assertNumQueries(1): ContentType.objects.get_for_model(ContentType) with self.assertNumQueries(0): ContentType.objects.get_for_model(ContentType) other_manager = ContentTypeManager() other_manager.model = ContentType with self.assertNumQueries(1): other_manager.get_for_model(ContentType) with self.assertNumQueries(0): other_manager.get_for_model(ContentType) def test_missing_model(self): """ Displaying content types in admin (or anywhere) doesn't break on leftover content type records in the DB for which no model is defined anymore. """ ct = ContentType.objects.create( app_label="contenttypes", model="OldModel", ) self.assertEqual(str(ct), "OldModel") self.assertIsNone(ct.model_class()) # Stale ContentTypes can be fetched like any other object. ct_fetched = ContentType.objects.get_for_id(ct.pk) self.assertIsNone(ct_fetched.model_class()) def test_str(self): ct = ContentType.objects.get(app_label="contenttypes_tests", model="site") self.assertEqual(str(ct), "contenttypes_tests | site") def test_app_labeled_name(self): ct = ContentType.objects.get(app_label="contenttypes_tests", model="site") self.assertEqual(ct.app_labeled_name, "contenttypes_tests | site") def test_app_labeled_name_unknown_model(self): ct = ContentType(app_label="contenttypes_tests", model="unknown") self.assertEqual(ct.app_labeled_name, "unknown") class TestRouter: def db_for_read(self, model, **hints): return "other" def db_for_write(self, model, **hints): return "default" @override_settings(DATABASE_ROUTERS=[TestRouter()]) class ContentTypesMultidbTests(TestCase): databases = {"default", "other"} def test_multidb(self): """ When using multiple databases, ContentType.objects.get_for_model() uses db_for_read(). """ ContentType.objects.clear_cache() with self.assertNumQueries(0, using="default"), self.assertNumQueries( 1, using="other" ): ContentType.objects.get_for_model(Author)
9231635b234594d29e56cd6be3abae8c8d61d9bba199ded15c086d8b8b78cc31
from urllib.parse import quote from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation from django.contrib.contenttypes.models import ContentType from django.contrib.sites.models import SiteManager from django.db import models class Site(models.Model): domain = models.CharField(max_length=100) objects = SiteManager() class Author(models.Model): name = models.CharField(max_length=100) def get_absolute_url(self): return "/authors/%s/" % self.id class Article(models.Model): title = models.CharField(max_length=100) slug = models.SlugField() author = models.ForeignKey(Author, models.CASCADE) date_created = models.DateTimeField() class SchemeIncludedURL(models.Model): url = models.URLField(max_length=100) def get_absolute_url(self): return self.url class ConcreteModel(models.Model): name = models.CharField(max_length=10) class ProxyModel(ConcreteModel): class Meta: proxy = True class FooWithoutUrl(models.Model): """ Fake model not defining ``get_absolute_url`` for ContentTypesTests.test_shortcut_view_without_get_absolute_url() """ name = models.CharField(max_length=30, unique=True) class FooWithUrl(FooWithoutUrl): """ Fake model defining ``get_absolute_url`` for ContentTypesTests.test_shortcut_view(). """ def get_absolute_url(self): return "/users/%s/" % quote(self.name) class FooWithBrokenAbsoluteUrl(FooWithoutUrl): """ Fake model defining a ``get_absolute_url`` method containing an error """ def get_absolute_url(self): return "/users/%s/" % self.unknown_field class Question(models.Model): text = models.CharField(max_length=200) answer_set = GenericRelation("Answer") class Answer(models.Model): text = models.CharField(max_length=200) content_type = models.ForeignKey(ContentType, models.CASCADE) object_id = models.PositiveIntegerField() question = GenericForeignKey() class Meta: order_with_respect_to = "question" class Post(models.Model): """An ordered tag on an item.""" title = models.CharField(max_length=200) content_type = models.ForeignKey(ContentType, models.CASCADE, null=True) object_id = models.PositiveIntegerField(null=True) parent = GenericForeignKey() children = GenericRelation("Post") class Meta: order_with_respect_to = "parent" class ModelWithNullFKToSite(models.Model): title = models.CharField(max_length=200) site = models.ForeignKey(Site, null=True, on_delete=models.CASCADE) post = models.ForeignKey(Post, null=True, on_delete=models.CASCADE) def get_absolute_url(self): return "/title/%s/" % quote(self.title) class ModelWithM2MToSite(models.Model): title = models.CharField(max_length=200) sites = models.ManyToManyField(Site) def get_absolute_url(self): return "/title/%s/" % quote(self.title)
184db667237fbccbd596d0443f62cbb538adb18576ff87ad6fa446d09eb12279
from unittest import mock from django.apps.registry import Apps, apps from django.contrib.contenttypes import management as contenttypes_management from django.contrib.contenttypes.models import ContentType from django.core.management import call_command from django.test import TestCase, modify_settings from django.test.utils import captured_stdout from .models import ModelWithNullFKToSite, Post @modify_settings(INSTALLED_APPS={"append": ["empty_models", "no_models"]}) class RemoveStaleContentTypesTests(TestCase): # Speed up tests by avoiding retrieving ContentTypes for all test apps. available_apps = [ "contenttypes_tests", "empty_models", "no_models", "django.contrib.contenttypes", ] @classmethod def setUpTestData(cls): cls.before_count = ContentType.objects.count() cls.content_type = ContentType.objects.create( app_label="contenttypes_tests", model="Fake" ) def setUp(self): self.app_config = apps.get_app_config("contenttypes_tests") def test_interactive_true_with_dependent_objects(self): """ interactive mode (the default) deletes stale content types and warns of dependent objects. """ post = Post.objects.create(title="post", content_type=self.content_type) # A related object is needed to show that a custom collector with # can_fast_delete=False is needed. ModelWithNullFKToSite.objects.create(post=post) with mock.patch("builtins.input", return_value="yes"): with captured_stdout() as stdout: call_command("remove_stale_contenttypes", verbosity=2, stdout=stdout) self.assertEqual(Post.objects.count(), 0) output = stdout.getvalue() self.assertIn("- Content type for contenttypes_tests.Fake", output) self.assertIn("- 1 contenttypes_tests.Post object(s)", output) self.assertIn("- 1 contenttypes_tests.ModelWithNullFKToSite", output) self.assertIn("Deleting stale content type", output) self.assertEqual(ContentType.objects.count(), self.before_count) def test_interactive_true_without_dependent_objects(self): """ interactive mode deletes stale content types even if there aren't any dependent objects. """ with mock.patch("builtins.input", return_value="yes"): with captured_stdout() as stdout: call_command("remove_stale_contenttypes", verbosity=2) self.assertIn("Deleting stale content type", stdout.getvalue()) self.assertEqual(ContentType.objects.count(), self.before_count) def test_interactive_false(self): """non-interactive mode deletes stale content types.""" with captured_stdout() as stdout: call_command("remove_stale_contenttypes", interactive=False, verbosity=2) self.assertIn("Deleting stale content type", stdout.getvalue()) self.assertEqual(ContentType.objects.count(), self.before_count) def test_unavailable_content_type_model(self): """A ContentType isn't created if the model isn't available.""" apps = Apps() with self.assertNumQueries(0): contenttypes_management.create_contenttypes( self.app_config, interactive=False, verbosity=0, apps=apps ) self.assertEqual(ContentType.objects.count(), self.before_count + 1) @modify_settings(INSTALLED_APPS={"remove": ["empty_models"]}) def test_contenttypes_removed_in_installed_apps_without_models(self): ContentType.objects.create(app_label="empty_models", model="Fake 1") ContentType.objects.create(app_label="no_models", model="Fake 2") with mock.patch( "builtins.input", return_value="yes" ), captured_stdout() as stdout: call_command("remove_stale_contenttypes", verbosity=2) self.assertNotIn( "Deleting stale content type 'empty_models | Fake 1'", stdout.getvalue(), ) self.assertIn( "Deleting stale content type 'no_models | Fake 2'", stdout.getvalue(), ) self.assertEqual(ContentType.objects.count(), self.before_count + 1) @modify_settings(INSTALLED_APPS={"remove": ["empty_models"]}) def test_contenttypes_removed_for_apps_not_in_installed_apps(self): ContentType.objects.create(app_label="empty_models", model="Fake 1") ContentType.objects.create(app_label="no_models", model="Fake 2") with mock.patch( "builtins.input", return_value="yes" ), captured_stdout() as stdout: call_command( "remove_stale_contenttypes", include_stale_apps=True, verbosity=2 ) self.assertIn( "Deleting stale content type 'empty_models | Fake 1'", stdout.getvalue(), ) self.assertIn( "Deleting stale content type 'no_models | Fake 2'", stdout.getvalue(), ) self.assertEqual(ContentType.objects.count(), self.before_count)
0712200de07f1b3020de0567d32e8bc3c0d3683e101ce45fc977ff113e9ba136
from django.apps.registry import apps from django.conf import settings from django.contrib.contenttypes import management as contenttypes_management from django.contrib.contenttypes.models import ContentType from django.core.management import call_command from django.db import migrations, models from django.test import TransactionTestCase, override_settings @override_settings( MIGRATION_MODULES=dict( settings.MIGRATION_MODULES, contenttypes_tests="contenttypes_tests.operations_migrations", ), ) class ContentTypeOperationsTests(TransactionTestCase): databases = {"default", "other"} available_apps = [ "contenttypes_tests", "django.contrib.contenttypes", ] class TestRouter: def db_for_write(self, model, **hints): return "default" def setUp(self): app_config = apps.get_app_config("contenttypes_tests") models.signals.post_migrate.connect( self.assertOperationsInjected, sender=app_config ) def tearDown(self): app_config = apps.get_app_config("contenttypes_tests") models.signals.post_migrate.disconnect( self.assertOperationsInjected, sender=app_config ) def assertOperationsInjected(self, plan, **kwargs): for migration, _backward in plan: operations = iter(migration.operations) for operation in operations: if isinstance(operation, migrations.RenameModel): next_operation = next(operations) self.assertIsInstance( next_operation, contenttypes_management.RenameContentType ) self.assertEqual(next_operation.app_label, migration.app_label) self.assertEqual(next_operation.old_model, operation.old_name_lower) self.assertEqual(next_operation.new_model, operation.new_name_lower) def test_existing_content_type_rename(self): ContentType.objects.create(app_label="contenttypes_tests", model="foo") call_command( "migrate", "contenttypes_tests", database="default", interactive=False, verbosity=0, ) self.assertFalse( ContentType.objects.filter( app_label="contenttypes_tests", model="foo" ).exists() ) self.assertTrue( ContentType.objects.filter( app_label="contenttypes_tests", model="renamedfoo" ).exists() ) call_command( "migrate", "contenttypes_tests", "zero", database="default", interactive=False, verbosity=0, ) self.assertTrue( ContentType.objects.filter( app_label="contenttypes_tests", model="foo" ).exists() ) self.assertFalse( ContentType.objects.filter( app_label="contenttypes_tests", model="renamedfoo" ).exists() ) @override_settings(DATABASE_ROUTERS=[TestRouter()]) def test_existing_content_type_rename_other_database(self): ContentType.objects.using("other").create( app_label="contenttypes_tests", model="foo" ) other_content_types = ContentType.objects.using("other").filter( app_label="contenttypes_tests" ) call_command( "migrate", "contenttypes_tests", database="other", interactive=False, verbosity=0, ) self.assertFalse(other_content_types.filter(model="foo").exists()) self.assertTrue(other_content_types.filter(model="renamedfoo").exists()) call_command( "migrate", "contenttypes_tests", "zero", database="other", interactive=False, verbosity=0, ) self.assertTrue(other_content_types.filter(model="foo").exists()) self.assertFalse(other_content_types.filter(model="renamedfoo").exists()) def test_missing_content_type_rename_ignore(self): call_command( "migrate", "contenttypes_tests", database="default", interactive=False, verbosity=0, ) self.assertFalse( ContentType.objects.filter( app_label="contenttypes_tests", model="foo" ).exists() ) self.assertTrue( ContentType.objects.filter( app_label="contenttypes_tests", model="renamedfoo" ).exists() ) call_command( "migrate", "contenttypes_tests", "zero", database="default", interactive=False, verbosity=0, ) self.assertTrue( ContentType.objects.filter( app_label="contenttypes_tests", model="foo" ).exists() ) self.assertFalse( ContentType.objects.filter( app_label="contenttypes_tests", model="renamedfoo" ).exists() ) def test_content_type_rename_conflict(self): ContentType.objects.create(app_label="contenttypes_tests", model="foo") ContentType.objects.create(app_label="contenttypes_tests", model="renamedfoo") call_command( "migrate", "contenttypes_tests", database="default", interactive=False, verbosity=0, ) self.assertTrue( ContentType.objects.filter( app_label="contenttypes_tests", model="foo" ).exists() ) self.assertTrue( ContentType.objects.filter( app_label="contenttypes_tests", model="renamedfoo" ).exists() ) call_command( "migrate", "contenttypes_tests", "zero", database="default", interactive=False, verbosity=0, ) self.assertTrue( ContentType.objects.filter( app_label="contenttypes_tests", model="foo" ).exists() ) self.assertTrue( ContentType.objects.filter( app_label="contenttypes_tests", model="renamedfoo" ).exists() )
9cb27da0b064b7c48967e93fed0ca4e300fa2e95ee096147a9460c55b9f1eabb
import json from django.contrib.contenttypes.fields import GenericForeignKey from django.db import models from django.test import TestCase from django.test.utils import isolate_apps from .models import Answer, Post, Question @isolate_apps("contenttypes_tests") class GenericForeignKeyTests(TestCase): def test_str(self): class Model(models.Model): field = GenericForeignKey() self.assertEqual(str(Model.field), "contenttypes_tests.Model.field") def test_get_content_type_no_arguments(self): with self.assertRaisesMessage( Exception, "Impossible arguments to GFK.get_content_type!" ): Answer.question.get_content_type() def test_incorrect_get_prefetch_queryset_arguments(self): with self.assertRaisesMessage( ValueError, "Custom queryset can't be used for this lookup." ): Answer.question.get_prefetch_queryset( Answer.objects.all(), Answer.objects.all() ) def test_get_object_cache_respects_deleted_objects(self): question = Question.objects.create(text="Who?") post = Post.objects.create(title="Answer", parent=question) question_pk = question.pk Question.objects.all().delete() post = Post.objects.get(pk=post.pk) with self.assertNumQueries(1): self.assertEqual(post.object_id, question_pk) self.assertIsNone(post.parent) self.assertIsNone(post.parent) class GenericRelationTests(TestCase): def test_value_to_string(self): question = Question.objects.create(text="test") answer1 = Answer.objects.create(question=question) answer2 = Answer.objects.create(question=question) result = json.loads(Question.answer_set.field.value_to_string(question)) self.assertCountEqual(result, [answer1.pk, answer2.pk])
a069580b6e21ed57a53ce843bfe2d6b9499d888db6c8c3d7bdcee44b2a83927e
from django.contrib.contenttypes import views from django.urls import re_path urlpatterns = [ re_path(r"^shortcut/([0-9]+)/(.*)/$", views.shortcut), ]
a078fc5e5ac75bf758de80130585f402d7b1c99f312eed4b5efe247ce6a0a84f
from unittest import mock from django.contrib.contenttypes.checks import check_model_name_lengths from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation from django.contrib.contenttypes.models import ContentType from django.core import checks from django.db import models from django.test import SimpleTestCase, override_settings from django.test.utils import isolate_apps @isolate_apps("contenttypes_tests", attr_name="apps") class GenericForeignKeyTests(SimpleTestCase): def test_missing_content_type_field(self): class TaggedItem(models.Model): # no content_type field object_id = models.PositiveIntegerField() content_object = GenericForeignKey() expected = [ checks.Error( "The GenericForeignKey content type references the nonexistent " "field 'TaggedItem.content_type'.", obj=TaggedItem.content_object, id="contenttypes.E002", ) ] self.assertEqual(TaggedItem.content_object.check(), expected) def test_invalid_content_type_field(self): class Model(models.Model): content_type = models.IntegerField() # should be ForeignKey object_id = models.PositiveIntegerField() content_object = GenericForeignKey("content_type", "object_id") self.assertEqual( Model.content_object.check(), [ checks.Error( "'Model.content_type' is not a ForeignKey.", hint=( "GenericForeignKeys must use a ForeignKey to " "'contenttypes.ContentType' as the 'content_type' field." ), obj=Model.content_object, id="contenttypes.E003", ) ], ) def test_content_type_field_pointing_to_wrong_model(self): class Model(models.Model): content_type = models.ForeignKey( "self", models.CASCADE ) # should point to ContentType object_id = models.PositiveIntegerField() content_object = GenericForeignKey("content_type", "object_id") self.assertEqual( Model.content_object.check(), [ checks.Error( "'Model.content_type' is not a ForeignKey to " "'contenttypes.ContentType'.", hint=( "GenericForeignKeys must use a ForeignKey to " "'contenttypes.ContentType' as the 'content_type' field." ), obj=Model.content_object, id="contenttypes.E004", ) ], ) def test_missing_object_id_field(self): class TaggedItem(models.Model): content_type = models.ForeignKey(ContentType, models.CASCADE) # missing object_id field content_object = GenericForeignKey() self.assertEqual( TaggedItem.content_object.check(), [ checks.Error( "The GenericForeignKey object ID references the nonexistent " "field 'object_id'.", obj=TaggedItem.content_object, id="contenttypes.E001", ) ], ) def test_field_name_ending_with_underscore(self): class Model(models.Model): content_type = models.ForeignKey(ContentType, models.CASCADE) object_id = models.PositiveIntegerField() content_object_ = GenericForeignKey("content_type", "object_id") self.assertEqual( Model.content_object_.check(), [ checks.Error( "Field names must not end with an underscore.", obj=Model.content_object_, id="fields.E001", ) ], ) @override_settings( INSTALLED_APPS=[ "django.contrib.auth", "django.contrib.contenttypes", "contenttypes_tests", ] ) def test_generic_foreign_key_checks_are_performed(self): class Model(models.Model): content_object = GenericForeignKey() with mock.patch.object(GenericForeignKey, "check") as check: checks.run_checks(app_configs=self.apps.get_app_configs()) check.assert_called_once_with() @isolate_apps("contenttypes_tests") class GenericRelationTests(SimpleTestCase): def test_valid_generic_relationship(self): class TaggedItem(models.Model): content_type = models.ForeignKey(ContentType, models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey() class Bookmark(models.Model): tags = GenericRelation("TaggedItem") self.assertEqual(Bookmark.tags.field.check(), []) def test_valid_generic_relationship_with_explicit_fields(self): class TaggedItem(models.Model): custom_content_type = models.ForeignKey(ContentType, models.CASCADE) custom_object_id = models.PositiveIntegerField() content_object = GenericForeignKey( "custom_content_type", "custom_object_id" ) class Bookmark(models.Model): tags = GenericRelation( "TaggedItem", content_type_field="custom_content_type", object_id_field="custom_object_id", ) self.assertEqual(Bookmark.tags.field.check(), []) def test_pointing_to_missing_model(self): class Model(models.Model): rel = GenericRelation("MissingModel") self.assertEqual( Model.rel.field.check(), [ checks.Error( "Field defines a relation with model 'MissingModel', " "which is either not installed, or is abstract.", obj=Model.rel.field, id="fields.E300", ) ], ) def test_valid_self_referential_generic_relationship(self): class Model(models.Model): rel = GenericRelation("Model") content_type = models.ForeignKey(ContentType, models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey("content_type", "object_id") self.assertEqual(Model.rel.field.check(), []) def test_missing_generic_foreign_key(self): class TaggedItem(models.Model): content_type = models.ForeignKey(ContentType, models.CASCADE) object_id = models.PositiveIntegerField() class Bookmark(models.Model): tags = GenericRelation("TaggedItem") self.assertEqual( Bookmark.tags.field.check(), [ checks.Error( "The GenericRelation defines a relation with the model " "'contenttypes_tests.TaggedItem', but that model does not have a " "GenericForeignKey.", obj=Bookmark.tags.field, id="contenttypes.E004", ) ], ) @override_settings(TEST_SWAPPED_MODEL="contenttypes_tests.Replacement") def test_pointing_to_swapped_model(self): class Replacement(models.Model): pass class SwappedModel(models.Model): content_type = models.ForeignKey(ContentType, models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey() class Meta: swappable = "TEST_SWAPPED_MODEL" class Model(models.Model): rel = GenericRelation("SwappedModel") self.assertEqual( Model.rel.field.check(), [ checks.Error( "Field defines a relation with the model " "'contenttypes_tests.SwappedModel', " "which has been swapped out.", hint=( "Update the relation to point at 'settings.TEST_SWAPPED_MODEL'." ), obj=Model.rel.field, id="fields.E301", ) ], ) def test_field_name_ending_with_underscore(self): class TaggedItem(models.Model): content_type = models.ForeignKey(ContentType, models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey() class InvalidBookmark(models.Model): tags_ = GenericRelation("TaggedItem") self.assertEqual( InvalidBookmark.tags_.field.check(), [ checks.Error( "Field names must not end with an underscore.", obj=InvalidBookmark.tags_.field, id="fields.E001", ) ], ) @isolate_apps("contenttypes_tests", attr_name="apps") class ModelCheckTests(SimpleTestCase): def test_model_name_too_long(self): model = type("A" * 101, (models.Model,), {"__module__": self.__module__}) self.assertEqual( check_model_name_lengths(self.apps.get_app_configs()), [ checks.Error( "Model names must be at most 100 characters (got 101).", obj=model, id="contenttypes.E005", ) ], ) def test_model_name_max_length(self): type("A" * 100, (models.Model,), {"__module__": self.__module__}) self.assertEqual(check_model_name_lengths(self.apps.get_app_configs()), [])
b45cc3e9ee155a95c96432fd074c19dd63479cc8e13fab20dfb64954c51e0edc
""" Testing signals emitted on changing m2m relations. """ from django.db import models from django.test import TestCase from .models import Car, Part, Person, SportsCar class ManyToManySignalsTest(TestCase): @classmethod def setUpTestData(cls): cls.vw = Car.objects.create(name="VW") cls.bmw = Car.objects.create(name="BMW") cls.toyota = Car.objects.create(name="Toyota") cls.wheelset = Part.objects.create(name="Wheelset") cls.doors = Part.objects.create(name="Doors") cls.engine = Part.objects.create(name="Engine") cls.airbag = Part.objects.create(name="Airbag") cls.sunroof = Part.objects.create(name="Sunroof") cls.alice = Person.objects.create(name="Alice") cls.bob = Person.objects.create(name="Bob") cls.chuck = Person.objects.create(name="Chuck") cls.daisy = Person.objects.create(name="Daisy") def setUp(self): self.m2m_changed_messages = [] def m2m_changed_signal_receiver(self, signal, sender, **kwargs): message = { "instance": kwargs["instance"], "action": kwargs["action"], "reverse": kwargs["reverse"], "model": kwargs["model"], } if kwargs["pk_set"]: message["objects"] = list( kwargs["model"].objects.filter(pk__in=kwargs["pk_set"]) ) self.m2m_changed_messages.append(message) def tearDown(self): # disconnect all signal handlers models.signals.m2m_changed.disconnect( self.m2m_changed_signal_receiver, Car.default_parts.through ) models.signals.m2m_changed.disconnect( self.m2m_changed_signal_receiver, Car.optional_parts.through ) models.signals.m2m_changed.disconnect( self.m2m_changed_signal_receiver, Person.fans.through ) models.signals.m2m_changed.disconnect( self.m2m_changed_signal_receiver, Person.friends.through ) def _initialize_signal_car(self, add_default_parts_before_set_signal=False): """Install a listener on the two m2m relations.""" models.signals.m2m_changed.connect( self.m2m_changed_signal_receiver, Car.optional_parts.through ) if add_default_parts_before_set_signal: # adding a default part to our car - no signal listener installed self.vw.default_parts.add(self.sunroof) models.signals.m2m_changed.connect( self.m2m_changed_signal_receiver, Car.default_parts.through ) def test_pk_set_on_repeated_add_remove(self): """ m2m_changed is always fired, even for repeated calls to the same method, but the behavior of pk_sets differs by action. - For signals related to `add()`, only PKs that will actually be inserted are sent. - For `remove()` all PKs are sent, even if they will not affect the DB. """ pk_sets_sent = [] def handler(signal, sender, **kwargs): if kwargs["action"] in ["pre_add", "pre_remove"]: pk_sets_sent.append(kwargs["pk_set"]) models.signals.m2m_changed.connect(handler, Car.default_parts.through) self.vw.default_parts.add(self.wheelset) self.vw.default_parts.add(self.wheelset) self.vw.default_parts.remove(self.wheelset) self.vw.default_parts.remove(self.wheelset) expected_pk_sets = [ {self.wheelset.pk}, set(), {self.wheelset.pk}, {self.wheelset.pk}, ] self.assertEqual(pk_sets_sent, expected_pk_sets) models.signals.m2m_changed.disconnect(handler, Car.default_parts.through) def test_m2m_relations_add_remove_clear(self): expected_messages = [] self._initialize_signal_car(add_default_parts_before_set_signal=True) self.vw.default_parts.add(self.wheelset, self.doors, self.engine) expected_messages.append( { "instance": self.vw, "action": "pre_add", "reverse": False, "model": Part, "objects": [self.doors, self.engine, self.wheelset], } ) expected_messages.append( { "instance": self.vw, "action": "post_add", "reverse": False, "model": Part, "objects": [self.doors, self.engine, self.wheelset], } ) self.assertEqual(self.m2m_changed_messages, expected_messages) # give the BMW and Toyota some doors as well self.doors.car_set.add(self.bmw, self.toyota) expected_messages.append( { "instance": self.doors, "action": "pre_add", "reverse": True, "model": Car, "objects": [self.bmw, self.toyota], } ) expected_messages.append( { "instance": self.doors, "action": "post_add", "reverse": True, "model": Car, "objects": [self.bmw, self.toyota], } ) self.assertEqual(self.m2m_changed_messages, expected_messages) def test_m2m_relations_signals_remove_relation(self): self._initialize_signal_car() # remove the engine from the self.vw and the airbag (which is not set # but is returned) self.vw.default_parts.remove(self.engine, self.airbag) self.assertEqual( self.m2m_changed_messages, [ { "instance": self.vw, "action": "pre_remove", "reverse": False, "model": Part, "objects": [self.airbag, self.engine], }, { "instance": self.vw, "action": "post_remove", "reverse": False, "model": Part, "objects": [self.airbag, self.engine], }, ], ) def test_m2m_relations_signals_give_the_self_vw_some_optional_parts(self): expected_messages = [] self._initialize_signal_car() # give the self.vw some optional parts (second relation to same model) self.vw.optional_parts.add(self.airbag, self.sunroof) expected_messages.append( { "instance": self.vw, "action": "pre_add", "reverse": False, "model": Part, "objects": [self.airbag, self.sunroof], } ) expected_messages.append( { "instance": self.vw, "action": "post_add", "reverse": False, "model": Part, "objects": [self.airbag, self.sunroof], } ) self.assertEqual(self.m2m_changed_messages, expected_messages) # add airbag to all the cars (even though the self.vw already has one) self.airbag.cars_optional.add(self.vw, self.bmw, self.toyota) expected_messages.append( { "instance": self.airbag, "action": "pre_add", "reverse": True, "model": Car, "objects": [self.bmw, self.toyota], } ) expected_messages.append( { "instance": self.airbag, "action": "post_add", "reverse": True, "model": Car, "objects": [self.bmw, self.toyota], } ) self.assertEqual(self.m2m_changed_messages, expected_messages) def test_m2m_relations_signals_reverse_relation_with_custom_related_name(self): self._initialize_signal_car() # remove airbag from the self.vw (reverse relation with custom # related_name) self.airbag.cars_optional.remove(self.vw) self.assertEqual( self.m2m_changed_messages, [ { "instance": self.airbag, "action": "pre_remove", "reverse": True, "model": Car, "objects": [self.vw], }, { "instance": self.airbag, "action": "post_remove", "reverse": True, "model": Car, "objects": [self.vw], }, ], ) def test_m2m_relations_signals_clear_all_parts_of_the_self_vw(self): self._initialize_signal_car() # clear all parts of the self.vw self.vw.default_parts.clear() self.assertEqual( self.m2m_changed_messages, [ { "instance": self.vw, "action": "pre_clear", "reverse": False, "model": Part, }, { "instance": self.vw, "action": "post_clear", "reverse": False, "model": Part, }, ], ) def test_m2m_relations_signals_all_the_doors_off_of_cars(self): self._initialize_signal_car() # take all the doors off of cars self.doors.car_set.clear() self.assertEqual( self.m2m_changed_messages, [ { "instance": self.doors, "action": "pre_clear", "reverse": True, "model": Car, }, { "instance": self.doors, "action": "post_clear", "reverse": True, "model": Car, }, ], ) def test_m2m_relations_signals_reverse_relation(self): self._initialize_signal_car() # take all the airbags off of cars (clear reverse relation with custom # related_name) self.airbag.cars_optional.clear() self.assertEqual( self.m2m_changed_messages, [ { "instance": self.airbag, "action": "pre_clear", "reverse": True, "model": Car, }, { "instance": self.airbag, "action": "post_clear", "reverse": True, "model": Car, }, ], ) def test_m2m_relations_signals_alternative_ways(self): expected_messages = [] self._initialize_signal_car() # alternative ways of setting relation: self.vw.default_parts.create(name="Windows") p6 = Part.objects.get(name="Windows") expected_messages.append( { "instance": self.vw, "action": "pre_add", "reverse": False, "model": Part, "objects": [p6], } ) expected_messages.append( { "instance": self.vw, "action": "post_add", "reverse": False, "model": Part, "objects": [p6], } ) self.assertEqual(self.m2m_changed_messages, expected_messages) # direct assignment clears the set first, then adds self.vw.default_parts.set([self.wheelset, self.doors, self.engine]) expected_messages.append( { "instance": self.vw, "action": "pre_remove", "reverse": False, "model": Part, "objects": [p6], } ) expected_messages.append( { "instance": self.vw, "action": "post_remove", "reverse": False, "model": Part, "objects": [p6], } ) expected_messages.append( { "instance": self.vw, "action": "pre_add", "reverse": False, "model": Part, "objects": [self.doors, self.engine, self.wheelset], } ) expected_messages.append( { "instance": self.vw, "action": "post_add", "reverse": False, "model": Part, "objects": [self.doors, self.engine, self.wheelset], } ) self.assertEqual(self.m2m_changed_messages, expected_messages) def test_m2m_relations_signals_clearing_removing(self): expected_messages = [] self._initialize_signal_car(add_default_parts_before_set_signal=True) # set by clearing. self.vw.default_parts.set([self.wheelset, self.doors, self.engine], clear=True) expected_messages.append( { "instance": self.vw, "action": "pre_clear", "reverse": False, "model": Part, } ) expected_messages.append( { "instance": self.vw, "action": "post_clear", "reverse": False, "model": Part, } ) expected_messages.append( { "instance": self.vw, "action": "pre_add", "reverse": False, "model": Part, "objects": [self.doors, self.engine, self.wheelset], } ) expected_messages.append( { "instance": self.vw, "action": "post_add", "reverse": False, "model": Part, "objects": [self.doors, self.engine, self.wheelset], } ) self.assertEqual(self.m2m_changed_messages, expected_messages) # set by only removing what's necessary. self.vw.default_parts.set([self.wheelset, self.doors], clear=False) expected_messages.append( { "instance": self.vw, "action": "pre_remove", "reverse": False, "model": Part, "objects": [self.engine], } ) expected_messages.append( { "instance": self.vw, "action": "post_remove", "reverse": False, "model": Part, "objects": [self.engine], } ) self.assertEqual(self.m2m_changed_messages, expected_messages) def test_m2m_relations_signals_when_inheritance(self): expected_messages = [] self._initialize_signal_car(add_default_parts_before_set_signal=True) # Signals still work when model inheritance is involved c4 = SportsCar.objects.create(name="Bugatti", price="1000000") c4b = Car.objects.get(name="Bugatti") c4.default_parts.set([self.doors]) expected_messages.append( { "instance": c4, "action": "pre_add", "reverse": False, "model": Part, "objects": [self.doors], } ) expected_messages.append( { "instance": c4, "action": "post_add", "reverse": False, "model": Part, "objects": [self.doors], } ) self.assertEqual(self.m2m_changed_messages, expected_messages) self.engine.car_set.add(c4) expected_messages.append( { "instance": self.engine, "action": "pre_add", "reverse": True, "model": Car, "objects": [c4b], } ) expected_messages.append( { "instance": self.engine, "action": "post_add", "reverse": True, "model": Car, "objects": [c4b], } ) self.assertEqual(self.m2m_changed_messages, expected_messages) def _initialize_signal_person(self): # Install a listener on the two m2m relations. models.signals.m2m_changed.connect( self.m2m_changed_signal_receiver, Person.fans.through ) models.signals.m2m_changed.connect( self.m2m_changed_signal_receiver, Person.friends.through ) def test_m2m_relations_with_self_add_friends(self): self._initialize_signal_person() self.alice.friends.set([self.bob, self.chuck]) self.assertEqual( self.m2m_changed_messages, [ { "instance": self.alice, "action": "pre_add", "reverse": False, "model": Person, "objects": [self.bob, self.chuck], }, { "instance": self.alice, "action": "post_add", "reverse": False, "model": Person, "objects": [self.bob, self.chuck], }, ], ) def test_m2m_relations_with_self_add_fan(self): self._initialize_signal_person() self.alice.fans.set([self.daisy]) self.assertEqual( self.m2m_changed_messages, [ { "instance": self.alice, "action": "pre_add", "reverse": False, "model": Person, "objects": [self.daisy], }, { "instance": self.alice, "action": "post_add", "reverse": False, "model": Person, "objects": [self.daisy], }, ], ) def test_m2m_relations_with_self_add_idols(self): self._initialize_signal_person() self.chuck.idols.set([self.alice, self.bob]) self.assertEqual( self.m2m_changed_messages, [ { "instance": self.chuck, "action": "pre_add", "reverse": True, "model": Person, "objects": [self.alice, self.bob], }, { "instance": self.chuck, "action": "post_add", "reverse": True, "model": Person, "objects": [self.alice, self.bob], }, ], )
e00d81036b04efbfc185f3c0b8473081aadf68ac0edf51664777a596203a3909
from django.db import models class Part(models.Model): name = models.CharField(max_length=20) class Meta: ordering = ("name",) class Car(models.Model): name = models.CharField(max_length=20) default_parts = models.ManyToManyField(Part) optional_parts = models.ManyToManyField(Part, related_name="cars_optional") class Meta: ordering = ("name",) class SportsCar(Car): price = models.IntegerField() class Person(models.Model): name = models.CharField(max_length=20) fans = models.ManyToManyField("self", related_name="idols", symmetrical=False) friends = models.ManyToManyField("self") class Meta: ordering = ("name",)
6f0baea706ae043700791f591711d5ae08293147ec8b2d669604d5a0296b6266
from django.contrib.auth.backends import ModelBackend from .models import CustomUser class CustomUserBackend(ModelBackend): def authenticate(self, request, username=None, password=None): try: user = CustomUser.custom_objects.get_by_natural_key(username) if user.check_password(password): return user except CustomUser.DoesNotExist: return None def get_user(self, user_id): try: return CustomUser.custom_objects.get(pk=user_id) except CustomUser.DoesNotExist: return None
1be3b4ca552731047f8e17e5ea27dce2ac610111ffe2a438ee397863bb499f73
""" Regression tests for the Test Client, especially the customized assertions. """ import itertools import os from django.contrib.auth.models import User from django.contrib.auth.signals import user_logged_in, user_logged_out from django.http import HttpResponse from django.template import Context, RequestContext, TemplateSyntaxError, engines from django.template.response import SimpleTemplateResponse from django.test import ( Client, SimpleTestCase, TestCase, modify_settings, override_settings, ) from django.test.client import RedirectCycleError, RequestFactory, encode_file from django.test.utils import ContextList from django.urls import NoReverseMatch, reverse from django.utils.translation import gettext_lazy from .models import CustomUser from .views import CustomTestException class TestDataMixin: @classmethod def setUpTestData(cls): cls.u1 = User.objects.create_user(username="testclient", password="password") cls.staff = User.objects.create_user( username="staff", password="password", is_staff=True ) @override_settings(ROOT_URLCONF="test_client_regress.urls") class AssertContainsTests(SimpleTestCase): def test_contains(self): "Responses can be inspected for content, including counting repeated substrings" response = self.client.get("/no_template_view/") self.assertNotContains(response, "never") self.assertContains(response, "never", 0) self.assertContains(response, "once") self.assertContains(response, "once", 1) self.assertContains(response, "twice") self.assertContains(response, "twice", 2) try: self.assertContains(response, "text", status_code=999) except AssertionError as e: self.assertIn( "Couldn't retrieve content: Response code was 200 (expected 999)", str(e), ) try: self.assertContains(response, "text", status_code=999, msg_prefix="abc") except AssertionError as e: self.assertIn( "abc: Couldn't retrieve content: Response code was 200 (expected 999)", str(e), ) try: self.assertNotContains(response, "text", status_code=999) except AssertionError as e: self.assertIn( "Couldn't retrieve content: Response code was 200 (expected 999)", str(e), ) try: self.assertNotContains(response, "text", status_code=999, msg_prefix="abc") except AssertionError as e: self.assertIn( "abc: Couldn't retrieve content: Response code was 200 (expected 999)", str(e), ) try: self.assertNotContains(response, "once") except AssertionError as e: self.assertIn("Response should not contain 'once'", str(e)) try: self.assertNotContains(response, "once", msg_prefix="abc") except AssertionError as e: self.assertIn("abc: Response should not contain 'once'", str(e)) try: self.assertContains(response, "never", 1) except AssertionError as e: self.assertIn( "Found 0 instances of 'never' in response (expected 1)", str(e) ) try: self.assertContains(response, "never", 1, msg_prefix="abc") except AssertionError as e: self.assertIn( "abc: Found 0 instances of 'never' in response (expected 1)", str(e) ) try: self.assertContains(response, "once", 0) except AssertionError as e: self.assertIn( "Found 1 instances of 'once' in response (expected 0)", str(e) ) try: self.assertContains(response, "once", 0, msg_prefix="abc") except AssertionError as e: self.assertIn( "abc: Found 1 instances of 'once' in response (expected 0)", str(e) ) try: self.assertContains(response, "once", 2) except AssertionError as e: self.assertIn( "Found 1 instances of 'once' in response (expected 2)", str(e) ) try: self.assertContains(response, "once", 2, msg_prefix="abc") except AssertionError as e: self.assertIn( "abc: Found 1 instances of 'once' in response (expected 2)", str(e) ) try: self.assertContains(response, "twice", 1) except AssertionError as e: self.assertIn( "Found 2 instances of 'twice' in response (expected 1)", str(e) ) try: self.assertContains(response, "twice", 1, msg_prefix="abc") except AssertionError as e: self.assertIn( "abc: Found 2 instances of 'twice' in response (expected 1)", str(e) ) try: self.assertContains(response, "thrice") except AssertionError as e: self.assertIn("Couldn't find 'thrice' in response", str(e)) try: self.assertContains(response, "thrice", msg_prefix="abc") except AssertionError as e: self.assertIn("abc: Couldn't find 'thrice' in response", str(e)) try: self.assertContains(response, "thrice", 3) except AssertionError as e: self.assertIn( "Found 0 instances of 'thrice' in response (expected 3)", str(e) ) try: self.assertContains(response, "thrice", 3, msg_prefix="abc") except AssertionError as e: self.assertIn( "abc: Found 0 instances of 'thrice' in response (expected 3)", str(e) ) def test_unicode_contains(self): "Unicode characters can be found in template context" # Regression test for #10183 r = self.client.get("/check_unicode/") self.assertContains(r, "さかき") self.assertContains(r, b"\xe5\xb3\xa0".decode()) def test_unicode_not_contains(self): "Unicode characters can be searched for, and not found in template context" # Regression test for #10183 r = self.client.get("/check_unicode/") self.assertNotContains(r, "はたけ") self.assertNotContains(r, b"\xe3\x81\xaf\xe3\x81\x9f\xe3\x81\x91".decode()) def test_binary_contains(self): r = self.client.get("/check_binary/") self.assertContains(r, b"%PDF-1.4\r\n%\x93\x8c\x8b\x9e") with self.assertRaises(AssertionError): self.assertContains(r, b"%PDF-1.4\r\n%\x93\x8c\x8b\x9e", count=2) def test_binary_not_contains(self): r = self.client.get("/check_binary/") self.assertNotContains(r, b"%ODF-1.4\r\n%\x93\x8c\x8b\x9e") with self.assertRaises(AssertionError): self.assertNotContains(r, b"%PDF-1.4\r\n%\x93\x8c\x8b\x9e") def test_nontext_contains(self): r = self.client.get("/no_template_view/") self.assertContains(r, gettext_lazy("once")) def test_nontext_not_contains(self): r = self.client.get("/no_template_view/") self.assertNotContains(r, gettext_lazy("never")) def test_assert_contains_renders_template_response(self): """ An unrendered SimpleTemplateResponse may be used in assertContains(). """ template = engines["django"].from_string("Hello") response = SimpleTemplateResponse(template) self.assertContains(response, "Hello") def test_assert_contains_using_non_template_response(self): """auto-rendering does not affect responses that aren't instances (or subclasses) of SimpleTemplateResponse. Refs #15826. """ response = HttpResponse("Hello") self.assertContains(response, "Hello") def test_assert_not_contains_renders_template_response(self): """ An unrendered SimpleTemplateResponse may be used in assertNotContains(). """ template = engines["django"].from_string("Hello") response = SimpleTemplateResponse(template) self.assertNotContains(response, "Bye") def test_assert_not_contains_using_non_template_response(self): """ auto-rendering does not affect responses that aren't instances (or subclasses) of SimpleTemplateResponse. """ response = HttpResponse("Hello") self.assertNotContains(response, "Bye") @override_settings(ROOT_URLCONF="test_client_regress.urls") class AssertTemplateUsedTests(TestDataMixin, TestCase): def test_no_context(self): "Template usage assertions work then templates aren't in use" response = self.client.get("/no_template_view/") # The no template case doesn't mess with the template assertions self.assertTemplateNotUsed(response, "GET Template") try: self.assertTemplateUsed(response, "GET Template") except AssertionError as e: self.assertIn("No templates used to render the response", str(e)) try: self.assertTemplateUsed(response, "GET Template", msg_prefix="abc") except AssertionError as e: self.assertIn("abc: No templates used to render the response", str(e)) msg = "No templates used to render the response" with self.assertRaisesMessage(AssertionError, msg): self.assertTemplateUsed(response, "GET Template", count=2) def test_single_context(self): "Template assertions work when there is a single context" response = self.client.get("/post_view/", {}) msg = ( ": Template 'Empty GET Template' was used unexpectedly in " "rendering the response" ) with self.assertRaisesMessage(AssertionError, msg): self.assertTemplateNotUsed(response, "Empty GET Template") with self.assertRaisesMessage(AssertionError, "abc" + msg): self.assertTemplateNotUsed(response, "Empty GET Template", msg_prefix="abc") msg = ( ": Template 'Empty POST Template' was not a template used to " "render the response. Actual template(s) used: Empty GET Template" ) with self.assertRaisesMessage(AssertionError, msg): self.assertTemplateUsed(response, "Empty POST Template") with self.assertRaisesMessage(AssertionError, "abc" + msg): self.assertTemplateUsed(response, "Empty POST Template", msg_prefix="abc") msg = ( ": Template 'Empty GET Template' was expected to be rendered 2 " "time(s) but was actually rendered 1 time(s)." ) with self.assertRaisesMessage(AssertionError, msg): self.assertTemplateUsed(response, "Empty GET Template", count=2) with self.assertRaisesMessage(AssertionError, "abc" + msg): self.assertTemplateUsed( response, "Empty GET Template", msg_prefix="abc", count=2 ) def test_multiple_context(self): "Template assertions work when there are multiple contexts" post_data = { "text": "Hello World", "email": "[email protected]", "value": 37, "single": "b", "multi": ("b", "c", "e"), } response = self.client.post("/form_view_with_template/", post_data) self.assertContains(response, "POST data OK") msg = "Template '%s' was used unexpectedly in rendering the response" with self.assertRaisesMessage(AssertionError, msg % "form_view.html"): self.assertTemplateNotUsed(response, "form_view.html") with self.assertRaisesMessage(AssertionError, msg % "base.html"): self.assertTemplateNotUsed(response, "base.html") msg = ( "Template 'Valid POST Template' was not a template used to render " "the response. Actual template(s) used: form_view.html, base.html" ) with self.assertRaisesMessage(AssertionError, msg): self.assertTemplateUsed(response, "Valid POST Template") msg = ( "Template 'base.html' was expected to be rendered 2 time(s) but " "was actually rendered 1 time(s)." ) with self.assertRaisesMessage(AssertionError, msg): self.assertTemplateUsed(response, "base.html", count=2) def test_template_rendered_multiple_times(self): """Template assertions work when a template is rendered multiple times.""" response = self.client.get("/render_template_multiple_times/") self.assertTemplateUsed(response, "base.html", count=2) @override_settings(ROOT_URLCONF="test_client_regress.urls") class AssertRedirectsTests(SimpleTestCase): def test_redirect_page(self): "An assertion is raised if the original page couldn't be retrieved as expected" # This page will redirect with code 301, not 302 response = self.client.get("/permanent_redirect_view/") try: self.assertRedirects(response, "/get_view/") except AssertionError as e: self.assertIn( "Response didn't redirect as expected: Response code was 301 " "(expected 302)", str(e), ) try: self.assertRedirects(response, "/get_view/", msg_prefix="abc") except AssertionError as e: self.assertIn( "abc: Response didn't redirect as expected: Response code was 301 " "(expected 302)", str(e), ) def test_lost_query(self): """ An assertion is raised if the redirect location doesn't preserve GET parameters. """ response = self.client.get("/redirect_view/", {"var": "value"}) try: self.assertRedirects(response, "/get_view/") except AssertionError as e: self.assertIn( "Response redirected to '/get_view/?var=value', expected '/get_view/'", str(e), ) try: self.assertRedirects(response, "/get_view/", msg_prefix="abc") except AssertionError as e: self.assertIn( "abc: Response redirected to '/get_view/?var=value', expected " "'/get_view/'", str(e), ) def test_incorrect_target(self): "An assertion is raised if the response redirects to another target" response = self.client.get("/permanent_redirect_view/") try: # Should redirect to get_view self.assertRedirects(response, "/some_view/") except AssertionError as e: self.assertIn( "Response didn't redirect as expected: Response code was 301 " "(expected 302)", str(e), ) def test_target_page(self): """ An assertion is raised if the response redirect target cannot be retrieved as expected. """ response = self.client.get("/double_redirect_view/") try: # The redirect target responds with a 301 code, not 200 self.assertRedirects(response, "http://testserver/permanent_redirect_view/") except AssertionError as e: self.assertIn( "Couldn't retrieve redirection page '/permanent_redirect_view/': " "response code was 301 (expected 200)", str(e), ) try: # The redirect target responds with a 301 code, not 200 self.assertRedirects( response, "http://testserver/permanent_redirect_view/", msg_prefix="abc" ) except AssertionError as e: self.assertIn( "abc: Couldn't retrieve redirection page '/permanent_redirect_view/': " "response code was 301 (expected 200)", str(e), ) def test_redirect_chain(self): "You can follow a redirect chain of multiple redirects" response = self.client.get("/redirects/further/more/", {}, follow=True) self.assertRedirects( response, "/no_template_view/", status_code=302, target_status_code=200 ) self.assertEqual(len(response.redirect_chain), 1) self.assertEqual(response.redirect_chain[0], ("/no_template_view/", 302)) def test_multiple_redirect_chain(self): "You can follow a redirect chain of multiple redirects" response = self.client.get("/redirects/", {}, follow=True) self.assertRedirects( response, "/no_template_view/", status_code=302, target_status_code=200 ) self.assertEqual(len(response.redirect_chain), 3) self.assertEqual(response.redirect_chain[0], ("/redirects/further/", 302)) self.assertEqual(response.redirect_chain[1], ("/redirects/further/more/", 302)) self.assertEqual(response.redirect_chain[2], ("/no_template_view/", 302)) def test_redirect_chain_to_non_existent(self): "You can follow a chain to a nonexistent view." response = self.client.get("/redirect_to_non_existent_view2/", {}, follow=True) self.assertRedirects( response, "/non_existent_view/", status_code=302, target_status_code=404 ) def test_redirect_chain_to_self(self): "Redirections to self are caught and escaped" with self.assertRaises(RedirectCycleError) as context: self.client.get("/redirect_to_self/", {}, follow=True) response = context.exception.last_response # The chain of redirects stops once the cycle is detected. self.assertRedirects( response, "/redirect_to_self/", status_code=302, target_status_code=302 ) self.assertEqual(len(response.redirect_chain), 2) def test_redirect_to_self_with_changing_query(self): "Redirections don't loop forever even if query is changing" with self.assertRaises(RedirectCycleError): self.client.get( "/redirect_to_self_with_changing_query_view/", {"counter": "0"}, follow=True, ) def test_circular_redirect(self): "Circular redirect chains are caught and escaped" with self.assertRaises(RedirectCycleError) as context: self.client.get("/circular_redirect_1/", {}, follow=True) response = context.exception.last_response # The chain of redirects will get back to the starting point, but stop there. self.assertRedirects( response, "/circular_redirect_2/", status_code=302, target_status_code=302 ) self.assertEqual(len(response.redirect_chain), 4) def test_redirect_chain_post(self): "A redirect chain will be followed from an initial POST post" response = self.client.post("/redirects/", {"nothing": "to_send"}, follow=True) self.assertRedirects(response, "/no_template_view/", 302, 200) self.assertEqual(len(response.redirect_chain), 3) def test_redirect_chain_head(self): "A redirect chain will be followed from an initial HEAD request" response = self.client.head("/redirects/", {"nothing": "to_send"}, follow=True) self.assertRedirects(response, "/no_template_view/", 302, 200) self.assertEqual(len(response.redirect_chain), 3) def test_redirect_chain_options(self): "A redirect chain will be followed from an initial OPTIONS request" response = self.client.options("/redirects/", follow=True) self.assertRedirects(response, "/no_template_view/", 302, 200) self.assertEqual(len(response.redirect_chain), 3) def test_redirect_chain_put(self): "A redirect chain will be followed from an initial PUT request" response = self.client.put("/redirects/", follow=True) self.assertRedirects(response, "/no_template_view/", 302, 200) self.assertEqual(len(response.redirect_chain), 3) def test_redirect_chain_delete(self): "A redirect chain will be followed from an initial DELETE request" response = self.client.delete("/redirects/", follow=True) self.assertRedirects(response, "/no_template_view/", 302, 200) self.assertEqual(len(response.redirect_chain), 3) @modify_settings(ALLOWED_HOSTS={"append": "otherserver"}) def test_redirect_to_different_host(self): "The test client will preserve scheme, host and port changes" response = self.client.get("/redirect_other_host/", follow=True) self.assertRedirects( response, "https://otherserver:8443/no_template_view/", status_code=302, target_status_code=200, ) # We can't use is_secure() or get_host() # because response.request is a dictionary, not an HttpRequest self.assertEqual(response.request.get("wsgi.url_scheme"), "https") self.assertEqual(response.request.get("SERVER_NAME"), "otherserver") self.assertEqual(response.request.get("SERVER_PORT"), "8443") # assertRedirects() can follow redirect to 'otherserver' too. response = self.client.get("/redirect_other_host/", follow=False) self.assertRedirects( response, "https://otherserver:8443/no_template_view/", status_code=302, target_status_code=200, ) def test_redirect_chain_on_non_redirect_page(self): """ An assertion is raised if the original page couldn't be retrieved as expected. """ # This page will redirect with code 301, not 302 response = self.client.get("/get_view/", follow=True) try: self.assertRedirects(response, "/get_view/") except AssertionError as e: self.assertIn( "Response didn't redirect as expected: Response code was 200 " "(expected 302)", str(e), ) try: self.assertRedirects(response, "/get_view/", msg_prefix="abc") except AssertionError as e: self.assertIn( "abc: Response didn't redirect as expected: Response code was 200 " "(expected 302)", str(e), ) def test_redirect_on_non_redirect_page(self): "An assertion is raised if the original page couldn't be retrieved as expected" # This page will redirect with code 301, not 302 response = self.client.get("/get_view/") try: self.assertRedirects(response, "/get_view/") except AssertionError as e: self.assertIn( "Response didn't redirect as expected: Response code was 200 " "(expected 302)", str(e), ) try: self.assertRedirects(response, "/get_view/", msg_prefix="abc") except AssertionError as e: self.assertIn( "abc: Response didn't redirect as expected: Response code was 200 " "(expected 302)", str(e), ) def test_redirect_scheme(self): """ An assertion is raised if the response doesn't have the scheme specified in expected_url. """ # For all possible True/False combinations of follow and secure for follow, secure in itertools.product([True, False], repeat=2): # always redirects to https response = self.client.get( "/https_redirect_view/", follow=follow, secure=secure ) # the goal scheme is https self.assertRedirects( response, "https://testserver/secure_view/", status_code=302 ) with self.assertRaises(AssertionError): self.assertRedirects( response, "http://testserver/secure_view/", status_code=302 ) def test_redirect_fetch_redirect_response(self): """Preserve extra headers of requests made with django.test.Client.""" methods = ( "get", "post", "head", "options", "put", "patch", "delete", "trace", ) for method in methods: with self.subTest(method=method): req_method = getattr(self.client, method) response = req_method( "/redirect_based_on_extra_headers_1/", follow=False, HTTP_REDIRECT="val", ) self.assertRedirects( response, "/redirect_based_on_extra_headers_2/", fetch_redirect_response=True, status_code=302, target_status_code=302, ) @override_settings(ROOT_URLCONF="test_client_regress.urls") class AssertFormErrorTests(SimpleTestCase): def test_unknown_form(self): "An assertion is raised if the form name is unknown" post_data = { "text": "Hello World", "email": "not an email address", "value": 37, "single": "b", "multi": ("b", "c", "e"), } response = self.client.post("/form_view/", post_data) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, "Invalid POST Template") msg = "The form 'wrong_form' was not used to render the response" with self.assertRaisesMessage(AssertionError, msg): self.assertFormError(response, "wrong_form", "some_field", "Some error.") with self.assertRaisesMessage(AssertionError, "abc: " + msg): self.assertFormError( response, "wrong_form", "some_field", "Some error.", msg_prefix="abc" ) def test_unknown_field(self): "An assertion is raised if the field name is unknown" post_data = { "text": "Hello World", "email": "not an email address", "value": 37, "single": "b", "multi": ("b", "c", "e"), } response = self.client.post("/form_view/", post_data) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, "Invalid POST Template") msg = ( "The form <TestForm bound=True, valid=False, " "fields=(text;email;value;single;multi)> does not contain the field " "'some_field'." ) with self.assertRaisesMessage(AssertionError, msg): self.assertFormError(response, "form", "some_field", "Some error.") with self.assertRaisesMessage(AssertionError, "abc: " + msg): self.assertFormError( response, "form", "some_field", "Some error.", msg_prefix="abc" ) def test_noerror_field(self): "An assertion is raised if the field doesn't have any errors" post_data = { "text": "Hello World", "email": "not an email address", "value": 37, "single": "b", "multi": ("b", "c", "e"), } response = self.client.post("/form_view/", post_data) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, "Invalid POST Template") msg = ( "The errors of field 'value' on form <TestForm bound=True, valid=False, " "fields=(text;email;value;single;multi)> don't match." ) with self.assertRaisesMessage(AssertionError, msg): self.assertFormError(response, "form", "value", "Some error.") with self.assertRaisesMessage(AssertionError, "abc: " + msg): self.assertFormError( response, "form", "value", "Some error.", msg_prefix="abc" ) def test_unknown_error(self): "An assertion is raised if the field doesn't contain the provided error" post_data = { "text": "Hello World", "email": "not an email address", "value": 37, "single": "b", "multi": ("b", "c", "e"), } response = self.client.post("/form_view/", post_data) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, "Invalid POST Template") msg = ( "The errors of field 'email' on form <TestForm bound=True, valid=False, " "fields=(text;email;value;single;multi)> don't match." ) with self.assertRaisesMessage(AssertionError, msg): self.assertFormError(response, "form", "email", "Some error.") with self.assertRaisesMessage(AssertionError, "abc: " + msg): self.assertFormError( response, "form", "email", "Some error.", msg_prefix="abc" ) def test_unknown_nonfield_error(self): """ An assertion is raised if the form's non field errors doesn't contain the provided error. """ post_data = { "text": "Hello World", "email": "not an email address", "value": 37, "single": "b", "multi": ("b", "c", "e"), } response = self.client.post("/form_view/", post_data) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, "Invalid POST Template") msg = ( "The non-field errors of form <TestForm bound=True, valid=False, " "fields=(text;email;value;single;multi)> don't match." ) with self.assertRaisesMessage(AssertionError, msg): self.assertFormError(response, "form", None, "Some error.") with self.assertRaisesMessage(AssertionError, "abc: " + msg): self.assertFormError( response, "form", None, "Some error.", msg_prefix="abc" ) @override_settings(ROOT_URLCONF="test_client_regress.urls") class AssertFormsetErrorTests(SimpleTestCase): msg_prefixes = [("", {}), ("abc: ", {"msg_prefix": "abc"})] def setUp(self): """Makes response object for testing field and non-field errors""" # For testing field and non-field errors self.response_form_errors = self.getResponse( { "form-TOTAL_FORMS": "2", "form-INITIAL_FORMS": "2", "form-0-text": "Raise non-field error", "form-0-email": "not an email address", "form-0-value": 37, "form-0-single": "b", "form-0-multi": ("b", "c", "e"), "form-1-text": "Hello World", "form-1-email": "[email protected]", "form-1-value": 37, "form-1-single": "b", "form-1-multi": ("b", "c", "e"), } ) # For testing non-form errors self.response_nonform_errors = self.getResponse( { "form-TOTAL_FORMS": "2", "form-INITIAL_FORMS": "2", "form-0-text": "Hello World", "form-0-email": "[email protected]", "form-0-value": 37, "form-0-single": "b", "form-0-multi": ("b", "c", "e"), "form-1-text": "Hello World", "form-1-email": "[email protected]", "form-1-value": 37, "form-1-single": "b", "form-1-multi": ("b", "c", "e"), } ) def getResponse(self, post_data): response = self.client.post("/formset_view/", post_data) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, "Invalid POST Template") return response def test_unknown_formset(self): "An assertion is raised if the formset name is unknown" for prefix, kwargs in self.msg_prefixes: msg = ( prefix + "The formset 'wrong_formset' was not used to render the response" ) with self.assertRaisesMessage(AssertionError, msg): self.assertFormsetError( self.response_form_errors, "wrong_formset", 0, "Some_field", "Some error.", **kwargs, ) def test_unknown_field(self): "An assertion is raised if the field name is unknown" for prefix, kwargs in self.msg_prefixes: msg = ( f"{prefix}The form 0 of formset <TestFormFormSet: bound=True " f"valid=False total_forms=2> does not contain the field 'Some_field'." ) with self.assertRaisesMessage(AssertionError, msg): self.assertFormsetError( self.response_form_errors, "my_formset", 0, "Some_field", "Some error.", **kwargs, ) def test_no_error_field(self): "An assertion is raised if the field doesn't have any errors" for prefix, kwargs in self.msg_prefixes: msg = ( f"{prefix}The errors of field 'value' on form 1 of formset " f"<TestFormFormSet: bound=True valid=False total_forms=2> don't match." ) with self.assertRaisesMessage(AssertionError, msg): self.assertFormsetError( self.response_form_errors, "my_formset", 1, "value", "Some error.", **kwargs, ) def test_unknown_error(self): "An assertion is raised if the field doesn't contain the specified error" for prefix, kwargs in self.msg_prefixes: msg = ( f"{prefix}The errors of field 'email' on form 0 of formset " f"<TestFormFormSet: bound=True valid=False total_forms=2> don't match." ) with self.assertRaisesMessage(AssertionError, msg): self.assertFormsetError( self.response_form_errors, "my_formset", 0, "email", "Some error.", **kwargs, ) def test_field_error(self): "No assertion is raised if the field contains the provided error" error_msg = ["Enter a valid email address."] for prefix, kwargs in self.msg_prefixes: self.assertFormsetError( self.response_form_errors, "my_formset", 0, "email", error_msg, **kwargs ) def test_no_nonfield_error(self): """ An assertion is raised if the formsets non-field errors doesn't contain any errors. """ for prefix, kwargs in self.msg_prefixes: msg = ( f"{prefix}The non-field errors of form 1 of formset <TestFormFormSet: " f"bound=True valid=False total_forms=2> don't match." ) with self.assertRaisesMessage(AssertionError, msg): self.assertFormsetError( self.response_form_errors, "my_formset", 1, None, "Some error.", **kwargs, ) def test_unknown_nonfield_error(self): """ An assertion is raised if the formsets non-field errors doesn't contain the provided error. """ for prefix, kwargs in self.msg_prefixes: msg = ( f"{prefix}The non-field errors of form 0 of formset <TestFormFormSet: " f"bound=True valid=False total_forms=2> don't match." ) with self.assertRaisesMessage(AssertionError, msg): self.assertFormsetError( self.response_form_errors, "my_formset", 0, None, "Some error.", **kwargs, ) def test_nonfield_error(self): """ No assertion is raised if the formsets non-field errors contains the provided error. """ for prefix, kwargs in self.msg_prefixes: self.assertFormsetError( self.response_form_errors, "my_formset", 0, None, "Non-field error.", **kwargs, ) def test_no_nonform_error(self): """ An assertion is raised if the formsets non-form errors doesn't contain any errors. """ for prefix, kwargs in self.msg_prefixes: msg = ( f"{prefix}The non-form errors of formset <TestFormFormSet: bound=True " f"valid=False total_forms=2> don't match" ) with self.assertRaisesMessage(AssertionError, msg): self.assertFormsetError( self.response_form_errors, "my_formset", None, None, "Some error.", **kwargs, ) def test_unknown_nonform_error(self): """ An assertion is raised if the formsets non-form errors doesn't contain the provided error. """ for prefix, kwargs in self.msg_prefixes: msg = ( f"{prefix}The non-form errors of formset <TestFormFormSet: bound=True " f"valid=False total_forms=2> don't match" ) with self.assertRaisesMessage(AssertionError, msg): self.assertFormsetError( self.response_nonform_errors, "my_formset", None, None, "Some error.", **kwargs, ) def test_nonform_error(self): """ No assertion is raised if the formsets non-form errors contains the provided error. """ msg = "Forms in a set must have distinct email addresses." for prefix, kwargs in self.msg_prefixes: self.assertFormsetError( self.response_nonform_errors, "my_formset", None, None, msg, **kwargs ) @override_settings(ROOT_URLCONF="test_client_regress.urls") class LoginTests(TestDataMixin, TestCase): def test_login_different_client(self): "Using a different test client doesn't violate authentication" # Create a second client, and log in. c = Client() login = c.login(username="testclient", password="password") self.assertTrue(login, "Could not log in") # Get a redirection page with the second client. response = c.get("/login_protected_redirect_view/") # At this points, the self.client isn't logged in. # assertRedirects uses the original client, not the default client. self.assertRedirects(response, "/get_view/") @override_settings( SESSION_ENGINE="test_client_regress.session", ROOT_URLCONF="test_client_regress.urls", ) class SessionEngineTests(TestDataMixin, TestCase): def test_login(self): "A session engine that modifies the session key can be used to log in" login = self.client.login(username="testclient", password="password") self.assertTrue(login, "Could not log in") # Try to access a login protected page. response = self.client.get("/login_protected_view/") self.assertEqual(response.status_code, 200) self.assertEqual(response.context["user"].username, "testclient") @override_settings( ROOT_URLCONF="test_client_regress.urls", ) class URLEscapingTests(SimpleTestCase): def test_simple_argument_get(self): "Get a view that has a simple string argument" response = self.client.get(reverse("arg_view", args=["Slartibartfast"])) self.assertEqual(response.status_code, 200) self.assertEqual(response.content, b"Howdy, Slartibartfast") def test_argument_with_space_get(self): "Get a view that has a string argument that requires escaping" response = self.client.get(reverse("arg_view", args=["Arthur Dent"])) self.assertEqual(response.status_code, 200) self.assertEqual(response.content, b"Hi, Arthur") def test_simple_argument_post(self): "Post for a view that has a simple string argument" response = self.client.post(reverse("arg_view", args=["Slartibartfast"])) self.assertEqual(response.status_code, 200) self.assertEqual(response.content, b"Howdy, Slartibartfast") def test_argument_with_space_post(self): "Post for a view that has a string argument that requires escaping" response = self.client.post(reverse("arg_view", args=["Arthur Dent"])) self.assertEqual(response.status_code, 200) self.assertEqual(response.content, b"Hi, Arthur") @override_settings(ROOT_URLCONF="test_client_regress.urls") class ExceptionTests(TestDataMixin, TestCase): def test_exception_cleared(self): "#5836 - A stale user exception isn't re-raised by the test client." login = self.client.login(username="testclient", password="password") self.assertTrue(login, "Could not log in") with self.assertRaises(CustomTestException): self.client.get("/staff_only/") # At this point, an exception has been raised, and should be cleared. # This next operation should be successful; if it isn't we have a problem. login = self.client.login(username="staff", password="password") self.assertTrue(login, "Could not log in") self.client.get("/staff_only/") @override_settings(ROOT_URLCONF="test_client_regress.urls") class TemplateExceptionTests(SimpleTestCase): @override_settings( TEMPLATES=[ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [os.path.join(os.path.dirname(__file__), "bad_templates")], } ] ) def test_bad_404_template(self): "Errors found when rendering 404 error templates are re-raised" with self.assertRaises(TemplateSyntaxError): self.client.get("/no_such_view/") # We need two different tests to check URLconf substitution - one to check # it was changed, and another one (without self.urls) to check it was reverted on # teardown. This pair of tests relies upon the alphabetical ordering of test execution. @override_settings(ROOT_URLCONF="test_client_regress.urls") class UrlconfSubstitutionTests(SimpleTestCase): def test_urlconf_was_changed(self): "TestCase can enforce a custom URLconf on a per-test basis" url = reverse("arg_view", args=["somename"]) self.assertEqual(url, "/arg_view/somename/") # This test needs to run *after* UrlconfSubstitutionTests; the zz prefix in the # name is to ensure alphabetical ordering. class zzUrlconfSubstitutionTests(SimpleTestCase): def test_urlconf_was_reverted(self): """URLconf is reverted to original value after modification in a TestCase This will not find a match as the default ROOT_URLCONF is empty. """ with self.assertRaises(NoReverseMatch): reverse("arg_view", args=["somename"]) @override_settings(ROOT_URLCONF="test_client_regress.urls") class ContextTests(TestDataMixin, TestCase): def test_single_context(self): "Context variables can be retrieved from a single context" response = self.client.get("/request_data/", data={"foo": "whiz"}) self.assertIsInstance(response.context, RequestContext) self.assertIn("get-foo", response.context) self.assertEqual(response.context["get-foo"], "whiz") self.assertEqual(response.context["data"], "sausage") with self.assertRaisesMessage(KeyError, "does-not-exist"): response.context["does-not-exist"] def test_inherited_context(self): "Context variables can be retrieved from a list of contexts" response = self.client.get("/request_data_extended/", data={"foo": "whiz"}) self.assertEqual(response.context.__class__, ContextList) self.assertEqual(len(response.context), 2) self.assertIn("get-foo", response.context) self.assertEqual(response.context["get-foo"], "whiz") self.assertEqual(response.context["data"], "bacon") with self.assertRaisesMessage(KeyError, "does-not-exist"): response.context["does-not-exist"] def test_contextlist_keys(self): c1 = Context() c1.update({"hello": "world", "goodbye": "john"}) c1.update({"hello": "dolly", "dolly": "parton"}) c2 = Context() c2.update({"goodbye": "world", "python": "rocks"}) c2.update({"goodbye": "dolly"}) k = ContextList([c1, c2]) # None, True and False are builtins of BaseContext, and present # in every Context without needing to be added. self.assertEqual( {"None", "True", "False", "hello", "goodbye", "python", "dolly"}, k.keys() ) def test_contextlist_get(self): c1 = Context({"hello": "world", "goodbye": "john"}) c2 = Context({"goodbye": "world", "python": "rocks"}) k = ContextList([c1, c2]) self.assertEqual(k.get("hello"), "world") self.assertEqual(k.get("goodbye"), "john") self.assertEqual(k.get("python"), "rocks") self.assertEqual(k.get("nonexistent", "default"), "default") def test_15368(self): # Need to insert a context processor that assumes certain things about # the request instance. This triggers a bug caused by some ways of # copying RequestContext. with self.settings( TEMPLATES=[ { "BACKEND": "django.template.backends.django.DjangoTemplates", "APP_DIRS": True, "OPTIONS": { "context_processors": [ "test_client_regress.context_processors.special", ], }, } ] ): response = self.client.get("/request_context_view/") self.assertContains(response, "Path: /request_context_view/") def test_nested_requests(self): """ response.context is not lost when view call another view. """ response = self.client.get("/nested_view/") self.assertIsInstance(response.context, RequestContext) self.assertEqual(response.context["nested"], "yes") @override_settings(ROOT_URLCONF="test_client_regress.urls") class SessionTests(TestDataMixin, TestCase): def test_session(self): "The session isn't lost if a user logs in" # The session doesn't exist to start. response = self.client.get("/check_session/") self.assertEqual(response.status_code, 200) self.assertEqual(response.content, b"NO") # This request sets a session variable. response = self.client.get("/set_session/") self.assertEqual(response.status_code, 200) self.assertEqual(response.content, b"set_session") # The session has been modified response = self.client.get("/check_session/") self.assertEqual(response.status_code, 200) self.assertEqual(response.content, b"YES") # Log in login = self.client.login(username="testclient", password="password") self.assertTrue(login, "Could not log in") # Session should still contain the modified value response = self.client.get("/check_session/") self.assertEqual(response.status_code, 200) self.assertEqual(response.content, b"YES") def test_session_initiated(self): session = self.client.session session["session_var"] = "foo" session.save() response = self.client.get("/check_session/") self.assertEqual(response.content, b"foo") def test_logout(self): """Logout should work whether the user is logged in or not (#9978).""" self.client.logout() login = self.client.login(username="testclient", password="password") self.assertTrue(login, "Could not log in") self.client.logout() self.client.logout() def test_logout_with_user(self): """Logout should send user_logged_out signal if user was logged in.""" def listener(*args, **kwargs): listener.executed = True self.assertEqual(kwargs["sender"], User) listener.executed = False user_logged_out.connect(listener) self.client.login(username="testclient", password="password") self.client.logout() user_logged_out.disconnect(listener) self.assertTrue(listener.executed) @override_settings(AUTH_USER_MODEL="test_client_regress.CustomUser") def test_logout_with_custom_user(self): """Logout should send user_logged_out signal if custom user was logged in.""" def listener(*args, **kwargs): self.assertEqual(kwargs["sender"], CustomUser) listener.executed = True listener.executed = False u = CustomUser.custom_objects.create(email="[email protected]") u.set_password("password") u.save() user_logged_out.connect(listener) self.client.login(username="[email protected]", password="password") self.client.logout() user_logged_out.disconnect(listener) self.assertTrue(listener.executed) @override_settings( AUTHENTICATION_BACKENDS=( "django.contrib.auth.backends.ModelBackend", "test_client_regress.auth_backends.CustomUserBackend", ) ) def test_logout_with_custom_auth_backend(self): "Request a logout after logging in with custom authentication backend" def listener(*args, **kwargs): self.assertEqual(kwargs["sender"], CustomUser) listener.executed = True listener.executed = False u = CustomUser.custom_objects.create(email="[email protected]") u.set_password("password") u.save() user_logged_out.connect(listener) self.client.login(username="[email protected]", password="password") self.client.logout() user_logged_out.disconnect(listener) self.assertTrue(listener.executed) def test_logout_without_user(self): """Logout should send signal even if user not authenticated.""" def listener(user, *args, **kwargs): listener.user = user listener.executed = True listener.executed = False user_logged_out.connect(listener) self.client.login(username="incorrect", password="password") self.client.logout() user_logged_out.disconnect(listener) self.assertTrue(listener.executed) self.assertIsNone(listener.user) def test_login_with_user(self): """Login should send user_logged_in signal on successful login.""" def listener(*args, **kwargs): listener.executed = True listener.executed = False user_logged_in.connect(listener) self.client.login(username="testclient", password="password") user_logged_out.disconnect(listener) self.assertTrue(listener.executed) def test_login_without_signal(self): """Login shouldn't send signal if user wasn't logged in""" def listener(*args, **kwargs): listener.executed = True listener.executed = False user_logged_in.connect(listener) self.client.login(username="incorrect", password="password") user_logged_in.disconnect(listener) self.assertFalse(listener.executed) @override_settings(ROOT_URLCONF="test_client_regress.urls") class RequestMethodTests(SimpleTestCase): def test_get(self): "Request a view via request method GET" response = self.client.get("/request_methods/") self.assertEqual(response.status_code, 200) self.assertEqual(response.content, b"request method: GET") def test_post(self): "Request a view via request method POST" response = self.client.post("/request_methods/") self.assertEqual(response.status_code, 200) self.assertEqual(response.content, b"request method: POST") def test_head(self): "Request a view via request method HEAD" response = self.client.head("/request_methods/") self.assertEqual(response.status_code, 200) # A HEAD request doesn't return any content. self.assertNotEqual(response.content, b"request method: HEAD") self.assertEqual(response.content, b"") def test_options(self): "Request a view via request method OPTIONS" response = self.client.options("/request_methods/") self.assertEqual(response.status_code, 200) self.assertEqual(response.content, b"request method: OPTIONS") def test_put(self): "Request a view via request method PUT" response = self.client.put("/request_methods/") self.assertEqual(response.status_code, 200) self.assertEqual(response.content, b"request method: PUT") def test_delete(self): "Request a view via request method DELETE" response = self.client.delete("/request_methods/") self.assertEqual(response.status_code, 200) self.assertEqual(response.content, b"request method: DELETE") def test_patch(self): "Request a view via request method PATCH" response = self.client.patch("/request_methods/") self.assertEqual(response.status_code, 200) self.assertEqual(response.content, b"request method: PATCH") @override_settings(ROOT_URLCONF="test_client_regress.urls") class RequestMethodStringDataTests(SimpleTestCase): def test_post(self): "Request a view with string data via request method POST" # Regression test for #11371 data = '{"test": "json"}' response = self.client.post( "/request_methods/", data=data, content_type="application/json" ) self.assertEqual(response.status_code, 200) self.assertEqual(response.content, b"request method: POST") def test_put(self): "Request a view with string data via request method PUT" # Regression test for #11371 data = '{"test": "json"}' response = self.client.put( "/request_methods/", data=data, content_type="application/json" ) self.assertEqual(response.status_code, 200) self.assertEqual(response.content, b"request method: PUT") def test_patch(self): "Request a view with string data via request method PATCH" # Regression test for #17797 data = '{"test": "json"}' response = self.client.patch( "/request_methods/", data=data, content_type="application/json" ) self.assertEqual(response.status_code, 200) self.assertEqual(response.content, b"request method: PATCH") def test_empty_string_data(self): "Request a view with empty string data via request method GET/POST/HEAD" # Regression test for #21740 response = self.client.get("/body/", data="", content_type="application/json") self.assertEqual(response.content, b"") response = self.client.post("/body/", data="", content_type="application/json") self.assertEqual(response.content, b"") response = self.client.head("/body/", data="", content_type="application/json") self.assertEqual(response.content, b"") def test_json_bytes(self): response = self.client.post( "/body/", data=b"{'value': 37}", content_type="application/json" ) self.assertEqual(response.content, b"{'value': 37}") def test_json(self): response = self.client.get("/json_response/") self.assertEqual(response.json(), {"key": "value"}) def test_json_charset(self): response = self.client.get("/json_response_latin1/") self.assertEqual(response.charset, "latin1") self.assertEqual(response.json(), {"a": "Å"}) def test_json_structured_suffixes(self): valid_types = ( "application/vnd.api+json", "application/vnd.api.foo+json", "application/json; charset=utf-8", "application/activity+json", "application/activity+json; charset=utf-8", ) for content_type in valid_types: response = self.client.get( "/json_response/", {"content_type": content_type} ) self.assertEqual(response.headers["Content-Type"], content_type) self.assertEqual(response.json(), {"key": "value"}) def test_json_multiple_access(self): response = self.client.get("/json_response/") self.assertIs(response.json(), response.json()) def test_json_wrong_header(self): response = self.client.get("/body/") msg = ( 'Content-Type header is "text/html; charset=utf-8", not "application/json"' ) with self.assertRaisesMessage(ValueError, msg): self.assertEqual(response.json(), {"key": "value"}) @override_settings( ROOT_URLCONF="test_client_regress.urls", ) class QueryStringTests(SimpleTestCase): def test_get_like_requests(self): for method_name in ("get", "head"): # A GET-like request can pass a query string as data (#10571) method = getattr(self.client, method_name) response = method("/request_data/", data={"foo": "whiz"}) self.assertEqual(response.context["get-foo"], "whiz") # A GET-like request can pass a query string as part of the URL response = method("/request_data/?foo=whiz") self.assertEqual(response.context["get-foo"], "whiz") # Data provided in the URL to a GET-like request is overridden by # actual form data. response = method("/request_data/?foo=whiz", data={"foo": "bang"}) self.assertEqual(response.context["get-foo"], "bang") response = method("/request_data/?foo=whiz", data={"bar": "bang"}) self.assertIsNone(response.context["get-foo"]) self.assertEqual(response.context["get-bar"], "bang") def test_post_like_requests(self): # A POST-like request can pass a query string as data response = self.client.post("/request_data/", data={"foo": "whiz"}) self.assertIsNone(response.context["get-foo"]) self.assertEqual(response.context["post-foo"], "whiz") # A POST-like request can pass a query string as part of the URL response = self.client.post("/request_data/?foo=whiz") self.assertEqual(response.context["get-foo"], "whiz") self.assertIsNone(response.context["post-foo"]) # POST data provided in the URL augments actual form data response = self.client.post("/request_data/?foo=whiz", data={"foo": "bang"}) self.assertEqual(response.context["get-foo"], "whiz") self.assertEqual(response.context["post-foo"], "bang") response = self.client.post("/request_data/?foo=whiz", data={"bar": "bang"}) self.assertEqual(response.context["get-foo"], "whiz") self.assertIsNone(response.context["get-bar"]) self.assertIsNone(response.context["post-foo"]) self.assertEqual(response.context["post-bar"], "bang") @override_settings(ROOT_URLCONF="test_client_regress.urls") class PayloadEncodingTests(SimpleTestCase): """Regression tests for #10571.""" def test_simple_payload(self): """A simple ASCII-only text can be POSTed.""" text = "English: mountain pass" response = self.client.post( "/parse_encoded_text/", text, content_type="text/plain" ) self.assertEqual(response.content, text.encode()) def test_utf8_payload(self): """Non-ASCII data encoded as UTF-8 can be POSTed.""" text = "dog: собака" response = self.client.post( "/parse_encoded_text/", text, content_type="text/plain; charset=utf-8" ) self.assertEqual(response.content, text.encode()) def test_utf16_payload(self): """Non-ASCII data encoded as UTF-16 can be POSTed.""" text = "dog: собака" response = self.client.post( "/parse_encoded_text/", text, content_type="text/plain; charset=utf-16" ) self.assertEqual(response.content, text.encode("utf-16")) def test_non_utf_payload(self): """Non-ASCII data as a non-UTF based encoding can be POSTed.""" text = "dog: собака" response = self.client.post( "/parse_encoded_text/", text, content_type="text/plain; charset=koi8-r" ) self.assertEqual(response.content, text.encode("koi8-r")) class DummyFile: def __init__(self, filename): self.name = filename def read(self): return b"TEST_FILE_CONTENT" class UploadedFileEncodingTest(SimpleTestCase): def test_file_encoding(self): encoded_file = encode_file( "TEST_BOUNDARY", "TEST_KEY", DummyFile("test_name.bin") ) self.assertEqual(b"--TEST_BOUNDARY", encoded_file[0]) self.assertEqual( b'Content-Disposition: form-data; name="TEST_KEY"; ' b'filename="test_name.bin"', encoded_file[1], ) self.assertEqual(b"TEST_FILE_CONTENT", encoded_file[-1]) def test_guesses_content_type_on_file_encoding(self): self.assertEqual( b"Content-Type: application/octet-stream", encode_file("IGNORE", "IGNORE", DummyFile("file.bin"))[2], ) self.assertEqual( b"Content-Type: text/plain", encode_file("IGNORE", "IGNORE", DummyFile("file.txt"))[2], ) self.assertIn( encode_file("IGNORE", "IGNORE", DummyFile("file.zip"))[2], ( b"Content-Type: application/x-compress", b"Content-Type: application/x-zip", b"Content-Type: application/x-zip-compressed", b"Content-Type: application/zip", ), ) self.assertEqual( b"Content-Type: application/octet-stream", encode_file("IGNORE", "IGNORE", DummyFile("file.unknown"))[2], ) @override_settings( ROOT_URLCONF="test_client_regress.urls", ) class RequestHeadersTest(SimpleTestCase): def test_client_headers(self): "A test client can receive custom headers" response = self.client.get("/check_headers/", HTTP_X_ARG_CHECK="Testing 123") self.assertEqual(response.content, b"HTTP_X_ARG_CHECK: Testing 123") self.assertEqual(response.status_code, 200) def test_client_headers_redirect(self): "Test client headers are preserved through redirects" response = self.client.get( "/check_headers_redirect/", follow=True, HTTP_X_ARG_CHECK="Testing 123" ) self.assertEqual(response.content, b"HTTP_X_ARG_CHECK: Testing 123") self.assertRedirects( response, "/check_headers/", status_code=302, target_status_code=200 ) @override_settings(ROOT_URLCONF="test_client_regress.urls") class ReadLimitedStreamTest(SimpleTestCase): """ HttpRequest.body, HttpRequest.read(), and HttpRequest.read(BUFFER) have proper LimitedStream behavior. Refs #14753, #15785 """ def test_body_from_empty_request(self): """HttpRequest.body on a test client GET request should return the empty string.""" self.assertEqual(self.client.get("/body/").content, b"") def test_read_from_empty_request(self): """HttpRequest.read() on a test client GET request should return the empty string.""" self.assertEqual(self.client.get("/read_all/").content, b"") def test_read_numbytes_from_empty_request(self): """HttpRequest.read(LARGE_BUFFER) on a test client GET request should return the empty string.""" self.assertEqual(self.client.get("/read_buffer/").content, b"") def test_read_from_nonempty_request(self): """HttpRequest.read() on a test client PUT request with some payload should return that payload.""" payload = b"foobar" self.assertEqual( self.client.put( "/read_all/", data=payload, content_type="text/plain" ).content, payload, ) def test_read_numbytes_from_nonempty_request(self): """HttpRequest.read(LARGE_BUFFER) on a test client PUT request with some payload should return that payload.""" payload = b"foobar" self.assertEqual( self.client.put( "/read_buffer/", data=payload, content_type="text/plain" ).content, payload, ) @override_settings(ROOT_URLCONF="test_client_regress.urls") class RequestFactoryStateTest(SimpleTestCase): """Regression tests for #15929.""" # These tests are checking that certain middleware don't change certain # global state. Alternatively, from the point of view of a test, they are # ensuring test isolation behavior. So, unusually, it doesn't make sense to # run the tests individually, and if any are failing it is confusing to run # them with any other set of tests. def common_test_that_should_always_pass(self): request = RequestFactory().get("/") request.session = {} self.assertFalse(hasattr(request, "user")) def test_request(self): self.common_test_that_should_always_pass() def test_request_after_client(self): # apart from the next line the three tests are identical self.client.get("/") self.common_test_that_should_always_pass() def test_request_after_client_2(self): # This test is executed after the previous one self.common_test_that_should_always_pass() @override_settings(ROOT_URLCONF="test_client_regress.urls") class RequestFactoryEnvironmentTests(SimpleTestCase): """ Regression tests for #8551 and #17067: ensure that environment variables are set correctly in RequestFactory. """ def test_should_set_correct_env_variables(self): request = RequestFactory().get("/path/") self.assertEqual(request.META.get("REMOTE_ADDR"), "127.0.0.1") self.assertEqual(request.META.get("SERVER_NAME"), "testserver") self.assertEqual(request.META.get("SERVER_PORT"), "80") self.assertEqual(request.META.get("SERVER_PROTOCOL"), "HTTP/1.1") self.assertEqual( request.META.get("SCRIPT_NAME") + request.META.get("PATH_INFO"), "/path/" ) def test_cookies(self): factory = RequestFactory() factory.cookies.load('A="B"; C="D"; Path=/; Version=1') request = factory.get("/") self.assertEqual(request.META["HTTP_COOKIE"], 'A="B"; C="D"')
2e8336e1b1c41425c5c4644f1a2ef68be1c74646984d51632a8abbe16a11f3d6
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager from django.db import models class CustomUser(AbstractBaseUser): email = models.EmailField(verbose_name="email address", max_length=255, unique=True) custom_objects = BaseUserManager() USERNAME_FIELD = "email" class Meta: app_label = "test_client_regress"
37a67f4301d21bc48558e09ee2cd03f5a5b5a5d1ff75b5a77f03aef3702022e6
from django.contrib.sessions.backends.base import SessionBase class SessionStore(SessionBase): """ A simple cookie-based session storage implementation. The session key is actually the session data, pickled and encoded. This means that saving the session will change the session key. """ def __init__(self, session_key=None): super().__init__(session_key) def exists(self, session_key): return False def create(self): self._session_key = self.encode({}) def save(self, must_create=False): self._session_key = self.encode(self._session) def delete(self, session_key=None): self._session_key = self.encode({}) def load(self): try: return self.decode(self.session_key) except Exception: self.modified = True return {}
fb5684a8713527823bf3bad211c91e25199a78684075e6ce88b783c9dda9eb63
def special(request): return {"path": request.special_path}
94f5f43daa90b9677c5aa2aa1497d7419c73b2af189340289e5b21c849fdb0a0
from django.urls import include, path from django.views.generic import RedirectView from . import views urlpatterns = [ path("", include("test_client.urls")), path("no_template_view/", views.no_template_view), path("staff_only/", views.staff_only_view), path("get_view/", views.get_view), path("request_data/", views.request_data), path( "request_data_extended/", views.request_data, {"template": "extended.html", "data": "bacon"}, ), path("arg_view/<name>/", views.view_with_argument, name="arg_view"), path("nested_view/", views.nested_view, name="nested_view"), path("login_protected_redirect_view/", views.login_protected_redirect_view), path("redirects/", RedirectView.as_view(url="/redirects/further/")), path("redirects/further/", RedirectView.as_view(url="/redirects/further/more/")), path("redirects/further/more/", RedirectView.as_view(url="/no_template_view/")), path( "redirect_to_non_existent_view/", RedirectView.as_view(url="/non_existent_view/"), ), path( "redirect_to_non_existent_view2/", RedirectView.as_view(url="/redirect_to_non_existent_view/"), ), path("redirect_to_self/", RedirectView.as_view(url="/redirect_to_self/")), path( "redirect_to_self_with_changing_query_view/", views.redirect_to_self_with_changing_query_view, ), path("circular_redirect_1/", RedirectView.as_view(url="/circular_redirect_2/")), path("circular_redirect_2/", RedirectView.as_view(url="/circular_redirect_3/")), path("circular_redirect_3/", RedirectView.as_view(url="/circular_redirect_1/")), path( "redirect_other_host/", RedirectView.as_view(url="https://otherserver:8443/no_template_view/"), ), path( "redirect_based_on_extra_headers_1/", views.redirect_based_on_extra_headers_1_view, ), path( "redirect_based_on_extra_headers_2/", views.redirect_based_on_extra_headers_2_view, ), path("set_session/", views.set_session_view), path("check_session/", views.check_session_view), path("request_methods/", views.request_methods_view), path("check_unicode/", views.return_unicode), path("check_binary/", views.return_undecodable_binary), path("json_response/", views.return_json_response), path("json_response_latin1/", views.return_json_response_latin1), path("parse_encoded_text/", views.return_text_file), path("check_headers/", views.check_headers), path("check_headers_redirect/", RedirectView.as_view(url="/check_headers/")), path("body/", views.body), path("read_all/", views.read_all), path("read_buffer/", views.read_buffer), path("request_context_view/", views.request_context_view), path("render_template_multiple_times/", views.render_template_multiple_times), ]
c5eb42c7e0e2ce34c2cca943db2767257feea5a32282a8234d05a56b272073dd
from urllib.parse import urlencode from django.conf import settings from django.contrib.auth.decorators import login_required from django.http import HttpResponse, HttpResponseRedirect, JsonResponse from django.shortcuts import render from django.template.loader import render_to_string from django.test import Client from django.test.client import CONTENT_TYPE_RE class CustomTestException(Exception): pass def no_template_view(request): "A simple view that expects a GET request, and returns a rendered template" return HttpResponse( "No template used. Sample content: twice once twice. Content ends." ) def staff_only_view(request): "A view that can only be visited by staff. Non staff members get an exception" if request.user.is_staff: return HttpResponse() else: raise CustomTestException() @login_required def get_view(request): "A simple login protected view" return HttpResponse("Hello world") def request_data(request, template="base.html", data="sausage"): "A simple view that returns the request data in the context" return render( request, template, { "get-foo": request.GET.get("foo"), "get-bar": request.GET.get("bar"), "post-foo": request.POST.get("foo"), "post-bar": request.POST.get("bar"), "data": data, }, ) def view_with_argument(request, name): """A view that takes a string argument The purpose of this view is to check that if a space is provided in the argument, the test framework unescapes the %20 before passing the value to the view. """ if name == "Arthur Dent": return HttpResponse("Hi, Arthur") else: return HttpResponse("Howdy, %s" % name) def nested_view(request): """ A view that uses test client to call another view. """ c = Client() c.get("/no_template_view/") return render(request, "base.html", {"nested": "yes"}) @login_required def login_protected_redirect_view(request): "A view that redirects all requests to the GET view" return HttpResponseRedirect("/get_view/") def redirect_to_self_with_changing_query_view(request): query = request.GET.copy() query["counter"] += "0" return HttpResponseRedirect( "/redirect_to_self_with_changing_query_view/?%s" % urlencode(query) ) def set_session_view(request): "A view that sets a session variable" request.session["session_var"] = "YES" return HttpResponse("set_session") def check_session_view(request): "A view that reads a session variable" return HttpResponse(request.session.get("session_var", "NO")) def request_methods_view(request): "A view that responds with the request method" return HttpResponse("request method: %s" % request.method) def return_unicode(request): return render(request, "unicode.html") def return_undecodable_binary(request): return HttpResponse( b"%PDF-1.4\r\n%\x93\x8c\x8b\x9e ReportLab Generated PDF document " b"http://www.reportlab.com" ) def return_json_response(request): content_type = request.GET.get("content_type") kwargs = {"content_type": content_type} if content_type else {} return JsonResponse({"key": "value"}, **kwargs) def return_json_response_latin1(request): return HttpResponse( b'{"a":"\xc5"}', content_type="application/json; charset=latin1" ) def return_text_file(request): "A view that parses and returns text as a file." match = CONTENT_TYPE_RE.match(request.META["CONTENT_TYPE"]) if match: charset = match[1] else: charset = settings.DEFAULT_CHARSET return HttpResponse( request.body, status=200, content_type="text/plain; charset=%s" % charset ) def check_headers(request): "A view that responds with value of the X-ARG-CHECK header" return HttpResponse( "HTTP_X_ARG_CHECK: %s" % request.META.get("HTTP_X_ARG_CHECK", "Undefined") ) def body(request): "A view that is requested with GET and accesses request.body. Refs #14753." return HttpResponse(request.body) def read_all(request): "A view that is requested with accesses request.read()." return HttpResponse(request.read()) def read_buffer(request): "A view that is requested with accesses request.read(LARGE_BUFFER)." return HttpResponse(request.read(99999)) def request_context_view(request): # Special attribute that won't be present on a plain HttpRequest request.special_path = request.path return render(request, "request_context.html") def render_template_multiple_times(request): """A view that renders a template multiple times.""" return HttpResponse(render_to_string("base.html") + render_to_string("base.html")) def redirect_based_on_extra_headers_1_view(request): if "HTTP_REDIRECT" in request.META: return HttpResponseRedirect("/redirect_based_on_extra_headers_2/") return HttpResponse() def redirect_based_on_extra_headers_2_view(request): if "HTTP_REDIRECT" in request.META: return HttpResponseRedirect("/redirects/further/more/") return HttpResponse()
e0e7aef913d69924e2cdd5224af1dbf74524b48c91b434debe7497a043c5cdf6
from django.apps import apps from django.db import models from django.test import SimpleTestCase, override_settings from django.test.utils import isolate_lru_cache class FieldDeconstructionTests(SimpleTestCase): """ Tests the deconstruct() method on all core fields. """ def test_name(self): """ Tests the outputting of the correct name if assigned one. """ # First try using a "normal" field field = models.CharField(max_length=65) name, path, args, kwargs = field.deconstruct() self.assertIsNone(name) field.set_attributes_from_name("is_awesome_test") name, path, args, kwargs = field.deconstruct() self.assertEqual(name, "is_awesome_test") # Now try with a ForeignKey field = models.ForeignKey("some_fake.ModelName", models.CASCADE) name, path, args, kwargs = field.deconstruct() self.assertIsNone(name) field.set_attributes_from_name("author") name, path, args, kwargs = field.deconstruct() self.assertEqual(name, "author") def test_db_tablespace(self): field = models.Field() _, _, args, kwargs = field.deconstruct() self.assertEqual(args, []) self.assertEqual(kwargs, {}) # With a DEFAULT_DB_TABLESPACE. with self.settings(DEFAULT_DB_TABLESPACE="foo"): _, _, args, kwargs = field.deconstruct() self.assertEqual(args, []) self.assertEqual(kwargs, {}) # With a db_tablespace. field = models.Field(db_tablespace="foo") _, _, args, kwargs = field.deconstruct() self.assertEqual(args, []) self.assertEqual(kwargs, {"db_tablespace": "foo"}) # With a db_tablespace equal to DEFAULT_DB_TABLESPACE. with self.settings(DEFAULT_DB_TABLESPACE="foo"): _, _, args, kwargs = field.deconstruct() self.assertEqual(args, []) self.assertEqual(kwargs, {"db_tablespace": "foo"}) def test_auto_field(self): field = models.AutoField(primary_key=True) field.set_attributes_from_name("id") name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.AutoField") self.assertEqual(args, []) self.assertEqual(kwargs, {"primary_key": True}) def test_big_integer_field(self): field = models.BigIntegerField() name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.BigIntegerField") self.assertEqual(args, []) self.assertEqual(kwargs, {}) def test_boolean_field(self): field = models.BooleanField() name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.BooleanField") self.assertEqual(args, []) self.assertEqual(kwargs, {}) field = models.BooleanField(default=True) name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.BooleanField") self.assertEqual(args, []) self.assertEqual(kwargs, {"default": True}) def test_char_field(self): field = models.CharField(max_length=65) name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.CharField") self.assertEqual(args, []) self.assertEqual(kwargs, {"max_length": 65}) field = models.CharField(max_length=65, null=True, blank=True) name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.CharField") self.assertEqual(args, []) self.assertEqual(kwargs, {"max_length": 65, "null": True, "blank": True}) def test_char_field_choices(self): field = models.CharField(max_length=1, choices=(("A", "One"), ("B", "Two"))) name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.CharField") self.assertEqual(args, []) self.assertEqual( kwargs, {"choices": [("A", "One"), ("B", "Two")], "max_length": 1} ) def test_csi_field(self): field = models.CommaSeparatedIntegerField(max_length=100) name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.CommaSeparatedIntegerField") self.assertEqual(args, []) self.assertEqual(kwargs, {"max_length": 100}) def test_date_field(self): field = models.DateField() name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.DateField") self.assertEqual(args, []) self.assertEqual(kwargs, {}) field = models.DateField(auto_now=True) name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.DateField") self.assertEqual(args, []) self.assertEqual(kwargs, {"auto_now": True}) def test_datetime_field(self): field = models.DateTimeField() name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.DateTimeField") self.assertEqual(args, []) self.assertEqual(kwargs, {}) field = models.DateTimeField(auto_now_add=True) name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.DateTimeField") self.assertEqual(args, []) self.assertEqual(kwargs, {"auto_now_add": True}) # Bug #21785 field = models.DateTimeField(auto_now=True, auto_now_add=True) name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.DateTimeField") self.assertEqual(args, []) self.assertEqual(kwargs, {"auto_now_add": True, "auto_now": True}) def test_decimal_field(self): field = models.DecimalField(max_digits=5, decimal_places=2) name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.DecimalField") self.assertEqual(args, []) self.assertEqual(kwargs, {"max_digits": 5, "decimal_places": 2}) def test_decimal_field_0_decimal_places(self): """ A DecimalField with decimal_places=0 should work (#22272). """ field = models.DecimalField(max_digits=5, decimal_places=0) name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.DecimalField") self.assertEqual(args, []) self.assertEqual(kwargs, {"max_digits": 5, "decimal_places": 0}) def test_email_field(self): field = models.EmailField() name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.EmailField") self.assertEqual(args, []) self.assertEqual(kwargs, {"max_length": 254}) field = models.EmailField(max_length=255) name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.EmailField") self.assertEqual(args, []) self.assertEqual(kwargs, {"max_length": 255}) def test_file_field(self): field = models.FileField(upload_to="foo/bar") name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.FileField") self.assertEqual(args, []) self.assertEqual(kwargs, {"upload_to": "foo/bar"}) # Test max_length field = models.FileField(upload_to="foo/bar", max_length=200) name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.FileField") self.assertEqual(args, []) self.assertEqual(kwargs, {"upload_to": "foo/bar", "max_length": 200}) def test_file_path_field(self): field = models.FilePathField(match=r".*\.txt$") name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.FilePathField") self.assertEqual(args, []) self.assertEqual(kwargs, {"match": r".*\.txt$"}) field = models.FilePathField(recursive=True, allow_folders=True, max_length=123) name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.FilePathField") self.assertEqual(args, []) self.assertEqual( kwargs, {"recursive": True, "allow_folders": True, "max_length": 123} ) def test_float_field(self): field = models.FloatField() name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.FloatField") self.assertEqual(args, []) self.assertEqual(kwargs, {}) def test_foreign_key(self): # Test basic pointing from django.contrib.auth.models import Permission field = models.ForeignKey("auth.Permission", models.CASCADE) field.remote_field.model = Permission field.remote_field.field_name = "id" name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.ForeignKey") self.assertEqual(args, []) self.assertEqual(kwargs, {"to": "auth.permission", "on_delete": models.CASCADE}) self.assertFalse(hasattr(kwargs["to"], "setting_name")) # Test swap detection for swappable model field = models.ForeignKey("auth.User", models.CASCADE) name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.ForeignKey") self.assertEqual(args, []) self.assertEqual(kwargs, {"to": "auth.user", "on_delete": models.CASCADE}) self.assertEqual(kwargs["to"].setting_name, "AUTH_USER_MODEL") # Swap detection for lowercase swappable model. field = models.ForeignKey("auth.user", models.CASCADE) name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.ForeignKey") self.assertEqual(args, []) self.assertEqual(kwargs, {"to": "auth.user", "on_delete": models.CASCADE}) self.assertEqual(kwargs["to"].setting_name, "AUTH_USER_MODEL") # Test nonexistent (for now) model field = models.ForeignKey("something.Else", models.CASCADE) name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.ForeignKey") self.assertEqual(args, []) self.assertEqual(kwargs, {"to": "something.else", "on_delete": models.CASCADE}) # Test on_delete field = models.ForeignKey("auth.User", models.SET_NULL) name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.ForeignKey") self.assertEqual(args, []) self.assertEqual(kwargs, {"to": "auth.user", "on_delete": models.SET_NULL}) # Test to_field preservation field = models.ForeignKey("auth.Permission", models.CASCADE, to_field="foobar") name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.ForeignKey") self.assertEqual(args, []) self.assertEqual( kwargs, { "to": "auth.permission", "to_field": "foobar", "on_delete": models.CASCADE, }, ) # Test related_name preservation field = models.ForeignKey( "auth.Permission", models.CASCADE, related_name="foobar" ) name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.ForeignKey") self.assertEqual(args, []) self.assertEqual( kwargs, { "to": "auth.permission", "related_name": "foobar", "on_delete": models.CASCADE, }, ) # Test related_query_name field = models.ForeignKey( "auth.Permission", models.CASCADE, related_query_name="foobar" ) name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.ForeignKey") self.assertEqual(args, []) self.assertEqual( kwargs, { "to": "auth.permission", "related_query_name": "foobar", "on_delete": models.CASCADE, }, ) # Test limit_choices_to field = models.ForeignKey( "auth.Permission", models.CASCADE, limit_choices_to={"foo": "bar"} ) name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.ForeignKey") self.assertEqual(args, []) self.assertEqual( kwargs, { "to": "auth.permission", "limit_choices_to": {"foo": "bar"}, "on_delete": models.CASCADE, }, ) # Test unique field = models.ForeignKey("auth.Permission", models.CASCADE, unique=True) name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.ForeignKey") self.assertEqual(args, []) self.assertEqual( kwargs, {"to": "auth.permission", "unique": True, "on_delete": models.CASCADE}, ) @override_settings(AUTH_USER_MODEL="auth.Permission") def test_foreign_key_swapped(self): with isolate_lru_cache(apps.get_swappable_settings_name): # It doesn't matter that we swapped out user for permission; # there's no validation. We just want to check the setting stuff works. field = models.ForeignKey("auth.Permission", models.CASCADE) name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.ForeignKey") self.assertEqual(args, []) self.assertEqual(kwargs, {"to": "auth.permission", "on_delete": models.CASCADE}) self.assertEqual(kwargs["to"].setting_name, "AUTH_USER_MODEL") # Model names are case-insensitive. with isolate_lru_cache(apps.get_swappable_settings_name): # It doesn't matter that we swapped out user for permission; # there's no validation. We just want to check the setting stuff # works. field = models.ForeignKey("auth.permission", models.CASCADE) name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.ForeignKey") self.assertEqual(args, []) self.assertEqual(kwargs, {"to": "auth.permission", "on_delete": models.CASCADE}) self.assertEqual(kwargs["to"].setting_name, "AUTH_USER_MODEL") def test_one_to_one(self): # Test basic pointing from django.contrib.auth.models import Permission field = models.OneToOneField("auth.Permission", models.CASCADE) field.remote_field.model = Permission field.remote_field.field_name = "id" name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.OneToOneField") self.assertEqual(args, []) self.assertEqual(kwargs, {"to": "auth.permission", "on_delete": models.CASCADE}) self.assertFalse(hasattr(kwargs["to"], "setting_name")) # Test swap detection for swappable model field = models.OneToOneField("auth.User", models.CASCADE) name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.OneToOneField") self.assertEqual(args, []) self.assertEqual(kwargs, {"to": "auth.user", "on_delete": models.CASCADE}) self.assertEqual(kwargs["to"].setting_name, "AUTH_USER_MODEL") # Test nonexistent (for now) model field = models.OneToOneField("something.Else", models.CASCADE) name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.OneToOneField") self.assertEqual(args, []) self.assertEqual(kwargs, {"to": "something.else", "on_delete": models.CASCADE}) # Test on_delete field = models.OneToOneField("auth.User", models.SET_NULL) name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.OneToOneField") self.assertEqual(args, []) self.assertEqual(kwargs, {"to": "auth.user", "on_delete": models.SET_NULL}) # Test to_field field = models.OneToOneField( "auth.Permission", models.CASCADE, to_field="foobar" ) name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.OneToOneField") self.assertEqual(args, []) self.assertEqual( kwargs, { "to": "auth.permission", "to_field": "foobar", "on_delete": models.CASCADE, }, ) # Test related_name field = models.OneToOneField( "auth.Permission", models.CASCADE, related_name="foobar" ) name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.OneToOneField") self.assertEqual(args, []) self.assertEqual( kwargs, { "to": "auth.permission", "related_name": "foobar", "on_delete": models.CASCADE, }, ) # Test related_query_name field = models.OneToOneField( "auth.Permission", models.CASCADE, related_query_name="foobar" ) name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.OneToOneField") self.assertEqual(args, []) self.assertEqual( kwargs, { "to": "auth.permission", "related_query_name": "foobar", "on_delete": models.CASCADE, }, ) # Test limit_choices_to field = models.OneToOneField( "auth.Permission", models.CASCADE, limit_choices_to={"foo": "bar"} ) name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.OneToOneField") self.assertEqual(args, []) self.assertEqual( kwargs, { "to": "auth.permission", "limit_choices_to": {"foo": "bar"}, "on_delete": models.CASCADE, }, ) # Test unique field = models.OneToOneField("auth.Permission", models.CASCADE, unique=True) name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.OneToOneField") self.assertEqual(args, []) self.assertEqual(kwargs, {"to": "auth.permission", "on_delete": models.CASCADE}) def test_image_field(self): field = models.ImageField( upload_to="foo/barness", width_field="width", height_field="height" ) name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.ImageField") self.assertEqual(args, []) self.assertEqual( kwargs, { "upload_to": "foo/barness", "width_field": "width", "height_field": "height", }, ) def test_integer_field(self): field = models.IntegerField() name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.IntegerField") self.assertEqual(args, []) self.assertEqual(kwargs, {}) def test_ip_address_field(self): field = models.IPAddressField() name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.IPAddressField") self.assertEqual(args, []) self.assertEqual(kwargs, {}) def test_generic_ip_address_field(self): field = models.GenericIPAddressField() name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.GenericIPAddressField") self.assertEqual(args, []) self.assertEqual(kwargs, {}) field = models.GenericIPAddressField(protocol="IPv6") name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.GenericIPAddressField") self.assertEqual(args, []) self.assertEqual(kwargs, {"protocol": "IPv6"}) def test_many_to_many_field(self): # Test normal field = models.ManyToManyField("auth.Permission") name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.ManyToManyField") self.assertEqual(args, []) self.assertEqual(kwargs, {"to": "auth.permission"}) self.assertFalse(hasattr(kwargs["to"], "setting_name")) # Test swappable field = models.ManyToManyField("auth.User") name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.ManyToManyField") self.assertEqual(args, []) self.assertEqual(kwargs, {"to": "auth.user"}) self.assertEqual(kwargs["to"].setting_name, "AUTH_USER_MODEL") # Test through field = models.ManyToManyField("auth.Permission", through="auth.Group") name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.ManyToManyField") self.assertEqual(args, []) self.assertEqual(kwargs, {"to": "auth.permission", "through": "auth.Group"}) # Test custom db_table field = models.ManyToManyField("auth.Permission", db_table="custom_table") name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.ManyToManyField") self.assertEqual(args, []) self.assertEqual(kwargs, {"to": "auth.permission", "db_table": "custom_table"}) # Test related_name field = models.ManyToManyField("auth.Permission", related_name="custom_table") name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.ManyToManyField") self.assertEqual(args, []) self.assertEqual( kwargs, {"to": "auth.permission", "related_name": "custom_table"} ) # Test related_query_name field = models.ManyToManyField("auth.Permission", related_query_name="foobar") name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.ManyToManyField") self.assertEqual(args, []) self.assertEqual( kwargs, {"to": "auth.permission", "related_query_name": "foobar"} ) # Test limit_choices_to field = models.ManyToManyField( "auth.Permission", limit_choices_to={"foo": "bar"} ) name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.ManyToManyField") self.assertEqual(args, []) self.assertEqual( kwargs, {"to": "auth.permission", "limit_choices_to": {"foo": "bar"}} ) @override_settings(AUTH_USER_MODEL="auth.Permission") def test_many_to_many_field_swapped(self): with isolate_lru_cache(apps.get_swappable_settings_name): # It doesn't matter that we swapped out user for permission; # there's no validation. We just want to check the setting stuff works. field = models.ManyToManyField("auth.Permission") name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.ManyToManyField") self.assertEqual(args, []) self.assertEqual(kwargs, {"to": "auth.permission"}) self.assertEqual(kwargs["to"].setting_name, "AUTH_USER_MODEL") def test_many_to_many_field_related_name(self): class MyModel(models.Model): flag = models.BooleanField(default=True) m2m = models.ManyToManyField("self") m2m_related_name = models.ManyToManyField( "self", related_query_name="custom_query_name", limit_choices_to={"flag": True}, ) name, path, args, kwargs = MyModel.m2m.field.deconstruct() self.assertEqual(path, "django.db.models.ManyToManyField") self.assertEqual(args, []) # deconstruct() should not include attributes which were not passed to # the field during initialization. self.assertEqual(kwargs, {"to": "field_deconstruction.mymodel"}) # Passed attributes. name, path, args, kwargs = MyModel.m2m_related_name.field.deconstruct() self.assertEqual(path, "django.db.models.ManyToManyField") self.assertEqual(args, []) self.assertEqual( kwargs, { "to": "field_deconstruction.mymodel", "related_query_name": "custom_query_name", "limit_choices_to": {"flag": True}, }, ) def test_positive_integer_field(self): field = models.PositiveIntegerField() name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.PositiveIntegerField") self.assertEqual(args, []) self.assertEqual(kwargs, {}) def test_positive_small_integer_field(self): field = models.PositiveSmallIntegerField() name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.PositiveSmallIntegerField") self.assertEqual(args, []) self.assertEqual(kwargs, {}) def test_positive_big_integer_field(self): field = models.PositiveBigIntegerField() name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.PositiveBigIntegerField") self.assertEqual(args, []) self.assertEqual(kwargs, {}) def test_slug_field(self): field = models.SlugField() name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.SlugField") self.assertEqual(args, []) self.assertEqual(kwargs, {}) field = models.SlugField(db_index=False, max_length=231) name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.SlugField") self.assertEqual(args, []) self.assertEqual(kwargs, {"db_index": False, "max_length": 231}) def test_small_integer_field(self): field = models.SmallIntegerField() name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.SmallIntegerField") self.assertEqual(args, []) self.assertEqual(kwargs, {}) def test_text_field(self): field = models.TextField() name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.TextField") self.assertEqual(args, []) self.assertEqual(kwargs, {}) def test_time_field(self): field = models.TimeField() name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.TimeField") self.assertEqual(args, []) self.assertEqual(kwargs, {}) field = models.TimeField(auto_now=True) name, path, args, kwargs = field.deconstruct() self.assertEqual(args, []) self.assertEqual(kwargs, {"auto_now": True}) field = models.TimeField(auto_now_add=True) name, path, args, kwargs = field.deconstruct() self.assertEqual(args, []) self.assertEqual(kwargs, {"auto_now_add": True}) def test_url_field(self): field = models.URLField() name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.URLField") self.assertEqual(args, []) self.assertEqual(kwargs, {}) field = models.URLField(max_length=231) name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.URLField") self.assertEqual(args, []) self.assertEqual(kwargs, {"max_length": 231}) def test_binary_field(self): field = models.BinaryField() name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.BinaryField") self.assertEqual(args, []) self.assertEqual(kwargs, {}) field = models.BinaryField(editable=True) name, path, args, kwargs = field.deconstruct() self.assertEqual(args, []) self.assertEqual(kwargs, {"editable": True})
5cd87d668e27bf8d93c5095354bb4bf59ffdf70f134607a48d3f71f1d173a6ba
import datetime from django.test import TestCase from .models import Person class RecursiveM2MTests(TestCase): @classmethod def setUpTestData(cls): cls.a, cls.b, cls.c, cls.d = [ Person.objects.create(name=name) for name in ["Anne", "Bill", "Chuck", "David"] ] cls.a.friends.add(cls.b, cls.c) # Add m2m for Anne and Chuck in reverse direction. cls.d.friends.add(cls.a, cls.c) def test_recursive_m2m_all(self): for person, friends in ( (self.a, [self.b, self.c, self.d]), (self.b, [self.a]), (self.c, [self.a, self.d]), (self.d, [self.a, self.c]), ): with self.subTest(person=person): self.assertSequenceEqual(person.friends.all(), friends) def test_recursive_m2m_reverse_add(self): # Add m2m for Anne in reverse direction. self.b.friends.add(self.a) self.assertSequenceEqual(self.a.friends.all(), [self.b, self.c, self.d]) self.assertSequenceEqual(self.b.friends.all(), [self.a]) def test_recursive_m2m_remove(self): self.b.friends.remove(self.a) self.assertSequenceEqual(self.a.friends.all(), [self.c, self.d]) self.assertSequenceEqual(self.b.friends.all(), []) def test_recursive_m2m_clear(self): # Clear m2m for Anne. self.a.friends.clear() self.assertSequenceEqual(self.a.friends.all(), []) # Reverse m2m relationships should be removed. self.assertSequenceEqual(self.c.friends.all(), [self.d]) self.assertSequenceEqual(self.d.friends.all(), [self.c]) def test_recursive_m2m_add_via_related_name(self): # Add m2m with custom related name for Anne in reverse direction. self.d.stalkers.add(self.a) self.assertSequenceEqual(self.a.idols.all(), [self.d]) self.assertSequenceEqual(self.a.stalkers.all(), []) def test_recursive_m2m_add_in_both_directions(self): # Adding the same relation twice results in a single relation. self.a.idols.add(self.d) self.d.stalkers.add(self.a) self.assertSequenceEqual(self.a.idols.all(), [self.d]) def test_recursive_m2m_related_to_self(self): self.a.idols.add(self.a) self.assertSequenceEqual(self.a.idols.all(), [self.a]) self.assertSequenceEqual(self.a.stalkers.all(), [self.a]) class RecursiveSymmetricalM2MThroughTests(TestCase): @classmethod def setUpTestData(cls): cls.a, cls.b, cls.c, cls.d = [ Person.objects.create(name=name) for name in ["Anne", "Bill", "Chuck", "David"] ] cls.a.colleagues.add( cls.b, cls.c, through_defaults={ "first_meet": datetime.date(2013, 1, 5), }, ) # Add m2m for Anne and Chuck in reverse direction. cls.d.colleagues.add( cls.a, cls.c, through_defaults={ "first_meet": datetime.date(2015, 6, 15), }, ) def test_recursive_m2m_all(self): for person, colleagues in ( (self.a, [self.b, self.c, self.d]), (self.b, [self.a]), (self.c, [self.a, self.d]), (self.d, [self.a, self.c]), ): with self.subTest(person=person): self.assertSequenceEqual(person.colleagues.all(), colleagues) def test_recursive_m2m_reverse_add(self): # Add m2m for Anne in reverse direction. self.b.colleagues.add( self.a, through_defaults={ "first_meet": datetime.date(2013, 1, 5), }, ) self.assertSequenceEqual(self.a.colleagues.all(), [self.b, self.c, self.d]) self.assertSequenceEqual(self.b.colleagues.all(), [self.a]) def test_recursive_m2m_remove(self): self.b.colleagues.remove(self.a) self.assertSequenceEqual(self.a.colleagues.all(), [self.c, self.d]) self.assertSequenceEqual(self.b.colleagues.all(), []) def test_recursive_m2m_clear(self): # Clear m2m for Anne. self.a.colleagues.clear() self.assertSequenceEqual(self.a.friends.all(), []) # Reverse m2m relationships is removed. self.assertSequenceEqual(self.c.colleagues.all(), [self.d]) self.assertSequenceEqual(self.d.colleagues.all(), [self.c]) def test_recursive_m2m_set(self): # Set new relationships for Chuck. self.c.colleagues.set( [self.b, self.d], through_defaults={ "first_meet": datetime.date(2013, 1, 5), }, ) self.assertSequenceEqual(self.c.colleagues.order_by("name"), [self.b, self.d]) # Reverse m2m relationships is removed. self.assertSequenceEqual(self.a.colleagues.order_by("name"), [self.b, self.d])
904d2b6f0c86e459a2d9eb629361a07eb17dd68bb7289d10e7c53064a2e3e4b0
""" Many-to-many relationships between the same two tables In this example, a ``Person`` can have many friends, who are also ``Person`` objects. Friendship is a symmetrical relationship - if I am your friend, you are my friend. Here, ``friends`` is an example of a symmetrical ``ManyToManyField``. A ``Person`` can also have many idols - but while I may idolize you, you may not think the same of me. Here, ``idols`` is an example of a non-symmetrical ``ManyToManyField``. Only recursive ``ManyToManyField`` fields may be non-symmetrical, and they are symmetrical by default. This test validates that the many-to-many table is created using a mangled name if there is a name clash, and tests that symmetry is preserved where appropriate. """ from django.db import models class Person(models.Model): name = models.CharField(max_length=20) friends = models.ManyToManyField("self") colleagues = models.ManyToManyField("self", symmetrical=True, through="Colleague") idols = models.ManyToManyField("self", symmetrical=False, related_name="stalkers") def __str__(self): return self.name class Colleague(models.Model): first = models.ForeignKey(Person, models.CASCADE) second = models.ForeignKey(Person, models.CASCADE, related_name="+") first_meet = models.DateField()
8181144a6c722e62bce45465675905d611f178302b6b96ceec6eca751196c2db
import datetime import itertools import tempfile from django.core.files.storage import FileSystemStorage from django.db import models callable_default_counter = itertools.count() def callable_default(): return next(callable_default_counter) temp_storage = FileSystemStorage(location=tempfile.mkdtemp()) class BoundaryModel(models.Model): positive_integer = models.PositiveIntegerField(null=True, blank=True) class Defaults(models.Model): name = models.CharField(max_length=255, default="class default value") def_date = models.DateField(default=datetime.date(1980, 1, 1)) value = models.IntegerField(default=42) callable_default = models.IntegerField(default=callable_default) class ChoiceModel(models.Model): """For ModelChoiceField and ModelMultipleChoiceField tests.""" CHOICES = [ ("", "No Preference"), ("f", "Foo"), ("b", "Bar"), ] INTEGER_CHOICES = [ (None, "No Preference"), (1, "Foo"), (2, "Bar"), ] STRING_CHOICES_WITH_NONE = [ (None, "No Preference"), ("f", "Foo"), ("b", "Bar"), ] name = models.CharField(max_length=10) choice = models.CharField(max_length=2, blank=True, choices=CHOICES) choice_string_w_none = models.CharField( max_length=2, blank=True, null=True, choices=STRING_CHOICES_WITH_NONE ) choice_integer = models.IntegerField(choices=INTEGER_CHOICES, blank=True, null=True) class ChoiceOptionModel(models.Model): """ Destination for ChoiceFieldModel's ForeignKey. Can't reuse ChoiceModel because error_message tests require that it have no instances. """ name = models.CharField(max_length=10) class Meta: ordering = ("name",) def __str__(self): return "ChoiceOption %d" % self.pk def choice_default(): return ChoiceOptionModel.objects.get_or_create(name="default")[0].pk def choice_default_list(): return [choice_default()] def int_default(): return 1 def int_list_default(): return [1] class ChoiceFieldModel(models.Model): """Model with ForeignKey to another model, for testing ModelForm generation with ModelChoiceField.""" choice = models.ForeignKey( ChoiceOptionModel, models.CASCADE, blank=False, default=choice_default, ) choice_int = models.ForeignKey( ChoiceOptionModel, models.CASCADE, blank=False, related_name="choice_int", default=int_default, ) multi_choice = models.ManyToManyField( ChoiceOptionModel, blank=False, related_name="multi_choice", default=choice_default_list, ) multi_choice_int = models.ManyToManyField( ChoiceOptionModel, blank=False, related_name="multi_choice_int", default=int_list_default, ) class OptionalMultiChoiceModel(models.Model): multi_choice = models.ManyToManyField( ChoiceOptionModel, blank=False, related_name="not_relevant", default=choice_default, ) multi_choice_optional = models.ManyToManyField( ChoiceOptionModel, blank=True, related_name="not_relevant2", ) class FileModel(models.Model): file = models.FileField(storage=temp_storage, upload_to="tests") class Article(models.Model): content = models.TextField()
52e40696471e8ef7d324e2d868c1c78bca87a5f98fdb8238e56a00cb9617ed08
from django.urls import path from .views import ArticleFormView, form_view urlpatterns = [ path("form_view/", form_view, name="form_view"), path("model_form/<int:pk>/", ArticleFormView.as_view(), name="article_form"), ]
01296e2b87f9d04d942396309b2f220f1fc846b7cc16b814ce8e7e2a4aede8b8
from django import forms from django.http import HttpResponse from django.template import Context, Template from django.views.generic.edit import UpdateView from .models import Article class ArticleForm(forms.ModelForm): content = forms.CharField(strip=False, widget=forms.Textarea) class Meta: model = Article fields = "__all__" class ArticleFormView(UpdateView): model = Article success_url = "/" form_class = ArticleForm def form_view(request): class Form(forms.Form): number = forms.FloatField() template = Template("<html>{{ form }}</html>") context = Context({"form": Form()}) return HttpResponse(template.render(context))
779415886c3413e3ec6a339aad81b2aa3afb1c4f25796d116dc3189e560a3c48
import copy import datetime from operator import attrgetter from django.core.exceptions import ValidationError from django.db import models, router from django.db.models.sql import InsertQuery from django.test import TestCase, skipUnlessDBFeature from django.test.utils import isolate_apps from django.utils.timezone import get_fixed_timezone from .models import ( Article, Department, Event, 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 following queries would raise: # "TypeError: Related Field has invalid lookup: gte" def test_related_gte_lookup(self): """ Regression test for #10153: foreign key __gte lookups. """ Worker.objects.filter(department__gte=0) def test_related_lte_lookup(self): """ Regression test for #10153: foreign key __lte lookups. """ Worker.objects.filter(department__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) query.insert_values([Party._meta.fields[0]], [], raw=False) # this line will raise an AttributeError without the accompanying fix query.get_compiler(using=db).as_sql() def test_empty_choice(self): # NOTE: Part of the regression test here is merely parsing the model # declaration. The verbose_name, in particular, did not always work. a = Article.objects.create( headline="Look at me!", pub_date=datetime.datetime.now() ) # An empty choice field should return None for the display name. self.assertIs(a.get_status_display(), None) # Empty strings should be returned as string a = Article.objects.get(pk=a.pk) self.assertEqual(a.misc_data, "") def test_long_textfield(self): # TextFields can hold more than 4000 characters (this was broken in # Oracle). a = Article.objects.create( headline="Really, really big", pub_date=datetime.datetime.now(), article_text="ABCDE" * 1000, ) a = Article.objects.get(pk=a.pk) self.assertEqual(len(a.article_text), 5000) def test_long_unicode_textfield(self): # TextFields can hold more than 4000 bytes also when they are # less than 4000 characters a = Article.objects.create( headline="Really, really big", pub_date=datetime.datetime.now(), article_text="\u05d0\u05d1\u05d2" * 1000, ) a = Article.objects.get(pk=a.pk) self.assertEqual(len(a.article_text), 3000) def test_date_lookup(self): # Regression test for #659 Party.objects.create(when=datetime.datetime(1999, 12, 31)) Party.objects.create(when=datetime.datetime(1998, 12, 31)) Party.objects.create(when=datetime.datetime(1999, 1, 1)) Party.objects.create(when=datetime.datetime(1, 3, 3)) self.assertQuerysetEqual(Party.objects.filter(when__month=2), []) self.assertQuerysetEqual( Party.objects.filter(when__month=1), [datetime.date(1999, 1, 1)], attrgetter("when"), ) self.assertQuerysetEqual( Party.objects.filter(when__month=12), [ datetime.date(1999, 12, 31), datetime.date(1998, 12, 31), ], attrgetter("when"), ordered=False, ) self.assertQuerysetEqual( Party.objects.filter(when__year=1998), [ datetime.date(1998, 12, 31), ], attrgetter("when"), ) # Regression test for #8510 self.assertQuerysetEqual( Party.objects.filter(when__day="31"), [ datetime.date(1999, 12, 31), datetime.date(1998, 12, 31), ], attrgetter("when"), ordered=False, ) self.assertQuerysetEqual( Party.objects.filter(when__month="12"), [ datetime.date(1999, 12, 31), datetime.date(1998, 12, 31), ], attrgetter("when"), ordered=False, ) self.assertQuerysetEqual( Party.objects.filter(when__year="1998"), [ datetime.date(1998, 12, 31), ], attrgetter("when"), ) # Regression test for #18969 self.assertQuerysetEqual( Party.objects.filter(when__year=1), [ datetime.date(1, 3, 3), ], attrgetter("when"), ) self.assertQuerysetEqual( Party.objects.filter(when__year="1"), [ datetime.date(1, 3, 3), ], attrgetter("when"), ) def test_date_filter_null(self): # Date filtering was failing with NULL date values in SQLite # (regression test for #3501, among other things). Party.objects.create(when=datetime.datetime(1999, 1, 1)) Party.objects.create() p = Party.objects.filter(when__month=1)[0] self.assertEqual(p.when, datetime.date(1999, 1, 1)) self.assertQuerysetEqual( Party.objects.filter(pk=p.pk).dates("when", "month"), [1], attrgetter("month"), ) def test_get_next_prev_by_field(self): # get_next_by_FIELD() and get_previous_by_FIELD() don't crash when # microseconds values are stored in the database. Event.objects.create(when=datetime.datetime(2000, 1, 1, 16, 0, 0)) Event.objects.create(when=datetime.datetime(2000, 1, 1, 6, 1, 1)) Event.objects.create(when=datetime.datetime(2000, 1, 1, 13, 1, 1)) e = Event.objects.create(when=datetime.datetime(2000, 1, 1, 12, 0, 20, 24)) self.assertEqual( e.get_next_by_when().when, datetime.datetime(2000, 1, 1, 13, 1, 1) ) self.assertEqual( e.get_previous_by_when().when, datetime.datetime(2000, 1, 1, 6, 1, 1) ) def test_get_next_prev_by_field_unsaved(self): msg = "get_next/get_previous cannot be used on unsaved objects." with self.assertRaisesMessage(ValueError, msg): Event().get_next_by_when() with self.assertRaisesMessage(ValueError, msg): Event().get_previous_by_when() def test_primary_key_foreign_key_types(self): # Check Department and Worker (non-default PK type) d = Department.objects.create(id=10, name="IT") w = Worker.objects.create(department=d, name="Full-time") self.assertEqual(str(w), "Full-time") @skipUnlessDBFeature("supports_timezones") def test_timezones(self): # Saving and updating with timezone-aware datetime Python objects. # Regression test for #10443. # The idea is that all these creations and saving should work without # crashing. It's not rocket science. dt1 = datetime.datetime(2008, 8, 31, 16, 20, tzinfo=get_fixed_timezone(600)) dt2 = datetime.datetime(2008, 8, 31, 17, 20, tzinfo=get_fixed_timezone(600)) obj = Article.objects.create( headline="A headline", pub_date=dt1, article_text="foo" ) obj.pub_date = dt2 obj.save() self.assertEqual( Article.objects.filter(headline="A headline").update(pub_date=dt1), 1 ) def test_chained_fks(self): """ Chained foreign keys with to_field produce incorrect query. """ m1 = Model1.objects.create(pkey=1000) m2 = Model2.objects.create(model1=m1) m3 = Model3.objects.create(model2=m2) # this is the actual test for #18432 m3 = Model3.objects.get(model2=1000) m3.model2 @isolate_apps("model_regress") def test_metaclass_can_access_attribute_dict(self): """ Model metaclasses have access to the class attribute dict in __init__() (#30254). """ class HorseBase(models.base.ModelBase): def __init__(cls, name, bases, attrs): super().__init__(name, bases, attrs) cls.horns = 1 if "magic" in attrs else 0 class Horse(models.Model, metaclass=HorseBase): name = models.CharField(max_length=255) magic = True self.assertEqual(Horse.horns, 1) class ModelValidationTest(TestCase): def test_pk_validation(self): NonAutoPK.objects.create(name="one") again = NonAutoPK(name="one") with self.assertRaises(ValidationError): again.validate_unique() class EvaluateMethodTest(TestCase): """ Regression test for #13640: cannot filter by objects with 'evaluate' attr """ def test_model_with_evaluate_method(self): """ You can filter by objects that have an 'evaluate' attr """ dept = Department.objects.create(pk=1, name="abc") dept.evaluate = "abc" Worker.objects.filter(department=dept) class ModelFieldsCacheTest(TestCase): def test_fields_cache_reset_on_copy(self): department1 = Department.objects.create(id=1, name="department1") department2 = Department.objects.create(id=2, name="department2") worker1 = Worker.objects.create(name="worker", department=department1) worker2 = copy.copy(worker1) self.assertEqual(worker2.department, department1) # Changing related fields doesn't mutate the base object. worker2.department = department2 self.assertEqual(worker2.department, department2) self.assertEqual(worker1.department, department1)
edec005f9aa9e4781f5c458954642953a13d9191b8778cb2ebb8ca1913fe6a6f
from django.db import models class Article(models.Model): CHOICES = ( (1, "first"), (2, "second"), ) headline = models.CharField(max_length=100, default="Default headline") pub_date = models.DateTimeField() status = models.IntegerField(blank=True, null=True, choices=CHOICES) misc_data = models.CharField(max_length=100, blank=True) article_text = models.TextField() class Meta: ordering = ("pub_date", "headline") # A utf-8 verbose name (Ångström's Articles) to test they are valid. verbose_name = "\xc3\x85ngstr\xc3\xb6m's Articles" class Movie(models.Model): # Test models with non-default primary keys / AutoFields #5218 movie_id = models.AutoField(primary_key=True) name = models.CharField(max_length=60) class Party(models.Model): when = models.DateField(null=True) class Event(models.Model): when = models.DateTimeField() class Department(models.Model): id = models.PositiveIntegerField(primary_key=True) name = models.CharField(max_length=200) class Worker(models.Model): department = models.ForeignKey(Department, models.CASCADE) name = models.CharField(max_length=200) def __str__(self): return self.name class NonAutoPK(models.Model): name = models.CharField(max_length=10, primary_key=True) # Chained foreign keys with to_field produce incorrect query #18432 class Model1(models.Model): pkey = models.IntegerField(unique=True, db_index=True) class Model2(models.Model): model1 = models.ForeignKey(Model1, models.CASCADE, unique=True, to_field="pkey") class Model3(models.Model): model2 = models.ForeignKey(Model2, models.CASCADE, unique=True, to_field="model1")
07456bbead048219d66e38693e0ca6d5f7d2615f33dbbc5de658b30a5097e783
import pickle import django from django.db import 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 MissingDjangoVersion(models.Model): title = models.CharField(max_length=10) def __reduce__(self): reduce_list = super().__reduce__() data = 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." 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 different Django version than the current """ class DifferentDjangoVersion(models.Model): title = models.CharField(max_length=10) def __reduce__(self): reduce_list = super().__reduce__() data = reduce_list[-1] data[DJANGO_VERSION_PICKLE_KEY] = "1.0" return reduce_list p = DifferentDjangoVersion(title="FooBar") msg = ( "Pickled model instance's Django version 1.0 does not match the " "current version %s." % django.__version__ ) with self.assertRaisesMessage(RuntimeWarning, msg): pickle.loads(pickle.dumps(p)) def test_with_getstate(self): """ A model may override __getstate__() to choose the attributes to pickle. """ class PickledModel(models.Model): def __getstate__(self): state = super().__getstate__().copy() del state["dont_pickle"] return state m = PickledModel() m.dont_pickle = 1 dumped = pickle.dumps(m) self.assertEqual(m.dont_pickle, 1) reloaded = pickle.loads(dumped) self.assertFalse(hasattr(reloaded, "dont_pickle"))
7de8414794e0b8ecca1b7b56555bf69957553fb9e218885988e2af4c0f7b2cc2
from django.db.models.base import ModelState, ModelStateCacheDescriptor from django.test import SimpleTestCase class ModelStateTests(SimpleTestCase): def test_fields_cache_descriptor(self): self.assertIsInstance(ModelState.fields_cache, ModelStateCacheDescriptor) def test_related_managers_descriptor(self): self.assertIsInstance( ModelState.related_managers_cache, ModelStateCacheDescriptor )
4236387b28dfd210d9f50e2534e9fb20aaaeb1d4650cb01b80a54181b9bba5aa
import unittest from django.core.exceptions import FieldError from django.db import IntegrityError, connection, transaction from django.db.models import CharField, Count, F, IntegerField, Max from django.db.models.functions import Abs, Concat, Lower from django.test import TestCase from django.test.utils import register_lookup from .models import ( A, B, Bar, D, DataPoint, Foo, RelatedPoint, UniqueNumber, UniqueNumberChild, ) class SimpleTest(TestCase): @classmethod def setUpTestData(cls): cls.a1 = A.objects.create() cls.a2 = A.objects.create() for x in range(20): B.objects.create(a=cls.a1) D.objects.create(a=cls.a1) def test_nonempty_update(self): """ Update changes the right number of rows for a nonempty queryset """ num_updated = self.a1.b_set.update(y=100) self.assertEqual(num_updated, 20) cnt = B.objects.filter(y=100).count() self.assertEqual(cnt, 20) def test_empty_update(self): """ Update changes the right number of rows for an empty queryset """ num_updated = self.a2.b_set.update(y=100) self.assertEqual(num_updated, 0) cnt = B.objects.filter(y=100).count() self.assertEqual(cnt, 0) def test_nonempty_update_with_inheritance(self): """ Update changes the right number of rows for an empty queryset when the update affects only a base table """ num_updated = self.a1.d_set.update(y=100) self.assertEqual(num_updated, 20) cnt = D.objects.filter(y=100).count() self.assertEqual(cnt, 20) def test_empty_update_with_inheritance(self): """ Update changes the right number of rows for an empty queryset when the update affects only a base table """ num_updated = self.a2.d_set.update(y=100) self.assertEqual(num_updated, 0) cnt = D.objects.filter(y=100).count() self.assertEqual(cnt, 0) def test_foreign_key_update_with_id(self): """ Update works using <field>_id for foreign keys """ num_updated = self.a1.d_set.update(a_id=self.a2) self.assertEqual(num_updated, 20) self.assertEqual(self.a2.d_set.count(), 20) class AdvancedTests(TestCase): @classmethod def setUpTestData(cls): cls.d0 = DataPoint.objects.create(name="d0", value="apple") cls.d2 = DataPoint.objects.create(name="d2", value="banana") cls.d3 = DataPoint.objects.create(name="d3", value="banana") cls.r1 = RelatedPoint.objects.create(name="r1", data=cls.d3) def test_update(self): """ Objects are updated by first filtering the candidates into a queryset and then calling the update() method. It executes immediately and returns nothing. """ resp = DataPoint.objects.filter(value="apple").update(name="d1") self.assertEqual(resp, 1) resp = DataPoint.objects.filter(value="apple") self.assertEqual(list(resp), [self.d0]) def test_update_multiple_objects(self): """ We can update multiple objects at once. """ resp = DataPoint.objects.filter(value="banana").update(value="pineapple") self.assertEqual(resp, 2) self.assertEqual(DataPoint.objects.get(name="d2").value, "pineapple") def test_update_fk(self): """ Foreign key fields can also be updated, although you can only update the object referred to, not anything inside the related object. """ resp = RelatedPoint.objects.filter(name="r1").update(data=self.d0) self.assertEqual(resp, 1) resp = RelatedPoint.objects.filter(data__name="d0") self.assertEqual(list(resp), [self.r1]) def test_update_multiple_fields(self): """ Multiple fields can be updated at once """ resp = DataPoint.objects.filter(value="apple").update( value="fruit", another_value="peach" ) self.assertEqual(resp, 1) d = DataPoint.objects.get(name="d0") self.assertEqual(d.value, "fruit") self.assertEqual(d.another_value, "peach") def test_update_all(self): """ In the rare case you want to update every instance of a model, update() is also a manager method. """ self.assertEqual(DataPoint.objects.update(value="thing"), 3) resp = DataPoint.objects.values("value").distinct() self.assertEqual(list(resp), [{"value": "thing"}]) def test_update_slice_fail(self): """ We do not support update on already sliced query sets. """ method = DataPoint.objects.all()[:2].update msg = "Cannot update a query once a slice has been taken." with self.assertRaisesMessage(TypeError, msg): method(another_value="another thing") def test_update_respects_to_field(self): """ Update of an FK field which specifies a to_field works. """ a_foo = Foo.objects.create(target="aaa") b_foo = Foo.objects.create(target="bbb") bar = Bar.objects.create(foo=a_foo) self.assertEqual(bar.foo_id, a_foo.target) bar_qs = Bar.objects.filter(pk=bar.pk) self.assertEqual(bar_qs[0].foo_id, a_foo.target) bar_qs.update(foo=b_foo) self.assertEqual(bar_qs[0].foo_id, b_foo.target) def test_update_m2m_field(self): msg = ( "Cannot update model field " "<django.db.models.fields.related.ManyToManyField: m2m_foo> " "(only non-relations and foreign keys permitted)." ) with self.assertRaisesMessage(FieldError, msg): Bar.objects.update(m2m_foo="whatever") def test_update_transformed_field(self): A.objects.create(x=5) A.objects.create(x=-6) with register_lookup(IntegerField, Abs): A.objects.update(x=F("x__abs")) self.assertCountEqual(A.objects.values_list("x", flat=True), [5, 6]) def test_update_annotated_queryset(self): """ Update of a queryset that's been annotated. """ # Trivial annotated update qs = DataPoint.objects.annotate(alias=F("value")) self.assertEqual(qs.update(another_value="foo"), 3) # Update where annotation is used for filtering qs = DataPoint.objects.annotate(alias=F("value")).filter(alias="apple") self.assertEqual(qs.update(another_value="foo"), 1) # Update where annotation is used in update parameters qs = DataPoint.objects.annotate(alias=F("value")) self.assertEqual(qs.update(another_value=F("alias")), 3) # Update where aggregation annotation is used in update parameters qs = DataPoint.objects.annotate(max=Max("value")) msg = ( "Aggregate functions are not allowed in this query " "(another_value=Max(Col(update_datapoint, update.DataPoint.value)))." ) with self.assertRaisesMessage(FieldError, msg): qs.update(another_value=F("max")) def test_update_annotated_multi_table_queryset(self): """ Update of a queryset that's been annotated and involves multiple tables. """ # Trivial annotated update qs = DataPoint.objects.annotate(related_count=Count("relatedpoint")) self.assertEqual(qs.update(value="Foo"), 3) # Update where annotation is used for filtering qs = DataPoint.objects.annotate(related_count=Count("relatedpoint")) self.assertEqual(qs.filter(related_count=1).update(value="Foo"), 1) # Update where aggregation annotation is used in update parameters qs = RelatedPoint.objects.annotate(max=Max("data__value")) msg = "Joined field references are not permitted in this query" with self.assertRaisesMessage(FieldError, msg): qs.update(name=F("max")) def test_update_with_joined_field_annotation(self): msg = "Joined field references are not permitted in this query" with register_lookup(CharField, Lower): for annotation in ( F("data__name"), F("data__name__lower"), Lower("data__name"), Concat("data__name", "data__value"), ): with self.subTest(annotation=annotation): with self.assertRaisesMessage(FieldError, msg): RelatedPoint.objects.annotate( new_name=annotation, ).update(name=F("new_name")) @unittest.skipUnless( connection.vendor == "mysql", "UPDATE...ORDER BY syntax is supported on MySQL/MariaDB", ) class MySQLUpdateOrderByTest(TestCase): """Update field with a unique constraint using an ordered queryset.""" @classmethod def setUpTestData(cls): UniqueNumber.objects.create(number=1) UniqueNumber.objects.create(number=2) def test_order_by_update_on_unique_constraint(self): tests = [ ("-number", "id"), (F("number").desc(), "id"), (F("number") * -1, "id"), ] for ordering in tests: with self.subTest(ordering=ordering), transaction.atomic(): updated = UniqueNumber.objects.order_by(*ordering).update( number=F("number") + 1, ) self.assertEqual(updated, 2) def test_order_by_update_on_unique_constraint_annotation(self): # Ordering by annotations is omitted because they cannot be resolved in # .update(). with self.assertRaises(IntegrityError): UniqueNumber.objects.annotate(number_inverse=F("number").desc(),).order_by( "number_inverse" ).update( number=F("number") + 1, ) def test_order_by_update_on_parent_unique_constraint(self): # Ordering by inherited fields is omitted because joined fields cannot # be used in the ORDER BY clause. UniqueNumberChild.objects.create(number=3) UniqueNumberChild.objects.create(number=4) with self.assertRaises(IntegrityError): UniqueNumberChild.objects.order_by("number").update( number=F("number") + 1, ) def test_order_by_update_on_related_field(self): # Ordering by related fields is omitted because joined fields cannot be # used in the ORDER BY clause. data = DataPoint.objects.create(name="d0", value="apple") related = RelatedPoint.objects.create(name="r0", data=data) with self.assertNumQueries(1) as ctx: updated = RelatedPoint.objects.order_by("data__name").update(name="new") sql = ctx.captured_queries[0]["sql"] self.assertNotIn("ORDER BY", sql) self.assertEqual(updated, 1) related.refresh_from_db() self.assertEqual(related.name, "new")
99da13ec2f2e0c0ad8448d3471a8887fcc60d1f432c795d03f854db32f1c7283
""" Tests for the update() queryset method that allows in-place, multi-object updates. """ from django.db import models class DataPoint(models.Model): name = models.CharField(max_length=20) value = models.CharField(max_length=20) another_value = models.CharField(max_length=20, blank=True) class RelatedPoint(models.Model): name = models.CharField(max_length=20) data = models.ForeignKey(DataPoint, models.CASCADE) class A(models.Model): x = models.IntegerField(default=10) class B(models.Model): a = models.ForeignKey(A, models.CASCADE) y = models.IntegerField(default=10) class C(models.Model): y = models.IntegerField(default=10) class D(C): a = models.ForeignKey(A, models.CASCADE) class Foo(models.Model): target = models.CharField(max_length=10, unique=True) class Bar(models.Model): foo = models.ForeignKey(Foo, models.CASCADE, to_field="target") m2m_foo = models.ManyToManyField(Foo, related_name="m2m_foo") class UniqueNumber(models.Model): number = models.IntegerField(unique=True) class UniqueNumberChild(UniqueNumber): pass
cad5a19db473c90c1afc7aa80b403ddedfe96019ec3d5ea5db6e96be267c8383
from django.urls import path from . import views urlpatterns = [ path("index/", views.index_page, name="index"), ]
2a43160a58935e5ee3027670ea3dbce615f3af641b1b6cad8c8a1b059ce4d62b
""" 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 article models with and without a get_absolute_url method (for create_update generic views tests). """ title = models.CharField(max_length=100) slug = models.SlugField() author = models.ForeignKey(Author, models.CASCADE) class Meta: abstract = True class Article(BaseArticle): date_created = models.DateTimeField() class UrlArticle(BaseArticle): """ An Article class with 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 Model with a DateField instead of DateTimeField, for testing #7602 """ date_created = models.DateField()
308e5989eb51e68789b8814fe13197ab2f6434540546594892de8bdcbdf2c9e5
from django.contrib import admin from django.urls import path urlpatterns = [ # This is the same as in the default project template path("admin/", admin.site.urls), ]
44a9a61e8d1f49101cb7e6c5b24172c76247f95e7654f20c86350dd3d8032fbe
from django.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_dict = { "queryset": Article.objects.all(), "paginate_by": 2, } object_list_no_paginate_by = { "queryset": Article.objects.all(), } numeric_days_info_dict = dict(date_based_info_dict, 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")), 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( "nonascii_redirect/", RedirectView.as_view(url="/中文/target/", permanent=False) ), path( "permanent_nonascii_redirect/", RedirectView.as_view(url="/中文/target/", permanent=True), ), ] # json response urlpatterns += [ path("json/response/", views.json_response_view), ]
372a739ac69c7537ebbf3b72126827fda04ecf4f3f12a1a2022cf46ff16d4343
import os from functools import partial from django.conf.urls.i18n import i18n_patterns from django.urls 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("", views.index_page), # Default views path("nonexistent_url/", partial(defaults.page_not_found, exception=None)), path("server_error/", defaults.server_error), # a view 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), 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.Http404View.as_view()), path("classbased500/", views.Raises500View.as_view()), # i18n views path("i18n/", include("django.conf.urls.i18n")), path("jsi18n/", i18n.JavaScriptCatalog.as_view(packages=["view_tests"])), path("jsi18n/app1/", i18n.JavaScriptCatalog.as_view(packages=["view_tests.app1"])), path("jsi18n/app2/", i18n.JavaScriptCatalog.as_view(packages=["view_tests.app2"])), path("jsi18n/app5/", i18n.JavaScriptCatalog.as_view(packages=["view_tests.app5"])), path( "jsi18n_english_translation/", i18n.JavaScriptCatalog.as_view(packages=["view_tests.app0"]), ), path( "jsi18n_multi_packages1/", i18n.JavaScriptCatalog.as_view(packages=["view_tests.app1", "view_tests.app2"]), ), path( "jsi18n_multi_packages2/", i18n.JavaScriptCatalog.as_view(packages=["view_tests.app3", "view_tests.app4"]), ), path( "jsi18n_admin/", i18n.JavaScriptCatalog.as_view(packages=["django.contrib.admin", "view_tests"]), ), path("jsi18n_template/", views.jsi18n), path("jsi18n_multi_catalogs/", views.jsi18n_multi_catalogs), path("jsoni18n/", i18n.JSONCatalog.as_view(packages=["view_tests"])), # Static views re_path( r"^site_media/(?P<path>.*)$", static.serve, {"document_root": media_dir, "show_indexes": True}, ), ] urlpatterns += i18n_patterns( re_path(_(r"^translated/$"), views.index_page, name="i18n_prefixed"), ) urlpatterns += [ path( "safestring_exception/", views.safestring_in_template_exception, name="safestring_exception", ), path("template_exception/", views.template_exception, name="template_exception"), path( "raises_template_does_not_exist/<path:path>", views.raises_template_does_not_exist, name="raises_template_does_not_exist", ), path("render_no_template/", views.render_no_template, name="render_no_template"), re_path( r"^test-setlang/(?P<parameter>[^/]+)/$", views.with_parameter, name="with_parameter", ), # Patterns to test the technical 404. re_path(r"^regex-post/(?P<pk>[0-9]+)/$", views.index_page, name="regex-post"), path("path-post/<int:pk>/", views.index_page, name="path-post"), ]
bfd0f0078fb93047dbf7648321bc476401520803cb9224db63ffa929877f2a9f
import datetime import decimal import logging import sys from pathlib import Path from django.core.exceptions import BadRequest, PermissionDenied, SuspiciousOperation from django.http import Http404, HttpResponse, JsonResponse from django.shortcuts import render from django.template import Context, Template, TemplateDoesNotExist from django.urls import get_resolver from django.views import View from django.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""" return HttpResponse("<html><body>Dummy page</body></html>") def with_parameter(request, parameter): return HttpResponse("ok") def raises(request): # Make sure that a callable that 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 technical_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 Exception: return technical_500_response(request, *sys.exc_info()) class Raises500View(View): def get(self, request): try: raise Exception except Exception: return technical_500_response(request, *sys.exc_info()) def raises400(request): raise SuspiciousOperation def raises400_bad_request(request): raise BadRequest("Malformed request syntax") def raises403(request): raise PermissionDenied("Insufficient Permissions") def raises404(request): resolver = get_resolver(None) resolver.resolve("/not-in-urls") def technical404(request): raise Http404("Testing technical 404.") class Http404View(View): def get(self, request): raise Http404("Testing class-based technical 404.") def template_exception(request): return render(request, "debug/template_exception.html") def safestring_in_template_exception(request): """ Trigger an exception in the template machinery which causes a SafeString to be inserted as args[0] of the Exception. """ template = Template('{% extends "<script>alert(1);</script>" %}') try: template.render(Context()) except Exception: return technical_500_response(request, *sys.exc_info()) def jsi18n(request): return render(request, "jsi18n.html") def jsi18n_multi_catalogs(request): return render(request, "jsi18n-multi-catalogs.html") def raises_template_does_not_exist(request, path="i_dont_exist.html"): # 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: return render(request, path) except TemplateDoesNotExist: return technical_500_response(request, *sys.exc_info()) def render_no_template(request): # If we do not specify a template, we need to make sure the debug # view doesn't blow up. return render(request, [], {}) def send_log(request, exc_info): logger = logging.getLogger("django") # The default logging config has a logging filter to ensure admin emails are # only sent with DEBUG=False, but since someone might choose to remove that # filter, we still want to be able to test the behavior of error emails # with DEBUG=True. So we need to remove the filter temporarily. admin_email_handler = [ h for h in logger.handlers if h.__class__.__name__ == "AdminEmailHandler" ][0] orig_filters = admin_email_handler.filters admin_email_handler.filters = [] admin_email_handler.include_html = True logger.error( "Internal Server Error: %s", request.path, exc_info=exc_info, extra={"status_code": 500, "request": request}, ) admin_email_handler.filters = orig_filters def non_sensitive_view(request): # Do not just use plain strings for the variables' values in the code # so that the tests don't return false positives when the function's source # is displayed in the exception report. cooked_eggs = "".join(["s", "c", "r", "a", "m", "b", "l", "e", "d"]) # NOQA sauce = "".join( # NOQA ["w", "o", "r", "c", "e", "s", "t", "e", "r", "s", "h", "i", "r", "e"] ) try: raise Exception except Exception: exc_info = sys.exc_info() send_log(request, exc_info) return technical_500_response(request, *exc_info) @sensitive_variables("sauce") @sensitive_post_parameters("bacon-key", "sausage-key") def sensitive_view(request): # Do not just use plain strings for the variables' values in the code # so that the tests don't return false positives when the function's source # is displayed in the exception report. cooked_eggs = "".join(["s", "c", "r", "a", "m", "b", "l", "e", "d"]) # NOQA sauce = "".join( # NOQA ["w", "o", "r", "c", "e", "s", "t", "e", "r", "s", "h", "i", "r", "e"] ) try: raise Exception except Exception: exc_info = sys.exc_info() send_log(request, exc_info) return technical_500_response(request, *exc_info) @sensitive_variables() @sensitive_post_parameters() def paranoid_view(request): # Do not just use plain strings for the variables' values in the code # so that the tests don't return false positives when the function's source # is displayed in the exception report. cooked_eggs = "".join(["s", "c", "r", "a", "m", "b", "l", "e", "d"]) # NOQA sauce = "".join( # NOQA ["w", "o", "r", "c", "e", "s", "t", "e", "r", "s", "h", "i", "r", "e"] ) try: raise Exception except Exception: exc_info = sys.exc_info() send_log(request, exc_info) return technical_500_response(request, *exc_info) def sensitive_args_function_caller(request): try: sensitive_args_function( "".join( ["w", "o", "r", "c", "e", "s", "t", "e", "r", "s", "h", "i", "r", "e"] ) ) except Exception: exc_info = sys.exc_info() send_log(request, exc_info) return technical_500_response(request, *exc_info) @sensitive_variables("sauce") def sensitive_args_function(sauce): # Do not just use plain strings for the variables' values in the code # so that the tests don't return false positives when the function's source # is displayed in the exception report. cooked_eggs = "".join(["s", "c", "r", "a", "m", "b", "l", "e", "d"]) # NOQA raise Exception def sensitive_kwargs_function_caller(request): try: sensitive_kwargs_function( "".join( ["w", "o", "r", "c", "e", "s", "t", "e", "r", "s", "h", "i", "r", "e"] ) ) except Exception: exc_info = sys.exc_info() send_log(request, exc_info) return technical_500_response(request, *exc_info) @sensitive_variables("sauce") def sensitive_kwargs_function(sauce=None): # Do not just use plain strings for the variables' values in the code # so that the tests don't return false positives when the function's source # is displayed in the exception report. cooked_eggs = "".join(["s", "c", "r", "a", "m", "b", "l", "e", "d"]) # NOQA raise Exception class UnsafeExceptionReporterFilter(SafeExceptionReporterFilter): """ Ignores all the filtering done by its parent class. """ def get_post_parameters(self, request): return request.POST def get_traceback_frame_variables(self, request, tb_frame): return tb_frame.f_locals.items() @sensitive_variables() @sensitive_post_parameters() def custom_exception_reporter_filter_view(request): # Do not just use plain strings for the variables' values in the code # so that the tests don't return false positives when the function's source # is displayed in the exception report. cooked_eggs = "".join(["s", "c", "r", "a", "m", "b", "l", "e", "d"]) # NOQA sauce = "".join( # NOQA ["w", "o", "r", "c", "e", "s", "t", "e", "r", "s", "h", "i", "r", "e"] ) request.exception_reporter_filter = UnsafeExceptionReporterFilter() try: raise Exception except Exception: exc_info = sys.exc_info() send_log(request, exc_info) return technical_500_response(request, *exc_info) class CustomExceptionReporter(ExceptionReporter): custom_traceback_text = "custom traceback text" def get_traceback_html(self): return self.custom_traceback_text class TemplateOverrideExceptionReporter(ExceptionReporter): html_template_path = TEMPLATES_PATH / "my_technical_500.html" text_template_path = TEMPLATES_PATH / "my_technical_500.txt" def custom_reporter_class_view(request): request.exception_reporter_class = CustomExceptionReporter try: raise Exception except Exception: exc_info = sys.exc_info() return technical_500_response(request, *exc_info) class Klass: @sensitive_variables("sauce") def method(self, request): # Do not just use plain strings for the variables' values in the code # so that the tests don't return false positives when the function's # source is displayed in the exception report. cooked_eggs = "".join(["s", "c", "r", "a", "m", "b", "l", "e", "d"]) # NOQA sauce = "".join( # NOQA ["w", "o", "r", "c", "e", "s", "t", "e", "r", "s", "h", "i", "r", "e"] ) try: raise Exception except Exception: exc_info = sys.exc_info() send_log(request, exc_info) return technical_500_response(request, *exc_info) def sensitive_method_view(request): return Klass().method(request) @sensitive_variables("sauce") @sensitive_post_parameters("bacon-key", "sausage-key") def multivalue_dict_key_error(request): cooked_eggs = "".join(["s", "c", "r", "a", "m", "b", "l", "e", "d"]) # NOQA sauce = "".join( # NOQA ["w", "o", "r", "c", "e", "s", "t", "e", "r", "s", "h", "i", "r", "e"] ) try: request.POST["bar"] except Exception: exc_info = sys.exc_info() send_log(request, exc_info) return technical_500_response(request, *exc_info) def json_response_view(request): return JsonResponse( { "a": [1, 2, 3], "foo": {"bar": "baz"}, # Make sure datetime and Decimal objects would be serialized properly "timestamp": datetime.datetime(2013, 5, 19, 20), "value": decimal.Decimal("3.14"), } )
5d76c809c27e39998554890d15967091b83c6edc128feb02f0e604a3ea6b74d8
import sys import threading import time from unittest import skipIf, skipUnless from django.db import ( DatabaseError, Error, IntegrityError, OperationalError, connection, transaction, ) from django.test import ( TestCase, TransactionTestCase, skipIfDBFeature, skipUnlessDBFeature, ) from .models import Reporter @skipUnlessDBFeature("uses_savepoints") class AtomicTests(TransactionTestCase): """ Tests for the atomic decorator and context manager. The tests make assertions on internal attributes because there isn't a robust way to ask the database for its current transaction state. Since the decorator syntax is converted into a context manager (see the implementation), there are only a few basic tests with the decorator syntax and the bulk of the tests use the context manager syntax. """ available_apps = ["transactions"] def test_decorator_syntax_commit(self): @transaction.atomic def make_reporter(): return Reporter.objects.create(first_name="Tintin") reporter = make_reporter() self.assertSequenceEqual(Reporter.objects.all(), [reporter]) def test_decorator_syntax_rollback(self): @transaction.atomic def make_reporter(): Reporter.objects.create(first_name="Haddock") raise Exception("Oops, that's his last name") with self.assertRaisesMessage(Exception, "Oops"): make_reporter() self.assertSequenceEqual(Reporter.objects.all(), []) def test_alternate_decorator_syntax_commit(self): @transaction.atomic() def make_reporter(): return Reporter.objects.create(first_name="Tintin") reporter = make_reporter() self.assertSequenceEqual(Reporter.objects.all(), [reporter]) def test_alternate_decorator_syntax_rollback(self): @transaction.atomic() def make_reporter(): Reporter.objects.create(first_name="Haddock") raise Exception("Oops, that's his last name") with self.assertRaisesMessage(Exception, "Oops"): make_reporter() self.assertSequenceEqual(Reporter.objects.all(), []) def test_commit(self): with transaction.atomic(): reporter = Reporter.objects.create(first_name="Tintin") self.assertSequenceEqual(Reporter.objects.all(), [reporter]) def test_rollback(self): with self.assertRaisesMessage(Exception, "Oops"): with transaction.atomic(): Reporter.objects.create(first_name="Haddock") raise Exception("Oops, that's his last name") self.assertSequenceEqual(Reporter.objects.all(), []) def test_nested_commit_commit(self): with transaction.atomic(): reporter1 = Reporter.objects.create(first_name="Tintin") with transaction.atomic(): reporter2 = Reporter.objects.create( first_name="Archibald", last_name="Haddock" ) self.assertSequenceEqual(Reporter.objects.all(), [reporter2, reporter1]) def test_nested_commit_rollback(self): with transaction.atomic(): reporter = Reporter.objects.create(first_name="Tintin") with self.assertRaisesMessage(Exception, "Oops"): with transaction.atomic(): Reporter.objects.create(first_name="Haddock") raise Exception("Oops, that's his last name") self.assertSequenceEqual(Reporter.objects.all(), [reporter]) def test_nested_rollback_commit(self): with self.assertRaisesMessage(Exception, "Oops"): with transaction.atomic(): Reporter.objects.create(last_name="Tintin") with transaction.atomic(): Reporter.objects.create(last_name="Haddock") raise Exception("Oops, that's his first name") self.assertSequenceEqual(Reporter.objects.all(), []) def test_nested_rollback_rollback(self): with self.assertRaisesMessage(Exception, "Oops"): with transaction.atomic(): Reporter.objects.create(last_name="Tintin") with self.assertRaisesMessage(Exception, "Oops"): with transaction.atomic(): Reporter.objects.create(first_name="Haddock") raise Exception("Oops, that's his last name") raise Exception("Oops, that's his first name") self.assertSequenceEqual(Reporter.objects.all(), []) def test_merged_commit_commit(self): with transaction.atomic(): reporter1 = Reporter.objects.create(first_name="Tintin") with transaction.atomic(savepoint=False): reporter2 = Reporter.objects.create( first_name="Archibald", last_name="Haddock" ) self.assertSequenceEqual(Reporter.objects.all(), [reporter2, reporter1]) def test_merged_commit_rollback(self): with transaction.atomic(): Reporter.objects.create(first_name="Tintin") with self.assertRaisesMessage(Exception, "Oops"): with transaction.atomic(savepoint=False): Reporter.objects.create(first_name="Haddock") raise Exception("Oops, that's his last name") # Writes in the outer block are rolled back too. self.assertSequenceEqual(Reporter.objects.all(), []) def test_merged_rollback_commit(self): with self.assertRaisesMessage(Exception, "Oops"): with transaction.atomic(): Reporter.objects.create(last_name="Tintin") with transaction.atomic(savepoint=False): Reporter.objects.create(last_name="Haddock") raise Exception("Oops, that's his first name") self.assertSequenceEqual(Reporter.objects.all(), []) def test_merged_rollback_rollback(self): with self.assertRaisesMessage(Exception, "Oops"): with transaction.atomic(): Reporter.objects.create(last_name="Tintin") with self.assertRaisesMessage(Exception, "Oops"): with transaction.atomic(savepoint=False): Reporter.objects.create(first_name="Haddock") raise Exception("Oops, that's his last name") raise Exception("Oops, that's his first name") self.assertSequenceEqual(Reporter.objects.all(), []) def test_reuse_commit_commit(self): atomic = transaction.atomic() with atomic: reporter1 = Reporter.objects.create(first_name="Tintin") with atomic: reporter2 = Reporter.objects.create( first_name="Archibald", last_name="Haddock" ) self.assertSequenceEqual(Reporter.objects.all(), [reporter2, reporter1]) def test_reuse_commit_rollback(self): atomic = transaction.atomic() with atomic: reporter = Reporter.objects.create(first_name="Tintin") with self.assertRaisesMessage(Exception, "Oops"): with atomic: Reporter.objects.create(first_name="Haddock") raise Exception("Oops, that's his last name") self.assertSequenceEqual(Reporter.objects.all(), [reporter]) def test_reuse_rollback_commit(self): atomic = transaction.atomic() with self.assertRaisesMessage(Exception, "Oops"): with atomic: Reporter.objects.create(last_name="Tintin") with atomic: Reporter.objects.create(last_name="Haddock") raise Exception("Oops, that's his first name") self.assertSequenceEqual(Reporter.objects.all(), []) def test_reuse_rollback_rollback(self): atomic = transaction.atomic() with self.assertRaisesMessage(Exception, "Oops"): with atomic: Reporter.objects.create(last_name="Tintin") with self.assertRaisesMessage(Exception, "Oops"): with atomic: Reporter.objects.create(first_name="Haddock") raise Exception("Oops, that's his last name") raise Exception("Oops, that's his first name") self.assertSequenceEqual(Reporter.objects.all(), []) def test_force_rollback(self): with transaction.atomic(): Reporter.objects.create(first_name="Tintin") # atomic block shouldn't rollback, but force it. self.assertFalse(transaction.get_rollback()) transaction.set_rollback(True) self.assertSequenceEqual(Reporter.objects.all(), []) def test_prevent_rollback(self): with transaction.atomic(): reporter = Reporter.objects.create(first_name="Tintin") sid = transaction.savepoint() # trigger a database error inside an inner atomic without savepoint with self.assertRaises(DatabaseError): with transaction.atomic(savepoint=False): with connection.cursor() as cursor: cursor.execute("SELECT no_such_col FROM transactions_reporter") # prevent atomic from rolling back since we're recovering manually self.assertTrue(transaction.get_rollback()) transaction.set_rollback(False) transaction.savepoint_rollback(sid) self.assertSequenceEqual(Reporter.objects.all(), [reporter]) class AtomicInsideTransactionTests(AtomicTests): """All basic tests for atomic should also pass within an existing transaction.""" def setUp(self): self.atomic = transaction.atomic() self.atomic.__enter__() def tearDown(self): self.atomic.__exit__(*sys.exc_info()) class AtomicWithoutAutocommitTests(AtomicTests): """All basic tests for atomic should also pass when autocommit is turned off.""" def setUp(self): transaction.set_autocommit(False) def tearDown(self): # The tests access the database after exercising 'atomic', initiating # a transaction ; a rollback is required before restoring autocommit. transaction.rollback() transaction.set_autocommit(True) @skipUnlessDBFeature("uses_savepoints") class AtomicMergeTests(TransactionTestCase): """Test merging transactions with savepoint=False.""" available_apps = ["transactions"] def test_merged_outer_rollback(self): with transaction.atomic(): Reporter.objects.create(first_name="Tintin") with transaction.atomic(savepoint=False): Reporter.objects.create(first_name="Archibald", last_name="Haddock") with self.assertRaisesMessage(Exception, "Oops"): with transaction.atomic(savepoint=False): Reporter.objects.create(first_name="Calculus") raise Exception("Oops, that's his last name") # The third insert couldn't be roll back. Temporarily mark the # connection as not needing rollback to check it. self.assertTrue(transaction.get_rollback()) transaction.set_rollback(False) self.assertEqual(Reporter.objects.count(), 3) transaction.set_rollback(True) # The second insert couldn't be roll back. Temporarily mark the # connection as not needing rollback to check it. self.assertTrue(transaction.get_rollback()) transaction.set_rollback(False) self.assertEqual(Reporter.objects.count(), 3) transaction.set_rollback(True) # The first block has a savepoint and must roll back. self.assertSequenceEqual(Reporter.objects.all(), []) def test_merged_inner_savepoint_rollback(self): with transaction.atomic(): reporter = Reporter.objects.create(first_name="Tintin") with transaction.atomic(): Reporter.objects.create(first_name="Archibald", last_name="Haddock") with self.assertRaisesMessage(Exception, "Oops"): with transaction.atomic(savepoint=False): Reporter.objects.create(first_name="Calculus") raise Exception("Oops, that's his last name") # The third insert couldn't be roll back. Temporarily mark the # connection as not needing rollback to check it. self.assertTrue(transaction.get_rollback()) transaction.set_rollback(False) self.assertEqual(Reporter.objects.count(), 3) transaction.set_rollback(True) # The second block has a savepoint and must roll back. self.assertEqual(Reporter.objects.count(), 1) self.assertSequenceEqual(Reporter.objects.all(), [reporter]) @skipUnlessDBFeature("uses_savepoints") class AtomicErrorsTests(TransactionTestCase): available_apps = ["transactions"] forbidden_atomic_msg = "This is forbidden when an 'atomic' block is active." def test_atomic_prevents_setting_autocommit(self): autocommit = transaction.get_autocommit() with transaction.atomic(): with self.assertRaisesMessage( transaction.TransactionManagementError, self.forbidden_atomic_msg ): transaction.set_autocommit(not autocommit) # Make sure autocommit wasn't changed. self.assertEqual(connection.autocommit, autocommit) def test_atomic_prevents_calling_transaction_methods(self): with transaction.atomic(): with self.assertRaisesMessage( transaction.TransactionManagementError, self.forbidden_atomic_msg ): transaction.commit() with self.assertRaisesMessage( transaction.TransactionManagementError, self.forbidden_atomic_msg ): transaction.rollback() def test_atomic_prevents_queries_in_broken_transaction(self): r1 = Reporter.objects.create(first_name="Archibald", last_name="Haddock") with transaction.atomic(): r2 = Reporter(first_name="Cuthbert", last_name="Calculus", id=r1.id) with self.assertRaises(IntegrityError): r2.save(force_insert=True) # The transaction is marked as needing rollback. msg = ( "An error occurred in the current transaction. You can't " "execute queries until the end of the 'atomic' block." ) with self.assertRaisesMessage(transaction.TransactionManagementError, msg): r2.save(force_update=True) self.assertEqual(Reporter.objects.get(pk=r1.pk).last_name, "Haddock") @skipIfDBFeature("atomic_transactions") def test_atomic_allows_queries_after_fixing_transaction(self): r1 = Reporter.objects.create(first_name="Archibald", last_name="Haddock") with transaction.atomic(): r2 = Reporter(first_name="Cuthbert", last_name="Calculus", id=r1.id) with self.assertRaises(IntegrityError): r2.save(force_insert=True) # Mark the transaction as no longer needing rollback. transaction.set_rollback(False) r2.save(force_update=True) self.assertEqual(Reporter.objects.get(pk=r1.pk).last_name, "Calculus") @skipUnlessDBFeature("test_db_allows_multiple_connections") def test_atomic_prevents_queries_in_broken_transaction_after_client_close(self): with transaction.atomic(): Reporter.objects.create(first_name="Archibald", last_name="Haddock") connection.close() # The connection is closed and the transaction is marked as # needing rollback. This will raise an InterfaceError on databases # that refuse to create cursors on closed connections (PostgreSQL) # and a TransactionManagementError on other databases. with self.assertRaises(Error): Reporter.objects.create(first_name="Cuthbert", last_name="Calculus") # The connection is usable again . self.assertEqual(Reporter.objects.count(), 0) @skipUnless(connection.vendor == "mysql", "MySQL-specific behaviors") class AtomicMySQLTests(TransactionTestCase): available_apps = ["transactions"] @skipIf(threading is None, "Test requires threading") def test_implicit_savepoint_rollback(self): """MySQL implicitly rolls back savepoints when it deadlocks (#22291).""" Reporter.objects.create(id=1) Reporter.objects.create(id=2) main_thread_ready = threading.Event() def other_thread(): try: with transaction.atomic(): Reporter.objects.select_for_update().get(id=1) main_thread_ready.wait() # 1) This line locks... (see below for 2) Reporter.objects.exclude(id=1).update(id=2) finally: # This is the thread-local connection, not the main connection. connection.close() other_thread = threading.Thread(target=other_thread) other_thread.start() with self.assertRaisesMessage(OperationalError, "Deadlock found"): # Double atomic to enter a transaction and create a savepoint. with transaction.atomic(): with transaction.atomic(): Reporter.objects.select_for_update().get(id=2) main_thread_ready.set() # The two threads can't be synchronized with an event here # because the other thread locks. Sleep for a little while. time.sleep(1) # 2) ... and this line deadlocks. (see above for 1) Reporter.objects.exclude(id=2).update(id=1) other_thread.join() class AtomicMiscTests(TransactionTestCase): available_apps = ["transactions"] def test_wrap_callable_instance(self): """#20028 -- Atomic must support wrapping callable instances.""" class Callable: def __call__(self): pass # Must not raise an exception transaction.atomic(Callable()) @skipUnlessDBFeature("can_release_savepoints") def test_atomic_does_not_leak_savepoints_on_failure(self): """#23074 -- Savepoints must be released after rollback.""" # Expect an error when rolling back a savepoint that doesn't exist. # Done outside of the transaction block to ensure proper recovery. with self.assertRaises(Error): # Start a plain transaction. with transaction.atomic(): # Swallow the intentional error raised in the sub-transaction. with self.assertRaisesMessage(Exception, "Oops"): # Start a sub-transaction with a savepoint. with transaction.atomic(): sid = connection.savepoint_ids[-1] raise Exception("Oops") # This is expected to fail because the savepoint no longer exists. connection.savepoint_rollback(sid) def test_mark_for_rollback_on_error_in_transaction(self): with transaction.atomic(savepoint=False): # Swallow the intentional error raised. with self.assertRaisesMessage(Exception, "Oops"): # Wrap in `mark_for_rollback_on_error` to check if the # transaction is marked broken. with transaction.mark_for_rollback_on_error(): # Ensure that we are still in a good state. self.assertFalse(transaction.get_rollback()) raise Exception("Oops") # mark_for_rollback_on_error marked the transaction as broken … self.assertTrue(transaction.get_rollback()) # … and further queries fail. msg = "You can't execute queries until the end of the 'atomic' block." with self.assertRaisesMessage(transaction.TransactionManagementError, msg): Reporter.objects.create() # Transaction errors are reset at the end of an transaction, so this # should just work. Reporter.objects.create() def test_mark_for_rollback_on_error_in_autocommit(self): self.assertTrue(transaction.get_autocommit()) # Swallow the intentional error raised. with self.assertRaisesMessage(Exception, "Oops"): # Wrap in `mark_for_rollback_on_error` to check if the transaction # is marked broken. with transaction.mark_for_rollback_on_error(): # Ensure that we are still in a good state. self.assertFalse(transaction.get_connection().needs_rollback) raise Exception("Oops") # Ensure that `mark_for_rollback_on_error` did not mark the transaction # as broken, since we are in autocommit mode … self.assertFalse(transaction.get_connection().needs_rollback) # … and further queries work nicely. Reporter.objects.create() class NonAutocommitTests(TransactionTestCase): available_apps = [] def setUp(self): transaction.set_autocommit(False) def tearDown(self): transaction.rollback() transaction.set_autocommit(True) def test_orm_query_after_error_and_rollback(self): """ ORM queries are allowed after an error and a rollback in non-autocommit mode (#27504). """ r1 = Reporter.objects.create(first_name="Archibald", last_name="Haddock") r2 = Reporter(first_name="Cuthbert", last_name="Calculus", id=r1.id) with self.assertRaises(IntegrityError): r2.save(force_insert=True) transaction.rollback() Reporter.objects.last() def test_orm_query_without_autocommit(self): """#24921 -- ORM queries must be possible after set_autocommit(False).""" Reporter.objects.create(first_name="Tintin") class DurableTestsBase: available_apps = ["transactions"] def test_commit(self): with transaction.atomic(durable=True): reporter = Reporter.objects.create(first_name="Tintin") self.assertEqual(Reporter.objects.get(), reporter) def test_nested_outer_durable(self): with transaction.atomic(durable=True): reporter1 = Reporter.objects.create(first_name="Tintin") with transaction.atomic(): reporter2 = Reporter.objects.create( first_name="Archibald", last_name="Haddock", ) self.assertSequenceEqual(Reporter.objects.all(), [reporter2, reporter1]) def test_nested_both_durable(self): msg = "A durable atomic block cannot be nested within another atomic block." with transaction.atomic(durable=True): with self.assertRaisesMessage(RuntimeError, msg): with transaction.atomic(durable=True): pass def test_nested_inner_durable(self): msg = "A durable atomic block cannot be nested within another atomic block." with transaction.atomic(): with self.assertRaisesMessage(RuntimeError, msg): with transaction.atomic(durable=True): pass def test_sequence_of_durables(self): with transaction.atomic(durable=True): reporter = Reporter.objects.create(first_name="Tintin 1") self.assertEqual(Reporter.objects.get(first_name="Tintin 1"), reporter) with transaction.atomic(durable=True): reporter = Reporter.objects.create(first_name="Tintin 2") self.assertEqual(Reporter.objects.get(first_name="Tintin 2"), reporter) class DurableTransactionTests(DurableTestsBase, TransactionTestCase): pass class DurableTests(DurableTestsBase, TestCase): pass
693ba411ccb9cde38f9049f8af6e0084725e581591f85c05481bc57e69d86249
""" Transactions Django handles transactions in three different ways. The default is to commit each transaction upon a write, but you can decorate a function to get commit-on-success behavior. Alternatively, you can manage the transaction manually. """ from django.db import models class Reporter(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) email = models.EmailField() class Meta: ordering = ("first_name", "last_name") def __str__(self): return ("%s %s" % (self.first_name, self.last_name)).strip()
7bad2fd78334b5737f26d862897d187571048733c6446d70861eb327671f198a
# Unit tests for cache framework # Uses whatever cache backend is set in the test settings file. import copy import io import os import pickle import re import shutil import sys import tempfile import threading import time import unittest from pathlib import Path from unittest import mock, skipIf from django.conf import settings from django.core import management, signals from django.core.cache import ( DEFAULT_CACHE_ALIAS, CacheHandler, CacheKeyWarning, InvalidCacheKey, cache, caches, ) from django.core.cache.backends.base import InvalidCacheBackendError from django.core.cache.backends.redis import RedisCacheClient from django.core.cache.utils import make_template_fragment_key from django.db import close_old_connections, connection, connections from django.db.backends.utils import CursorWrapper from django.http import ( HttpRequest, HttpResponse, HttpResponseNotModified, StreamingHttpResponse, ) from django.middleware.cache import ( CacheMiddleware, FetchFromCacheMiddleware, UpdateCacheMiddleware, ) from django.middleware.csrf import CsrfViewMiddleware from django.template import engines from django.template.context_processors import csrf from django.template.response import TemplateResponse from django.test import ( RequestFactory, SimpleTestCase, TestCase, TransactionTestCase, override_settings, ) from django.test.signals import setting_changed from django.test.utils import CaptureQueriesContext from django.utils import timezone, translation from django.utils.cache import ( get_cache_key, learn_cache_key, patch_cache_control, patch_vary_headers, ) from django.views.decorators.cache import cache_control, cache_page from .models import Poll, expensive_calculation # functions/classes for complex data type tests def f(): return 42 class C: def m(n): return 24 class Unpicklable: def __getstate__(self): raise pickle.PickleError() def empty_response(request): return HttpResponse() KEY_ERRORS_WITH_MEMCACHED_MSG = ( "Cache key contains characters that will cause errors if used with memcached: %r" ) @override_settings( CACHES={ "default": { "BACKEND": "django.core.cache.backends.dummy.DummyCache", } } ) class DummyCacheTests(SimpleTestCase): # The Dummy cache backend doesn't really behave like a test backend, # so it has its own test case. def test_simple(self): "Dummy cache backend ignores cache set calls" cache.set("key", "value") self.assertIsNone(cache.get("key")) def test_add(self): "Add doesn't do anything in dummy cache backend" self.assertIs(cache.add("addkey1", "value"), True) self.assertIs(cache.add("addkey1", "newvalue"), True) self.assertIsNone(cache.get("addkey1")) def test_non_existent(self): "Nonexistent keys aren't found in the dummy cache backend" self.assertIsNone(cache.get("does_not_exist")) self.assertEqual(cache.get("does_not_exist", "bang!"), "bang!") def test_get_many(self): "get_many returns nothing for the dummy cache backend" cache.set_many({"a": "a", "b": "b", "c": "c", "d": "d"}) self.assertEqual(cache.get_many(["a", "c", "d"]), {}) self.assertEqual(cache.get_many(["a", "b", "e"]), {}) def test_get_many_invalid_key(self): msg = KEY_ERRORS_WITH_MEMCACHED_MSG % ":1:key with spaces" with self.assertWarnsMessage(CacheKeyWarning, msg): cache.get_many(["key with spaces"]) def test_delete(self): "Cache deletion is transparently ignored on the dummy cache backend" cache.set_many({"key1": "spam", "key2": "eggs"}) self.assertIsNone(cache.get("key1")) self.assertIs(cache.delete("key1"), False) self.assertIsNone(cache.get("key1")) self.assertIsNone(cache.get("key2")) def test_has_key(self): "The has_key method doesn't ever return True for the dummy cache backend" cache.set("hello1", "goodbye1") self.assertIs(cache.has_key("hello1"), False) self.assertIs(cache.has_key("goodbye1"), False) def test_in(self): "The in operator doesn't ever return True for the dummy cache backend" cache.set("hello2", "goodbye2") self.assertNotIn("hello2", cache) self.assertNotIn("goodbye2", cache) def test_incr(self): "Dummy cache values can't be incremented" cache.set("answer", 42) with self.assertRaises(ValueError): cache.incr("answer") with self.assertRaises(ValueError): cache.incr("does_not_exist") with self.assertRaises(ValueError): cache.incr("does_not_exist", -1) def test_decr(self): "Dummy cache values can't be decremented" cache.set("answer", 42) with self.assertRaises(ValueError): cache.decr("answer") with self.assertRaises(ValueError): cache.decr("does_not_exist") with self.assertRaises(ValueError): cache.decr("does_not_exist", -1) def test_touch(self): """Dummy cache can't do touch().""" self.assertIs(cache.touch("whatever"), False) def test_data_types(self): "All data types are ignored equally by the dummy cache" tests = { "string": "this is a string", "int": 42, "bool": True, "list": [1, 2, 3, 4], "tuple": (1, 2, 3, 4), "dict": {"A": 1, "B": 2}, "function": f, "class": C, } for key, value in tests.items(): with self.subTest(key=key): cache.set(key, value) self.assertIsNone(cache.get(key)) def test_expiration(self): "Expiration has no effect on the dummy cache" cache.set("expire1", "very quickly", 1) cache.set("expire2", "very quickly", 1) cache.set("expire3", "very quickly", 1) time.sleep(2) self.assertIsNone(cache.get("expire1")) self.assertIs(cache.add("expire2", "newvalue"), True) self.assertIsNone(cache.get("expire2")) self.assertIs(cache.has_key("expire3"), False) def test_unicode(self): "Unicode values are ignored by the dummy cache" stuff = { "ascii": "ascii_value", "unicode_ascii": "Iñtërnâtiônàlizætiøn1", "Iñtërnâtiônàlizætiøn": "Iñtërnâtiônàlizætiøn2", "ascii2": {"x": 1}, } for (key, value) in stuff.items(): with self.subTest(key=key): cache.set(key, value) self.assertIsNone(cache.get(key)) def test_set_many(self): "set_many does nothing for the dummy cache backend" self.assertEqual(cache.set_many({"a": 1, "b": 2}), []) self.assertEqual(cache.set_many({"a": 1, "b": 2}, timeout=2, version="1"), []) def test_set_many_invalid_key(self): msg = KEY_ERRORS_WITH_MEMCACHED_MSG % ":1:key with spaces" with self.assertWarnsMessage(CacheKeyWarning, msg): cache.set_many({"key with spaces": "foo"}) def test_delete_many(self): "delete_many does nothing for the dummy cache backend" cache.delete_many(["a", "b"]) def test_delete_many_invalid_key(self): msg = KEY_ERRORS_WITH_MEMCACHED_MSG % ":1:key with spaces" with self.assertWarnsMessage(CacheKeyWarning, msg): cache.delete_many(["key with spaces"]) def test_clear(self): "clear does nothing for the dummy cache backend" cache.clear() def test_incr_version(self): "Dummy cache versions can't be incremented" cache.set("answer", 42) with self.assertRaises(ValueError): cache.incr_version("answer") with self.assertRaises(ValueError): cache.incr_version("does_not_exist") def test_decr_version(self): "Dummy cache versions can't be decremented" cache.set("answer", 42) with self.assertRaises(ValueError): cache.decr_version("answer") with self.assertRaises(ValueError): cache.decr_version("does_not_exist") def test_get_or_set(self): self.assertEqual(cache.get_or_set("mykey", "default"), "default") self.assertIsNone(cache.get_or_set("mykey", None)) def test_get_or_set_callable(self): def my_callable(): return "default" self.assertEqual(cache.get_or_set("mykey", my_callable), "default") self.assertEqual(cache.get_or_set("mykey", my_callable()), "default") def custom_key_func(key, key_prefix, version): "A customized cache key function" return "CUSTOM-" + "-".join([key_prefix, str(version), key]) _caches_setting_base = { "default": {}, "prefix": {"KEY_PREFIX": "cacheprefix{}".format(os.getpid())}, "v2": {"VERSION": 2}, "custom_key": {"KEY_FUNCTION": custom_key_func}, "custom_key2": {"KEY_FUNCTION": "cache.tests.custom_key_func"}, "cull": {"OPTIONS": {"MAX_ENTRIES": 30}}, "zero_cull": {"OPTIONS": {"CULL_FREQUENCY": 0, "MAX_ENTRIES": 30}}, } def caches_setting_for_tests(base=None, exclude=None, **params): # `base` is used to pull in the memcached config from the original settings, # `exclude` is a set of cache names denoting which `_caches_setting_base` keys # should be omitted. # `params` are test specific overrides and `_caches_settings_base` is the # base config for the tests. # This results in the following search order: # params -> _caches_setting_base -> base base = base or {} exclude = exclude or set() setting = {k: base.copy() for k in _caches_setting_base if k not in exclude} for key, cache_params in setting.items(): cache_params.update(_caches_setting_base[key]) cache_params.update(params) return setting class BaseCacheTests: # A common set of tests to apply to all cache backends factory = RequestFactory() # Some clients raise custom exceptions when .incr() or .decr() are called # with a non-integer value. incr_decr_type_error = TypeError def tearDown(self): cache.clear() def test_simple(self): # Simple cache set/get works cache.set("key", "value") self.assertEqual(cache.get("key"), "value") def test_default_used_when_none_is_set(self): """If None is cached, get() returns it instead of the default.""" cache.set("key_default_none", None) self.assertIsNone(cache.get("key_default_none", default="default")) def test_add(self): # A key can be added to a cache self.assertIs(cache.add("addkey1", "value"), True) self.assertIs(cache.add("addkey1", "newvalue"), False) self.assertEqual(cache.get("addkey1"), "value") def test_prefix(self): # Test for same cache key conflicts between shared backend cache.set("somekey", "value") # should not be set in the prefixed cache self.assertIs(caches["prefix"].has_key("somekey"), False) caches["prefix"].set("somekey", "value2") self.assertEqual(cache.get("somekey"), "value") self.assertEqual(caches["prefix"].get("somekey"), "value2") def test_non_existent(self): """Nonexistent cache keys return as None/default.""" self.assertIsNone(cache.get("does_not_exist")) self.assertEqual(cache.get("does_not_exist", "bang!"), "bang!") def test_get_many(self): # Multiple cache keys can be returned using get_many cache.set_many({"a": "a", "b": "b", "c": "c", "d": "d"}) self.assertEqual( cache.get_many(["a", "c", "d"]), {"a": "a", "c": "c", "d": "d"} ) self.assertEqual(cache.get_many(["a", "b", "e"]), {"a": "a", "b": "b"}) self.assertEqual(cache.get_many(iter(["a", "b", "e"])), {"a": "a", "b": "b"}) cache.set_many({"x": None, "y": 1}) self.assertEqual(cache.get_many(["x", "y"]), {"x": None, "y": 1}) def test_delete(self): # Cache keys can be deleted cache.set_many({"key1": "spam", "key2": "eggs"}) self.assertEqual(cache.get("key1"), "spam") self.assertIs(cache.delete("key1"), True) self.assertIsNone(cache.get("key1")) self.assertEqual(cache.get("key2"), "eggs") def test_delete_nonexistent(self): self.assertIs(cache.delete("nonexistent_key"), False) def test_has_key(self): # The cache can be inspected for cache keys cache.set("hello1", "goodbye1") self.assertIs(cache.has_key("hello1"), True) self.assertIs(cache.has_key("goodbye1"), False) cache.set("no_expiry", "here", None) self.assertIs(cache.has_key("no_expiry"), True) cache.set("null", None) self.assertIs(cache.has_key("null"), True) def test_in(self): # The in operator can be used to inspect cache contents cache.set("hello2", "goodbye2") self.assertIn("hello2", cache) self.assertNotIn("goodbye2", cache) cache.set("null", None) self.assertIn("null", cache) def test_incr(self): # Cache values can be incremented cache.set("answer", 41) self.assertEqual(cache.incr("answer"), 42) self.assertEqual(cache.get("answer"), 42) self.assertEqual(cache.incr("answer", 10), 52) self.assertEqual(cache.get("answer"), 52) self.assertEqual(cache.incr("answer", -10), 42) with self.assertRaises(ValueError): cache.incr("does_not_exist") with self.assertRaises(ValueError): cache.incr("does_not_exist", -1) cache.set("null", None) with self.assertRaises(self.incr_decr_type_error): cache.incr("null") def test_decr(self): # Cache values can be decremented cache.set("answer", 43) self.assertEqual(cache.decr("answer"), 42) self.assertEqual(cache.get("answer"), 42) self.assertEqual(cache.decr("answer", 10), 32) self.assertEqual(cache.get("answer"), 32) self.assertEqual(cache.decr("answer", -10), 42) with self.assertRaises(ValueError): cache.decr("does_not_exist") with self.assertRaises(ValueError): cache.incr("does_not_exist", -1) cache.set("null", None) with self.assertRaises(self.incr_decr_type_error): cache.decr("null") def test_close(self): self.assertTrue(hasattr(cache, "close")) cache.close() def test_data_types(self): # Many different data types can be cached tests = { "string": "this is a string", "int": 42, "bool": True, "list": [1, 2, 3, 4], "tuple": (1, 2, 3, 4), "dict": {"A": 1, "B": 2}, "function": f, "class": C, } for key, value in tests.items(): with self.subTest(key=key): cache.set(key, value) self.assertEqual(cache.get(key), value) def test_cache_read_for_model_instance(self): # Don't want fields with callable as default to be called on cache read expensive_calculation.num_runs = 0 Poll.objects.all().delete() my_poll = Poll.objects.create(question="Well?") self.assertEqual(Poll.objects.count(), 1) pub_date = my_poll.pub_date cache.set("question", my_poll) cached_poll = cache.get("question") self.assertEqual(cached_poll.pub_date, pub_date) # We only want the default expensive calculation run once self.assertEqual(expensive_calculation.num_runs, 1) def test_cache_write_for_model_instance_with_deferred(self): # Don't want fields with callable as default to be called on cache write expensive_calculation.num_runs = 0 Poll.objects.all().delete() Poll.objects.create(question="What?") self.assertEqual(expensive_calculation.num_runs, 1) defer_qs = Poll.objects.defer("question") self.assertEqual(defer_qs.count(), 1) self.assertEqual(expensive_calculation.num_runs, 1) cache.set("deferred_queryset", defer_qs) # cache set should not re-evaluate default functions self.assertEqual(expensive_calculation.num_runs, 1) def test_cache_read_for_model_instance_with_deferred(self): # Don't want fields with callable as default to be called on cache read expensive_calculation.num_runs = 0 Poll.objects.all().delete() Poll.objects.create(question="What?") self.assertEqual(expensive_calculation.num_runs, 1) defer_qs = Poll.objects.defer("question") self.assertEqual(defer_qs.count(), 1) cache.set("deferred_queryset", defer_qs) self.assertEqual(expensive_calculation.num_runs, 1) runs_before_cache_read = expensive_calculation.num_runs cache.get("deferred_queryset") # We only want the default expensive calculation run on creation and set self.assertEqual(expensive_calculation.num_runs, runs_before_cache_read) def test_expiration(self): # Cache values can be set to expire cache.set("expire1", "very quickly", 1) cache.set("expire2", "very quickly", 1) cache.set("expire3", "very quickly", 1) time.sleep(2) self.assertIsNone(cache.get("expire1")) self.assertIs(cache.add("expire2", "newvalue"), True) self.assertEqual(cache.get("expire2"), "newvalue") self.assertIs(cache.has_key("expire3"), False) def test_touch(self): # cache.touch() updates the timeout. cache.set("expire1", "very quickly", timeout=1) self.assertIs(cache.touch("expire1", timeout=4), True) time.sleep(2) self.assertIs(cache.has_key("expire1"), True) time.sleep(3) self.assertIs(cache.has_key("expire1"), False) # cache.touch() works without the timeout argument. cache.set("expire1", "very quickly", timeout=1) self.assertIs(cache.touch("expire1"), True) time.sleep(2) self.assertIs(cache.has_key("expire1"), True) self.assertIs(cache.touch("nonexistent"), False) def test_unicode(self): # Unicode values can be cached stuff = { "ascii": "ascii_value", "unicode_ascii": "Iñtërnâtiônàlizætiøn1", "Iñtërnâtiônàlizætiøn": "Iñtërnâtiônàlizætiøn2", "ascii2": {"x": 1}, } # Test `set` for (key, value) in stuff.items(): with self.subTest(key=key): cache.set(key, value) self.assertEqual(cache.get(key), value) # Test `add` for (key, value) in stuff.items(): with self.subTest(key=key): self.assertIs(cache.delete(key), True) self.assertIs(cache.add(key, value), True) self.assertEqual(cache.get(key), value) # Test `set_many` for (key, value) in stuff.items(): self.assertIs(cache.delete(key), True) cache.set_many(stuff) for (key, value) in stuff.items(): with self.subTest(key=key): self.assertEqual(cache.get(key), value) def test_binary_string(self): # Binary strings should be cacheable from zlib import compress, decompress value = "value_to_be_compressed" compressed_value = compress(value.encode()) # Test set cache.set("binary1", compressed_value) compressed_result = cache.get("binary1") self.assertEqual(compressed_value, compressed_result) self.assertEqual(value, decompress(compressed_result).decode()) # Test add self.assertIs(cache.add("binary1-add", compressed_value), True) compressed_result = cache.get("binary1-add") self.assertEqual(compressed_value, compressed_result) self.assertEqual(value, decompress(compressed_result).decode()) # Test set_many cache.set_many({"binary1-set_many": compressed_value}) compressed_result = cache.get("binary1-set_many") self.assertEqual(compressed_value, compressed_result) self.assertEqual(value, decompress(compressed_result).decode()) def test_set_many(self): # Multiple keys can be set using set_many cache.set_many({"key1": "spam", "key2": "eggs"}) self.assertEqual(cache.get("key1"), "spam") self.assertEqual(cache.get("key2"), "eggs") def test_set_many_returns_empty_list_on_success(self): """set_many() returns an empty list when all keys are inserted.""" failing_keys = cache.set_many({"key1": "spam", "key2": "eggs"}) self.assertEqual(failing_keys, []) def test_set_many_expiration(self): # set_many takes a second ``timeout`` parameter cache.set_many({"key1": "spam", "key2": "eggs"}, 1) time.sleep(2) self.assertIsNone(cache.get("key1")) self.assertIsNone(cache.get("key2")) def test_delete_many(self): # Multiple keys can be deleted using delete_many cache.set_many({"key1": "spam", "key2": "eggs", "key3": "ham"}) cache.delete_many(["key1", "key2"]) self.assertIsNone(cache.get("key1")) self.assertIsNone(cache.get("key2")) self.assertEqual(cache.get("key3"), "ham") def test_clear(self): # The cache can be emptied using clear cache.set_many({"key1": "spam", "key2": "eggs"}) cache.clear() self.assertIsNone(cache.get("key1")) self.assertIsNone(cache.get("key2")) def test_long_timeout(self): """ Follow memcached's convention where a timeout greater than 30 days is treated as an absolute expiration timestamp instead of a relative offset (#12399). """ cache.set("key1", "eggs", 60 * 60 * 24 * 30 + 1) # 30 days + 1 second self.assertEqual(cache.get("key1"), "eggs") self.assertIs(cache.add("key2", "ham", 60 * 60 * 24 * 30 + 1), True) self.assertEqual(cache.get("key2"), "ham") cache.set_many( {"key3": "sausage", "key4": "lobster bisque"}, 60 * 60 * 24 * 30 + 1 ) self.assertEqual(cache.get("key3"), "sausage") self.assertEqual(cache.get("key4"), "lobster bisque") def test_forever_timeout(self): """ Passing in None into timeout results in a value that is cached forever """ cache.set("key1", "eggs", None) self.assertEqual(cache.get("key1"), "eggs") self.assertIs(cache.add("key2", "ham", None), True) self.assertEqual(cache.get("key2"), "ham") self.assertIs(cache.add("key1", "new eggs", None), False) self.assertEqual(cache.get("key1"), "eggs") cache.set_many({"key3": "sausage", "key4": "lobster bisque"}, None) self.assertEqual(cache.get("key3"), "sausage") self.assertEqual(cache.get("key4"), "lobster bisque") cache.set("key5", "belgian fries", timeout=1) self.assertIs(cache.touch("key5", timeout=None), True) time.sleep(2) self.assertEqual(cache.get("key5"), "belgian fries") def test_zero_timeout(self): """ Passing in zero into timeout results in a value that is not cached """ cache.set("key1", "eggs", 0) self.assertIsNone(cache.get("key1")) self.assertIs(cache.add("key2", "ham", 0), True) self.assertIsNone(cache.get("key2")) cache.set_many({"key3": "sausage", "key4": "lobster bisque"}, 0) self.assertIsNone(cache.get("key3")) self.assertIsNone(cache.get("key4")) cache.set("key5", "belgian fries", timeout=5) self.assertIs(cache.touch("key5", timeout=0), True) self.assertIsNone(cache.get("key5")) def test_float_timeout(self): # Make sure a timeout given as a float doesn't crash anything. cache.set("key1", "spam", 100.2) self.assertEqual(cache.get("key1"), "spam") def _perform_cull_test(self, cull_cache_name, initial_count, final_count): try: cull_cache = caches[cull_cache_name] except InvalidCacheBackendError: self.skipTest("Culling isn't implemented.") # Create initial cache key entries. This will overflow the cache, # causing a cull. for i in range(1, initial_count): cull_cache.set("cull%d" % i, "value", 1000) count = 0 # Count how many keys are left in the cache. for i in range(1, initial_count): if cull_cache.has_key("cull%d" % i): count += 1 self.assertEqual(count, final_count) def test_cull(self): self._perform_cull_test("cull", 50, 29) def test_zero_cull(self): self._perform_cull_test("zero_cull", 50, 19) def test_cull_delete_when_store_empty(self): try: cull_cache = caches["cull"] except InvalidCacheBackendError: self.skipTest("Culling isn't implemented.") old_max_entries = cull_cache._max_entries # Force _cull to delete on first cached record. cull_cache._max_entries = -1 try: cull_cache.set("force_cull_delete", "value", 1000) self.assertIs(cull_cache.has_key("force_cull_delete"), True) finally: cull_cache._max_entries = old_max_entries def _perform_invalid_key_test(self, key, expected_warning, key_func=None): """ All the builtin backends should warn (except memcached that should error) on keys that would be refused by memcached. This encourages portable caching code without making it too difficult to use production backends with more liberal key rules. Refs #6447. """ # mimic custom ``make_key`` method being defined since the default will # never show the below warnings def func(key, *args): return key old_func = cache.key_func cache.key_func = key_func or func tests = [ ("add", [key, 1]), ("get", [key]), ("set", [key, 1]), ("incr", [key]), ("decr", [key]), ("touch", [key]), ("delete", [key]), ("get_many", [[key, "b"]]), ("set_many", [{key: 1, "b": 2}]), ("delete_many", [[key, "b"]]), ] try: for operation, args in tests: with self.subTest(operation=operation): with self.assertWarns(CacheKeyWarning) as cm: getattr(cache, operation)(*args) self.assertEqual(str(cm.warning), expected_warning) finally: cache.key_func = old_func def test_invalid_key_characters(self): # memcached doesn't allow whitespace or control characters in keys. key = "key with spaces and 清" self._perform_invalid_key_test(key, KEY_ERRORS_WITH_MEMCACHED_MSG % key) def test_invalid_key_length(self): # memcached limits key length to 250. key = ("a" * 250) + "清" expected_warning = ( "Cache key will cause errors if used with memcached: " "%r (longer than %s)" % (key, 250) ) self._perform_invalid_key_test(key, expected_warning) def test_invalid_with_version_key_length(self): # Custom make_key() that adds a version to the key and exceeds the # limit. def key_func(key, *args): return key + ":1" key = "a" * 249 expected_warning = ( "Cache key will cause errors if used with memcached: " "%r (longer than %s)" % (key_func(key), 250) ) self._perform_invalid_key_test(key, expected_warning, key_func=key_func) def test_cache_versioning_get_set(self): # set, using default version = 1 cache.set("answer1", 42) self.assertEqual(cache.get("answer1"), 42) self.assertEqual(cache.get("answer1", version=1), 42) self.assertIsNone(cache.get("answer1", version=2)) self.assertIsNone(caches["v2"].get("answer1")) self.assertEqual(caches["v2"].get("answer1", version=1), 42) self.assertIsNone(caches["v2"].get("answer1", version=2)) # set, default version = 1, but manually override version = 2 cache.set("answer2", 42, version=2) self.assertIsNone(cache.get("answer2")) self.assertIsNone(cache.get("answer2", version=1)) self.assertEqual(cache.get("answer2", version=2), 42) self.assertEqual(caches["v2"].get("answer2"), 42) self.assertIsNone(caches["v2"].get("answer2", version=1)) self.assertEqual(caches["v2"].get("answer2", version=2), 42) # v2 set, using default version = 2 caches["v2"].set("answer3", 42) self.assertIsNone(cache.get("answer3")) self.assertIsNone(cache.get("answer3", version=1)) self.assertEqual(cache.get("answer3", version=2), 42) self.assertEqual(caches["v2"].get("answer3"), 42) self.assertIsNone(caches["v2"].get("answer3", version=1)) self.assertEqual(caches["v2"].get("answer3", version=2), 42) # v2 set, default version = 2, but manually override version = 1 caches["v2"].set("answer4", 42, version=1) self.assertEqual(cache.get("answer4"), 42) self.assertEqual(cache.get("answer4", version=1), 42) self.assertIsNone(cache.get("answer4", version=2)) self.assertIsNone(caches["v2"].get("answer4")) self.assertEqual(caches["v2"].get("answer4", version=1), 42) self.assertIsNone(caches["v2"].get("answer4", version=2)) def test_cache_versioning_add(self): # add, default version = 1, but manually override version = 2 self.assertIs(cache.add("answer1", 42, version=2), True) self.assertIsNone(cache.get("answer1", version=1)) self.assertEqual(cache.get("answer1", version=2), 42) self.assertIs(cache.add("answer1", 37, version=2), False) self.assertIsNone(cache.get("answer1", version=1)) self.assertEqual(cache.get("answer1", version=2), 42) self.assertIs(cache.add("answer1", 37, version=1), True) self.assertEqual(cache.get("answer1", version=1), 37) self.assertEqual(cache.get("answer1", version=2), 42) # v2 add, using default version = 2 self.assertIs(caches["v2"].add("answer2", 42), True) self.assertIsNone(cache.get("answer2", version=1)) self.assertEqual(cache.get("answer2", version=2), 42) self.assertIs(caches["v2"].add("answer2", 37), False) self.assertIsNone(cache.get("answer2", version=1)) self.assertEqual(cache.get("answer2", version=2), 42) self.assertIs(caches["v2"].add("answer2", 37, version=1), True) self.assertEqual(cache.get("answer2", version=1), 37) self.assertEqual(cache.get("answer2", version=2), 42) # v2 add, default version = 2, but manually override version = 1 self.assertIs(caches["v2"].add("answer3", 42, version=1), True) self.assertEqual(cache.get("answer3", version=1), 42) self.assertIsNone(cache.get("answer3", version=2)) self.assertIs(caches["v2"].add("answer3", 37, version=1), False) self.assertEqual(cache.get("answer3", version=1), 42) self.assertIsNone(cache.get("answer3", version=2)) self.assertIs(caches["v2"].add("answer3", 37), True) self.assertEqual(cache.get("answer3", version=1), 42) self.assertEqual(cache.get("answer3", version=2), 37) def test_cache_versioning_has_key(self): cache.set("answer1", 42) # has_key self.assertIs(cache.has_key("answer1"), True) self.assertIs(cache.has_key("answer1", version=1), True) self.assertIs(cache.has_key("answer1", version=2), False) self.assertIs(caches["v2"].has_key("answer1"), False) self.assertIs(caches["v2"].has_key("answer1", version=1), True) self.assertIs(caches["v2"].has_key("answer1", version=2), False) def test_cache_versioning_delete(self): cache.set("answer1", 37, version=1) cache.set("answer1", 42, version=2) self.assertIs(cache.delete("answer1"), True) self.assertIsNone(cache.get("answer1", version=1)) self.assertEqual(cache.get("answer1", version=2), 42) cache.set("answer2", 37, version=1) cache.set("answer2", 42, version=2) self.assertIs(cache.delete("answer2", version=2), True) self.assertEqual(cache.get("answer2", version=1), 37) self.assertIsNone(cache.get("answer2", version=2)) cache.set("answer3", 37, version=1) cache.set("answer3", 42, version=2) self.assertIs(caches["v2"].delete("answer3"), True) self.assertEqual(cache.get("answer3", version=1), 37) self.assertIsNone(cache.get("answer3", version=2)) cache.set("answer4", 37, version=1) cache.set("answer4", 42, version=2) self.assertIs(caches["v2"].delete("answer4", version=1), True) self.assertIsNone(cache.get("answer4", version=1)) self.assertEqual(cache.get("answer4", version=2), 42) def test_cache_versioning_incr_decr(self): cache.set("answer1", 37, version=1) cache.set("answer1", 42, version=2) self.assertEqual(cache.incr("answer1"), 38) self.assertEqual(cache.get("answer1", version=1), 38) self.assertEqual(cache.get("answer1", version=2), 42) self.assertEqual(cache.decr("answer1"), 37) self.assertEqual(cache.get("answer1", version=1), 37) self.assertEqual(cache.get("answer1", version=2), 42) cache.set("answer2", 37, version=1) cache.set("answer2", 42, version=2) self.assertEqual(cache.incr("answer2", version=2), 43) self.assertEqual(cache.get("answer2", version=1), 37) self.assertEqual(cache.get("answer2", version=2), 43) self.assertEqual(cache.decr("answer2", version=2), 42) self.assertEqual(cache.get("answer2", version=1), 37) self.assertEqual(cache.get("answer2", version=2), 42) cache.set("answer3", 37, version=1) cache.set("answer3", 42, version=2) self.assertEqual(caches["v2"].incr("answer3"), 43) self.assertEqual(cache.get("answer3", version=1), 37) self.assertEqual(cache.get("answer3", version=2), 43) self.assertEqual(caches["v2"].decr("answer3"), 42) self.assertEqual(cache.get("answer3", version=1), 37) self.assertEqual(cache.get("answer3", version=2), 42) cache.set("answer4", 37, version=1) cache.set("answer4", 42, version=2) self.assertEqual(caches["v2"].incr("answer4", version=1), 38) self.assertEqual(cache.get("answer4", version=1), 38) self.assertEqual(cache.get("answer4", version=2), 42) self.assertEqual(caches["v2"].decr("answer4", version=1), 37) self.assertEqual(cache.get("answer4", version=1), 37) self.assertEqual(cache.get("answer4", version=2), 42) def test_cache_versioning_get_set_many(self): # set, using default version = 1 cache.set_many({"ford1": 37, "arthur1": 42}) self.assertEqual( cache.get_many(["ford1", "arthur1"]), {"ford1": 37, "arthur1": 42} ) self.assertEqual( cache.get_many(["ford1", "arthur1"], version=1), {"ford1": 37, "arthur1": 42}, ) self.assertEqual(cache.get_many(["ford1", "arthur1"], version=2), {}) self.assertEqual(caches["v2"].get_many(["ford1", "arthur1"]), {}) self.assertEqual( caches["v2"].get_many(["ford1", "arthur1"], version=1), {"ford1": 37, "arthur1": 42}, ) self.assertEqual(caches["v2"].get_many(["ford1", "arthur1"], version=2), {}) # set, default version = 1, but manually override version = 2 cache.set_many({"ford2": 37, "arthur2": 42}, version=2) self.assertEqual(cache.get_many(["ford2", "arthur2"]), {}) self.assertEqual(cache.get_many(["ford2", "arthur2"], version=1), {}) self.assertEqual( cache.get_many(["ford2", "arthur2"], version=2), {"ford2": 37, "arthur2": 42}, ) self.assertEqual( caches["v2"].get_many(["ford2", "arthur2"]), {"ford2": 37, "arthur2": 42} ) self.assertEqual(caches["v2"].get_many(["ford2", "arthur2"], version=1), {}) self.assertEqual( caches["v2"].get_many(["ford2", "arthur2"], version=2), {"ford2": 37, "arthur2": 42}, ) # v2 set, using default version = 2 caches["v2"].set_many({"ford3": 37, "arthur3": 42}) self.assertEqual(cache.get_many(["ford3", "arthur3"]), {}) self.assertEqual(cache.get_many(["ford3", "arthur3"], version=1), {}) self.assertEqual( cache.get_many(["ford3", "arthur3"], version=2), {"ford3": 37, "arthur3": 42}, ) self.assertEqual( caches["v2"].get_many(["ford3", "arthur3"]), {"ford3": 37, "arthur3": 42} ) self.assertEqual(caches["v2"].get_many(["ford3", "arthur3"], version=1), {}) self.assertEqual( caches["v2"].get_many(["ford3", "arthur3"], version=2), {"ford3": 37, "arthur3": 42}, ) # v2 set, default version = 2, but manually override version = 1 caches["v2"].set_many({"ford4": 37, "arthur4": 42}, version=1) self.assertEqual( cache.get_many(["ford4", "arthur4"]), {"ford4": 37, "arthur4": 42} ) self.assertEqual( cache.get_many(["ford4", "arthur4"], version=1), {"ford4": 37, "arthur4": 42}, ) self.assertEqual(cache.get_many(["ford4", "arthur4"], version=2), {}) self.assertEqual(caches["v2"].get_many(["ford4", "arthur4"]), {}) self.assertEqual( caches["v2"].get_many(["ford4", "arthur4"], version=1), {"ford4": 37, "arthur4": 42}, ) self.assertEqual(caches["v2"].get_many(["ford4", "arthur4"], version=2), {}) def test_incr_version(self): cache.set("answer", 42, version=2) self.assertIsNone(cache.get("answer")) self.assertIsNone(cache.get("answer", version=1)) self.assertEqual(cache.get("answer", version=2), 42) self.assertIsNone(cache.get("answer", version=3)) self.assertEqual(cache.incr_version("answer", version=2), 3) self.assertIsNone(cache.get("answer")) self.assertIsNone(cache.get("answer", version=1)) self.assertIsNone(cache.get("answer", version=2)) self.assertEqual(cache.get("answer", version=3), 42) caches["v2"].set("answer2", 42) self.assertEqual(caches["v2"].get("answer2"), 42) self.assertIsNone(caches["v2"].get("answer2", version=1)) self.assertEqual(caches["v2"].get("answer2", version=2), 42) self.assertIsNone(caches["v2"].get("answer2", version=3)) self.assertEqual(caches["v2"].incr_version("answer2"), 3) self.assertIsNone(caches["v2"].get("answer2")) self.assertIsNone(caches["v2"].get("answer2", version=1)) self.assertIsNone(caches["v2"].get("answer2", version=2)) self.assertEqual(caches["v2"].get("answer2", version=3), 42) with self.assertRaises(ValueError): cache.incr_version("does_not_exist") cache.set("null", None) self.assertEqual(cache.incr_version("null"), 2) def test_decr_version(self): cache.set("answer", 42, version=2) self.assertIsNone(cache.get("answer")) self.assertIsNone(cache.get("answer", version=1)) self.assertEqual(cache.get("answer", version=2), 42) self.assertEqual(cache.decr_version("answer", version=2), 1) self.assertEqual(cache.get("answer"), 42) self.assertEqual(cache.get("answer", version=1), 42) self.assertIsNone(cache.get("answer", version=2)) caches["v2"].set("answer2", 42) self.assertEqual(caches["v2"].get("answer2"), 42) self.assertIsNone(caches["v2"].get("answer2", version=1)) self.assertEqual(caches["v2"].get("answer2", version=2), 42) self.assertEqual(caches["v2"].decr_version("answer2"), 1) self.assertIsNone(caches["v2"].get("answer2")) self.assertEqual(caches["v2"].get("answer2", version=1), 42) self.assertIsNone(caches["v2"].get("answer2", version=2)) with self.assertRaises(ValueError): cache.decr_version("does_not_exist", version=2) cache.set("null", None, version=2) self.assertEqual(cache.decr_version("null", version=2), 1) def test_custom_key_func(self): # Two caches with different key functions aren't visible to each other cache.set("answer1", 42) self.assertEqual(cache.get("answer1"), 42) self.assertIsNone(caches["custom_key"].get("answer1")) self.assertIsNone(caches["custom_key2"].get("answer1")) caches["custom_key"].set("answer2", 42) self.assertIsNone(cache.get("answer2")) self.assertEqual(caches["custom_key"].get("answer2"), 42) self.assertEqual(caches["custom_key2"].get("answer2"), 42) @override_settings(CACHE_MIDDLEWARE_ALIAS=DEFAULT_CACHE_ALIAS) def test_cache_write_unpicklable_object(self): fetch_middleware = FetchFromCacheMiddleware(empty_response) request = self.factory.get("/cache/test") request._cache_update_cache = True get_cache_data = FetchFromCacheMiddleware(empty_response).process_request( request ) self.assertIsNone(get_cache_data) content = "Testing cookie serialization." def get_response(req): response = HttpResponse(content) response.set_cookie("foo", "bar") return response update_middleware = UpdateCacheMiddleware(get_response) response = update_middleware(request) get_cache_data = fetch_middleware.process_request(request) self.assertIsNotNone(get_cache_data) self.assertEqual(get_cache_data.content, content.encode()) self.assertEqual(get_cache_data.cookies, response.cookies) UpdateCacheMiddleware(lambda req: get_cache_data)(request) get_cache_data = fetch_middleware.process_request(request) self.assertIsNotNone(get_cache_data) self.assertEqual(get_cache_data.content, content.encode()) self.assertEqual(get_cache_data.cookies, response.cookies) def test_add_fail_on_pickleerror(self): # Shouldn't fail silently if trying to cache an unpicklable type. with self.assertRaises(pickle.PickleError): cache.add("unpicklable", Unpicklable()) def test_set_fail_on_pickleerror(self): with self.assertRaises(pickle.PickleError): cache.set("unpicklable", Unpicklable()) def test_get_or_set(self): self.assertIsNone(cache.get("projector")) self.assertEqual(cache.get_or_set("projector", 42), 42) self.assertEqual(cache.get("projector"), 42) self.assertIsNone(cache.get_or_set("null", None)) # Previous get_or_set() stores None in the cache. self.assertIsNone(cache.get("null", "default")) def test_get_or_set_callable(self): def my_callable(): return "value" self.assertEqual(cache.get_or_set("mykey", my_callable), "value") self.assertEqual(cache.get_or_set("mykey", my_callable()), "value") self.assertIsNone(cache.get_or_set("null", lambda: None)) # Previous get_or_set() stores None in the cache. self.assertIsNone(cache.get("null", "default")) def test_get_or_set_version(self): msg = "get_or_set() missing 1 required positional argument: 'default'" self.assertEqual(cache.get_or_set("brian", 1979, version=2), 1979) with self.assertRaisesMessage(TypeError, msg): cache.get_or_set("brian") with self.assertRaisesMessage(TypeError, msg): cache.get_or_set("brian", version=1) self.assertIsNone(cache.get("brian", version=1)) self.assertEqual(cache.get_or_set("brian", 42, version=1), 42) self.assertEqual(cache.get_or_set("brian", 1979, version=2), 1979) self.assertIsNone(cache.get("brian", version=3)) def test_get_or_set_racing(self): with mock.patch( "%s.%s" % (settings.CACHES["default"]["BACKEND"], "add") ) as cache_add: # Simulate cache.add() failing to add a value. In that case, the # default value should be returned. cache_add.return_value = False self.assertEqual(cache.get_or_set("key", "default"), "default") @override_settings( CACHES=caches_setting_for_tests( BACKEND="django.core.cache.backends.db.DatabaseCache", # Spaces are used in the table name to ensure quoting/escaping is working LOCATION="test cache table", ) ) class DBCacheTests(BaseCacheTests, TransactionTestCase): available_apps = ["cache"] def setUp(self): # The super calls needs to happen first for the settings override. super().setUp() self.create_table() def tearDown(self): # The super call needs to happen first because it uses the database. super().tearDown() self.drop_table() def create_table(self): management.call_command("createcachetable", verbosity=0) def drop_table(self): with connection.cursor() as cursor: table_name = connection.ops.quote_name("test cache table") cursor.execute("DROP TABLE %s" % table_name) def test_get_many_num_queries(self): cache.set_many({"a": 1, "b": 2}) cache.set("expired", "expired", 0.01) with self.assertNumQueries(1): self.assertEqual(cache.get_many(["a", "b"]), {"a": 1, "b": 2}) time.sleep(0.02) with self.assertNumQueries(2): self.assertEqual(cache.get_many(["a", "b", "expired"]), {"a": 1, "b": 2}) def test_delete_many_num_queries(self): cache.set_many({"a": 1, "b": 2, "c": 3}) with self.assertNumQueries(1): cache.delete_many(["a", "b", "c"]) def test_cull_queries(self): old_max_entries = cache._max_entries # Force _cull to delete on first cached record. cache._max_entries = -1 with CaptureQueriesContext(connection) as captured_queries: try: cache.set("force_cull", "value", 1000) finally: cache._max_entries = old_max_entries num_count_queries = sum("COUNT" in query["sql"] for query in captured_queries) self.assertEqual(num_count_queries, 1) # Column names are quoted. for query in captured_queries: sql = query["sql"] if "expires" in sql: self.assertIn(connection.ops.quote_name("expires"), sql) if "cache_key" in sql: self.assertIn(connection.ops.quote_name("cache_key"), sql) def test_delete_cursor_rowcount(self): """ The rowcount attribute should not be checked on a closed cursor. """ class MockedCursorWrapper(CursorWrapper): is_closed = False def close(self): self.cursor.close() self.is_closed = True @property def rowcount(self): if self.is_closed: raise Exception("Cursor is closed.") return self.cursor.rowcount cache.set_many({"a": 1, "b": 2}) with mock.patch("django.db.backends.utils.CursorWrapper", MockedCursorWrapper): self.assertIs(cache.delete("a"), True) def test_zero_cull(self): self._perform_cull_test("zero_cull", 50, 18) def test_second_call_doesnt_crash(self): out = io.StringIO() management.call_command("createcachetable", stdout=out) self.assertEqual( out.getvalue(), "Cache table 'test cache table' already exists.\n" * len(settings.CACHES), ) @override_settings( CACHES=caches_setting_for_tests( BACKEND="django.core.cache.backends.db.DatabaseCache", # Use another table name to avoid the 'table already exists' message. LOCATION="createcachetable_dry_run_mode", ) ) def test_createcachetable_dry_run_mode(self): out = io.StringIO() management.call_command("createcachetable", dry_run=True, stdout=out) output = out.getvalue() self.assertTrue(output.startswith("CREATE TABLE")) def test_createcachetable_with_table_argument(self): """ Delete and recreate cache table with legacy behavior (explicitly specifying the table name). """ self.drop_table() out = io.StringIO() management.call_command( "createcachetable", "test cache table", verbosity=2, stdout=out, ) self.assertEqual(out.getvalue(), "Cache table 'test cache table' created.\n") def test_has_key_query_columns_quoted(self): with CaptureQueriesContext(connection) as captured_queries: cache.has_key("key") self.assertEqual(len(captured_queries), 1) sql = captured_queries[0]["sql"] # Column names are quoted. self.assertIn(connection.ops.quote_name("expires"), sql) self.assertIn(connection.ops.quote_name("cache_key"), sql) @override_settings(USE_TZ=True) class DBCacheWithTimeZoneTests(DBCacheTests): pass class DBCacheRouter: """A router that puts the cache table on the 'other' database.""" def db_for_read(self, model, **hints): if model._meta.app_label == "django_cache": return "other" return None def db_for_write(self, model, **hints): if model._meta.app_label == "django_cache": return "other" return None def allow_migrate(self, db, app_label, **hints): if app_label == "django_cache": return db == "other" return None @override_settings( CACHES={ "default": { "BACKEND": "django.core.cache.backends.db.DatabaseCache", "LOCATION": "my_cache_table", }, }, ) class CreateCacheTableForDBCacheTests(TestCase): databases = {"default", "other"} @override_settings(DATABASE_ROUTERS=[DBCacheRouter()]) def test_createcachetable_observes_database_router(self): # cache table should not be created on 'default' with self.assertNumQueries(0, using="default"): management.call_command("createcachetable", database="default", verbosity=0) # cache table should be created on 'other' # Queries: # 1: check table doesn't already exist # 2: create savepoint (if transactional DDL is supported) # 3: create the table # 4: create the index # 5: release savepoint (if transactional DDL is supported) num = 5 if connections["other"].features.can_rollback_ddl else 3 with self.assertNumQueries(num, using="other"): management.call_command("createcachetable", database="other", verbosity=0) class PicklingSideEffect: def __init__(self, cache): self.cache = cache self.locked = False def __getstate__(self): self.locked = self.cache._lock.locked() return {} limit_locmem_entries = override_settings( CACHES=caches_setting_for_tests( BACKEND="django.core.cache.backends.locmem.LocMemCache", OPTIONS={"MAX_ENTRIES": 9}, ) ) @override_settings( CACHES=caches_setting_for_tests( BACKEND="django.core.cache.backends.locmem.LocMemCache", ) ) class LocMemCacheTests(BaseCacheTests, TestCase): def setUp(self): super().setUp() # LocMem requires a hack to make the other caches # share a data store with the 'normal' cache. caches["prefix"]._cache = cache._cache caches["prefix"]._expire_info = cache._expire_info caches["v2"]._cache = cache._cache caches["v2"]._expire_info = cache._expire_info caches["custom_key"]._cache = cache._cache caches["custom_key"]._expire_info = cache._expire_info caches["custom_key2"]._cache = cache._cache caches["custom_key2"]._expire_info = cache._expire_info @override_settings( CACHES={ "default": {"BACKEND": "django.core.cache.backends.locmem.LocMemCache"}, "other": { "BACKEND": "django.core.cache.backends.locmem.LocMemCache", "LOCATION": "other", }, } ) def test_multiple_caches(self): "Multiple locmem caches are isolated" cache.set("value", 42) self.assertEqual(caches["default"].get("value"), 42) self.assertIsNone(caches["other"].get("value")) def test_locking_on_pickle(self): """#20613/#18541 -- Ensures pickling is done outside of the lock.""" bad_obj = PicklingSideEffect(cache) cache.set("set", bad_obj) self.assertFalse(bad_obj.locked, "Cache was locked during pickling") self.assertIs(cache.add("add", bad_obj), True) self.assertFalse(bad_obj.locked, "Cache was locked during pickling") def test_incr_decr_timeout(self): """incr/decr does not modify expiry time (matches memcached behavior)""" key = "value" _key = cache.make_key(key) cache.set(key, 1, timeout=cache.default_timeout * 10) expire = cache._expire_info[_key] self.assertEqual(cache.incr(key), 2) self.assertEqual(expire, cache._expire_info[_key]) self.assertEqual(cache.decr(key), 1) self.assertEqual(expire, cache._expire_info[_key]) @limit_locmem_entries def test_lru_get(self): """get() moves cache keys.""" for key in range(9): cache.set(key, key, timeout=None) for key in range(6): self.assertEqual(cache.get(key), key) cache.set(9, 9, timeout=None) for key in range(6): self.assertEqual(cache.get(key), key) for key in range(6, 9): self.assertIsNone(cache.get(key)) self.assertEqual(cache.get(9), 9) @limit_locmem_entries def test_lru_set(self): """set() moves cache keys.""" for key in range(9): cache.set(key, key, timeout=None) for key in range(3, 9): cache.set(key, key, timeout=None) cache.set(9, 9, timeout=None) for key in range(3, 10): self.assertEqual(cache.get(key), key) for key in range(3): self.assertIsNone(cache.get(key)) @limit_locmem_entries def test_lru_incr(self): """incr() moves cache keys.""" for key in range(9): cache.set(key, key, timeout=None) for key in range(6): self.assertEqual(cache.incr(key), key + 1) cache.set(9, 9, timeout=None) for key in range(6): self.assertEqual(cache.get(key), key + 1) for key in range(6, 9): self.assertIsNone(cache.get(key)) self.assertEqual(cache.get(9), 9) # memcached and redis backends aren't guaranteed to be available. # To check the backends, the test settings file will need to contain at least # one cache backend setting that points at your cache server. configured_caches = {} for _cache_params in settings.CACHES.values(): configured_caches[_cache_params["BACKEND"]] = _cache_params PyLibMCCache_params = configured_caches.get( "django.core.cache.backends.memcached.PyLibMCCache" ) PyMemcacheCache_params = configured_caches.get( "django.core.cache.backends.memcached.PyMemcacheCache" ) # The memcached backends don't support cull-related options like `MAX_ENTRIES`. memcached_excluded_caches = {"cull", "zero_cull"} RedisCache_params = configured_caches.get("django.core.cache.backends.redis.RedisCache") # The redis backend does not support cull-related options like `MAX_ENTRIES`. redis_excluded_caches = {"cull", "zero_cull"} class BaseMemcachedTests(BaseCacheTests): # By default it's assumed that the client doesn't clean up connections # properly, in which case the backend must do so after each request. should_disconnect_on_close = True def test_location_multiple_servers(self): locations = [ ["server1.tld", "server2:11211"], "server1.tld;server2:11211", "server1.tld,server2:11211", ] for location in locations: with self.subTest(location=location): params = {"BACKEND": self.base_params["BACKEND"], "LOCATION": location} with self.settings(CACHES={"default": params}): self.assertEqual(cache._servers, ["server1.tld", "server2:11211"]) def _perform_invalid_key_test(self, key, expected_warning): """ While other backends merely warn, memcached should raise for an invalid key. """ msg = expected_warning.replace(key, cache.make_key(key)) tests = [ ("add", [key, 1]), ("get", [key]), ("set", [key, 1]), ("incr", [key]), ("decr", [key]), ("touch", [key]), ("delete", [key]), ("get_many", [[key, "b"]]), ("set_many", [{key: 1, "b": 2}]), ("delete_many", [[key, "b"]]), ] for operation, args in tests: with self.subTest(operation=operation): with self.assertRaises(InvalidCacheKey) as cm: getattr(cache, operation)(*args) self.assertEqual(str(cm.exception), msg) def test_invalid_with_version_key_length(self): # make_key() adds a version to the key and exceeds the limit. key = "a" * 248 expected_warning = ( "Cache key will cause errors if used with memcached: " "%r (longer than %s)" % (key, 250) ) self._perform_invalid_key_test(key, expected_warning) def test_default_never_expiring_timeout(self): # Regression test for #22845 with self.settings( CACHES=caches_setting_for_tests( base=self.base_params, exclude=memcached_excluded_caches, TIMEOUT=None ) ): cache.set("infinite_foo", "bar") self.assertEqual(cache.get("infinite_foo"), "bar") def test_default_far_future_timeout(self): # Regression test for #22845 with self.settings( CACHES=caches_setting_for_tests( base=self.base_params, exclude=memcached_excluded_caches, # 60*60*24*365, 1 year TIMEOUT=31536000, ) ): cache.set("future_foo", "bar") self.assertEqual(cache.get("future_foo"), "bar") def test_memcached_deletes_key_on_failed_set(self): # By default memcached allows objects up to 1MB. For the cache_db session # backend to always use the current session, memcached needs to delete # the old key if it fails to set. max_value_length = 2**20 cache.set("small_value", "a") self.assertEqual(cache.get("small_value"), "a") large_value = "a" * (max_value_length + 1) try: cache.set("small_value", large_value) except Exception: # Most clients (e.g. pymemcache or pylibmc) raise when the value is # too large. This test is primarily checking that the key was # deleted, so the return/exception behavior for the set() itself is # not important. pass # small_value should be deleted, or set if configured to accept larger values value = cache.get("small_value") self.assertTrue(value is None or value == large_value) def test_close(self): # For clients that don't manage their connections properly, the # connection is closed when the request is complete. signals.request_finished.disconnect(close_old_connections) try: with mock.patch.object( cache._class, "disconnect_all", autospec=True ) as mock_disconnect: signals.request_finished.send(self.__class__) self.assertIs(mock_disconnect.called, self.should_disconnect_on_close) finally: signals.request_finished.connect(close_old_connections) def test_set_many_returns_failing_keys(self): def fail_set_multi(mapping, *args, **kwargs): return mapping.keys() with mock.patch.object(cache._class, "set_multi", side_effect=fail_set_multi): failing_keys = cache.set_many({"key": "value"}) self.assertEqual(failing_keys, ["key"]) @unittest.skipUnless(PyLibMCCache_params, "PyLibMCCache backend not configured") @override_settings( CACHES=caches_setting_for_tests( base=PyLibMCCache_params, exclude=memcached_excluded_caches, ) ) class PyLibMCCacheTests(BaseMemcachedTests, TestCase): base_params = PyLibMCCache_params # libmemcached manages its own connections. should_disconnect_on_close = False @property def incr_decr_type_error(self): return cache._lib.ClientError @override_settings( CACHES=caches_setting_for_tests( base=PyLibMCCache_params, exclude=memcached_excluded_caches, OPTIONS={ "binary": True, "behaviors": {"tcp_nodelay": True}, }, ) ) def test_pylibmc_options(self): self.assertTrue(cache._cache.binary) self.assertEqual(cache._cache.behaviors["tcp_nodelay"], int(True)) def test_pylibmc_client_servers(self): backend = self.base_params["BACKEND"] tests = [ ("unix:/run/memcached/socket", "/run/memcached/socket"), ("/run/memcached/socket", "/run/memcached/socket"), ("localhost", "localhost"), ("localhost:11211", "localhost:11211"), ("[::1]", "[::1]"), ("[::1]:11211", "[::1]:11211"), ("127.0.0.1", "127.0.0.1"), ("127.0.0.1:11211", "127.0.0.1:11211"), ] for location, expected in tests: settings = {"default": {"BACKEND": backend, "LOCATION": location}} with self.subTest(location), self.settings(CACHES=settings): self.assertEqual(cache.client_servers, [expected]) @unittest.skipUnless(PyMemcacheCache_params, "PyMemcacheCache backend not configured") @override_settings( CACHES=caches_setting_for_tests( base=PyMemcacheCache_params, exclude=memcached_excluded_caches, ) ) class PyMemcacheCacheTests(BaseMemcachedTests, TestCase): base_params = PyMemcacheCache_params @property def incr_decr_type_error(self): return cache._lib.exceptions.MemcacheClientError def test_pymemcache_highest_pickle_version(self): self.assertEqual( cache._cache.default_kwargs["serde"]._serialize_func.keywords[ "pickle_version" ], pickle.HIGHEST_PROTOCOL, ) for cache_key in settings.CACHES: for client_key, client in caches[cache_key]._cache.clients.items(): with self.subTest(cache_key=cache_key, server=client_key): self.assertEqual( client.serde._serialize_func.keywords["pickle_version"], pickle.HIGHEST_PROTOCOL, ) @override_settings( CACHES=caches_setting_for_tests( base=PyMemcacheCache_params, exclude=memcached_excluded_caches, OPTIONS={"no_delay": True}, ) ) def test_pymemcache_options(self): self.assertIs(cache._cache.default_kwargs["no_delay"], True) @override_settings( CACHES=caches_setting_for_tests( BACKEND="django.core.cache.backends.filebased.FileBasedCache", ) ) class FileBasedCacheTests(BaseCacheTests, TestCase): """ Specific test cases for the file-based cache. """ def setUp(self): super().setUp() self.dirname = self.mkdtemp() # Caches location cannot be modified through override_settings / # modify_settings, hence settings are manipulated directly here and the # setting_changed signal is triggered manually. for cache_params in settings.CACHES.values(): cache_params["LOCATION"] = self.dirname setting_changed.send(self.__class__, setting="CACHES", enter=False) def tearDown(self): super().tearDown() # Call parent first, as cache.clear() may recreate cache base directory shutil.rmtree(self.dirname) def mkdtemp(self): return tempfile.mkdtemp() def test_ignores_non_cache_files(self): fname = os.path.join(self.dirname, "not-a-cache-file") with open(fname, "w"): os.utime(fname, None) cache.clear() self.assertTrue( os.path.exists(fname), "Expected cache.clear to ignore non cache files" ) os.remove(fname) def test_clear_does_not_remove_cache_dir(self): cache.clear() self.assertTrue( os.path.exists(self.dirname), "Expected cache.clear to keep the cache dir" ) def test_creates_cache_dir_if_nonexistent(self): os.rmdir(self.dirname) cache.set("foo", "bar") self.assertTrue(os.path.exists(self.dirname)) def test_get_ignores_enoent(self): cache.set("foo", "bar") os.unlink(cache._key_to_file("foo")) # Returns the default instead of erroring. self.assertEqual(cache.get("foo", "baz"), "baz") @skipIf( sys.platform == "win32", "Windows only partially supports umasks and chmod.", ) def test_cache_dir_permissions(self): os.rmdir(self.dirname) dir_path = Path(self.dirname) / "nested" / "filebasedcache" for cache_params in settings.CACHES.values(): cache_params["LOCATION"] = dir_path setting_changed.send(self.__class__, setting="CACHES", enter=False) cache.set("foo", "bar") self.assertIs(dir_path.exists(), True) tests = [ dir_path, dir_path.parent, dir_path.parent.parent, ] for directory in tests: with self.subTest(directory=directory): dir_mode = directory.stat().st_mode & 0o777 self.assertEqual(dir_mode, 0o700) def test_get_does_not_ignore_non_filenotfound_exceptions(self): with mock.patch("builtins.open", side_effect=OSError): with self.assertRaises(OSError): cache.get("foo") def test_empty_cache_file_considered_expired(self): cache_file = cache._key_to_file("foo") with open(cache_file, "wb") as fh: fh.write(b"") with open(cache_file, "rb") as fh: self.assertIs(cache._is_expired(fh), True) @unittest.skipUnless(RedisCache_params, "Redis backend not configured") @override_settings( CACHES=caches_setting_for_tests( base=RedisCache_params, exclude=redis_excluded_caches, ) ) class RedisCacheTests(BaseCacheTests, TestCase): def setUp(self): import redis super().setUp() self.lib = redis @property def incr_decr_type_error(self): return self.lib.ResponseError def test_cache_client_class(self): self.assertIs(cache._class, RedisCacheClient) self.assertIsInstance(cache._cache, RedisCacheClient) def test_get_backend_timeout_method(self): positive_timeout = 10 positive_backend_timeout = cache.get_backend_timeout(positive_timeout) self.assertEqual(positive_backend_timeout, positive_timeout) negative_timeout = -5 negative_backend_timeout = cache.get_backend_timeout(negative_timeout) self.assertEqual(negative_backend_timeout, 0) none_timeout = None none_backend_timeout = cache.get_backend_timeout(none_timeout) self.assertIsNone(none_backend_timeout) def test_get_connection_pool_index(self): pool_index = cache._cache._get_connection_pool_index(write=True) self.assertEqual(pool_index, 0) pool_index = cache._cache._get_connection_pool_index(write=False) if len(cache._cache._servers) == 1: self.assertEqual(pool_index, 0) else: self.assertGreater(pool_index, 0) self.assertLess(pool_index, len(cache._cache._servers)) def test_get_connection_pool(self): pool = cache._cache._get_connection_pool(write=True) self.assertIsInstance(pool, self.lib.ConnectionPool) pool = cache._cache._get_connection_pool(write=False) self.assertIsInstance(pool, self.lib.ConnectionPool) def test_get_client(self): self.assertIsInstance(cache._cache.get_client(), self.lib.Redis) def test_serializer_dumps(self): self.assertEqual(cache._cache._serializer.dumps(123), 123) self.assertIsInstance(cache._cache._serializer.dumps(True), bytes) self.assertIsInstance(cache._cache._serializer.dumps("abc"), bytes) class FileBasedCachePathLibTests(FileBasedCacheTests): def mkdtemp(self): tmp_dir = super().mkdtemp() return Path(tmp_dir) @override_settings( CACHES={ "default": { "BACKEND": "cache.liberal_backend.CacheClass", }, } ) class CustomCacheKeyValidationTests(SimpleTestCase): """ Tests for the ability to mixin a custom ``validate_key`` method to a custom cache backend that otherwise inherits from a builtin backend, and override the default key validation. Refs #6447. """ def test_custom_key_validation(self): # this key is both longer than 250 characters, and has spaces key = "some key with spaces" * 15 val = "a value" cache.set(key, val) self.assertEqual(cache.get(key), val) @override_settings( CACHES={ "default": { "BACKEND": "cache.closeable_cache.CacheClass", } } ) class CacheClosingTests(SimpleTestCase): def test_close(self): self.assertFalse(cache.closed) signals.request_finished.send(self.__class__) self.assertTrue(cache.closed) def test_close_only_initialized(self): with self.settings( CACHES={ "cache_1": { "BACKEND": "cache.closeable_cache.CacheClass", }, "cache_2": { "BACKEND": "cache.closeable_cache.CacheClass", }, } ): self.assertEqual(caches.all(initialized_only=True), []) signals.request_finished.send(self.__class__) self.assertEqual(caches.all(initialized_only=True), []) DEFAULT_MEMORY_CACHES_SETTINGS = { "default": { "BACKEND": "django.core.cache.backends.locmem.LocMemCache", "LOCATION": "unique-snowflake", } } NEVER_EXPIRING_CACHES_SETTINGS = copy.deepcopy(DEFAULT_MEMORY_CACHES_SETTINGS) NEVER_EXPIRING_CACHES_SETTINGS["default"]["TIMEOUT"] = None class DefaultNonExpiringCacheKeyTests(SimpleTestCase): """ Settings having Cache arguments with a TIMEOUT=None create Caches that will set non-expiring keys. """ def setUp(self): # The 5 minute (300 seconds) default expiration time for keys is # defined in the implementation of the initializer method of the # BaseCache type. self.DEFAULT_TIMEOUT = caches[DEFAULT_CACHE_ALIAS].default_timeout def tearDown(self): del self.DEFAULT_TIMEOUT def test_default_expiration_time_for_keys_is_5_minutes(self): """The default expiration time of a cache key is 5 minutes. This value is defined in django.core.cache.backends.base.BaseCache.__init__(). """ self.assertEqual(300, self.DEFAULT_TIMEOUT) def test_caches_with_unset_timeout_has_correct_default_timeout(self): """Caches that have the TIMEOUT parameter undefined in the default settings will use the default 5 minute timeout. """ cache = caches[DEFAULT_CACHE_ALIAS] self.assertEqual(self.DEFAULT_TIMEOUT, cache.default_timeout) @override_settings(CACHES=NEVER_EXPIRING_CACHES_SETTINGS) def test_caches_set_with_timeout_as_none_has_correct_default_timeout(self): """Memory caches that have the TIMEOUT parameter set to `None` in the default settings with have `None` as the default timeout. This means "no timeout". """ cache = caches[DEFAULT_CACHE_ALIAS] self.assertIsNone(cache.default_timeout) self.assertIsNone(cache.get_backend_timeout()) @override_settings(CACHES=DEFAULT_MEMORY_CACHES_SETTINGS) def test_caches_with_unset_timeout_set_expiring_key(self): """Memory caches that have the TIMEOUT parameter unset will set cache keys having the default 5 minute timeout. """ key = "my-key" value = "my-value" cache = caches[DEFAULT_CACHE_ALIAS] cache.set(key, value) cache_key = cache.make_key(key) self.assertIsNotNone(cache._expire_info[cache_key]) @override_settings(CACHES=NEVER_EXPIRING_CACHES_SETTINGS) def test_caches_set_with_timeout_as_none_set_non_expiring_key(self): """Memory caches that have the TIMEOUT parameter set to `None` will set a non expiring key by default. """ key = "another-key" value = "another-value" cache = caches[DEFAULT_CACHE_ALIAS] cache.set(key, value) cache_key = cache.make_key(key) self.assertIsNone(cache._expire_info[cache_key]) @override_settings( CACHE_MIDDLEWARE_KEY_PREFIX="settingsprefix", CACHE_MIDDLEWARE_SECONDS=1, CACHES={ "default": { "BACKEND": "django.core.cache.backends.locmem.LocMemCache", }, }, USE_I18N=False, ALLOWED_HOSTS=[".example.com"], ) class CacheUtils(SimpleTestCase): """TestCase for django.utils.cache functions.""" host = "www.example.com" path = "/cache/test/" factory = RequestFactory(HTTP_HOST=host) def tearDown(self): cache.clear() def _get_request_cache(self, method="GET", query_string=None, update_cache=None): request = self._get_request( self.host, self.path, method, query_string=query_string ) request._cache_update_cache = update_cache if update_cache else True return request def test_patch_vary_headers(self): headers = ( # Initial vary, new headers, resulting vary. (None, ("Accept-Encoding",), "Accept-Encoding"), ("Accept-Encoding", ("accept-encoding",), "Accept-Encoding"), ("Accept-Encoding", ("ACCEPT-ENCODING",), "Accept-Encoding"), ("Cookie", ("Accept-Encoding",), "Cookie, Accept-Encoding"), ( "Cookie, Accept-Encoding", ("Accept-Encoding",), "Cookie, Accept-Encoding", ), ( "Cookie, Accept-Encoding", ("Accept-Encoding", "cookie"), "Cookie, Accept-Encoding", ), (None, ("Accept-Encoding", "COOKIE"), "Accept-Encoding, COOKIE"), ( "Cookie, Accept-Encoding", ("Accept-Encoding", "cookie"), "Cookie, Accept-Encoding", ), ( "Cookie , Accept-Encoding", ("Accept-Encoding", "cookie"), "Cookie, Accept-Encoding", ), ("*", ("Accept-Language", "Cookie"), "*"), ("Accept-Language, Cookie", ("*",), "*"), ) for initial_vary, newheaders, resulting_vary in headers: with self.subTest(initial_vary=initial_vary, newheaders=newheaders): response = HttpResponse() if initial_vary is not None: response.headers["Vary"] = initial_vary patch_vary_headers(response, newheaders) self.assertEqual(response.headers["Vary"], resulting_vary) def test_get_cache_key(self): request = self.factory.get(self.path) response = HttpResponse() # Expect None if no headers have been set yet. self.assertIsNone(get_cache_key(request)) # Set headers to an empty list. learn_cache_key(request, response) self.assertEqual( get_cache_key(request), "views.decorators.cache.cache_page.settingsprefix.GET." "18a03f9c9649f7d684af5db3524f5c99.d41d8cd98f00b204e9800998ecf8427e", ) # A specified key_prefix is taken into account. key_prefix = "localprefix" learn_cache_key(request, response, key_prefix=key_prefix) self.assertEqual( get_cache_key(request, key_prefix=key_prefix), "views.decorators.cache.cache_page.localprefix.GET." "18a03f9c9649f7d684af5db3524f5c99.d41d8cd98f00b204e9800998ecf8427e", ) def test_get_cache_key_with_query(self): request = self.factory.get(self.path, {"test": 1}) response = HttpResponse() # Expect None if no headers have been set yet. self.assertIsNone(get_cache_key(request)) # Set headers to an empty list. learn_cache_key(request, response) # The querystring is taken into account. self.assertEqual( get_cache_key(request), "views.decorators.cache.cache_page.settingsprefix.GET." "beaf87a9a99ee81c673ea2d67ccbec2a.d41d8cd98f00b204e9800998ecf8427e", ) def test_cache_key_varies_by_url(self): """ get_cache_key keys differ by fully-qualified URL instead of path """ request1 = self.factory.get(self.path, HTTP_HOST="sub-1.example.com") learn_cache_key(request1, HttpResponse()) request2 = self.factory.get(self.path, HTTP_HOST="sub-2.example.com") learn_cache_key(request2, HttpResponse()) self.assertNotEqual(get_cache_key(request1), get_cache_key(request2)) def test_learn_cache_key(self): request = self.factory.head(self.path) response = HttpResponse() response.headers["Vary"] = "Pony" # Make sure that the Vary header is added to the key hash learn_cache_key(request, response) self.assertEqual( get_cache_key(request), "views.decorators.cache.cache_page.settingsprefix.GET." "18a03f9c9649f7d684af5db3524f5c99.d41d8cd98f00b204e9800998ecf8427e", ) def test_patch_cache_control(self): tests = ( # Initial Cache-Control, kwargs to patch_cache_control, expected # Cache-Control parts. (None, {"private": True}, {"private"}), ("", {"private": True}, {"private"}), # no-cache. ("", {"no_cache": "Set-Cookie"}, {"no-cache=Set-Cookie"}), ("", {"no-cache": "Set-Cookie"}, {"no-cache=Set-Cookie"}), ("no-cache=Set-Cookie", {"no_cache": True}, {"no-cache"}), ("no-cache=Set-Cookie,no-cache=Link", {"no_cache": True}, {"no-cache"}), ( "no-cache=Set-Cookie", {"no_cache": "Link"}, {"no-cache=Set-Cookie", "no-cache=Link"}, ), ( "no-cache=Set-Cookie,no-cache=Link", {"no_cache": "Custom"}, {"no-cache=Set-Cookie", "no-cache=Link", "no-cache=Custom"}, ), # Test whether private/public attributes are mutually exclusive ("private", {"private": True}, {"private"}), ("private", {"public": True}, {"public"}), ("public", {"public": True}, {"public"}), ("public", {"private": True}, {"private"}), ( "must-revalidate,max-age=60,private", {"public": True}, {"must-revalidate", "max-age=60", "public"}, ), ( "must-revalidate,max-age=60,public", {"private": True}, {"must-revalidate", "max-age=60", "private"}, ), ( "must-revalidate,max-age=60", {"public": True}, {"must-revalidate", "max-age=60", "public"}, ), ) cc_delim_re = re.compile(r"\s*,\s*") for initial_cc, newheaders, expected_cc in tests: with self.subTest(initial_cc=initial_cc, newheaders=newheaders): response = HttpResponse() if initial_cc is not None: response.headers["Cache-Control"] = initial_cc patch_cache_control(response, **newheaders) parts = set(cc_delim_re.split(response.headers["Cache-Control"])) self.assertEqual(parts, expected_cc) @override_settings( CACHES={ "default": { "BACKEND": "django.core.cache.backends.locmem.LocMemCache", "KEY_PREFIX": "cacheprefix", }, }, ) class PrefixedCacheUtils(CacheUtils): pass @override_settings( CACHE_MIDDLEWARE_SECONDS=60, CACHE_MIDDLEWARE_KEY_PREFIX="test", CACHES={ "default": { "BACKEND": "django.core.cache.backends.locmem.LocMemCache", }, }, ) class CacheHEADTest(SimpleTestCase): path = "/cache/test/" factory = RequestFactory() def tearDown(self): cache.clear() def _set_cache(self, request, msg): return UpdateCacheMiddleware(lambda req: HttpResponse(msg))(request) def test_head_caches_correctly(self): test_content = "test content" request = self.factory.head(self.path) request._cache_update_cache = True self._set_cache(request, test_content) request = self.factory.head(self.path) request._cache_update_cache = True get_cache_data = FetchFromCacheMiddleware(empty_response).process_request( request ) self.assertIsNotNone(get_cache_data) self.assertEqual(test_content.encode(), get_cache_data.content) def test_head_with_cached_get(self): test_content = "test content" request = self.factory.get(self.path) request._cache_update_cache = True self._set_cache(request, test_content) request = self.factory.head(self.path) get_cache_data = FetchFromCacheMiddleware(empty_response).process_request( request ) self.assertIsNotNone(get_cache_data) self.assertEqual(test_content.encode(), get_cache_data.content) @override_settings( CACHE_MIDDLEWARE_KEY_PREFIX="settingsprefix", CACHES={ "default": { "BACKEND": "django.core.cache.backends.locmem.LocMemCache", }, }, LANGUAGES=[ ("en", "English"), ("es", "Spanish"), ], ) class CacheI18nTest(SimpleTestCase): path = "/cache/test/" factory = RequestFactory() def tearDown(self): cache.clear() @override_settings(USE_I18N=True, USE_TZ=False) def test_cache_key_i18n_translation(self): request = self.factory.get(self.path) lang = translation.get_language() response = HttpResponse() key = learn_cache_key(request, response) self.assertIn( lang, key, "Cache keys should include the language name when translation is active", ) key2 = get_cache_key(request) self.assertEqual(key, key2) def check_accept_language_vary(self, accept_language, vary, reference_key): request = self.factory.get(self.path) request.META["HTTP_ACCEPT_LANGUAGE"] = accept_language request.META["HTTP_ACCEPT_ENCODING"] = "gzip;q=1.0, identity; q=0.5, *;q=0" response = HttpResponse() response.headers["Vary"] = vary key = learn_cache_key(request, response) key2 = get_cache_key(request) self.assertEqual(key, reference_key) self.assertEqual(key2, reference_key) @override_settings(USE_I18N=True, USE_TZ=False) def test_cache_key_i18n_translation_accept_language(self): lang = translation.get_language() self.assertEqual(lang, "en") request = self.factory.get(self.path) request.META["HTTP_ACCEPT_ENCODING"] = "gzip;q=1.0, identity; q=0.5, *;q=0" response = HttpResponse() response.headers["Vary"] = "accept-encoding" key = learn_cache_key(request, response) self.assertIn( lang, key, "Cache keys should include the language name when translation is active", ) self.check_accept_language_vary( "en-us", "cookie, accept-language, accept-encoding", key ) self.check_accept_language_vary( "en-US", "cookie, accept-encoding, accept-language", key ) self.check_accept_language_vary( "en-US,en;q=0.8", "accept-encoding, accept-language, cookie", key ) self.check_accept_language_vary( "en-US,en;q=0.8,ko;q=0.6", "accept-language, cookie, accept-encoding", key ) self.check_accept_language_vary( "ko-kr,ko;q=0.8,en-us;q=0.5,en;q=0.3 ", "accept-encoding, cookie, accept-language", key, ) self.check_accept_language_vary( "ko-KR,ko;q=0.8,en-US;q=0.6,en;q=0.4", "accept-language, accept-encoding, cookie", key, ) self.check_accept_language_vary( "ko;q=1.0,en;q=0.5", "cookie, accept-language, accept-encoding", key ) self.check_accept_language_vary( "ko, en", "cookie, accept-encoding, accept-language", key ) self.check_accept_language_vary( "ko-KR, en-US", "accept-encoding, accept-language, cookie", key ) @override_settings(USE_I18N=False, USE_TZ=True) def test_cache_key_i18n_timezone(self): request = self.factory.get(self.path) tz = timezone.get_current_timezone_name() response = HttpResponse() key = learn_cache_key(request, response) self.assertIn( tz, key, "Cache keys should include the time zone name when time zones are active", ) key2 = get_cache_key(request) self.assertEqual(key, key2) @override_settings(USE_I18N=False) def test_cache_key_no_i18n(self): request = self.factory.get(self.path) lang = translation.get_language() tz = timezone.get_current_timezone_name() response = HttpResponse() key = learn_cache_key(request, response) self.assertNotIn( lang, key, "Cache keys shouldn't include the language name when i18n isn't active", ) self.assertNotIn( tz, key, "Cache keys shouldn't include the time zone name when i18n isn't active", ) @override_settings( CACHE_MIDDLEWARE_KEY_PREFIX="test", CACHE_MIDDLEWARE_SECONDS=60, USE_I18N=True, ) def test_middleware(self): def set_cache(request, lang, msg): def get_response(req): return HttpResponse(msg) translation.activate(lang) return UpdateCacheMiddleware(get_response)(request) # cache with non empty request.GET request = self.factory.get(self.path, {"foo": "bar", "other": "true"}) request._cache_update_cache = True get_cache_data = FetchFromCacheMiddleware(empty_response).process_request( request ) # first access, cache must return None self.assertIsNone(get_cache_data) content = "Check for cache with QUERY_STRING" def get_response(req): return HttpResponse(content) UpdateCacheMiddleware(get_response)(request) get_cache_data = FetchFromCacheMiddleware(empty_response).process_request( request ) # cache must return content self.assertIsNotNone(get_cache_data) self.assertEqual(get_cache_data.content, content.encode()) # different QUERY_STRING, cache must be empty request = self.factory.get(self.path, {"foo": "bar", "somethingelse": "true"}) request._cache_update_cache = True get_cache_data = FetchFromCacheMiddleware(empty_response).process_request( request ) self.assertIsNone(get_cache_data) # i18n tests en_message = "Hello world!" es_message = "Hola mundo!" request = self.factory.get(self.path) request._cache_update_cache = True set_cache(request, "en", en_message) get_cache_data = FetchFromCacheMiddleware(empty_response).process_request( request ) # The cache can be recovered self.assertIsNotNone(get_cache_data) self.assertEqual(get_cache_data.content, en_message.encode()) # change the session language and set content request = self.factory.get(self.path) request._cache_update_cache = True set_cache(request, "es", es_message) # change again the language translation.activate("en") # retrieve the content from cache get_cache_data = FetchFromCacheMiddleware(empty_response).process_request( request ) self.assertEqual(get_cache_data.content, en_message.encode()) # change again the language translation.activate("es") get_cache_data = FetchFromCacheMiddleware(empty_response).process_request( request ) self.assertEqual(get_cache_data.content, es_message.encode()) # reset the language translation.deactivate() @override_settings( CACHE_MIDDLEWARE_KEY_PREFIX="test", CACHE_MIDDLEWARE_SECONDS=60, ) def test_middleware_doesnt_cache_streaming_response(self): request = self.factory.get(self.path) get_cache_data = FetchFromCacheMiddleware(empty_response).process_request( request ) self.assertIsNone(get_cache_data) def get_stream_response(req): return StreamingHttpResponse(["Check for cache with streaming content."]) UpdateCacheMiddleware(get_stream_response)(request) get_cache_data = FetchFromCacheMiddleware(empty_response).process_request( request ) self.assertIsNone(get_cache_data) @override_settings( CACHES={ "default": { "BACKEND": "django.core.cache.backends.locmem.LocMemCache", "KEY_PREFIX": "cacheprefix", }, }, ) class PrefixedCacheI18nTest(CacheI18nTest): pass def hello_world_view(request, value): return HttpResponse("Hello World %s" % value) def csrf_view(request): return HttpResponse(csrf(request)["csrf_token"]) @override_settings( CACHE_MIDDLEWARE_ALIAS="other", CACHE_MIDDLEWARE_KEY_PREFIX="middlewareprefix", CACHE_MIDDLEWARE_SECONDS=30, CACHES={ "default": { "BACKEND": "django.core.cache.backends.locmem.LocMemCache", }, "other": { "BACKEND": "django.core.cache.backends.locmem.LocMemCache", "LOCATION": "other", "TIMEOUT": "1", }, }, ) class CacheMiddlewareTest(SimpleTestCase): factory = RequestFactory() def setUp(self): self.default_cache = caches["default"] self.other_cache = caches["other"] def tearDown(self): self.default_cache.clear() self.other_cache.clear() super().tearDown() def test_constructor(self): """ The constructor is correctly distinguishing between usage of CacheMiddleware as Middleware vs. usage of CacheMiddleware as view decorator and setting attributes appropriately. """ # If only one argument is passed in construction, it's being used as # middleware. middleware = CacheMiddleware(empty_response) # Now test object attributes against values defined in setUp above self.assertEqual(middleware.cache_timeout, 30) self.assertEqual(middleware.key_prefix, "middlewareprefix") self.assertEqual(middleware.cache_alias, "other") self.assertEqual(middleware.cache, self.other_cache) # If more arguments are being passed in construction, it's being used # as a decorator. First, test with "defaults": as_view_decorator = CacheMiddleware( empty_response, cache_alias=None, key_prefix=None ) self.assertEqual( as_view_decorator.cache_timeout, 30 ) # Timeout value for 'default' cache, i.e. 30 self.assertEqual(as_view_decorator.key_prefix, "") # Value of DEFAULT_CACHE_ALIAS from django.core.cache self.assertEqual(as_view_decorator.cache_alias, "default") self.assertEqual(as_view_decorator.cache, self.default_cache) # Next, test with custom values: as_view_decorator_with_custom = CacheMiddleware( hello_world_view, cache_timeout=60, cache_alias="other", key_prefix="foo" ) self.assertEqual(as_view_decorator_with_custom.cache_timeout, 60) self.assertEqual(as_view_decorator_with_custom.key_prefix, "foo") self.assertEqual(as_view_decorator_with_custom.cache_alias, "other") self.assertEqual(as_view_decorator_with_custom.cache, self.other_cache) def test_update_cache_middleware_constructor(self): middleware = UpdateCacheMiddleware(empty_response) self.assertEqual(middleware.cache_timeout, 30) self.assertIsNone(middleware.page_timeout) self.assertEqual(middleware.key_prefix, "middlewareprefix") self.assertEqual(middleware.cache_alias, "other") self.assertEqual(middleware.cache, self.other_cache) def test_fetch_cache_middleware_constructor(self): middleware = FetchFromCacheMiddleware(empty_response) self.assertEqual(middleware.key_prefix, "middlewareprefix") self.assertEqual(middleware.cache_alias, "other") self.assertEqual(middleware.cache, self.other_cache) def test_middleware(self): middleware = CacheMiddleware(hello_world_view) prefix_middleware = CacheMiddleware(hello_world_view, key_prefix="prefix1") timeout_middleware = CacheMiddleware(hello_world_view, cache_timeout=1) request = self.factory.get("/view/") # Put the request through the request middleware result = middleware.process_request(request) self.assertIsNone(result) response = hello_world_view(request, "1") # Now put the response through the response middleware response = middleware.process_response(request, response) # Repeating the request should result in a cache hit result = middleware.process_request(request) self.assertIsNotNone(result) self.assertEqual(result.content, b"Hello World 1") # The same request through a different middleware won't hit result = prefix_middleware.process_request(request) self.assertIsNone(result) # The same request with a timeout _will_ hit result = timeout_middleware.process_request(request) self.assertIsNotNone(result) self.assertEqual(result.content, b"Hello World 1") def test_view_decorator(self): # decorate the same view with different cache decorators default_view = cache_page(3)(hello_world_view) default_with_prefix_view = cache_page(3, key_prefix="prefix1")(hello_world_view) explicit_default_view = cache_page(3, cache="default")(hello_world_view) explicit_default_with_prefix_view = cache_page( 3, cache="default", key_prefix="prefix1" )(hello_world_view) other_view = cache_page(1, cache="other")(hello_world_view) other_with_prefix_view = cache_page(1, cache="other", key_prefix="prefix2")( hello_world_view ) request = self.factory.get("/view/") # Request the view once response = default_view(request, "1") self.assertEqual(response.content, b"Hello World 1") # Request again -- hit the cache response = default_view(request, "2") self.assertEqual(response.content, b"Hello World 1") # Requesting the same view with the explicit cache should yield the same result response = explicit_default_view(request, "3") self.assertEqual(response.content, b"Hello World 1") # Requesting with a prefix will hit a different cache key response = explicit_default_with_prefix_view(request, "4") self.assertEqual(response.content, b"Hello World 4") # Hitting the same view again gives a cache hit response = explicit_default_with_prefix_view(request, "5") self.assertEqual(response.content, b"Hello World 4") # And going back to the implicit cache will hit the same cache response = default_with_prefix_view(request, "6") self.assertEqual(response.content, b"Hello World 4") # Requesting from an alternate cache won't hit cache response = other_view(request, "7") self.assertEqual(response.content, b"Hello World 7") # But a repeated hit will hit cache response = other_view(request, "8") self.assertEqual(response.content, b"Hello World 7") # And prefixing the alternate cache yields yet another cache entry response = other_with_prefix_view(request, "9") self.assertEqual(response.content, b"Hello World 9") # But if we wait a couple of seconds... time.sleep(2) # ... the default cache will still hit caches["default"] response = default_view(request, "11") self.assertEqual(response.content, b"Hello World 1") # ... the default cache with a prefix will still hit response = default_with_prefix_view(request, "12") self.assertEqual(response.content, b"Hello World 4") # ... the explicit default cache will still hit response = explicit_default_view(request, "13") self.assertEqual(response.content, b"Hello World 1") # ... the explicit default cache with a prefix will still hit response = explicit_default_with_prefix_view(request, "14") self.assertEqual(response.content, b"Hello World 4") # .. but a rapidly expiring cache won't hit response = other_view(request, "15") self.assertEqual(response.content, b"Hello World 15") # .. even if it has a prefix response = other_with_prefix_view(request, "16") self.assertEqual(response.content, b"Hello World 16") def test_cache_page_timeout(self): # Page timeout takes precedence over the "max-age" section of the # "Cache-Control". tests = [ (1, 3), # max_age < page_timeout. (3, 1), # max_age > page_timeout. ] for max_age, page_timeout in tests: with self.subTest(max_age=max_age, page_timeout=page_timeout): view = cache_page(timeout=page_timeout)( cache_control(max_age=max_age)(hello_world_view) ) request = self.factory.get("/view/") response = view(request, "1") self.assertEqual(response.content, b"Hello World 1") time.sleep(1) response = view(request, "2") self.assertEqual( response.content, b"Hello World 1" if page_timeout > max_age else b"Hello World 2", ) cache.clear() def test_cached_control_private_not_cached(self): """Responses with 'Cache-Control: private' are not cached.""" view_with_private_cache = cache_page(3)( cache_control(private=True)(hello_world_view) ) request = self.factory.get("/view/") response = view_with_private_cache(request, "1") self.assertEqual(response.content, b"Hello World 1") response = view_with_private_cache(request, "2") self.assertEqual(response.content, b"Hello World 2") def test_sensitive_cookie_not_cached(self): """ Django must prevent caching of responses that set a user-specific (and maybe security sensitive) cookie in response to a cookie-less request. """ request = self.factory.get("/view/") csrf_middleware = CsrfViewMiddleware(csrf_view) csrf_middleware.process_view(request, csrf_view, (), {}) cache_middleware = CacheMiddleware(csrf_middleware) self.assertIsNone(cache_middleware.process_request(request)) cache_middleware(request) # Inserting a CSRF cookie in a cookie-less request prevented caching. self.assertIsNone(cache_middleware.process_request(request)) def test_304_response_has_http_caching_headers_but_not_cached(self): original_view = mock.Mock(return_value=HttpResponseNotModified()) view = cache_page(2)(original_view) request = self.factory.get("/view/") # The view shouldn't be cached on the second call. view(request).close() response = view(request) response.close() self.assertEqual(original_view.call_count, 2) self.assertIsInstance(response, HttpResponseNotModified) self.assertIn("Cache-Control", response) self.assertIn("Expires", response) def test_per_thread(self): """The cache instance is different for each thread.""" thread_caches = [] middleware = CacheMiddleware(empty_response) def runner(): thread_caches.append(middleware.cache) for _ in range(2): thread = threading.Thread(target=runner) thread.start() thread.join() self.assertIsNot(thread_caches[0], thread_caches[1]) @override_settings( CACHE_MIDDLEWARE_KEY_PREFIX="settingsprefix", CACHE_MIDDLEWARE_SECONDS=1, CACHES={ "default": { "BACKEND": "django.core.cache.backends.locmem.LocMemCache", }, }, USE_I18N=False, ) class TestWithTemplateResponse(SimpleTestCase): """ Tests various headers w/ TemplateResponse. Most are probably redundant since they manipulate the same object anyway but the ETag header is 'special' because it relies on the content being complete (which is not necessarily always the case with a TemplateResponse) """ path = "/cache/test/" factory = RequestFactory() def tearDown(self): cache.clear() def test_patch_vary_headers(self): headers = ( # Initial vary, new headers, resulting vary. (None, ("Accept-Encoding",), "Accept-Encoding"), ("Accept-Encoding", ("accept-encoding",), "Accept-Encoding"), ("Accept-Encoding", ("ACCEPT-ENCODING",), "Accept-Encoding"), ("Cookie", ("Accept-Encoding",), "Cookie, Accept-Encoding"), ( "Cookie, Accept-Encoding", ("Accept-Encoding",), "Cookie, Accept-Encoding", ), ( "Cookie, Accept-Encoding", ("Accept-Encoding", "cookie"), "Cookie, Accept-Encoding", ), (None, ("Accept-Encoding", "COOKIE"), "Accept-Encoding, COOKIE"), ( "Cookie, Accept-Encoding", ("Accept-Encoding", "cookie"), "Cookie, Accept-Encoding", ), ( "Cookie , Accept-Encoding", ("Accept-Encoding", "cookie"), "Cookie, Accept-Encoding", ), ) for initial_vary, newheaders, resulting_vary in headers: with self.subTest(initial_vary=initial_vary, newheaders=newheaders): template = engines["django"].from_string("This is a test") response = TemplateResponse(HttpRequest(), template) if initial_vary is not None: response.headers["Vary"] = initial_vary patch_vary_headers(response, newheaders) self.assertEqual(response.headers["Vary"], resulting_vary) def test_get_cache_key(self): request = self.factory.get(self.path) template = engines["django"].from_string("This is a test") response = TemplateResponse(HttpRequest(), template) key_prefix = "localprefix" # Expect None if no headers have been set yet. self.assertIsNone(get_cache_key(request)) # Set headers to an empty list. learn_cache_key(request, response) self.assertEqual( get_cache_key(request), "views.decorators.cache.cache_page.settingsprefix.GET." "58a0a05c8a5620f813686ff969c26853.d41d8cd98f00b204e9800998ecf8427e", ) # A specified key_prefix is taken into account. learn_cache_key(request, response, key_prefix=key_prefix) self.assertEqual( get_cache_key(request, key_prefix=key_prefix), "views.decorators.cache.cache_page.localprefix.GET." "58a0a05c8a5620f813686ff969c26853.d41d8cd98f00b204e9800998ecf8427e", ) def test_get_cache_key_with_query(self): request = self.factory.get(self.path, {"test": 1}) template = engines["django"].from_string("This is a test") response = TemplateResponse(HttpRequest(), template) # Expect None if no headers have been set yet. self.assertIsNone(get_cache_key(request)) # Set headers to an empty list. learn_cache_key(request, response) # The querystring is taken into account. self.assertEqual( get_cache_key(request), "views.decorators.cache.cache_page.settingsprefix.GET." "0f1c2d56633c943073c4569d9a9502fe.d41d8cd98f00b204e9800998ecf8427e", ) class TestMakeTemplateFragmentKey(SimpleTestCase): def test_without_vary_on(self): key = make_template_fragment_key("a.fragment") self.assertEqual( key, "template.cache.a.fragment.d41d8cd98f00b204e9800998ecf8427e" ) def test_with_one_vary_on(self): key = make_template_fragment_key("foo", ["abc"]) self.assertEqual(key, "template.cache.foo.493e283d571a73056196f1a68efd0f66") def test_with_many_vary_on(self): key = make_template_fragment_key("bar", ["abc", "def"]) self.assertEqual(key, "template.cache.bar.17c1a507a0cb58384f4c639067a93520") def test_proper_escaping(self): key = make_template_fragment_key("spam", ["abc:def%"]) self.assertEqual(key, "template.cache.spam.06c8ae8e8c430b69fb0a6443504153dc") def test_with_ints_vary_on(self): key = make_template_fragment_key("foo", [1, 2, 3, 4, 5]) self.assertEqual(key, "template.cache.foo.7ae8fd2e0d25d651c683bdeebdb29461") def test_with_unicode_vary_on(self): key = make_template_fragment_key("foo", ["42º", "😀"]) self.assertEqual(key, "template.cache.foo.7ced1c94e543668590ba39b3c08b0237") def test_long_vary_on(self): key = make_template_fragment_key("foo", ["x" * 10000]) self.assertEqual(key, "template.cache.foo.3670b349b5124aa56bdb50678b02b23a") class CacheHandlerTest(SimpleTestCase): def test_same_instance(self): """ Attempting to retrieve the same alias should yield the same instance. """ cache1 = caches["default"] cache2 = caches["default"] self.assertIs(cache1, cache2) def test_per_thread(self): """ Requesting the same alias from separate threads should yield separate instances. """ c = [] def runner(): c.append(caches["default"]) for x in range(2): t = threading.Thread(target=runner) t.start() t.join() self.assertIsNot(c[0], c[1]) def test_nonexistent_alias(self): msg = "The connection 'nonexistent' doesn't exist." with self.assertRaisesMessage(InvalidCacheBackendError, msg): caches["nonexistent"] def test_nonexistent_backend(self): test_caches = CacheHandler( { "invalid_backend": { "BACKEND": "django.nonexistent.NonexistentBackend", }, } ) msg = ( "Could not find backend 'django.nonexistent.NonexistentBackend': " "No module named 'django.nonexistent'" ) with self.assertRaisesMessage(InvalidCacheBackendError, msg): test_caches["invalid_backend"] def test_all(self): test_caches = CacheHandler( { "cache_1": { "BACKEND": "django.core.cache.backends.dummy.DummyCache", }, "cache_2": { "BACKEND": "django.core.cache.backends.dummy.DummyCache", }, } ) self.assertEqual(test_caches.all(initialized_only=True), []) cache_1 = test_caches["cache_1"] self.assertEqual(test_caches.all(initialized_only=True), [cache_1]) self.assertEqual(len(test_caches.all()), 2) # .all() initializes all caches. self.assertEqual(len(test_caches.all(initialized_only=True)), 2) self.assertEqual(test_caches.all(), test_caches.all(initialized_only=True))
77a2db84e06f878beae132453fbdd686038197e28f53e4a64b5eac0c19a2c7f4
from django.db import models from django.utils import timezone def expensive_calculation(): expensive_calculation.num_runs += 1 return timezone.now() class Poll(models.Model): question = models.CharField(max_length=200) answer = models.CharField(max_length=200) pub_date = models.DateTimeField("date published", default=expensive_calculation)
f7c5c5a481c54db9556a0a9428e08de49d9c1313aeebcb98a3f2a5d4548c6478
import asyncio from django.core.cache import CacheKeyWarning, cache from django.test import SimpleTestCase, override_settings from .tests import KEY_ERRORS_WITH_MEMCACHED_MSG @override_settings( CACHES={ "default": { "BACKEND": "django.core.cache.backends.dummy.DummyCache", } } ) class AsyncDummyCacheTests(SimpleTestCase): async def test_simple(self): """Dummy cache backend ignores cache set calls.""" await cache.aset("key", "value") self.assertIsNone(await cache.aget("key")) async def test_aadd(self): """Add doesn't do anything in dummy cache backend.""" self.assertIs(await cache.aadd("key", "value"), True) self.assertIs(await cache.aadd("key", "new_value"), True) self.assertIsNone(await cache.aget("key")) async def test_non_existent(self): """Nonexistent keys aren't found in the dummy cache backend.""" self.assertIsNone(await cache.aget("does_not_exist")) self.assertEqual(await cache.aget("does_not_exist", "default"), "default") async def test_aget_many(self): """aget_many() returns nothing for the dummy cache backend.""" await cache.aset_many({"a": "a", "b": "b", "c": "c", "d": "d"}) self.assertEqual(await cache.aget_many(["a", "c", "d"]), {}) self.assertEqual(await cache.aget_many(["a", "b", "e"]), {}) async def test_aget_many_invalid_key(self): msg = KEY_ERRORS_WITH_MEMCACHED_MSG % ":1:key with spaces" with self.assertWarnsMessage(CacheKeyWarning, msg): await cache.aget_many(["key with spaces"]) async def test_adelete(self): """ Cache deletion is transparently ignored on the dummy cache backend. """ await cache.aset_many({"key1": "spam", "key2": "eggs"}) self.assertIsNone(await cache.aget("key1")) self.assertIs(await cache.adelete("key1"), False) self.assertIsNone(await cache.aget("key1")) self.assertIsNone(await cache.aget("key2")) async def test_ahas_key(self): """ahas_key() doesn't ever return True for the dummy cache backend.""" await cache.aset("hello1", "goodbye1") self.assertIs(await cache.ahas_key("hello1"), False) self.assertIs(await cache.ahas_key("goodbye1"), False) async def test_aincr(self): """Dummy cache values can't be incremented.""" await cache.aset("answer", 42) with self.assertRaises(ValueError): await cache.aincr("answer") with self.assertRaises(ValueError): await cache.aincr("does_not_exist") with self.assertRaises(ValueError): await cache.aincr("does_not_exist", -1) async def test_adecr(self): """Dummy cache values can't be decremented.""" await cache.aset("answer", 42) with self.assertRaises(ValueError): await cache.adecr("answer") with self.assertRaises(ValueError): await cache.adecr("does_not_exist") with self.assertRaises(ValueError): await cache.adecr("does_not_exist", -1) async def test_atouch(self): self.assertIs(await cache.atouch("key"), False) async def test_data_types(self): """All data types are ignored equally by the dummy cache.""" def f(): return 42 class C: def m(n): return 24 data = { "string": "this is a string", "int": 42, "list": [1, 2, 3, 4], "tuple": (1, 2, 3, 4), "dict": {"A": 1, "B": 2}, "function": f, "class": C, } await cache.aset("data", data) self.assertIsNone(await cache.aget("data")) async def test_expiration(self): """Expiration has no effect on the dummy cache.""" await cache.aset("expire1", "very quickly", 1) await cache.aset("expire2", "very quickly", 1) await cache.aset("expire3", "very quickly", 1) await asyncio.sleep(2) self.assertIsNone(await cache.aget("expire1")) self.assertIs(await cache.aadd("expire2", "new_value"), True) self.assertIsNone(await cache.aget("expire2")) self.assertIs(await cache.ahas_key("expire3"), False) async def test_unicode(self): """Unicode values are ignored by the dummy cache.""" tests = { "ascii": "ascii_value", "unicode_ascii": "Iñtërnâtiônàlizætiøn1", "Iñtërnâtiônàlizætiøn": "Iñtërnâtiônàlizætiøn2", "ascii2": {"x": 1}, } for key, value in tests.items(): with self.subTest(key=key): await cache.aset(key, value) self.assertIsNone(await cache.aget(key)) async def test_aset_many(self): """aset_many() does nothing for the dummy cache backend.""" self.assertEqual(await cache.aset_many({"a": 1, "b": 2}), []) self.assertEqual( await cache.aset_many({"a": 1, "b": 2}, timeout=2, version="1"), [], ) async def test_aset_many_invalid_key(self): msg = KEY_ERRORS_WITH_MEMCACHED_MSG % ":1:key with spaces" with self.assertWarnsMessage(CacheKeyWarning, msg): await cache.aset_many({"key with spaces": "foo"}) async def test_adelete_many(self): """adelete_many() does nothing for the dummy cache backend.""" await cache.adelete_many(["a", "b"]) async def test_adelete_many_invalid_key(self): msg = KEY_ERRORS_WITH_MEMCACHED_MSG % ":1:key with spaces" with self.assertWarnsMessage(CacheKeyWarning, msg): await cache.adelete_many({"key with spaces": "foo"}) async def test_aclear(self): """aclear() does nothing for the dummy cache backend.""" await cache.aclear() async def test_aclose(self): """aclose() does nothing for the dummy cache backend.""" await cache.aclose() async def test_aincr_version(self): """Dummy cache versions can't be incremented.""" await cache.aset("answer", 42) with self.assertRaises(ValueError): await cache.aincr_version("answer") with self.assertRaises(ValueError): await cache.aincr_version("answer", version=2) with self.assertRaises(ValueError): await cache.aincr_version("does_not_exist") async def test_adecr_version(self): """Dummy cache versions can't be decremented.""" await cache.aset("answer", 42) with self.assertRaises(ValueError): await cache.adecr_version("answer") with self.assertRaises(ValueError): await cache.adecr_version("answer", version=2) with self.assertRaises(ValueError): await cache.adecr_version("does_not_exist") async def test_aget_or_set(self): self.assertEqual(await cache.aget_or_set("key", "default"), "default") self.assertIsNone(await cache.aget_or_set("key", None)) async def test_aget_or_set_callable(self): def my_callable(): return "default" self.assertEqual(await cache.aget_or_set("key", my_callable), "default") self.assertEqual(await cache.aget_or_set("key", my_callable()), "default")
d59f82ef1f9dc0c0b211e7bc24273a30186ca1098d8fc3af83a890447c9c4f15
import os import sys import unittest from importlib import import_module from zipimport import zipimporter from django.test import SimpleTestCase, modify_settings from django.test.utils import extend_sys_path from django.utils.module_loading import ( autodiscover_modules, import_string, module_has_submodule, ) from django.utils.version import PY310 class DefaultLoader(unittest.TestCase): def test_loader(self): "Normal module existence can be tested" test_module = import_module("utils_tests.test_module") test_no_submodule = import_module("utils_tests.test_no_submodule") # An importable child self.assertTrue(module_has_submodule(test_module, "good_module")) mod = import_module("utils_tests.test_module.good_module") self.assertEqual(mod.content, "Good Module") # A child that exists, but will generate an import error if loaded self.assertTrue(module_has_submodule(test_module, "bad_module")) with self.assertRaises(ImportError): import_module("utils_tests.test_module.bad_module") # A child that doesn't exist self.assertFalse(module_has_submodule(test_module, "no_such_module")) with self.assertRaises(ImportError): import_module("utils_tests.test_module.no_such_module") # A child that doesn't exist, but is the name of a package on the path self.assertFalse(module_has_submodule(test_module, "django")) with self.assertRaises(ImportError): import_module("utils_tests.test_module.django") # Don't be confused by caching of import misses import types # NOQA: causes attempted import of utils_tests.types self.assertFalse(module_has_submodule(sys.modules["utils_tests"], "types")) # A module which doesn't have a __path__ (so no submodules) self.assertFalse(module_has_submodule(test_no_submodule, "anything")) with self.assertRaises(ImportError): import_module("utils_tests.test_no_submodule.anything") def test_has_sumbodule_with_dotted_path(self): """Nested module existence can be tested.""" test_module = import_module("utils_tests.test_module") # A grandchild that exists. self.assertIs( module_has_submodule(test_module, "child_module.grandchild_module"), True ) # A grandchild that doesn't exist. self.assertIs( module_has_submodule(test_module, "child_module.no_such_module"), False ) # A grandchild whose parent doesn't exist. self.assertIs( module_has_submodule(test_module, "no_such_module.grandchild_module"), False ) # A grandchild whose parent is not a package. self.assertIs( module_has_submodule(test_module, "good_module.no_such_module"), False ) class EggLoader(unittest.TestCase): def setUp(self): self.egg_dir = "%s/eggs" % os.path.dirname(__file__) def tearDown(self): sys.path_importer_cache.clear() sys.modules.pop("egg_module.sub1.sub2.bad_module", None) sys.modules.pop("egg_module.sub1.sub2.good_module", None) sys.modules.pop("egg_module.sub1.sub2", None) sys.modules.pop("egg_module.sub1", None) sys.modules.pop("egg_module.bad_module", None) sys.modules.pop("egg_module.good_module", None) sys.modules.pop("egg_module", None) def test_shallow_loader(self): "Module existence can be tested inside eggs" egg_name = "%s/test_egg.egg" % self.egg_dir with extend_sys_path(egg_name): egg_module = import_module("egg_module") # An importable child self.assertTrue(module_has_submodule(egg_module, "good_module")) mod = import_module("egg_module.good_module") self.assertEqual(mod.content, "Good Module") # A child that exists, but will generate an import error if loaded self.assertTrue(module_has_submodule(egg_module, "bad_module")) with self.assertRaises(ImportError): import_module("egg_module.bad_module") # A child that doesn't exist self.assertFalse(module_has_submodule(egg_module, "no_such_module")) with self.assertRaises(ImportError): import_module("egg_module.no_such_module") def test_deep_loader(self): "Modules deep inside an egg can still be tested for existence" egg_name = "%s/test_egg.egg" % self.egg_dir with extend_sys_path(egg_name): egg_module = import_module("egg_module.sub1.sub2") # An importable child self.assertTrue(module_has_submodule(egg_module, "good_module")) mod = import_module("egg_module.sub1.sub2.good_module") self.assertEqual(mod.content, "Deep Good Module") # A child that exists, but will generate an import error if loaded self.assertTrue(module_has_submodule(egg_module, "bad_module")) with self.assertRaises(ImportError): import_module("egg_module.sub1.sub2.bad_module") # A child that doesn't exist self.assertFalse(module_has_submodule(egg_module, "no_such_module")) with self.assertRaises(ImportError): import_module("egg_module.sub1.sub2.no_such_module") class ModuleImportTests(SimpleTestCase): def test_import_string(self): cls = import_string("django.utils.module_loading.import_string") self.assertEqual(cls, import_string) # Test exceptions raised with self.assertRaises(ImportError): import_string("no_dots_in_path") msg = 'Module "utils_tests" does not define a "unexistent" attribute' with self.assertRaisesMessage(ImportError, msg): import_string("utils_tests.unexistent") @modify_settings(INSTALLED_APPS={"append": "utils_tests.test_module"}) class AutodiscoverModulesTestCase(SimpleTestCase): def tearDown(self): sys.path_importer_cache.clear() sys.modules.pop("utils_tests.test_module.another_bad_module", None) sys.modules.pop("utils_tests.test_module.another_good_module", None) sys.modules.pop("utils_tests.test_module.bad_module", None) sys.modules.pop("utils_tests.test_module.good_module", None) sys.modules.pop("utils_tests.test_module", None) def test_autodiscover_modules_found(self): autodiscover_modules("good_module") def test_autodiscover_modules_not_found(self): autodiscover_modules("missing_module") def test_autodiscover_modules_found_but_bad_module(self): with self.assertRaisesMessage( ImportError, "No module named 'a_package_name_that_does_not_exist'" ): autodiscover_modules("bad_module") def test_autodiscover_modules_several_one_bad_module(self): with self.assertRaisesMessage( ImportError, "No module named 'a_package_name_that_does_not_exist'" ): autodiscover_modules("good_module", "bad_module") def test_autodiscover_modules_several_found(self): autodiscover_modules("good_module", "another_good_module") def test_autodiscover_modules_several_found_with_registry(self): from .test_module import site autodiscover_modules("good_module", "another_good_module", register_to=site) self.assertEqual(site._registry, {"lorem": "ipsum"}) def test_validate_registry_keeps_intact(self): from .test_module import site with self.assertRaisesMessage(Exception, "Some random exception."): autodiscover_modules("another_bad_module", register_to=site) self.assertEqual(site._registry, {}) def test_validate_registry_resets_after_erroneous_module(self): from .test_module import site with self.assertRaisesMessage(Exception, "Some random exception."): autodiscover_modules( "another_good_module", "another_bad_module", register_to=site ) self.assertEqual(site._registry, {"lorem": "ipsum"}) def test_validate_registry_resets_after_missing_module(self): from .test_module import site autodiscover_modules( "does_not_exist", "another_good_module", "does_not_exist2", register_to=site ) self.assertEqual(site._registry, {"lorem": "ipsum"}) if PY310: class TestFinder: def __init__(self, *args, **kwargs): self.importer = zipimporter(*args, **kwargs) def find_spec(self, path, target=None): return self.importer.find_spec(path, target) else: class TestFinder: def __init__(self, *args, **kwargs): self.importer = zipimporter(*args, **kwargs) def find_module(self, path): importer = self.importer.find_module(path) if importer is None: return return TestLoader(importer) class TestLoader: def __init__(self, importer): self.importer = importer def load_module(self, name): mod = self.importer.load_module(name) mod.__loader__ = self return mod class CustomLoader(EggLoader): """The Custom Loader test is exactly the same as the EggLoader, but it uses a custom defined Loader class. Although the EggLoader combines both functions into one class, this isn't required. """ def setUp(self): super().setUp() sys.path_hooks.insert(0, TestFinder) sys.path_importer_cache.clear() def tearDown(self): super().tearDown() sys.path_hooks.pop(0)
841ff3cbb69766ec990a8d035dfdbcb9727b8c6e0d2d9461cb57b634b7d44d24
import unittest from django.utils import inspect class Person: def no_arguments(self): return None def one_argument(self, something): return something def just_args(self, *args): return args def all_kinds(self, name, address="home", age=25, *args, **kwargs): return kwargs @classmethod def cls_all_kinds(cls, name, address="home", age=25, *args, **kwargs): return kwargs class TestInspectMethods(unittest.TestCase): def test_get_callable_parameters(self): self.assertIs( inspect._get_callable_parameters(Person.no_arguments), inspect._get_callable_parameters(Person.no_arguments), ) self.assertIs( inspect._get_callable_parameters(Person().no_arguments), inspect._get_callable_parameters(Person().no_arguments), ) def test_get_func_full_args_no_arguments(self): self.assertEqual(inspect.get_func_full_args(Person.no_arguments), []) self.assertEqual(inspect.get_func_full_args(Person().no_arguments), []) def test_get_func_full_args_one_argument(self): self.assertEqual( inspect.get_func_full_args(Person.one_argument), [("something",)] ) self.assertEqual( inspect.get_func_full_args(Person().one_argument), [("something",)], ) def test_get_func_full_args_all_arguments_method(self): arguments = [ ("name",), ("address", "home"), ("age", 25), ("*args",), ("**kwargs",), ] self.assertEqual(inspect.get_func_full_args(Person.all_kinds), arguments) self.assertEqual(inspect.get_func_full_args(Person().all_kinds), arguments) def test_get_func_full_args_all_arguments_classmethod(self): arguments = [ ("name",), ("address", "home"), ("age", 25), ("*args",), ("**kwargs",), ] self.assertEqual(inspect.get_func_full_args(Person.cls_all_kinds), arguments) self.assertEqual(inspect.get_func_full_args(Person().cls_all_kinds), arguments) def test_func_accepts_var_args_has_var_args(self): self.assertIs(inspect.func_accepts_var_args(Person.just_args), True) self.assertIs(inspect.func_accepts_var_args(Person().just_args), True) def test_func_accepts_var_args_no_var_args(self): self.assertIs(inspect.func_accepts_var_args(Person.one_argument), False) self.assertIs(inspect.func_accepts_var_args(Person().one_argument), False) def test_method_has_no_args(self): self.assertIs(inspect.method_has_no_args(Person.no_arguments), True) self.assertIs(inspect.method_has_no_args(Person().no_arguments), True) self.assertIs(inspect.method_has_no_args(Person.one_argument), False) self.assertIs(inspect.method_has_no_args(Person().one_argument), False) def test_func_supports_parameter(self): self.assertIs( inspect.func_supports_parameter(Person.all_kinds, "address"), True ) self.assertIs( inspect.func_supports_parameter(Person().all_kinds, "address"), True, ) self.assertIs(inspect.func_supports_parameter(Person.all_kinds, "zone"), False) self.assertIs( inspect.func_supports_parameter(Person().all_kinds, "zone"), False, ) def test_func_accepts_kwargs(self): self.assertIs(inspect.func_accepts_kwargs(Person.just_args), False) self.assertIs(inspect.func_accepts_kwargs(Person().just_args), False) self.assertIs(inspect.func_accepts_kwargs(Person.all_kinds), True) self.assertIs(inspect.func_accepts_kwargs(Person().just_args), False)
af8d2c11a9f7c2f1d7f8791f7c0cab4ff8d208377d283f07123a382e0d3ac3ed
import unittest from django.utils.termcolors import ( DARK_PALETTE, DEFAULT_PALETTE, LIGHT_PALETTE, NOCOLOR_PALETTE, PALETTES, colorize, parse_color_setting, ) class TermColorTests(unittest.TestCase): def test_empty_string(self): self.assertEqual(parse_color_setting(""), PALETTES[DEFAULT_PALETTE]) def test_simple_palette(self): self.assertEqual(parse_color_setting("light"), PALETTES[LIGHT_PALETTE]) self.assertEqual(parse_color_setting("dark"), PALETTES[DARK_PALETTE]) self.assertIsNone(parse_color_setting("nocolor")) def test_fg(self): self.assertEqual( parse_color_setting("error=green"), dict(PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green"}), ) def test_fg_bg(self): self.assertEqual( parse_color_setting("error=green/blue"), dict(PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green", "bg": "blue"}), ) def test_fg_opts(self): self.assertEqual( parse_color_setting("error=green,blink"), dict(PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green", "opts": ("blink",)}), ) self.assertEqual( parse_color_setting("error=green,bold,blink"), dict( PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green", "opts": ("blink", "bold")}, ), ) def test_fg_bg_opts(self): self.assertEqual( parse_color_setting("error=green/blue,blink"), dict( PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green", "bg": "blue", "opts": ("blink",)}, ), ) self.assertEqual( parse_color_setting("error=green/blue,bold,blink"), dict( PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green", "bg": "blue", "opts": ("blink", "bold")}, ), ) def test_override_palette(self): self.assertEqual( parse_color_setting("light;error=green"), dict(PALETTES[LIGHT_PALETTE], ERROR={"fg": "green"}), ) def test_override_nocolor(self): self.assertEqual( parse_color_setting("nocolor;error=green"), dict(PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green"}), ) def test_reverse_override(self): self.assertEqual( parse_color_setting("error=green;light"), PALETTES[LIGHT_PALETTE] ) def test_multiple_roles(self): self.assertEqual( parse_color_setting("error=green;sql_field=blue"), dict( PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green"}, SQL_FIELD={"fg": "blue"}, ), ) def test_override_with_multiple_roles(self): self.assertEqual( parse_color_setting("light;error=green;sql_field=blue"), dict( PALETTES[LIGHT_PALETTE], ERROR={"fg": "green"}, SQL_FIELD={"fg": "blue"} ), ) def test_empty_definition(self): self.assertIsNone(parse_color_setting(";")) self.assertEqual(parse_color_setting("light;"), PALETTES[LIGHT_PALETTE]) self.assertIsNone(parse_color_setting(";;;")) def test_empty_options(self): self.assertEqual( parse_color_setting("error=green,"), dict(PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green"}), ) self.assertEqual( parse_color_setting("error=green,,,"), dict(PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green"}), ) self.assertEqual( parse_color_setting("error=green,,blink,,"), dict(PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green", "opts": ("blink",)}), ) def test_bad_palette(self): self.assertIsNone(parse_color_setting("unknown")) def test_bad_role(self): self.assertIsNone(parse_color_setting("unknown=")) self.assertIsNone(parse_color_setting("unknown=green")) self.assertEqual( parse_color_setting("unknown=green;sql_field=blue"), dict(PALETTES[NOCOLOR_PALETTE], SQL_FIELD={"fg": "blue"}), ) def test_bad_color(self): self.assertIsNone(parse_color_setting("error=")) self.assertEqual( parse_color_setting("error=;sql_field=blue"), dict(PALETTES[NOCOLOR_PALETTE], SQL_FIELD={"fg": "blue"}), ) self.assertIsNone(parse_color_setting("error=unknown")) self.assertEqual( parse_color_setting("error=unknown;sql_field=blue"), dict(PALETTES[NOCOLOR_PALETTE], SQL_FIELD={"fg": "blue"}), ) self.assertEqual( parse_color_setting("error=green/unknown"), dict(PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green"}), ) self.assertEqual( parse_color_setting("error=green/blue/something"), dict(PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green", "bg": "blue"}), ) self.assertEqual( parse_color_setting("error=green/blue/something,blink"), dict( PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green", "bg": "blue", "opts": ("blink",)}, ), ) def test_bad_option(self): self.assertEqual( parse_color_setting("error=green,unknown"), dict(PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green"}), ) self.assertEqual( parse_color_setting("error=green,unknown,blink"), dict(PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green", "opts": ("blink",)}), ) def test_role_case(self): self.assertEqual( parse_color_setting("ERROR=green"), dict(PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green"}), ) self.assertEqual( parse_color_setting("eRrOr=green"), dict(PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green"}), ) def test_color_case(self): self.assertEqual( parse_color_setting("error=GREEN"), dict(PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green"}), ) self.assertEqual( parse_color_setting("error=GREEN/BLUE"), dict(PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green", "bg": "blue"}), ) self.assertEqual( parse_color_setting("error=gReEn"), dict(PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green"}), ) self.assertEqual( parse_color_setting("error=gReEn/bLuE"), dict(PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green", "bg": "blue"}), ) def test_opts_case(self): self.assertEqual( parse_color_setting("error=green,BLINK"), dict(PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green", "opts": ("blink",)}), ) self.assertEqual( parse_color_setting("error=green,bLiNk"), dict(PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green", "opts": ("blink",)}), ) def test_colorize_empty_text(self): self.assertEqual(colorize(text=None), "\x1b[m\x1b[0m") self.assertEqual(colorize(text=""), "\x1b[m\x1b[0m") self.assertEqual(colorize(text=None, opts=("noreset",)), "\x1b[m") self.assertEqual(colorize(text="", opts=("noreset",)), "\x1b[m") def test_colorize_reset(self): self.assertEqual(colorize(text="", opts=("reset",)), "\x1b[0m") def test_colorize_fg_bg(self): self.assertEqual(colorize(text="Test", fg="red"), "\x1b[31mTest\x1b[0m") self.assertEqual(colorize(text="Test", bg="red"), "\x1b[41mTest\x1b[0m") # Ignored kwarg. self.assertEqual(colorize(text="Test", other="red"), "\x1b[mTest\x1b[0m") def test_colorize_opts(self): self.assertEqual( colorize(text="Test", opts=("bold", "underscore")), "\x1b[1;4mTest\x1b[0m", ) self.assertEqual( colorize(text="Test", opts=("blink",)), "\x1b[5mTest\x1b[0m", ) # Ignored opts. self.assertEqual( colorize(text="Test", opts=("not_an_option",)), "\x1b[mTest\x1b[0m", )
93feabe29d9aa16cce2c420675decc9fdc276d8dd85e32fed246850ce4cc2648
from datetime import date, datetime, time, tzinfo from django.test import SimpleTestCase, override_settings from django.test.utils import TZ_SUPPORT, requires_tz_support from django.utils import dateformat, translation from django.utils.dateformat import format from django.utils.timezone import ( get_default_timezone, get_fixed_timezone, make_aware, utc, ) @override_settings(TIME_ZONE="Europe/Copenhagen") class DateFormatTests(SimpleTestCase): def setUp(self): self._orig_lang = translation.get_language() translation.activate("en-us") def tearDown(self): translation.activate(self._orig_lang) def test_date(self): d = date(2009, 5, 16) self.assertEqual(date.fromtimestamp(int(format(d, "U"))), d) def test_naive_datetime(self): dt = datetime(2009, 5, 16, 5, 30, 30) self.assertEqual(datetime.fromtimestamp(int(format(dt, "U"))), dt) def test_naive_ambiguous_datetime(self): # dt is ambiguous in Europe/Copenhagen. pytz raises an exception for # the ambiguity, which results in an empty string. dt = datetime(2015, 10, 25, 2, 30, 0) # Try all formatters that involve self.timezone. self.assertEqual(format(dt, "I"), "") self.assertEqual(format(dt, "O"), "") self.assertEqual(format(dt, "T"), "") self.assertEqual(format(dt, "Z"), "") @requires_tz_support def test_datetime_with_local_tzinfo(self): ltz = get_default_timezone() dt = make_aware(datetime(2009, 5, 16, 5, 30, 30), ltz) self.assertEqual(datetime.fromtimestamp(int(format(dt, "U")), ltz), dt) self.assertEqual( datetime.fromtimestamp(int(format(dt, "U"))), dt.replace(tzinfo=None) ) @requires_tz_support def test_datetime_with_tzinfo(self): tz = get_fixed_timezone(-510) ltz = get_default_timezone() dt = make_aware(datetime(2009, 5, 16, 5, 30, 30), ltz) self.assertEqual(datetime.fromtimestamp(int(format(dt, "U")), tz), dt) self.assertEqual(datetime.fromtimestamp(int(format(dt, "U")), ltz), dt) # astimezone() is safe here because the target timezone doesn't have DST self.assertEqual( datetime.fromtimestamp(int(format(dt, "U"))), dt.astimezone(ltz).replace(tzinfo=None), ) self.assertEqual( datetime.fromtimestamp(int(format(dt, "U")), tz).timetuple(), dt.astimezone(tz).timetuple(), ) self.assertEqual( datetime.fromtimestamp(int(format(dt, "U")), ltz).timetuple(), dt.astimezone(ltz).timetuple(), ) def test_epoch(self): udt = datetime(1970, 1, 1, tzinfo=utc) self.assertEqual(format(udt, "U"), "0") def test_empty_format(self): my_birthday = datetime(1979, 7, 8, 22, 00) self.assertEqual(dateformat.format(my_birthday, ""), "") def test_am_pm(self): morning = time(7, 00) evening = time(19, 00) self.assertEqual(dateformat.format(morning, "a"), "a.m.") self.assertEqual(dateformat.format(evening, "a"), "p.m.") self.assertEqual(dateformat.format(morning, "A"), "AM") self.assertEqual(dateformat.format(evening, "A"), "PM") def test_microsecond(self): # Regression test for #18951 dt = datetime(2009, 5, 16, microsecond=123) self.assertEqual(dateformat.format(dt, "u"), "000123") def test_date_formats(self): # Specifiers 'I', 'r', and 'U' are covered in test_timezones(). my_birthday = datetime(1979, 7, 8, 22, 00) for specifier, expected in [ ("b", "jul"), ("d", "08"), ("D", "Sun"), ("E", "July"), ("F", "July"), ("j", "8"), ("l", "Sunday"), ("L", "False"), ("m", "07"), ("M", "Jul"), ("n", "7"), ("N", "July"), ("o", "1979"), ("S", "th"), ("t", "31"), ("w", "0"), ("W", "27"), ("y", "79"), ("Y", "1979"), ("z", "189"), ]: with self.subTest(specifier=specifier): self.assertEqual(dateformat.format(my_birthday, specifier), expected) def test_date_formats_c_format(self): timestamp = datetime(2008, 5, 19, 11, 45, 23, 123456) self.assertEqual( dateformat.format(timestamp, "c"), "2008-05-19T11:45:23.123456" ) def test_time_formats(self): # Specifiers 'I', 'r', and 'U' are covered in test_timezones(). my_birthday = datetime(1979, 7, 8, 22, 00) for specifier, expected in [ ("a", "p.m."), ("A", "PM"), ("f", "10"), ("g", "10"), ("G", "22"), ("h", "10"), ("H", "22"), ("i", "00"), ("P", "10 p.m."), ("s", "00"), ("u", "000000"), ]: with self.subTest(specifier=specifier): self.assertEqual(dateformat.format(my_birthday, specifier), expected) def test_dateformat(self): my_birthday = datetime(1979, 7, 8, 22, 00) self.assertEqual(dateformat.format(my_birthday, r"Y z \C\E\T"), "1979 189 CET") self.assertEqual(dateformat.format(my_birthday, r"jS \o\f F"), "8th of July") def test_futuredates(self): the_future = datetime(2100, 10, 25, 0, 00) self.assertEqual(dateformat.format(the_future, r"Y"), "2100") def test_day_of_year_leap(self): self.assertEqual(dateformat.format(datetime(2000, 12, 31), "z"), "366") def test_timezones(self): my_birthday = datetime(1979, 7, 8, 22, 00) summertime = datetime(2005, 10, 30, 1, 00) wintertime = datetime(2005, 10, 30, 4, 00) noon = time(12, 0, 0) # 3h30m to the west of UTC tz = get_fixed_timezone(-210) aware_dt = datetime(2009, 5, 16, 5, 30, 30, tzinfo=tz) if TZ_SUPPORT: for specifier, expected in [ ("e", ""), ("O", "+0100"), ("r", "Sun, 08 Jul 1979 22:00:00 +0100"), ("T", "CET"), ("U", "300315600"), ("Z", "3600"), ]: with self.subTest(specifier=specifier): self.assertEqual( dateformat.format(my_birthday, specifier), expected ) self.assertEqual(dateformat.format(aware_dt, "e"), "-0330") self.assertEqual( dateformat.format(aware_dt, "r"), "Sat, 16 May 2009 05:30:30 -0330", ) self.assertEqual(dateformat.format(summertime, "I"), "1") self.assertEqual(dateformat.format(summertime, "O"), "+0200") self.assertEqual(dateformat.format(wintertime, "I"), "0") self.assertEqual(dateformat.format(wintertime, "O"), "+0100") for specifier in ["e", "O", "T", "Z"]: with self.subTest(specifier=specifier): self.assertEqual(dateformat.time_format(noon, specifier), "") # Ticket #16924 -- We don't need timezone support to test this self.assertEqual(dateformat.format(aware_dt, "O"), "-0330") def test_invalid_time_format_specifiers(self): my_birthday = date(1984, 8, 7) for specifier in ["a", "A", "f", "g", "G", "h", "H", "i", "P", "r", "s", "u"]: with self.subTest(specifier=specifier): msg = ( "The format for date objects may not contain time-related " f"format specifiers (found {specifier!r})." ) with self.assertRaisesMessage(TypeError, msg): dateformat.format(my_birthday, specifier) @requires_tz_support def test_e_format_with_named_time_zone(self): dt = datetime(1970, 1, 1, tzinfo=utc) self.assertEqual(dateformat.format(dt, "e"), "UTC") @requires_tz_support def test_e_format_with_time_zone_with_unimplemented_tzname(self): class NoNameTZ(tzinfo): """Time zone without .tzname() defined.""" def utcoffset(self, dt): return None dt = datetime(1970, 1, 1, tzinfo=NoNameTZ()) self.assertEqual(dateformat.format(dt, "e"), "") def test_P_format(self): for expected, t in [ ("midnight", time(0)), ("noon", time(12)), ("4 a.m.", time(4)), ("8:30 a.m.", time(8, 30)), ("4 p.m.", time(16)), ("8:30 p.m.", time(20, 30)), ]: with self.subTest(time=t): self.assertEqual(dateformat.time_format(t, "P"), expected) def test_r_format_with_non_en_locale(self): # Changing the locale doesn't change the "r" format. dt = datetime(1979, 7, 8, 22, 00) with translation.override("fr"): self.assertEqual( dateformat.format(dt, "r"), "Sun, 08 Jul 1979 22:00:00 +0100", ) def test_S_format(self): for expected, days in [ ("st", [1, 21, 31]), ("nd", [2, 22]), ("rd", [3, 23]), ("th", (n for n in range(4, 31) if n not in [21, 22, 23])), ]: for day in days: dt = date(1970, 1, day) with self.subTest(day=day): self.assertEqual(dateformat.format(dt, "S"), expected) def test_y_format_year_before_1000(self): tests = [ (476, "76"), (42, "42"), (4, "04"), ] for year, expected_date in tests: with self.subTest(year=year): self.assertEqual( dateformat.format(datetime(year, 9, 8, 5, 0), "y"), expected_date, ) def test_Y_format_year_before_1000(self): self.assertEqual(dateformat.format(datetime(1, 1, 1), "Y"), "0001") self.assertEqual(dateformat.format(datetime(999, 1, 1), "Y"), "0999") def test_twelve_hour_format(self): tests = [ (0, "12", "12"), (1, "1", "01"), (11, "11", "11"), (12, "12", "12"), (13, "1", "01"), (23, "11", "11"), ] for hour, g_expected, h_expected in tests: dt = datetime(2000, 1, 1, hour) with self.subTest(hour=hour): self.assertEqual(dateformat.format(dt, "g"), g_expected) self.assertEqual(dateformat.format(dt, "h"), h_expected)
be3912b4b06fe96fb00223e85f5ae4cb40600664cf9cc9ab012c17862f194b40
import datetime import unittest from unittest import mock try: import pytz except ImportError: pytz = None try: import zoneinfo except ImportError: from backports import zoneinfo from django.test import SimpleTestCase, ignore_warnings, override_settings from django.utils import timezone from django.utils.deprecation import RemovedInDjango50Warning PARIS_ZI = zoneinfo.ZoneInfo("Europe/Paris") EAT = timezone.get_fixed_timezone(180) # Africa/Nairobi ICT = timezone.get_fixed_timezone(420) # Asia/Bangkok UTC = datetime.timezone.utc HAS_PYTZ = pytz is not None if not HAS_PYTZ: CET = None PARIS_IMPLS = (PARIS_ZI,) needs_pytz = unittest.skip("Test requires pytz") else: CET = pytz.timezone("Europe/Paris") PARIS_IMPLS = (PARIS_ZI, CET) def needs_pytz(f): return f class TimezoneTests(SimpleTestCase): def setUp(self): # RemovedInDjango50Warning timezone.get_default_timezone.cache_clear() def tearDown(self): # RemovedInDjango50Warning timezone.get_default_timezone.cache_clear() def test_default_timezone_is_zoneinfo(self): self.assertIsInstance(timezone.get_default_timezone(), zoneinfo.ZoneInfo) @needs_pytz @ignore_warnings(category=RemovedInDjango50Warning) @override_settings(USE_DEPRECATED_PYTZ=True) def test_setting_allows_fallback_to_pytz(self): self.assertIsInstance(timezone.get_default_timezone(), pytz.BaseTzInfo) def test_now(self): with override_settings(USE_TZ=True): self.assertTrue(timezone.is_aware(timezone.now())) with override_settings(USE_TZ=False): self.assertTrue(timezone.is_naive(timezone.now())) def test_localdate(self): naive = datetime.datetime(2015, 1, 1, 0, 0, 1) with self.assertRaisesMessage( ValueError, "localtime() cannot be applied to a naive datetime" ): timezone.localdate(naive) with self.assertRaisesMessage( ValueError, "localtime() cannot be applied to a naive datetime" ): timezone.localdate(naive, timezone=EAT) aware = datetime.datetime(2015, 1, 1, 0, 0, 1, tzinfo=ICT) self.assertEqual( timezone.localdate(aware, timezone=EAT), datetime.date(2014, 12, 31) ) with timezone.override(EAT): self.assertEqual(timezone.localdate(aware), datetime.date(2014, 12, 31)) with mock.patch("django.utils.timezone.now", return_value=aware): self.assertEqual( timezone.localdate(timezone=EAT), datetime.date(2014, 12, 31) ) with timezone.override(EAT): self.assertEqual(timezone.localdate(), datetime.date(2014, 12, 31)) def test_override(self): default = timezone.get_default_timezone() try: timezone.activate(ICT) with timezone.override(EAT): self.assertIs(EAT, timezone.get_current_timezone()) self.assertIs(ICT, timezone.get_current_timezone()) with timezone.override(None): self.assertIs(default, timezone.get_current_timezone()) self.assertIs(ICT, timezone.get_current_timezone()) timezone.deactivate() with timezone.override(EAT): self.assertIs(EAT, timezone.get_current_timezone()) self.assertIs(default, timezone.get_current_timezone()) with timezone.override(None): self.assertIs(default, timezone.get_current_timezone()) self.assertIs(default, timezone.get_current_timezone()) finally: timezone.deactivate() def test_override_decorator(self): default = timezone.get_default_timezone() @timezone.override(EAT) def func_tz_eat(): self.assertIs(EAT, timezone.get_current_timezone()) @timezone.override(None) def func_tz_none(): self.assertIs(default, timezone.get_current_timezone()) try: timezone.activate(ICT) func_tz_eat() self.assertIs(ICT, timezone.get_current_timezone()) func_tz_none() self.assertIs(ICT, timezone.get_current_timezone()) timezone.deactivate() func_tz_eat() self.assertIs(default, timezone.get_current_timezone()) func_tz_none() self.assertIs(default, timezone.get_current_timezone()) finally: timezone.deactivate() def test_override_string_tz(self): with timezone.override("Asia/Bangkok"): self.assertEqual(timezone.get_current_timezone_name(), "Asia/Bangkok") def test_override_fixed_offset(self): with timezone.override(datetime.timezone(datetime.timedelta(), "tzname")): self.assertEqual(timezone.get_current_timezone_name(), "tzname") def test_activate_invalid_timezone(self): with self.assertRaisesMessage(ValueError, "Invalid timezone: None"): timezone.activate(None) def test_is_aware(self): self.assertTrue( timezone.is_aware(datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT)) ) self.assertFalse(timezone.is_aware(datetime.datetime(2011, 9, 1, 13, 20, 30))) def test_is_naive(self): self.assertFalse( timezone.is_naive(datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT)) ) self.assertTrue(timezone.is_naive(datetime.datetime(2011, 9, 1, 13, 20, 30))) def test_make_aware(self): self.assertEqual( timezone.make_aware(datetime.datetime(2011, 9, 1, 13, 20, 30), EAT), datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT), ) with self.assertRaises(ValueError): timezone.make_aware( datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT), EAT ) def test_make_naive(self): self.assertEqual( timezone.make_naive( datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT), EAT ), datetime.datetime(2011, 9, 1, 13, 20, 30), ) self.assertEqual( timezone.make_naive( datetime.datetime(2011, 9, 1, 17, 20, 30, tzinfo=ICT), EAT ), datetime.datetime(2011, 9, 1, 13, 20, 30), ) with self.assertRaisesMessage( ValueError, "make_naive() cannot be applied to a naive datetime" ): timezone.make_naive(datetime.datetime(2011, 9, 1, 13, 20, 30), EAT) def test_make_naive_no_tz(self): self.assertEqual( timezone.make_naive(datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT)), datetime.datetime(2011, 9, 1, 5, 20, 30), ) def test_make_aware_no_tz(self): self.assertEqual( timezone.make_aware(datetime.datetime(2011, 9, 1, 13, 20, 30)), datetime.datetime( 2011, 9, 1, 13, 20, 30, tzinfo=timezone.get_fixed_timezone(-300) ), ) def test_make_aware2(self): CEST = datetime.timezone(datetime.timedelta(hours=2), "CEST") for tz in PARIS_IMPLS: with self.subTest(repr(tz)): self.assertEqual( timezone.make_aware(datetime.datetime(2011, 9, 1, 12, 20, 30), tz), datetime.datetime(2011, 9, 1, 12, 20, 30, tzinfo=CEST), ) if HAS_PYTZ: with self.assertRaises(ValueError): timezone.make_aware( CET.localize(datetime.datetime(2011, 9, 1, 12, 20, 30)), CET ) with self.assertRaises(ValueError): timezone.make_aware( datetime.datetime(2011, 9, 1, 12, 20, 30, tzinfo=PARIS_ZI), PARIS_ZI ) @needs_pytz def test_make_naive_pytz(self): self.assertEqual( timezone.make_naive( CET.localize(datetime.datetime(2011, 9, 1, 12, 20, 30)), CET ), datetime.datetime(2011, 9, 1, 12, 20, 30), ) self.assertEqual( timezone.make_naive( pytz.timezone("Asia/Bangkok").localize( datetime.datetime(2011, 9, 1, 17, 20, 30) ), CET, ), datetime.datetime(2011, 9, 1, 12, 20, 30), ) with self.assertRaisesMessage( ValueError, "make_naive() cannot be applied to a naive datetime" ): timezone.make_naive(datetime.datetime(2011, 9, 1, 12, 20, 30), CET) def test_make_naive_zoneinfo(self): self.assertEqual( timezone.make_naive( datetime.datetime(2011, 9, 1, 12, 20, 30, tzinfo=PARIS_ZI), PARIS_ZI ), datetime.datetime(2011, 9, 1, 12, 20, 30), ) self.assertEqual( timezone.make_naive( datetime.datetime(2011, 9, 1, 12, 20, 30, fold=1, tzinfo=PARIS_ZI), PARIS_ZI, ), datetime.datetime(2011, 9, 1, 12, 20, 30, fold=1), ) @needs_pytz @ignore_warnings(category=RemovedInDjango50Warning) def test_make_aware_pytz_ambiguous(self): # 2:30 happens twice, once before DST ends and once after ambiguous = datetime.datetime(2015, 10, 25, 2, 30) with self.assertRaises(pytz.AmbiguousTimeError): timezone.make_aware(ambiguous, timezone=CET) std = timezone.make_aware(ambiguous, timezone=CET, is_dst=False) dst = timezone.make_aware(ambiguous, timezone=CET, is_dst=True) self.assertEqual(std - dst, datetime.timedelta(hours=1)) self.assertEqual(std.tzinfo.utcoffset(std), datetime.timedelta(hours=1)) self.assertEqual(dst.tzinfo.utcoffset(dst), datetime.timedelta(hours=2)) def test_make_aware_zoneinfo_ambiguous(self): # 2:30 happens twice, once before DST ends and once after ambiguous = datetime.datetime(2015, 10, 25, 2, 30) std = timezone.make_aware(ambiguous.replace(fold=1), timezone=PARIS_ZI) dst = timezone.make_aware(ambiguous, timezone=PARIS_ZI) self.assertEqual( std.astimezone(UTC) - dst.astimezone(UTC), datetime.timedelta(hours=1) ) self.assertEqual(std.utcoffset(), datetime.timedelta(hours=1)) self.assertEqual(dst.utcoffset(), datetime.timedelta(hours=2)) @needs_pytz @ignore_warnings(category=RemovedInDjango50Warning) def test_make_aware_pytz_non_existent(self): # 2:30 never happened due to DST non_existent = datetime.datetime(2015, 3, 29, 2, 30) with self.assertRaises(pytz.NonExistentTimeError): timezone.make_aware(non_existent, timezone=CET) std = timezone.make_aware(non_existent, timezone=CET, is_dst=False) dst = timezone.make_aware(non_existent, timezone=CET, is_dst=True) self.assertEqual(std - dst, datetime.timedelta(hours=1)) self.assertEqual(std.tzinfo.utcoffset(std), datetime.timedelta(hours=1)) self.assertEqual(dst.tzinfo.utcoffset(dst), datetime.timedelta(hours=2)) def test_make_aware_zoneinfo_non_existent(self): # 2:30 never happened due to DST non_existent = datetime.datetime(2015, 3, 29, 2, 30) std = timezone.make_aware(non_existent, PARIS_ZI) dst = timezone.make_aware(non_existent.replace(fold=1), PARIS_ZI) self.assertEqual( std.astimezone(UTC) - dst.astimezone(UTC), datetime.timedelta(hours=1) ) self.assertEqual(std.utcoffset(), datetime.timedelta(hours=1)) self.assertEqual(dst.utcoffset(), datetime.timedelta(hours=2)) def test_make_aware_is_dst_deprecation_warning(self): msg = ( "The is_dst argument to make_aware(), used by the Trunc() " "database functions and QuerySet.datetimes(), is deprecated as it " "has no effect with zoneinfo time zones." ) with self.assertRaisesMessage(RemovedInDjango50Warning, msg): timezone.make_aware( datetime.datetime(2011, 9, 1, 13, 20, 30), EAT, is_dst=True ) def test_get_timezone_name(self): """ The _get_timezone_name() helper must return the offset for fixed offset timezones, for usage with Trunc DB functions. The datetime.timezone examples show the current behavior. """ tests = [ # datetime.timezone, fixed offset with and without `name`. (datetime.timezone(datetime.timedelta(hours=10)), "UTC+10:00"), ( datetime.timezone(datetime.timedelta(hours=10), name="Etc/GMT-10"), "Etc/GMT-10", ), # zoneinfo, named and fixed offset. (zoneinfo.ZoneInfo("Europe/Madrid"), "Europe/Madrid"), (zoneinfo.ZoneInfo("Etc/GMT-10"), "+10"), ] if HAS_PYTZ: tests += [ # pytz, named and fixed offset. (pytz.timezone("Europe/Madrid"), "Europe/Madrid"), (pytz.timezone("Etc/GMT-10"), "+10"), ] for tz, expected in tests: with self.subTest(tz=tz, expected=expected): self.assertEqual(timezone._get_timezone_name(tz), expected) def test_get_default_timezone(self): self.assertEqual(timezone.get_default_timezone_name(), "America/Chicago") def test_fixedoffset_timedelta(self): delta = datetime.timedelta(hours=1) self.assertEqual(timezone.get_fixed_timezone(delta).utcoffset(None), delta) def test_fixedoffset_negative_timedelta(self): delta = datetime.timedelta(hours=-2) self.assertEqual(timezone.get_fixed_timezone(delta).utcoffset(None), delta)
42d1b867fc3a3e064eb5d6c69753699cb3bfbc2c145bd2931821c0a45cfa7797
import datetime import unittest from django.utils.dateparse import parse_duration from django.utils.duration import ( duration_iso_string, duration_microseconds, duration_string, ) class TestDurationString(unittest.TestCase): def test_simple(self): duration = datetime.timedelta(hours=1, minutes=3, seconds=5) self.assertEqual(duration_string(duration), "01:03:05") def test_days(self): duration = datetime.timedelta(days=1, hours=1, minutes=3, seconds=5) self.assertEqual(duration_string(duration), "1 01:03:05") def test_microseconds(self): duration = datetime.timedelta(hours=1, minutes=3, seconds=5, microseconds=12345) self.assertEqual(duration_string(duration), "01:03:05.012345") def test_negative(self): duration = datetime.timedelta(days=-1, hours=1, minutes=3, seconds=5) self.assertEqual(duration_string(duration), "-1 01:03:05") class TestParseDurationRoundtrip(unittest.TestCase): def test_simple(self): duration = datetime.timedelta(hours=1, minutes=3, seconds=5) self.assertEqual(parse_duration(duration_string(duration)), duration) def test_days(self): duration = datetime.timedelta(days=1, hours=1, minutes=3, seconds=5) self.assertEqual(parse_duration(duration_string(duration)), duration) def test_microseconds(self): duration = datetime.timedelta(hours=1, minutes=3, seconds=5, microseconds=12345) self.assertEqual(parse_duration(duration_string(duration)), duration) def test_negative(self): duration = datetime.timedelta(days=-1, hours=1, minutes=3, seconds=5) self.assertEqual(parse_duration(duration_string(duration)), duration) class TestISODurationString(unittest.TestCase): def test_simple(self): duration = datetime.timedelta(hours=1, minutes=3, seconds=5) self.assertEqual(duration_iso_string(duration), "P0DT01H03M05S") def test_days(self): duration = datetime.timedelta(days=1, hours=1, minutes=3, seconds=5) self.assertEqual(duration_iso_string(duration), "P1DT01H03M05S") def test_microseconds(self): duration = datetime.timedelta(hours=1, minutes=3, seconds=5, microseconds=12345) self.assertEqual(duration_iso_string(duration), "P0DT01H03M05.012345S") def test_negative(self): duration = -1 * datetime.timedelta(days=1, hours=1, minutes=3, seconds=5) self.assertEqual(duration_iso_string(duration), "-P1DT01H03M05S") class TestParseISODurationRoundtrip(unittest.TestCase): def test_simple(self): duration = datetime.timedelta(hours=1, minutes=3, seconds=5) self.assertEqual(parse_duration(duration_iso_string(duration)), duration) def test_days(self): duration = datetime.timedelta(days=1, hours=1, minutes=3, seconds=5) self.assertEqual(parse_duration(duration_iso_string(duration)), duration) def test_microseconds(self): duration = datetime.timedelta(hours=1, minutes=3, seconds=5, microseconds=12345) self.assertEqual(parse_duration(duration_iso_string(duration)), duration) def test_negative(self): duration = datetime.timedelta(days=-1, hours=1, minutes=3, seconds=5) self.assertEqual( parse_duration(duration_iso_string(duration)).total_seconds(), duration.total_seconds(), ) class TestDurationMicroseconds(unittest.TestCase): def test(self): deltas = [ datetime.timedelta.max, datetime.timedelta.min, datetime.timedelta.resolution, -datetime.timedelta.resolution, datetime.timedelta(microseconds=8999999999999999), ] for delta in deltas: with self.subTest(delta=delta): self.assertEqual( datetime.timedelta(microseconds=duration_microseconds(delta)), delta )
3ba936a0d788de0db754c287fe9b070fffe0171c0fffe6a0c19adfd9465bebde
import re import unittest from django.test import SimpleTestCase from django.utils import regex_helper class NormalizeTests(unittest.TestCase): def test_empty(self): pattern = r"" expected = [("", [])] result = regex_helper.normalize(pattern) self.assertEqual(result, expected) def test_escape(self): pattern = r"\\\^\$\.\|\?\*\+\(\)\[" expected = [("\\^$.|?*+()[", [])] result = regex_helper.normalize(pattern) self.assertEqual(result, expected) def test_group_positional(self): pattern = r"(.*)-(.+)" expected = [("%(_0)s-%(_1)s", ["_0", "_1"])] result = regex_helper.normalize(pattern) self.assertEqual(result, expected) def test_group_noncapturing(self): pattern = r"(?:non-capturing)" expected = [("non-capturing", [])] result = regex_helper.normalize(pattern) self.assertEqual(result, expected) def test_group_named(self): pattern = r"(?P<first_group_name>.*)-(?P<second_group_name>.*)" expected = [ ( "%(first_group_name)s-%(second_group_name)s", ["first_group_name", "second_group_name"], ) ] result = regex_helper.normalize(pattern) self.assertEqual(result, expected) def test_group_backreference(self): pattern = r"(?P<first_group_name>.*)-(?P=first_group_name)" expected = [("%(first_group_name)s-%(first_group_name)s", ["first_group_name"])] result = regex_helper.normalize(pattern) self.assertEqual(result, expected) class LazyReCompileTests(SimpleTestCase): def test_flags_with_pre_compiled_regex(self): test_pattern = re.compile("test") lazy_test_pattern = regex_helper._lazy_re_compile(test_pattern, re.I) msg = "flags must be empty if regex is passed pre-compiled" with self.assertRaisesMessage(AssertionError, msg): lazy_test_pattern.match("TEST")
3c73b164bff7b87b46c43ec0664eef37ec0dd8f3c6551a1cf60917752f063a43
import datetime from django.test import TestCase from django.test.utils import requires_tz_support from django.utils import timezone, translation from django.utils.timesince import timesince, timeuntil from django.utils.translation import npgettext_lazy class TimesinceTests(TestCase): def setUp(self): self.t = datetime.datetime(2007, 8, 14, 13, 46, 0) self.onemicrosecond = datetime.timedelta(microseconds=1) self.onesecond = datetime.timedelta(seconds=1) self.oneminute = datetime.timedelta(minutes=1) self.onehour = datetime.timedelta(hours=1) self.oneday = datetime.timedelta(days=1) self.oneweek = datetime.timedelta(days=7) self.onemonth = datetime.timedelta(days=30) self.oneyear = datetime.timedelta(days=365) def test_equal_datetimes(self): """equal datetimes.""" # NOTE: \xa0 avoids wrapping between value and unit self.assertEqual(timesince(self.t, self.t), "0\xa0minutes") def test_ignore_microseconds_and_seconds(self): """Microseconds and seconds are ignored.""" self.assertEqual( timesince(self.t, self.t + self.onemicrosecond), "0\xa0minutes" ) self.assertEqual(timesince(self.t, self.t + self.onesecond), "0\xa0minutes") def test_other_units(self): """Test other units.""" self.assertEqual(timesince(self.t, self.t + self.oneminute), "1\xa0minute") self.assertEqual(timesince(self.t, self.t + self.onehour), "1\xa0hour") self.assertEqual(timesince(self.t, self.t + self.oneday), "1\xa0day") self.assertEqual(timesince(self.t, self.t + self.oneweek), "1\xa0week") self.assertEqual(timesince(self.t, self.t + self.onemonth), "1\xa0month") self.assertEqual(timesince(self.t, self.t + self.oneyear), "1\xa0year") def test_multiple_units(self): """Test multiple units.""" self.assertEqual( timesince(self.t, self.t + 2 * self.oneday + 6 * self.onehour), "2\xa0days, 6\xa0hours", ) self.assertEqual( timesince(self.t, self.t + 2 * self.oneweek + 2 * self.oneday), "2\xa0weeks, 2\xa0days", ) def test_display_first_unit(self): """ If the two differing units aren't adjacent, only the first unit is displayed. """ self.assertEqual( timesince( self.t, self.t + 2 * self.oneweek + 3 * self.onehour + 4 * self.oneminute, ), "2\xa0weeks", ) self.assertEqual( timesince(self.t, self.t + 4 * self.oneday + 5 * self.oneminute), "4\xa0days", ) def test_display_second_before_first(self): """ When the second date occurs before the first, we should always get 0 minutes. """ self.assertEqual( timesince(self.t, self.t - self.onemicrosecond), "0\xa0minutes" ) self.assertEqual(timesince(self.t, self.t - self.onesecond), "0\xa0minutes") self.assertEqual(timesince(self.t, self.t - self.oneminute), "0\xa0minutes") self.assertEqual(timesince(self.t, self.t - self.onehour), "0\xa0minutes") self.assertEqual(timesince(self.t, self.t - self.oneday), "0\xa0minutes") self.assertEqual(timesince(self.t, self.t - self.oneweek), "0\xa0minutes") self.assertEqual(timesince(self.t, self.t - self.onemonth), "0\xa0minutes") self.assertEqual(timesince(self.t, self.t - self.oneyear), "0\xa0minutes") self.assertEqual( timesince(self.t, self.t - 2 * self.oneday - 6 * self.onehour), "0\xa0minutes", ) self.assertEqual( timesince(self.t, self.t - 2 * self.oneweek - 2 * self.oneday), "0\xa0minutes", ) self.assertEqual( timesince( self.t, self.t - 2 * self.oneweek - 3 * self.onehour - 4 * self.oneminute, ), "0\xa0minutes", ) self.assertEqual( timesince(self.t, self.t - 4 * self.oneday - 5 * self.oneminute), "0\xa0minutes", ) def test_second_before_equal_first_humanize_time_strings(self): time_strings = { "minute": npgettext_lazy( "naturaltime-future", "%(num)d minute", "%(num)d minutes", "num", ), } with translation.override("cs"): for now in [self.t, self.t - self.onemicrosecond, self.t - self.oneday]: with self.subTest(now): self.assertEqual( timesince(self.t, now, time_strings=time_strings), "0\xa0minut", ) @requires_tz_support def test_different_timezones(self): """When using two different timezones.""" now = datetime.datetime.now() now_tz = timezone.make_aware(now, timezone.get_default_timezone()) now_tz_i = timezone.localtime(now_tz, timezone.get_fixed_timezone(195)) self.assertEqual(timesince(now), "0\xa0minutes") self.assertEqual(timesince(now_tz), "0\xa0minutes") self.assertEqual(timesince(now_tz_i), "0\xa0minutes") self.assertEqual(timesince(now_tz, now_tz_i), "0\xa0minutes") self.assertEqual(timeuntil(now), "0\xa0minutes") self.assertEqual(timeuntil(now_tz), "0\xa0minutes") self.assertEqual(timeuntil(now_tz_i), "0\xa0minutes") self.assertEqual(timeuntil(now_tz, now_tz_i), "0\xa0minutes") def test_date_objects(self): """Both timesince and timeuntil should work on date objects (#17937).""" today = datetime.date.today() self.assertEqual(timesince(today + self.oneday), "0\xa0minutes") self.assertEqual(timeuntil(today - self.oneday), "0\xa0minutes") def test_both_date_objects(self): """Timesince should work with both date objects (#9672)""" today = datetime.date.today() self.assertEqual(timeuntil(today + self.oneday, today), "1\xa0day") self.assertEqual(timeuntil(today - self.oneday, today), "0\xa0minutes") self.assertEqual(timeuntil(today + self.oneweek, today), "1\xa0week") def test_leap_year(self): start_date = datetime.date(2016, 12, 25) self.assertEqual(timeuntil(start_date + self.oneweek, start_date), "1\xa0week") self.assertEqual(timesince(start_date, start_date + self.oneweek), "1\xa0week") def test_leap_year_new_years_eve(self): t = datetime.date(2016, 12, 31) now = datetime.datetime(2016, 12, 31, 18, 0, 0) self.assertEqual(timesince(t + self.oneday, now), "0\xa0minutes") self.assertEqual(timeuntil(t - self.oneday, now), "0\xa0minutes") def test_naive_datetime_with_tzinfo_attribute(self): class naive(datetime.tzinfo): def utcoffset(self, dt): return None future = datetime.datetime(2080, 1, 1, tzinfo=naive()) self.assertEqual(timesince(future), "0\xa0minutes") past = datetime.datetime(1980, 1, 1, tzinfo=naive()) self.assertEqual(timeuntil(past), "0\xa0minutes") def test_thousand_years_ago(self): t = datetime.datetime(1007, 8, 14, 13, 46, 0) self.assertEqual(timesince(t, self.t), "1000\xa0years") self.assertEqual(timeuntil(self.t, t), "1000\xa0years") def test_depth(self): t = ( self.t + self.oneyear + self.onemonth + self.oneweek + self.oneday + self.onehour ) tests = [ (t, 1, "1\xa0year"), (t, 2, "1\xa0year, 1\xa0month"), (t, 3, "1\xa0year, 1\xa0month, 1\xa0week"), (t, 4, "1\xa0year, 1\xa0month, 1\xa0week, 1\xa0day"), (t, 5, "1\xa0year, 1\xa0month, 1\xa0week, 1\xa0day, 1\xa0hour"), (t, 6, "1\xa0year, 1\xa0month, 1\xa0week, 1\xa0day, 1\xa0hour"), (self.t + self.onehour, 5, "1\xa0hour"), (self.t + (4 * self.oneminute), 3, "4\xa0minutes"), (self.t + self.onehour + self.oneminute, 1, "1\xa0hour"), (self.t + self.oneday + self.onehour, 1, "1\xa0day"), (self.t + self.oneweek + self.oneday, 1, "1\xa0week"), (self.t + self.onemonth + self.oneweek, 1, "1\xa0month"), (self.t + self.oneyear + self.onemonth, 1, "1\xa0year"), (self.t + self.oneyear + self.oneweek + self.oneday, 3, "1\xa0year"), ] for value, depth, expected in tests: with self.subTest(): self.assertEqual(timesince(self.t, value, depth=depth), expected) self.assertEqual(timeuntil(value, self.t, depth=depth), expected) def test_depth_invalid(self): msg = "depth must be greater than 0." with self.assertRaisesMessage(ValueError, msg): timesince(self.t, self.t, depth=0)
8ecb57768357d6e228f502031d592a8aead7ffde86bddcb88a36207fdcc7b8f1
from django.test import SimpleTestCase from django.utils.deconstruct import deconstructible from django.utils.version import get_docs_version @deconstructible() class DeconstructibleClass: pass class DeconstructibleChildClass(DeconstructibleClass): pass @deconstructible( path="utils_tests.deconstructible_classes.DeconstructibleWithPathClass" ) class DeconstructibleWithPathClass: pass class DeconstructibleWithPathChildClass(DeconstructibleWithPathClass): pass @deconstructible( path="utils_tests.deconstructible_classes.DeconstructibleInvalidPathClass", ) class DeconstructibleInvalidPathClass: pass class DeconstructibleInvalidPathChildClass(DeconstructibleInvalidPathClass): pass class DeconstructibleTests(SimpleTestCase): def test_deconstruct(self): obj = DeconstructibleClass("arg", key="value") path, args, kwargs = obj.deconstruct() self.assertEqual(path, "utils_tests.test_deconstruct.DeconstructibleClass") self.assertEqual(args, ("arg",)) self.assertEqual(kwargs, {"key": "value"}) def test_deconstruct_with_path(self): obj = DeconstructibleWithPathClass("arg", key="value") path, args, kwargs = obj.deconstruct() self.assertEqual( path, "utils_tests.deconstructible_classes.DeconstructibleWithPathClass", ) self.assertEqual(args, ("arg",)) self.assertEqual(kwargs, {"key": "value"}) def test_deconstruct_child(self): obj = DeconstructibleChildClass("arg", key="value") path, args, kwargs = obj.deconstruct() self.assertEqual(path, "utils_tests.test_deconstruct.DeconstructibleChildClass") self.assertEqual(args, ("arg",)) self.assertEqual(kwargs, {"key": "value"}) def test_deconstruct_child_with_path(self): obj = DeconstructibleWithPathChildClass("arg", key="value") path, args, kwargs = obj.deconstruct() self.assertEqual( path, "utils_tests.test_deconstruct.DeconstructibleWithPathChildClass", ) self.assertEqual(args, ("arg",)) self.assertEqual(kwargs, {"key": "value"}) def test_invalid_path(self): obj = DeconstructibleInvalidPathClass() docs_version = get_docs_version() msg = ( f"Could not find object DeconstructibleInvalidPathClass in " f"utils_tests.deconstructible_classes.\n" f"Please note that you cannot serialize things like inner " f"classes. Please move the object into the main module body to " f"use migrations.\n" f"For more information, see " f"https://docs.djangoproject.com/en/{docs_version}/topics/" f"migrations/#serializing-values" ) with self.assertRaisesMessage(ValueError, msg): obj.deconstruct() def test_parent_invalid_path(self): obj = DeconstructibleInvalidPathChildClass("arg", key="value") path, args, kwargs = obj.deconstruct() self.assertEqual( path, "utils_tests.test_deconstruct.DeconstructibleInvalidPathChildClass", ) self.assertEqual(args, ("arg",)) self.assertEqual(kwargs, {"key": "value"})
f969465fa13a5b65976664f5e966c130ce5a617763910790ba1b534a86028e82
import datetime import sys import unittest from pathlib import Path from unittest import mock from urllib.parse import quote_plus from django.test import SimpleTestCase from django.utils.encoding import ( DjangoUnicodeDecodeError, escape_uri_path, filepath_to_uri, force_bytes, force_str, get_system_encoding, iri_to_uri, repercent_broken_unicode, smart_bytes, smart_str, uri_to_iri, ) from django.utils.functional import SimpleLazyObject from django.utils.translation import gettext_lazy class TestEncodingUtils(SimpleTestCase): def test_force_str_exception(self): """ Broken __str__ actually raises an error. """ class MyString: def __str__(self): return b"\xc3\xb6\xc3\xa4\xc3\xbc" # str(s) raises a TypeError if the result is not a text type. with self.assertRaises(TypeError): force_str(MyString()) def test_force_str_lazy(self): s = SimpleLazyObject(lambda: "x") self.assertIs(type(force_str(s)), str) def test_force_str_DjangoUnicodeDecodeError(self): msg = ( "'utf-8' codec can't decode byte 0xff in position 0: invalid " "start byte. You passed in b'\\xff' (<class 'bytes'>)" ) with self.assertRaisesMessage(DjangoUnicodeDecodeError, msg): force_str(b"\xff") def test_force_bytes_exception(self): """ force_bytes knows how to convert to bytes an exception containing non-ASCII characters in its args. """ error_msg = "This is an exception, voilà" exc = ValueError(error_msg) self.assertEqual(force_bytes(exc), error_msg.encode()) self.assertEqual( force_bytes(exc, encoding="ascii", errors="ignore"), b"This is an exception, voil", ) def test_force_bytes_strings_only(self): today = datetime.date.today() self.assertEqual(force_bytes(today, strings_only=True), today) def test_force_bytes_encoding(self): error_msg = "This is an exception, voilà".encode() result = force_bytes(error_msg, encoding="ascii", errors="ignore") self.assertEqual(result, b"This is an exception, voil") def test_force_bytes_memory_view(self): data = b"abc" result = force_bytes(memoryview(data)) # Type check is needed because memoryview(bytes) == bytes. self.assertIs(type(result), bytes) self.assertEqual(result, data) def test_smart_bytes(self): class Test: def __str__(self): return "ŠĐĆŽćžšđ" lazy_func = gettext_lazy("x") self.assertIs(smart_bytes(lazy_func), lazy_func) self.assertEqual( smart_bytes(Test()), b"\xc5\xa0\xc4\x90\xc4\x86\xc5\xbd\xc4\x87\xc5\xbe\xc5\xa1\xc4\x91", ) self.assertEqual(smart_bytes(1), b"1") self.assertEqual(smart_bytes("foo"), b"foo") def test_smart_str(self): class Test: def __str__(self): return "ŠĐĆŽćžšđ" lazy_func = gettext_lazy("x") self.assertIs(smart_str(lazy_func), lazy_func) self.assertEqual( smart_str(Test()), "\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" ) self.assertEqual(smart_str(1), "1") self.assertEqual(smart_str("foo"), "foo") def test_get_default_encoding(self): with mock.patch("locale.getdefaultlocale", side_effect=Exception): self.assertEqual(get_system_encoding(), "ascii") def test_repercent_broken_unicode_recursion_error(self): # Prepare a string long enough to force a recursion error if the tested # function uses recursion. data = b"\xfc" * sys.getrecursionlimit() try: self.assertEqual( repercent_broken_unicode(data), b"%FC" * sys.getrecursionlimit() ) except RecursionError: self.fail("Unexpected RecursionError raised.") class TestRFC3987IEncodingUtils(unittest.TestCase): def test_filepath_to_uri(self): self.assertIsNone(filepath_to_uri(None)) self.assertEqual( filepath_to_uri("upload\\чубака.mp4"), "upload/%D1%87%D1%83%D0%B1%D0%B0%D0%BA%D0%B0.mp4", ) self.assertEqual(filepath_to_uri(Path("upload/test.png")), "upload/test.png") self.assertEqual(filepath_to_uri(Path("upload\\test.png")), "upload/test.png") def test_iri_to_uri(self): cases = [ # Valid UTF-8 sequences are encoded. ("red%09rosé#red", "red%09ros%C3%A9#red"), ("/blog/for/Jürgen Münster/", "/blog/for/J%C3%BCrgen%20M%C3%BCnster/"), ( "locations/%s" % quote_plus("Paris & Orléans"), "locations/Paris+%26+Orl%C3%A9ans", ), # Reserved chars remain unescaped. ("%&", "%&"), ("red&♥ros%#red", "red&%E2%99%A5ros%#red"), (gettext_lazy("red&♥ros%#red"), "red&%E2%99%A5ros%#red"), ] for iri, uri in cases: with self.subTest(iri): self.assertEqual(iri_to_uri(iri), uri) # Test idempotency. self.assertEqual(iri_to_uri(iri_to_uri(iri)), uri) def test_uri_to_iri(self): cases = [ (None, None), # Valid UTF-8 sequences are decoded. ("/%e2%89%Ab%E2%99%a5%E2%89%aB/", "/≫♥≫/"), ("/%E2%99%A5%E2%99%A5/?utf8=%E2%9C%93", "/♥♥/?utf8=✓"), ("/%41%5a%6B/", "/AZk/"), # Reserved and non-URL valid ASCII chars are not decoded. ("/%25%20%02%41%7b/", "/%25%20%02A%7b/"), # Broken UTF-8 sequences remain escaped. ("/%AAd%AAj%AAa%AAn%AAg%AAo%AA/", "/%AAd%AAj%AAa%AAn%AAg%AAo%AA/"), ("/%E2%99%A5%E2%E2%99%A5/", "/♥%E2♥/"), ("/%E2%99%A5%E2%99%E2%99%A5/", "/♥%E2%99♥/"), ("/%E2%E2%99%A5%E2%99%A5%99/", "/%E2♥♥%99/"), ( "/%E2%99%A5%E2%99%A5/?utf8=%9C%93%E2%9C%93%9C%93", "/♥♥/?utf8=%9C%93✓%9C%93", ), ] for uri, iri in cases: with self.subTest(uri): self.assertEqual(uri_to_iri(uri), iri) # Test idempotency. self.assertEqual(uri_to_iri(uri_to_iri(uri)), iri) def test_complementarity(self): cases = [ ( "/blog/for/J%C3%BCrgen%20M%C3%BCnster/", "/blog/for/J\xfcrgen%20M\xfcnster/", ), ("%&", "%&"), ("red&%E2%99%A5ros%#red", "red&♥ros%#red"), ("/%E2%99%A5%E2%99%A5/", "/♥♥/"), ("/%E2%99%A5%E2%99%A5/?utf8=%E2%9C%93", "/♥♥/?utf8=✓"), ("/%25%20%02%7b/", "/%25%20%02%7b/"), ("/%AAd%AAj%AAa%AAn%AAg%AAo%AA/", "/%AAd%AAj%AAa%AAn%AAg%AAo%AA/"), ("/%E2%99%A5%E2%E2%99%A5/", "/♥%E2♥/"), ("/%E2%99%A5%E2%99%E2%99%A5/", "/♥%E2%99♥/"), ("/%E2%E2%99%A5%E2%99%A5%99/", "/%E2♥♥%99/"), ( "/%E2%99%A5%E2%99%A5/?utf8=%9C%93%E2%9C%93%9C%93", "/♥♥/?utf8=%9C%93✓%9C%93", ), ] for uri, iri in cases: with self.subTest(uri): self.assertEqual(iri_to_uri(uri_to_iri(uri)), uri) self.assertEqual(uri_to_iri(iri_to_uri(iri)), iri) def test_escape_uri_path(self): cases = [ ( "/;some/=awful/?path/:with/@lots/&of/+awful/chars", "/%3Bsome/%3Dawful/%3Fpath/:with/@lots/&of/+awful/chars", ), ("/foo#bar", "/foo%23bar"), ("/foo?bar", "/foo%3Fbar"), ] for uri, expected in cases: with self.subTest(uri): self.assertEqual(escape_uri_path(uri), expected)
e4900a04344cdf186c80ad2999d9dc2ffc37efc82183c7072a3904ceb8d35560
import os import unittest from pathlib import Path from django.core.exceptions import SuspiciousFileOperation from django.utils._os import safe_join, to_path class SafeJoinTests(unittest.TestCase): def test_base_path_ends_with_sep(self): drive, path = os.path.splitdrive(safe_join("/abc/", "abc")) self.assertEqual(path, "{0}abc{0}abc".format(os.path.sep)) def test_root_path(self): drive, path = os.path.splitdrive(safe_join("/", "path")) self.assertEqual( path, "{}path".format(os.path.sep), ) drive, path = os.path.splitdrive(safe_join("/", "")) self.assertEqual( path, os.path.sep, ) def test_parent_path(self): with self.assertRaises(SuspiciousFileOperation): safe_join("/abc/", "../def") class ToPathTests(unittest.TestCase): def test_to_path(self): for path in ("/tmp/some_file.txt", Path("/tmp/some_file.txt")): with self.subTest(path): self.assertEqual(to_path(path), Path("/tmp/some_file.txt")) def test_to_path_invalid_value(self): with self.assertRaises(TypeError): to_path(42)
6e3031b1e87ba618acee21c2c58e2ac259f4cb67b548085d21033d8ef18768cc
import pickle from django.contrib.auth.models import User from django.test import TestCase from django.utils.functional import SimpleLazyObject class TestUtilsSimpleLazyObjectDjangoTestCase(TestCase): def test_pickle(self): user = User.objects.create_user("johndoe", "[email protected]", "pass") x = SimpleLazyObject(lambda: user) pickle.dumps(x) # Try the variant protocol levels. pickle.dumps(x, 0) pickle.dumps(x, 1) pickle.dumps(x, 2)
932dc64e550de2439bcb472c1bd3c0fbdb2336056891f17ece506c80607c55e6
import unittest from datetime import date, datetime, time, timedelta from django.utils.dateparse import ( parse_date, parse_datetime, parse_duration, parse_time, ) from django.utils.timezone import get_fixed_timezone class DateParseTests(unittest.TestCase): def test_parse_date(self): # Valid inputs self.assertEqual(parse_date("2012-04-23"), date(2012, 4, 23)) self.assertEqual(parse_date("2012-4-9"), date(2012, 4, 9)) # Invalid inputs self.assertIsNone(parse_date("20120423")) with self.assertRaises(ValueError): parse_date("2012-04-56") def test_parse_time(self): # Valid inputs self.assertEqual(parse_time("09:15:00"), time(9, 15)) self.assertEqual(parse_time("10:10"), time(10, 10)) self.assertEqual(parse_time("10:20:30.400"), time(10, 20, 30, 400000)) self.assertEqual(parse_time("10:20:30,400"), time(10, 20, 30, 400000)) self.assertEqual(parse_time("4:8:16"), time(4, 8, 16)) # Time zone offset is ignored. self.assertEqual(parse_time("00:05:23+04:00"), time(0, 5, 23)) # Invalid inputs self.assertIsNone(parse_time("00:05:")) self.assertIsNone(parse_time("00:05:23,")) self.assertIsNone(parse_time("00:05:23+")) self.assertIsNone(parse_time("00:05:23+25:00")) self.assertIsNone(parse_time("4:18:101")) self.assertIsNone(parse_time("091500")) with self.assertRaises(ValueError): parse_time("09:15:90") def test_parse_datetime(self): valid_inputs = ( ("2012-04-23T09:15:00", datetime(2012, 4, 23, 9, 15)), ("2012-4-9 4:8:16", datetime(2012, 4, 9, 4, 8, 16)), ( "2012-04-23T09:15:00Z", datetime(2012, 4, 23, 9, 15, 0, 0, get_fixed_timezone(0)), ), ( "2012-4-9 4:8:16-0320", datetime(2012, 4, 9, 4, 8, 16, 0, get_fixed_timezone(-200)), ), ( "2012-04-23T10:20:30.400+02:30", datetime(2012, 4, 23, 10, 20, 30, 400000, get_fixed_timezone(150)), ), ( "2012-04-23T10:20:30.400+02", datetime(2012, 4, 23, 10, 20, 30, 400000, get_fixed_timezone(120)), ), ( "2012-04-23T10:20:30.400-02", datetime(2012, 4, 23, 10, 20, 30, 400000, get_fixed_timezone(-120)), ), ( "2012-04-23T10:20:30,400-02", datetime(2012, 4, 23, 10, 20, 30, 400000, get_fixed_timezone(-120)), ), ( "2012-04-23T10:20:30.400 +0230", datetime(2012, 4, 23, 10, 20, 30, 400000, get_fixed_timezone(150)), ), ( "2012-04-23T10:20:30,400 +00", datetime(2012, 4, 23, 10, 20, 30, 400000, get_fixed_timezone(0)), ), ( "2012-04-23T10:20:30 -02", datetime(2012, 4, 23, 10, 20, 30, 0, get_fixed_timezone(-120)), ), ) for source, expected in valid_inputs: with self.subTest(source=source): self.assertEqual(parse_datetime(source), expected) # Invalid inputs self.assertIsNone(parse_datetime("20120423091500")) with self.assertRaises(ValueError): parse_datetime("2012-04-56T09:15:90") class DurationParseTests(unittest.TestCase): def test_parse_python_format(self): timedeltas = [ timedelta( days=4, minutes=15, seconds=30, milliseconds=100 ), # fractions of seconds timedelta(hours=10, minutes=15, seconds=30), # hours, minutes, seconds timedelta(days=4, minutes=15, seconds=30), # multiple days timedelta(days=1, minutes=00, seconds=00), # single day timedelta(days=-4, minutes=15, seconds=30), # negative durations timedelta(minutes=15, seconds=30), # minute & seconds timedelta(seconds=30), # seconds ] for delta in timedeltas: with self.subTest(delta=delta): self.assertEqual(parse_duration(format(delta)), delta) def test_parse_postgresql_format(self): test_values = ( ("1 day", timedelta(1)), ("-1 day", timedelta(-1)), ("1 day 0:00:01", timedelta(days=1, seconds=1)), ("1 day -0:00:01", timedelta(days=1, seconds=-1)), ("-1 day -0:00:01", timedelta(days=-1, seconds=-1)), ("-1 day +0:00:01", timedelta(days=-1, seconds=1)), ( "4 days 0:15:30.1", timedelta(days=4, minutes=15, seconds=30, milliseconds=100), ), ( "4 days 0:15:30.0001", timedelta(days=4, minutes=15, seconds=30, microseconds=100), ), ("-4 days -15:00:30", timedelta(days=-4, hours=-15, seconds=-30)), ) for source, expected in test_values: with self.subTest(source=source): self.assertEqual(parse_duration(source), expected) def test_seconds(self): self.assertEqual(parse_duration("30"), timedelta(seconds=30)) def test_minutes_seconds(self): self.assertEqual(parse_duration("15:30"), timedelta(minutes=15, seconds=30)) self.assertEqual(parse_duration("5:30"), timedelta(minutes=5, seconds=30)) def test_hours_minutes_seconds(self): self.assertEqual( parse_duration("10:15:30"), timedelta(hours=10, minutes=15, seconds=30) ) self.assertEqual( parse_duration("1:15:30"), timedelta(hours=1, minutes=15, seconds=30) ) self.assertEqual( parse_duration("100:200:300"), timedelta(hours=100, minutes=200, seconds=300), ) def test_days(self): self.assertEqual( parse_duration("4 15:30"), timedelta(days=4, minutes=15, seconds=30) ) self.assertEqual( parse_duration("4 10:15:30"), timedelta(days=4, hours=10, minutes=15, seconds=30), ) def test_fractions_of_seconds(self): test_values = ( ("15:30.1", timedelta(minutes=15, seconds=30, milliseconds=100)), ("15:30.01", timedelta(minutes=15, seconds=30, milliseconds=10)), ("15:30.001", timedelta(minutes=15, seconds=30, milliseconds=1)), ("15:30.0001", timedelta(minutes=15, seconds=30, microseconds=100)), ("15:30.00001", timedelta(minutes=15, seconds=30, microseconds=10)), ("15:30.000001", timedelta(minutes=15, seconds=30, microseconds=1)), ("15:30,000001", timedelta(minutes=15, seconds=30, microseconds=1)), ) for source, expected in test_values: with self.subTest(source=source): self.assertEqual(parse_duration(source), expected) def test_negative(self): test_values = ( ("-4 15:30", timedelta(days=-4, minutes=15, seconds=30)), ("-172800", timedelta(days=-2)), ("-15:30", timedelta(minutes=-15, seconds=-30)), ("-1:15:30", timedelta(hours=-1, minutes=-15, seconds=-30)), ("-30.1", timedelta(seconds=-30, milliseconds=-100)), ("-30,1", timedelta(seconds=-30, milliseconds=-100)), ("-00:01:01", timedelta(minutes=-1, seconds=-1)), ("-01:01", timedelta(seconds=-61)), ("-01:-01", None), ) for source, expected in test_values: with self.subTest(source=source): self.assertEqual(parse_duration(source), expected) def test_iso_8601(self): test_values = ( ("P4Y", None), ("P4M", None), ("P4W", None), ("P4D", timedelta(days=4)), ("-P1D", timedelta(days=-1)), ("P0.5D", timedelta(hours=12)), ("P0,5D", timedelta(hours=12)), ("-P0.5D", timedelta(hours=-12)), ("-P0,5D", timedelta(hours=-12)), ("PT5H", timedelta(hours=5)), ("-PT5H", timedelta(hours=-5)), ("PT5M", timedelta(minutes=5)), ("-PT5M", timedelta(minutes=-5)), ("PT5S", timedelta(seconds=5)), ("-PT5S", timedelta(seconds=-5)), ("PT0.000005S", timedelta(microseconds=5)), ("PT0,000005S", timedelta(microseconds=5)), ("-PT0.000005S", timedelta(microseconds=-5)), ("-PT0,000005S", timedelta(microseconds=-5)), ("-P4DT1H", timedelta(days=-4, hours=-1)), # Invalid separators for decimal fractions. ("P3(3D", None), ("PT3)3H", None), ("PT3|3M", None), ("PT3/3S", None), ) for source, expected in test_values: with self.subTest(source=source): self.assertEqual(parse_duration(source), expected)
a91c8d0d90473cccb0275ad94008d0b105cc425af93507a5a33e299ef0efd61c
import os from datetime import datetime from django.test import SimpleTestCase from django.utils.functional import lazystr from django.utils.html import ( conditional_escape, escape, escapejs, format_html, html_safe, json_script, linebreaks, smart_urlquote, strip_spaces_between_tags, strip_tags, urlize, ) from django.utils.safestring import mark_safe class TestUtilsHtml(SimpleTestCase): def check_output(self, function, value, output=None): """ function(value) equals output. If output is None, function(value) equals value. """ if output is None: output = value self.assertEqual(function(value), output) def test_escape(self): items = ( ("&", "&amp;"), ("<", "&lt;"), (">", "&gt;"), ('"', "&quot;"), ("'", "&#x27;"), ) # Substitution patterns for testing the above items. patterns = ("%s", "asdf%sfdsa", "%s1", "1%sb") for value, output in items: with self.subTest(value=value, output=output): for pattern in patterns: with self.subTest(value=value, output=output, pattern=pattern): self.check_output(escape, pattern % value, pattern % output) self.check_output( escape, lazystr(pattern % value), pattern % output ) # Check repeated values. self.check_output(escape, value * 2, output * 2) # Verify it doesn't double replace &. self.check_output(escape, "<&", "&lt;&amp;") def test_format_html(self): self.assertEqual( format_html( "{} {} {third} {fourth}", "< Dangerous >", mark_safe("<b>safe</b>"), third="< dangerous again", fourth=mark_safe("<i>safe again</i>"), ), "&lt; Dangerous &gt; <b>safe</b> &lt; dangerous again <i>safe again</i>", ) def test_linebreaks(self): items = ( ("para1\n\npara2\r\rpara3", "<p>para1</p>\n\n<p>para2</p>\n\n<p>para3</p>"), ( "para1\nsub1\rsub2\n\npara2", "<p>para1<br>sub1<br>sub2</p>\n\n<p>para2</p>", ), ( "para1\r\n\r\npara2\rsub1\r\rpara4", "<p>para1</p>\n\n<p>para2<br>sub1</p>\n\n<p>para4</p>", ), ("para1\tmore\n\npara2", "<p>para1\tmore</p>\n\n<p>para2</p>"), ) for value, output in items: with self.subTest(value=value, output=output): self.check_output(linebreaks, value, output) self.check_output(linebreaks, lazystr(value), output) def test_strip_tags(self): items = ( ( "<p>See: &#39;&eacute; is an apostrophe followed by e acute</p>", "See: &#39;&eacute; is an apostrophe followed by e acute", ), ( "<p>See: &#x27;&eacute; is an apostrophe followed by e acute</p>", "See: &#x27;&eacute; is an apostrophe followed by e acute", ), ("<adf>a", "a"), ("</adf>a", "a"), ("<asdf><asdf>e", "e"), ("hi, <f x", "hi, <f x"), ("234<235, right?", "234<235, right?"), ("a4<a5 right?", "a4<a5 right?"), ("b7>b2!", "b7>b2!"), ("</fe", "</fe"), ("<x>b<y>", "b"), ("a<p onclick=\"alert('<test>')\">b</p>c", "abc"), ("a<p a >b</p>c", "abc"), ("d<a:b c:d>e</p>f", "def"), ('<strong>foo</strong><a href="http://example.com">bar</a>', "foobar"), # caused infinite loop on Pythons not patched with # https://bugs.python.org/issue20288 ("&gotcha&#;<>", "&gotcha&#;<>"), ("<sc<!-- -->ript>test<<!-- -->/script>", "ript>test"), ("<script>alert()</script>&h", "alert()h"), ("><!" + ("&" * 16000) + "D", "><!" + ("&" * 16000) + "D"), ("X<<<<br>br>br>br>X", "XX"), ) for value, output in items: with self.subTest(value=value, output=output): self.check_output(strip_tags, value, output) self.check_output(strip_tags, lazystr(value), output) def test_strip_tags_files(self): # Test with more lengthy content (also catching performance regressions) for filename in ("strip_tags1.html", "strip_tags2.txt"): with self.subTest(filename=filename): path = os.path.join(os.path.dirname(__file__), "files", filename) with open(path) as fp: content = fp.read() start = datetime.now() stripped = strip_tags(content) elapsed = datetime.now() - start self.assertEqual(elapsed.seconds, 0) self.assertIn("Please try again.", stripped) self.assertNotIn("<", stripped) def test_strip_spaces_between_tags(self): # Strings that should come out untouched. items = (" <adf>", "<adf> ", " </adf> ", " <f> x</f>") for value in items: with self.subTest(value=value): self.check_output(strip_spaces_between_tags, value) self.check_output(strip_spaces_between_tags, lazystr(value)) # Strings that have spaces to strip. items = ( ("<d> </d>", "<d></d>"), ("<p>hello </p>\n<p> world</p>", "<p>hello </p><p> world</p>"), ("\n<p>\t</p>\n<p> </p>\n", "\n<p></p><p></p>\n"), ) for value, output in items: with self.subTest(value=value, output=output): self.check_output(strip_spaces_between_tags, value, output) self.check_output(strip_spaces_between_tags, lazystr(value), output) def test_escapejs(self): items = ( ( "\"double quotes\" and 'single quotes'", "\\u0022double quotes\\u0022 and \\u0027single quotes\\u0027", ), (r"\ : backslashes, too", "\\u005C : backslashes, too"), ( "and lots of whitespace: \r\n\t\v\f\b", "and lots of whitespace: \\u000D\\u000A\\u0009\\u000B\\u000C\\u0008", ), ( r"<script>and this</script>", "\\u003Cscript\\u003Eand this\\u003C/script\\u003E", ), ( "paragraph separator:\u2029and line separator:\u2028", "paragraph separator:\\u2029and line separator:\\u2028", ), ("`", "\\u0060"), ) for value, output in items: with self.subTest(value=value, output=output): self.check_output(escapejs, value, output) self.check_output(escapejs, lazystr(value), output) def test_json_script(self): tests = ( # "<", ">" and "&" are quoted inside JSON strings ( ( "&<>", '<script id="test_id" type="application/json">' '"\\u0026\\u003C\\u003E"</script>', ) ), # "<", ">" and "&" are quoted inside JSON objects ( {"a": "<script>test&ing</script>"}, '<script id="test_id" type="application/json">' '{"a": "\\u003Cscript\\u003Etest\\u0026ing\\u003C/script\\u003E"}' "</script>", ), # Lazy strings are quoted ( lazystr("&<>"), '<script id="test_id" type="application/json">"\\u0026\\u003C\\u003E"' "</script>", ), ( {"a": lazystr("<script>test&ing</script>")}, '<script id="test_id" type="application/json">' '{"a": "\\u003Cscript\\u003Etest\\u0026ing\\u003C/script\\u003E"}' "</script>", ), ) for arg, expected in tests: with self.subTest(arg=arg): self.assertEqual(json_script(arg, "test_id"), expected) def test_json_script_without_id(self): self.assertHTMLEqual( json_script({"key": "value"}), '<script type="application/json">{"key": "value"}</script>', ) def test_smart_urlquote(self): items = ( ("http://öäü.com/", "http://xn--4ca9at.com/"), ("http://öäü.com/öäü/", "http://xn--4ca9at.com/%C3%B6%C3%A4%C3%BC/"), # Everything unsafe is quoted, !*'();:@&=+$,/?#[]~ is considered # safe as per RFC. ( "http://example.com/path/öäü/", "http://example.com/path/%C3%B6%C3%A4%C3%BC/", ), ("http://example.com/%C3%B6/ä/", "http://example.com/%C3%B6/%C3%A4/"), ("http://example.com/?x=1&y=2+3&z=", "http://example.com/?x=1&y=2+3&z="), ("http://example.com/?x=<>\"'", "http://example.com/?x=%3C%3E%22%27"), ( "http://example.com/?q=http://example.com/?x=1%26q=django", "http://example.com/?q=http%3A%2F%2Fexample.com%2F%3Fx%3D1%26q%3D" "django", ), ( "http://example.com/?q=http%3A%2F%2Fexample.com%2F%3Fx%3D1%26q%3D" "django", "http://example.com/?q=http%3A%2F%2Fexample.com%2F%3Fx%3D1%26q%3D" "django", ), ("http://.www.f oo.bar/", "http://.www.f%20oo.bar/"), ) # IDNs are properly quoted for value, output in items: with self.subTest(value=value, output=output): self.assertEqual(smart_urlquote(value), output) def test_conditional_escape(self): s = "<h1>interop</h1>" self.assertEqual(conditional_escape(s), "&lt;h1&gt;interop&lt;/h1&gt;") self.assertEqual(conditional_escape(mark_safe(s)), s) self.assertEqual(conditional_escape(lazystr(mark_safe(s))), s) def test_html_safe(self): @html_safe class HtmlClass: def __str__(self): return "<h1>I'm a html class!</h1>" html_obj = HtmlClass() self.assertTrue(hasattr(HtmlClass, "__html__")) self.assertTrue(hasattr(html_obj, "__html__")) self.assertEqual(str(html_obj), html_obj.__html__()) def test_html_safe_subclass(self): class BaseClass: def __html__(self): # defines __html__ on its own return "some html content" def __str__(self): return "some non html content" @html_safe class Subclass(BaseClass): def __str__(self): # overrides __str__ and is marked as html_safe return "some html safe content" subclass_obj = Subclass() self.assertEqual(str(subclass_obj), subclass_obj.__html__()) def test_html_safe_defines_html_error(self): msg = "can't apply @html_safe to HtmlClass because it defines __html__()." with self.assertRaisesMessage(ValueError, msg): @html_safe class HtmlClass: def __html__(self): return "<h1>I'm a html class!</h1>" def test_html_safe_doesnt_define_str(self): msg = "can't apply @html_safe to HtmlClass because it doesn't define __str__()." with self.assertRaisesMessage(ValueError, msg): @html_safe class HtmlClass: pass def test_urlize(self): tests = ( ( "Search for google.com/?q=! and see.", 'Search for <a href="http://google.com/?q=">google.com/?q=</a>! and ' "see.", ), ( "Search for google.com/?q=1&lt! and see.", 'Search for <a href="http://google.com/?q=1%3C">google.com/?q=1&lt' "</a>! and see.", ), ( lazystr("Search for google.com/?q=!"), 'Search for <a href="http://google.com/?q=">google.com/?q=</a>!', ), ("[email protected]", '<a href="mailto:[email protected]">[email protected]</a>'), ) for value, output in tests: with self.subTest(value=value): self.assertEqual(urlize(value), output) def test_urlize_unchanged_inputs(self): tests = ( ("a" + "@a" * 50000) + "a", # simple_email_re catastrophic test ("a" + "." * 1000000) + "a", # trailing_punctuation catastrophic test "foo@", "@foo.com", "[email protected]", "foo@localhost", "foo@localhost.", ) for value in tests: with self.subTest(value=value): self.assertEqual(urlize(value), value)
66c1cf3e020f4490aadb70214c854a8f9998e14aeefabd1398f9a5d78e5ad6bf
import copy import unittest from django.utils.tree import Node class NodeTests(unittest.TestCase): def setUp(self): self.node1_children = [("a", 1), ("b", 2)] self.node1 = Node(self.node1_children) self.node2 = Node() def test_str(self): self.assertEqual(str(self.node1), "(DEFAULT: ('a', 1), ('b', 2))") self.assertEqual(str(self.node2), "(DEFAULT: )") def test_repr(self): self.assertEqual(repr(self.node1), "<Node: (DEFAULT: ('a', 1), ('b', 2))>") self.assertEqual(repr(self.node2), "<Node: (DEFAULT: )>") def test_hash(self): node3 = Node(self.node1_children, negated=True) node4 = Node(self.node1_children, connector="OTHER") node5 = Node(self.node1_children) node6 = Node([["a", 1], ["b", 2]]) node7 = Node([("a", [1, 2])]) node8 = Node([("a", (1, 2))]) self.assertNotEqual(hash(self.node1), hash(self.node2)) self.assertNotEqual(hash(self.node1), hash(node3)) self.assertNotEqual(hash(self.node1), hash(node4)) self.assertEqual(hash(self.node1), hash(node5)) self.assertEqual(hash(self.node1), hash(node6)) self.assertEqual(hash(self.node2), hash(Node())) self.assertEqual(hash(node7), hash(node8)) def test_len(self): self.assertEqual(len(self.node1), 2) self.assertEqual(len(self.node2), 0) def test_bool(self): self.assertTrue(self.node1) self.assertFalse(self.node2) def test_contains(self): self.assertIn(("a", 1), self.node1) self.assertNotIn(("a", 1), self.node2) def test_add(self): # start with the same children of node1 then add an item node3 = Node(self.node1_children) node3_added_child = ("c", 3) # add() returns the added data self.assertEqual(node3.add(node3_added_child, Node.default), node3_added_child) # we added exactly one item, len() should reflect that self.assertEqual(len(self.node1) + 1, len(node3)) self.assertEqual(str(node3), "(DEFAULT: ('a', 1), ('b', 2), ('c', 3))") def test_add_eq_child_mixed_connector(self): node = Node(["a", "b"], "OR") self.assertEqual(node.add("a", "AND"), "a") self.assertEqual(node, Node([Node(["a", "b"], "OR"), "a"], "AND")) def test_negate(self): # negated is False by default self.assertFalse(self.node1.negated) self.node1.negate() self.assertTrue(self.node1.negated) self.node1.negate() self.assertFalse(self.node1.negated) def test_deepcopy(self): node4 = copy.copy(self.node1) node5 = copy.deepcopy(self.node1) self.assertIs(self.node1.children, node4.children) self.assertIsNot(self.node1.children, node5.children) def test_eq_children(self): node = Node(self.node1_children) self.assertEqual(node, self.node1) self.assertNotEqual(node, self.node2) def test_eq_connector(self): new_node = Node(connector="NEW") default_node = Node(connector="DEFAULT") self.assertEqual(default_node, self.node2) self.assertNotEqual(default_node, new_node) def test_eq_negated(self): node = Node(negated=False) negated = Node(negated=True) self.assertNotEqual(negated, node)
ce958def37dcb7457311030a74317434529bd82ec58928f3479862867c5445e8
from django.template import Context, Template from django.test import SimpleTestCase from django.utils import html, translation from django.utils.functional import Promise, lazy, lazystr from django.utils.safestring import SafeData, SafeString, mark_safe from django.utils.translation import gettext_lazy class customescape(str): def __html__(self): # Implement specific and wrong escaping in order to be able to detect # when it runs. return self.replace("<", "<<").replace(">", ">>") class SafeStringTest(SimpleTestCase): def assertRenderEqual(self, tpl, expected, **context): context = Context(context) tpl = Template(tpl) self.assertEqual(tpl.render(context), expected) def test_mark_safe(self): s = mark_safe("a&b") self.assertRenderEqual("{{ s }}", "a&b", s=s) self.assertRenderEqual("{{ s|force_escape }}", "a&amp;b", s=s) def test_mark_safe_str(self): """ Calling str() on a SafeString instance doesn't lose the safe status. """ s = mark_safe("a&b") self.assertIsInstance(str(s), type(s)) def test_mark_safe_object_implementing_dunder_html(self): e = customescape("<a&b>") s = mark_safe(e) self.assertIs(s, e) self.assertRenderEqual("{{ s }}", "<<a&b>>", s=s) self.assertRenderEqual("{{ s|force_escape }}", "&lt;a&amp;b&gt;", s=s) def test_mark_safe_lazy(self): safe_s = mark_safe(lazystr("a&b")) self.assertIsInstance(safe_s, Promise) self.assertRenderEqual("{{ s }}", "a&b", s=safe_s) self.assertIsInstance(str(safe_s), SafeData) def test_mark_safe_lazy_i18n(self): s = mark_safe(gettext_lazy("name")) tpl = Template("{{ s }}") with translation.override("fr"): self.assertEqual(tpl.render(Context({"s": s})), "nom") def test_mark_safe_object_implementing_dunder_str(self): class Obj: def __str__(self): return "<obj>" s = mark_safe(Obj()) self.assertRenderEqual("{{ s }}", "<obj>", s=s) def test_mark_safe_result_implements_dunder_html(self): self.assertEqual(mark_safe("a&b").__html__(), "a&b") def test_mark_safe_lazy_result_implements_dunder_html(self): self.assertEqual(mark_safe(lazystr("a&b")).__html__(), "a&b") def test_add_lazy_safe_text_and_safe_text(self): s = html.escape(lazystr("a")) s += mark_safe("&b") self.assertRenderEqual("{{ s }}", "a&b", s=s) s = html.escapejs(lazystr("a")) s += mark_safe("&b") self.assertRenderEqual("{{ s }}", "a&b", s=s) def test_mark_safe_as_decorator(self): """ mark_safe used as a decorator leaves the result of a function unchanged. """ def clean_string_provider(): return "<html><body>dummy</body></html>" self.assertEqual(mark_safe(clean_string_provider)(), clean_string_provider()) def test_mark_safe_decorator_does_not_affect_dunder_html(self): """ mark_safe doesn't affect a callable that has an __html__() method. """ class SafeStringContainer: def __html__(self): return "<html></html>" self.assertIs(mark_safe(SafeStringContainer), SafeStringContainer) def test_mark_safe_decorator_does_not_affect_promises(self): """ mark_safe doesn't affect lazy strings (Promise objects). """ def html_str(): return "<html></html>" lazy_str = lazy(html_str, str)() self.assertEqual(mark_safe(lazy_str), html_str()) def test_default_additional_attrs(self): s = SafeString("a&b") msg = "object has no attribute 'dynamic_attr'" with self.assertRaisesMessage(AttributeError, msg): s.dynamic_attr = True def test_default_safe_data_additional_attrs(self): s = SafeData() msg = "object has no attribute 'dynamic_attr'" with self.assertRaisesMessage(AttributeError, msg): s.dynamic_attr = True
120ea560f56ab06592a596b7fbfa8ec58627ff19347fe5f73ee066e545587fe2
from django.test import SimpleTestCase from django.utils.connection import BaseConnectionHandler class BaseConnectionHandlerTests(SimpleTestCase): def test_create_connection(self): handler = BaseConnectionHandler() msg = "Subclasses must implement create_connection()." with self.assertRaisesMessage(NotImplementedError, msg): handler.create_connection(None)
23258f12cccb16a8a6dd1409281ef3ef8d7ab3c1cbe27d8d53b783ffc3047371
from django.test import SimpleTestCase from django.utils.hashable import make_hashable class TestHashable(SimpleTestCase): def test_equal(self): tests = ( ([], ()), (["a", 1], ("a", 1)), ({}, ()), ({"a"}, ("a",)), (frozenset({"a"}), {"a"}), ({"a": 1, "b": 2}, (("a", 1), ("b", 2))), ({"b": 2, "a": 1}, (("a", 1), ("b", 2))), (("a", ["b", 1]), ("a", ("b", 1))), (("a", {"b": 1}), ("a", (("b", 1),))), ) for value, expected in tests: with self.subTest(value=value): self.assertEqual(make_hashable(value), expected) def test_count_equal(self): tests = ( ({"a": 1, "b": ["a", 1]}, (("a", 1), ("b", ("a", 1)))), ({"a": 1, "b": ("a", [1, 2])}, (("a", 1), ("b", ("a", (1, 2))))), ) for value, expected in tests: with self.subTest(value=value): self.assertCountEqual(make_hashable(value), expected) def test_unhashable(self): class Unhashable: __hash__ = None with self.assertRaisesMessage(TypeError, "unhashable type: 'Unhashable'"): make_hashable(Unhashable())
eb72416411c51c35a5f443f3f8d38bab9f2dc178c4330cb296cd813ac7184151
from decimal import Decimal from sys import float_info from django.test import SimpleTestCase from django.utils.numberformat import format as nformat class TestNumberFormat(SimpleTestCase): def test_format_number(self): self.assertEqual(nformat(1234, "."), "1234") self.assertEqual(nformat(1234.2, "."), "1234.2") self.assertEqual(nformat(1234, ".", decimal_pos=2), "1234.00") self.assertEqual(nformat(1234, ".", grouping=2, thousand_sep=","), "1234") self.assertEqual( nformat(1234, ".", grouping=2, thousand_sep=",", force_grouping=True), "12,34", ) self.assertEqual(nformat(-1234.33, ".", decimal_pos=1), "-1234.3") # The use_l10n parameter can force thousand grouping behavior. with self.settings(USE_THOUSAND_SEPARATOR=True): self.assertEqual( nformat(1234, ".", grouping=3, thousand_sep=",", use_l10n=False), "1234" ) self.assertEqual( nformat(1234, ".", grouping=3, thousand_sep=",", use_l10n=True), "1,234" ) def test_format_string(self): self.assertEqual(nformat("1234", "."), "1234") self.assertEqual(nformat("1234.2", "."), "1234.2") self.assertEqual(nformat("1234", ".", decimal_pos=2), "1234.00") self.assertEqual(nformat("1234", ".", grouping=2, thousand_sep=","), "1234") self.assertEqual( nformat("1234", ".", grouping=2, thousand_sep=",", force_grouping=True), "12,34", ) self.assertEqual(nformat("-1234.33", ".", decimal_pos=1), "-1234.3") self.assertEqual( nformat( "10000", ".", grouping=3, thousand_sep="comma", force_grouping=True ), "10comma000", ) def test_large_number(self): most_max = ( "{}179769313486231570814527423731704356798070567525844996" "598917476803157260780028538760589558632766878171540458953" "514382464234321326889464182768467546703537516986049910576" "551282076245490090389328944075868508455133942304583236903" "222948165808559332123348274797826204144723168738177180919" "29988125040402618412485836{}" ) most_max2 = ( "{}35953862697246314162905484746340871359614113505168999" "31978349536063145215600570775211791172655337563430809179" "07028764928468642653778928365536935093407075033972099821" "15310256415249098018077865788815173701691026788460916647" "38064458963316171186642466965495956524082894463374763543" "61838599762500808052368249716736" ) int_max = int(float_info.max) self.assertEqual(nformat(int_max, "."), most_max.format("", "8")) self.assertEqual(nformat(int_max + 1, "."), most_max.format("", "9")) self.assertEqual(nformat(int_max * 2, "."), most_max2.format("")) self.assertEqual(nformat(0 - int_max, "."), most_max.format("-", "8")) self.assertEqual(nformat(-1 - int_max, "."), most_max.format("-", "9")) self.assertEqual(nformat(-2 * int_max, "."), most_max2.format("-")) def test_float_numbers(self): tests = [ (9e-10, 10, "0.0000000009"), (9e-19, 2, "0.00"), (0.00000000000099, 0, "0"), (0.00000000000099, 13, "0.0000000000009"), (1e16, None, "10000000000000000"), (1e16, 2, "10000000000000000.00"), # A float without a fractional part (3.) results in a ".0" when no # decimal_pos is given. Contrast that with the Decimal('3.') case # in test_decimal_numbers which doesn't return a fractional part. (3.0, None, "3.0"), ] for value, decimal_pos, expected_value in tests: with self.subTest(value=value, decimal_pos=decimal_pos): self.assertEqual(nformat(value, ".", decimal_pos), expected_value) # Thousand grouping behavior. self.assertEqual( nformat(1e16, ".", thousand_sep=",", grouping=3, force_grouping=True), "10,000,000,000,000,000", ) self.assertEqual( nformat( 1e16, ".", decimal_pos=2, thousand_sep=",", grouping=3, force_grouping=True, ), "10,000,000,000,000,000.00", ) def test_decimal_numbers(self): self.assertEqual(nformat(Decimal("1234"), "."), "1234") self.assertEqual(nformat(Decimal("1234.2"), "."), "1234.2") self.assertEqual(nformat(Decimal("1234"), ".", decimal_pos=2), "1234.00") self.assertEqual( nformat(Decimal("1234"), ".", grouping=2, thousand_sep=","), "1234" ) self.assertEqual( nformat( Decimal("1234"), ".", grouping=2, thousand_sep=",", force_grouping=True ), "12,34", ) self.assertEqual(nformat(Decimal("-1234.33"), ".", decimal_pos=1), "-1234.3") self.assertEqual( nformat(Decimal("0.00000001"), ".", decimal_pos=8), "0.00000001" ) self.assertEqual(nformat(Decimal("9e-19"), ".", decimal_pos=2), "0.00") self.assertEqual(nformat(Decimal(".00000000000099"), ".", decimal_pos=0), "0") self.assertEqual( nformat( Decimal("1e16"), ".", thousand_sep=",", grouping=3, force_grouping=True ), "10,000,000,000,000,000", ) self.assertEqual( nformat( Decimal("1e16"), ".", decimal_pos=2, thousand_sep=",", grouping=3, force_grouping=True, ), "10,000,000,000,000,000.00", ) self.assertEqual(nformat(Decimal("3."), "."), "3") self.assertEqual(nformat(Decimal("3.0"), "."), "3.0") # Very large & small numbers. tests = [ ("9e9999", None, "9e+9999"), ("9e9999", 3, "9.000e+9999"), ("9e201", None, "9e+201"), ("9e200", None, "9e+200"), ("1.2345e999", 2, "1.23e+999"), ("9e-999", None, "9e-999"), ("1e-7", 8, "0.00000010"), ("1e-8", 8, "0.00000001"), ("1e-9", 8, "0.00000000"), ("1e-10", 8, "0.00000000"), ("1e-11", 8, "0.00000000"), ("1" + ("0" * 300), 3, "1.000e+300"), ("0.{}1234".format("0" * 299), 3, "0.000"), ] for value, decimal_pos, expected_value in tests: with self.subTest(value=value): self.assertEqual( nformat(Decimal(value), ".", decimal_pos), expected_value ) def test_decimal_subclass(self): class EuroDecimal(Decimal): """ Wrapper for Decimal which prefixes each amount with the € symbol. """ def __format__(self, specifier, **kwargs): amount = super().__format__(specifier, **kwargs) return "€ {}".format(amount) price = EuroDecimal("1.23") self.assertEqual(nformat(price, ","), "€ 1,23")
9b8d6dd925f0b994f6fb4ff80fe55b7b4eb8d54e76e59149f7b095981e226ea7
from unittest import mock from django.test import SimpleTestCase from django.test.utils import ignore_warnings from django.utils.deprecation import RemovedInDjango50Warning from django.utils.functional import cached_property, classproperty, lazy class FunctionalTests(SimpleTestCase): def test_lazy(self): t = lazy(lambda: tuple(range(3)), list, tuple) for a, b in zip(t(), range(3)): self.assertEqual(a, b) def test_lazy_base_class(self): """lazy also finds base class methods in the proxy object""" class Base: def base_method(self): pass class Klazz(Base): pass t = lazy(lambda: Klazz(), Klazz)() self.assertIn("base_method", dir(t)) def test_lazy_base_class_override(self): """lazy finds the correct (overridden) method implementation""" class Base: def method(self): return "Base" class Klazz(Base): def method(self): return "Klazz" t = lazy(lambda: Klazz(), Base)() self.assertEqual(t.method(), "Klazz") def test_lazy_object_to_string(self): class Klazz: def __str__(self): return "Î am ā Ǩlâzz." def __bytes__(self): return b"\xc3\x8e am \xc4\x81 binary \xc7\xa8l\xc3\xa2zz." t = lazy(lambda: Klazz(), Klazz)() self.assertEqual(str(t), "Î am ā Ǩlâzz.") self.assertEqual(bytes(t), b"\xc3\x8e am \xc4\x81 binary \xc7\xa8l\xc3\xa2zz.") def assertCachedPropertyWorks(self, attr, Class): with self.subTest(attr=attr): def get(source): return getattr(source, attr) obj = Class() class SubClass(Class): pass subobj = SubClass() # Docstring is preserved. self.assertEqual(get(Class).__doc__, "Here is the docstring...") self.assertEqual(get(SubClass).__doc__, "Here is the docstring...") # It's cached. self.assertEqual(get(obj), get(obj)) self.assertEqual(get(subobj), get(subobj)) # The correct value is returned. self.assertEqual(get(obj)[0], 1) self.assertEqual(get(subobj)[0], 1) # State isn't shared between instances. obj2 = Class() subobj2 = SubClass() self.assertNotEqual(get(obj), get(obj2)) self.assertNotEqual(get(subobj), get(subobj2)) # It behaves like a property when there's no instance. self.assertIsInstance(get(Class), cached_property) self.assertIsInstance(get(SubClass), cached_property) # 'other_value' doesn't become a property. self.assertTrue(callable(obj.other_value)) self.assertTrue(callable(subobj.other_value)) def test_cached_property(self): """cached_property caches its value and behaves like a property.""" class Class: @cached_property def value(self): """Here is the docstring...""" return 1, object() @cached_property def __foo__(self): """Here is the docstring...""" return 1, object() def other_value(self): """Here is the docstring...""" return 1, object() other = cached_property(other_value) attrs = ["value", "other", "__foo__"] for attr in attrs: self.assertCachedPropertyWorks(attr, Class) @ignore_warnings(category=RemovedInDjango50Warning) def test_cached_property_name(self): class Class: def other_value(self): """Here is the docstring...""" return 1, object() other = cached_property(other_value, name="other") other2 = cached_property(other_value, name="different_name") self.assertCachedPropertyWorks("other", Class) # An explicit name is ignored. obj = Class() obj.other2 self.assertFalse(hasattr(obj, "different_name")) def test_cached_property_name_deprecation_warning(self): def value(self): return 1 msg = "The name argument is deprecated as it's unnecessary as of Python 3.6." with self.assertWarnsMessage(RemovedInDjango50Warning, msg): cached_property(value, name="other_name") def test_cached_property_auto_name(self): """ cached_property caches its value and behaves like a property on mangled methods or when the name kwarg isn't set. """ class Class: @cached_property def __value(self): """Here is the docstring...""" return 1, object() def other_value(self): """Here is the docstring...""" return 1, object() other = cached_property(other_value) attrs = ["_Class__value", "other"] for attr in attrs: self.assertCachedPropertyWorks(attr, Class) def test_cached_property_reuse_different_names(self): """Disallow this case because the decorated function wouldn't be cached.""" with self.assertRaises(RuntimeError) as ctx: class ReusedCachedProperty: @cached_property def a(self): pass b = a self.assertEqual( str(ctx.exception.__context__), str( TypeError( "Cannot assign the same cached_property to two different " "names ('a' and 'b')." ) ), ) def test_cached_property_reuse_same_name(self): """ Reusing a cached_property on different classes under the same name is allowed. """ counter = 0 @cached_property def _cp(_self): nonlocal counter counter += 1 return counter class A: cp = _cp class B: cp = _cp a = A() b = B() self.assertEqual(a.cp, 1) self.assertEqual(b.cp, 2) self.assertEqual(a.cp, 1) def test_cached_property_set_name_not_called(self): cp = cached_property(lambda s: None) class Foo: pass Foo.cp = cp msg = ( "Cannot use cached_property instance without calling __set_name__() on it." ) with self.assertRaisesMessage(TypeError, msg): Foo().cp def test_lazy_add(self): lazy_4 = lazy(lambda: 4, int) lazy_5 = lazy(lambda: 5, int) self.assertEqual(lazy_4() + lazy_5(), 9) def test_lazy_equality(self): """ == and != work correctly for Promises. """ lazy_a = lazy(lambda: 4, int) lazy_b = lazy(lambda: 4, int) lazy_c = lazy(lambda: 5, int) self.assertEqual(lazy_a(), lazy_b()) self.assertNotEqual(lazy_b(), lazy_c()) def test_lazy_repr_text(self): original_object = "Lazy translation text" lazy_obj = lazy(lambda: original_object, str) self.assertEqual(repr(original_object), repr(lazy_obj())) def test_lazy_repr_int(self): original_object = 15 lazy_obj = lazy(lambda: original_object, int) self.assertEqual(repr(original_object), repr(lazy_obj())) def test_lazy_repr_bytes(self): original_object = b"J\xc3\xbcst a str\xc3\xadng" lazy_obj = lazy(lambda: original_object, bytes) self.assertEqual(repr(original_object), repr(lazy_obj())) def test_lazy_class_preparation_caching(self): # lazy() should prepare the proxy class only once i.e. the first time # it's used. lazified = lazy(lambda: 0, int) __proxy__ = lazified().__class__ with mock.patch.object(__proxy__, "__prepare_class__") as mocked: lazified() mocked.assert_not_called() def test_lazy_bytes_and_str_result_classes(self): lazy_obj = lazy(lambda: "test", str, bytes) msg = "Cannot call lazy() with both bytes and text return types." with self.assertRaisesMessage(ValueError, msg): lazy_obj() def test_classproperty_getter(self): class Foo: foo_attr = 123 def __init__(self): self.foo_attr = 456 @classproperty def foo(cls): return cls.foo_attr class Bar: bar = classproperty() @bar.getter def bar(cls): return 123 self.assertEqual(Foo.foo, 123) self.assertEqual(Foo().foo, 123) self.assertEqual(Bar.bar, 123) self.assertEqual(Bar().bar, 123) def test_classproperty_override_getter(self): class Foo: @classproperty def foo(cls): return 123 @foo.getter def foo(cls): return 456 self.assertEqual(Foo.foo, 456) self.assertEqual(Foo().foo, 456)
41b665adaece9f24e01a85a00c8def85c2f88af9a8d6ffe5482b38ae08c50514
import hashlib import unittest from django.test import SimpleTestCase from django.utils.crypto import ( InvalidAlgorithm, constant_time_compare, pbkdf2, salted_hmac, ) class TestUtilsCryptoMisc(SimpleTestCase): def test_constant_time_compare(self): # It's hard to test for constant time, just test the result. self.assertTrue(constant_time_compare(b"spam", b"spam")) self.assertFalse(constant_time_compare(b"spam", b"eggs")) self.assertTrue(constant_time_compare("spam", "spam")) self.assertFalse(constant_time_compare("spam", "eggs")) def test_salted_hmac(self): tests = [ ((b"salt", b"value"), {}, "b51a2e619c43b1ca4f91d15c57455521d71d61eb"), (("salt", "value"), {}, "b51a2e619c43b1ca4f91d15c57455521d71d61eb"), ( ("salt", "value"), {"secret": "abcdefg"}, "8bbee04ccddfa24772d1423a0ba43bd0c0e24b76", ), ( ("salt", "value"), {"secret": "x" * hashlib.sha1().block_size}, "bd3749347b412b1b0a9ea65220e55767ac8e96b0", ), ( ("salt", "value"), {"algorithm": "sha256"}, "ee0bf789e4e009371a5372c90f73fcf17695a8439c9108b0480f14e347b3f9ec", ), ( ("salt", "value"), { "algorithm": "blake2b", "secret": "x" * hashlib.blake2b().block_size, }, "fc6b9800a584d40732a07fa33fb69c35211269441823bca431a143853c32f" "e836cf19ab881689528ede647dac412170cd5d3407b44c6d0f44630690c54" "ad3d58", ), ] for args, kwargs, digest in tests: with self.subTest(args=args, kwargs=kwargs): self.assertEqual(salted_hmac(*args, **kwargs).hexdigest(), digest) def test_invalid_algorithm(self): msg = "'whatever' is not an algorithm accepted by the hashlib module." with self.assertRaisesMessage(InvalidAlgorithm, msg): salted_hmac("salt", "value", algorithm="whatever") class TestUtilsCryptoPBKDF2(unittest.TestCase): # https://tools.ietf.org/html/draft-josefsson-pbkdf2-test-vectors-06 rfc_vectors = [ { "args": { "password": "password", "salt": "salt", "iterations": 1, "dklen": 20, "digest": hashlib.sha1, }, "result": "0c60c80f961f0e71f3a9b524af6012062fe037a6", }, { "args": { "password": "password", "salt": "salt", "iterations": 2, "dklen": 20, "digest": hashlib.sha1, }, "result": "ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957", }, { "args": { "password": "password", "salt": "salt", "iterations": 4096, "dklen": 20, "digest": hashlib.sha1, }, "result": "4b007901b765489abead49d926f721d065a429c1", }, # # this takes way too long :( # { # "args": { # "password": "password", # "salt": "salt", # "iterations": 16777216, # "dklen": 20, # "digest": hashlib.sha1, # }, # "result": "eefe3d61cd4da4e4e9945b3d6ba2158c2634e984", # }, { "args": { "password": "passwordPASSWORDpassword", "salt": "saltSALTsaltSALTsaltSALTsaltSALTsalt", "iterations": 4096, "dklen": 25, "digest": hashlib.sha1, }, "result": "3d2eec4fe41c849b80c8d83662c0e44a8b291a964cf2f07038", }, { "args": { "password": "pass\0word", "salt": "sa\0lt", "iterations": 4096, "dklen": 16, "digest": hashlib.sha1, }, "result": "56fa6aa75548099dcc37d7f03425e0c3", }, ] regression_vectors = [ { "args": { "password": "password", "salt": "salt", "iterations": 1, "dklen": 20, "digest": hashlib.sha256, }, "result": "120fb6cffcf8b32c43e7225256c4f837a86548c9", }, { "args": { "password": "password", "salt": "salt", "iterations": 1, "dklen": 20, "digest": hashlib.sha512, }, "result": "867f70cf1ade02cff3752599a3a53dc4af34c7a6", }, { "args": { "password": "password", "salt": "salt", "iterations": 1000, "dklen": 0, "digest": hashlib.sha512, }, "result": ( "afe6c5530785b6cc6b1c6453384731bd5ee432ee" "549fd42fb6695779ad8a1c5bf59de69c48f774ef" "c4007d5298f9033c0241d5ab69305e7b64eceeb8d" "834cfec" ), }, # Check leading zeros are not stripped (#17481) { "args": { "password": b"\xba", "salt": "salt", "iterations": 1, "dklen": 20, "digest": hashlib.sha1, }, "result": "0053d3b91a7f1e54effebd6d68771e8a6e0b2c5b", }, ] def test_public_vectors(self): for vector in self.rfc_vectors: result = pbkdf2(**vector["args"]) self.assertEqual(result.hex(), vector["result"]) def test_regression_vectors(self): for vector in self.regression_vectors: result = pbkdf2(**vector["args"]) self.assertEqual(result.hex(), vector["result"]) def test_default_hmac_alg(self): kwargs = { "password": b"password", "salt": b"salt", "iterations": 1, "dklen": 20, } self.assertEqual( pbkdf2(**kwargs), hashlib.pbkdf2_hmac(hash_name=hashlib.sha256().name, **kwargs), )
8e0c4ba2034305a239c2f232a41999bc52c874d152f440ac2de227a0c862f1ef
import platform def on_macos_with_hfs(): """ MacOS 10.13 (High Sierra) and lower can use HFS+ as a filesystem. HFS+ has a time resolution of only one second which can be too low for some of the tests. """ macos_version = platform.mac_ver()[0] if macos_version != "": parsed_macos_version = tuple(int(x) for x in macos_version.split(".")) return parsed_macos_version < (10, 14) return False
023294ac9604bab707a2c749e1cdc767b0283b720b45901103cf8dddb5eef22b
import contextlib import os import py_compile import shutil import sys import tempfile import threading import time import types import weakref import zipfile from importlib import import_module from pathlib import Path from subprocess import CompletedProcess from unittest import mock, skip, skipIf try: import zoneinfo except ImportError: from backports import zoneinfo import django.__main__ from django.apps.registry import Apps from django.test import SimpleTestCase from django.test.utils import extend_sys_path from django.utils import autoreload from django.utils.autoreload import WatchmanUnavailable from .test_module import __main__ as test_main from .test_module import main_module as test_main_module from .utils import on_macos_with_hfs class TestIterModulesAndFiles(SimpleTestCase): def import_and_cleanup(self, name): import_module(name) self.addCleanup(lambda: sys.path_importer_cache.clear()) self.addCleanup(lambda: sys.modules.pop(name, None)) def clear_autoreload_caches(self): autoreload.iter_modules_and_files.cache_clear() def assertFileFound(self, filename): # Some temp directories are symlinks. Python resolves these fully while # importing. resolved_filename = filename.resolve(strict=True) self.clear_autoreload_caches() # Test uncached access self.assertIn( resolved_filename, list(autoreload.iter_all_python_module_files()) ) # Test cached access self.assertIn( resolved_filename, list(autoreload.iter_all_python_module_files()) ) self.assertEqual(autoreload.iter_modules_and_files.cache_info().hits, 1) def assertFileNotFound(self, filename): resolved_filename = filename.resolve(strict=True) self.clear_autoreload_caches() # Test uncached access self.assertNotIn( resolved_filename, list(autoreload.iter_all_python_module_files()) ) # Test cached access self.assertNotIn( resolved_filename, list(autoreload.iter_all_python_module_files()) ) self.assertEqual(autoreload.iter_modules_and_files.cache_info().hits, 1) def temporary_file(self, filename): dirname = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, dirname) return Path(dirname) / filename def test_paths_are_pathlib_instances(self): for filename in autoreload.iter_all_python_module_files(): self.assertIsInstance(filename, Path) def test_file_added(self): """ When a file is added, it's returned by iter_all_python_module_files(). """ filename = self.temporary_file("test_deleted_removed_module.py") filename.touch() with extend_sys_path(str(filename.parent)): self.import_and_cleanup("test_deleted_removed_module") self.assertFileFound(filename.absolute()) def test_check_errors(self): """ When a file containing an error is imported in a function wrapped by check_errors(), gen_filenames() returns it. """ filename = self.temporary_file("test_syntax_error.py") filename.write_text("Ceci n'est pas du Python.") with extend_sys_path(str(filename.parent)): try: with self.assertRaises(SyntaxError): autoreload.check_errors(import_module)("test_syntax_error") finally: autoreload._exception = None self.assertFileFound(filename) def test_check_errors_catches_all_exceptions(self): """ Since Python may raise arbitrary exceptions when importing code, check_errors() must catch Exception, not just some subclasses. """ filename = self.temporary_file("test_exception.py") filename.write_text("raise Exception") with extend_sys_path(str(filename.parent)): try: with self.assertRaises(Exception): autoreload.check_errors(import_module)("test_exception") finally: autoreload._exception = None self.assertFileFound(filename) def test_zip_reload(self): """ Modules imported from zipped files have their archive location included in the result. """ zip_file = self.temporary_file("zip_import.zip") with zipfile.ZipFile(str(zip_file), "w", zipfile.ZIP_DEFLATED) as zipf: zipf.writestr("test_zipped_file.py", "") with extend_sys_path(str(zip_file)): self.import_and_cleanup("test_zipped_file") self.assertFileFound(zip_file) def test_bytecode_conversion_to_source(self): """.pyc and .pyo files are included in the files list.""" filename = self.temporary_file("test_compiled.py") filename.touch() compiled_file = Path( py_compile.compile(str(filename), str(filename.with_suffix(".pyc"))) ) filename.unlink() with extend_sys_path(str(compiled_file.parent)): self.import_and_cleanup("test_compiled") self.assertFileFound(compiled_file) def test_weakref_in_sys_module(self): """iter_all_python_module_file() ignores weakref modules.""" time_proxy = weakref.proxy(time) sys.modules["time_proxy"] = time_proxy self.addCleanup(lambda: sys.modules.pop("time_proxy", None)) list(autoreload.iter_all_python_module_files()) # No crash. def test_module_without_spec(self): module = types.ModuleType("test_module") del module.__spec__ self.assertEqual( autoreload.iter_modules_and_files((module,), frozenset()), frozenset() ) def test_main_module_is_resolved(self): main_module = sys.modules["__main__"] self.assertFileFound(Path(main_module.__file__)) def test_main_module_without_file_is_not_resolved(self): fake_main = types.ModuleType("__main__") self.assertEqual( autoreload.iter_modules_and_files((fake_main,), frozenset()), frozenset() ) def test_path_with_embedded_null_bytes(self): for path in ( "embedded_null_byte\x00.py", "di\x00rectory/embedded_null_byte.py", ): with self.subTest(path=path): self.assertEqual( autoreload.iter_modules_and_files((), frozenset([path])), frozenset(), ) class TestChildArguments(SimpleTestCase): @mock.patch.dict(sys.modules, {"__main__": django.__main__}) @mock.patch("sys.argv", [django.__main__.__file__, "runserver"]) @mock.patch("sys.warnoptions", []) @mock.patch("sys._xoptions", {}) def test_run_as_module(self): self.assertEqual( autoreload.get_child_arguments(), [sys.executable, "-m", "django", "runserver"], ) @mock.patch.dict(sys.modules, {"__main__": test_main}) @mock.patch("sys.argv", [test_main.__file__, "runserver"]) @mock.patch("sys.warnoptions", []) @mock.patch("sys._xoptions", {}) def test_run_as_non_django_module(self): self.assertEqual( autoreload.get_child_arguments(), [sys.executable, "-m", "utils_tests.test_module", "runserver"], ) @mock.patch.dict(sys.modules, {"__main__": test_main_module}) @mock.patch("sys.argv", [test_main.__file__, "runserver"]) @mock.patch("sys.warnoptions", []) @mock.patch("sys._xoptions", {}) def test_run_as_non_django_module_non_package(self): self.assertEqual( autoreload.get_child_arguments(), [sys.executable, "-m", "utils_tests.test_module.main_module", "runserver"], ) @mock.patch("__main__.__spec__", None) @mock.patch("sys.argv", [__file__, "runserver"]) @mock.patch("sys.warnoptions", ["error"]) @mock.patch("sys._xoptions", {}) def test_warnoptions(self): self.assertEqual( autoreload.get_child_arguments(), [sys.executable, "-Werror", __file__, "runserver"], ) @mock.patch("sys.argv", [__file__, "runserver"]) @mock.patch("sys.warnoptions", []) @mock.patch("sys._xoptions", {"utf8": True, "a": "b"}) def test_xoptions(self): self.assertEqual( autoreload.get_child_arguments(), [sys.executable, "-Xutf8", "-Xa=b", __file__, "runserver"], ) @mock.patch("__main__.__spec__", None) @mock.patch("sys.warnoptions", []) def test_exe_fallback(self): with tempfile.TemporaryDirectory() as tmpdir: exe_path = Path(tmpdir) / "django-admin.exe" exe_path.touch() with mock.patch("sys.argv", [exe_path.with_suffix(""), "runserver"]): self.assertEqual( autoreload.get_child_arguments(), [exe_path, "runserver"] ) @mock.patch("__main__.__spec__", None) @mock.patch("sys.warnoptions", []) @mock.patch("sys._xoptions", {}) def test_entrypoint_fallback(self): with tempfile.TemporaryDirectory() as tmpdir: script_path = Path(tmpdir) / "django-admin-script.py" script_path.touch() with mock.patch( "sys.argv", [script_path.with_name("django-admin"), "runserver"] ): self.assertEqual( autoreload.get_child_arguments(), [sys.executable, script_path, "runserver"], ) @mock.patch("__main__.__spec__", None) @mock.patch("sys.argv", ["does-not-exist", "runserver"]) @mock.patch("sys.warnoptions", []) def test_raises_runtimeerror(self): msg = "Script does-not-exist does not exist." with self.assertRaisesMessage(RuntimeError, msg): autoreload.get_child_arguments() @mock.patch("sys.argv", [__file__, "runserver"]) @mock.patch("sys.warnoptions", []) @mock.patch("sys._xoptions", {}) def test_module_no_spec(self): module = types.ModuleType("test_module") del module.__spec__ with mock.patch.dict(sys.modules, {"__main__": module}): self.assertEqual( autoreload.get_child_arguments(), [sys.executable, __file__, "runserver"], ) class TestUtilities(SimpleTestCase): def test_is_django_module(self): for module, expected in ((zoneinfo, False), (sys, False), (autoreload, True)): with self.subTest(module=module): self.assertIs(autoreload.is_django_module(module), expected) def test_is_django_path(self): for module, expected in ( (zoneinfo.__file__, False), (contextlib.__file__, False), (autoreload.__file__, True), ): with self.subTest(module=module): self.assertIs(autoreload.is_django_path(module), expected) class TestCommonRoots(SimpleTestCase): def test_common_roots(self): paths = ( Path("/first/second"), Path("/first/second/third"), Path("/first/"), Path("/root/first/"), ) results = autoreload.common_roots(paths) self.assertCountEqual(results, [Path("/first/"), Path("/root/first/")]) class TestSysPathDirectories(SimpleTestCase): def setUp(self): self._directory = tempfile.TemporaryDirectory() self.directory = Path(self._directory.name).resolve(strict=True).absolute() self.file = self.directory / "test" self.file.touch() def tearDown(self): self._directory.cleanup() def test_sys_paths_with_directories(self): with extend_sys_path(str(self.file)): paths = list(autoreload.sys_path_directories()) self.assertIn(self.file.parent, paths) def test_sys_paths_non_existing(self): nonexistent_file = Path(self.directory.name) / "does_not_exist" with extend_sys_path(str(nonexistent_file)): paths = list(autoreload.sys_path_directories()) self.assertNotIn(nonexistent_file, paths) self.assertNotIn(nonexistent_file.parent, paths) def test_sys_paths_absolute(self): paths = list(autoreload.sys_path_directories()) self.assertTrue(all(p.is_absolute() for p in paths)) def test_sys_paths_directories(self): with extend_sys_path(str(self.directory)): paths = list(autoreload.sys_path_directories()) self.assertIn(self.directory, paths) class GetReloaderTests(SimpleTestCase): @mock.patch("django.utils.autoreload.WatchmanReloader") def test_watchman_unavailable(self, mocked_watchman): mocked_watchman.check_availability.side_effect = WatchmanUnavailable self.assertIsInstance(autoreload.get_reloader(), autoreload.StatReloader) @mock.patch.object(autoreload.WatchmanReloader, "check_availability") def test_watchman_available(self, mocked_available): # If WatchmanUnavailable isn't raised, Watchman will be chosen. mocked_available.return_value = None result = autoreload.get_reloader() self.assertIsInstance(result, autoreload.WatchmanReloader) class RunWithReloaderTests(SimpleTestCase): @mock.patch.dict(os.environ, {autoreload.DJANGO_AUTORELOAD_ENV: "true"}) @mock.patch("django.utils.autoreload.get_reloader") def test_swallows_keyboard_interrupt(self, mocked_get_reloader): mocked_get_reloader.side_effect = KeyboardInterrupt() autoreload.run_with_reloader(lambda: None) # No exception @mock.patch.dict(os.environ, {autoreload.DJANGO_AUTORELOAD_ENV: "false"}) @mock.patch("django.utils.autoreload.restart_with_reloader") def test_calls_sys_exit(self, mocked_restart_reloader): mocked_restart_reloader.return_value = 1 with self.assertRaises(SystemExit) as exc: autoreload.run_with_reloader(lambda: None) self.assertEqual(exc.exception.code, 1) @mock.patch.dict(os.environ, {autoreload.DJANGO_AUTORELOAD_ENV: "true"}) @mock.patch("django.utils.autoreload.start_django") @mock.patch("django.utils.autoreload.get_reloader") def test_calls_start_django(self, mocked_reloader, mocked_start_django): mocked_reloader.return_value = mock.sentinel.RELOADER autoreload.run_with_reloader(mock.sentinel.METHOD) self.assertEqual(mocked_start_django.call_count, 1) self.assertSequenceEqual( mocked_start_django.call_args[0], [mock.sentinel.RELOADER, mock.sentinel.METHOD], ) class StartDjangoTests(SimpleTestCase): @mock.patch("django.utils.autoreload.StatReloader") def test_watchman_becomes_unavailable(self, mocked_stat): mocked_stat.should_stop.return_value = True fake_reloader = mock.MagicMock() fake_reloader.should_stop = False fake_reloader.run.side_effect = autoreload.WatchmanUnavailable() autoreload.start_django(fake_reloader, lambda: None) self.assertEqual(mocked_stat.call_count, 1) @mock.patch("django.utils.autoreload.ensure_echo_on") def test_echo_on_called(self, mocked_echo): fake_reloader = mock.MagicMock() autoreload.start_django(fake_reloader, lambda: None) self.assertEqual(mocked_echo.call_count, 1) @mock.patch("django.utils.autoreload.check_errors") def test_check_errors_called(self, mocked_check_errors): fake_method = mock.MagicMock(return_value=None) fake_reloader = mock.MagicMock() autoreload.start_django(fake_reloader, fake_method) self.assertCountEqual(mocked_check_errors.call_args[0], [fake_method]) @mock.patch("threading.Thread") @mock.patch("django.utils.autoreload.check_errors") def test_starts_thread_with_args(self, mocked_check_errors, mocked_thread): fake_reloader = mock.MagicMock() fake_main_func = mock.MagicMock() fake_thread = mock.MagicMock() mocked_check_errors.return_value = fake_main_func mocked_thread.return_value = fake_thread autoreload.start_django(fake_reloader, fake_main_func, 123, abc=123) self.assertEqual(mocked_thread.call_count, 1) self.assertEqual( mocked_thread.call_args[1], { "target": fake_main_func, "args": (123,), "kwargs": {"abc": 123}, "name": "django-main-thread", }, ) self.assertIs(fake_thread.daemon, True) self.assertTrue(fake_thread.start.called) class TestCheckErrors(SimpleTestCase): def test_mutates_error_files(self): fake_method = mock.MagicMock(side_effect=RuntimeError()) wrapped = autoreload.check_errors(fake_method) with mock.patch.object(autoreload, "_error_files") as mocked_error_files: try: with self.assertRaises(RuntimeError): wrapped() finally: autoreload._exception = None self.assertEqual(mocked_error_files.append.call_count, 1) class TestRaiseLastException(SimpleTestCase): @mock.patch("django.utils.autoreload._exception", None) def test_no_exception(self): # Should raise no exception if _exception is None autoreload.raise_last_exception() def test_raises_exception(self): class MyException(Exception): pass # Create an exception try: raise MyException("Test Message") except MyException: exc_info = sys.exc_info() with mock.patch("django.utils.autoreload._exception", exc_info): with self.assertRaisesMessage(MyException, "Test Message"): autoreload.raise_last_exception() def test_raises_custom_exception(self): class MyException(Exception): def __init__(self, msg, extra_context): super().__init__(msg) self.extra_context = extra_context # Create an exception. try: raise MyException("Test Message", "extra context") except MyException: exc_info = sys.exc_info() with mock.patch("django.utils.autoreload._exception", exc_info): with self.assertRaisesMessage(MyException, "Test Message"): autoreload.raise_last_exception() def test_raises_exception_with_context(self): try: raise Exception(2) except Exception as e: try: raise Exception(1) from e except Exception: exc_info = sys.exc_info() with mock.patch("django.utils.autoreload._exception", exc_info): with self.assertRaises(Exception) as cm: autoreload.raise_last_exception() self.assertEqual(cm.exception.args[0], 1) self.assertEqual(cm.exception.__cause__.args[0], 2) class RestartWithReloaderTests(SimpleTestCase): executable = "/usr/bin/python" def patch_autoreload(self, argv): patch_call = mock.patch( "django.utils.autoreload.subprocess.run", return_value=CompletedProcess(argv, 0), ) patches = [ mock.patch("django.utils.autoreload.sys.argv", argv), mock.patch("django.utils.autoreload.sys.executable", self.executable), mock.patch("django.utils.autoreload.sys.warnoptions", ["all"]), mock.patch("django.utils.autoreload.sys._xoptions", {}), ] for p in patches: p.start() self.addCleanup(p.stop) mock_call = patch_call.start() self.addCleanup(patch_call.stop) return mock_call def test_manage_py(self): with tempfile.TemporaryDirectory() as temp_dir: script = Path(temp_dir) / "manage.py" script.touch() argv = [str(script), "runserver"] mock_call = self.patch_autoreload(argv) with mock.patch("__main__.__spec__", None): autoreload.restart_with_reloader() self.assertEqual(mock_call.call_count, 1) self.assertEqual( mock_call.call_args[0][0], [self.executable, "-Wall"] + argv, ) def test_python_m_django(self): main = "/usr/lib/pythonX.Y/site-packages/django/__main__.py" argv = [main, "runserver"] mock_call = self.patch_autoreload(argv) with mock.patch("django.__main__.__file__", main): with mock.patch.dict(sys.modules, {"__main__": django.__main__}): autoreload.restart_with_reloader() self.assertEqual(mock_call.call_count, 1) self.assertEqual( mock_call.call_args[0][0], [self.executable, "-Wall", "-m", "django"] + argv[1:], ) class ReloaderTests(SimpleTestCase): RELOADER_CLS = None def setUp(self): self._tempdir = tempfile.TemporaryDirectory() self.tempdir = Path(self._tempdir.name).resolve(strict=True).absolute() self.existing_file = self.ensure_file(self.tempdir / "test.py") self.nonexistent_file = (self.tempdir / "does_not_exist.py").absolute() self.reloader = self.RELOADER_CLS() def tearDown(self): self._tempdir.cleanup() self.reloader.stop() def ensure_file(self, path): path.parent.mkdir(exist_ok=True, parents=True) path.touch() # On Linux and Windows updating the mtime of a file using touch() will # set a timestamp value that is in the past, as the time value for the # last kernel tick is used rather than getting the correct absolute # time. # To make testing simpler set the mtime to be the observed time when # this function is called. self.set_mtime(path, time.time()) return path.absolute() def set_mtime(self, fp, value): os.utime(str(fp), (value, value)) def increment_mtime(self, fp, by=1): current_time = time.time() self.set_mtime(fp, current_time + by) @contextlib.contextmanager def tick_twice(self): ticker = self.reloader.tick() next(ticker) yield next(ticker) class IntegrationTests: @mock.patch("django.utils.autoreload.BaseReloader.notify_file_changed") @mock.patch( "django.utils.autoreload.iter_all_python_module_files", return_value=frozenset() ) def test_glob(self, mocked_modules, notify_mock): non_py_file = self.ensure_file(self.tempdir / "non_py_file") self.reloader.watch_dir(self.tempdir, "*.py") with self.tick_twice(): self.increment_mtime(non_py_file) self.increment_mtime(self.existing_file) self.assertEqual(notify_mock.call_count, 1) self.assertCountEqual(notify_mock.call_args[0], [self.existing_file]) @mock.patch("django.utils.autoreload.BaseReloader.notify_file_changed") @mock.patch( "django.utils.autoreload.iter_all_python_module_files", return_value=frozenset() ) def test_multiple_globs(self, mocked_modules, notify_mock): self.ensure_file(self.tempdir / "x.test") self.reloader.watch_dir(self.tempdir, "*.py") self.reloader.watch_dir(self.tempdir, "*.test") with self.tick_twice(): self.increment_mtime(self.existing_file) self.assertEqual(notify_mock.call_count, 1) self.assertCountEqual(notify_mock.call_args[0], [self.existing_file]) @mock.patch("django.utils.autoreload.BaseReloader.notify_file_changed") @mock.patch( "django.utils.autoreload.iter_all_python_module_files", return_value=frozenset() ) def test_overlapping_globs(self, mocked_modules, notify_mock): self.reloader.watch_dir(self.tempdir, "*.py") self.reloader.watch_dir(self.tempdir, "*.p*") with self.tick_twice(): self.increment_mtime(self.existing_file) self.assertEqual(notify_mock.call_count, 1) self.assertCountEqual(notify_mock.call_args[0], [self.existing_file]) @mock.patch("django.utils.autoreload.BaseReloader.notify_file_changed") @mock.patch( "django.utils.autoreload.iter_all_python_module_files", return_value=frozenset() ) def test_glob_recursive(self, mocked_modules, notify_mock): non_py_file = self.ensure_file(self.tempdir / "dir" / "non_py_file") py_file = self.ensure_file(self.tempdir / "dir" / "file.py") self.reloader.watch_dir(self.tempdir, "**/*.py") with self.tick_twice(): self.increment_mtime(non_py_file) self.increment_mtime(py_file) self.assertEqual(notify_mock.call_count, 1) self.assertCountEqual(notify_mock.call_args[0], [py_file]) @mock.patch("django.utils.autoreload.BaseReloader.notify_file_changed") @mock.patch( "django.utils.autoreload.iter_all_python_module_files", return_value=frozenset() ) def test_multiple_recursive_globs(self, mocked_modules, notify_mock): non_py_file = self.ensure_file(self.tempdir / "dir" / "test.txt") py_file = self.ensure_file(self.tempdir / "dir" / "file.py") self.reloader.watch_dir(self.tempdir, "**/*.txt") self.reloader.watch_dir(self.tempdir, "**/*.py") with self.tick_twice(): self.increment_mtime(non_py_file) self.increment_mtime(py_file) self.assertEqual(notify_mock.call_count, 2) self.assertCountEqual( notify_mock.call_args_list, [mock.call(py_file), mock.call(non_py_file)] ) @mock.patch("django.utils.autoreload.BaseReloader.notify_file_changed") @mock.patch( "django.utils.autoreload.iter_all_python_module_files", return_value=frozenset() ) def test_nested_glob_recursive(self, mocked_modules, notify_mock): inner_py_file = self.ensure_file(self.tempdir / "dir" / "file.py") self.reloader.watch_dir(self.tempdir, "**/*.py") self.reloader.watch_dir(inner_py_file.parent, "**/*.py") with self.tick_twice(): self.increment_mtime(inner_py_file) self.assertEqual(notify_mock.call_count, 1) self.assertCountEqual(notify_mock.call_args[0], [inner_py_file]) @mock.patch("django.utils.autoreload.BaseReloader.notify_file_changed") @mock.patch( "django.utils.autoreload.iter_all_python_module_files", return_value=frozenset() ) def test_overlapping_glob_recursive(self, mocked_modules, notify_mock): py_file = self.ensure_file(self.tempdir / "dir" / "file.py") self.reloader.watch_dir(self.tempdir, "**/*.p*") self.reloader.watch_dir(self.tempdir, "**/*.py*") with self.tick_twice(): self.increment_mtime(py_file) self.assertEqual(notify_mock.call_count, 1) self.assertCountEqual(notify_mock.call_args[0], [py_file]) class BaseReloaderTests(ReloaderTests): RELOADER_CLS = autoreload.BaseReloader def test_watch_dir_with_unresolvable_path(self): path = Path("unresolvable_directory") with mock.patch.object(Path, "absolute", side_effect=FileNotFoundError): self.reloader.watch_dir(path, "**/*.mo") self.assertEqual(list(self.reloader.directory_globs), []) def test_watch_with_glob(self): self.reloader.watch_dir(self.tempdir, "*.py") watched_files = list(self.reloader.watched_files()) self.assertIn(self.existing_file, watched_files) def test_watch_files_with_recursive_glob(self): inner_file = self.ensure_file(self.tempdir / "test" / "test.py") self.reloader.watch_dir(self.tempdir, "**/*.py") watched_files = list(self.reloader.watched_files()) self.assertIn(self.existing_file, watched_files) self.assertIn(inner_file, watched_files) def test_run_loop_catches_stopiteration(self): def mocked_tick(): yield with mock.patch.object(self.reloader, "tick", side_effect=mocked_tick) as tick: self.reloader.run_loop() self.assertEqual(tick.call_count, 1) def test_run_loop_stop_and_return(self): def mocked_tick(*args): yield self.reloader.stop() return # Raises StopIteration with mock.patch.object(self.reloader, "tick", side_effect=mocked_tick) as tick: self.reloader.run_loop() self.assertEqual(tick.call_count, 1) def test_wait_for_apps_ready_checks_for_exception(self): app_reg = Apps() app_reg.ready_event.set() # thread.is_alive() is False if it's not started. dead_thread = threading.Thread() self.assertFalse(self.reloader.wait_for_apps_ready(app_reg, dead_thread)) def test_wait_for_apps_ready_without_exception(self): app_reg = Apps() app_reg.ready_event.set() thread = mock.MagicMock() thread.is_alive.return_value = True self.assertTrue(self.reloader.wait_for_apps_ready(app_reg, thread)) def skip_unless_watchman_available(): try: autoreload.WatchmanReloader.check_availability() except WatchmanUnavailable as e: return skip("Watchman unavailable: %s" % e) return lambda func: func @skip_unless_watchman_available() class WatchmanReloaderTests(ReloaderTests, IntegrationTests): RELOADER_CLS = autoreload.WatchmanReloader def setUp(self): super().setUp() # Shorten the timeout to speed up tests. self.reloader.client_timeout = int(os.environ.get("DJANGO_WATCHMAN_TIMEOUT", 2)) def test_watch_glob_ignores_non_existing_directories_two_levels(self): with mock.patch.object(self.reloader, "_subscribe") as mocked_subscribe: self.reloader._watch_glob(self.tempdir / "does_not_exist" / "more", ["*"]) self.assertFalse(mocked_subscribe.called) def test_watch_glob_uses_existing_parent_directories(self): with mock.patch.object(self.reloader, "_subscribe") as mocked_subscribe: self.reloader._watch_glob(self.tempdir / "does_not_exist", ["*"]) self.assertSequenceEqual( mocked_subscribe.call_args[0], [ self.tempdir, "glob-parent-does_not_exist:%s" % self.tempdir, ["anyof", ["match", "does_not_exist/*", "wholename"]], ], ) def test_watch_glob_multiple_patterns(self): with mock.patch.object(self.reloader, "_subscribe") as mocked_subscribe: self.reloader._watch_glob(self.tempdir, ["*", "*.py"]) self.assertSequenceEqual( mocked_subscribe.call_args[0], [ self.tempdir, "glob:%s" % self.tempdir, ["anyof", ["match", "*", "wholename"], ["match", "*.py", "wholename"]], ], ) def test_watched_roots_contains_files(self): paths = self.reloader.watched_roots([self.existing_file]) self.assertIn(self.existing_file.parent, paths) def test_watched_roots_contains_directory_globs(self): self.reloader.watch_dir(self.tempdir, "*.py") paths = self.reloader.watched_roots([]) self.assertIn(self.tempdir, paths) def test_watched_roots_contains_sys_path(self): with extend_sys_path(str(self.tempdir)): paths = self.reloader.watched_roots([]) self.assertIn(self.tempdir, paths) def test_check_server_status(self): self.assertTrue(self.reloader.check_server_status()) def test_check_server_status_raises_error(self): with mock.patch.object(self.reloader.client, "query") as mocked_query: mocked_query.side_effect = Exception() with self.assertRaises(autoreload.WatchmanUnavailable): self.reloader.check_server_status() @mock.patch("pywatchman.client") def test_check_availability(self, mocked_client): mocked_client().capabilityCheck.side_effect = Exception() with self.assertRaisesMessage( WatchmanUnavailable, "Cannot connect to the watchman service" ): self.RELOADER_CLS.check_availability() @mock.patch("pywatchman.client") def test_check_availability_lower_version(self, mocked_client): mocked_client().capabilityCheck.return_value = {"version": "4.8.10"} with self.assertRaisesMessage( WatchmanUnavailable, "Watchman 4.9 or later is required." ): self.RELOADER_CLS.check_availability() def test_pywatchman_not_available(self): with mock.patch.object(autoreload, "pywatchman") as mocked: mocked.__bool__.return_value = False with self.assertRaisesMessage( WatchmanUnavailable, "pywatchman not installed." ): self.RELOADER_CLS.check_availability() def test_update_watches_raises_exceptions(self): class TestException(Exception): pass with mock.patch.object(self.reloader, "_update_watches") as mocked_watches: with mock.patch.object( self.reloader, "check_server_status" ) as mocked_server_status: mocked_watches.side_effect = TestException() mocked_server_status.return_value = True with self.assertRaises(TestException): self.reloader.update_watches() self.assertIsInstance( mocked_server_status.call_args[0][0], TestException ) @mock.patch.dict(os.environ, {"DJANGO_WATCHMAN_TIMEOUT": "10"}) def test_setting_timeout_from_environment_variable(self): self.assertEqual(self.RELOADER_CLS().client_timeout, 10) @skipIf(on_macos_with_hfs(), "These tests do not work with HFS+ as a filesystem") class StatReloaderTests(ReloaderTests, IntegrationTests): RELOADER_CLS = autoreload.StatReloader def setUp(self): super().setUp() # Shorten the sleep time to speed up tests. self.reloader.SLEEP_TIME = 0.01 @mock.patch("django.utils.autoreload.StatReloader.notify_file_changed") def test_tick_does_not_trigger_twice(self, mock_notify_file_changed): with mock.patch.object( self.reloader, "watched_files", return_value=[self.existing_file] ): ticker = self.reloader.tick() next(ticker) self.increment_mtime(self.existing_file) next(ticker) next(ticker) self.assertEqual(mock_notify_file_changed.call_count, 1) def test_snapshot_files_ignores_missing_files(self): with mock.patch.object( self.reloader, "watched_files", return_value=[self.nonexistent_file] ): self.assertEqual(dict(self.reloader.snapshot_files()), {}) def test_snapshot_files_updates(self): with mock.patch.object( self.reloader, "watched_files", return_value=[self.existing_file] ): snapshot1 = dict(self.reloader.snapshot_files()) self.assertIn(self.existing_file, snapshot1) self.increment_mtime(self.existing_file) snapshot2 = dict(self.reloader.snapshot_files()) self.assertNotEqual( snapshot1[self.existing_file], snapshot2[self.existing_file] ) def test_snapshot_files_with_duplicates(self): with mock.patch.object( self.reloader, "watched_files", return_value=[self.existing_file, self.existing_file], ): snapshot = list(self.reloader.snapshot_files()) self.assertEqual(len(snapshot), 1) self.assertEqual(snapshot[0][0], self.existing_file)
c4a8f50535afa280ca0b7568211650653a841a0521b29bfd95698beba7251a75
from datetime import date as original_date from datetime import datetime as original_datetime from django.test import SimpleTestCase, ignore_warnings from django.utils.deprecation import RemovedInDjango50Warning with ignore_warnings(category=RemovedInDjango50Warning): from django.utils.datetime_safe import date, datetime class DatetimeTests(SimpleTestCase): def setUp(self): self.percent_y_safe = (1900, 1, 1) # >= 1900 required on Windows. self.just_safe = (1000, 1, 1) self.just_unsafe = (999, 12, 31, 23, 59, 59) self.really_old = (20, 1, 1) self.more_recent = (2006, 1, 1) def test_compare_datetimes(self): self.assertEqual( original_datetime(*self.more_recent), datetime(*self.more_recent) ) self.assertEqual( original_datetime(*self.really_old), datetime(*self.really_old) ) self.assertEqual(original_date(*self.more_recent), date(*self.more_recent)) self.assertEqual(original_date(*self.really_old), date(*self.really_old)) self.assertEqual( original_date(*self.just_safe).strftime("%Y-%m-%d"), date(*self.just_safe).strftime("%Y-%m-%d"), ) self.assertEqual( original_datetime(*self.just_safe).strftime("%Y-%m-%d"), datetime(*self.just_safe).strftime("%Y-%m-%d"), ) def test_safe_strftime(self): self.assertEqual( date(*self.just_unsafe[:3]).strftime("%Y-%m-%d (weekday %w)"), "0999-12-31 (weekday 2)", ) self.assertEqual( date(*self.just_safe).strftime("%Y-%m-%d (weekday %w)"), "1000-01-01 (weekday 3)", ) self.assertEqual( datetime(*self.just_unsafe).strftime("%Y-%m-%d %H:%M:%S (weekday %w)"), "0999-12-31 23:59:59 (weekday 2)", ) self.assertEqual( datetime(*self.just_safe).strftime("%Y-%m-%d %H:%M:%S (weekday %w)"), "1000-01-01 00:00:00 (weekday 3)", ) # %y will error before this date self.assertEqual(date(*self.percent_y_safe).strftime("%y"), "00") self.assertEqual(datetime(*self.percent_y_safe).strftime("%y"), "00") with self.assertRaisesMessage( TypeError, "strftime of dates before 1000 does not handle %y" ): datetime(*self.just_unsafe).strftime("%y") self.assertEqual( date(1850, 8, 2).strftime("%Y/%m/%d was a %A"), "1850/08/02 was a Friday" ) def test_zero_padding(self): """ Regression for #12524 Pre-1000AD dates are padded with zeros if necessary """ self.assertEqual( date(1, 1, 1).strftime("%Y/%m/%d was a %A"), "0001/01/01 was a Monday" )
d84cb793402edb40561bc6fc4f1f49daffe31685b1b4f827cfaa378065154595
import unittest from django.utils.ipv6 import clean_ipv6_address, is_valid_ipv6_address class TestUtilsIPv6(unittest.TestCase): def test_validates_correct_plain_address(self): self.assertTrue(is_valid_ipv6_address("fe80::223:6cff:fe8a:2e8a")) self.assertTrue(is_valid_ipv6_address("2a02::223:6cff:fe8a:2e8a")) self.assertTrue(is_valid_ipv6_address("1::2:3:4:5:6:7")) self.assertTrue(is_valid_ipv6_address("::")) self.assertTrue(is_valid_ipv6_address("::a")) self.assertTrue(is_valid_ipv6_address("2::")) def test_validates_correct_with_v4mapping(self): self.assertTrue(is_valid_ipv6_address("::ffff:254.42.16.14")) self.assertTrue(is_valid_ipv6_address("::ffff:0a0a:0a0a")) def test_validates_incorrect_plain_address(self): self.assertFalse(is_valid_ipv6_address("foo")) self.assertFalse(is_valid_ipv6_address("127.0.0.1")) self.assertFalse(is_valid_ipv6_address("12345::")) self.assertFalse(is_valid_ipv6_address("1::2:3::4")) self.assertFalse(is_valid_ipv6_address("1::zzz")) self.assertFalse(is_valid_ipv6_address("1::2:3:4:5:6:7:8")) self.assertFalse(is_valid_ipv6_address("1:2")) self.assertFalse(is_valid_ipv6_address("1:::2")) self.assertFalse(is_valid_ipv6_address("fe80::223: 6cff:fe8a:2e8a")) self.assertFalse(is_valid_ipv6_address("2a02::223:6cff :fe8a:2e8a")) def test_validates_incorrect_with_v4mapping(self): self.assertFalse(is_valid_ipv6_address("::ffff:999.42.16.14")) self.assertFalse(is_valid_ipv6_address("::ffff:zzzz:0a0a")) # The ::1.2.3.4 format used to be valid but was deprecated # in rfc4291 section 2.5.5.1 self.assertTrue(is_valid_ipv6_address("::254.42.16.14")) self.assertTrue(is_valid_ipv6_address("::0a0a:0a0a")) self.assertFalse(is_valid_ipv6_address("::999.42.16.14")) self.assertFalse(is_valid_ipv6_address("::zzzz:0a0a")) def test_cleans_plain_address(self): self.assertEqual(clean_ipv6_address("DEAD::0:BEEF"), "dead::beef") self.assertEqual( clean_ipv6_address("2001:000:a:0000:0:fe:fe:beef"), "2001:0:a::fe:fe:beef" ) self.assertEqual( clean_ipv6_address("2001::a:0000:0:fe:fe:beef"), "2001:0:a::fe:fe:beef" ) def test_cleans_with_v4_mapping(self): self.assertEqual(clean_ipv6_address("::ffff:0a0a:0a0a"), "::ffff:10.10.10.10") self.assertEqual(clean_ipv6_address("::ffff:1234:1234"), "::ffff:18.52.18.52") self.assertEqual(clean_ipv6_address("::ffff:18.52.18.52"), "::ffff:18.52.18.52") self.assertEqual(clean_ipv6_address("::ffff:0.52.18.52"), "::ffff:0.52.18.52") self.assertEqual(clean_ipv6_address("::ffff:0.0.0.0"), "::ffff:0.0.0.0") def test_unpacks_ipv4(self): self.assertEqual( clean_ipv6_address("::ffff:0a0a:0a0a", unpack_ipv4=True), "10.10.10.10" ) self.assertEqual( clean_ipv6_address("::ffff:1234:1234", unpack_ipv4=True), "18.52.18.52" ) self.assertEqual( clean_ipv6_address("::ffff:18.52.18.52", unpack_ipv4=True), "18.52.18.52" )
ab2a8fc0ec8081b0b49c8a5bf8a4a91b6aa9b3a7f3b8d8775d68a2e7a9490e6d
""" Tests for stuff in django.utils.datastructures. """ import collections.abc import copy import pickle from django.test import SimpleTestCase from django.utils.datastructures import ( CaseInsensitiveMapping, DictWrapper, ImmutableList, MultiValueDict, MultiValueDictKeyError, OrderedSet, ) class OrderedSetTests(SimpleTestCase): def test_init_with_iterable(self): s = OrderedSet([1, 2, 3]) self.assertEqual(list(s.dict.keys()), [1, 2, 3]) def test_remove(self): s = OrderedSet() self.assertEqual(len(s), 0) s.add(1) s.add(2) s.remove(2) self.assertEqual(len(s), 1) self.assertNotIn(2, s) def test_discard(self): s = OrderedSet() self.assertEqual(len(s), 0) s.add(1) s.discard(2) self.assertEqual(len(s), 1) def test_reversed(self): s = reversed(OrderedSet([1, 2, 3])) self.assertIsInstance(s, collections.abc.Iterator) self.assertEqual(list(s), [3, 2, 1]) def test_contains(self): s = OrderedSet() self.assertEqual(len(s), 0) s.add(1) self.assertIn(1, s) def test_bool(self): # Refs #23664 s = OrderedSet() self.assertFalse(s) s.add(1) self.assertTrue(s) def test_len(self): s = OrderedSet() self.assertEqual(len(s), 0) s.add(1) s.add(2) s.add(2) self.assertEqual(len(s), 2) def test_repr(self): self.assertEqual(repr(OrderedSet()), "OrderedSet()") self.assertEqual(repr(OrderedSet([2, 3, 2, 1])), "OrderedSet([2, 3, 1])") class MultiValueDictTests(SimpleTestCase): def test_repr(self): d = MultiValueDict({"key": "value"}) self.assertEqual(repr(d), "<MultiValueDict: {'key': 'value'}>") def test_multivaluedict(self): d = MultiValueDict( {"name": ["Adrian", "Simon"], "position": ["Developer"], "empty": []} ) self.assertEqual(d["name"], "Simon") self.assertEqual(d.get("name"), "Simon") self.assertEqual(d.getlist("name"), ["Adrian", "Simon"]) self.assertEqual( list(d.items()), [("name", "Simon"), ("position", "Developer"), ("empty", [])], ) self.assertEqual( list(d.lists()), [("name", ["Adrian", "Simon"]), ("position", ["Developer"]), ("empty", [])], ) with self.assertRaisesMessage(MultiValueDictKeyError, "'lastname'"): d.__getitem__("lastname") self.assertIsNone(d.get("empty")) self.assertEqual(d.get("empty", "nonexistent"), "nonexistent") self.assertIsNone(d.get("lastname")) self.assertEqual(d.get("lastname", "nonexistent"), "nonexistent") self.assertEqual(d.getlist("lastname"), []) self.assertEqual( d.getlist("doesnotexist", ["Adrian", "Simon"]), ["Adrian", "Simon"] ) d.setlist("lastname", ["Holovaty", "Willison"]) self.assertEqual(d.getlist("lastname"), ["Holovaty", "Willison"]) self.assertEqual(list(d.values()), ["Simon", "Developer", [], "Willison"]) def test_appendlist(self): d = MultiValueDict() d.appendlist("name", "Adrian") d.appendlist("name", "Simon") self.assertEqual(d.getlist("name"), ["Adrian", "Simon"]) def test_copy(self): for copy_func in [copy.copy, lambda d: d.copy()]: with self.subTest(copy_func): d1 = MultiValueDict({"developers": ["Carl", "Fred"]}) self.assertEqual(d1["developers"], "Fred") d2 = copy_func(d1) d2.update({"developers": "Groucho"}) self.assertEqual(d2["developers"], "Groucho") self.assertEqual(d1["developers"], "Fred") d1 = MultiValueDict({"key": [[]]}) self.assertEqual(d1["key"], []) d2 = copy_func(d1) d2["key"].append("Penguin") self.assertEqual(d1["key"], ["Penguin"]) self.assertEqual(d2["key"], ["Penguin"]) def test_deepcopy(self): d1 = MultiValueDict({"a": [[123]]}) d2 = copy.copy(d1) d3 = copy.deepcopy(d1) self.assertIs(d1["a"], d2["a"]) self.assertIsNot(d1["a"], d3["a"]) def test_pickle(self): x = MultiValueDict({"a": ["1", "2"], "b": ["3"]}) self.assertEqual(x, pickle.loads(pickle.dumps(x))) def test_dict_translation(self): mvd = MultiValueDict( { "devs": ["Bob", "Joe"], "pm": ["Rory"], } ) d = mvd.dict() self.assertEqual(list(d), list(mvd)) for key in mvd: self.assertEqual(d[key], mvd[key]) self.assertEqual({}, MultiValueDict().dict()) def test_getlist_doesnt_mutate(self): x = MultiValueDict({"a": ["1", "2"], "b": ["3"]}) values = x.getlist("a") values += x.getlist("b") self.assertEqual(x.getlist("a"), ["1", "2"]) def test_internal_getlist_does_mutate(self): x = MultiValueDict({"a": ["1", "2"], "b": ["3"]}) values = x._getlist("a") values += x._getlist("b") self.assertEqual(x._getlist("a"), ["1", "2", "3"]) def test_getlist_default(self): x = MultiValueDict({"a": [1]}) MISSING = object() values = x.getlist("b", default=MISSING) self.assertIs(values, MISSING) def test_getlist_none_empty_values(self): x = MultiValueDict({"a": None, "b": []}) self.assertIsNone(x.getlist("a")) self.assertEqual(x.getlist("b"), []) def test_setitem(self): x = MultiValueDict({"a": [1, 2]}) x["a"] = 3 self.assertEqual(list(x.lists()), [("a", [3])]) def test_setdefault(self): x = MultiValueDict({"a": [1, 2]}) a = x.setdefault("a", 3) b = x.setdefault("b", 3) self.assertEqual(a, 2) self.assertEqual(b, 3) self.assertEqual(list(x.lists()), [("a", [1, 2]), ("b", [3])]) def test_update_too_many_args(self): x = MultiValueDict({"a": []}) msg = "update expected at most 1 argument, got 2" with self.assertRaisesMessage(TypeError, msg): x.update(1, 2) def test_update_no_args(self): x = MultiValueDict({"a": []}) x.update() self.assertEqual(list(x.lists()), [("a", [])]) def test_update_dict_arg(self): x = MultiValueDict({"a": [1], "b": [2], "c": [3]}) x.update({"a": 4, "b": 5}) self.assertEqual(list(x.lists()), [("a", [1, 4]), ("b", [2, 5]), ("c", [3])]) def test_update_multivaluedict_arg(self): x = MultiValueDict({"a": [1], "b": [2], "c": [3]}) x.update(MultiValueDict({"a": [4], "b": [5]})) self.assertEqual(list(x.lists()), [("a", [1, 4]), ("b", [2, 5]), ("c", [3])]) def test_update_kwargs(self): x = MultiValueDict({"a": [1], "b": [2], "c": [3]}) x.update(a=4, b=5) self.assertEqual(list(x.lists()), [("a", [1, 4]), ("b", [2, 5]), ("c", [3])]) def test_update_with_empty_iterable(self): for value in ["", b"", (), [], set(), {}]: d = MultiValueDict() d.update(value) self.assertEqual(d, MultiValueDict()) def test_update_with_iterable_of_pairs(self): for value in [(("a", 1),), [("a", 1)], {("a", 1)}]: d = MultiValueDict() d.update(value) self.assertEqual(d, MultiValueDict({"a": [1]})) def test_update_raises_correct_exceptions(self): # MultiValueDict.update() raises equivalent exceptions to # dict.update(). # Non-iterable values raise TypeError. for value in [None, True, False, 123, 123.45]: with self.subTest(value), self.assertRaises(TypeError): MultiValueDict().update(value) # Iterables of objects that cannot be unpacked raise TypeError. for value in [b"123", b"abc", (1, 2, 3), [1, 2, 3], {1, 2, 3}]: with self.subTest(value), self.assertRaises(TypeError): MultiValueDict().update(value) # Iterables of unpackable objects with incorrect number of items raise # ValueError. for value in ["123", "abc", ("a", "b", "c"), ["a", "b", "c"], {"a", "b", "c"}]: with self.subTest(value), self.assertRaises(ValueError): MultiValueDict().update(value) class ImmutableListTests(SimpleTestCase): def test_sort(self): d = ImmutableList(range(10)) # AttributeError: ImmutableList object is immutable. with self.assertRaisesMessage( AttributeError, "ImmutableList object is immutable." ): d.sort() self.assertEqual(repr(d), "(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)") def test_custom_warning(self): d = ImmutableList(range(10), warning="Object is immutable!") self.assertEqual(d[1], 1) # AttributeError: Object is immutable! with self.assertRaisesMessage(AttributeError, "Object is immutable!"): d.__setitem__(1, "test") class DictWrapperTests(SimpleTestCase): def test_dictwrapper(self): def f(x): return "*%s" % x d = DictWrapper({"a": "a"}, f, "xx_") self.assertEqual( "Normal: %(a)s. Modified: %(xx_a)s" % d, "Normal: a. Modified: *a" ) class CaseInsensitiveMappingTests(SimpleTestCase): def setUp(self): self.dict1 = CaseInsensitiveMapping( { "Accept": "application/json", "content-type": "text/html", } ) def test_create_with_invalid_values(self): msg = "dictionary update sequence element #1 has length 4; 2 is required" with self.assertRaisesMessage(ValueError, msg): CaseInsensitiveMapping([("Key1", "Val1"), "Key2"]) def test_create_with_invalid_key(self): msg = "Element key 1 invalid, only strings are allowed" with self.assertRaisesMessage(ValueError, msg): CaseInsensitiveMapping([(1, "2")]) def test_list(self): self.assertEqual(list(self.dict1), ["Accept", "content-type"]) def test_dict(self): self.assertEqual( dict(self.dict1), {"Accept": "application/json", "content-type": "text/html"}, ) def test_repr(self): dict1 = CaseInsensitiveMapping({"Accept": "application/json"}) dict2 = CaseInsensitiveMapping({"content-type": "text/html"}) self.assertEqual(repr(dict1), repr({"Accept": "application/json"})) self.assertEqual(repr(dict2), repr({"content-type": "text/html"})) def test_str(self): dict1 = CaseInsensitiveMapping({"Accept": "application/json"}) dict2 = CaseInsensitiveMapping({"content-type": "text/html"}) self.assertEqual(str(dict1), str({"Accept": "application/json"})) self.assertEqual(str(dict2), str({"content-type": "text/html"})) def test_equal(self): self.assertEqual( self.dict1, {"Accept": "application/json", "content-type": "text/html"} ) self.assertNotEqual( self.dict1, {"accept": "application/jso", "Content-Type": "text/html"} ) self.assertNotEqual(self.dict1, "string") def test_items(self): other = {"Accept": "application/json", "content-type": "text/html"} self.assertEqual(sorted(self.dict1.items()), sorted(other.items())) def test_copy(self): copy = self.dict1.copy() self.assertIs(copy, self.dict1) self.assertEqual(copy, self.dict1) def test_getitem(self): self.assertEqual(self.dict1["Accept"], "application/json") self.assertEqual(self.dict1["accept"], "application/json") self.assertEqual(self.dict1["aCCept"], "application/json") self.assertEqual(self.dict1["content-type"], "text/html") self.assertEqual(self.dict1["Content-Type"], "text/html") self.assertEqual(self.dict1["Content-type"], "text/html") def test_in(self): self.assertIn("Accept", self.dict1) self.assertIn("accept", self.dict1) self.assertIn("aCCept", self.dict1) self.assertIn("content-type", self.dict1) self.assertIn("Content-Type", self.dict1) def test_del(self): self.assertIn("Accept", self.dict1) msg = "'CaseInsensitiveMapping' object does not support item deletion" with self.assertRaisesMessage(TypeError, msg): del self.dict1["Accept"] self.assertIn("Accept", self.dict1) def test_set(self): self.assertEqual(len(self.dict1), 2) msg = "'CaseInsensitiveMapping' object does not support item assignment" with self.assertRaisesMessage(TypeError, msg): self.dict1["New Key"] = 1 self.assertEqual(len(self.dict1), 2)
81a499e5f77438ccd141dc8eb9c5fd46811e72c268de4d283f5c43433b00c033
import platform import unittest from datetime import datetime, timezone from unittest import mock from django.test import SimpleTestCase from django.utils.datastructures import MultiValueDict from django.utils.http import ( base36_to_int, escape_leading_slashes, http_date, int_to_base36, is_same_domain, parse_etags, parse_http_date, quote_etag, url_has_allowed_host_and_scheme, urlencode, urlsafe_base64_decode, urlsafe_base64_encode, ) class URLEncodeTests(SimpleTestCase): cannot_encode_none_msg = ( "Cannot encode None for key 'a' in a query string. Did you mean to " "pass an empty string or omit the value?" ) def test_tuples(self): self.assertEqual(urlencode((("a", 1), ("b", 2), ("c", 3))), "a=1&b=2&c=3") def test_dict(self): result = urlencode({"a": 1, "b": 2, "c": 3}) # Dictionaries are treated as unordered. self.assertIn( result, [ "a=1&b=2&c=3", "a=1&c=3&b=2", "b=2&a=1&c=3", "b=2&c=3&a=1", "c=3&a=1&b=2", "c=3&b=2&a=1", ], ) def test_dict_containing_sequence_not_doseq(self): self.assertEqual(urlencode({"a": [1, 2]}, doseq=False), "a=%5B1%2C+2%5D") def test_dict_containing_tuple_not_doseq(self): self.assertEqual(urlencode({"a": (1, 2)}, doseq=False), "a=%281%2C+2%29") def test_custom_iterable_not_doseq(self): class IterableWithStr: def __str__(self): return "custom" def __iter__(self): yield from range(0, 3) self.assertEqual(urlencode({"a": IterableWithStr()}, doseq=False), "a=custom") def test_dict_containing_sequence_doseq(self): self.assertEqual(urlencode({"a": [1, 2]}, doseq=True), "a=1&a=2") def test_dict_containing_empty_sequence_doseq(self): self.assertEqual(urlencode({"a": []}, doseq=True), "") def test_multivaluedict(self): result = urlencode( MultiValueDict( { "name": ["Adrian", "Simon"], "position": ["Developer"], } ), doseq=True, ) # MultiValueDicts are similarly unordered. self.assertIn( result, [ "name=Adrian&name=Simon&position=Developer", "position=Developer&name=Adrian&name=Simon", ], ) def test_dict_with_bytes_values(self): self.assertEqual(urlencode({"a": b"abc"}, doseq=True), "a=abc") def test_dict_with_sequence_of_bytes(self): self.assertEqual( urlencode({"a": [b"spam", b"eggs", b"bacon"]}, doseq=True), "a=spam&a=eggs&a=bacon", ) def test_dict_with_bytearray(self): self.assertEqual(urlencode({"a": bytearray(range(2))}, doseq=True), "a=0&a=1") def test_generator(self): self.assertEqual(urlencode({"a": range(2)}, doseq=True), "a=0&a=1") self.assertEqual(urlencode({"a": range(2)}, doseq=False), "a=range%280%2C+2%29") def test_none(self): with self.assertRaisesMessage(TypeError, self.cannot_encode_none_msg): urlencode({"a": None}) def test_none_in_sequence(self): with self.assertRaisesMessage(TypeError, self.cannot_encode_none_msg): urlencode({"a": [None]}, doseq=True) def test_none_in_generator(self): def gen(): yield None with self.assertRaisesMessage(TypeError, self.cannot_encode_none_msg): urlencode({"a": gen()}, doseq=True) class Base36IntTests(SimpleTestCase): def test_roundtrip(self): for n in [0, 1, 1000, 1000000]: self.assertEqual(n, base36_to_int(int_to_base36(n))) def test_negative_input(self): with self.assertRaisesMessage(ValueError, "Negative base36 conversion input."): int_to_base36(-1) def test_to_base36_errors(self): for n in ["1", "foo", {1: 2}, (1, 2, 3), 3.141]: with self.assertRaises(TypeError): int_to_base36(n) def test_invalid_literal(self): for n in ["#", " "]: with self.assertRaisesMessage( ValueError, "invalid literal for int() with base 36: '%s'" % n ): base36_to_int(n) def test_input_too_large(self): with self.assertRaisesMessage(ValueError, "Base36 input too large"): base36_to_int("1" * 14) def test_to_int_errors(self): for n in [123, {1: 2}, (1, 2, 3), 3.141]: with self.assertRaises(TypeError): base36_to_int(n) def test_values(self): for n, b36 in [(0, "0"), (1, "1"), (42, "16"), (818469960, "django")]: self.assertEqual(int_to_base36(n), b36) self.assertEqual(base36_to_int(b36), n) class URLHasAllowedHostAndSchemeTests(unittest.TestCase): def test_bad_urls(self): bad_urls = ( "http://example.com", "http:///example.com", "https://example.com", "ftp://example.com", r"\\example.com", r"\\\example.com", r"/\\/example.com", r"\\\example.com", r"\\example.com", r"\\//example.com", r"/\/example.com", r"\/example.com", r"/\example.com", "http:///example.com", r"http:/\//example.com", r"http:\/example.com", r"http:/\example.com", 'javascript:alert("XSS")', "\njavascript:alert(x)", "\x08//example.com", r"http://otherserver\@example.com", r"http:\\testserver\@example.com", r"http://testserver\me:[email protected]", r"http://testserver\@example.com", r"http:\\testserver\confirm\[email protected]", "http:999999999", "ftp:9999999999", "\n", "http://[2001:cdba:0000:0000:0000:0000:3257:9652/", "http://2001:cdba:0000:0000:0000:0000:3257:9652]/", ) for bad_url in bad_urls: with self.subTest(url=bad_url): self.assertIs( url_has_allowed_host_and_scheme( bad_url, allowed_hosts={"testserver", "testserver2"} ), False, ) def test_good_urls(self): good_urls = ( "/view/?param=http://example.com", "/view/?param=https://example.com", "/view?param=ftp://example.com", "view/?param=//example.com", "https://testserver/", "HTTPS://testserver/", "//testserver/", "http://testserver/[email protected]", "/url%20with%20spaces/", "path/http:2222222222", ) for good_url in good_urls: with self.subTest(url=good_url): self.assertIs( url_has_allowed_host_and_scheme( good_url, allowed_hosts={"otherserver", "testserver"} ), True, ) def test_basic_auth(self): # Valid basic auth credentials are allowed. self.assertIs( url_has_allowed_host_and_scheme( r"http://user:pass@testserver/", allowed_hosts={"user:pass@testserver"} ), True, ) def test_no_allowed_hosts(self): # A path without host is allowed. self.assertIs( url_has_allowed_host_and_scheme( "/confirm/[email protected]", allowed_hosts=None ), True, ) # Basic auth without host is not allowed. self.assertIs( url_has_allowed_host_and_scheme( r"http://testserver\@example.com", allowed_hosts=None ), False, ) def test_allowed_hosts_str(self): self.assertIs( url_has_allowed_host_and_scheme( "http://good.com/good", allowed_hosts="good.com" ), True, ) self.assertIs( url_has_allowed_host_and_scheme( "http://good.co/evil", allowed_hosts="good.com" ), False, ) def test_secure_param_https_urls(self): secure_urls = ( "https://example.com/p", "HTTPS://example.com/p", "/view/?param=http://example.com", ) for url in secure_urls: with self.subTest(url=url): self.assertIs( url_has_allowed_host_and_scheme( url, allowed_hosts={"example.com"}, require_https=True ), True, ) def test_secure_param_non_https_urls(self): insecure_urls = ( "http://example.com/p", "ftp://example.com/p", "//example.com/p", ) for url in insecure_urls: with self.subTest(url=url): self.assertIs( url_has_allowed_host_and_scheme( url, allowed_hosts={"example.com"}, require_https=True ), False, ) class URLSafeBase64Tests(unittest.TestCase): def test_roundtrip(self): bytestring = b"foo" encoded = urlsafe_base64_encode(bytestring) decoded = urlsafe_base64_decode(encoded) self.assertEqual(bytestring, decoded) class IsSameDomainTests(unittest.TestCase): def test_good(self): for pair in ( ("example.com", "example.com"), ("example.com", ".example.com"), ("foo.example.com", ".example.com"), ("example.com:8888", "example.com:8888"), ("example.com:8888", ".example.com:8888"), ("foo.example.com:8888", ".example.com:8888"), ): self.assertIs(is_same_domain(*pair), True) def test_bad(self): for pair in ( ("example2.com", "example.com"), ("foo.example.com", "example.com"), ("example.com:9999", "example.com:8888"), ("foo.example.com:8888", ""), ): self.assertIs(is_same_domain(*pair), False) class ETagProcessingTests(unittest.TestCase): def test_parsing(self): self.assertEqual( parse_etags(r'"" , "etag", "e\\tag", W/"weak"'), ['""', '"etag"', r'"e\\tag"', 'W/"weak"'], ) self.assertEqual(parse_etags("*"), ["*"]) # Ignore RFC 2616 ETags that are invalid according to RFC 7232. self.assertEqual(parse_etags(r'"etag", "e\"t\"ag"'), ['"etag"']) def test_quoting(self): self.assertEqual(quote_etag("etag"), '"etag"') # unquoted self.assertEqual(quote_etag('"etag"'), '"etag"') # quoted self.assertEqual(quote_etag('W/"etag"'), 'W/"etag"') # quoted, weak class HttpDateProcessingTests(unittest.TestCase): def test_http_date(self): t = 1167616461.0 self.assertEqual(http_date(t), "Mon, 01 Jan 2007 01:54:21 GMT") def test_parsing_rfc1123(self): parsed = parse_http_date("Sun, 06 Nov 1994 08:49:37 GMT") self.assertEqual( datetime.fromtimestamp(parsed, timezone.utc), datetime(1994, 11, 6, 8, 49, 37, tzinfo=timezone.utc), ) @unittest.skipIf(platform.architecture()[0] == "32bit", "The Year 2038 problem.") @mock.patch("django.utils.http.datetime.datetime") def test_parsing_rfc850(self, mocked_datetime): mocked_datetime.side_effect = datetime mocked_datetime.now = mock.Mock() now_1 = datetime(2019, 11, 6, 8, 49, 37, tzinfo=timezone.utc) now_2 = datetime(2020, 11, 6, 8, 49, 37, tzinfo=timezone.utc) now_3 = datetime(2048, 11, 6, 8, 49, 37, tzinfo=timezone.utc) tests = ( ( now_1, "Tuesday, 31-Dec-69 08:49:37 GMT", datetime(2069, 12, 31, 8, 49, 37, tzinfo=timezone.utc), ), ( now_1, "Tuesday, 10-Nov-70 08:49:37 GMT", datetime(1970, 11, 10, 8, 49, 37, tzinfo=timezone.utc), ), ( now_1, "Sunday, 06-Nov-94 08:49:37 GMT", datetime(1994, 11, 6, 8, 49, 37, tzinfo=timezone.utc), ), ( now_2, "Wednesday, 31-Dec-70 08:49:37 GMT", datetime(2070, 12, 31, 8, 49, 37, tzinfo=timezone.utc), ), ( now_2, "Friday, 31-Dec-71 08:49:37 GMT", datetime(1971, 12, 31, 8, 49, 37, tzinfo=timezone.utc), ), ( now_3, "Sunday, 31-Dec-00 08:49:37 GMT", datetime(2000, 12, 31, 8, 49, 37, tzinfo=timezone.utc), ), ( now_3, "Friday, 31-Dec-99 08:49:37 GMT", datetime(1999, 12, 31, 8, 49, 37, tzinfo=timezone.utc), ), ) for now, rfc850str, expected_date in tests: with self.subTest(rfc850str=rfc850str): mocked_datetime.now.return_value = now parsed = parse_http_date(rfc850str) mocked_datetime.now.assert_called_once_with(tz=timezone.utc) self.assertEqual( datetime.fromtimestamp(parsed, timezone.utc), expected_date, ) mocked_datetime.reset_mock() def test_parsing_asctime(self): parsed = parse_http_date("Sun Nov 6 08:49:37 1994") self.assertEqual( datetime.fromtimestamp(parsed, timezone.utc), datetime(1994, 11, 6, 8, 49, 37, tzinfo=timezone.utc), ) def test_parsing_asctime_nonascii_digits(self): """Non-ASCII unicode decimals raise an error.""" with self.assertRaises(ValueError): parse_http_date("Sun Nov 6 08:49:37 1994") with self.assertRaises(ValueError): parse_http_date("Sun Nov 12 08:49:37 1994") def test_parsing_year_less_than_70(self): parsed = parse_http_date("Sun Nov 6 08:49:37 0037") self.assertEqual( datetime.fromtimestamp(parsed, timezone.utc), datetime(2037, 11, 6, 8, 49, 37, tzinfo=timezone.utc), ) class EscapeLeadingSlashesTests(unittest.TestCase): def test(self): tests = ( ("//example.com", "/%2Fexample.com"), ("//", "/%2F"), ) for url, expected in tests: with self.subTest(url=url): self.assertEqual(escape_leading_slashes(url), expected)
9207603d0071e2c1ceff6a8cf741ef641122b15d47665b6a564de94db6fb3257
import os import stat import sys import tempfile import unittest from django.core.exceptions import SuspiciousOperation from django.test import SimpleTestCase from django.utils import archive try: import bz2 # NOQA HAS_BZ2 = True except ImportError: HAS_BZ2 = False try: import lzma # NOQA HAS_LZMA = True except ImportError: HAS_LZMA = False class TestArchive(unittest.TestCase): def setUp(self): self.testdir = os.path.join(os.path.dirname(__file__), "archives") self.old_cwd = os.getcwd() os.chdir(self.testdir) def tearDown(self): os.chdir(self.old_cwd) def test_extract_function(self): with os.scandir(self.testdir) as entries: for entry in entries: with self.subTest(entry.name), tempfile.TemporaryDirectory() as tmpdir: if (entry.name.endswith(".bz2") and not HAS_BZ2) or ( entry.name.endswith((".lzma", ".xz")) and not HAS_LZMA ): continue archive.extract(entry.path, tmpdir) self.assertTrue(os.path.isfile(os.path.join(tmpdir, "1"))) self.assertTrue(os.path.isfile(os.path.join(tmpdir, "2"))) self.assertTrue(os.path.isfile(os.path.join(tmpdir, "foo", "1"))) self.assertTrue(os.path.isfile(os.path.join(tmpdir, "foo", "2"))) self.assertTrue( os.path.isfile(os.path.join(tmpdir, "foo", "bar", "1")) ) self.assertTrue( os.path.isfile(os.path.join(tmpdir, "foo", "bar", "2")) ) @unittest.skipIf( sys.platform == "win32", "Python on Windows has a limited os.chmod()." ) def test_extract_file_permissions(self): """archive.extract() preserves file permissions.""" mask = stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO umask = os.umask(0) os.umask(umask) # Restore the original umask. with os.scandir(self.testdir) as entries: for entry in entries: if ( entry.name.startswith("leadpath_") or (entry.name.endswith(".bz2") and not HAS_BZ2) or (entry.name.endswith((".lzma", ".xz")) and not HAS_LZMA) ): continue with self.subTest(entry.name), tempfile.TemporaryDirectory() as tmpdir: archive.extract(entry.path, tmpdir) # An executable file in the archive has executable # permissions. filepath = os.path.join(tmpdir, "executable") self.assertEqual(os.stat(filepath).st_mode & mask, 0o775) # A file is readable even if permission data is missing. filepath = os.path.join(tmpdir, "no_permissions") self.assertEqual(os.stat(filepath).st_mode & mask, 0o666 & ~umask) class TestArchiveInvalid(SimpleTestCase): def test_extract_function_traversal(self): archives_dir = os.path.join(os.path.dirname(__file__), "traversal_archives") tests = [ ("traversal.tar", ".."), ("traversal_absolute.tar", "/tmp/evil.py"), ] if sys.platform == "win32": tests += [ ("traversal_disk_win.tar", "d:evil.py"), ("traversal_disk_win.zip", "d:evil.py"), ] msg = "Archive contains invalid path: '%s'" for entry, invalid_path in tests: with self.subTest(entry), tempfile.TemporaryDirectory() as tmpdir: with self.assertRaisesMessage(SuspiciousOperation, msg % invalid_path): archive.extract(os.path.join(archives_dir, entry), tmpdir)
0625f8d2165c6281faf370c2bf0bc87f5827dc7a4f09292a9bcabdfa44dc24bd
import unittest from unittest import mock from django.utils.lorem_ipsum import paragraph, paragraphs, sentence, words class LoremIpsumTests(unittest.TestCase): def test_negative_words(self): """words(n) returns n + 19 words, even if n is negative.""" self.assertEqual( words(-5), "lorem ipsum dolor sit amet consectetur adipisicing elit sed do " "eiusmod tempor incididunt ut", ) def test_same_or_less_common_words(self): """words(n) for n < 19.""" self.assertEqual(words(7), "lorem ipsum dolor sit amet consectetur adipisicing") def test_common_words_in_string(self): """words(n) starts with the 19 standard lorem ipsum words for n > 19.""" self.assertTrue( words(25).startswith( "lorem ipsum dolor sit amet consectetur adipisicing elit sed " "do eiusmod tempor incididunt ut labore et dolore magna aliqua" ) ) def test_more_words_than_common(self): """words(n) returns n words for n > 19.""" self.assertEqual(len(words(25).split()), 25) def test_common_large_number_of_words(self): """words(n) has n words when n is greater than len(WORDS).""" self.assertEqual(len(words(500).split()), 500) @mock.patch("django.utils.lorem_ipsum.random.sample") def test_not_common_words(self, mock_sample): """words(n, common=False) returns random words.""" mock_sample.return_value = ["exercitationem", "perferendis"] self.assertEqual(words(2, common=False), "exercitationem perferendis") def test_sentence_starts_with_capital(self): """A sentence starts with a capital letter.""" self.assertTrue(sentence()[0].isupper()) @mock.patch("django.utils.lorem_ipsum.random.sample") @mock.patch("django.utils.lorem_ipsum.random.choice") @mock.patch("django.utils.lorem_ipsum.random.randint") def test_sentence(self, mock_randint, mock_choice, mock_sample): """ Sentences are built using some number of phrases and a set of words. """ mock_randint.return_value = 2 # Use two phrases. mock_sample.return_value = ["exercitationem", "perferendis"] mock_choice.return_value = "?" value = sentence() self.assertEqual(mock_randint.call_count, 3) self.assertEqual(mock_sample.call_count, 2) self.assertEqual(mock_choice.call_count, 1) self.assertEqual( value, "Exercitationem perferendis, exercitationem perferendis?" ) @mock.patch("django.utils.lorem_ipsum.random.choice") def test_sentence_ending(self, mock_choice): """Sentences end with a question mark or a period.""" mock_choice.return_value = "?" self.assertIn(sentence()[-1], "?") mock_choice.return_value = "." self.assertIn(sentence()[-1], ".") @mock.patch("django.utils.lorem_ipsum.random.sample") @mock.patch("django.utils.lorem_ipsum.random.choice") @mock.patch("django.utils.lorem_ipsum.random.randint") def test_paragraph(self, mock_paragraph_randint, mock_choice, mock_sample): """paragraph() generates a single paragraph.""" # Make creating 2 sentences use 2 phrases. mock_paragraph_randint.return_value = 2 mock_sample.return_value = ["exercitationem", "perferendis"] mock_choice.return_value = "." value = paragraph() self.assertEqual(mock_paragraph_randint.call_count, 7) self.assertEqual( value, ( "Exercitationem perferendis, exercitationem perferendis. " "Exercitationem perferendis, exercitationem perferendis." ), ) @mock.patch("django.utils.lorem_ipsum.random.sample") @mock.patch("django.utils.lorem_ipsum.random.choice") @mock.patch("django.utils.lorem_ipsum.random.randint") def test_paragraphs_not_common(self, mock_randint, mock_choice, mock_sample): """ paragraphs(1, common=False) generating one paragraph that's not the COMMON_P paragraph. """ # Make creating 2 sentences use 2 phrases. mock_randint.return_value = 2 mock_sample.return_value = ["exercitationem", "perferendis"] mock_choice.return_value = "." self.assertEqual( paragraphs(1, common=False), [ "Exercitationem perferendis, exercitationem perferendis. " "Exercitationem perferendis, exercitationem perferendis." ], ) self.assertEqual(mock_randint.call_count, 7) def test_paragraphs(self): """paragraphs(1) uses the COMMON_P paragraph.""" self.assertEqual( paragraphs(1), [ "Lorem ipsum dolor sit amet, consectetur adipisicing elit, " "sed do eiusmod tempor incididunt ut labore et dolore magna " "aliqua. Ut enim ad minim veniam, quis nostrud exercitation " "ullamco laboris nisi ut aliquip ex ea commodo consequat. " "Duis aute irure dolor in reprehenderit in voluptate velit " "esse cillum dolore eu fugiat nulla pariatur. Excepteur sint " "occaecat cupidatat non proident, sunt in culpa qui officia " "deserunt mollit anim id est laborum." ], )
84d5d98ffded2772b89a5d72180f25e6c2d0db4996dd8d9aa57707812f0e11f0
import copy import pickle import sys import warnings from unittest import TestCase from django.utils.functional import LazyObject, SimpleLazyObject, empty from .models import Category, CategoryInfo class Foo: """ A simple class with just one attribute. """ foo = "bar" def __eq__(self, other): return self.foo == other.foo class LazyObjectTestCase(TestCase): def lazy_wrap(self, wrapped_object): """ Wrap the given object into a LazyObject """ class AdHocLazyObject(LazyObject): def _setup(self): self._wrapped = wrapped_object return AdHocLazyObject() def test_getattribute(self): """ Proxy methods don't exist on wrapped objects unless they're set. """ attrs = [ "__getitem__", "__setitem__", "__delitem__", "__iter__", "__len__", "__contains__", ] foo = Foo() obj = self.lazy_wrap(foo) for attr in attrs: with self.subTest(attr): self.assertFalse(hasattr(obj, attr)) setattr(foo, attr, attr) obj_with_attr = self.lazy_wrap(foo) self.assertTrue(hasattr(obj_with_attr, attr)) self.assertEqual(getattr(obj_with_attr, attr), attr) def test_getattr(self): obj = self.lazy_wrap(Foo()) self.assertEqual(obj.foo, "bar") def test_getattr_falsey(self): class Thing: def __getattr__(self, key): return [] obj = self.lazy_wrap(Thing()) self.assertEqual(obj.main, []) def test_setattr(self): obj = self.lazy_wrap(Foo()) obj.foo = "BAR" obj.bar = "baz" self.assertEqual(obj.foo, "BAR") self.assertEqual(obj.bar, "baz") def test_setattr2(self): # Same as test_setattr but in reversed order obj = self.lazy_wrap(Foo()) obj.bar = "baz" obj.foo = "BAR" self.assertEqual(obj.foo, "BAR") self.assertEqual(obj.bar, "baz") def test_delattr(self): obj = self.lazy_wrap(Foo()) obj.bar = "baz" self.assertEqual(obj.bar, "baz") del obj.bar with self.assertRaises(AttributeError): obj.bar def test_cmp(self): obj1 = self.lazy_wrap("foo") obj2 = self.lazy_wrap("bar") obj3 = self.lazy_wrap("foo") self.assertEqual(obj1, "foo") self.assertEqual(obj1, obj3) self.assertNotEqual(obj1, obj2) self.assertNotEqual(obj1, "bar") def test_lt(self): obj1 = self.lazy_wrap(1) obj2 = self.lazy_wrap(2) self.assertLess(obj1, obj2) def test_gt(self): obj1 = self.lazy_wrap(1) obj2 = self.lazy_wrap(2) self.assertGreater(obj2, obj1) def test_bytes(self): obj = self.lazy_wrap(b"foo") self.assertEqual(bytes(obj), b"foo") def test_text(self): obj = self.lazy_wrap("foo") self.assertEqual(str(obj), "foo") def test_bool(self): # Refs #21840 for f in [False, 0, (), {}, [], None, set()]: self.assertFalse(self.lazy_wrap(f)) for t in [True, 1, (1,), {1: 2}, [1], object(), {1}]: self.assertTrue(t) def test_dir(self): obj = self.lazy_wrap("foo") self.assertEqual(dir(obj), dir("foo")) def test_len(self): for seq in ["asd", [1, 2, 3], {"a": 1, "b": 2, "c": 3}]: obj = self.lazy_wrap(seq) self.assertEqual(len(obj), 3) def test_class(self): self.assertIsInstance(self.lazy_wrap(42), int) class Bar(Foo): pass self.assertIsInstance(self.lazy_wrap(Bar()), Foo) def test_hash(self): obj = self.lazy_wrap("foo") d = {obj: "bar"} self.assertIn("foo", d) self.assertEqual(d["foo"], "bar") def test_contains(self): test_data = [ ("c", "abcde"), (2, [1, 2, 3]), ("a", {"a": 1, "b": 2, "c": 3}), (2, {1, 2, 3}), ] for needle, haystack in test_data: self.assertIn(needle, self.lazy_wrap(haystack)) # __contains__ doesn't work when the haystack is a string and the # needle a LazyObject. for needle_haystack in test_data[1:]: self.assertIn(self.lazy_wrap(needle), haystack) self.assertIn(self.lazy_wrap(needle), self.lazy_wrap(haystack)) def test_getitem(self): obj_list = self.lazy_wrap([1, 2, 3]) obj_dict = self.lazy_wrap({"a": 1, "b": 2, "c": 3}) self.assertEqual(obj_list[0], 1) self.assertEqual(obj_list[-1], 3) self.assertEqual(obj_list[1:2], [2]) self.assertEqual(obj_dict["b"], 2) with self.assertRaises(IndexError): obj_list[3] with self.assertRaises(KeyError): obj_dict["f"] def test_setitem(self): obj_list = self.lazy_wrap([1, 2, 3]) obj_dict = self.lazy_wrap({"a": 1, "b": 2, "c": 3}) obj_list[0] = 100 self.assertEqual(obj_list, [100, 2, 3]) obj_list[1:2] = [200, 300, 400] self.assertEqual(obj_list, [100, 200, 300, 400, 3]) obj_dict["a"] = 100 obj_dict["d"] = 400 self.assertEqual(obj_dict, {"a": 100, "b": 2, "c": 3, "d": 400}) def test_delitem(self): obj_list = self.lazy_wrap([1, 2, 3]) obj_dict = self.lazy_wrap({"a": 1, "b": 2, "c": 3}) del obj_list[-1] del obj_dict["c"] self.assertEqual(obj_list, [1, 2]) self.assertEqual(obj_dict, {"a": 1, "b": 2}) with self.assertRaises(IndexError): del obj_list[3] with self.assertRaises(KeyError): del obj_dict["f"] def test_iter(self): # Tests whether an object's custom `__iter__` method is being # used when iterating over it. class IterObject: def __init__(self, values): self.values = values def __iter__(self): return iter(self.values) original_list = ["test", "123"] self.assertEqual(list(self.lazy_wrap(IterObject(original_list))), original_list) def test_pickle(self): # See ticket #16563 obj = self.lazy_wrap(Foo()) obj.bar = "baz" pickled = pickle.dumps(obj) unpickled = pickle.loads(pickled) self.assertIsInstance(unpickled, Foo) self.assertEqual(unpickled, obj) self.assertEqual(unpickled.foo, obj.foo) self.assertEqual(unpickled.bar, obj.bar) # Test copying lazy objects wrapping both builtin types and user-defined # classes since a lot of the relevant code does __dict__ manipulation and # builtin types don't have __dict__. def test_copy_list(self): # Copying a list works and returns the correct objects. lst = [1, 2, 3] obj = self.lazy_wrap(lst) len(lst) # forces evaluation obj2 = copy.copy(obj) self.assertIsNot(obj, obj2) self.assertIsInstance(obj2, list) self.assertEqual(obj2, [1, 2, 3]) def test_copy_list_no_evaluation(self): # Copying a list doesn't force evaluation. lst = [1, 2, 3] obj = self.lazy_wrap(lst) obj2 = copy.copy(obj) self.assertIsNot(obj, obj2) self.assertIs(obj._wrapped, empty) self.assertIs(obj2._wrapped, empty) def test_copy_class(self): # Copying a class works and returns the correct objects. foo = Foo() obj = self.lazy_wrap(foo) str(foo) # forces evaluation obj2 = copy.copy(obj) self.assertIsNot(obj, obj2) self.assertIsInstance(obj2, Foo) self.assertEqual(obj2, Foo()) def test_copy_class_no_evaluation(self): # Copying a class doesn't force evaluation. foo = Foo() obj = self.lazy_wrap(foo) obj2 = copy.copy(obj) self.assertIsNot(obj, obj2) self.assertIs(obj._wrapped, empty) self.assertIs(obj2._wrapped, empty) def test_deepcopy_list(self): # Deep copying a list works and returns the correct objects. lst = [1, 2, 3] obj = self.lazy_wrap(lst) len(lst) # forces evaluation obj2 = copy.deepcopy(obj) self.assertIsNot(obj, obj2) self.assertIsInstance(obj2, list) self.assertEqual(obj2, [1, 2, 3]) def test_deepcopy_list_no_evaluation(self): # Deep copying doesn't force evaluation. lst = [1, 2, 3] obj = self.lazy_wrap(lst) obj2 = copy.deepcopy(obj) self.assertIsNot(obj, obj2) self.assertIs(obj._wrapped, empty) self.assertIs(obj2._wrapped, empty) def test_deepcopy_class(self): # Deep copying a class works and returns the correct objects. foo = Foo() obj = self.lazy_wrap(foo) str(foo) # forces evaluation obj2 = copy.deepcopy(obj) self.assertIsNot(obj, obj2) self.assertIsInstance(obj2, Foo) self.assertEqual(obj2, Foo()) def test_deepcopy_class_no_evaluation(self): # Deep copying doesn't force evaluation. foo = Foo() obj = self.lazy_wrap(foo) obj2 = copy.deepcopy(obj) self.assertIsNot(obj, obj2) self.assertIs(obj._wrapped, empty) self.assertIs(obj2._wrapped, empty) class SimpleLazyObjectTestCase(LazyObjectTestCase): # By inheriting from LazyObjectTestCase and redefining the lazy_wrap() # method which all testcases use, we get to make sure all behaviors # tested in the parent testcase also apply to SimpleLazyObject. def lazy_wrap(self, wrapped_object): return SimpleLazyObject(lambda: wrapped_object) def test_repr(self): # First, for an unevaluated SimpleLazyObject obj = self.lazy_wrap(42) # __repr__ contains __repr__ of setup function and does not evaluate # the SimpleLazyObject self.assertRegex(repr(obj), "^<SimpleLazyObject:") self.assertIs(obj._wrapped, empty) # make sure evaluation hasn't been triggered self.assertEqual(obj, 42) # evaluate the lazy object self.assertIsInstance(obj._wrapped, int) self.assertEqual(repr(obj), "<SimpleLazyObject: 42>") def test_add(self): obj1 = self.lazy_wrap(1) self.assertEqual(obj1 + 1, 2) obj2 = self.lazy_wrap(2) self.assertEqual(obj2 + obj1, 3) self.assertEqual(obj1 + obj2, 3) def test_radd(self): obj1 = self.lazy_wrap(1) self.assertEqual(1 + obj1, 2) def test_trace(self): # See ticket #19456 old_trace_func = sys.gettrace() try: def trace_func(frame, event, arg): frame.f_locals["self"].__class__ if old_trace_func is not None: old_trace_func(frame, event, arg) sys.settrace(trace_func) self.lazy_wrap(None) finally: sys.settrace(old_trace_func) def test_none(self): i = [0] def f(): i[0] += 1 return None x = SimpleLazyObject(f) self.assertEqual(str(x), "None") self.assertEqual(i, [1]) self.assertEqual(str(x), "None") self.assertEqual(i, [1]) def test_dict(self): # See ticket #18447 lazydict = SimpleLazyObject(lambda: {"one": 1}) self.assertEqual(lazydict["one"], 1) lazydict["one"] = -1 self.assertEqual(lazydict["one"], -1) self.assertIn("one", lazydict) self.assertNotIn("two", lazydict) self.assertEqual(len(lazydict), 1) del lazydict["one"] with self.assertRaises(KeyError): lazydict["one"] def test_list_set(self): lazy_list = SimpleLazyObject(lambda: [1, 2, 3, 4, 5]) lazy_set = SimpleLazyObject(lambda: {1, 2, 3, 4}) self.assertIn(1, lazy_list) self.assertIn(1, lazy_set) self.assertNotIn(6, lazy_list) self.assertNotIn(6, lazy_set) self.assertEqual(len(lazy_list), 5) self.assertEqual(len(lazy_set), 4) class BaseBaz: """ A base class with a funky __reduce__ method, meant to simulate the __reduce__ method of Model, which sets self._django_version. """ def __init__(self): self.baz = "wrong" def __reduce__(self): self.baz = "right" return super().__reduce__() def __eq__(self, other): if self.__class__ != other.__class__: return False for attr in ["bar", "baz", "quux"]: if hasattr(self, attr) != hasattr(other, attr): return False elif getattr(self, attr, None) != getattr(other, attr, None): return False return True class Baz(BaseBaz): """ A class that inherits from BaseBaz and has its own __reduce_ex__ method. """ def __init__(self, bar): self.bar = bar super().__init__() def __reduce_ex__(self, proto): self.quux = "quux" return super().__reduce_ex__(proto) class BazProxy(Baz): """ A class that acts as a proxy for Baz. It does some scary mucking about with dicts, which simulates some crazy things that people might do with e.g. proxy models. """ def __init__(self, baz): self.__dict__ = baz.__dict__ self._baz = baz # Grandparent super super(BaseBaz, self).__init__() class SimpleLazyObjectPickleTestCase(TestCase): """ Regression test for pickling a SimpleLazyObject wrapping a model (#25389). Also covers other classes with a custom __reduce__ method. """ def test_pickle_with_reduce(self): """ Test in a fairly synthetic setting. """ # Test every pickle protocol available for protocol in range(pickle.HIGHEST_PROTOCOL + 1): lazy_objs = [ SimpleLazyObject(lambda: BaseBaz()), SimpleLazyObject(lambda: Baz(1)), SimpleLazyObject(lambda: BazProxy(Baz(2))), ] for obj in lazy_objs: pickled = pickle.dumps(obj, protocol) unpickled = pickle.loads(pickled) self.assertEqual(unpickled, obj) self.assertEqual(unpickled.baz, "right") def test_pickle_model(self): """ Test on an actual model, based on the report in #25426. """ category = Category.objects.create(name="thing1") CategoryInfo.objects.create(category=category) # Test every pickle protocol available for protocol in range(pickle.HIGHEST_PROTOCOL + 1): lazy_category = SimpleLazyObject(lambda: category) # Test both if we accessed a field on the model and if we didn't. lazy_category.categoryinfo lazy_category_2 = SimpleLazyObject(lambda: category) with warnings.catch_warnings(record=True) as recorded: self.assertEqual( pickle.loads(pickle.dumps(lazy_category, protocol)), category ) self.assertEqual( pickle.loads(pickle.dumps(lazy_category_2, protocol)), category ) # Assert that there were no warnings. self.assertEqual(len(recorded), 0)
5e3393660c6341ec1e320c57faef76a5593d382955662d5a67a1d91ca1874c0f
"""Tests for jslex.""" # originally from https://bitbucket.org/ned/jslex from django.test import SimpleTestCase from django.utils.jslex import JsLexer, prepare_js_for_gettext class JsTokensTest(SimpleTestCase): LEX_CASES = [ # ids ("a ABC $ _ a123", ["id a", "id ABC", "id $", "id _", "id a123"]), ( "\\u1234 abc\\u0020 \\u0065_\\u0067", ["id \\u1234", "id abc\\u0020", "id \\u0065_\\u0067"], ), # numbers ( "123 1.234 0.123e-3 0 1E+40 1e1 .123", [ "dnum 123", "dnum 1.234", "dnum 0.123e-3", "dnum 0", "dnum 1E+40", "dnum 1e1", "dnum .123", ], ), ("0x1 0xabCD 0XABcd", ["hnum 0x1", "hnum 0xabCD", "hnum 0XABcd"]), ("010 0377 090", ["onum 010", "onum 0377", "dnum 0", "dnum 90"]), ("0xa123ghi", ["hnum 0xa123", "id ghi"]), # keywords ( "function Function FUNCTION", ["keyword function", "id Function", "id FUNCTION"], ), ( "const constructor in inherits", ["keyword const", "id constructor", "keyword in", "id inherits"], ), ("true true_enough", ["reserved true", "id true_enough"]), # strings (""" 'hello' "hello" """, ["string 'hello'", 'string "hello"']), ( r""" 'don\'t' "don\"t" '"' "'" '\'' "\"" """, [ r"""string 'don\'t'""", r'''string "don\"t"''', r"""string '"'""", r'''string "'"''', r"""string '\''""", r'''string "\""''', ], ), (r'"ƃuıxǝ⅂ ʇdıɹɔsɐʌɐſ\""', [r'string "ƃuıxǝ⅂ ʇdıɹɔsɐʌɐſ\""']), # comments ("a//b", ["id a", "linecomment //b"]), ( "/****/a/=2//hello", ["comment /****/", "id a", "punct /=", "dnum 2", "linecomment //hello"], ), ( "/*\n * Header\n */\na=1;", ["comment /*\n * Header\n */", "id a", "punct =", "dnum 1", "punct ;"], ), # punctuation ("a+++b", ["id a", "punct ++", "punct +", "id b"]), # regex (r"a=/a*/,1", ["id a", "punct =", "regex /a*/", "punct ,", "dnum 1"]), (r"a=/a*[^/]+/,1", ["id a", "punct =", "regex /a*[^/]+/", "punct ,", "dnum 1"]), (r"a=/a*\[^/,1", ["id a", "punct =", r"regex /a*\[^/", "punct ,", "dnum 1"]), (r"a=/\//,1", ["id a", "punct =", r"regex /\//", "punct ,", "dnum 1"]), # next two are from https://www-archive.mozilla.org/js/language/js20-2002-04/rationale/syntax.html#regular-expressions # NOQA ( 'for (var x = a in foo && "</x>" || mot ? z:/x:3;x<5;y</g/i) {xyz(x++);}', [ "keyword for", "punct (", "keyword var", "id x", "punct =", "id a", "keyword in", "id foo", "punct &&", 'string "</x>"', "punct ||", "id mot", "punct ?", "id z", "punct :", "regex /x:3;x<5;y</g", "punct /", "id i", "punct )", "punct {", "id xyz", "punct (", "id x", "punct ++", "punct )", "punct ;", "punct }", ], ), ( 'for (var x = a in foo && "</x>" || mot ? z/x:3;x<5;y</g/i) {xyz(x++);}', [ "keyword for", "punct (", "keyword var", "id x", "punct =", "id a", "keyword in", "id foo", "punct &&", 'string "</x>"', "punct ||", "id mot", "punct ?", "id z", "punct /", "id x", "punct :", "dnum 3", "punct ;", "id x", "punct <", "dnum 5", "punct ;", "id y", "punct <", "regex /g/i", "punct )", "punct {", "id xyz", "punct (", "id x", "punct ++", "punct )", "punct ;", "punct }", ], ), # Various "illegal" regexes that are valid according to the std. ( r"""/????/, /++++/, /[----]/ """, ["regex /????/", "punct ,", "regex /++++/", "punct ,", "regex /[----]/"], ), # Stress cases from https://stackoverflow.com/questions/5533925/what-javascript-constructs-does-jslex-incorrectly-lex/5573409#5573409 # NOQA (r"""/\[/""", [r"""regex /\[/"""]), (r"""/[i]/""", [r"""regex /[i]/"""]), (r"""/[\]]/""", [r"""regex /[\]]/"""]), (r"""/a[\]]/""", [r"""regex /a[\]]/"""]), (r"""/a[\]]b/""", [r"""regex /a[\]]b/"""]), (r"""/[\]/]/gi""", [r"""regex /[\]/]/gi"""]), (r"""/\[[^\]]+\]/gi""", [r"""regex /\[[^\]]+\]/gi"""]), ( r""" rexl.re = { NAME: /^(?![0-9])(?:\w)+|^"(?:[^"]|"")+"/, UNQUOTED_LITERAL: /^@(?:(?![0-9])(?:\w|\:)+|^"(?:[^"]|"")+")\[[^\]]+\]/, QUOTED_LITERAL: /^'(?:[^']|'')*'/, NUMERIC_LITERAL: /^[0-9]+(?:\.[0-9]*(?:[eE][-+][0-9]+)?)?/, SYMBOL: /^(?:==|=|<>|<=|<|>=|>|!~~|!~|~~|~|!==|!=|!~=|!~|!|&|\||\.|\:|,|\(|\)|\[|\]|\{|\}|\?|\:|;|@|\^|\/\+|\/|\*|\+|-)/ }; """, # NOQA [ "id rexl", "punct .", "id re", "punct =", "punct {", "id NAME", "punct :", r"""regex /^(?![0-9])(?:\w)+|^"(?:[^"]|"")+"/""", "punct ,", "id UNQUOTED_LITERAL", "punct :", r"""regex /^@(?:(?![0-9])(?:\w|\:)+|^"(?:[^"]|"")+")\[[^\]]+\]/""", "punct ,", "id QUOTED_LITERAL", "punct :", r"""regex /^'(?:[^']|'')*'/""", "punct ,", "id NUMERIC_LITERAL", "punct :", r"""regex /^[0-9]+(?:\.[0-9]*(?:[eE][-+][0-9]+)?)?/""", "punct ,", "id SYMBOL", "punct :", r"""regex /^(?:==|=|<>|<=|<|>=|>|!~~|!~|~~|~|!==|!=|!~=|!~|!|&|\||\.|\:|,|\(|\)|\[|\]|\{|\}|\?|\:|;|@|\^|\/\+|\/|\*|\+|-)/""", # NOQA "punct }", "punct ;", ], ), ( r""" rexl.re = { NAME: /^(?![0-9])(?:\w)+|^"(?:[^"]|"")+"/, UNQUOTED_LITERAL: /^@(?:(?![0-9])(?:\w|\:)+|^"(?:[^"]|"")+")\[[^\]]+\]/, QUOTED_LITERAL: /^'(?:[^']|'')*'/, NUMERIC_LITERAL: /^[0-9]+(?:\.[0-9]*(?:[eE][-+][0-9]+)?)?/, SYMBOL: /^(?:==|=|<>|<=|<|>=|>|!~~|!~|~~|~|!==|!=|!~=|!~|!|&|\||\.|\:|,|\(|\)|\[|\]|\{|\}|\?|\:|;|@|\^|\/\+|\/|\*|\+|-)/ }; str = '"'; """, # NOQA [ "id rexl", "punct .", "id re", "punct =", "punct {", "id NAME", "punct :", r"""regex /^(?![0-9])(?:\w)+|^"(?:[^"]|"")+"/""", "punct ,", "id UNQUOTED_LITERAL", "punct :", r"""regex /^@(?:(?![0-9])(?:\w|\:)+|^"(?:[^"]|"")+")\[[^\]]+\]/""", "punct ,", "id QUOTED_LITERAL", "punct :", r"""regex /^'(?:[^']|'')*'/""", "punct ,", "id NUMERIC_LITERAL", "punct :", r"""regex /^[0-9]+(?:\.[0-9]*(?:[eE][-+][0-9]+)?)?/""", "punct ,", "id SYMBOL", "punct :", r"""regex /^(?:==|=|<>|<=|<|>=|>|!~~|!~|~~|~|!==|!=|!~=|!~|!|&|\||\.|\:|,|\(|\)|\[|\]|\{|\}|\?|\:|;|@|\^|\/\+|\/|\*|\+|-)/""", # NOQA "punct }", "punct ;", "id str", "punct =", """string '"'""", "punct ;", ], ), ( r' this._js = "e.str(\"" + this.value.replace(/\\/g, "\\\\")' r'.replace(/"/g, "\\\"") + "\")"; ', [ "keyword this", "punct .", "id _js", "punct =", r'''string "e.str(\""''', "punct +", "keyword this", "punct .", "id value", "punct .", "id replace", "punct (", r"regex /\\/g", "punct ,", r'string "\\\\"', "punct )", "punct .", "id replace", "punct (", r'regex /"/g', "punct ,", r'string "\\\""', "punct )", "punct +", r'string "\")"', "punct ;", ], ), ] def make_function(input, toks): def test_func(self): lexer = JsLexer() result = [ "%s %s" % (name, tok) for name, tok in lexer.lex(input) if name != "ws" ] self.assertEqual(result, toks) return test_func for i, (input, toks) in enumerate(JsTokensTest.LEX_CASES): setattr(JsTokensTest, "test_case_%d" % i, make_function(input, toks)) GETTEXT_CASES = ( ( r""" a = 1; /* /[0-9]+/ */ b = 0x2a0b / 1; // /[0-9]+/ c = 3; """, r""" a = 1; /* /[0-9]+/ */ b = 0x2a0b / 1; // /[0-9]+/ c = 3; """, ), ( r""" a = 1.234e-5; /* * /[0-9+/ */ b = .0123; """, r""" a = 1.234e-5; /* * /[0-9+/ */ b = .0123; """, ), ( r""" x = y / z; alert(gettext("hello")); x /= 3; """, r""" x = y / z; alert(gettext("hello")); x /= 3; """, ), ( r""" s = "Hello \"th/foo/ere\""; s = 'He\x23llo \'th/foo/ere\''; s = 'slash quote \", just quote "'; """, r""" s = "Hello \"th/foo/ere\""; s = "He\x23llo \'th/foo/ere\'"; s = "slash quote \", just quote \""; """, ), ( r""" s = "Line continuation\ continued /hello/ still the string";/hello/; """, r""" s = "Line continuation\ continued /hello/ still the string";"REGEX"; """, ), ( r""" var regex = /pattern/; var regex2 = /matter/gm; var regex3 = /[*/]+/gm.foo("hey"); """, r""" var regex = "REGEX"; var regex2 = "REGEX"; var regex3 = "REGEX".foo("hey"); """, ), ( r""" for (var x = a in foo && "</x>" || mot ? z:/x:3;x<5;y</g/i) {xyz(x++);} for (var x = a in foo && "</x>" || mot ? z/x:3;x<5;y</g/i) {xyz(x++);} """, r""" for (var x = a in foo && "</x>" || mot ? z:"REGEX"/i) {xyz(x++);} for (var x = a in foo && "</x>" || mot ? z/x:3;x<5;y<"REGEX") {xyz(x++);} """, ), ( """ \\u1234xyz = gettext('Hello there'); """, r""" Uu1234xyz = gettext("Hello there"); """, ), ) class JsToCForGettextTest(SimpleTestCase): pass def make_function(js, c): def test_func(self): self.assertEqual(prepare_js_for_gettext(js), c) return test_func for i, pair in enumerate(GETTEXT_CASES): setattr(JsToCForGettextTest, "test_case_%d" % i, make_function(*pair))
cb6edce654146e38af4a5ddceaaff4d742b47f5f1cfe8de97ef01a2980830f56
from django.http import HttpResponse from django.template import engines from django.template.response import TemplateResponse from django.test import RequestFactory, SimpleTestCase from django.utils.decorators import decorator_from_middleware class ProcessViewMiddleware: def __init__(self, get_response): self.get_response = get_response def process_view(self, request, view_func, view_args, view_kwargs): pass process_view_dec = decorator_from_middleware(ProcessViewMiddleware) @process_view_dec def process_view(request): return HttpResponse() class ClassProcessView: def __call__(self, request): return HttpResponse() class_process_view = process_view_dec(ClassProcessView()) class FullMiddleware: def __init__(self, get_response): self.get_response = get_response def process_request(self, request): request.process_request_reached = True def process_view(self, request, view_func, view_args, view_kwargs): request.process_view_reached = True def process_template_response(self, request, response): request.process_template_response_reached = True return response def process_response(self, request, response): # This should never receive unrendered content. request.process_response_content = response.content request.process_response_reached = True return response full_dec = decorator_from_middleware(FullMiddleware) class DecoratorFromMiddlewareTests(SimpleTestCase): """ Tests for view decorators created using ``django.utils.decorators.decorator_from_middleware``. """ rf = RequestFactory() def test_process_view_middleware(self): """ Test a middleware that implements process_view. """ process_view(self.rf.get("/")) def test_callable_process_view_middleware(self): """ Test a middleware that implements process_view, operating on a callable class. """ class_process_view(self.rf.get("/")) def test_full_dec_normal(self): """ All methods of middleware are called for normal HttpResponses """ @full_dec def normal_view(request): template = engines["django"].from_string("Hello world") return HttpResponse(template.render()) request = self.rf.get("/") normal_view(request) self.assertTrue(getattr(request, "process_request_reached", False)) self.assertTrue(getattr(request, "process_view_reached", False)) # process_template_response must not be called for HttpResponse self.assertFalse(getattr(request, "process_template_response_reached", False)) self.assertTrue(getattr(request, "process_response_reached", False)) def test_full_dec_templateresponse(self): """ All methods of middleware are called for TemplateResponses in the right sequence. """ @full_dec def template_response_view(request): template = engines["django"].from_string("Hello world") return TemplateResponse(request, template) request = self.rf.get("/") response = template_response_view(request) self.assertTrue(getattr(request, "process_request_reached", False)) self.assertTrue(getattr(request, "process_view_reached", False)) self.assertTrue(getattr(request, "process_template_response_reached", False)) # response must not be rendered yet. self.assertFalse(response._is_rendered) # process_response must not be called until after response is rendered, # otherwise some decorators like csrf_protect and gzip_page will not # work correctly. See #16004 self.assertFalse(getattr(request, "process_response_reached", False)) response.render() self.assertTrue(getattr(request, "process_response_reached", False)) # process_response saw the rendered content self.assertEqual(request.process_response_content, b"Hello world")
7c42b77eb0d43e0cdf6f3f12a86a6975a1495c3ab1611f45bcaf68117a90daa4
import datetime from django.test import SimpleTestCase from django.utils import feedgenerator from django.utils.timezone import get_fixed_timezone, utc class FeedgeneratorTests(SimpleTestCase): """ Tests for the low-level syndication feed framework. """ def test_get_tag_uri(self): """ get_tag_uri() correctly generates TagURIs. """ self.assertEqual( feedgenerator.get_tag_uri( "http://example.org/foo/bar#headline", datetime.date(2004, 10, 25) ), "tag:example.org,2004-10-25:/foo/bar/headline", ) def test_get_tag_uri_with_port(self): """ get_tag_uri() correctly generates TagURIs from URLs with port numbers. """ self.assertEqual( feedgenerator.get_tag_uri( "http://www.example.org:8000/2008/11/14/django#headline", datetime.datetime(2008, 11, 14, 13, 37, 0), ), "tag:www.example.org,2008-11-14:/2008/11/14/django/headline", ) def test_rfc2822_date(self): """ rfc2822_date() correctly formats datetime objects. """ self.assertEqual( feedgenerator.rfc2822_date(datetime.datetime(2008, 11, 14, 13, 37, 0)), "Fri, 14 Nov 2008 13:37:00 -0000", ) def test_rfc2822_date_with_timezone(self): """ rfc2822_date() correctly formats datetime objects with tzinfo. """ self.assertEqual( feedgenerator.rfc2822_date( datetime.datetime( 2008, 11, 14, 13, 37, 0, tzinfo=get_fixed_timezone(60) ) ), "Fri, 14 Nov 2008 13:37:00 +0100", ) def test_rfc2822_date_without_time(self): """ rfc2822_date() correctly formats date objects. """ self.assertEqual( feedgenerator.rfc2822_date(datetime.date(2008, 11, 14)), "Fri, 14 Nov 2008 00:00:00 -0000", ) def test_rfc3339_date(self): """ rfc3339_date() correctly formats datetime objects. """ self.assertEqual( feedgenerator.rfc3339_date(datetime.datetime(2008, 11, 14, 13, 37, 0)), "2008-11-14T13:37:00Z", ) def test_rfc3339_date_with_timezone(self): """ rfc3339_date() correctly formats datetime objects with tzinfo. """ self.assertEqual( feedgenerator.rfc3339_date( datetime.datetime( 2008, 11, 14, 13, 37, 0, tzinfo=get_fixed_timezone(120) ) ), "2008-11-14T13:37:00+02:00", ) def test_rfc3339_date_without_time(self): """ rfc3339_date() correctly formats date objects. """ self.assertEqual( feedgenerator.rfc3339_date(datetime.date(2008, 11, 14)), "2008-11-14T00:00:00Z", ) def test_atom1_mime_type(self): """ Atom MIME type has UTF8 Charset parameter set """ atom_feed = feedgenerator.Atom1Feed("title", "link", "description") self.assertEqual(atom_feed.content_type, "application/atom+xml; charset=utf-8") def test_rss_mime_type(self): """ RSS MIME type has UTF8 Charset parameter set """ rss_feed = feedgenerator.Rss201rev2Feed("title", "link", "description") self.assertEqual(rss_feed.content_type, "application/rss+xml; charset=utf-8") # Two regression tests for #14202 def test_feed_without_feed_url_gets_rendered_without_atom_link(self): feed = feedgenerator.Rss201rev2Feed("title", "/link/", "descr") self.assertIsNone(feed.feed["feed_url"]) feed_content = feed.writeString("utf-8") self.assertNotIn("<atom:link", feed_content) self.assertNotIn('href="/feed/"', feed_content) self.assertNotIn('rel="self"', feed_content) def test_feed_with_feed_url_gets_rendered_with_atom_link(self): feed = feedgenerator.Rss201rev2Feed( "title", "/link/", "descr", feed_url="/feed/" ) self.assertEqual(feed.feed["feed_url"], "/feed/") feed_content = feed.writeString("utf-8") self.assertIn("<atom:link", feed_content) self.assertIn('href="/feed/"', feed_content) self.assertIn('rel="self"', feed_content) def test_atom_add_item(self): # Not providing any optional arguments to Atom1Feed.add_item() feed = feedgenerator.Atom1Feed("title", "/link/", "descr") feed.add_item("item_title", "item_link", "item_description") feed.writeString("utf-8") def test_deterministic_attribute_order(self): feed = feedgenerator.Atom1Feed("title", "/link/", "desc") feed_content = feed.writeString("utf-8") self.assertIn('href="/link/" rel="alternate"', feed_content) def test_latest_post_date_returns_utc_time(self): for use_tz in (True, False): with self.settings(USE_TZ=use_tz): rss_feed = feedgenerator.Rss201rev2Feed("title", "link", "description") self.assertEqual(rss_feed.latest_post_date().tzinfo, utc)
1d61c4895f68f4dcbb3e189910fcb9b23f284dfb6acb03b0ad1ece6629467eb5
from unittest import TestCase from django.test import ignore_warnings from django.utils.deprecation import RemovedInDjango50Warning with ignore_warnings(category=RemovedInDjango50Warning): from django.utils.baseconv import ( BaseConverter, base2, base16, base36, base56, base62, base64, ) # RemovedInDjango50Warning class TestBaseConv(TestCase): def test_baseconv(self): nums = [-(10**10), 10**10, *range(-100, 100)] for converter in [base2, base16, base36, base56, base62, base64]: for i in nums: self.assertEqual(i, converter.decode(converter.encode(i))) def test_base11(self): base11 = BaseConverter("0123456789-", sign="$") self.assertEqual(base11.encode(1234), "-22") self.assertEqual(base11.decode("-22"), 1234) self.assertEqual(base11.encode(-1234), "$-22") self.assertEqual(base11.decode("$-22"), -1234) def test_base20(self): base20 = BaseConverter("0123456789abcdefghij") self.assertEqual(base20.encode(1234), "31e") self.assertEqual(base20.decode("31e"), 1234) self.assertEqual(base20.encode(-1234), "-31e") self.assertEqual(base20.decode("-31e"), -1234) def test_base64(self): self.assertEqual(base64.encode(1234), "JI") self.assertEqual(base64.decode("JI"), 1234) self.assertEqual(base64.encode(-1234), "$JI") self.assertEqual(base64.decode("$JI"), -1234) def test_base7(self): base7 = BaseConverter("cjdhel3", sign="g") self.assertEqual(base7.encode(1234), "hejd") self.assertEqual(base7.decode("hejd"), 1234) self.assertEqual(base7.encode(-1234), "ghejd") self.assertEqual(base7.decode("ghejd"), -1234) def test_exception(self): with self.assertRaises(ValueError): BaseConverter("abc", sign="a") self.assertIsInstance(BaseConverter("abc", sign="d"), BaseConverter) def test_repr(self): base7 = BaseConverter("cjdhel3", sign="g") self.assertEqual(repr(base7), "<BaseConverter: base7 (cjdhel3)>")
e5e8ac551399aa16b021e729db3def2826292c02066af87df1fadcd8be295179
import json import sys from django.core.exceptions import SuspiciousFileOperation from django.test import SimpleTestCase from django.utils import text from django.utils.functional import lazystr from django.utils.text import format_lazy from django.utils.translation import gettext_lazy, override IS_WIDE_BUILD = len("\U0001F4A9") == 1 class TestUtilsText(SimpleTestCase): def test_get_text_list(self): self.assertEqual(text.get_text_list(["a", "b", "c", "d"]), "a, b, c or d") self.assertEqual(text.get_text_list(["a", "b", "c"], "and"), "a, b and c") self.assertEqual(text.get_text_list(["a", "b"], "and"), "a and b") self.assertEqual(text.get_text_list(["a"]), "a") self.assertEqual(text.get_text_list([]), "") with override("ar"): self.assertEqual(text.get_text_list(["a", "b", "c"]), "a، b أو c") def test_smart_split(self): testdata = [ ('This is "a person" test.', ["This", "is", '"a person"', "test."]), ('This is "a person\'s" test.', ["This", "is", '"a person\'s"', "test."]), ('This is "a person\\"s" test.', ["This", "is", '"a person\\"s"', "test."]), ("\"a 'one", ['"a', "'one"]), ("all friends' tests", ["all", "friends'", "tests"]), ( 'url search_page words="something else"', ["url", "search_page", 'words="something else"'], ), ( "url search_page words='something else'", ["url", "search_page", "words='something else'"], ), ( 'url search_page words "something else"', ["url", "search_page", "words", '"something else"'], ), ( 'url search_page words-"something else"', ["url", "search_page", 'words-"something else"'], ), ("url search_page words=hello", ["url", "search_page", "words=hello"]), ( 'url search_page words="something else', ["url", "search_page", 'words="something', "else"], ), ("cut:','|cut:' '", ["cut:','|cut:' '"]), (lazystr("a b c d"), ["a", "b", "c", "d"]), # Test for #20231 ] for test, expected in testdata: with self.subTest(value=test): self.assertEqual(list(text.smart_split(test)), expected) def test_truncate_chars(self): truncator = text.Truncator("The quick brown fox jumped over the lazy dog.") self.assertEqual( "The quick brown fox jumped over the lazy dog.", truncator.chars(100) ), self.assertEqual("The quick brown fox …", truncator.chars(21)), self.assertEqual("The quick brown fo.....", truncator.chars(23, ".....")), self.assertEqual(".....", truncator.chars(4, ".....")), nfc = text.Truncator("o\xfco\xfco\xfco\xfc") nfd = text.Truncator("ou\u0308ou\u0308ou\u0308ou\u0308") self.assertEqual("oüoüoüoü", nfc.chars(8)) self.assertEqual("oüoüoüoü", nfd.chars(8)) self.assertEqual("oü…", nfc.chars(3)) self.assertEqual("oü…", nfd.chars(3)) # Ensure the final length is calculated correctly when there are # combining characters with no precomposed form, and that combining # characters are not split up. truncator = text.Truncator("-B\u030AB\u030A----8") self.assertEqual("-B\u030A…", truncator.chars(3)) self.assertEqual("-B\u030AB\u030A-…", truncator.chars(5)) self.assertEqual("-B\u030AB\u030A----8", truncator.chars(8)) # Ensure the length of the end text is correctly calculated when it # contains combining characters with no precomposed form. truncator = text.Truncator("-----") self.assertEqual("---B\u030A", truncator.chars(4, "B\u030A")) self.assertEqual("-----", truncator.chars(5, "B\u030A")) # Make a best effort to shorten to the desired length, but requesting # a length shorter than the ellipsis shouldn't break self.assertEqual("…", text.Truncator("asdf").chars(0)) # lazy strings are handled correctly self.assertEqual( text.Truncator(lazystr("The quick brown fox")).chars(10), "The quick…" ) def test_truncate_chars_html(self): perf_test_values = [ (("</a" + "\t" * 50000) + "//>", None), ("&" * 50000, "&" * 9 + "…"), ("_X<<<<<<<<<<<>", None), ] for value, expected in perf_test_values: with self.subTest(value=value): truncator = text.Truncator(value) self.assertEqual( expected if expected else value, truncator.chars(10, html=True) ) def test_truncate_words(self): truncator = text.Truncator("The quick brown fox jumped over the lazy dog.") self.assertEqual( "The quick brown fox jumped over the lazy dog.", truncator.words(10) ) self.assertEqual("The quick brown fox…", truncator.words(4)) self.assertEqual("The quick brown fox[snip]", truncator.words(4, "[snip]")) # lazy strings are handled correctly truncator = text.Truncator( lazystr("The quick brown fox jumped over the lazy dog.") ) self.assertEqual("The quick brown fox…", truncator.words(4)) def test_truncate_html_words(self): truncator = text.Truncator( '<p id="par"><strong><em>The quick brown fox jumped over the lazy dog.</em>' "</strong></p>" ) self.assertEqual( '<p id="par"><strong><em>The quick brown fox jumped over the lazy dog.</em>' "</strong></p>", truncator.words(10, html=True), ) self.assertEqual( '<p id="par"><strong><em>The quick brown fox…</em></strong></p>', truncator.words(4, html=True), ) self.assertEqual( '<p id="par"><strong><em>The quick brown fox....</em></strong></p>', truncator.words(4, "....", html=True), ) self.assertEqual( '<p id="par"><strong><em>The quick brown fox</em></strong></p>', truncator.words(4, "", html=True), ) # Test with new line inside tag truncator = text.Truncator( '<p>The quick <a href="xyz.html"\n id="mylink">brown fox</a> jumped over ' "the lazy dog.</p>" ) self.assertEqual( '<p>The quick <a href="xyz.html"\n id="mylink">brown…</a></p>', truncator.words(3, html=True), ) # Test self-closing tags truncator = text.Truncator( "<br/>The <hr />quick brown fox jumped over the lazy dog." ) self.assertEqual("<br/>The <hr />quick brown…", truncator.words(3, html=True)) truncator = text.Truncator( "<br>The <hr/>quick <em>brown fox</em> jumped over the lazy dog." ) self.assertEqual( "<br>The <hr/>quick <em>brown…</em>", truncator.words(3, html=True) ) # Test html entities truncator = text.Truncator( "<i>Buenos d&iacute;as! &#x00bf;C&oacute;mo est&aacute;?</i>" ) self.assertEqual( "<i>Buenos d&iacute;as! &#x00bf;C&oacute;mo…</i>", truncator.words(3, html=True), ) truncator = text.Truncator("<p>I &lt;3 python, what about you?</p>") self.assertEqual("<p>I &lt;3 python,…</p>", truncator.words(3, html=True)) perf_test_values = [ ("</a" + "\t" * 50000) + "//>", "&" * 50000, "_X<<<<<<<<<<<>", ] for value in perf_test_values: with self.subTest(value=value): truncator = text.Truncator(value) self.assertEqual(value, truncator.words(50, html=True)) def test_wrap(self): digits = "1234 67 9" self.assertEqual(text.wrap(digits, 100), "1234 67 9") self.assertEqual(text.wrap(digits, 9), "1234 67 9") self.assertEqual(text.wrap(digits, 8), "1234 67\n9") self.assertEqual(text.wrap("short\na long line", 7), "short\na long\nline") self.assertEqual( text.wrap("do-not-break-long-words please? ok", 8), "do-not-break-long-words\nplease?\nok", ) long_word = "l%sng" % ("o" * 20) self.assertEqual(text.wrap(long_word, 20), long_word) self.assertEqual( text.wrap("a %s word" % long_word, 10), "a\n%s\nword" % long_word ) self.assertEqual(text.wrap(lazystr(digits), 100), "1234 67 9") def test_normalize_newlines(self): self.assertEqual( text.normalize_newlines("abc\ndef\rghi\r\n"), "abc\ndef\nghi\n" ) self.assertEqual(text.normalize_newlines("\n\r\r\n\r"), "\n\n\n\n") self.assertEqual(text.normalize_newlines("abcdefghi"), "abcdefghi") self.assertEqual(text.normalize_newlines(""), "") self.assertEqual( text.normalize_newlines(lazystr("abc\ndef\rghi\r\n")), "abc\ndef\nghi\n" ) def test_phone2numeric(self): numeric = text.phone2numeric("0800 flowers") self.assertEqual(numeric, "0800 3569377") lazy_numeric = lazystr(text.phone2numeric("0800 flowers")) self.assertEqual(lazy_numeric, "0800 3569377") def test_slugify(self): items = ( # given - expected - Unicode? ("Hello, World!", "hello-world", False), ("spam & eggs", "spam-eggs", False), (" multiple---dash and space ", "multiple-dash-and-space", False), ("\t whitespace-in-value \n", "whitespace-in-value", False), ("underscore_in-value", "underscore_in-value", False), ("__strip__underscore-value___", "strip__underscore-value", False), ("--strip-dash-value---", "strip-dash-value", False), ("__strip-mixed-value---", "strip-mixed-value", False), ("_ -strip-mixed-value _-", "strip-mixed-value", False), ("spam & ıçüş", "spam-ıçüş", True), ("foo ıç bar", "foo-ıç-bar", True), (" foo ıç bar", "foo-ıç-bar", True), ("你好", "你好", True), ("İstanbul", "istanbul", True), ) for value, output, is_unicode in items: with self.subTest(value=value): self.assertEqual(text.slugify(value, allow_unicode=is_unicode), output) # Interning the result may be useful, e.g. when fed to Path. with self.subTest("intern"): self.assertEqual(sys.intern(text.slugify("a")), "a") def test_unescape_string_literal(self): items = [ ('"abc"', "abc"), ("'abc'", "abc"), ('"a "bc""', 'a "bc"'), ("''ab' c'", "'ab' c"), ] for value, output in items: with self.subTest(value=value): self.assertEqual(text.unescape_string_literal(value), output) self.assertEqual(text.unescape_string_literal(lazystr(value)), output) def test_unescape_string_literal_invalid_value(self): items = ["", "abc", "'abc\""] for item in items: msg = f"Not a string literal: {item!r}" with self.assertRaisesMessage(ValueError, msg): text.unescape_string_literal(item) def test_get_valid_filename(self): filename = "^&'@{}[],$=!-#()%+~_123.txt" self.assertEqual(text.get_valid_filename(filename), "-_123.txt") self.assertEqual(text.get_valid_filename(lazystr(filename)), "-_123.txt") msg = "Could not derive file name from '???'" with self.assertRaisesMessage(SuspiciousFileOperation, msg): text.get_valid_filename("???") # After sanitizing this would yield '..'. msg = "Could not derive file name from '$.$.$'" with self.assertRaisesMessage(SuspiciousFileOperation, msg): text.get_valid_filename("$.$.$") def test_compress_sequence(self): data = [{"key": i} for i in range(10)] seq = list(json.JSONEncoder().iterencode(data)) seq = [s.encode() for s in seq] actual_length = len(b"".join(seq)) out = text.compress_sequence(seq) compressed_length = len(b"".join(out)) self.assertLess(compressed_length, actual_length) def test_format_lazy(self): self.assertEqual("django/test", format_lazy("{}/{}", "django", lazystr("test"))) self.assertEqual("django/test", format_lazy("{0}/{1}", *("django", "test"))) self.assertEqual( "django/test", format_lazy("{a}/{b}", **{"a": "django", "b": "test"}) ) self.assertEqual( "django/test", format_lazy("{a[0]}/{a[1]}", a=("django", "test")) ) t = {} s = format_lazy("{0[a]}-{p[a]}", t, p=t) t["a"] = lazystr("django") self.assertEqual("django-django", s) t["a"] = "update" self.assertEqual("update-update", s) # The format string can be lazy. (string comes from contrib.admin) s = format_lazy( gettext_lazy("Added {name} “{object}”."), name="article", object="My first try", ) with override("fr"): self.assertEqual("Ajout de article «\xa0My first try\xa0».", s)