test_loaders.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. """
  2. Test cases for the template loaders
  3. Note: This test requires setuptools!
  4. """
  5. from django.conf import settings
  6. if __name__ == '__main__':
  7. settings.configure()
  8. import imp
  9. import os.path
  10. import sys
  11. import unittest
  12. try:
  13. import pkg_resources
  14. except ImportError:
  15. pkg_resources = None
  16. from django.template import TemplateDoesNotExist, Context
  17. from django.template.loaders.eggs import Loader as EggLoader
  18. from django.template import loader
  19. from django.utils import six
  20. from django.utils._os import upath
  21. from django.utils.six import StringIO
  22. # Mock classes and objects for pkg_resources functions.
  23. class MockLoader(object):
  24. pass
  25. def create_egg(name, resources):
  26. """
  27. Creates a mock egg with a list of resources.
  28. name: The name of the module.
  29. resources: A dictionary of resources. Keys are the names and values the data.
  30. """
  31. egg = imp.new_module(name)
  32. egg.__loader__ = MockLoader()
  33. egg._resources = resources
  34. sys.modules[name] = egg
  35. @unittest.skipUnless(pkg_resources, 'setuptools is not installed')
  36. class EggLoaderTest(unittest.TestCase):
  37. def setUp(self):
  38. # Defined here b/c at module scope we may not have pkg_resources
  39. class MockProvider(pkg_resources.NullProvider):
  40. def __init__(self, module):
  41. pkg_resources.NullProvider.__init__(self, module)
  42. self.module = module
  43. def _has(self, path):
  44. return path in self.module._resources
  45. def _isdir(self, path):
  46. return False
  47. def get_resource_stream(self, manager, resource_name):
  48. return self.module._resources[resource_name]
  49. def _get(self, path):
  50. return self.module._resources[path].read()
  51. pkg_resources._provider_factories[MockLoader] = MockProvider
  52. self.empty_egg = create_egg("egg_empty", {})
  53. self.egg_1 = create_egg("egg_1", {
  54. os.path.normcase('templates/y.html'): StringIO("y"),
  55. os.path.normcase('templates/x.txt'): StringIO("x"),
  56. })
  57. self._old_installed_apps = settings.INSTALLED_APPS
  58. settings.INSTALLED_APPS = []
  59. def tearDown(self):
  60. settings.INSTALLED_APPS = self._old_installed_apps
  61. def test_empty(self):
  62. "Loading any template on an empty egg should fail"
  63. settings.INSTALLED_APPS = ['egg_empty']
  64. egg_loader = EggLoader()
  65. self.assertRaises(TemplateDoesNotExist, egg_loader.load_template_source, "not-existing.html")
  66. def test_non_existing(self):
  67. "Template loading fails if the template is not in the egg"
  68. settings.INSTALLED_APPS = ['egg_1']
  69. egg_loader = EggLoader()
  70. self.assertRaises(TemplateDoesNotExist, egg_loader.load_template_source, "not-existing.html")
  71. def test_existing(self):
  72. "A template can be loaded from an egg"
  73. settings.INSTALLED_APPS = ['egg_1']
  74. egg_loader = EggLoader()
  75. contents, template_name = egg_loader.load_template_source("y.html")
  76. self.assertEqual(contents, "y")
  77. self.assertEqual(template_name, "egg:egg_1:templates/y.html")
  78. def test_not_installed(self):
  79. "Loading an existent template from an egg not included in INSTALLED_APPS should fail"
  80. settings.INSTALLED_APPS = []
  81. egg_loader = EggLoader()
  82. self.assertRaises(TemplateDoesNotExist, egg_loader.load_template_source, "y.html")
  83. class CachedLoader(unittest.TestCase):
  84. def setUp(self):
  85. self.old_TEMPLATE_LOADERS = settings.TEMPLATE_LOADERS
  86. settings.TEMPLATE_LOADERS = (
  87. ('django.template.loaders.cached.Loader', (
  88. 'django.template.loaders.filesystem.Loader',
  89. )
  90. ),
  91. )
  92. def tearDown(self):
  93. settings.TEMPLATE_LOADERS = self.old_TEMPLATE_LOADERS
  94. def test_templatedir_caching(self):
  95. "Check that the template directories form part of the template cache key. Refs #13573"
  96. # Retrive a template specifying a template directory to check
  97. t1, name = loader.find_template('test.html', (os.path.join(os.path.dirname(upath(__file__)), 'templates', 'first'),))
  98. # Now retrieve the same template name, but from a different directory
  99. t2, name = loader.find_template('test.html', (os.path.join(os.path.dirname(upath(__file__)), 'templates', 'second'),))
  100. # The two templates should not have the same content
  101. self.assertNotEqual(t1.render(Context({})), t2.render(Context({})))
  102. def test_missing_template_is_cached(self):
  103. "#19949 -- Check that the missing template is cached."
  104. template_loader = loader.find_template_loader(settings.TEMPLATE_LOADERS[0])
  105. # Empty cache, which may be filled from previous tests.
  106. template_loader.reset()
  107. # Check that 'missing.html' isn't already in cache before 'missing.html' is loaded
  108. self.assertRaises(KeyError, lambda: template_loader.template_cache["missing.html"])
  109. # Try to load it, it should fail
  110. self.assertRaises(TemplateDoesNotExist, template_loader.load_template, "missing.html")
  111. # Verify that the fact that the missing template, which hasn't been found, has actually
  112. # been cached:
  113. self.assertEqual(template_loader.template_cache.get("missing.html"),
  114. TemplateDoesNotExist,
  115. "Cached template loader doesn't cache file lookup misses. It should.")
  116. class RenderToStringTest(unittest.TestCase):
  117. def setUp(self):
  118. self._old_TEMPLATE_DIRS = settings.TEMPLATE_DIRS
  119. settings.TEMPLATE_DIRS = (
  120. os.path.join(os.path.dirname(upath(__file__)), 'templates'),
  121. )
  122. def tearDown(self):
  123. settings.TEMPLATE_DIRS = self._old_TEMPLATE_DIRS
  124. def test_basic(self):
  125. self.assertEqual(loader.render_to_string('test_context.html'), 'obj:')
  126. def test_basic_context(self):
  127. self.assertEqual(loader.render_to_string('test_context.html',
  128. {'obj': 'test'}), 'obj:test')
  129. def test_existing_context_kept_clean(self):
  130. context = Context({'obj': 'before'})
  131. output = loader.render_to_string('test_context.html', {'obj': 'after'},
  132. context_instance=context)
  133. self.assertEqual(output, 'obj:after')
  134. self.assertEqual(context['obj'], 'before')
  135. def test_empty_list(self):
  136. six.assertRaisesRegex(self, TemplateDoesNotExist,
  137. 'No template names provided$',
  138. loader.render_to_string, [])
  139. def test_select_templates_from_empty_list(self):
  140. six.assertRaisesRegex(self, TemplateDoesNotExist,
  141. 'No template names provided$',
  142. loader.select_template, [])