Added tests for logging undefined and added it to the docs.
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Armin Ronacher · committed by Armin Ronacher · parent d2641be · Browse files · 5 files·+97 added−21 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+97 added−21 removed
- other:+97 added−21 removed
Provenance
- Commit
6e9dfbf- Tree
446d55a- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
d2641be
5 files changed+97 added−21 removed
modified:docs/api.rst+5 added
314 unmodified lines315 .. autoclass:: jinja2.DebugUndefined()316 317 .. autoclass:: jinja2.StrictUndefined()318 319+There is also a factory function that can decorate undefined objects to320+implement logging on failures:321+322+.. autofunction:: jinja2.make_logging_undefined323+324 Undefined objects are created by calling :attr:`undefined`.325 326 .. admonition:: Implementation327 468 unmodified linesmodified:jinja2/testsuite/api.py+26 added-1 removed
15 unmodified lines16 from jinja2.testsuite import JinjaTestCase17 18 from jinja2 import Environment, Undefined, DebugUndefined, \19 StrictUndefined, UndefinedError, meta, \20- is_undefined, Template, DictLoader20+ is_undefined, Template, DictLoader, make_logging_undefined21 from jinja2.utils import Cycler22 23 env = Environment()24 173 unmodified lines198 pass199 else:200 assert False, "Expected actual attribute error"201 202+ def test_logging_undefined(self):203+ _messages = []204+ class DebugLogger(object):205+ def warning(self, msg, *args):206+ _messages.append('W:' + msg % args)207+ def error(self, msg, *args):208+ _messages.append('E:' + msg % args)209+210+ logging_undefined = make_logging_undefined(DebugLogger())211+ env = Environment(undefined=logging_undefined)212+ self.assert_equal(env.from_string('{{ missing }}').render(), u'')213+ self.assert_raises(UndefinedError,214+ env.from_string('{{ missing.attribute }}').render)215+ self.assert_equal(env.from_string('{{ missing|list }}').render(), '[]')216+ self.assert_equal(env.from_string('{{ missing is not defined }}').render(), 'True')217+ self.assert_equal(env.from_string('{{ foo.missing }}').render(foo=42), '')218+ self.assert_equal(env.from_string('{{ not missing }}').render(), 'True')219+ self.assert_equal(_messages, [220+ 'W:Template variable warning: missing is undefined',221+ "E:Template variable error: 'missing' is undefined",222+ 'W:Template variable warning: missing is undefined',223+ 'W:Template variable warning: int object has no attribute missing',224+ 'W:Template variable warning: missing is undefined',225+ ])226+227 def test_default_undefined(self):228 env = Environment(undefined=Undefined)229 self.assert_equal(env.from_string('{{ missing }}').render(), u'')230 self.assert_raises(UndefinedError,55 unmodified linesmodified:jinja2/__init__.py+3 added-2 removed
40 unmodified lines41 from jinja2.bccache import BytecodeCache, FileSystemBytecodeCache, \42 MemcachedBytecodeCache43 44 # undefined types45-from jinja2.runtime import Undefined, DebugUndefined, StrictUndefined45+from jinja2.runtime import Undefined, DebugUndefined, StrictUndefined, \46+ make_logging_undefined47 48 # exceptions49 from jinja2.exceptions import TemplateError, UndefinedError, \50 TemplateNotFound, TemplatesNotFound, TemplateSyntaxError, \14 unmodified lines65 'StrictUndefined', 'TemplateError', 'UndefinedError', 'TemplateNotFound',66 'TemplatesNotFound', 'TemplateSyntaxError', 'TemplateAssertionError',67 'ModuleLoader', 'environmentfilter', 'contextfilter', 'Markup', 'escape',68 'environmentfunction', 'contextfunction', 'clear_caches', 'is_undefined',68- 'evalcontextfilter', 'evalcontextfunction'69+ 'evalcontextfilter', 'evalcontextfunction', 'make_logging_undefined',70 ]modified:jinja2/runtime.py+61 added-18 removed
525 unmodified lines526 return 'Undefined'527 528 529 def make_logging_undefined(logger=None, base=None):530- """Given a logger object this returns a new undefined class that531- will log all failures into it. If no logger is given a default532- logger is created.530+ """Given a logger object this returns a new undefined class that will531+ log certain failures. It will log iterations and printing. If no532+ logger is given a default logger is created.533+534+ Example::535+536+ logger = logging.getLogger(__name__)537+ LoggingUndefined = make_logging_undefined(538+ logger=logger,539+ base=Undefined540+ )541+542+ .. versionadded:: 2.8543+544+ :param logger: the logger to use. If not provided, a default logger545+ is created.546+ :param base: the base class to add logging functionality to. This547+ defaults to :class:`Undefined`.548 """549 if logger is None:550 import logging551 logger = logging.getLogger(__name__)552 logger.addHandler(logging.StreamHandler(sys.stderr))553 if base is None:554 base = Undefined555 556+ def _log_message(undef):557+ if undef._undefined_hint is None:558+ if undef._undefined_obj is missing:559+ hint = '%s is undefined' % undef._undefined_name560+ elif not isinstance(undef._undefined_name, string_types):561+ hint = '%s has no element %s' % (562+ object_type_repr(undef._undefined_obj),563+ undef._undefined_name)564+ else:565+ hint = '%s has no attribute %s' % (566+ object_type_repr(undef._undefined_obj),567+ undef._undefined_name)568+ else:569+ hint = undef._undefined_hint570+ logger.warning('Template variable warning: %s', hint)571+572 class LoggingUndefined(base):573+574+ def _fail_with_undefined_error(self, *args, **kwargs):575+ try:576+ return base._fail_with_undefined_error(self, *args, **kwargs)577+ except self._undefined_exception as e:578+ logger.error('Template variable error: %s', str(e))579+ raise e580+581 def __str__(self):543- if self._undefined_hint is None:544- if self._undefined_obj is missing:545- hint = '%s is undefined' % self._undefined_name546- elif not isinstance(self._undefined_name, string_types):547- hint = '%s has no element %s' % (548- object_type_repr(self._undefined_obj),549- self._undefined_name)550- else:551- hint = '%s has no attribute %s' % (552- object_type_repr(self._undefined_obj),553- self._undefined_name)554- else:555- hint = self._undefined_hint556- logger.error('Template error: %s', hint)557- return base.__str__(self)582+ rv = base.__str__(self)583+ _log_message(self)584+ return rv585 586+ if PY2:587+ def __unicode__(self):588+ rv = base.__unicode__(self)589+ _log_message(self)590+ return rv591+592+ def __iter__(self):593+ rv = base.__iter__(self)594+ _log_message(self)595+ return rv596+597+ def __nonzero__(self):598+ rv = base.__nonzero__(self)599+ _log_message(self)600+ return rv601+602 return LoggingUndefined603 604 605 @implements_to_string55 unmodified linesmodified:CHANGES+2 added
12 unmodified lines13 instead of load names.14 - Fixed loop length calculation for some iterators.15 - Changed how Jinja2 enforces strings to be native strings in16 Python 2 to work when people break their default encoding.17+- Added :func:`make_logging_undefined` which returns an undefined18+ object that logs failures into a logger.19 20 Version 2.7.221 -------------22 (bugfix release, released on January 10th 2014)321 unmodified lines