test_management.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. import codecs
  2. import datetime
  3. import os
  4. import shutil
  5. import tempfile
  6. import unittest
  7. from io import StringIO
  8. from unittest import mock
  9. from admin_scripts.tests import AdminScriptTestCase
  10. from django.conf import settings
  11. from django.contrib.staticfiles import storage
  12. from django.contrib.staticfiles.management.commands import collectstatic
  13. from django.core.exceptions import ImproperlyConfigured
  14. from django.core.management import call_command
  15. from django.test import override_settings
  16. from django.test.utils import extend_sys_path
  17. from django.utils import timezone
  18. from django.utils._os import symlinks_supported
  19. from django.utils.functional import empty
  20. from .cases import CollectionTestCase, StaticFilesTestCase, TestDefaults
  21. from .settings import TEST_ROOT, TEST_SETTINGS
  22. from .storage import DummyStorage
  23. class TestNoFilesCreated:
  24. def test_no_files_created(self):
  25. """
  26. Make sure no files were create in the destination directory.
  27. """
  28. self.assertEqual(os.listdir(settings.STATIC_ROOT), [])
  29. class TestFindStatic(TestDefaults, CollectionTestCase):
  30. """
  31. Test ``findstatic`` management command.
  32. """
  33. def _get_file(self, filepath):
  34. path = call_command('findstatic', filepath, all=False, verbosity=0, stdout=StringIO())
  35. with codecs.open(path, "r", "utf-8") as f:
  36. return f.read()
  37. def test_all_files(self):
  38. """
  39. findstatic returns all candidate files if run without --first and -v1.
  40. """
  41. result = call_command('findstatic', 'test/file.txt', verbosity=1, stdout=StringIO())
  42. lines = [l.strip() for l in result.split('\n')]
  43. self.assertEqual(len(lines), 3) # three because there is also the "Found <file> here" line
  44. self.assertIn('project', lines[1])
  45. self.assertIn('apps', lines[2])
  46. def test_all_files_less_verbose(self):
  47. """
  48. findstatic returns all candidate files if run without --first and -v0.
  49. """
  50. result = call_command('findstatic', 'test/file.txt', verbosity=0, stdout=StringIO())
  51. lines = [l.strip() for l in result.split('\n')]
  52. self.assertEqual(len(lines), 2)
  53. self.assertIn('project', lines[0])
  54. self.assertIn('apps', lines[1])
  55. def test_all_files_more_verbose(self):
  56. """
  57. findstatic returns all candidate files if run without --first and -v2.
  58. Also, test that findstatic returns the searched locations with -v2.
  59. """
  60. result = call_command('findstatic', 'test/file.txt', verbosity=2, stdout=StringIO())
  61. lines = [l.strip() for l in result.split('\n')]
  62. self.assertIn('project', lines[1])
  63. self.assertIn('apps', lines[2])
  64. self.assertIn("Looking in the following locations:", lines[3])
  65. searched_locations = ', '.join(lines[4:])
  66. # AppDirectoriesFinder searched locations
  67. self.assertIn(os.path.join('staticfiles_tests', 'apps', 'test', 'static'), searched_locations)
  68. self.assertIn(os.path.join('staticfiles_tests', 'apps', 'no_label', 'static'), searched_locations)
  69. # FileSystemFinder searched locations
  70. self.assertIn(TEST_SETTINGS['STATICFILES_DIRS'][1][1], searched_locations)
  71. self.assertIn(TEST_SETTINGS['STATICFILES_DIRS'][0], searched_locations)
  72. # DefaultStorageFinder searched locations
  73. self.assertIn(
  74. os.path.join('staticfiles_tests', 'project', 'site_media', 'media'),
  75. searched_locations
  76. )
  77. class TestConfiguration(StaticFilesTestCase):
  78. def test_location_empty(self):
  79. msg = 'without having set the STATIC_ROOT setting to a filesystem path'
  80. err = StringIO()
  81. for root in ['', None]:
  82. with override_settings(STATIC_ROOT=root):
  83. with self.assertRaisesMessage(ImproperlyConfigured, msg):
  84. call_command('collectstatic', interactive=False, verbosity=0, stderr=err)
  85. def test_local_storage_detection_helper(self):
  86. staticfiles_storage = storage.staticfiles_storage
  87. try:
  88. storage.staticfiles_storage._wrapped = empty
  89. with self.settings(STATICFILES_STORAGE='django.contrib.staticfiles.storage.StaticFilesStorage'):
  90. command = collectstatic.Command()
  91. self.assertTrue(command.is_local_storage())
  92. storage.staticfiles_storage._wrapped = empty
  93. with self.settings(STATICFILES_STORAGE='staticfiles_tests.storage.DummyStorage'):
  94. command = collectstatic.Command()
  95. self.assertFalse(command.is_local_storage())
  96. collectstatic.staticfiles_storage = storage.FileSystemStorage()
  97. command = collectstatic.Command()
  98. self.assertTrue(command.is_local_storage())
  99. collectstatic.staticfiles_storage = DummyStorage()
  100. command = collectstatic.Command()
  101. self.assertFalse(command.is_local_storage())
  102. finally:
  103. staticfiles_storage._wrapped = empty
  104. collectstatic.staticfiles_storage = staticfiles_storage
  105. storage.staticfiles_storage = staticfiles_storage
  106. class TestCollectionHelpSubcommand(AdminScriptTestCase):
  107. @override_settings(STATIC_ROOT=None)
  108. def test_missing_settings_dont_prevent_help(self):
  109. """
  110. Even if the STATIC_ROOT setting is not set, one can still call the
  111. `manage.py help collectstatic` command.
  112. """
  113. self.write_settings('settings.py', apps=['django.contrib.staticfiles'])
  114. out, err = self.run_manage(['help', 'collectstatic'])
  115. self.assertNoOutput(err)
  116. class TestCollection(TestDefaults, CollectionTestCase):
  117. """
  118. Test ``collectstatic`` management command.
  119. """
  120. def test_ignore(self):
  121. """
  122. -i patterns are ignored.
  123. """
  124. self.assertFileNotFound('test/test.ignoreme')
  125. def test_common_ignore_patterns(self):
  126. """
  127. Common ignore patterns (*~, .*, CVS) are ignored.
  128. """
  129. self.assertFileNotFound('test/.hidden')
  130. self.assertFileNotFound('test/backup~')
  131. self.assertFileNotFound('test/CVS')
  132. class TestCollectionClear(CollectionTestCase):
  133. """
  134. Test the ``--clear`` option of the ``collectstatic`` management command.
  135. """
  136. def run_collectstatic(self, **kwargs):
  137. clear_filepath = os.path.join(settings.STATIC_ROOT, 'cleared.txt')
  138. with open(clear_filepath, 'w') as f:
  139. f.write('should be cleared')
  140. super().run_collectstatic(clear=True)
  141. def test_cleared_not_found(self):
  142. self.assertFileNotFound('cleared.txt')
  143. def test_dir_not_exists(self, **kwargs):
  144. shutil.rmtree(settings.STATIC_ROOT)
  145. super().run_collectstatic(clear=True)
  146. @override_settings(STATICFILES_STORAGE='staticfiles_tests.storage.PathNotImplementedStorage')
  147. def test_handle_path_notimplemented(self):
  148. self.run_collectstatic()
  149. self.assertFileNotFound('cleared.txt')
  150. class TestInteractiveMessages(CollectionTestCase):
  151. overwrite_warning_msg = "This will overwrite existing files!"
  152. delete_warning_msg = "This will DELETE ALL FILES in this location!"
  153. files_copied_msg = "static files copied"
  154. @staticmethod
  155. def mock_input(stdout):
  156. def _input(msg):
  157. stdout.write(msg)
  158. return 'yes'
  159. return _input
  160. def test_warning_when_clearing_staticdir(self):
  161. stdout = StringIO()
  162. self.run_collectstatic()
  163. with mock.patch('builtins.input', side_effect=self.mock_input(stdout)):
  164. call_command('collectstatic', interactive=True, clear=True, stdout=stdout)
  165. output = stdout.getvalue()
  166. self.assertNotIn(self.overwrite_warning_msg, output)
  167. self.assertIn(self.delete_warning_msg, output)
  168. def test_warning_when_overwriting_files_in_staticdir(self):
  169. stdout = StringIO()
  170. self.run_collectstatic()
  171. with mock.patch('builtins.input', side_effect=self.mock_input(stdout)):
  172. call_command('collectstatic', interactive=True, stdout=stdout)
  173. output = stdout.getvalue()
  174. self.assertIn(self.overwrite_warning_msg, output)
  175. self.assertNotIn(self.delete_warning_msg, output)
  176. def test_no_warning_when_staticdir_does_not_exist(self):
  177. stdout = StringIO()
  178. shutil.rmtree(settings.STATIC_ROOT)
  179. call_command('collectstatic', interactive=True, stdout=stdout)
  180. output = stdout.getvalue()
  181. self.assertNotIn(self.overwrite_warning_msg, output)
  182. self.assertNotIn(self.delete_warning_msg, output)
  183. self.assertIn(self.files_copied_msg, output)
  184. def test_no_warning_for_empty_staticdir(self):
  185. stdout = StringIO()
  186. with tempfile.TemporaryDirectory(prefix='collectstatic_empty_staticdir_test') as static_dir:
  187. with override_settings(STATIC_ROOT=static_dir):
  188. call_command('collectstatic', interactive=True, stdout=stdout)
  189. output = stdout.getvalue()
  190. self.assertNotIn(self.overwrite_warning_msg, output)
  191. self.assertNotIn(self.delete_warning_msg, output)
  192. self.assertIn(self.files_copied_msg, output)
  193. class TestCollectionExcludeNoDefaultIgnore(TestDefaults, CollectionTestCase):
  194. """
  195. Test ``--exclude-dirs`` and ``--no-default-ignore`` options of the
  196. ``collectstatic`` management command.
  197. """
  198. def run_collectstatic(self):
  199. super().run_collectstatic(use_default_ignore_patterns=False)
  200. def test_no_common_ignore_patterns(self):
  201. """
  202. With --no-default-ignore, common ignore patterns (*~, .*, CVS)
  203. are not ignored.
  204. """
  205. self.assertFileContains('test/.hidden', 'should be ignored')
  206. self.assertFileContains('test/backup~', 'should be ignored')
  207. self.assertFileContains('test/CVS', 'should be ignored')
  208. @override_settings(INSTALLED_APPS=[
  209. 'staticfiles_tests.apps.staticfiles_config.IgnorePatternsAppConfig',
  210. 'staticfiles_tests.apps.test',
  211. ])
  212. class TestCollectionCustomIgnorePatterns(CollectionTestCase):
  213. def test_custom_ignore_patterns(self):
  214. """
  215. A custom ignore_patterns list, ['*.css'] in this case, can be specified
  216. in an AppConfig definition.
  217. """
  218. self.assertFileNotFound('test/nonascii.css')
  219. self.assertFileContains('test/.hidden', 'should be ignored')
  220. class TestCollectionDryRun(TestNoFilesCreated, CollectionTestCase):
  221. """
  222. Test ``--dry-run`` option for ``collectstatic`` management command.
  223. """
  224. def run_collectstatic(self):
  225. super().run_collectstatic(dry_run=True)
  226. class TestCollectionFilesOverride(CollectionTestCase):
  227. """
  228. Test overriding duplicated files by ``collectstatic`` management command.
  229. Check for proper handling of apps order in installed apps even if file modification
  230. dates are in different order:
  231. 'staticfiles_test_app',
  232. 'staticfiles_tests.apps.no_label',
  233. """
  234. def setUp(self):
  235. self.temp_dir = tempfile.mkdtemp()
  236. self.addCleanup(shutil.rmtree, self.temp_dir)
  237. # get modification and access times for no_label/static/file2.txt
  238. self.orig_path = os.path.join(TEST_ROOT, 'apps', 'no_label', 'static', 'file2.txt')
  239. self.orig_mtime = os.path.getmtime(self.orig_path)
  240. self.orig_atime = os.path.getatime(self.orig_path)
  241. # prepare duplicate of file2.txt from a temporary app
  242. # this file will have modification time older than no_label/static/file2.txt
  243. # anyway it should be taken to STATIC_ROOT because the temporary app is before
  244. # 'no_label' app in installed apps
  245. self.temp_app_path = os.path.join(self.temp_dir, 'staticfiles_test_app')
  246. self.testfile_path = os.path.join(self.temp_app_path, 'static', 'file2.txt')
  247. os.makedirs(self.temp_app_path)
  248. with open(os.path.join(self.temp_app_path, '__init__.py'), 'w+'):
  249. pass
  250. os.makedirs(os.path.dirname(self.testfile_path))
  251. with open(self.testfile_path, 'w+') as f:
  252. f.write('duplicate of file2.txt')
  253. os.utime(self.testfile_path, (self.orig_atime - 1, self.orig_mtime - 1))
  254. self.settings_with_test_app = self.modify_settings(
  255. INSTALLED_APPS={'prepend': 'staticfiles_test_app'})
  256. with extend_sys_path(self.temp_dir):
  257. self.settings_with_test_app.enable()
  258. super().setUp()
  259. def tearDown(self):
  260. super().tearDown()
  261. self.settings_with_test_app.disable()
  262. def test_ordering_override(self):
  263. """
  264. Test if collectstatic takes files in proper order
  265. """
  266. self.assertFileContains('file2.txt', 'duplicate of file2.txt')
  267. # run collectstatic again
  268. self.run_collectstatic()
  269. self.assertFileContains('file2.txt', 'duplicate of file2.txt')
  270. # The collectstatic test suite already has conflicting files since both
  271. # project/test/file.txt and apps/test/static/test/file.txt are collected. To
  272. # properly test for the warning not happening unless we tell it to explicitly,
  273. # we remove the project directory and will add back a conflicting file later.
  274. @override_settings(STATICFILES_DIRS=[])
  275. class TestCollectionOverwriteWarning(CollectionTestCase):
  276. """
  277. Test warning in ``collectstatic`` output when a file is skipped because a
  278. previous file was already written to the same path.
  279. """
  280. # If this string is in the collectstatic output, it means the warning we're
  281. # looking for was emitted.
  282. warning_string = 'Found another file'
  283. def _collectstatic_output(self, **kwargs):
  284. """
  285. Run collectstatic, and capture and return the output. We want to run
  286. the command at highest verbosity, which is why we can't
  287. just call e.g. BaseCollectionTestCase.run_collectstatic()
  288. """
  289. out = StringIO()
  290. call_command('collectstatic', interactive=False, verbosity=3, stdout=out, **kwargs)
  291. return out.getvalue()
  292. def test_no_warning(self):
  293. """
  294. There isn't a warning if there isn't a duplicate destination.
  295. """
  296. output = self._collectstatic_output(clear=True)
  297. self.assertNotIn(self.warning_string, output)
  298. def test_warning(self):
  299. """
  300. There is a warning when there are duplicate destinations.
  301. """
  302. with tempfile.TemporaryDirectory() as static_dir:
  303. duplicate = os.path.join(static_dir, 'test', 'file.txt')
  304. os.mkdir(os.path.dirname(duplicate))
  305. with open(duplicate, 'w+') as f:
  306. f.write('duplicate of file.txt')
  307. with self.settings(STATICFILES_DIRS=[static_dir]):
  308. output = self._collectstatic_output(clear=True)
  309. self.assertIn(self.warning_string, output)
  310. os.remove(duplicate)
  311. # Make sure the warning went away again.
  312. with self.settings(STATICFILES_DIRS=[static_dir]):
  313. output = self._collectstatic_output(clear=True)
  314. self.assertNotIn(self.warning_string, output)
  315. @override_settings(STATICFILES_STORAGE='staticfiles_tests.storage.DummyStorage')
  316. class TestCollectionNonLocalStorage(TestNoFilesCreated, CollectionTestCase):
  317. """
  318. Tests for a Storage that implements get_modified_time() but not path()
  319. (#15035).
  320. """
  321. def test_storage_properties(self):
  322. # Properties of the Storage as described in the ticket.
  323. storage = DummyStorage()
  324. self.assertEqual(storage.get_modified_time('name'), datetime.datetime(1970, 1, 1, tzinfo=timezone.utc))
  325. with self.assertRaisesMessage(NotImplementedError, "This backend doesn't support absolute paths."):
  326. storage.path('name')
  327. class TestCollectionNeverCopyStorage(CollectionTestCase):
  328. @override_settings(STATICFILES_STORAGE='staticfiles_tests.storage.NeverCopyRemoteStorage')
  329. def test_skips_newer_files_in_remote_storage(self):
  330. """
  331. collectstatic skips newer files in a remote storage.
  332. run_collectstatic() in setUp() copies the static files, then files are
  333. always skipped after NeverCopyRemoteStorage is activated since
  334. NeverCopyRemoteStorage.get_modified_time() returns a datetime in the
  335. future to simulate an unmodified file.
  336. """
  337. stdout = StringIO()
  338. self.run_collectstatic(stdout=stdout, verbosity=2)
  339. output = stdout.getvalue()
  340. self.assertIn("Skipping 'test.txt' (not modified)", output)
  341. @unittest.skipUnless(symlinks_supported(), "Must be able to symlink to run this test.")
  342. class TestCollectionLinks(TestDefaults, CollectionTestCase):
  343. """
  344. Test ``--link`` option for ``collectstatic`` management command.
  345. Note that by inheriting ``TestDefaults`` we repeat all
  346. the standard file resolving tests here, to make sure using
  347. ``--link`` does not change the file-selection semantics.
  348. """
  349. def run_collectstatic(self, clear=False, link=True, **kwargs):
  350. super().run_collectstatic(link=link, clear=clear, **kwargs)
  351. def test_links_created(self):
  352. """
  353. With ``--link``, symbolic links are created.
  354. """
  355. self.assertTrue(os.path.islink(os.path.join(settings.STATIC_ROOT, 'test.txt')))
  356. def test_broken_symlink(self):
  357. """
  358. Test broken symlink gets deleted.
  359. """
  360. path = os.path.join(settings.STATIC_ROOT, 'test.txt')
  361. os.unlink(path)
  362. self.run_collectstatic()
  363. self.assertTrue(os.path.islink(path))
  364. def test_symlinks_and_files_replaced(self):
  365. """
  366. Running collectstatic in non-symlink mode replaces symlinks with files,
  367. while symlink mode replaces files with symlinks.
  368. """
  369. path = os.path.join(settings.STATIC_ROOT, 'test.txt')
  370. self.assertTrue(os.path.islink(path))
  371. self.run_collectstatic(link=False)
  372. self.assertFalse(os.path.islink(path))
  373. self.run_collectstatic(link=True)
  374. self.assertTrue(os.path.islink(path))
  375. def test_clear_broken_symlink(self):
  376. """
  377. With ``--clear``, broken symbolic links are deleted.
  378. """
  379. nonexistent_file_path = os.path.join(settings.STATIC_ROOT, 'nonexistent.txt')
  380. broken_symlink_path = os.path.join(settings.STATIC_ROOT, 'symlink.txt')
  381. os.symlink(nonexistent_file_path, broken_symlink_path)
  382. self.run_collectstatic(clear=True)
  383. self.assertFalse(os.path.lexists(broken_symlink_path))