PageRenderTime 123ms CodeModel.GetById 110ms app.highlight 9ms RepoModel.GetById 1ms app.codeStats 0ms

/tests/regressiontests/templates/loaders.py

https://code.google.com/p/mango-py/
Python | 177 lines | 128 code | 34 blank | 15 comment | 3 complexity | 4e13d619c8f76186dcb49d020a2f8530 MD5 | raw file
  1"""
  2Test cases for the template loaders
  3
  4Note: This test requires setuptools!
  5"""
  6
  7from django.conf import settings
  8
  9if __name__ == '__main__':
 10    settings.configure()
 11
 12import sys
 13import pkg_resources
 14import imp
 15import StringIO
 16import os.path
 17import warnings
 18
 19from django.template import TemplateDoesNotExist, Context
 20from django.template.loaders.eggs import load_template_source as lts_egg
 21from django.template.loaders.eggs import Loader as EggLoader
 22from django.template import loader
 23from django.test.utils import get_warnings_state, restore_warnings_state
 24from django.utils import unittest
 25
 26
 27# Mock classes and objects for pkg_resources functions.
 28class MockProvider(pkg_resources.NullProvider):
 29    def __init__(self, module):
 30        pkg_resources.NullProvider.__init__(self, module)
 31        self.module = module
 32
 33    def _has(self, path):
 34        return path in self.module._resources
 35
 36    def _isdir(self,path):
 37        return False
 38
 39    def get_resource_stream(self, manager, resource_name):
 40        return self.module._resources[resource_name]
 41
 42    def _get(self, path):
 43        return self.module._resources[path].read()
 44
 45class MockLoader(object):
 46    pass
 47
 48def create_egg(name, resources):
 49    """
 50    Creates a mock egg with a list of resources.
 51
 52    name: The name of the module.
 53    resources: A dictionary of resources. Keys are the names and values the data.
 54    """
 55    egg = imp.new_module(name)
 56    egg.__loader__ = MockLoader()
 57    egg._resources = resources
 58    sys.modules[name] = egg
 59
 60class DeprecatedEggLoaderTest(unittest.TestCase):
 61    "Test the deprecated load_template_source interface to the egg loader"
 62    def setUp(self):
 63        pkg_resources._provider_factories[MockLoader] = MockProvider
 64
 65        self.empty_egg = create_egg("egg_empty", {})
 66        self.egg_1 = create_egg("egg_1", {
 67            os.path.normcase('templates/y.html') : StringIO.StringIO("y"),
 68            os.path.normcase('templates/x.txt') : StringIO.StringIO("x"),
 69        })
 70        self._old_installed_apps = settings.INSTALLED_APPS
 71        settings.INSTALLED_APPS = []
 72        self._warnings_state = get_warnings_state()
 73        warnings.filterwarnings("ignore", category=DeprecationWarning,
 74                                module='django.template.loaders.eggs')
 75
 76    def tearDown(self):
 77        settings.INSTALLED_APPS = self._old_installed_apps
 78        restore_warnings_state(self._warnings_state)
 79
 80    def test_existing(self):
 81        "A template can be loaded from an egg"
 82        settings.INSTALLED_APPS = ['egg_1']
 83        contents, template_name = lts_egg("y.html")
 84        self.assertEqual(contents, "y")
 85        self.assertEqual(template_name, "egg:egg_1:templates/y.html")
 86
 87
 88class EggLoaderTest(unittest.TestCase):
 89    def setUp(self):
 90        pkg_resources._provider_factories[MockLoader] = MockProvider
 91
 92        self.empty_egg = create_egg("egg_empty", {})
 93        self.egg_1 = create_egg("egg_1", {
 94            os.path.normcase('templates/y.html') : StringIO.StringIO("y"),
 95            os.path.normcase('templates/x.txt') : StringIO.StringIO("x"),
 96        })
 97        self._old_installed_apps = settings.INSTALLED_APPS
 98        settings.INSTALLED_APPS = []
 99
100    def tearDown(self):
101        settings.INSTALLED_APPS = self._old_installed_apps
102
103    def test_empty(self):
104        "Loading any template on an empty egg should fail"
105        settings.INSTALLED_APPS = ['egg_empty']
106        egg_loader = EggLoader()
107        self.assertRaises(TemplateDoesNotExist, egg_loader.load_template_source, "not-existing.html")
108
109    def test_non_existing(self):
110        "Template loading fails if the template is not in the egg"
111        settings.INSTALLED_APPS = ['egg_1']
112        egg_loader = EggLoader()
113        self.assertRaises(TemplateDoesNotExist, egg_loader.load_template_source, "not-existing.html")
114
115    def test_existing(self):
116        "A template can be loaded from an egg"
117        settings.INSTALLED_APPS = ['egg_1']
118        egg_loader = EggLoader()
119        contents, template_name = egg_loader.load_template_source("y.html")
120        self.assertEqual(contents, "y")
121        self.assertEqual(template_name, "egg:egg_1:templates/y.html")
122
123    def test_not_installed(self):
124        "Loading an existent template from an egg not included in INSTALLED_APPS should fail"
125        settings.INSTALLED_APPS = []
126        egg_loader = EggLoader()
127        self.assertRaises(TemplateDoesNotExist, egg_loader.load_template_source, "y.html")
128
129class CachedLoader(unittest.TestCase):
130    def setUp(self):
131        self.old_TEMPLATE_LOADERS = settings.TEMPLATE_LOADERS
132        settings.TEMPLATE_LOADERS = (
133            ('django.template.loaders.cached.Loader', (
134                    'django.template.loaders.filesystem.Loader',
135                )
136            ),
137        )
138    def tearDown(self):
139        settings.TEMPLATE_LOADERS = self.old_TEMPLATE_LOADERS
140
141    def test_templatedir_caching(self):
142        "Check that the template directories form part of the template cache key. Refs #13573"
143        # Retrive a template specifying a template directory to check
144        t1, name = loader.find_template('test.html', (os.path.join(os.path.dirname(__file__), 'templates', 'first'),))
145        # Now retrieve the same template name, but from a different directory
146        t2, name = loader.find_template('test.html', (os.path.join(os.path.dirname(__file__), 'templates', 'second'),))
147
148        # The two templates should not have the same content
149        self.assertNotEqual(t1.render(Context({})), t2.render(Context({})))
150
151class RenderToStringTest(unittest.TestCase):
152
153    def setUp(self):
154        self._old_TEMPLATE_DIRS = settings.TEMPLATE_DIRS
155        settings.TEMPLATE_DIRS = (
156            os.path.join(os.path.dirname(__file__), 'templates'),
157        )
158
159    def tearDown(self):
160        settings.TEMPLATE_DIRS = self._old_TEMPLATE_DIRS
161
162    def test_basic(self):
163        self.assertEqual(loader.render_to_string('test_context.html'), 'obj:')
164
165    def test_basic_context(self):
166        self.assertEqual(loader.render_to_string('test_context.html',
167                                                 {'obj': 'test'}), 'obj:test')
168
169    def test_existing_context_kept_clean(self):
170        context = Context({'obj': 'before'})
171        output = loader.render_to_string('test_context.html', {'obj': 'after'},
172                                         context_instance=context)
173        self.assertEqual(output, 'obj:after')
174        self.assertEqual(context['obj'], 'before')
175
176if __name__ == "__main__":
177    unittest.main()