diff options
author | django-bot <ops@djangoproject.com> | 2022-02-03 20:24:19 +0100 |
---|---|---|
committer | Mariusz Felisiak <felisiak.mariusz@gmail.com> | 2022-02-07 20:37:05 +0100 |
commit | 9c19aff7c7561e3a82978a272ecdaad40dda5c00 (patch) | |
tree | f0506b668a013d0063e5fba3dbf4863b466713ba /tests/staticfiles_tests | |
parent | f68fa8b45dfac545cfc4111d4e52804c86db68d3 (diff) | |
download | django-9c19aff7c7561e3a82978a272ecdaad40dda5c00.tar.gz |
Refs #33476 -- Reformatted code with Black.
Diffstat (limited to 'tests/staticfiles_tests')
-rw-r--r-- | tests/staticfiles_tests/apps/staticfiles_config.py | 2 | ||||
-rw-r--r-- | tests/staticfiles_tests/cases.py | 36 | ||||
-rw-r--r-- | tests/staticfiles_tests/settings.py | 36 | ||||
-rw-r--r-- | tests/staticfiles_tests/storage.py | 16 | ||||
-rw-r--r-- | tests/staticfiles_tests/test_checks.py | 125 | ||||
-rw-r--r-- | tests/staticfiles_tests/test_finders.py | 53 | ||||
-rw-r--r-- | tests/staticfiles_tests/test_forms.py | 20 | ||||
-rw-r--r-- | tests/staticfiles_tests/test_handlers.py | 4 | ||||
-rw-r--r-- | tests/staticfiles_tests/test_liveserver.py | 24 | ||||
-rw-r--r-- | tests/staticfiles_tests/test_management.py | 269 | ||||
-rw-r--r-- | tests/staticfiles_tests/test_storage.py | 295 | ||||
-rw-r--r-- | tests/staticfiles_tests/test_templatetags.py | 13 | ||||
-rw-r--r-- | tests/staticfiles_tests/test_utils.py | 3 | ||||
-rw-r--r-- | tests/staticfiles_tests/test_views.py | 8 | ||||
-rw-r--r-- | tests/staticfiles_tests/urls/default.py | 2 |
15 files changed, 520 insertions, 386 deletions
diff --git a/tests/staticfiles_tests/apps/staticfiles_config.py b/tests/staticfiles_tests/apps/staticfiles_config.py index b8b3960c9d..cf2147f1fa 100644 --- a/tests/staticfiles_tests/apps/staticfiles_config.py +++ b/tests/staticfiles_tests/apps/staticfiles_config.py @@ -2,4 +2,4 @@ from django.contrib.staticfiles.apps import StaticFilesConfig class IgnorePatternsAppConfig(StaticFilesConfig): - ignore_patterns = ['*.css', '*/vendor/*.js'] + ignore_patterns = ["*.css", "*/vendor/*.js"] diff --git a/tests/staticfiles_tests/cases.py b/tests/staticfiles_tests/cases.py index 4e767d9cb0..5e8b150b33 100644 --- a/tests/staticfiles_tests/cases.py +++ b/tests/staticfiles_tests/cases.py @@ -33,7 +33,10 @@ class BaseStaticFilesMixin: 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' as var %%}{{ var }}" + % path + ) return "{%% load static from static %%}{%% static '%s' %%}" % path def assertStaticRenders(self, path, result, asvar=False, **kwargs): @@ -60,6 +63,7 @@ class CollectionTestCase(BaseStaticFilesMixin, SimpleTestCase): is separated because some test cases need those asserts without all these tests. """ + run_collectstatic_in_setUp = True def setUp(self): @@ -82,13 +86,18 @@ class CollectionTestCase(BaseStaticFilesMixin, SimpleTestCase): return tempfile.mkdtemp() def run_collectstatic(self, *, verbosity=0, **kwargs): - call_command('collectstatic', interactive=False, verbosity=verbosity, - ignore_patterns=['*.ignoreme'], **kwargs) + call_command( + "collectstatic", + interactive=False, + verbosity=verbosity, + ignore_patterns=["*.ignoreme"], + **kwargs, + ) def _get_file(self, filepath): - assert filepath, 'filepath is empty.' + assert filepath, "filepath is empty." filepath = os.path.join(settings.STATIC_ROOT, filepath) - with open(filepath, encoding='utf-8') as f: + with open(filepath, encoding="utf-8") as f: return f.read() @@ -96,43 +105,44 @@ 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') + 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') + 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') + 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') + 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') + 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') + self.assertFileContains("test/camelCase.txt", "camelCase") def test_filename_with_percent_sign(self): - self.assertFileContains('test/%2F.txt', '%2F content') + self.assertFileContains("test/%2F.txt", "%2F content") diff --git a/tests/staticfiles_tests/settings.py b/tests/staticfiles_tests/settings.py index 3bd581824d..a5fd116c0a 100644 --- a/tests/staticfiles_tests/settings.py +++ b/tests/staticfiles_tests/settings.py @@ -4,27 +4,27 @@ 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', + "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', + "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', + "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': [], + "MIDDLEWARE": [], } diff --git a/tests/staticfiles_tests/storage.py b/tests/staticfiles_tests/storage.py index 6a319f934d..1bb4e37485 100644 --- a/tests/staticfiles_tests/storage.py +++ b/tests/staticfiles_tests/storage.py @@ -12,8 +12,9 @@ class DummyStorage(storage.Storage): A storage class that implements get_modified_time() but raises NotImplementedError for path(). """ + def _save(self, name, content): - return 'dummy' + return "dummy" def delete(self, name): pass @@ -26,9 +27,8 @@ class DummyStorage(storage.Storage): class PathNotImplementedStorage(storage.Storage): - def _save(self, name, content): - return 'dummy' + return "dummy" def _path(self, name): return os.path.join(settings.STATIC_ROOT, name) @@ -62,19 +62,19 @@ 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' + return path + "?a=b&c=d" class SimpleStorage(ManifestStaticFilesStorage): - def file_hash(self, name, content=None): - return 'deploy12345' + return "deploy12345" class ExtraPatternsStorage(ManifestStaticFilesStorage): @@ -82,9 +82,11 @@ 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", ( + "*.js", + ( ( r"""(?P<matched>url\(['"]{0,1}\s*(?P<url>.*?)["']{0,1}\))""", 'JS_URL("%(url)s")', diff --git a/tests/staticfiles_tests/test_checks.py b/tests/staticfiles_tests/test_checks.py index 4b2195b46f..5a4cbe7d0f 100644 --- a/tests/staticfiles_tests/test_checks.py +++ b/tests/staticfiles_tests/test_checks.py @@ -16,15 +16,15 @@ class FindersCheckTests(CollectionTestCase): def test_base_finder_check_not_implemented(self): finder = BaseFinder() - msg = 'subclasses may provide a check() method to verify the finder is configured correctly.' + 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') + error1 = Error("1") + error2 = Error("2") + error3 = Error("3") def get_finders(): class Finder1(BaseFinder): @@ -44,71 +44,88 @@ class FindersCheckTests(CollectionTestCase): return [Finder1(), Finder2(), Finder3(), Finder4()] - with mock.patch('django.contrib.staticfiles.checks.get_finders', get_finders): + 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') + @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', - ) - ]) + 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', - ) - ]) + 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', - ) - ]) + 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', - ), - ]) + 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', - ), - ]) + 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') + finder = get_finder("django.contrib.staticfiles.finders.FileSystemFinder") self.assertEqual(list(finder.list(None)), []) diff --git a/tests/staticfiles_tests/test_finders.py b/tests/staticfiles_tests/test_finders.py index 9d5707cc2d..9f2509d533 100644 --- a/tests/staticfiles_tests/test_finders.py +++ b/tests/staticfiles_tests/test_finders.py @@ -17,6 +17,7 @@ class TestFinders: 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) @@ -34,76 +35,86 @@ 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]) + 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]) + 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]) + 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')], + 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) + 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') + 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') + 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') + 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') + finders.find("spam") self.assertEqual( finders.searched_locations, - [os.path.join(TEST_ROOT, 'project', 'documents')] + [os.path.join(TEST_ROOT, "project", "documents")], ) - @override_settings(MEDIA_ROOT='') + @override_settings(MEDIA_ROOT="") def test_location_empty(self): msg = ( "The storage backend of the staticfiles finder " diff --git a/tests/staticfiles_tests/test_forms.py b/tests/staticfiles_tests/test_forms.py index fadbe6e1d5..d95fed43cc 100644 --- a/tests/staticfiles_tests/test_forms.py +++ b/tests/staticfiles_tests/test_forms.py @@ -8,23 +8,23 @@ from django.test import SimpleTestCase, override_settings class StaticTestStorage(storage.StaticFilesStorage): def url(self, name): - return urljoin('https://example.com/assets/', 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', + 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')}, + 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'), + "/path/to/js1", + "http://media.other.com/path/to/js2", + "https://secure.other.com/path/to/js3", + static("relative/path/to/js4"), ), ) self.assertEqual( @@ -34,5 +34,5 @@ class StaticFilesFormsMediaTestCase(SimpleTestCase): <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>""" +<script src="https://example.com/assets/relative/path/to/js4"></script>""", ) diff --git a/tests/staticfiles_tests/test_handlers.py b/tests/staticfiles_tests/test_handlers.py index 4cd5811d88..e0451c6e16 100644 --- a/tests/staticfiles_tests/test_handlers.py +++ b/tests/staticfiles_tests/test_handlers.py @@ -9,14 +9,14 @@ class TestASGIStaticFilesHandler(StaticFilesTestCase): async_request_factory = AsyncRequestFactory() async def test_get_async_response(self): - request = self.async_request_factory.get('/static/test/file.txt') + 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') + 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) diff --git a/tests/staticfiles_tests/test_liveserver.py b/tests/staticfiles_tests/test_liveserver.py index 38d1513c9a..214459555d 100644 --- a/tests/staticfiles_tests/test_liveserver.py +++ b/tests/staticfiles_tests/test_liveserver.py @@ -13,10 +13,10 @@ 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'), + "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"), } @@ -34,17 +34,16 @@ class LiveServerBase(StaticLiveServerTestCase): 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 + old_STATIC_URL = TEST_SETTINGS["STATIC_URL"] + TEST_SETTINGS["STATIC_URL"] = None try: cls.raises_exception() finally: - TEST_SETTINGS['STATIC_URL'] = old_STATIC_URL + TEST_SETTINGS["STATIC_URL"] = old_STATIC_URL @classmethod def tearDownClass(cls): @@ -60,7 +59,7 @@ class StaticLiveServerChecks(LiveServerBase): # app without having set the required STATIC_URL setting.") pass else: - raise Exception('setUpClass() should have raised an exception.') + 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 @@ -69,16 +68,15 @@ class StaticLiveServerChecks(LiveServerBase): 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'}) + @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.') + with self.urlopen("/static/test/file.txt") as f: + self.assertEqual(f.read().rstrip(b"\r\n"), b"In static directory.") diff --git a/tests/staticfiles_tests/test_management.py b/tests/staticfiles_tests/test_management.py index 7ebac48239..afc8cc1637 100644 --- a/tests/staticfiles_tests/test_management.py +++ b/tests/staticfiles_tests/test_management.py @@ -11,9 +11,7 @@ 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.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 @@ -29,7 +27,6 @@ from .storage import DummyStorage class TestNoFilesCreated: - def test_no_files_created(self): """ Make sure no files were create in the destination directory. @@ -38,17 +35,17 @@ class TestNoFilesCreated: class TestRunserver(StaticFilesTestCase): - @override_settings(MIDDLEWARE=['django.middleware.common.CommonMiddleware']) + @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: + 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') + 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) @@ -62,75 +59,98 @@ 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: + 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]) + 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')] + 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]) + 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]) + 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:]) + 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) + 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) + 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 + 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' + msg = "without having set the STATIC_ROOT setting to a filesystem path" err = StringIO() - for root in ['', None]: + for root in ["", None]: with override_settings(STATIC_ROOT=root): with self.assertRaisesMessage(ImproperlyConfigured, msg): - call_command('collectstatic', interactive=False, verbosity=0, stderr=err) + 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'): + 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'): + with self.settings( + STATICFILES_STORAGE="staticfiles_tests.storage.DummyStorage" + ): command = collectstatic.Command() self.assertFalse(command.is_local_storage()) @@ -146,11 +166,11 @@ class TestConfiguration(StaticFilesTestCase): collectstatic.staticfiles_storage = staticfiles_storage storage.staticfiles_storage = staticfiles_storage - @override_settings(STATICFILES_DIRS=('test')) + @override_settings(STATICFILES_DIRS=("test")) def test_collectstatis_check(self): - msg = 'The STATICFILES_DIRS setting is not a tuple or list.' + msg = "The STATICFILES_DIRS setting is not a tuple or list." with self.assertRaisesMessage(SystemCheckError, msg): - call_command('collectstatic', skip_checks=False) + call_command("collectstatic", skip_checks=False) class TestCollectionHelpSubcommand(AdminScriptTestCase): @@ -160,8 +180,8 @@ class TestCollectionHelpSubcommand(AdminScriptTestCase): 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.write_settings("settings.py", apps=["django.contrib.staticfiles"]) + out, err = self.run_manage(["help", "collectstatic"]) self.assertNoOutput(err) @@ -169,22 +189,23 @@ class TestCollection(TestDefaults, CollectionTestCase): """ Test ``collectstatic`` management command. """ + def test_ignore(self): """ -i patterns are ignored. """ - self.assertFileNotFound('test/test.ignoreme') + 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') + self.assertFileNotFound("test/.hidden") + self.assertFileNotFound("test/backup~") + self.assertFileNotFound("test/CVS") def test_pathlib(self): - self.assertFileContains('pathlib.txt', 'pathlib') + self.assertFileContains("pathlib.txt", "pathlib") class TestCollectionPathLib(TestCollection): @@ -194,15 +215,15 @@ class TestCollectionPathLib(TestCollection): class TestCollectionVerbosity(CollectionTestCase): - copying_msg = 'Copying ' + copying_msg = "Copying " run_collectstatic_in_setUp = False - post_process_msg = 'Post-processed' - staticfiles_copied_msg = 'static files copied to' + 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(), '') + self.assertEqual(stdout.getvalue(), "") def test_verbosity_1(self): stdout = StringIO() @@ -218,13 +239,17 @@ class TestCollectionVerbosity(CollectionTestCase): self.assertIn(self.staticfiles_copied_msg, output) self.assertIn(self.copying_msg, output) - @override_settings(STATICFILES_STORAGE='django.contrib.staticfiles.storage.ManifestStaticFilesStorage') + @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') + @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) @@ -235,23 +260,26 @@ 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') + 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') + 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') + @override_settings( + STATICFILES_STORAGE="staticfiles_tests.storage.PathNotImplementedStorage" + ) def test_handle_path_notimplemented(self): self.run_collectstatic() - self.assertFileNotFound('cleared.txt') + self.assertFileNotFound("cleared.txt") class TestInteractiveMessages(CollectionTestCase): @@ -263,14 +291,15 @@ class TestInteractiveMessages(CollectionTestCase): def mock_input(stdout): def _input(msg): stdout.write(msg) - return 'yes' + 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) + 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) @@ -279,8 +308,8 @@ class TestInteractiveMessages(CollectionTestCase): 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) + 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) @@ -288,7 +317,7 @@ class TestInteractiveMessages(CollectionTestCase): def test_no_warning_when_staticdir_does_not_exist(self): stdout = StringIO() shutil.rmtree(settings.STATIC_ROOT) - call_command('collectstatic', interactive=True, stdout=stdout) + call_command("collectstatic", interactive=True, stdout=stdout) output = stdout.getvalue() self.assertNotIn(self.overwrite_warning_msg, output) self.assertNotIn(self.delete_warning_msg, output) @@ -296,9 +325,11 @@ class TestInteractiveMessages(CollectionTestCase): def test_no_warning_for_empty_staticdir(self): stdout = StringIO() - with tempfile.TemporaryDirectory(prefix='collectstatic_empty_staticdir_test') as static_dir: + 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) + call_command("collectstatic", interactive=True, stdout=stdout) output = stdout.getvalue() self.assertNotIn(self.overwrite_warning_msg, output) self.assertNotIn(self.delete_warning_msg, output) @@ -306,9 +337,11 @@ class TestInteractiveMessages(CollectionTestCase): 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) + 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): @@ -316,6 +349,7 @@ 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) @@ -324,35 +358,40 @@ class TestCollectionNoDefaultIgnore(TestDefaults, CollectionTestCase): 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') + 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', -]) +@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')) + 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') +@override_settings( + STATICFILES_STORAGE="django.contrib.staticfiles.storage.ManifestStaticFilesStorage" +) class TestCollectionDryRunManifestStaticFilesStorage(TestCollectionDryRun): pass @@ -365,12 +404,15 @@ class TestCollectionFilesOverride(CollectionTestCase): '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_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) @@ -378,21 +420,21 @@ class TestCollectionFilesOverride(CollectionTestCase): # 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') + 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+'): + 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') + 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'}, + INSTALLED_APPS={"prepend": "staticfiles_test_app"}, ) with extend_sys_path(self.temp_dir): self.settings_with_test_app.enable() @@ -407,12 +449,12 @@ class TestCollectionFilesOverride(CollectionTestCase): """ Test if collectstatic takes files in proper order """ - self.assertFileContains('file2.txt', 'duplicate of file2.txt') + self.assertFileContains("file2.txt", "duplicate of file2.txt") # run collectstatic again self.run_collectstatic() - self.assertFileContains('file2.txt', 'duplicate of file2.txt') + self.assertFileContains("file2.txt", "duplicate of file2.txt") # The collectstatic test suite already has conflicting files since both @@ -425,9 +467,10 @@ 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' + warning_string = "Found another file" def _collectstatic_output(self, **kwargs): """ @@ -436,7 +479,9 @@ class TestCollectionOverwriteWarning(CollectionTestCase): just call e.g. BaseCollectionTestCase.run_collectstatic() """ out = StringIO() - call_command('collectstatic', interactive=False, verbosity=3, stdout=out, **kwargs) + call_command( + "collectstatic", interactive=False, verbosity=3, stdout=out, **kwargs + ) return out.getvalue() def test_no_warning(self): @@ -451,10 +496,10 @@ class TestCollectionOverwriteWarning(CollectionTestCase): There is a warning when there are duplicate destinations. """ with tempfile.TemporaryDirectory() as static_dir: - duplicate = os.path.join(static_dir, 'test', 'file.txt') + 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 open(duplicate, "w+") as f: + f.write("duplicate of file.txt") with self.settings(STATICFILES_DIRS=[static_dir]): output = self._collectstatic_output(clear=True) @@ -468,23 +513,30 @@ class TestCollectionOverwriteWarning(CollectionTestCase): self.assertNotIn(self.warning_string, output) -@override_settings(STATICFILES_STORAGE='staticfiles_tests.storage.DummyStorage') +@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') + 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') + @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. @@ -508,6 +560,7 @@ class TestCollectionLinks(TestDefaults, CollectionTestCase): 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) @@ -515,13 +568,13 @@ class TestCollectionLinks(TestDefaults, CollectionTestCase): """ With ``--link``, symbolic links are created. """ - self.assertTrue(os.path.islink(os.path.join(settings.STATIC_ROOT, 'test.txt'))) + 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') + path = os.path.join(settings.STATIC_ROOT, "test.txt") os.unlink(path) self.run_collectstatic() self.assertTrue(os.path.islink(path)) @@ -531,7 +584,7 @@ class TestCollectionLinks(TestDefaults, CollectionTestCase): 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') + 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)) @@ -542,13 +595,17 @@ class TestCollectionLinks(TestDefaults, CollectionTestCase): """ 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') + 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') + @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."): + with self.assertRaisesMessage( + CommandError, "Can't symlink to a remote destination." + ): self.run_collectstatic() diff --git a/tests/staticfiles_tests/test_storage.py b/tests/staticfiles_tests/test_storage.py index 62484205b7..513d0cf010 100644 --- a/tests/staticfiles_tests/test_storage.py +++ b/tests/staticfiles_tests/test_storage.py @@ -22,7 +22,7 @@ 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, '') + return fullpath.replace(settings.STATIC_URL, "") class TestHashedFiles: @@ -40,10 +40,16 @@ class TestHashedFiles: pass def test_template_tag_return(self): - self.assertStaticRaises(ValueError, "does/not/exist.png", "/static/does/not/exist.png") + 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( + "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() @@ -62,18 +68,20 @@ class TestHashedFiles: 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.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: + 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) @@ -82,7 +90,9 @@ class TestHashedFiles: 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: + 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) @@ -93,11 +103,16 @@ class TestHashedFiles: 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;base64,d09GRgABAAAAADJoAA0AAAAAR2QAAQAAAAAAAAAAAAA', content) - self.assertIn(b'#default#VML', content) + 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;base64,d09GRgABAAAAADJoAA0AAAAAR2QAAQAAAAAAAAAAAAA", + content, + ) + self.assertIn(b"#default#VML", content) self.assertPostCondition() def test_template_tag_absolute(self): @@ -109,7 +124,7 @@ class TestHashedFiles: 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.assertIn(b"/static/cached/img/relative.acae32e4532b.png", content) self.assertPostCondition() def test_template_tag_absolute_root(self): @@ -131,7 +146,7 @@ class TestHashedFiles: 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.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() @@ -149,7 +164,7 @@ class TestHashedFiles: 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.assertNotIn(b"url(img/window.png)", content) self.assertIn(b'url("img/window.acae32e4532b.png")', content) self.assertPostCondition() @@ -161,14 +176,14 @@ class TestHashedFiles: self.assertPostCondition() @override_settings( - STATICFILES_DIRS=[os.path.join(TEST_ROOT, 'project', 'loop')], - STATICFILES_FINDERS=['django.contrib.staticfiles.finders.FileSystemFinder'], + 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) + 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() @@ -183,24 +198,28 @@ class TestHashedFiles: 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'], + "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']) + 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.assertCountEqual(stats["post_processed"], set(stats["post_processed"])) self.assertPostCondition() def test_css_import_case_insensitive(self): @@ -213,56 +232,56 @@ class TestHashedFiles: 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') + 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.assertNotIn(b"/*# sourceMappingURL=source_map.css.map */", content) self.assertIn( - b'/*# sourceMappingURL=source_map.css.99914b932bd3.map */', + 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') + 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.assertIn(b"/*# sOuRcEMaPpInGURL=source_map.css.map */", content) self.assertNotIn( - b'/*# sourceMappingURL=source_map.css.99914b932bd3.map */', + 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') + 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.assertNotIn(b"//# sourceMappingURL=source_map.js.map", content) self.assertIn( - b'//# sourceMappingURL=source_map.js.99914b932bd3.map', + 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') + 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.assertIn(b"//# sOuRcEMaPpInGURL=source_map.js.map", content) self.assertNotIn( - b'//# sourceMappingURL=source_map.js.99914b932bd3.map', + 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'], + STATICFILES_DIRS=[os.path.join(TEST_ROOT, "project", "faulty")], + STATICFILES_FINDERS=["django.contrib.staticfiles.finders.FileSystemFinder"], ) def test_post_processing_failure(self): """ @@ -271,21 +290,20 @@ class TestHashedFiles: finders.get_finder.cache_clear() err = StringIO() with self.assertRaises(Exception): - call_command('collectstatic', interactive=False, verbosity=0, stderr=err) + 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') +@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, '') + return fullpath.replace(settings.STATIC_URL, "") def test_multi_extension_patterns(self): """ @@ -307,20 +325,21 @@ class TestExtraPatternsStorage(CollectionTestCase): @override_settings( - STATICFILES_STORAGE='django.contrib.staticfiles.storage.ManifestStaticFilesStorage', + 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') + 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], @@ -352,11 +371,11 @@ class TestCollectionManifestStorage(TestHashedFiles, CollectionTestCase): self.assertTrue(os.path.exists(path)) def test_manifest_does_not_exist(self): - storage.staticfiles_storage.manifest_name = 'does.not.exist.json' + 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 mock.patch("builtins.open", side_effect=PermissionError): with self.assertRaises(PermissionError): storage.staticfiles_storage.read_manifest() @@ -365,7 +384,7 @@ class TestCollectionManifestStorage(TestHashedFiles, CollectionTestCase): manifest_content = storage.staticfiles_storage.read_manifest() self.assertIn( '"version": "%s"' % storage.staticfiles_storage.manifest_version, - manifest_content + manifest_content, ) def test_parse_cache(self): @@ -374,7 +393,9 @@ class TestCollectionManifestStorage(TestHashedFiles, CollectionTestCase): 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')) + cleared_file_name = storage.staticfiles_storage.clean_name( + os.path.join("test", "cleared.txt") + ) # collect the additional file self.run_collectstatic() @@ -400,50 +421,58 @@ class TestCollectionManifestStorage(TestHashedFiles, CollectionTestCase): self.assertNotIn(cleared_file_name, manifest_content) def test_missing_entry(self): - missing_file_name = 'cached/missing.css' + 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): + 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) + 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') + 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')) + 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.') - ]), + len( + [ + cached_file + for cached_file in cached_files + if cached_file.startswith("relative.") + ] + ), 2, ) -@override_settings(STATICFILES_STORAGE='staticfiles_tests.storage.NoneHashStorage') +@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') + relpath = self.hashed_file_path("cached/styles.css") + self.assertEqual(relpath, "cached/styles.css") @override_settings( - STATICFILES_STORAGE='staticfiles_tests.storage.NoPostProcessReplacedPathStorage' + STATICFILES_STORAGE="staticfiles_tests.storage.NoPostProcessReplacedPathStorage" ) class TestCollectionNoPostProcessReplacedPaths(CollectionTestCase): run_collectstatic_in_setUp = False @@ -451,10 +480,10 @@ class TestCollectionNoPostProcessReplacedPaths(CollectionTestCase): def test_collectstatistic_no_post_process_replaced_paths(self): stdout = StringIO() self.run_collectstatic(verbosity=1, stdout=stdout) - self.assertIn('post-processed', stdout.getvalue()) + self.assertIn("post-processed", stdout.getvalue()) -@override_settings(STATICFILES_STORAGE='staticfiles_tests.storage.SimpleStorage') +@override_settings(STATICFILES_STORAGE="staticfiles_tests.storage.SimpleStorage") class TestCollectionSimpleStorage(CollectionTestCase): hashed_file_path = hashed_file_path @@ -463,9 +492,13 @@ class TestCollectionSimpleStorage(CollectionTestCase): super().setUp() def test_template_tag_return(self): - self.assertStaticRaises(ValueError, "does/not/exist.png", "/static/does/not/exist.png") + 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( + "cached/styles.css", "/static/cached/styles.deploy12345.css" + ) self.assertStaticRenders("path/", "/static/path/") self.assertStaticRenders("path/?query", "/static/path/?query") @@ -481,7 +514,7 @@ class TestCollectionSimpleStorage(CollectionTestCase): class CustomManifestStorage(storage.ManifestStaticFilesStorage): def __init__(self, *args, manifest_storage=None, **kwargs): manifest_storage = storage.StaticFilesStorage( - location=kwargs.pop('manifest_location'), + location=kwargs.pop("manifest_location"), ) super().__init__(*args, manifest_storage=manifest_storage, **kwargs) @@ -496,8 +529,8 @@ class TestCustomManifestStorage(SimpleTestCase): ) 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: + 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): @@ -515,7 +548,7 @@ class TestCustomManifestStorage(SimpleTestCase): 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.assertIn("paths", new_manifest) self.assertNotEqual(new_manifest, self.manifest) def test_save_manifest_create(self): @@ -523,7 +556,7 @@ class TestCustomManifestStorage(SimpleTestCase): 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.assertIn("paths", new_manifest) self.assertNotEqual(new_manifest, self.manifest) @@ -531,19 +564,20 @@ class CustomStaticFilesStorage(storage.StaticFilesStorage): """ Used in TestStaticFilePermissions """ + def __init__(self, *args, **kwargs): - kwargs['file_permissions_mode'] = 0o640 - kwargs['directory_permissions_mode'] = 0o740 + kwargs["file_permissions_mode"] = 0o640 + kwargs["directory_permissions_mode"] = 0o740 super().__init__(*args, **kwargs) -@unittest.skipIf(sys.platform == 'win32', "Windows only partially supports chmod.") +@unittest.skipIf(sys.platform == "win32", "Windows only partially supports chmod.") class TestStaticFilePermissions(CollectionTestCase): command_params = { - 'interactive': False, - 'verbosity': 0, - 'ignore_patterns': ['*.ignoreme'], + "interactive": False, + "verbosity": 0, + "ignore_patterns": ["*.ignoreme"], } def setUp(self): @@ -564,15 +598,15 @@ class TestStaticFilePermissions(CollectionTestCase): FILE_UPLOAD_DIRECTORY_PERMISSIONS=0o765, ) def test_collect_static_files_permissions(self): - call_command('collectstatic', **self.command_params) + call_command("collectstatic", **self.command_params) static_root = Path(settings.STATIC_ROOT) - test_file = static_root / 'test.txt' + 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', + static_root / "subdir", + static_root / "nested", + static_root / "nested" / "css", ] for directory in tests: with self.subTest(directory=directory): @@ -584,15 +618,15 @@ class TestStaticFilePermissions(CollectionTestCase): FILE_UPLOAD_DIRECTORY_PERMISSIONS=None, ) def test_collect_static_files_default_permissions(self): - call_command('collectstatic', **self.command_params) + call_command("collectstatic", **self.command_params) static_root = Path(settings.STATIC_ROOT) - test_file = static_root / 'test.txt' + 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', + static_root / "subdir", + static_root / "nested", + static_root / "nested" / "css", ] for directory in tests: with self.subTest(directory=directory): @@ -602,18 +636,18 @@ class TestStaticFilePermissions(CollectionTestCase): @override_settings( FILE_UPLOAD_PERMISSIONS=0o655, FILE_UPLOAD_DIRECTORY_PERMISSIONS=0o765, - STATICFILES_STORAGE='staticfiles_tests.test_storage.CustomStaticFilesStorage', + STATICFILES_STORAGE="staticfiles_tests.test_storage.CustomStaticFilesStorage", ) def test_collect_static_files_subclass_of_static_storage(self): - call_command('collectstatic', **self.command_params) + call_command("collectstatic", **self.command_params) static_root = Path(settings.STATIC_ROOT) - test_file = static_root / 'test.txt' + 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', + static_root / "subdir", + static_root / "nested", + static_root / "nested" / "css", ] for directory in tests: with self.subTest(directory=directory): @@ -622,56 +656,57 @@ class TestStaticFilePermissions(CollectionTestCase): @override_settings( - STATICFILES_STORAGE='django.contrib.staticfiles.storage.ManifestStaticFilesStorage', + 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')) + 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) + 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'), + ("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: + with open(self._get_filename_path(filename), "w") as f: f.write(content) - with self.modify_settings(STATICFILES_DIRS={'append': self._temp_dir}): + 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') + 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) + 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: + 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') + 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) + self.assertIn(b"foo.57a5cb9ba68d.png", content) + self.assertIn(b"xyz.57a5cb9ba68d.png", content) diff --git a/tests/staticfiles_tests/test_templatetags.py b/tests/staticfiles_tests/test_templatetags.py index cd3f7d4bfa..4cc3f95ab1 100644 --- a/tests/staticfiles_tests/test_templatetags.py +++ b/tests/staticfiles_tests/test_templatetags.py @@ -4,18 +4,21 @@ 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"ed.html", "/static/special%3Fchars%26quoted.html") + self.assertStaticRenders( + "special?chars"ed.html", "/static/special%3Fchars%26quoted.html" + ) - @override_settings(STATICFILES_STORAGE='staticfiles_tests.storage.QueryStringStorage') + @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&c=d') - self.assertStaticRenders('a.html', 'a.html?a=b&c=d', autoescape=False) + self.assertStaticRenders("a.html", "a.html?a=b&c=d") + self.assertStaticRenders("a.html", "a.html?a=b&c=d", autoescape=False) diff --git a/tests/staticfiles_tests/test_utils.py b/tests/staticfiles_tests/test_utils.py index 2fe7344646..5acd406b68 100644 --- a/tests/staticfiles_tests/test_utils.py +++ b/tests/staticfiles_tests/test_utils.py @@ -4,8 +4,7 @@ from django.test import SimpleTestCase, override_settings class CheckSettingsTests(SimpleTestCase): - - @override_settings(DEBUG=True, MEDIA_URL='static/media/', STATIC_URL='static/') + @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): diff --git a/tests/staticfiles_tests/test_views.py b/tests/staticfiles_tests/test_views.py index d16f4a2cec..44c0cfe17f 100644 --- a/tests/staticfiles_tests/test_views.py +++ b/tests/staticfiles_tests/test_views.py @@ -7,11 +7,12 @@ from django.test import override_settings from .cases import StaticFilesTestCase, TestDefaults -@override_settings(ROOT_URLCONF='staticfiles_tests.urls.default') +@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))) @@ -27,8 +28,9 @@ class TestServeDisabled(TestServeStatic): """ Test serving static files disabled when DEBUG is False. """ + def test_disabled_serving(self): - self.assertFileNotFound('test.txt') + self.assertFileNotFound("test.txt") @override_settings(DEBUG=True) @@ -38,7 +40,7 @@ class TestServeStaticWithDefaultURL(TestDefaults, TestServeStatic): """ -@override_settings(DEBUG=True, ROOT_URLCONF='staticfiles_tests.urls.helper') +@override_settings(DEBUG=True, ROOT_URLCONF="staticfiles_tests.urls.helper") class TestServeStaticWithURLHelper(TestDefaults, TestServeStatic): """ Test static asset serving view with staticfiles_urlpatterns helper. diff --git a/tests/staticfiles_tests/urls/default.py b/tests/staticfiles_tests/urls/default.py index 7d45483131..a7345cf455 100644 --- a/tests/staticfiles_tests/urls/default.py +++ b/tests/staticfiles_tests/urls/default.py @@ -2,5 +2,5 @@ from django.contrib.staticfiles import views from django.urls import re_path urlpatterns = [ - re_path('^static/(?P<path>.*)$', views.serve), + re_path("^static/(?P<path>.*)$", views.serve), ] |