test_loaders.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. # -*- coding: utf-8 -*-
  2. from __future__ import unicode_literals
  3. import os.path
  4. import sys
  5. import types
  6. import unittest
  7. from contextlib import contextmanager
  8. from django.template import Context, TemplateDoesNotExist
  9. from django.template.engine import Engine
  10. from django.test import SimpleTestCase, override_settings
  11. from django.utils import six
  12. from .utils import TEMPLATE_DIR
  13. try:
  14. import pkg_resources
  15. except ImportError:
  16. pkg_resources = None
  17. class CachedLoaderTests(SimpleTestCase):
  18. def create_engine(self, **kwargs):
  19. return Engine(
  20. loaders=[
  21. ('django.template.loaders.cached.Loader', [
  22. 'django.template.loaders.filesystem.Loader',
  23. ]),
  24. ],
  25. )
  26. def test_templatedir_caching(self):
  27. """
  28. #13573 -- Template directories should be part of the cache key.
  29. """
  30. engine = self.create_engine()
  31. # Retrieve a template specifying a template directory to check
  32. t1, name = engine.find_template('test.html', (os.path.join(TEMPLATE_DIR, 'first'),))
  33. # Now retrieve the same template name, but from a different directory
  34. t2, name = engine.find_template('test.html', (os.path.join(TEMPLATE_DIR, 'second'),))
  35. # The two templates should not have the same content
  36. self.assertNotEqual(t1.render(Context({})), t2.render(Context({})))
  37. def test_missing_template_is_cached(self):
  38. """
  39. #19949 -- TemplateDoesNotExist exceptions should be cached.
  40. """
  41. engine = self.create_engine()
  42. loader = engine.template_loaders[0]
  43. self.assertFalse('missing.html' in loader.template_cache)
  44. with self.assertRaises(TemplateDoesNotExist):
  45. loader.load_template("missing.html")
  46. self.assertEqual(
  47. loader.template_cache["missing.html"],
  48. TemplateDoesNotExist,
  49. "Cached loader failed to cache the TemplateDoesNotExist exception",
  50. )
  51. def test_debug_nodelist_name(self):
  52. template_name = 'index.html'
  53. engine = Engine(dirs=[TEMPLATE_DIR], debug=True)
  54. template = engine.get_template(template_name)
  55. name = template.nodelist[0].source[0].name
  56. self.assertTrue(
  57. name.endswith(template_name),
  58. 'Template loaded through cached loader has incorrect name for debug page: %s' % template_name,
  59. )
  60. template = engine.get_template(template_name)
  61. name = template.nodelist[0].source[0].name
  62. self.assertTrue(
  63. name.endswith(template_name),
  64. 'Cached template loaded through cached loader has incorrect name for debug page: %s' % template_name,
  65. )
  66. @unittest.skipUnless(pkg_resources, 'setuptools is not installed')
  67. class EggLoaderTests(SimpleTestCase):
  68. @contextmanager
  69. def create_egg(self, name, resources):
  70. """
  71. Creates a mock egg with a list of resources.
  72. name: The name of the module.
  73. resources: A dictionary of template names mapped to file-like objects.
  74. """
  75. if six.PY2:
  76. name = name.encode('utf-8')
  77. class MockLoader(object):
  78. pass
  79. class MockProvider(pkg_resources.NullProvider):
  80. def __init__(self, module):
  81. pkg_resources.NullProvider.__init__(self, module)
  82. self.module = module
  83. def _has(self, path):
  84. return path in self.module._resources
  85. def _isdir(self, path):
  86. return False
  87. def get_resource_stream(self, manager, resource_name):
  88. return self.module._resources[resource_name]
  89. def _get(self, path):
  90. return self.module._resources[path].read()
  91. def _fn(self, base, resource_name):
  92. return os.path.normcase(resource_name)
  93. egg = types.ModuleType(name)
  94. egg.__loader__ = MockLoader()
  95. egg.__path__ = ['/some/bogus/path/']
  96. egg.__file__ = '/some/bogus/path/__init__.pyc'
  97. egg._resources = resources
  98. sys.modules[name] = egg
  99. pkg_resources._provider_factories[MockLoader] = MockProvider
  100. try:
  101. yield
  102. finally:
  103. del sys.modules[name]
  104. del pkg_resources._provider_factories[MockLoader]
  105. def setUp(self):
  106. engine = Engine(loaders=[
  107. 'django.template.loaders.eggs.Loader',
  108. ])
  109. self.loader = engine.template_loaders[0]
  110. def test_existing(self):
  111. templates = {
  112. os.path.normcase('templates/y.html'): six.StringIO("y"),
  113. }
  114. with self.create_egg('egg', templates):
  115. with override_settings(INSTALLED_APPS=['egg']):
  116. contents, template_name = self.loader.load_template_source("y.html")
  117. self.assertEqual(contents, "y")
  118. self.assertEqual(template_name, "egg:egg:templates/y.html")
  119. def test_non_existing(self):
  120. """
  121. Template loading fails if the template is not in the egg.
  122. """
  123. with self.create_egg('egg', {}):
  124. with override_settings(INSTALLED_APPS=['egg']):
  125. with self.assertRaises(TemplateDoesNotExist):
  126. self.loader.load_template_source("not-existing.html")
  127. def test_not_installed(self):
  128. """
  129. Template loading fails if the egg is not in INSTALLED_APPS.
  130. """
  131. templates = {
  132. os.path.normcase('templates/y.html'): six.StringIO("y"),
  133. }
  134. with self.create_egg('egg', templates):
  135. with self.assertRaises(TemplateDoesNotExist):
  136. self.loader.load_template_source("y.html")
  137. class FileSystemLoaderTests(SimpleTestCase):
  138. def setUp(self):
  139. self.engine = Engine()
  140. @contextmanager
  141. def source_checker(self, dirs):
  142. loader = self.engine.template_loaders[0]
  143. def check_sources(path, expected_sources):
  144. expected_sources = [os.path.abspath(s) for s in expected_sources]
  145. self.assertEqual(
  146. list(loader.get_template_sources(path)),
  147. expected_sources,
  148. )
  149. original_dirs = self.engine.dirs
  150. self.engine.dirs = dirs
  151. try:
  152. yield check_sources
  153. finally:
  154. self.engine.dirs = original_dirs
  155. def test_directory_security(self):
  156. with self.source_checker(['/dir1', '/dir2']) as check_sources:
  157. check_sources('index.html', ['/dir1/index.html', '/dir2/index.html'])
  158. check_sources('/etc/passwd', [])
  159. check_sources('etc/passwd', ['/dir1/etc/passwd', '/dir2/etc/passwd'])
  160. check_sources('../etc/passwd', [])
  161. check_sources('../../../etc/passwd', [])
  162. check_sources('/dir1/index.html', ['/dir1/index.html'])
  163. check_sources('../dir2/index.html', ['/dir2/index.html'])
  164. check_sources('/dir1blah', [])
  165. check_sources('../dir1blah', [])
  166. def test_unicode_template_name(self):
  167. with self.source_checker(['/dir1', '/dir2']) as check_sources:
  168. # UTF-8 bytestrings are permitted.
  169. check_sources(b'\xc3\x85ngstr\xc3\xb6m', ['/dir1/Ångström', '/dir2/Ångström'])
  170. # Unicode strings are permitted.
  171. check_sources('Ångström', ['/dir1/Ångström', '/dir2/Ångström'])
  172. def test_utf8_bytestring(self):
  173. """
  174. Invalid UTF-8 encoding in bytestrings should raise a useful error
  175. """
  176. engine = Engine()
  177. loader = engine.template_loaders[0]
  178. with self.assertRaises(UnicodeDecodeError):
  179. list(loader.get_template_sources(b'\xc3\xc3', ['/dir1']))
  180. def test_unicode_dir_name(self):
  181. with self.source_checker([b'/Stra\xc3\x9fe']) as check_sources:
  182. check_sources('Ångström', ['/Straße/Ångström'])
  183. check_sources(b'\xc3\x85ngstr\xc3\xb6m', ['/Straße/Ångström'])
  184. @unittest.skipUnless(
  185. os.path.normcase('/TEST') == os.path.normpath('/test'),
  186. "This test only runs on case-sensitive file systems.",
  187. )
  188. def test_case_sensitivity(self):
  189. with self.source_checker(['/dir1', '/DIR2']) as check_sources:
  190. check_sources('index.html', ['/dir1/index.html', '/DIR2/index.html'])
  191. check_sources('/DIR1/index.HTML', ['/DIR1/index.HTML'])
  192. class AppDirectoriesLoaderTest(SimpleTestCase):
  193. def setUp(self):
  194. self.engine = Engine(
  195. loaders=['django.template.loaders.app_directories.Loader'],
  196. )
  197. @override_settings(INSTALLED_APPS=['template_tests'])
  198. def test_load_template(self):
  199. self.engine.get_template('index.html')
  200. @override_settings(INSTALLED_APPS=[])
  201. def test_not_installed(self):
  202. with self.assertRaises(TemplateDoesNotExist):
  203. self.engine.get_template('index.html')