Ejemplo n.º 1
0
 def test_loaders_dirs_empty(self):
     """An empty dirs list in loaders overrides top level dirs."""
     engine = Engine(dirs=[TEMPLATE_DIR],
                     loaders=[('django.template.loaders.filesystem.Loader',
                               [])])
     with self.assertRaises(TemplateDoesNotExist):
         engine.get_template('index.html')
Ejemplo n.º 2
0
class AppDirectoriesLoaderTest(SimpleTestCase):
    def setUp(self):
        self.engine = Engine(
            loaders=['django.template.loaders.app_directories.Loader'], )

    @override_settings(INSTALLED_APPS=['template_tests'])
    def test_load_template(self):
        self.engine.get_template('index.html')

    @override_settings(INSTALLED_APPS=[])
    def test_not_installed(self):
        with self.assertRaises(TemplateDoesNotExist):
            self.engine.get_template('index.html')
Ejemplo n.º 3
0
class AppDirectoriesLoaderTest(SimpleTestCase):

    def setUp(self):
        self.engine = Engine(
            loaders=['django.template.loaders.app_directories.Loader'],
        )

    @override_settings(INSTALLED_APPS=['template_tests'])
    def test_load_template(self):
        self.engine.get_template('index.html')

    @override_settings(INSTALLED_APPS=[])
    def test_not_installed(self):
        with self.assertRaises(TemplateDoesNotExist):
            self.engine.get_template('index.html')
Ejemplo n.º 4
0
class PostOfficeTemplates(BaseEngine):
    """
    Customized Template Engine which keeps track on referenced images and stores them as attachments
    to be used in multipart email messages.
    """
    app_dirname = 'templates'

    def __init__(self, params):
        params = params.copy()
        options = params.pop('OPTIONS').copy()
        options.setdefault('autoescape', True)
        options.setdefault('debug', settings.DEBUG)
        options.setdefault('file_charset', settings.FILE_CHARSET)
        libraries = options.get('libraries', {})
        options['libraries'] = self.get_templatetag_libraries(libraries)
        super(PostOfficeTemplates, self).__init__(params)
        self.engine = Engine(self.dirs, self.app_dirs, **options)

    def from_string(self, template_code):
        return Template(self.engine.from_string(template_code), self)

    def get_template(self, template_name):
        try:
            template = self.engine.get_template(template_name)
            return Template(template, self)
        except TemplateDoesNotExist as exc:
            reraise(exc, self)

    def get_templatetag_libraries(self, custom_libraries):
        libraries = get_installed_libraries()
        libraries.update(custom_libraries)
        return libraries
Ejemplo n.º 5
0
class DjangoTemplates(BaseEngine):

    app_dirname = 'templates'

    def __init__(self, params):
        params = params.copy()
        options = params.pop('OPTIONS').copy()
        options.setdefault('autoescape', True)
        options.setdefault('debug', settings.DEBUG)
        options.setdefault('file_charset', settings.FILE_CHARSET)
        libraries = options.get('libraries', {})
        options['libraries'] = self.get_templatetag_libraries(libraries)
        super().__init__(params)
        self.engine = Engine(self.dirs, self.app_dirs, **options)

    def from_string(self, template_code):
        return Template(self.engine.from_string(template_code), self)

    def get_template(self, template_name):
        try:
            return Template(self.engine.get_template(template_name), self)
        except TemplateDoesNotExist as exc:
            reraise(exc, self)

    def get_templatetag_libraries(self, custom_libraries):
        """
        Return a collation of template tag libraries from installed
        applications and the supplied custom_libraries argument.
        """
        libraries = get_installed_libraries()
        libraries.update(custom_libraries)
        return libraries
Ejemplo n.º 6
0
class PostOfficeTemplates(BaseEngine):
    """
    Customized Template Engine which keeps track on referenced images and stores them as attachments
    to be used in multipart email messages.
    """
    app_dirname = 'templates'

    def __init__(self, params):
        params = params.copy()
        options = params.pop('OPTIONS').copy()
        options.setdefault('autoescape', True)
        options.setdefault('debug', settings.DEBUG)
        options.setdefault('file_charset', settings.FILE_CHARSET)
        libraries = options.get('libraries', {})
        options['libraries'] = self.get_templatetag_libraries(libraries)
        super(PostOfficeTemplates, self).__init__(params)
        self.engine = Engine(self.dirs, self.app_dirs, **options)

    def from_string(self, template_code):
        return Template(self.engine.from_string(template_code), self)

    def get_template(self, template_name):
        try:
            template = self.engine.get_template(template_name)
            return Template(template, self)
        except TemplateDoesNotExist as exc:
            reraise(exc, self)

    def get_templatetag_libraries(self, custom_libraries):
        libraries = get_installed_libraries()
        libraries.update(custom_libraries)
        return libraries
Ejemplo n.º 7
0
class DjangoTemplates(BaseEngine):

    app_dirname = 'templates'

    def __init__(self, params):
        params = params.copy()
        options = params.pop('OPTIONS').copy()
        options.setdefault('autoescape', True)
        options.setdefault('debug', settings.DEBUG)
        options.setdefault('file_charset', settings.FILE_CHARSET)
        libraries = options.get('libraries', {})
        options['libraries'] = self.get_templatetag_libraries(libraries)
        super(DjangoTemplates, self).__init__(params)
        self.engine = Engine(self.dirs, self.app_dirs, **options)

    def from_string(self, template_code):
        return Template(self.engine.from_string(template_code), self)

    def get_template(self, template_name):
        try:
            return Template(self.engine.get_template(template_name), self)
        except TemplateDoesNotExist as exc:
            reraise(exc, self)

    def get_templatetag_libraries(self, custom_libraries):
        """
        Return a collation of template tag libraries from installed
        applications and the supplied custom_libraries argument.
        """
        libraries = get_installed_libraries()
        libraries.update(custom_libraries)
        return libraries
Ejemplo n.º 8
0
    def test_debug_nodelist_name(self):
        template_name = 'index.html'
        engine = Engine(dirs=[TEMPLATE_DIR], debug=True)

        template = engine.get_template(template_name)
        name = template.nodelist[0].source[0].name
        self.assertTrue(
            name.endswith(template_name),
            'Template loaded through cached loader has incorrect name for debug page: %s' % template_name,
        )

        template = engine.get_template(template_name)
        name = template.nodelist[0].source[0].name
        self.assertTrue(
            name.endswith(template_name),
            'Cached template loaded through cached loader has incorrect name for debug page: %s' % template_name,
        )
Ejemplo n.º 9
0
    def test_cached_loader_priority(self):
        """
        Check that the order of template loader works. Refs #21460.
        """
        loaders = [
            ('django.template.loaders.cached.Loader', [
                'django.template.loaders.filesystem.Loader',
                'django.template.loaders.app_directories.Loader',
            ]),
        ]
        engine = Engine(dirs=[OTHER_DIR, TEMPLATE_DIR], loaders=loaders)

        template = engine.get_template('priority/foo.html')
        self.assertEqual(template.render(Context()), 'priority\n')

        template = engine.get_template('priority/foo.html')
        self.assertEqual(template.render(Context()), 'priority\n')
Ejemplo n.º 10
0
 def test_loader_priority(self):
     """
     #21460 -- Check that the order of template loader works.
     """
     loaders = ["django.template.loaders.filesystem.Loader", "django.template.loaders.app_directories.Loader"]
     engine = Engine(dirs=[OTHER_DIR, TEMPLATE_DIR], loaders=loaders)
     template = engine.get_template("priority/foo.html")
     self.assertEqual(template.render(Context()), "priority\n")
    def test_cached_loader_priority(self):
        """
        Check that the order of template loader works. Refs #21460.
        """
        loaders = [
            ('django.template.loaders.cached.Loader', [
                'django.template.loaders.filesystem.Loader',
                'django.template.loaders.app_directories.Loader',
            ]),
        ]
        engine = Engine(dirs=[OTHER_DIR, TEMPLATE_DIR], loaders=loaders)

        template = engine.get_template('priority/foo.html')
        self.assertEqual(template.render(Context()), 'priority\n')

        template = engine.get_template('priority/foo.html')
        self.assertEqual(template.render(Context()), 'priority\n')
Ejemplo n.º 12
0
    def test_debug_nodelist_name(self):
        template_name = 'index.html'
        engine = Engine(dirs=[TEMPLATE_DIR], debug=True)

        template = engine.get_template(template_name)
        name = template.nodelist[0].source[0].name
        self.assertTrue(
            name.endswith(template_name),
            'Template loaded through cached loader has incorrect name for debug page: %s' % template_name,
        )

        template = engine.get_template(template_name)
        name = template.nodelist[0].source[0].name
        self.assertTrue(
            name.endswith(template_name),
            'Cached template loaded through cached loader has incorrect name for debug page: %s' % template_name,
        )
Ejemplo n.º 13
0
    def test_cached_loader_priority(self):
        """
        The order of template loader works. Refs #21460.
        """
        loaders = [
            (
                "django.template.loaders.cached.Loader",
                [
                    "django.template.loaders.filesystem.Loader",
                    "django.template.loaders.app_directories.Loader",
                ],
            ),
        ]
        engine = Engine(dirs=[OTHER_DIR, TEMPLATE_DIR], loaders=loaders)

        template = engine.get_template("priority/foo.html")
        self.assertEqual(template.render(Context()), "priority\n")

        template = engine.get_template("priority/foo.html")
        self.assertEqual(template.render(Context()), "priority\n")
Ejemplo n.º 14
0
class DjangoTemplates(BaseEngine):

    app_dirname = 'templates'

    def __init__(self, params):
        params = params.copy()
        options = params.pop('OPTIONS').copy()
        options.setdefault('autoescape', True)
        options.setdefault('debug', settings.DEBUG)
        options.setdefault('file_charset', 'utf-8')
        libraries = options.get('libraries', {})
        # 下面这个值是字典对象
        # {'cache': 'django.templatetags.cache', 
        #  'i18n': 'django.templatetags.i18n', 
        #  'l10n': 'django.templatetags.l10n', 
        #  'static': 'django.templatetags.static', 
        #  'tz': 'django.templatetags.tz', 
        #  'admin_list': 'django.contrib.admin.templatetags.admin_list', 
        #  'admin_modify': 'django.contrib.admin.templatetags.admin_modify', 
        #  'admin_urls': 'django.contrib.admin.templatetags.admin_urls', 
        #  'log': 'django.contrib.admin.templatetags.log'
        # }
        options['libraries'] = self.get_templatetag_libraries(libraries)
        super().__init__(params)
        self.engine = Engine(self.dirs, self.app_dirs, **options)

    def from_string(self, template_code):
        return Template(self.engine.from_string(template_code), self)

    def get_template(self, template_name):
        # self 是「模板引擎对象」
        try:
            # self.engine 是 django.template.engine.Engine 类的实例,叫做「引擎对象」
            # self.engine.get_template 的返回值是「模板对象」,django.template.base.Template 类的实例
            # 下面这个 Template 是定义在当前模块中的类,该类的实例被称为「最终模板对象」
            return Template(self.engine.get_template(template_name), self)
        except TemplateDoesNotExist as exc:
            reraise(exc, self)

    def get_templatetag_libraries(self, custom_libraries):
        """
        Return a collation of template tag libraries from installed
        applications and the supplied custom_libraries argument.
        """
        libraries = get_installed_libraries()
        libraries.update(custom_libraries)
        return libraries
Ejemplo n.º 15
0
class DjangoTemplates(BaseEngine):

    app_dirname = 'templates'

    def __init__(self, params):
        params = params.copy()
        options = params.pop('OPTIONS').copy()
        options.setdefault('debug', settings.TEMPLATE_DEBUG)
        options.setdefault('file_charset', settings.FILE_CHARSET)
        super(DjangoTemplates, self).__init__(params)
        self.engine = Engine(self.dirs, self.app_dirs, **options)

    def from_string(self, template_code):
        return Template(self.engine.from_string(template_code))

    def get_template(self, template_name, dirs=_dirs_undefined):
        return Template(self.engine.get_template(template_name, dirs))
Ejemplo n.º 16
0
class DjangoTemplates(BaseEngine):

    app_dirname = 'templates'

    def __init__(self, params):
        params = params.copy()
        options = params.pop('OPTIONS').copy()
        options.setdefault('debug', settings.DEBUG)
        options.setdefault('file_charset', settings.FILE_CHARSET)
        super(DjangoTemplates, self).__init__(params)
        self.engine = Engine(self.dirs, self.app_dirs, **options)

    def from_string(self, template_code):
        return Template(self.engine.from_string(template_code))

    def get_template(self, template_name, dirs=_dirs_undefined):
        return Template(self.engine.get_template(template_name, dirs))
Ejemplo n.º 17
0
class TemplateDirsOverrideTests(SimpleTestCase):
    DIRS = ((OTHER_DIR,), [OTHER_DIR])

    def setUp(self):
        self.engine = Engine()

    def test_render_to_string(self):
        for dirs in self.DIRS:
            self.assertEqual(self.engine.render_to_string("test_dirs.html", dirs=dirs), "spam eggs\n")

    def test_get_template(self):
        for dirs in self.DIRS:
            template = self.engine.get_template("test_dirs.html", dirs=dirs)
            self.assertEqual(template.render(Context()), "spam eggs\n")

    def test_select_template(self):
        for dirs in self.DIRS:
            template = self.engine.select_template(["test_dirs.html"], dirs=dirs)
            self.assertEqual(template.render(Context()), "spam eggs\n")
Ejemplo n.º 18
0
class TornadoTemplate(BaseEngine):

    app_dirname = 'tornado'

    def __init__(self, params):
        params = params.copy()
        options = params.pop('OPTIONS').copy()
        options.setdefault('debug', settings.DEBUG)
        options.setdefault('file_charset', settings.FILE_CHARSET)
        super(TornadoTemplate, self).__init__(params)
        self.engine = Engine(self.dirs, self.app_dirs, **options)

    def from_string(self, template_code):
        return Template(self.engine.from_string(template_code))

    def get_template(self, template_name, dirs=_dirs_undefined):
        return Template(self.engine.get_template(template_name, dirs))

        self.env = environment_cls(**options)
Ejemplo n.º 19
0
class TemplateDirsOverrideTests(SimpleTestCase):
    DIRS = ((OTHER_DIR, ), [OTHER_DIR])

    def setUp(self):
        self.engine = Engine()

    def test_render_to_string(self):
        for dirs in self.DIRS:
            self.assertEqual(
                self.engine.render_to_string('test_dirs.html', dirs=dirs),
                'spam eggs\n',
            )

    def test_get_template(self):
        for dirs in self.DIRS:
            template = self.engine.get_template('test_dirs.html', dirs=dirs)
            self.assertEqual(template.render(Context()), 'spam eggs\n')

    def test_select_template(self):
        for dirs in self.DIRS:
            template = self.engine.select_template(['test_dirs.html'], dirs=dirs)
            self.assertEqual(template.render(Context()), 'spam eggs\n')
Ejemplo n.º 20
0
 def test_debug_nodelist_name(self):
     engine = Engine(dirs=[TEMPLATE_DIR], debug=True)
     template_name = 'index.html'
     template = engine.get_template(template_name)
     name = template.nodelist[0].source[0].name
     self.assertTrue(name.endswith(template_name))
Ejemplo n.º 21
0
 def test_origin_debug_false(self):
     engine = Engine(dirs=[TEMPLATE_DIR], debug=False)
     template = engine.get_template('index.html')
     self.assertEqual(template.origin, None)
 def test_origin(self):
     engine = Engine(dirs=[TEMPLATE_DIR], debug=True)
     template = engine.get_template('index.html')
     self.assertEqual(template.origin.template_name, 'index.html')
Ejemplo n.º 23
0
 def test_debug_nodelist_name(self):
     engine = Engine(dirs=[TEMPLATE_DIR], debug=True)
     template_name = "index.html"
     template = engine.get_template(template_name)
     name = template.nodelist[0].source[0].name
     self.assertTrue(name.endswith(template_name))
Ejemplo n.º 24
0
class CachedLoaderTests(SimpleTestCase):

    def setUp(self):
        self.engine = Engine(
            dirs=[TEMPLATE_DIR],
            loaders=[
                ('django.template.loaders.cached.Loader', [
                    'django.template.loaders.filesystem.Loader',
                ]),
            ],
        )

    def test_get_template(self):
        template = self.engine.get_template('index.html')
        self.assertEqual(template.origin.name, os.path.join(TEMPLATE_DIR, 'index.html'))
        self.assertEqual(template.origin.template_name, 'index.html')
        self.assertEqual(template.origin.loader, self.engine.template_loaders[0].loaders[0])

        cache = self.engine.template_loaders[0].get_template_cache
        self.assertEqual(cache['index.html'], template)

        # Run a second time from cache
        template = self.engine.get_template('index.html')
        self.assertEqual(template.origin.name, os.path.join(TEMPLATE_DIR, 'index.html'))
        self.assertEqual(template.origin.template_name, 'index.html')
        self.assertEqual(template.origin.loader, self.engine.template_loaders[0].loaders[0])

    def test_get_template_missing_debug_off(self):
        """
        With template debugging disabled, the raw TemplateDoesNotExist class
        should be cached when a template is missing. See ticket #26306 and
        docstrings in the cached loader for details.
        """
        self.engine.debug = False
        with self.assertRaises(TemplateDoesNotExist):
            self.engine.get_template('prod-template-missing.html')
        e = self.engine.template_loaders[0].get_template_cache['prod-template-missing.html']
        self.assertEqual(e, TemplateDoesNotExist)

    def test_get_template_missing_debug_on(self):
        """
        With template debugging enabled, a TemplateDoesNotExist instance
        should be cached when a template is missing.
        """
        self.engine.debug = True
        with self.assertRaises(TemplateDoesNotExist):
            self.engine.get_template('debug-template-missing.html')
        e = self.engine.template_loaders[0].get_template_cache['debug-template-missing.html']
        self.assertIsInstance(e, TemplateDoesNotExist)
        self.assertEqual(e.args[0], 'debug-template-missing.html')

    @unittest.skipIf(six.PY2, "Python 2 doesn't set extra exception attributes")
    def test_cached_exception_no_traceback(self):
        """
        When a TemplateDoesNotExist instance is cached, the cached instance
        should not contain the __traceback__, __context__, or __cause__
        attributes that Python sets when raising exceptions.
        """
        self.engine.debug = True
        with self.assertRaises(TemplateDoesNotExist):
            self.engine.get_template('no-traceback-in-cache.html')
        e = self.engine.template_loaders[0].get_template_cache['no-traceback-in-cache.html']

        error_msg = "Cached TemplateDoesNotExist must not have been thrown."
        self.assertIsNone(e.__traceback__, error_msg)
        self.assertIsNone(e.__context__, error_msg)
        self.assertIsNone(e.__cause__, error_msg)

    @ignore_warnings(category=RemovedInDjango20Warning)
    def test_load_template(self):
        loader = self.engine.template_loaders[0]
        template, origin = loader.load_template('index.html')
        self.assertEqual(template.origin.template_name, 'index.html')

        cache = self.engine.template_loaders[0].template_cache
        self.assertEqual(cache['index.html'][0], template)

        # Run a second time from cache
        loader = self.engine.template_loaders[0]
        source, name = loader.load_template('index.html')
        self.assertEqual(template.origin.template_name, 'index.html')

    @ignore_warnings(category=RemovedInDjango20Warning)
    def test_load_template_missing(self):
        """
        #19949 -- TemplateDoesNotExist exceptions should be cached.
        """
        loader = self.engine.template_loaders[0]

        self.assertFalse('missing.html' in loader.template_cache)

        with self.assertRaises(TemplateDoesNotExist):
            loader.load_template("missing.html")

        self.assertEqual(
            loader.template_cache["missing.html"],
            TemplateDoesNotExist,
            "Cached loader failed to cache the TemplateDoesNotExist exception",
        )

    @ignore_warnings(category=RemovedInDjango20Warning)
    def test_load_nonexistent_cached_template(self):
        loader = self.engine.template_loaders[0]
        template_name = 'nonexistent.html'

        # fill the template cache
        with self.assertRaises(TemplateDoesNotExist):
            loader.find_template(template_name)

        with self.assertRaisesMessage(TemplateDoesNotExist, template_name):
            loader.get_template(template_name)

    def test_templatedir_caching(self):
        """
        #13573 -- Template directories should be part of the cache key.
        """
        # Retrieve a template specifying a template directory to check
        t1, name = self.engine.find_template('test.html', (os.path.join(TEMPLATE_DIR, 'first'),))
        # Now retrieve the same template name, but from a different directory
        t2, name = self.engine.find_template('test.html', (os.path.join(TEMPLATE_DIR, 'second'),))

        # The two templates should not have the same content
        self.assertNotEqual(t1.render(Context({})), t2.render(Context({})))
Ejemplo n.º 25
0
 def test_loaders_dirs_empty(self):
     """An empty dirs list in loaders overrides top level dirs."""
     engine = Engine(dirs=[TEMPLATE_DIR], loaders=[('django.template.loaders.filesystem.Loader', [])])
     with self.assertRaises(TemplateDoesNotExist):
         engine.get_template('index.html')
Ejemplo n.º 26
0
class CachedLoaderTests(SimpleTestCase):

    def setUp(self):
        self.engine = Engine(
            dirs=[TEMPLATE_DIR],
            loaders=[
                ('django.template.loaders.cached.Loader', [
                    'django.template.loaders.filesystem.Loader',
                ]),
            ],
        )

    def test_get_template(self):
        template = self.engine.get_template('index.html')
        self.assertEqual(template.origin.name, os.path.join(TEMPLATE_DIR, 'index.html'))
        self.assertEqual(template.origin.template_name, 'index.html')
        self.assertEqual(template.origin.loader, self.engine.template_loaders[0].loaders[0])

        cache = self.engine.template_loaders[0].get_template_cache
        self.assertEqual(cache['index.html'], template)

        # Run a second time from cache
        template = self.engine.get_template('index.html')
        self.assertEqual(template.origin.name, os.path.join(TEMPLATE_DIR, 'index.html'))
        self.assertEqual(template.origin.template_name, 'index.html')
        self.assertEqual(template.origin.loader, self.engine.template_loaders[0].loaders[0])

    def test_get_template_missing_debug_off(self):
        """
        With template debugging disabled, the raw TemplateDoesNotExist class
        should be cached when a template is missing. See ticket #26306 and
        docstrings in the cached loader for details.
        """
        self.engine.debug = False
        with self.assertRaises(TemplateDoesNotExist):
            self.engine.get_template('prod-template-missing.html')
        e = self.engine.template_loaders[0].get_template_cache['prod-template-missing.html']
        self.assertEqual(e, TemplateDoesNotExist)

    def test_get_template_missing_debug_on(self):
        """
        With template debugging enabled, a TemplateDoesNotExist instance
        should be cached when a template is missing.
        """
        self.engine.debug = True
        with self.assertRaises(TemplateDoesNotExist):
            self.engine.get_template('debug-template-missing.html')
        e = self.engine.template_loaders[0].get_template_cache['debug-template-missing.html']
        self.assertIsInstance(e, TemplateDoesNotExist)
        self.assertEqual(e.args[0], 'debug-template-missing.html')

    @unittest.skipIf(six.PY2, "Python 2 doesn't set extra exception attributes")
    def test_cached_exception_no_traceback(self):
        """
        When a TemplateDoesNotExist instance is cached, the cached instance
        should not contain the __traceback__, __context__, or __cause__
        attributes that Python sets when raising exceptions.
        """
        self.engine.debug = True
        with self.assertRaises(TemplateDoesNotExist):
            self.engine.get_template('no-traceback-in-cache.html')
        e = self.engine.template_loaders[0].get_template_cache['no-traceback-in-cache.html']

        error_msg = "Cached TemplateDoesNotExist must not have been thrown."
        self.assertIsNone(e.__traceback__, error_msg)
        self.assertIsNone(e.__context__, error_msg)
        self.assertIsNone(e.__cause__, error_msg)

    @ignore_warnings(category=RemovedInDjango20Warning)
    def test_load_template(self):
        loader = self.engine.template_loaders[0]
        template, origin = loader.load_template('index.html')
        self.assertEqual(template.origin.template_name, 'index.html')

        cache = self.engine.template_loaders[0].template_cache
        self.assertEqual(cache['index.html'][0], template)

        # Run a second time from cache
        loader = self.engine.template_loaders[0]
        source, name = loader.load_template('index.html')
        self.assertEqual(template.origin.template_name, 'index.html')

    @ignore_warnings(category=RemovedInDjango20Warning)
    def test_load_template_missing(self):
        """
        #19949 -- TemplateDoesNotExist exceptions should be cached.
        """
        loader = self.engine.template_loaders[0]

        self.assertFalse('missing.html' in loader.template_cache)

        with self.assertRaises(TemplateDoesNotExist):
            loader.load_template("missing.html")

        self.assertEqual(
            loader.template_cache["missing.html"],
            TemplateDoesNotExist,
            "Cached loader failed to cache the TemplateDoesNotExist exception",
        )

    @ignore_warnings(category=RemovedInDjango20Warning)
    def test_load_nonexistent_cached_template(self):
        loader = self.engine.template_loaders[0]
        template_name = 'nonexistent.html'

        # fill the template cache
        with self.assertRaises(TemplateDoesNotExist):
            loader.find_template(template_name)

        with self.assertRaisesMessage(TemplateDoesNotExist, template_name):
            loader.get_template(template_name)

    def test_templatedir_caching(self):
        """
        #13573 -- Template directories should be part of the cache key.
        """
        # Retrieve a template specifying a template directory to check
        t1, name = self.engine.find_template('test.html', (os.path.join(TEMPLATE_DIR, 'first'),))
        # Now retrieve the same template name, but from a different directory
        t2, name = self.engine.find_template('test.html', (os.path.join(TEMPLATE_DIR, 'second'),))

        # The two templates should not have the same content
        self.assertNotEqual(t1.render(Context({})), t2.render(Context({})))

    def test_template_name_leading_dash_caching(self):
        """
        #26536 -- A leading dash in a template name shouldn't be stripped
        from its cache key.
        """
        self.assertEqual(self.engine.template_loaders[0].cache_key('-template.html', []), '-template.html')

    def test_template_name_lazy_string(self):
        """
        #26603 -- A template name specified as a lazy string should be forced
        to text before computing its cache key.
        """
        self.assertEqual(self.engine.template_loaders[0].cache_key(lazystr('template.html'), []), 'template.html')
Ejemplo n.º 27
0
    for c in response.cookies.values():
        response_headers.append((str("Set-Cookie"), str(c.output(header=""))))
    start_response(force_str(status), response_headers)
    if getattr(response, "file_to_stream",
               None) is not None and environ.get("wsgi.file_wrapper"):
        response = environ["wsgi.file_wrapper"](response.file_to_stream)
    return response


template_engine = Engine(
    dirs=[os.path.join(os.path.dirname(__file__), "./templates/content")],
    libraries={
        "zipcontent": "kolibri.core.content.templatetags.zip_content_tags"
    },
)
h5p_template = template_engine.get_template("h5p.html")
hashi_template = template_engine.get_template("hashi.html")

allowed_methods = set(["GET", "OPTIONS"])


def _hashi_response_from_request(request):
    if request.method not in allowed_methods:
        return HttpResponseNotAllowed(allowed_methods)

    filename = request.path_info.lstrip("/")

    if filename.split(".")[-1] != "html":
        return HttpResponseNotFound()

    if filename != get_hashi_html_filename():
Ejemplo n.º 28
0
class FileSystemLoaderTests(SimpleTestCase):

    def setUp(self):
        self.engine = Engine(dirs=[TEMPLATE_DIR])

    @contextmanager
    def set_dirs(self, dirs):
        original_dirs = self.engine.dirs
        self.engine.dirs = dirs
        try:
            yield
        finally:
            self.engine.dirs = original_dirs

    @contextmanager
    def source_checker(self, dirs):
        loader = self.engine.template_loaders[0]

        def check_sources(path, expected_sources):
            expected_sources = [os.path.abspath(s) for s in expected_sources]
            self.assertEqual(
                list(loader.get_template_sources(path)),
                expected_sources,
            )

        with self.set_dirs(dirs):
            yield check_sources

    def test_directory_security(self):
        with self.source_checker(['/dir1', '/dir2']) as check_sources:
            check_sources('index.html', ['/dir1/index.html', '/dir2/index.html'])
            check_sources('/etc/passwd', [])
            check_sources('etc/passwd', ['/dir1/etc/passwd', '/dir2/etc/passwd'])
            check_sources('../etc/passwd', [])
            check_sources('../../../etc/passwd', [])
            check_sources('/dir1/index.html', ['/dir1/index.html'])
            check_sources('../dir2/index.html', ['/dir2/index.html'])
            check_sources('/dir1blah', [])
            check_sources('../dir1blah', [])

    def test_unicode_template_name(self):
        with self.source_checker(['/dir1', '/dir2']) as check_sources:
            # UTF-8 bytestrings are permitted.
            check_sources(b'\xc3\x85ngstr\xc3\xb6m', ['/dir1/Ångström', '/dir2/Ångström'])
            # Unicode strings are permitted.
            check_sources('Ångström', ['/dir1/Ångström', '/dir2/Ångström'])

    def test_utf8_bytestring(self):
        """
        Invalid UTF-8 encoding in bytestrings should raise a useful error
        """
        engine = Engine()
        loader = engine.template_loaders[0]
        with self.assertRaises(UnicodeDecodeError):
            list(loader.get_template_sources(b'\xc3\xc3', ['/dir1']))

    def test_unicode_dir_name(self):
        with self.source_checker([b'/Stra\xc3\x9fe']) as check_sources:
            check_sources('Ångström', ['/Straße/Ångström'])
            check_sources(b'\xc3\x85ngstr\xc3\xb6m', ['/Straße/Ångström'])

    @unittest.skipUnless(
        os.path.normcase('/TEST') == os.path.normpath('/test'),
        "This test only runs on case-sensitive file systems.",
    )
    def test_case_sensitivity(self):
        with self.source_checker(['/dir1', '/DIR2']) as check_sources:
            check_sources('index.html', ['/dir1/index.html', '/DIR2/index.html'])
            check_sources('/DIR1/index.HTML', ['/DIR1/index.HTML'])

    def test_file_does_not_exist(self):
        with self.assertRaises(TemplateDoesNotExist):
            self.engine.get_template('doesnotexist.html')

    @unittest.skipIf(
        sys.platform == 'win32',
        "Python on Windows doesn't have working os.chmod().",
    )
    def test_permissions_error(self):
        with tempfile.NamedTemporaryFile() as tmpfile:
            tmpdir = os.path.dirname(tmpfile.name)
            tmppath = os.path.join(tmpdir, tmpfile.name)
            os.chmod(tmppath, 0o0222)
            with self.set_dirs([tmpdir]):
                with self.assertRaisesMessage(IOError, 'Permission denied'):
                    self.engine.get_template(tmpfile.name)

    def test_notafile_error(self):
        with self.assertRaises(IOError):
            self.engine.get_template('first')
Ejemplo n.º 29
0
 def test_loaders_dirs(self):
     engine = Engine(loaders=[('django.template.loaders.filesystem.Loader', [TEMPLATE_DIR])])
     template = engine.get_template('index.html')
     self.assertEqual(template.origin.name, os.path.join(TEMPLATE_DIR, 'index.html'))
Ejemplo n.º 30
0
class FileSystemLoaderTests(SimpleTestCase):

    def setUp(self):
        self.engine = Engine(dirs=[TEMPLATE_DIR])

    @contextmanager
    def set_dirs(self, dirs):
        original_dirs = self.engine.dirs
        self.engine.dirs = dirs
        try:
            yield
        finally:
            self.engine.dirs = original_dirs

    @contextmanager
    def source_checker(self, dirs):
        loader = self.engine.template_loaders[0]

        def check_sources(path, expected_sources):
            expected_sources = [os.path.abspath(s) for s in expected_sources]
            self.assertEqual(
                list(loader.get_template_sources(path)),
                expected_sources,
            )

        with self.set_dirs(dirs):
            yield check_sources

    def test_directory_security(self):
        with self.source_checker(['/dir1', '/dir2']) as check_sources:
            check_sources('index.html', ['/dir1/index.html', '/dir2/index.html'])
            check_sources('/etc/passwd', [])
            check_sources('etc/passwd', ['/dir1/etc/passwd', '/dir2/etc/passwd'])
            check_sources('../etc/passwd', [])
            check_sources('../../../etc/passwd', [])
            check_sources('/dir1/index.html', ['/dir1/index.html'])
            check_sources('../dir2/index.html', ['/dir2/index.html'])
            check_sources('/dir1blah', [])
            check_sources('../dir1blah', [])

    def test_unicode_template_name(self):
        with self.source_checker(['/dir1', '/dir2']) as check_sources:
            # UTF-8 bytestrings are permitted.
            check_sources(b'\xc3\x85ngstr\xc3\xb6m', ['/dir1/Ångström', '/dir2/Ångström'])
            # Unicode strings are permitted.
            check_sources('Ångström', ['/dir1/Ångström', '/dir2/Ångström'])

    def test_utf8_bytestring(self):
        """
        Invalid UTF-8 encoding in bytestrings should raise a useful error
        """
        engine = Engine()
        loader = engine.template_loaders[0]
        with self.assertRaises(UnicodeDecodeError):
            list(loader.get_template_sources(b'\xc3\xc3', ['/dir1']))

    def test_unicode_dir_name(self):
        with self.source_checker([b'/Stra\xc3\x9fe']) as check_sources:
            check_sources('Ångström', ['/Straße/Ångström'])
            check_sources(b'\xc3\x85ngstr\xc3\xb6m', ['/Straße/Ångström'])

    @unittest.skipUnless(
        os.path.normcase('/TEST') == os.path.normpath('/test'),
        "This test only runs on case-sensitive file systems.",
    )
    def test_case_sensitivity(self):
        with self.source_checker(['/dir1', '/DIR2']) as check_sources:
            check_sources('index.html', ['/dir1/index.html', '/DIR2/index.html'])
            check_sources('/DIR1/index.HTML', ['/DIR1/index.HTML'])

    def test_file_does_not_exist(self):
        with self.assertRaises(TemplateDoesNotExist):
            self.engine.get_template('doesnotexist.html')

    @unittest.skipIf(
        sys.platform == 'win32',
        "Python on Windows doesn't have working os.chmod().",
    )
    def test_permissions_error(self):
        with tempfile.NamedTemporaryFile() as tmpfile:
            tmpdir = os.path.dirname(tmpfile.name)
            tmppath = os.path.join(tmpdir, tmpfile.name)
            os.chmod(tmppath, 0o0222)
            with self.set_dirs([tmpdir]):
                with self.assertRaisesMessage(IOError, 'Permission denied'):
                    self.engine.get_template(tmpfile.name)

    def test_notafile_error(self):
        with self.assertRaisesMessage(IOError, 'Is a directory'):
            self.engine.get_template('first')
Ejemplo n.º 31
0
class CachedLoaderTests(SimpleTestCase):

    def setUp(self):
        self.engine = Engine(
            dirs=[TEMPLATE_DIR],
            loaders=[
                ('django.template.loaders.cached.Loader', [
                    'django.template.loaders.filesystem.Loader',
                ]),
            ],
        )

    def test_get_template(self):
        template = self.engine.get_template('index.html')
        self.assertEqual(template.origin.name, os.path.join(TEMPLATE_DIR, 'index.html'))
        self.assertEqual(template.origin.template_name, 'index.html')
        self.assertEqual(template.origin.loader, self.engine.template_loaders[0].loaders[0])

        cache = self.engine.template_loaders[0].get_template_cache
        self.assertEqual(cache['index.html'], template)

        # Run a second time from cache
        template = self.engine.get_template('index.html')
        self.assertEqual(template.origin.name, os.path.join(TEMPLATE_DIR, 'index.html'))
        self.assertEqual(template.origin.template_name, 'index.html')
        self.assertEqual(template.origin.loader, self.engine.template_loaders[0].loaders[0])

    def test_get_template_missing_debug_off(self):
        """
        With template debugging disabled, the raw TemplateDoesNotExist class
        should be cached when a template is missing. See ticket #26306 and
        docstrings in the cached loader for details.
        """
        self.engine.debug = False
        with self.assertRaises(TemplateDoesNotExist):
            self.engine.get_template('prod-template-missing.html')
        e = self.engine.template_loaders[0].get_template_cache['prod-template-missing.html']
        self.assertEqual(e, TemplateDoesNotExist)

    def test_get_template_missing_debug_on(self):
        """
        With template debugging enabled, a TemplateDoesNotExist instance
        should be cached when a template is missing.
        """
        self.engine.debug = True
        with self.assertRaises(TemplateDoesNotExist):
            self.engine.get_template('debug-template-missing.html')
        e = self.engine.template_loaders[0].get_template_cache['debug-template-missing.html']
        self.assertIsInstance(e, TemplateDoesNotExist)
        self.assertEqual(e.args[0], 'debug-template-missing.html')

    def test_cached_exception_no_traceback(self):
        """
        When a TemplateDoesNotExist instance is cached, the cached instance
        should not contain the __traceback__, __context__, or __cause__
        attributes that Python sets when raising exceptions.
        """
        self.engine.debug = True
        with self.assertRaises(TemplateDoesNotExist):
            self.engine.get_template('no-traceback-in-cache.html')
        e = self.engine.template_loaders[0].get_template_cache['no-traceback-in-cache.html']

        error_msg = "Cached TemplateDoesNotExist must not have been thrown."
        self.assertIsNone(e.__traceback__, error_msg)
        self.assertIsNone(e.__context__, error_msg)
        self.assertIsNone(e.__cause__, error_msg)

    def test_template_name_leading_dash_caching(self):
        """
        #26536 -- A leading dash in a template name shouldn't be stripped
        from its cache key.
        """
        self.assertEqual(self.engine.template_loaders[0].cache_key('-template.html', []), '-template.html')

    def test_template_name_lazy_string(self):
        """
        #26603 -- A template name specified as a lazy string should be forced
        to text before computing its cache key.
        """
        self.assertEqual(self.engine.template_loaders[0].cache_key(lazystr('template.html'), []), 'template.html')
Ejemplo n.º 32
0
 def test_origin(self):
     engine = Engine(dirs=[TEMPLATE_DIR], debug=True)
     template = engine.get_template('index.html')
     self.assertEqual(template.origin.template_name, 'index.html')
Ejemplo n.º 33
0
 def test_origin_debug_false(self):
     engine = Engine(dirs=[TEMPLATE_DIR], debug=False)
     template = engine.get_template("index.html")
     self.assertEqual(template.origin, None)
Ejemplo n.º 34
0
# Since this package contains a "django" module, this is required on Python 2.
Ejemplo n.º 35
0
class CachedLoaderTests(SimpleTestCase):

    def setUp(self):
        self.engine = Engine(
            dirs=[TEMPLATE_DIR],
            loaders=[
                ('django.template.loaders.cached.Loader', [
                    'django.template.loaders.filesystem.Loader',
                ]),
            ],
        )

    def test_get_template(self):
        template = self.engine.get_template('index.html')
        self.assertEqual(template.origin.name, os.path.join(TEMPLATE_DIR, 'index.html'))
        self.assertEqual(template.origin.template_name, 'index.html')
        self.assertEqual(template.origin.loader, self.engine.template_loaders[0].loaders[0])

        cache = self.engine.template_loaders[0].get_template_cache
        self.assertEqual(cache['index.html'], template)

        # Run a second time from cache
        template = self.engine.get_template('index.html')
        self.assertEqual(template.origin.name, os.path.join(TEMPLATE_DIR, 'index.html'))
        self.assertEqual(template.origin.template_name, 'index.html')
        self.assertEqual(template.origin.loader, self.engine.template_loaders[0].loaders[0])

    def test_get_template_missing(self):
        with self.assertRaises(TemplateDoesNotExist):
            self.engine.get_template('doesnotexist.html')
        e = self.engine.template_loaders[0].get_template_cache['doesnotexist.html']
        self.assertEqual(e.args[0], 'doesnotexist.html')

    @ignore_warnings(category=RemovedInDjango20Warning)
    def test_load_template(self):
        loader = self.engine.template_loaders[0]
        template, origin = loader.load_template('index.html')
        self.assertEqual(template.origin.template_name, 'index.html')

        cache = self.engine.template_loaders[0].template_cache
        self.assertEqual(cache['index.html'][0], template)

        # Run a second time from cache
        loader = self.engine.template_loaders[0]
        source, name = loader.load_template('index.html')
        self.assertEqual(template.origin.template_name, 'index.html')

    @ignore_warnings(category=RemovedInDjango20Warning)
    def test_load_template_missing(self):
        """
        #19949 -- TemplateDoesNotExist exceptions should be cached.
        """
        loader = self.engine.template_loaders[0]

        self.assertFalse('missing.html' in loader.template_cache)

        with self.assertRaises(TemplateDoesNotExist):
            loader.load_template("missing.html")

        self.assertEqual(
            loader.template_cache["missing.html"],
            TemplateDoesNotExist,
            "Cached loader failed to cache the TemplateDoesNotExist exception",
        )

    @ignore_warnings(category=RemovedInDjango20Warning)
    def test_load_nonexistent_cached_template(self):
        loader = self.engine.template_loaders[0]
        template_name = 'nonexistent.html'

        # fill the template cache
        with self.assertRaises(TemplateDoesNotExist):
            loader.find_template(template_name)

        with self.assertRaisesMessage(TemplateDoesNotExist, template_name):
            loader.get_template(template_name)

    def test_templatedir_caching(self):
        """
        #13573 -- Template directories should be part of the cache key.
        """
        # Retrieve a template specifying a template directory to check
        t1, name = self.engine.find_template('test.html', (os.path.join(TEMPLATE_DIR, 'first'),))
        # Now retrieve the same template name, but from a different directory
        t2, name = self.engine.find_template('test.html', (os.path.join(TEMPLATE_DIR, 'second'),))

        # The two templates should not have the same content
        self.assertNotEqual(t1.render(Context({})), t2.render(Context({})))
Ejemplo n.º 36
0
 def test_loaders_dirs(self):
     engine = Engine(loaders=[('django.template.loaders.filesystem.Loader', [TEMPLATE_DIR])])
     template = engine.get_template('index.html')
     self.assertEqual(template.origin.name, os.path.join(TEMPLATE_DIR, 'index.html'))
Ejemplo n.º 37
0
class CachedLoaderTests(SimpleTestCase):

    def setUp(self):
        self.engine = Engine(
            dirs=[TEMPLATE_DIR],
            loaders=[
                ('django.template.loaders.cached.Loader', [
                    'django.template.loaders.filesystem.Loader',
                ]),
            ],
        )

    def test_get_template(self):
        template = self.engine.get_template('index.html')
        self.assertEqual(template.origin.name, os.path.join(TEMPLATE_DIR, 'index.html'))
        self.assertEqual(template.origin.template_name, 'index.html')
        self.assertEqual(template.origin.loader, self.engine.template_loaders[0].loaders[0])

        cache = self.engine.template_loaders[0].get_template_cache
        self.assertEqual(cache['index.html'], template)

        # Run a second time from cache
        template = self.engine.get_template('index.html')
        self.assertEqual(template.origin.name, os.path.join(TEMPLATE_DIR, 'index.html'))
        self.assertEqual(template.origin.template_name, 'index.html')
        self.assertEqual(template.origin.loader, self.engine.template_loaders[0].loaders[0])

    def test_get_template_missing_debug_off(self):
        """
        With template debugging disabled, the raw TemplateDoesNotExist class
        should be cached when a template is missing. See ticket #26306 and
        docstrings in the cached loader for details.
        """
        self.engine.debug = False
        with self.assertRaises(TemplateDoesNotExist):
            self.engine.get_template('prod-template-missing.html')
        e = self.engine.template_loaders[0].get_template_cache['prod-template-missing.html']
        self.assertEqual(e, TemplateDoesNotExist)

    def test_get_template_missing_debug_on(self):
        """
        With template debugging enabled, a TemplateDoesNotExist instance
        should be cached when a template is missing.
        """
        self.engine.debug = True
        with self.assertRaises(TemplateDoesNotExist):
            self.engine.get_template('debug-template-missing.html')
        e = self.engine.template_loaders[0].get_template_cache['debug-template-missing.html']
        self.assertIsInstance(e, TemplateDoesNotExist)
        self.assertEqual(e.args[0], 'debug-template-missing.html')

    def test_cached_exception_no_traceback(self):
        """
        When a TemplateDoesNotExist instance is cached, the cached instance
        should not contain the __traceback__, __context__, or __cause__
        attributes that Python sets when raising exceptions.
        """
        self.engine.debug = True
        with self.assertRaises(TemplateDoesNotExist):
            self.engine.get_template('no-traceback-in-cache.html')
        e = self.engine.template_loaders[0].get_template_cache['no-traceback-in-cache.html']

        error_msg = "Cached TemplateDoesNotExist must not have been thrown."
        self.assertIsNone(e.__traceback__, error_msg)
        self.assertIsNone(e.__context__, error_msg)
        self.assertIsNone(e.__cause__, error_msg)

    def test_template_name_leading_dash_caching(self):
        """
        #26536 -- A leading dash in a template name shouldn't be stripped
        from its cache key.
        """
        self.assertEqual(self.engine.template_loaders[0].cache_key('-template.html', []), '-template.html')

    def test_template_name_lazy_string(self):
        """
        #26603 -- A template name specified as a lazy string should be forced
        to text before computing its cache key.
        """
        self.assertEqual(self.engine.template_loaders[0].cache_key(lazystr('template.html'), []), 'template.html')