Skip to content

Instantly share code, notes, and snippets.

@Xion
Created July 6, 2013 19:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Xion/5941003 to your computer and use it in GitHub Desktop.
Save Xion/5941003 to your computer and use it in GitHub Desktop.
from collections import Mapping
import unittest
import warnings
from flask import get_template_attribute
from myapplication import app
class JinjaTestCase(unittest.TestCase):
"""Base/mixin class for tests that may refer to Jinja templates
and symbols defined therin (mostly macros).
Usage::
class Hello(JinjaTestCase):
__template_imports__ = {
'hello': 'hello.html', # import 'hello' macro as 'hello' attr.
}
def test_hello(self):
self.assert_equal("Hello, world!", self.hello())
"""
class __metaclass__(type):
"""Metaclass for importing Jinja symbols as class attributes."""
def __new__(cls, cls_name, bases, dict_):
"""Create test case class, resolving ``__template_imports__``
specifications into Jinja template imports.
"""
imports = dict_.get('__template_imports__', {})
if isinstance(imports, Mapping):
imports = imports.items()
for name, template in imports:
if name in dict_:
warnings.warn(
"Template import %s/%s hides existing "
"attribute of class %s" % (template, name, cls_name))
dict_[name] = cls._template_import(template_name, name)
return type.__new__(cls, cls_name, bases, dict_)
@classmethod
def _template_import(cls, template_name, attribute):
"""Import template attribute from specified Jinja template file."""
with app.app_context():
return get_template_attribute(template_name, attribute)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment