tests.py 40 KB

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