tests.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888
  1. # -*- encoding: utf-8 -*-
  2. from __future__ import unicode_literals
  3. import codecs
  4. import os
  5. import posixpath
  6. import shutil
  7. import sys
  8. import tempfile
  9. import unittest
  10. from django.template import loader, Context
  11. from django.conf import settings
  12. from django.core.cache.backends.base import BaseCache
  13. from django.core.exceptions import ImproperlyConfigured
  14. from django.core.management import call_command
  15. from django.test import TestCase
  16. from django.test.utils import override_settings
  17. from django.utils.encoding import force_text
  18. from django.utils.functional import empty
  19. from django.utils._os import rmtree_errorhandler, upath
  20. from django.utils import six
  21. from django.contrib.staticfiles import finders, storage
  22. from django.contrib.staticfiles.management.commands import collectstatic
  23. TEST_ROOT = os.path.dirname(upath(__file__))
  24. TEST_SETTINGS = {
  25. 'DEBUG': True,
  26. 'MEDIA_URL': '/media/',
  27. 'STATIC_URL': '/static/',
  28. 'MEDIA_ROOT': os.path.join(TEST_ROOT, 'project', 'site_media', 'media'),
  29. 'STATIC_ROOT': os.path.join(TEST_ROOT, 'project', 'site_media', 'static'),
  30. 'STATICFILES_DIRS': (
  31. os.path.join(TEST_ROOT, 'project', 'documents'),
  32. ('prefix', os.path.join(TEST_ROOT, 'project', 'prefixed')),
  33. ),
  34. 'STATICFILES_FINDERS': (
  35. 'django.contrib.staticfiles.finders.FileSystemFinder',
  36. 'django.contrib.staticfiles.finders.AppDirectoriesFinder',
  37. 'django.contrib.staticfiles.finders.DefaultStorageFinder',
  38. ),
  39. }
  40. from django.contrib.staticfiles.management.commands.collectstatic import Command as CollectstaticCommand
  41. class BaseStaticFilesTestCase(object):
  42. """
  43. Test case with a couple utility assertions.
  44. """
  45. def setUp(self):
  46. # Clear the cached staticfiles_storage out, this is because when it first
  47. # gets accessed (by some other test), it evaluates settings.STATIC_ROOT,
  48. # since we're planning on changing that we need to clear out the cache.
  49. storage.staticfiles_storage._wrapped = empty
  50. # Clear the cached staticfile finders, so they are reinitialized every
  51. # run and pick up changes in settings.STATICFILES_DIRS.
  52. finders.get_finder.cache_clear()
  53. testfiles_path = os.path.join(TEST_ROOT, 'apps', 'test', 'static', 'test')
  54. # To make sure SVN doesn't hangs itself with the non-ASCII characters
  55. # during checkout, we actually create one file dynamically.
  56. self._nonascii_filepath = os.path.join(testfiles_path, '\u2297.txt')
  57. with codecs.open(self._nonascii_filepath, 'w', 'utf-8') as f:
  58. f.write("\u2297 in the app dir")
  59. # And also create the stupid hidden file to dwarf the setup.py's
  60. # package data handling.
  61. self._hidden_filepath = os.path.join(testfiles_path, '.hidden')
  62. with codecs.open(self._hidden_filepath, 'w', 'utf-8') as f:
  63. f.write("should be ignored")
  64. self._backup_filepath = os.path.join(
  65. TEST_ROOT, 'project', 'documents', 'test', 'backup~')
  66. with codecs.open(self._backup_filepath, 'w', 'utf-8') as f:
  67. f.write("should be ignored")
  68. def tearDown(self):
  69. os.unlink(self._nonascii_filepath)
  70. os.unlink(self._hidden_filepath)
  71. os.unlink(self._backup_filepath)
  72. def assertFileContains(self, filepath, text):
  73. self.assertIn(text, self._get_file(force_text(filepath)),
  74. "'%s' not in '%s'" % (text, filepath))
  75. def assertFileNotFound(self, filepath):
  76. self.assertRaises(IOError, self._get_file, filepath)
  77. def render_template(self, template, **kwargs):
  78. if isinstance(template, six.string_types):
  79. template = loader.get_template_from_string(template)
  80. return template.render(Context(kwargs)).strip()
  81. def static_template_snippet(self, path, asvar=False):
  82. if asvar:
  83. return "{%% load static from staticfiles %%}{%% static '%s' as var %%}{{ var }}" % path
  84. return "{%% load static from staticfiles %%}{%% static '%s' %%}" % path
  85. def assertStaticRenders(self, path, result, asvar=False, **kwargs):
  86. template = self.static_template_snippet(path, asvar)
  87. self.assertEqual(self.render_template(template, **kwargs), result)
  88. def assertStaticRaises(self, exc, path, result, asvar=False, **kwargs):
  89. self.assertRaises(exc, self.assertStaticRenders, path, result, **kwargs)
  90. @override_settings(**TEST_SETTINGS)
  91. class StaticFilesTestCase(BaseStaticFilesTestCase, TestCase):
  92. pass
  93. class BaseCollectionTestCase(BaseStaticFilesTestCase):
  94. """
  95. Tests shared by all file finding features (collectstatic,
  96. findstatic, and static serve view).
  97. This relies on the asserts defined in BaseStaticFilesTestCase, but
  98. is separated because some test cases need those asserts without
  99. all these tests.
  100. """
  101. def setUp(self):
  102. super(BaseCollectionTestCase, self).setUp()
  103. self.old_root = settings.STATIC_ROOT
  104. settings.STATIC_ROOT = tempfile.mkdtemp(dir=os.environ['DJANGO_TEST_TEMP_DIR'])
  105. self.run_collectstatic()
  106. # Use our own error handler that can handle .svn dirs on Windows
  107. self.addCleanup(shutil.rmtree, settings.STATIC_ROOT,
  108. ignore_errors=True, onerror=rmtree_errorhandler)
  109. def tearDown(self):
  110. settings.STATIC_ROOT = self.old_root
  111. super(BaseCollectionTestCase, self).tearDown()
  112. def run_collectstatic(self, **kwargs):
  113. call_command('collectstatic', interactive=False, verbosity='0',
  114. ignore_patterns=['*.ignoreme'], **kwargs)
  115. def _get_file(self, filepath):
  116. assert filepath, 'filepath is empty.'
  117. filepath = os.path.join(settings.STATIC_ROOT, filepath)
  118. with codecs.open(filepath, "r", "utf-8") as f:
  119. return f.read()
  120. class CollectionTestCase(BaseCollectionTestCase, StaticFilesTestCase):
  121. pass
  122. class TestDefaults(object):
  123. """
  124. A few standard test cases.
  125. """
  126. def test_staticfiles_dirs(self):
  127. """
  128. Can find a file in a STATICFILES_DIRS directory.
  129. """
  130. self.assertFileContains('test.txt', 'Can we find')
  131. self.assertFileContains(os.path.join('prefix', 'test.txt'), 'Prefix')
  132. def test_staticfiles_dirs_subdir(self):
  133. """
  134. Can find a file in a subdirectory of a STATICFILES_DIRS
  135. directory.
  136. """
  137. self.assertFileContains('subdir/test.txt', 'Can we find')
  138. def test_staticfiles_dirs_priority(self):
  139. """
  140. File in STATICFILES_DIRS has priority over file in app.
  141. """
  142. self.assertFileContains('test/file.txt', 'STATICFILES_DIRS')
  143. def test_app_files(self):
  144. """
  145. Can find a file in an app static/ directory.
  146. """
  147. self.assertFileContains('test/file1.txt', 'file1 in the app dir')
  148. def test_nonascii_filenames(self):
  149. """
  150. Can find a file with non-ASCII character in an app static/ directory.
  151. """
  152. self.assertFileContains('test/⊗.txt', '⊗ in the app dir')
  153. def test_camelcase_filenames(self):
  154. """
  155. Can find a file with capital letters.
  156. """
  157. self.assertFileContains('test/camelCase.txt', 'camelCase')
  158. class TestFindStatic(CollectionTestCase, TestDefaults):
  159. """
  160. Test ``findstatic`` management command.
  161. """
  162. def _get_file(self, filepath):
  163. out = six.StringIO()
  164. call_command('findstatic', filepath, all=False, verbosity=0, stdout=out)
  165. out.seek(0)
  166. lines = [l.strip() for l in out.readlines()]
  167. with codecs.open(force_text(lines[0].strip()), "r", "utf-8") as f:
  168. return f.read()
  169. def test_all_files(self):
  170. """
  171. Test that findstatic returns all candidate files if run without --first and -v1.
  172. """
  173. out = six.StringIO()
  174. call_command('findstatic', 'test/file.txt', verbosity=1, stdout=out)
  175. out.seek(0)
  176. lines = [l.strip() for l in out.readlines()]
  177. self.assertEqual(len(lines), 3) # three because there is also the "Found <file> here" line
  178. self.assertIn('project', force_text(lines[1]))
  179. self.assertIn('apps', force_text(lines[2]))
  180. def test_all_files_less_verbose(self):
  181. """
  182. Test that findstatic returns all candidate files if run without --first and -v0.
  183. """
  184. out = six.StringIO()
  185. call_command('findstatic', 'test/file.txt', verbosity=0, stdout=out)
  186. out.seek(0)
  187. lines = [l.strip() for l in out.readlines()]
  188. self.assertEqual(len(lines), 2)
  189. self.assertIn('project', force_text(lines[0]))
  190. self.assertIn('apps', force_text(lines[1]))
  191. class TestCollection(CollectionTestCase, TestDefaults):
  192. """
  193. Test ``collectstatic`` management command.
  194. """
  195. def test_ignore(self):
  196. """
  197. Test that -i patterns are ignored.
  198. """
  199. self.assertFileNotFound('test/test.ignoreme')
  200. def test_common_ignore_patterns(self):
  201. """
  202. Common ignore patterns (*~, .*, CVS) are ignored.
  203. """
  204. self.assertFileNotFound('test/.hidden')
  205. self.assertFileNotFound('test/backup~')
  206. self.assertFileNotFound('test/CVS')
  207. class TestCollectionClear(CollectionTestCase):
  208. """
  209. Test the ``--clear`` option of the ``collectstatic`` management command.
  210. """
  211. def run_collectstatic(self, **kwargs):
  212. clear_filepath = os.path.join(settings.STATIC_ROOT, 'cleared.txt')
  213. with open(clear_filepath, 'w') as f:
  214. f.write('should be cleared')
  215. super(TestCollectionClear, self).run_collectstatic(clear=True)
  216. def test_cleared_not_found(self):
  217. self.assertFileNotFound('cleared.txt')
  218. class TestCollectionExcludeNoDefaultIgnore(CollectionTestCase, TestDefaults):
  219. """
  220. Test ``--exclude-dirs`` and ``--no-default-ignore`` options of the
  221. ``collectstatic`` management command.
  222. """
  223. def run_collectstatic(self):
  224. super(TestCollectionExcludeNoDefaultIgnore, self).run_collectstatic(
  225. use_default_ignore_patterns=False)
  226. def test_no_common_ignore_patterns(self):
  227. """
  228. With --no-default-ignore, common ignore patterns (*~, .*, CVS)
  229. are not ignored.
  230. """
  231. self.assertFileContains('test/.hidden', 'should be ignored')
  232. self.assertFileContains('test/backup~', 'should be ignored')
  233. self.assertFileContains('test/CVS', 'should be ignored')
  234. class TestNoFilesCreated(object):
  235. def test_no_files_created(self):
  236. """
  237. Make sure no files were create in the destination directory.
  238. """
  239. self.assertEqual(os.listdir(settings.STATIC_ROOT), [])
  240. class TestCollectionDryRun(CollectionTestCase, TestNoFilesCreated):
  241. """
  242. Test ``--dry-run`` option for ``collectstatic`` management command.
  243. """
  244. def run_collectstatic(self):
  245. super(TestCollectionDryRun, self).run_collectstatic(dry_run=True)
  246. class TestCollectionFilesOverride(CollectionTestCase):
  247. """
  248. Test overriding duplicated files by ``collectstatic`` management command.
  249. Check for proper handling of apps order in INSTALLED_APPS even if file modification
  250. dates are in different order:
  251. 'staticfiles_tests.apps.test',
  252. 'staticfiles_tests.apps.no_label',
  253. """
  254. def setUp(self):
  255. self.orig_path = os.path.join(TEST_ROOT, 'apps', 'no_label', 'static', 'file2.txt')
  256. # get modification and access times for no_label/static/file2.txt
  257. self.orig_mtime = os.path.getmtime(self.orig_path)
  258. self.orig_atime = os.path.getatime(self.orig_path)
  259. # prepare duplicate of file2.txt from no_label app
  260. # this file will have modification time older than no_label/static/file2.txt
  261. # anyway it should be taken to STATIC_ROOT because 'test' app is before
  262. # 'no_label' app in INSTALLED_APPS
  263. self.testfile_path = os.path.join(TEST_ROOT, 'apps', 'test', 'static', 'file2.txt')
  264. with open(self.testfile_path, 'w+') as f:
  265. f.write('duplicate of file2.txt')
  266. os.utime(self.testfile_path, (self.orig_atime - 1, self.orig_mtime - 1))
  267. super(TestCollectionFilesOverride, self).setUp()
  268. def tearDown(self):
  269. if os.path.exists(self.testfile_path):
  270. os.unlink(self.testfile_path)
  271. # set back original modification time
  272. os.utime(self.orig_path, (self.orig_atime, self.orig_mtime))
  273. super(TestCollectionFilesOverride, self).tearDown()
  274. def test_ordering_override(self):
  275. """
  276. Test if collectstatic takes files in proper order
  277. """
  278. self.assertFileContains('file2.txt', 'duplicate of file2.txt')
  279. # run collectstatic again
  280. self.run_collectstatic()
  281. self.assertFileContains('file2.txt', 'duplicate of file2.txt')
  282. # and now change modification time of no_label/static/file2.txt
  283. # test app is first in INSTALLED_APPS so file2.txt should remain unmodified
  284. mtime = os.path.getmtime(self.testfile_path)
  285. atime = os.path.getatime(self.testfile_path)
  286. os.utime(self.orig_path, (mtime + 1, atime + 1))
  287. # run collectstatic again
  288. self.run_collectstatic()
  289. self.assertFileContains('file2.txt', 'duplicate of file2.txt')
  290. @override_settings(
  291. STATICFILES_STORAGE='staticfiles_tests.storage.DummyStorage',
  292. )
  293. class TestCollectionNonLocalStorage(CollectionTestCase, TestNoFilesCreated):
  294. """
  295. Tests for #15035
  296. """
  297. pass
  298. # we set DEBUG to False here since the template tag wouldn't work otherwise
  299. @override_settings(**dict(TEST_SETTINGS,
  300. STATICFILES_STORAGE='django.contrib.staticfiles.storage.CachedStaticFilesStorage',
  301. DEBUG=False,
  302. ))
  303. class TestCollectionCachedStorage(BaseCollectionTestCase,
  304. BaseStaticFilesTestCase, TestCase):
  305. """
  306. Tests for the Cache busting storage
  307. """
  308. def cached_file_path(self, path):
  309. fullpath = self.render_template(self.static_template_snippet(path))
  310. return fullpath.replace(settings.STATIC_URL, '')
  311. def test_template_tag_return(self):
  312. """
  313. Test the CachedStaticFilesStorage backend.
  314. """
  315. self.assertStaticRaises(ValueError,
  316. "does/not/exist.png",
  317. "/static/does/not/exist.png")
  318. self.assertStaticRenders("test/file.txt",
  319. "/static/test/file.dad0999e4f8f.txt")
  320. self.assertStaticRenders("test/file.txt",
  321. "/static/test/file.dad0999e4f8f.txt", asvar=True)
  322. self.assertStaticRenders("cached/styles.css",
  323. "/static/cached/styles.93b1147e8552.css")
  324. self.assertStaticRenders("path/",
  325. "/static/path/")
  326. self.assertStaticRenders("path/?query",
  327. "/static/path/?query")
  328. def test_template_tag_simple_content(self):
  329. relpath = self.cached_file_path("cached/styles.css")
  330. self.assertEqual(relpath, "cached/styles.93b1147e8552.css")
  331. with storage.staticfiles_storage.open(relpath) as relfile:
  332. content = relfile.read()
  333. self.assertNotIn(b"cached/other.css", content)
  334. self.assertIn(b"other.d41d8cd98f00.css", content)
  335. def test_path_ignored_completely(self):
  336. relpath = self.cached_file_path("cached/css/ignored.css")
  337. self.assertEqual(relpath, "cached/css/ignored.6c77f2643390.css")
  338. with storage.staticfiles_storage.open(relpath) as relfile:
  339. content = relfile.read()
  340. self.assertIn(b'#foobar', content)
  341. self.assertIn(b'http:foobar', content)
  342. self.assertIn(b'https:foobar', content)
  343. self.assertIn(b'data:foobar', content)
  344. self.assertIn(b'//foobar', content)
  345. def test_path_with_querystring(self):
  346. relpath = self.cached_file_path("cached/styles.css?spam=eggs")
  347. self.assertEqual(relpath,
  348. "cached/styles.93b1147e8552.css?spam=eggs")
  349. with storage.staticfiles_storage.open(
  350. "cached/styles.93b1147e8552.css") as relfile:
  351. content = relfile.read()
  352. self.assertNotIn(b"cached/other.css", content)
  353. self.assertIn(b"other.d41d8cd98f00.css", content)
  354. def test_path_with_fragment(self):
  355. relpath = self.cached_file_path("cached/styles.css#eggs")
  356. self.assertEqual(relpath, "cached/styles.93b1147e8552.css#eggs")
  357. with storage.staticfiles_storage.open(
  358. "cached/styles.93b1147e8552.css") as relfile:
  359. content = relfile.read()
  360. self.assertNotIn(b"cached/other.css", content)
  361. self.assertIn(b"other.d41d8cd98f00.css", content)
  362. def test_path_with_querystring_and_fragment(self):
  363. relpath = self.cached_file_path("cached/css/fragments.css")
  364. self.assertEqual(relpath, "cached/css/fragments.75433540b096.css")
  365. with storage.staticfiles_storage.open(relpath) as relfile:
  366. content = relfile.read()
  367. self.assertIn(b'fonts/font.a4b0478549d0.eot?#iefix', content)
  368. self.assertIn(b'fonts/font.b8d603e42714.svg#webfontIyfZbseF', content)
  369. self.assertIn(b'data:font/woff;charset=utf-8;base64,d09GRgABAAAAADJoAA0AAAAAR2QAAQAAAAAAAAAAAAA', content)
  370. self.assertIn(b'#default#VML', content)
  371. def test_template_tag_absolute(self):
  372. relpath = self.cached_file_path("cached/absolute.css")
  373. self.assertEqual(relpath, "cached/absolute.23f087ad823a.css")
  374. with storage.staticfiles_storage.open(relpath) as relfile:
  375. content = relfile.read()
  376. self.assertNotIn(b"/static/cached/styles.css", content)
  377. self.assertIn(b"/static/cached/styles.93b1147e8552.css", content)
  378. self.assertIn(b'/static/cached/img/relative.acae32e4532b.png', content)
  379. def test_template_tag_denorm(self):
  380. relpath = self.cached_file_path("cached/denorm.css")
  381. self.assertEqual(relpath, "cached/denorm.c5bd139ad821.css")
  382. with storage.staticfiles_storage.open(relpath) as relfile:
  383. content = relfile.read()
  384. self.assertNotIn(b"..//cached///styles.css", content)
  385. self.assertIn(b"../cached/styles.93b1147e8552.css", content)
  386. self.assertNotIn(b"url(img/relative.png )", content)
  387. self.assertIn(b'url("img/relative.acae32e4532b.png', content)
  388. def test_template_tag_relative(self):
  389. relpath = self.cached_file_path("cached/relative.css")
  390. self.assertEqual(relpath, "cached/relative.2217ea7273c2.css")
  391. with storage.staticfiles_storage.open(relpath) as relfile:
  392. content = relfile.read()
  393. self.assertNotIn(b"../cached/styles.css", content)
  394. self.assertNotIn(b'@import "styles.css"', content)
  395. self.assertNotIn(b'url(img/relative.png)', content)
  396. self.assertIn(b'url("img/relative.acae32e4532b.png")', content)
  397. self.assertIn(b"../cached/styles.93b1147e8552.css", content)
  398. def test_import_replacement(self):
  399. "See #18050"
  400. relpath = self.cached_file_path("cached/import.css")
  401. self.assertEqual(relpath, "cached/import.2b1d40b0bbd4.css")
  402. with storage.staticfiles_storage.open(relpath) as relfile:
  403. self.assertIn(b"""import url("styles.93b1147e8552.css")""", relfile.read())
  404. def test_template_tag_deep_relative(self):
  405. relpath = self.cached_file_path("cached/css/window.css")
  406. self.assertEqual(relpath, "cached/css/window.9db38d5169f3.css")
  407. with storage.staticfiles_storage.open(relpath) as relfile:
  408. content = relfile.read()
  409. self.assertNotIn(b'url(img/window.png)', content)
  410. self.assertIn(b'url("img/window.acae32e4532b.png")', content)
  411. def test_template_tag_url(self):
  412. relpath = self.cached_file_path("cached/url.css")
  413. self.assertEqual(relpath, "cached/url.615e21601e4b.css")
  414. with storage.staticfiles_storage.open(relpath) as relfile:
  415. self.assertIn(b"https://", relfile.read())
  416. def test_cache_invalidation(self):
  417. name = "cached/styles.css"
  418. hashed_name = "cached/styles.93b1147e8552.css"
  419. # check if the cache is filled correctly as expected
  420. cache_key = storage.staticfiles_storage.cache_key(name)
  421. cached_name = storage.staticfiles_storage.cache.get(cache_key)
  422. self.assertEqual(self.cached_file_path(name), cached_name)
  423. # clearing the cache to make sure we re-set it correctly in the url method
  424. storage.staticfiles_storage.cache.clear()
  425. cached_name = storage.staticfiles_storage.cache.get(cache_key)
  426. self.assertEqual(cached_name, None)
  427. self.assertEqual(self.cached_file_path(name), hashed_name)
  428. cached_name = storage.staticfiles_storage.cache.get(cache_key)
  429. self.assertEqual(cached_name, hashed_name)
  430. def test_post_processing(self):
  431. """Test that post_processing behaves correctly.
  432. Files that are alterable should always be post-processed; files that
  433. aren't should be skipped.
  434. collectstatic has already been called once in setUp() for this testcase,
  435. therefore we check by verifying behavior on a second run.
  436. """
  437. collectstatic_args = {
  438. 'interactive': False,
  439. 'verbosity': '0',
  440. 'link': False,
  441. 'clear': False,
  442. 'dry_run': False,
  443. 'post_process': True,
  444. 'use_default_ignore_patterns': True,
  445. 'ignore_patterns': ['*.ignoreme'],
  446. }
  447. collectstatic_cmd = CollectstaticCommand()
  448. collectstatic_cmd.set_options(**collectstatic_args)
  449. stats = collectstatic_cmd.collect()
  450. self.assertIn(os.path.join('cached', 'css', 'window.css'), stats['post_processed'])
  451. self.assertIn(os.path.join('cached', 'css', 'img', 'window.png'), stats['unmodified'])
  452. self.assertIn(os.path.join('test', 'nonascii.css'), stats['post_processed'])
  453. def test_cache_key_memcache_validation(self):
  454. """
  455. Handle cache key creation correctly, see #17861.
  456. """
  457. name = "/some crazy/long filename/ with spaces Here and ?#%#$/other/stuff/some crazy/long filename/ with spaces Here and ?#%#$/other/stuff/some crazy/long filename/ with spaces Here and ?#%#$/other/stuff/some crazy/long filename/ with spaces Here and ?#%#$/other/stuff/some crazy/long filename/ with spaces Here and ?#%#$/other/stuff/some crazy/" + "\x16" + "\xb4"
  458. cache_key = storage.staticfiles_storage.cache_key(name)
  459. cache_validator = BaseCache({})
  460. cache_validator.validate_key(cache_key)
  461. self.assertEqual(cache_key, 'staticfiles:821ea71ef36f95b3922a77f7364670e7')
  462. def test_css_import_case_insensitive(self):
  463. relpath = self.cached_file_path("cached/styles_insensitive.css")
  464. self.assertEqual(relpath, "cached/styles_insensitive.2f0151cca872.css")
  465. with storage.staticfiles_storage.open(relpath) as relfile:
  466. content = relfile.read()
  467. self.assertNotIn(b"cached/other.css", content)
  468. self.assertIn(b"other.d41d8cd98f00.css", content)
  469. @override_settings(
  470. STATICFILES_DIRS=(os.path.join(TEST_ROOT, 'project', 'faulty'),),
  471. STATICFILES_FINDERS=('django.contrib.staticfiles.finders.FileSystemFinder',),
  472. )
  473. def test_post_processing_failure(self):
  474. """
  475. Test that post_processing indicates the origin of the error when it
  476. fails. Regression test for #18986.
  477. """
  478. finders.get_finder.cache_clear()
  479. err = six.StringIO()
  480. with self.assertRaises(Exception):
  481. call_command('collectstatic', interactive=False, verbosity=0, stderr=err)
  482. self.assertEqual("Post-processing 'faulty.css' failed!\n\n", err.getvalue())
  483. # we set DEBUG to False here since the template tag wouldn't work otherwise
  484. @override_settings(**dict(TEST_SETTINGS,
  485. STATICFILES_STORAGE='staticfiles_tests.storage.SimpleCachedStaticFilesStorage',
  486. DEBUG=False,
  487. ))
  488. class TestCollectionSimpleCachedStorage(BaseCollectionTestCase,
  489. BaseStaticFilesTestCase, TestCase):
  490. """
  491. Tests for the Cache busting storage
  492. """
  493. def cached_file_path(self, path):
  494. fullpath = self.render_template(self.static_template_snippet(path))
  495. return fullpath.replace(settings.STATIC_URL, '')
  496. def test_template_tag_return(self):
  497. """
  498. Test the CachedStaticFilesStorage backend.
  499. """
  500. self.assertStaticRaises(ValueError,
  501. "does/not/exist.png",
  502. "/static/does/not/exist.png")
  503. self.assertStaticRenders("test/file.txt",
  504. "/static/test/file.deploy12345.txt")
  505. self.assertStaticRenders("cached/styles.css",
  506. "/static/cached/styles.deploy12345.css")
  507. self.assertStaticRenders("path/",
  508. "/static/path/")
  509. self.assertStaticRenders("path/?query",
  510. "/static/path/?query")
  511. def test_template_tag_simple_content(self):
  512. relpath = self.cached_file_path("cached/styles.css")
  513. self.assertEqual(relpath, "cached/styles.deploy12345.css")
  514. with storage.staticfiles_storage.open(relpath) as relfile:
  515. content = relfile.read()
  516. self.assertNotIn(b"cached/other.css", content)
  517. self.assertIn(b"other.deploy12345.css", content)
  518. if sys.platform != 'win32':
  519. class TestCollectionLinks(CollectionTestCase, TestDefaults):
  520. """
  521. Test ``--link`` option for ``collectstatic`` management command.
  522. Note that by inheriting ``TestDefaults`` we repeat all
  523. the standard file resolving tests here, to make sure using
  524. ``--link`` does not change the file-selection semantics.
  525. """
  526. def run_collectstatic(self):
  527. super(TestCollectionLinks, self).run_collectstatic(link=True)
  528. def test_links_created(self):
  529. """
  530. With ``--link``, symbolic links are created.
  531. """
  532. self.assertTrue(os.path.islink(os.path.join(settings.STATIC_ROOT, 'test.txt')))
  533. class TestServeStatic(StaticFilesTestCase):
  534. """
  535. Test static asset serving view.
  536. """
  537. urls = 'staticfiles_tests.urls.default'
  538. def _response(self, filepath):
  539. return self.client.get(
  540. posixpath.join(settings.STATIC_URL, filepath))
  541. def assertFileContains(self, filepath, text):
  542. self.assertContains(self._response(filepath), text)
  543. def assertFileNotFound(self, filepath):
  544. self.assertEqual(self._response(filepath).status_code, 404)
  545. class TestServeDisabled(TestServeStatic):
  546. """
  547. Test serving static files disabled when DEBUG is False.
  548. """
  549. def setUp(self):
  550. super(TestServeDisabled, self).setUp()
  551. settings.DEBUG = False
  552. def test_disabled_serving(self):
  553. self.assertFileNotFound('test.txt')
  554. class TestServeStaticWithDefaultURL(TestServeStatic, TestDefaults):
  555. """
  556. Test static asset serving view with manually configured URLconf.
  557. """
  558. pass
  559. class TestServeStaticWithURLHelper(TestServeStatic, TestDefaults):
  560. """
  561. Test static asset serving view with staticfiles_urlpatterns helper.
  562. """
  563. urls = 'staticfiles_tests.urls.helper'
  564. class TestServeAdminMedia(TestServeStatic):
  565. """
  566. Test serving media from django.contrib.admin.
  567. """
  568. def _response(self, filepath):
  569. return self.client.get(
  570. posixpath.join(settings.STATIC_URL, 'admin/', filepath))
  571. def test_serve_admin_media(self):
  572. self.assertFileContains('css/base.css', 'body')
  573. class FinderTestCase(object):
  574. """
  575. Base finder test mixin.
  576. On Windows, sometimes the case of the path we ask the finders for and the
  577. path(s) they find can differ. Compare them using os.path.normcase() to
  578. avoid false negatives.
  579. """
  580. def test_find_first(self):
  581. src, dst = self.find_first
  582. found = self.finder.find(src)
  583. self.assertEqual(os.path.normcase(found), os.path.normcase(dst))
  584. def test_find_all(self):
  585. src, dst = self.find_all
  586. found = self.finder.find(src, all=True)
  587. found = [os.path.normcase(f) for f in found]
  588. dst = [os.path.normcase(d) for d in dst]
  589. self.assertEqual(found, dst)
  590. class TestFileSystemFinder(StaticFilesTestCase, FinderTestCase):
  591. """
  592. Test FileSystemFinder.
  593. """
  594. def setUp(self):
  595. super(TestFileSystemFinder, self).setUp()
  596. self.finder = finders.FileSystemFinder()
  597. test_file_path = os.path.join(TEST_ROOT, 'project', 'documents', 'test', 'file.txt')
  598. self.find_first = (os.path.join('test', 'file.txt'), test_file_path)
  599. self.find_all = (os.path.join('test', 'file.txt'), [test_file_path])
  600. class TestAppDirectoriesFinder(StaticFilesTestCase, FinderTestCase):
  601. """
  602. Test AppDirectoriesFinder.
  603. """
  604. def setUp(self):
  605. super(TestAppDirectoriesFinder, self).setUp()
  606. self.finder = finders.AppDirectoriesFinder()
  607. test_file_path = os.path.join(TEST_ROOT, 'apps', 'test', 'static', 'test', 'file1.txt')
  608. self.find_first = (os.path.join('test', 'file1.txt'), test_file_path)
  609. self.find_all = (os.path.join('test', 'file1.txt'), [test_file_path])
  610. class TestDefaultStorageFinder(StaticFilesTestCase, FinderTestCase):
  611. """
  612. Test DefaultStorageFinder.
  613. """
  614. def setUp(self):
  615. super(TestDefaultStorageFinder, self).setUp()
  616. self.finder = finders.DefaultStorageFinder(
  617. storage=storage.StaticFilesStorage(location=settings.MEDIA_ROOT))
  618. test_file_path = os.path.join(settings.MEDIA_ROOT, 'media-file.txt')
  619. self.find_first = ('media-file.txt', test_file_path)
  620. self.find_all = ('media-file.txt', [test_file_path])
  621. class TestMiscFinder(TestCase):
  622. """
  623. A few misc finder tests.
  624. """
  625. def test_get_finder(self):
  626. self.assertIsInstance(finders.get_finder(
  627. 'django.contrib.staticfiles.finders.FileSystemFinder'),
  628. finders.FileSystemFinder)
  629. def test_get_finder_bad_classname(self):
  630. self.assertRaises(ImproperlyConfigured, finders.get_finder,
  631. 'django.contrib.staticfiles.finders.FooBarFinder')
  632. def test_get_finder_bad_module(self):
  633. self.assertRaises(ImproperlyConfigured,
  634. finders.get_finder, 'foo.bar.FooBarFinder')
  635. def test_cache(self):
  636. finders.get_finder.cache_clear()
  637. for n in range(10):
  638. finders.get_finder(
  639. 'django.contrib.staticfiles.finders.FileSystemFinder')
  640. cache_info = finders.get_finder.cache_info()
  641. self.assertEqual(cache_info.hits, 9)
  642. self.assertEqual(cache_info.currsize, 1)
  643. @override_settings(STATICFILES_DIRS='a string')
  644. def test_non_tuple_raises_exception(self):
  645. """
  646. We can't determine if STATICFILES_DIRS is set correctly just by
  647. looking at the type, but we can determine if it's definitely wrong.
  648. """
  649. self.assertRaises(ImproperlyConfigured, finders.FileSystemFinder)
  650. @override_settings(MEDIA_ROOT='')
  651. def test_location_empty(self):
  652. self.assertRaises(ImproperlyConfigured, finders.DefaultStorageFinder)
  653. class TestTemplateTag(StaticFilesTestCase):
  654. def test_template_tag(self):
  655. self.assertStaticRenders("does/not/exist.png",
  656. "/static/does/not/exist.png")
  657. self.assertStaticRenders("testfile.txt", "/static/testfile.txt")
  658. class TestAppStaticStorage(TestCase):
  659. def setUp(self):
  660. # Creates a python module foo_module in a directory with non ascii
  661. # characters
  662. self.search_path = 'search_path_\xc3\xbc'
  663. os.mkdir(self.search_path)
  664. module_path = os.path.join(self.search_path, 'foo_module')
  665. os.mkdir(module_path)
  666. self.init_file = open(os.path.join(module_path, '__init__.py'), 'w')
  667. sys.path.append(os.path.abspath(self.search_path))
  668. def tearDown(self):
  669. self.init_file.close()
  670. sys.path.remove(os.path.abspath(self.search_path))
  671. shutil.rmtree(self.search_path)
  672. def test_app_with_non_ascii_characters_in_path(self):
  673. """
  674. Regression test for #18404 - Tests AppStaticStorage with a module that
  675. has non ascii characters in path and a non utf8 file system encoding
  676. """
  677. # set file system encoding to a non unicode encoding
  678. old_enc_func = sys.getfilesystemencoding
  679. sys.getfilesystemencoding = lambda: 'ISO-8859-1'
  680. try:
  681. st = storage.AppStaticStorage('foo_module')
  682. st.path('bar')
  683. finally:
  684. sys.getfilesystemencoding = old_enc_func
  685. class CustomStaticFilesStorage(storage.StaticFilesStorage):
  686. """
  687. Used in TestStaticFilePermissions
  688. """
  689. def __init__(self, *args, **kwargs):
  690. kwargs['file_permissions_mode'] = 0o640
  691. kwargs['directory_permissions_mode'] = 0o740
  692. super(CustomStaticFilesStorage, self).__init__(*args, **kwargs)
  693. @unittest.skipIf(sys.platform.startswith('win'),
  694. "Windows only partially supports chmod.")
  695. class TestStaticFilePermissions(BaseCollectionTestCase, StaticFilesTestCase):
  696. command_params = {'interactive': False,
  697. 'post_process': True,
  698. 'verbosity': '0',
  699. 'ignore_patterns': ['*.ignoreme'],
  700. 'use_default_ignore_patterns': True,
  701. 'clear': False,
  702. 'link': False,
  703. 'dry_run': False}
  704. def setUp(self):
  705. self.umask = 0o027
  706. self.old_umask = os.umask(self.umask)
  707. super(TestStaticFilePermissions, self).setUp()
  708. def tearDown(self):
  709. os.umask(self.old_umask)
  710. super(TestStaticFilePermissions, self).tearDown()
  711. # Don't run collectstatic command in this test class.
  712. def run_collectstatic(self, **kwargs):
  713. pass
  714. @override_settings(FILE_UPLOAD_PERMISSIONS=0o655,
  715. FILE_UPLOAD_DIRECTORY_PERMISSIONS=0o765)
  716. def test_collect_static_files_permissions(self):
  717. collectstatic.Command().execute(**self.command_params)
  718. test_file = os.path.join(settings.STATIC_ROOT, "test.txt")
  719. test_dir = os.path.join(settings.STATIC_ROOT, "subdir")
  720. file_mode = os.stat(test_file)[0] & 0o777
  721. dir_mode = os.stat(test_dir)[0] & 0o777
  722. self.assertEqual(file_mode, 0o655)
  723. self.assertEqual(dir_mode, 0o765)
  724. @override_settings(FILE_UPLOAD_PERMISSIONS=None,
  725. FILE_UPLOAD_DIRECTORY_PERMISSIONS=None)
  726. def test_collect_static_files_default_permissions(self):
  727. collectstatic.Command().execute(**self.command_params)
  728. test_file = os.path.join(settings.STATIC_ROOT, "test.txt")
  729. test_dir = os.path.join(settings.STATIC_ROOT, "subdir")
  730. file_mode = os.stat(test_file)[0] & 0o777
  731. dir_mode = os.stat(test_dir)[0] & 0o777
  732. self.assertEqual(file_mode, 0o666 & ~self.umask)
  733. self.assertEqual(dir_mode, 0o777 & ~self.umask)
  734. @override_settings(FILE_UPLOAD_PERMISSIONS=0o655,
  735. FILE_UPLOAD_DIRECTORY_PERMISSIONS=0o765,
  736. STATICFILES_STORAGE='staticfiles_tests.tests.CustomStaticFilesStorage')
  737. def test_collect_static_files_subclass_of_static_storage(self):
  738. collectstatic.Command().execute(**self.command_params)
  739. test_file = os.path.join(settings.STATIC_ROOT, "test.txt")
  740. test_dir = os.path.join(settings.STATIC_ROOT, "subdir")
  741. file_mode = os.stat(test_file)[0] & 0o777
  742. dir_mode = os.stat(test_dir)[0] & 0o777
  743. self.assertEqual(file_mode, 0o640)
  744. self.assertEqual(dir_mode, 0o740)