tests.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728
  1. # -*- encoding: utf-8 -*-
  2. import codecs
  3. import os
  4. import posixpath
  5. import shutil
  6. import sys
  7. import tempfile
  8. from StringIO import StringIO
  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.files.storage import default_storage
  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 smart_unicode
  18. from django.utils.functional import empty
  19. from django.utils._os import rmtree_errorhandler
  20. from django.contrib.staticfiles import finders, storage
  21. TEST_ROOT = os.path.dirname(__file__)
  22. TEST_SETTINGS = {
  23. 'DEBUG': True,
  24. 'MEDIA_URL': '/media/',
  25. 'STATIC_URL': '/static/',
  26. 'MEDIA_ROOT': os.path.join(TEST_ROOT, 'project', 'site_media', 'media'),
  27. 'STATIC_ROOT': os.path.join(TEST_ROOT, 'project', 'site_media', 'static'),
  28. 'STATICFILES_DIRS': (
  29. os.path.join(TEST_ROOT, 'project', 'documents'),
  30. ('prefix', os.path.join(TEST_ROOT, 'project', 'prefixed')),
  31. ),
  32. 'STATICFILES_FINDERS': (
  33. 'django.contrib.staticfiles.finders.FileSystemFinder',
  34. 'django.contrib.staticfiles.finders.AppDirectoriesFinder',
  35. 'django.contrib.staticfiles.finders.DefaultStorageFinder',
  36. ),
  37. }
  38. from django.contrib.staticfiles.management.commands.collectstatic import Command as CollectstaticCommand
  39. class BaseStaticFilesTestCase(object):
  40. """
  41. Test case with a couple utility assertions.
  42. """
  43. def setUp(self):
  44. # Clear the cached default_storage out, this is because when it first
  45. # gets accessed (by some other test), it evaluates settings.MEDIA_ROOT,
  46. # since we're planning on changing that we need to clear out the cache.
  47. default_storage._wrapped = empty
  48. storage.staticfiles_storage._wrapped = empty
  49. testfiles_path = os.path.join(TEST_ROOT, 'apps', 'test', 'static', 'test')
  50. # To make sure SVN doesn't hangs itself with the non-ASCII characters
  51. # during checkout, we actually create one file dynamically.
  52. self._nonascii_filepath = os.path.join(testfiles_path, u'fi\u015fier.txt')
  53. with codecs.open(self._nonascii_filepath, 'w', 'utf-8') as f:
  54. f.write(u"fi\u015fier in the app dir")
  55. # And also create the stupid hidden file to dwarf the setup.py's
  56. # package data handling.
  57. self._hidden_filepath = os.path.join(testfiles_path, '.hidden')
  58. with codecs.open(self._hidden_filepath, 'w', 'utf-8') as f:
  59. f.write("should be ignored")
  60. self._backup_filepath = os.path.join(
  61. TEST_ROOT, 'project', 'documents', 'test', 'backup~')
  62. with codecs.open(self._backup_filepath, 'w', 'utf-8') as f:
  63. f.write("should be ignored")
  64. def tearDown(self):
  65. os.unlink(self._nonascii_filepath)
  66. os.unlink(self._hidden_filepath)
  67. os.unlink(self._backup_filepath)
  68. def assertFileContains(self, filepath, text):
  69. self.assertIn(text, self._get_file(smart_unicode(filepath)),
  70. u"'%s' not in '%s'" % (text, filepath))
  71. def assertFileNotFound(self, filepath):
  72. self.assertRaises(IOError, self._get_file, filepath)
  73. def render_template(self, template, **kwargs):
  74. if isinstance(template, basestring):
  75. template = loader.get_template_from_string(template)
  76. return template.render(Context(kwargs)).strip()
  77. def static_template_snippet(self, path):
  78. return "{%% load static from staticfiles %%}{%% static '%s' %%}" % path
  79. def assertStaticRenders(self, path, result, **kwargs):
  80. template = self.static_template_snippet(path)
  81. self.assertEqual(self.render_template(template, **kwargs), result)
  82. def assertStaticRaises(self, exc, path, result, **kwargs):
  83. self.assertRaises(exc, self.assertStaticRenders, path, result, **kwargs)
  84. @override_settings(**TEST_SETTINGS)
  85. class StaticFilesTestCase(BaseStaticFilesTestCase, TestCase):
  86. pass
  87. class BaseCollectionTestCase(BaseStaticFilesTestCase):
  88. """
  89. Tests shared by all file finding features (collectstatic,
  90. findstatic, and static serve view).
  91. This relies on the asserts defined in BaseStaticFilesTestCase, but
  92. is separated because some test cases need those asserts without
  93. all these tests.
  94. """
  95. def setUp(self):
  96. super(BaseCollectionTestCase, self).setUp()
  97. self.old_root = settings.STATIC_ROOT
  98. settings.STATIC_ROOT = tempfile.mkdtemp(dir=os.environ['DJANGO_TEST_TEMP_DIR'])
  99. self.run_collectstatic()
  100. # Use our own error handler that can handle .svn dirs on Windows
  101. self.addCleanup(shutil.rmtree, settings.STATIC_ROOT,
  102. ignore_errors=True, onerror=rmtree_errorhandler)
  103. def tearDown(self):
  104. settings.STATIC_ROOT = self.old_root
  105. super(BaseCollectionTestCase, self).tearDown()
  106. def run_collectstatic(self, **kwargs):
  107. call_command('collectstatic', interactive=False, verbosity='0',
  108. ignore_patterns=['*.ignoreme'], **kwargs)
  109. def _get_file(self, filepath):
  110. assert filepath, 'filepath is empty.'
  111. filepath = os.path.join(settings.STATIC_ROOT, filepath)
  112. with codecs.open(filepath, "r", "utf-8") as f:
  113. return f.read()
  114. class CollectionTestCase(BaseCollectionTestCase, StaticFilesTestCase):
  115. pass
  116. class TestDefaults(object):
  117. """
  118. A few standard test cases.
  119. """
  120. def test_staticfiles_dirs(self):
  121. """
  122. Can find a file in a STATICFILES_DIRS directory.
  123. """
  124. self.assertFileContains('test.txt', 'Can we find')
  125. self.assertFileContains(os.path.join('prefix', 'test.txt'), 'Prefix')
  126. def test_staticfiles_dirs_subdir(self):
  127. """
  128. Can find a file in a subdirectory of a STATICFILES_DIRS
  129. directory.
  130. """
  131. self.assertFileContains('subdir/test.txt', 'Can we find')
  132. def test_staticfiles_dirs_priority(self):
  133. """
  134. File in STATICFILES_DIRS has priority over file in app.
  135. """
  136. self.assertFileContains('test/file.txt', 'STATICFILES_DIRS')
  137. def test_app_files(self):
  138. """
  139. Can find a file in an app static/ directory.
  140. """
  141. self.assertFileContains('test/file1.txt', 'file1 in the app dir')
  142. def test_nonascii_filenames(self):
  143. """
  144. Can find a file with non-ASCII character in an app static/ directory.
  145. """
  146. self.assertFileContains(u'test/fişier.txt', u'fişier in the app dir')
  147. def test_camelcase_filenames(self):
  148. """
  149. Can find a file with capital letters.
  150. """
  151. self.assertFileContains(u'test/camelCase.txt', u'camelCase')
  152. class TestFindStatic(CollectionTestCase, TestDefaults):
  153. """
  154. Test ``findstatic`` management command.
  155. """
  156. def _get_file(self, filepath):
  157. _stdout = sys.stdout
  158. sys.stdout = StringIO()
  159. try:
  160. call_command('findstatic', filepath, all=False, verbosity='0')
  161. sys.stdout.seek(0)
  162. lines = [l.strip() for l in sys.stdout.readlines()]
  163. contents = codecs.open(
  164. smart_unicode(lines[1].strip()), "r", "utf-8").read()
  165. finally:
  166. sys.stdout = _stdout
  167. return contents
  168. def test_all_files(self):
  169. """
  170. Test that findstatic returns all candidate files if run without --first.
  171. """
  172. _stdout = sys.stdout
  173. sys.stdout = StringIO()
  174. try:
  175. call_command('findstatic', 'test/file.txt', verbosity='0')
  176. sys.stdout.seek(0)
  177. lines = [l.strip() for l in sys.stdout.readlines()]
  178. finally:
  179. sys.stdout = _stdout
  180. self.assertEqual(len(lines), 3) # three because there is also the "Found <file> here" line
  181. self.assertIn('project', lines[1])
  182. self.assertIn('apps', lines[2])
  183. class TestCollection(CollectionTestCase, TestDefaults):
  184. """
  185. Test ``collectstatic`` management command.
  186. """
  187. def test_ignore(self):
  188. """
  189. Test that -i patterns are ignored.
  190. """
  191. self.assertFileNotFound('test/test.ignoreme')
  192. def test_common_ignore_patterns(self):
  193. """
  194. Common ignore patterns (*~, .*, CVS) are ignored.
  195. """
  196. self.assertFileNotFound('test/.hidden')
  197. self.assertFileNotFound('test/backup~')
  198. self.assertFileNotFound('test/CVS')
  199. class TestCollectionClear(CollectionTestCase):
  200. """
  201. Test the ``--clear`` option of the ``collectstatic`` managemenet command.
  202. """
  203. def run_collectstatic(self, **kwargs):
  204. clear_filepath = os.path.join(settings.STATIC_ROOT, 'cleared.txt')
  205. with open(clear_filepath, 'w') as f:
  206. f.write('should be cleared')
  207. super(TestCollectionClear, self).run_collectstatic(clear=True)
  208. def test_cleared_not_found(self):
  209. self.assertFileNotFound('cleared.txt')
  210. class TestCollectionExcludeNoDefaultIgnore(CollectionTestCase, TestDefaults):
  211. """
  212. Test ``--exclude-dirs`` and ``--no-default-ignore`` options of the
  213. ``collectstatic`` management command.
  214. """
  215. def run_collectstatic(self):
  216. super(TestCollectionExcludeNoDefaultIgnore, self).run_collectstatic(
  217. use_default_ignore_patterns=False)
  218. def test_no_common_ignore_patterns(self):
  219. """
  220. With --no-default-ignore, common ignore patterns (*~, .*, CVS)
  221. are not ignored.
  222. """
  223. self.assertFileContains('test/.hidden', 'should be ignored')
  224. self.assertFileContains('test/backup~', 'should be ignored')
  225. self.assertFileContains('test/CVS', 'should be ignored')
  226. class TestNoFilesCreated(object):
  227. def test_no_files_created(self):
  228. """
  229. Make sure no files were create in the destination directory.
  230. """
  231. self.assertEqual(os.listdir(settings.STATIC_ROOT), [])
  232. class TestCollectionDryRun(CollectionTestCase, TestNoFilesCreated):
  233. """
  234. Test ``--dry-run`` option for ``collectstatic`` management command.
  235. """
  236. def run_collectstatic(self):
  237. super(TestCollectionDryRun, self).run_collectstatic(dry_run=True)
  238. class TestCollectionFilesOverride(CollectionTestCase):
  239. """
  240. Test overriding duplicated files by ``collectstatic`` management command.
  241. Check for proper handling of apps order in INSTALLED_APPS even if file modification
  242. dates are in different order:
  243. 'regressiontests.staticfiles_tests.apps.test',
  244. 'regressiontests.staticfiles_tests.apps.no_label',
  245. """
  246. def setUp(self):
  247. self.orig_path = os.path.join(TEST_ROOT, 'apps', 'no_label', 'static', 'file2.txt')
  248. # get modification and access times for no_label/static/file2.txt
  249. self.orig_mtime = os.path.getmtime(self.orig_path)
  250. self.orig_atime = os.path.getatime(self.orig_path)
  251. # prepare duplicate of file2.txt from no_label app
  252. # this file will have modification time older than no_label/static/file2.txt
  253. # anyway it should be taken to STATIC_ROOT because 'test' app is before
  254. # 'no_label' app in INSTALLED_APPS
  255. self.testfile_path = os.path.join(TEST_ROOT, 'apps', 'test', 'static', 'file2.txt')
  256. with open(self.testfile_path, 'w+') as f:
  257. f.write('duplicate of file2.txt')
  258. os.utime(self.testfile_path, (self.orig_atime - 1, self.orig_mtime - 1))
  259. super(TestCollectionFilesOverride, self).setUp()
  260. def tearDown(self):
  261. if os.path.exists(self.testfile_path):
  262. os.unlink(self.testfile_path)
  263. # set back original modification time
  264. os.utime(self.orig_path, (self.orig_atime, self.orig_mtime))
  265. super(TestCollectionFilesOverride, self).tearDown()
  266. def test_ordering_override(self):
  267. """
  268. Test if collectstatic takes files in proper order
  269. """
  270. self.assertFileContains('file2.txt', 'duplicate of file2.txt')
  271. # run collectstatic again
  272. self.run_collectstatic()
  273. self.assertFileContains('file2.txt', 'duplicate of file2.txt')
  274. # and now change modification time of no_label/static/file2.txt
  275. # test app is first in INSTALLED_APPS so file2.txt should remain unmodified
  276. mtime = os.path.getmtime(self.testfile_path)
  277. atime = os.path.getatime(self.testfile_path)
  278. os.utime(self.orig_path, (mtime + 1, atime + 1))
  279. # run collectstatic again
  280. self.run_collectstatic()
  281. self.assertFileContains('file2.txt', 'duplicate of file2.txt')
  282. @override_settings(
  283. STATICFILES_STORAGE='regressiontests.staticfiles_tests.storage.DummyStorage',
  284. )
  285. class TestCollectionNonLocalStorage(CollectionTestCase, TestNoFilesCreated):
  286. """
  287. Tests for #15035
  288. """
  289. pass
  290. # we set DEBUG to False here since the template tag wouldn't work otherwise
  291. @override_settings(**dict(TEST_SETTINGS,
  292. STATICFILES_STORAGE='django.contrib.staticfiles.storage.CachedStaticFilesStorage',
  293. DEBUG=False,
  294. ))
  295. class TestCollectionCachedStorage(BaseCollectionTestCase,
  296. BaseStaticFilesTestCase, TestCase):
  297. """
  298. Tests for the Cache busting storage
  299. """
  300. def cached_file_path(self, path):
  301. fullpath = self.render_template(self.static_template_snippet(path))
  302. return fullpath.replace(settings.STATIC_URL, '')
  303. def test_template_tag_return(self):
  304. """
  305. Test the CachedStaticFilesStorage backend.
  306. """
  307. self.assertStaticRaises(ValueError,
  308. "does/not/exist.png",
  309. "/static/does/not/exist.png")
  310. self.assertStaticRenders("test/file.txt",
  311. "/static/test/file.dad0999e4f8f.txt")
  312. self.assertStaticRenders("cached/styles.css",
  313. "/static/cached/styles.93b1147e8552.css")
  314. self.assertStaticRenders("path/",
  315. "/static/path/")
  316. self.assertStaticRenders("path/?query",
  317. "/static/path/?query")
  318. def test_template_tag_simple_content(self):
  319. relpath = self.cached_file_path("cached/styles.css")
  320. self.assertEqual(relpath, "cached/styles.93b1147e8552.css")
  321. with storage.staticfiles_storage.open(relpath) as relfile:
  322. content = relfile.read()
  323. self.assertNotIn(b"cached/other.css", content)
  324. self.assertIn(b"other.d41d8cd98f00.css", content)
  325. def test_path_with_querystring(self):
  326. relpath = self.cached_file_path("cached/styles.css?spam=eggs")
  327. self.assertEqual(relpath,
  328. "cached/styles.93b1147e8552.css?spam=eggs")
  329. with storage.staticfiles_storage.open(
  330. "cached/styles.93b1147e8552.css") as relfile:
  331. content = relfile.read()
  332. self.assertNotIn(b"cached/other.css", content)
  333. self.assertIn(b"other.d41d8cd98f00.css", content)
  334. def test_path_with_fragment(self):
  335. relpath = self.cached_file_path("cached/styles.css#eggs")
  336. self.assertEqual(relpath, "cached/styles.93b1147e8552.css#eggs")
  337. with storage.staticfiles_storage.open(
  338. "cached/styles.93b1147e8552.css") as relfile:
  339. content = relfile.read()
  340. self.assertNotIn(b"cached/other.css", content)
  341. self.assertIn(b"other.d41d8cd98f00.css", content)
  342. def test_path_with_querystring_and_fragment(self):
  343. relpath = self.cached_file_path("cached/css/fragments.css")
  344. self.assertEqual(relpath, "cached/css/fragments.75433540b096.css")
  345. with storage.staticfiles_storage.open(relpath) as relfile:
  346. content = relfile.read()
  347. self.assertIn(b'fonts/font.a4b0478549d0.eot?#iefix', content)
  348. self.assertIn(b'fonts/font.b8d603e42714.svg#webfontIyfZbseF', content)
  349. self.assertIn(b'data:font/woff;charset=utf-8;base64,d09GRgABAAAAADJoAA0AAAAAR2QAAQAAAAAAAAAAAAA', content)
  350. self.assertIn(b'#default#VML', content)
  351. def test_template_tag_absolute(self):
  352. relpath = self.cached_file_path("cached/absolute.css")
  353. self.assertEqual(relpath, "cached/absolute.23f087ad823a.css")
  354. with storage.staticfiles_storage.open(relpath) as relfile:
  355. content = relfile.read()
  356. self.assertNotIn(b"/static/cached/styles.css", content)
  357. self.assertIn(b"/static/cached/styles.93b1147e8552.css", content)
  358. self.assertIn(b'/static/cached/img/relative.acae32e4532b.png', content)
  359. def test_template_tag_denorm(self):
  360. relpath = self.cached_file_path("cached/denorm.css")
  361. self.assertEqual(relpath, "cached/denorm.c5bd139ad821.css")
  362. with storage.staticfiles_storage.open(relpath) as relfile:
  363. content = relfile.read()
  364. self.assertNotIn(b"..//cached///styles.css", content)
  365. self.assertIn(b"../cached/styles.93b1147e8552.css", content)
  366. self.assertNotIn(b"url(img/relative.png )", content)
  367. self.assertIn(b'url("img/relative.acae32e4532b.png', content)
  368. def test_template_tag_relative(self):
  369. relpath = self.cached_file_path("cached/relative.css")
  370. self.assertEqual(relpath, "cached/relative.2217ea7273c2.css")
  371. with storage.staticfiles_storage.open(relpath) as relfile:
  372. content = relfile.read()
  373. self.assertNotIn(b"../cached/styles.css", content)
  374. self.assertNotIn(b'@import "styles.css"', content)
  375. self.assertNotIn(b'url(img/relative.png)', content)
  376. self.assertIn(b'url("img/relative.acae32e4532b.png")', content)
  377. self.assertIn(b"../cached/styles.93b1147e8552.css", content)
  378. def test_template_tag_deep_relative(self):
  379. relpath = self.cached_file_path("cached/css/window.css")
  380. self.assertEqual(relpath, "cached/css/window.9db38d5169f3.css")
  381. with storage.staticfiles_storage.open(relpath) as relfile:
  382. content = relfile.read()
  383. self.assertNotIn(b'url(img/window.png)', content)
  384. self.assertIn(b'url("img/window.acae32e4532b.png")', content)
  385. def test_template_tag_url(self):
  386. relpath = self.cached_file_path("cached/url.css")
  387. self.assertEqual(relpath, "cached/url.615e21601e4b.css")
  388. with storage.staticfiles_storage.open(relpath) as relfile:
  389. self.assertIn(b"https://", relfile.read())
  390. def test_cache_invalidation(self):
  391. name = "cached/styles.css"
  392. hashed_name = "cached/styles.93b1147e8552.css"
  393. # check if the cache is filled correctly as expected
  394. cache_key = storage.staticfiles_storage.cache_key(name)
  395. cached_name = storage.staticfiles_storage.cache.get(cache_key)
  396. self.assertEqual(self.cached_file_path(name), cached_name)
  397. # clearing the cache to make sure we re-set it correctly in the url method
  398. storage.staticfiles_storage.cache.clear()
  399. cached_name = storage.staticfiles_storage.cache.get(cache_key)
  400. self.assertEqual(cached_name, None)
  401. self.assertEqual(self.cached_file_path(name), hashed_name)
  402. cached_name = storage.staticfiles_storage.cache.get(cache_key)
  403. self.assertEqual(cached_name, hashed_name)
  404. def test_post_processing(self):
  405. """Test that post_processing behaves correctly.
  406. Files that are alterable should always be post-processed; files that
  407. aren't should be skipped.
  408. collectstatic has already been called once in setUp() for this testcase,
  409. therefore we check by verifying behavior on a second run.
  410. """
  411. collectstatic_args = {
  412. 'interactive': False,
  413. 'verbosity': '0',
  414. 'link': False,
  415. 'clear': False,
  416. 'dry_run': False,
  417. 'post_process': True,
  418. 'use_default_ignore_patterns': True,
  419. 'ignore_patterns': ['*.ignoreme'],
  420. }
  421. collectstatic_cmd = CollectstaticCommand()
  422. collectstatic_cmd.set_options(**collectstatic_args)
  423. stats = collectstatic_cmd.collect()
  424. self.assertTrue(os.path.join('cached', 'css', 'window.css') in stats['post_processed'])
  425. self.assertTrue(os.path.join('cached', 'css', 'img', 'window.png') in stats['unmodified'])
  426. def test_cache_key_memcache_validation(self):
  427. """
  428. Handle cache key creation correctly, see #17861.
  429. """
  430. name = b"/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/" + chr(22) + chr(180)
  431. cache_key = storage.staticfiles_storage.cache_key(name)
  432. cache_validator = BaseCache({})
  433. cache_validator.validate_key(cache_key)
  434. self.assertEqual(cache_key, 'staticfiles:e95bbc36387084582df2a70750d7b351')
  435. # we set DEBUG to False here since the template tag wouldn't work otherwise
  436. @override_settings(**dict(TEST_SETTINGS,
  437. STATICFILES_STORAGE='regressiontests.staticfiles_tests.storage.SimpleCachedStaticFilesStorage',
  438. DEBUG=False,
  439. ))
  440. class TestCollectionSimpleCachedStorage(BaseCollectionTestCase,
  441. BaseStaticFilesTestCase, TestCase):
  442. """
  443. Tests for the Cache busting storage
  444. """
  445. def cached_file_path(self, path):
  446. fullpath = self.render_template(self.static_template_snippet(path))
  447. return fullpath.replace(settings.STATIC_URL, '')
  448. def test_template_tag_return(self):
  449. """
  450. Test the CachedStaticFilesStorage backend.
  451. """
  452. self.assertStaticRaises(ValueError,
  453. "does/not/exist.png",
  454. "/static/does/not/exist.png")
  455. self.assertStaticRenders("test/file.txt",
  456. "/static/test/file.deploy12345.txt")
  457. self.assertStaticRenders("cached/styles.css",
  458. "/static/cached/styles.deploy12345.css")
  459. self.assertStaticRenders("path/",
  460. "/static/path/")
  461. self.assertStaticRenders("path/?query",
  462. "/static/path/?query")
  463. def test_template_tag_simple_content(self):
  464. relpath = self.cached_file_path("cached/styles.css")
  465. self.assertEqual(relpath, "cached/styles.deploy12345.css")
  466. with storage.staticfiles_storage.open(relpath) as relfile:
  467. content = relfile.read()
  468. self.assertNotIn("cached/other.css", content)
  469. self.assertIn("other.deploy12345.css", content)
  470. if sys.platform != 'win32':
  471. class TestCollectionLinks(CollectionTestCase, TestDefaults):
  472. """
  473. Test ``--link`` option for ``collectstatic`` management command.
  474. Note that by inheriting ``TestDefaults`` we repeat all
  475. the standard file resolving tests here, to make sure using
  476. ``--link`` does not change the file-selection semantics.
  477. """
  478. def run_collectstatic(self):
  479. super(TestCollectionLinks, self).run_collectstatic(link=True)
  480. def test_links_created(self):
  481. """
  482. With ``--link``, symbolic links are created.
  483. """
  484. self.assertTrue(os.path.islink(os.path.join(settings.STATIC_ROOT, 'test.txt')))
  485. class TestServeStatic(StaticFilesTestCase):
  486. """
  487. Test static asset serving view.
  488. """
  489. urls = 'regressiontests.staticfiles_tests.urls.default'
  490. def _response(self, filepath):
  491. return self.client.get(
  492. posixpath.join(settings.STATIC_URL, filepath))
  493. def assertFileContains(self, filepath, text):
  494. self.assertContains(self._response(filepath), text)
  495. def assertFileNotFound(self, filepath):
  496. self.assertEqual(self._response(filepath).status_code, 404)
  497. class TestServeDisabled(TestServeStatic):
  498. """
  499. Test serving static files disabled when DEBUG is False.
  500. """
  501. def setUp(self):
  502. super(TestServeDisabled, self).setUp()
  503. settings.DEBUG = False
  504. def test_disabled_serving(self):
  505. self.assertRaisesRegexp(ImproperlyConfigured, 'The staticfiles view '
  506. 'can only be used in debug mode ', self._response, 'test.txt')
  507. class TestServeStaticWithDefaultURL(TestServeStatic, TestDefaults):
  508. """
  509. Test static asset serving view with manually configured URLconf.
  510. """
  511. pass
  512. class TestServeStaticWithURLHelper(TestServeStatic, TestDefaults):
  513. """
  514. Test static asset serving view with staticfiles_urlpatterns helper.
  515. """
  516. urls = 'regressiontests.staticfiles_tests.urls.helper'
  517. class TestServeAdminMedia(TestServeStatic):
  518. """
  519. Test serving media from django.contrib.admin.
  520. """
  521. def _response(self, filepath):
  522. return self.client.get(
  523. posixpath.join(settings.STATIC_URL, 'admin/', filepath))
  524. def test_serve_admin_media(self):
  525. self.assertFileContains('css/base.css', 'body')
  526. class FinderTestCase(object):
  527. """
  528. Base finder test mixin.
  529. On Windows, sometimes the case of the path we ask the finders for and the
  530. path(s) they find can differ. Compare them using os.path.normcase() to
  531. avoid false negatives.
  532. """
  533. def test_find_first(self):
  534. src, dst = self.find_first
  535. found = self.finder.find(src)
  536. self.assertEqual(os.path.normcase(found), os.path.normcase(dst))
  537. def test_find_all(self):
  538. src, dst = self.find_all
  539. found = self.finder.find(src, all=True)
  540. found = [os.path.normcase(f) for f in found]
  541. dst = [os.path.normcase(d) for d in dst]
  542. self.assertEqual(found, dst)
  543. class TestFileSystemFinder(StaticFilesTestCase, FinderTestCase):
  544. """
  545. Test FileSystemFinder.
  546. """
  547. def setUp(self):
  548. super(TestFileSystemFinder, self).setUp()
  549. self.finder = finders.FileSystemFinder()
  550. test_file_path = os.path.join(TEST_ROOT, 'project', 'documents', 'test', 'file.txt')
  551. self.find_first = (os.path.join('test', 'file.txt'), test_file_path)
  552. self.find_all = (os.path.join('test', 'file.txt'), [test_file_path])
  553. class TestAppDirectoriesFinder(StaticFilesTestCase, FinderTestCase):
  554. """
  555. Test AppDirectoriesFinder.
  556. """
  557. def setUp(self):
  558. super(TestAppDirectoriesFinder, self).setUp()
  559. self.finder = finders.AppDirectoriesFinder()
  560. test_file_path = os.path.join(TEST_ROOT, 'apps', 'test', 'static', 'test', 'file1.txt')
  561. self.find_first = (os.path.join('test', 'file1.txt'), test_file_path)
  562. self.find_all = (os.path.join('test', 'file1.txt'), [test_file_path])
  563. class TestDefaultStorageFinder(StaticFilesTestCase, FinderTestCase):
  564. """
  565. Test DefaultStorageFinder.
  566. """
  567. def setUp(self):
  568. super(TestDefaultStorageFinder, self).setUp()
  569. self.finder = finders.DefaultStorageFinder(
  570. storage=storage.StaticFilesStorage(location=settings.MEDIA_ROOT))
  571. test_file_path = os.path.join(settings.MEDIA_ROOT, 'media-file.txt')
  572. self.find_first = ('media-file.txt', test_file_path)
  573. self.find_all = ('media-file.txt', [test_file_path])
  574. class TestMiscFinder(TestCase):
  575. """
  576. A few misc finder tests.
  577. """
  578. def setUp(self):
  579. default_storage._wrapped = empty
  580. def test_get_finder(self):
  581. self.assertIsInstance(finders.get_finder(
  582. 'django.contrib.staticfiles.finders.FileSystemFinder'),
  583. finders.FileSystemFinder)
  584. def test_get_finder_bad_classname(self):
  585. self.assertRaises(ImproperlyConfigured, finders.get_finder,
  586. 'django.contrib.staticfiles.finders.FooBarFinder')
  587. def test_get_finder_bad_module(self):
  588. self.assertRaises(ImproperlyConfigured,
  589. finders.get_finder, 'foo.bar.FooBarFinder')
  590. @override_settings(STATICFILES_DIRS='a string')
  591. def test_non_tuple_raises_exception(self):
  592. """
  593. We can't determine if STATICFILES_DIRS is set correctly just by
  594. looking at the type, but we can determine if it's definitely wrong.
  595. """
  596. self.assertRaises(ImproperlyConfigured, finders.FileSystemFinder)
  597. @override_settings(MEDIA_ROOT='')
  598. def test_location_empty(self):
  599. self.assertRaises(ImproperlyConfigured, finders.DefaultStorageFinder)
  600. class TestTemplateTag(StaticFilesTestCase):
  601. def test_template_tag(self):
  602. self.assertStaticRenders("does/not/exist.png",
  603. "/static/does/not/exist.png")
  604. self.assertStaticRenders("testfile.txt", "/static/testfile.txt")