Skip to content
Myr

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

5 files+97 added−21 removed

modified:docs/api.rst+5 added
314 unmodified lines
315.. autoclass:: jinja2.DebugUndefined()316317.. autoclass:: jinja2.StrictUndefined()318319There is also a factory function that can decorate undefined objects to320implement logging on failures:321322.. autofunction:: jinja2.make_logging_undefined323324Undefined objects are created by calling :attr:`undefined`.325326.. admonition:: Implementation327
468 unmodified lines
modified:jinja2/testsuite/api.py+26 added-1 removed
15 unmodified lines
16from jinja2.testsuite import JinjaTestCase1718from jinja2 import Environment, Undefined, DebugUndefined, \19 StrictUndefined, UndefinedError, meta, \20 is_undefined, Template, DictLoader20 is_undefined, Template, DictLoader, make_logging_undefined21from jinja2.utils import Cycler2223env = Environment()24
173 unmodified lines
198 pass199 else:200 assert False, "Expected actual attribute error"201202 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)209210 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 ])226227 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 lines
modified:jinja2/__init__.py+3 added-2 removed
40 unmodified lines
41from jinja2.bccache import BytecodeCache, FileSystemBytecodeCache, \42 MemcachedBytecodeCache4344# undefined types45from jinja2.runtime import Undefined, DebugUndefined, StrictUndefined45from jinja2.runtime import Undefined, DebugUndefined, StrictUndefined, \46 make_logging_undefined4748# exceptions49from jinja2.exceptions import TemplateError, UndefinedError, \50 TemplateNotFound, TemplatesNotFound, TemplateSyntaxError, \
14 unmodified lines
65 '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 lines
526 return 'Undefined'527528529def 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.533534 Example::535536 logger = logging.getLogger(__name__)537 LoggingUndefined = make_logging_undefined(538 logger=logger,539 base=Undefined540 )541542 .. versionadded:: 2.8543544 :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 = Undefined555556 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)571572 class LoggingUndefined(base):573574 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 e580581 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 rv585586 if PY2:587 def __unicode__(self):588 rv = base.__unicode__(self)589 _log_message(self)590 return rv591592 def __iter__(self):593 rv = base.__iter__(self)594 _log_message(self)595 return rv596597 def __nonzero__(self):598 rv = base.__nonzero__(self)599 _log_message(self)600 return rv601602 return LoggingUndefined603604605@implements_to_string
55 unmodified lines
modified:CHANGES+2 added
12 unmodified lines
13 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.1920Version 2.7.221-------------22(bugfix release, released on January 10th 2014)
321 unmodified lines