tests.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  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.conf import settings
  10. from django.contrib.staticfiles import finders, storage
  11. from django.core.exceptions import ImproperlyConfigured
  12. from django.core.files.storage import default_storage
  13. from django.core.management import call_command
  14. from django.test import TestCase
  15. from django.utils.encoding import smart_unicode
  16. from django.utils._os import rmtree_errorhandler
  17. TEST_ROOT = os.path.normcase(os.path.dirname(__file__))
  18. class StaticFilesTestCase(TestCase):
  19. """
  20. Test case with a couple utility assertions.
  21. """
  22. def setUp(self):
  23. self.old_static_url = settings.STATIC_URL
  24. self.old_static_root = settings.STATIC_ROOT
  25. self.old_staticfiles_dirs = settings.STATICFILES_DIRS
  26. self.old_staticfiles_finders = settings.STATICFILES_FINDERS
  27. self.old_media_root = settings.MEDIA_ROOT
  28. self.old_media_url = settings.MEDIA_URL
  29. self.old_admin_media_prefix = settings.ADMIN_MEDIA_PREFIX
  30. self.old_debug = settings.DEBUG
  31. self.old_installed_apps = settings.INSTALLED_APPS
  32. site_media = os.path.join(TEST_ROOT, 'project', 'site_media')
  33. settings.DEBUG = True
  34. settings.MEDIA_ROOT = os.path.join(site_media, 'media')
  35. settings.MEDIA_URL = '/media/'
  36. settings.STATIC_ROOT = os.path.join(site_media, 'static')
  37. settings.STATIC_URL = '/static/'
  38. settings.ADMIN_MEDIA_PREFIX = '/static/admin/'
  39. settings.STATICFILES_DIRS = (
  40. os.path.join(TEST_ROOT, 'project', 'documents'),
  41. )
  42. settings.STATICFILES_FINDERS = (
  43. 'django.contrib.staticfiles.finders.FileSystemFinder',
  44. 'django.contrib.staticfiles.finders.AppDirectoriesFinder',
  45. 'django.contrib.staticfiles.finders.DefaultStorageFinder',
  46. )
  47. settings.INSTALLED_APPS = [
  48. 'django.contrib.admin',
  49. 'django.contrib.staticfiles',
  50. 'regressiontests.staticfiles_tests',
  51. 'regressiontests.staticfiles_tests.apps.test',
  52. 'regressiontests.staticfiles_tests.apps.no_label',
  53. ]
  54. # Clear the cached default_storage out, this is because when it first
  55. # gets accessed (by some other test), it evaluates settings.MEDIA_ROOT,
  56. # since we're planning on changing that we need to clear out the cache.
  57. default_storage._wrapped = None
  58. # To make sure SVN doesn't hangs itself with the non-ASCII characters
  59. # during checkout, we actually create one file dynamically.
  60. self._nonascii_filepath = os.path.join(
  61. TEST_ROOT, 'apps', 'test', 'static', 'test', u'fişier.txt')
  62. f = codecs.open(self._nonascii_filepath, 'w', 'utf-8')
  63. try:
  64. f.write(u"fişier in the app dir")
  65. finally:
  66. f.close()
  67. def tearDown(self):
  68. settings.DEBUG = self.old_debug
  69. settings.MEDIA_ROOT = self.old_media_root
  70. settings.MEDIA_URL = self.old_media_url
  71. settings.ADMIN_MEDIA_PREFIX = self.old_admin_media_prefix
  72. settings.STATIC_ROOT = self.old_static_root
  73. settings.STATIC_URL = self.old_static_url
  74. settings.STATICFILES_DIRS = self.old_staticfiles_dirs
  75. settings.STATICFILES_FINDERS = self.old_staticfiles_finders
  76. settings.INSTALLED_APPS = self.old_installed_apps
  77. if os.path.exists(self._nonascii_filepath):
  78. os.unlink(self._nonascii_filepath)
  79. def assertFileContains(self, filepath, text):
  80. self.assertTrue(text in self._get_file(smart_unicode(filepath)),
  81. u"'%s' not in '%s'" % (text, filepath))
  82. def assertFileNotFound(self, filepath):
  83. self.assertRaises(IOError, self._get_file, filepath)
  84. class BuildStaticTestCase(StaticFilesTestCase):
  85. """
  86. Tests shared by all file-resolving features (collectstatic,
  87. findstatic, and static serve view).
  88. This relies on the asserts defined in UtilityAssertsTestCase, but
  89. is separated because some test cases need those asserts without
  90. all these tests.
  91. """
  92. def setUp(self):
  93. super(BuildStaticTestCase, self).setUp()
  94. self.old_root = settings.STATIC_ROOT
  95. settings.STATIC_ROOT = tempfile.mkdtemp()
  96. self.run_collectstatic()
  97. def tearDown(self):
  98. # Use our own error handler that can handle .svn dirs on Windows
  99. shutil.rmtree(settings.STATIC_ROOT, ignore_errors=True,
  100. onerror=rmtree_errorhandler)
  101. settings.STATIC_ROOT = self.old_root
  102. super(BuildStaticTestCase, self).tearDown()
  103. def run_collectstatic(self, **kwargs):
  104. call_command('collectstatic', interactive=False, verbosity='0',
  105. ignore_patterns=['*.ignoreme'], **kwargs)
  106. def _get_file(self, filepath):
  107. assert filepath, 'filepath is empty.'
  108. filepath = os.path.join(settings.STATIC_ROOT, filepath)
  109. f = codecs.open(filepath, "r", "utf-8")
  110. try:
  111. return f.read()
  112. finally:
  113. f.close()
  114. class TestDefaults(object):
  115. """
  116. A few standard test cases.
  117. """
  118. def test_staticfiles_dirs(self):
  119. """
  120. Can find a file in a STATICFILES_DIRS directory.
  121. """
  122. self.assertFileContains('test.txt', 'Can we find')
  123. def test_staticfiles_dirs_subdir(self):
  124. """
  125. Can find a file in a subdirectory of a STATICFILES_DIRS
  126. directory.
  127. """
  128. self.assertFileContains('subdir/test.txt', 'Can we find')
  129. def test_staticfiles_dirs_priority(self):
  130. """
  131. File in STATICFILES_DIRS has priority over file in app.
  132. """
  133. self.assertFileContains('test/file.txt', 'STATICFILES_DIRS')
  134. def test_app_files(self):
  135. """
  136. Can find a file in an app static/ directory.
  137. """
  138. self.assertFileContains('test/file1.txt', 'file1 in the app dir')
  139. def test_nonascii_filenames(self):
  140. """
  141. Can find a file with non-ASCII character in an app static/ directory.
  142. """
  143. self.assertFileContains(u'test/fişier.txt', u'fişier in the app dir')
  144. class TestFindStatic(BuildStaticTestCase, TestDefaults):
  145. """
  146. Test ``findstatic`` management command.
  147. """
  148. def _get_file(self, filepath):
  149. _stdout = sys.stdout
  150. sys.stdout = StringIO()
  151. try:
  152. call_command('findstatic', filepath, all=False, verbosity='0')
  153. sys.stdout.seek(0)
  154. lines = [l.strip() for l in sys.stdout.readlines()]
  155. contents = codecs.open(lines[1].strip(), "r", "utf-8").read()
  156. finally:
  157. sys.stdout = _stdout
  158. return contents
  159. def test_all_files(self):
  160. """
  161. Test that findstatic returns all candidate files if run without --first.
  162. """
  163. _stdout = sys.stdout
  164. sys.stdout = StringIO()
  165. try:
  166. call_command('findstatic', 'test/file.txt', verbosity='0')
  167. sys.stdout.seek(0)
  168. lines = [l.strip() for l in sys.stdout.readlines()]
  169. finally:
  170. sys.stdout = _stdout
  171. self.assertEqual(len(lines), 3) # three because there is also the "Found <file> here" line
  172. self.assertTrue('project' in lines[1])
  173. self.assertTrue('apps' in lines[2])
  174. class TestBuildStatic(BuildStaticTestCase, TestDefaults):
  175. """
  176. Test ``collectstatic`` management command.
  177. """
  178. def test_ignore(self):
  179. """
  180. Test that -i patterns are ignored.
  181. """
  182. self.assertFileNotFound('test/test.ignoreme')
  183. def test_common_ignore_patterns(self):
  184. """
  185. Common ignore patterns (*~, .*, CVS) are ignored.
  186. """
  187. self.assertFileNotFound('test/.hidden')
  188. self.assertFileNotFound('test/backup~')
  189. self.assertFileNotFound('test/CVS')
  190. class TestBuildStaticExcludeNoDefaultIgnore(BuildStaticTestCase, TestDefaults):
  191. """
  192. Test ``--exclude-dirs`` and ``--no-default-ignore`` options for
  193. ``collectstatic`` management command.
  194. """
  195. def run_collectstatic(self):
  196. super(TestBuildStaticExcludeNoDefaultIgnore, self).run_collectstatic(
  197. use_default_ignore_patterns=False)
  198. def test_no_common_ignore_patterns(self):
  199. """
  200. With --no-default-ignore, common ignore patterns (*~, .*, CVS)
  201. are not ignored.
  202. """
  203. self.assertFileContains('test/.hidden', 'should be ignored')
  204. self.assertFileContains('test/backup~', 'should be ignored')
  205. self.assertFileContains('test/CVS', 'should be ignored')
  206. class TestNoFilesCreated(object):
  207. def test_no_files_created(self):
  208. """
  209. Make sure no files were create in the destination directory.
  210. """
  211. self.assertEqual(os.listdir(settings.STATIC_ROOT), [])
  212. class TestBuildStaticDryRun(BuildStaticTestCase, TestNoFilesCreated):
  213. """
  214. Test ``--dry-run`` option for ``collectstatic`` management command.
  215. """
  216. def run_collectstatic(self):
  217. super(TestBuildStaticDryRun, self).run_collectstatic(dry_run=True)
  218. class TestBuildStaticNonLocalStorage(BuildStaticTestCase, TestNoFilesCreated):
  219. """
  220. Tests for #15035
  221. """
  222. def setUp(self):
  223. self.old_staticfiles_storage = settings.STATICFILES_STORAGE
  224. settings.STATICFILES_STORAGE = 'regressiontests.staticfiles_tests.storage.DummyStorage'
  225. super(TestBuildStaticNonLocalStorage, self).setUp()
  226. def tearDown(self):
  227. super(TestBuildStaticNonLocalStorage, self).tearDown()
  228. settings.STATICFILES_STORAGE = self.old_staticfiles_storage
  229. if sys.platform != 'win32':
  230. class TestBuildStaticLinks(BuildStaticTestCase, TestDefaults):
  231. """
  232. Test ``--link`` option for ``collectstatic`` management command.
  233. Note that by inheriting ``TestDefaults`` we repeat all
  234. the standard file resolving tests here, to make sure using
  235. ``--link`` does not change the file-selection semantics.
  236. """
  237. def run_collectstatic(self):
  238. super(TestBuildStaticLinks, self).run_collectstatic(link=True)
  239. def test_links_created(self):
  240. """
  241. With ``--link``, symbolic links are created.
  242. """
  243. self.assertTrue(os.path.islink(os.path.join(settings.STATIC_ROOT, 'test.txt')))
  244. class TestServeStatic(StaticFilesTestCase):
  245. """
  246. Test static asset serving view.
  247. """
  248. urls = 'regressiontests.staticfiles_tests.urls.default'
  249. def _response(self, filepath):
  250. return self.client.get(
  251. posixpath.join(settings.STATIC_URL, filepath))
  252. def assertFileContains(self, filepath, text):
  253. self.assertContains(self._response(filepath), text)
  254. def assertFileNotFound(self, filepath):
  255. self.assertEqual(self._response(filepath).status_code, 404)
  256. class TestServeDisabled(TestServeStatic):
  257. """
  258. Test serving static files disabled when DEBUG is False.
  259. """
  260. def setUp(self):
  261. super(TestServeDisabled, self).setUp()
  262. settings.DEBUG = False
  263. def test_disabled_serving(self):
  264. self.assertRaisesRegexp(ImproperlyConfigured, 'The staticfiles view '
  265. 'can only be used in debug mode ', self._response, 'test.txt')
  266. class TestServeStaticWithDefaultURL(TestServeStatic, TestDefaults):
  267. """
  268. Test static asset serving view with manually configured URLconf.
  269. """
  270. pass
  271. class TestServeStaticWithURLHelper(TestServeStatic, TestDefaults):
  272. """
  273. Test static asset serving view with staticfiles_urlpatterns helper.
  274. """
  275. urls = 'regressiontests.staticfiles_tests.urls.helper'
  276. class TestServeAdminMedia(TestServeStatic):
  277. """
  278. Test serving media from django.contrib.admin.
  279. """
  280. def _response(self, filepath):
  281. return self.client.get(
  282. posixpath.join(settings.ADMIN_MEDIA_PREFIX, filepath))
  283. def test_serve_admin_media(self):
  284. self.assertFileContains('css/base.css', 'body')
  285. class FinderTestCase(object):
  286. """
  287. Base finder test mixin
  288. """
  289. def test_find_first(self):
  290. src, dst = self.find_first
  291. self.assertEqual(self.finder.find(src), dst)
  292. def test_find_all(self):
  293. src, dst = self.find_all
  294. self.assertEqual(self.finder.find(src, all=True), dst)
  295. class TestFileSystemFinder(StaticFilesTestCase, FinderTestCase):
  296. """
  297. Test FileSystemFinder.
  298. """
  299. def setUp(self):
  300. super(TestFileSystemFinder, self).setUp()
  301. self.finder = finders.FileSystemFinder()
  302. test_file_path = os.path.join(TEST_ROOT, 'project', 'documents', 'test', 'file.txt')
  303. self.find_first = (os.path.join('test', 'file.txt'), test_file_path)
  304. self.find_all = (os.path.join('test', 'file.txt'), [test_file_path])
  305. class TestAppDirectoriesFinder(StaticFilesTestCase, FinderTestCase):
  306. """
  307. Test AppDirectoriesFinder.
  308. """
  309. def setUp(self):
  310. super(TestAppDirectoriesFinder, self).setUp()
  311. self.finder = finders.AppDirectoriesFinder()
  312. test_file_path = os.path.join(TEST_ROOT, 'apps', 'test', 'static', 'test', 'file1.txt')
  313. self.find_first = (os.path.join('test', 'file1.txt'), test_file_path)
  314. self.find_all = (os.path.join('test', 'file1.txt'), [test_file_path])
  315. class TestDefaultStorageFinder(StaticFilesTestCase, FinderTestCase):
  316. """
  317. Test DefaultStorageFinder.
  318. """
  319. def setUp(self):
  320. super(TestDefaultStorageFinder, self).setUp()
  321. self.finder = finders.DefaultStorageFinder(
  322. storage=storage.StaticFilesStorage(location=settings.MEDIA_ROOT))
  323. test_file_path = os.path.join(settings.MEDIA_ROOT, 'media-file.txt')
  324. self.find_first = ('media-file.txt', test_file_path)
  325. self.find_all = ('media-file.txt', [test_file_path])
  326. class TestMiscFinder(TestCase):
  327. """
  328. A few misc finder tests.
  329. """
  330. def test_get_finder(self):
  331. self.assertTrue(isinstance(finders.get_finder(
  332. 'django.contrib.staticfiles.finders.FileSystemFinder'),
  333. finders.FileSystemFinder))
  334. def test_get_finder_bad_classname(self):
  335. self.assertRaises(ImproperlyConfigured,
  336. finders.get_finder, 'django.contrib.staticfiles.finders.FooBarFinder')
  337. def test_get_finder_bad_module(self):
  338. self.assertRaises(ImproperlyConfigured,
  339. finders.get_finder, 'foo.bar.FooBarFinder')
  340. class TestStaticfilesDirsType(TestCase):
  341. """
  342. We can't determine if STATICFILES_DIRS is set correctly just by looking at
  343. the type, but we can determine if it's definitely wrong.
  344. """
  345. def setUp(self):
  346. self.old_settings_dir = settings.STATICFILES_DIRS
  347. settings.STATICFILES_DIRS = 'a string'
  348. def tearDown(self):
  349. settings.STATICFILES_DIRS = self.old_settings_dir
  350. def test_non_tuple_raises_exception(self):
  351. self.assertRaises(ImproperlyConfigured, finders.FileSystemFinder)