worked on the tests and made undefined fail on comparisons now
Before adoption: this commit came in with the history the project adopted, so no landing records it.
--HG-- branch : trunk
authored by Armin Ronacher · committed by Armin Ronacher · parent 2feed1d · Browse files · 6 files·+91 added−52 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+91 added−52 removed
- tests:+1 added−8 removed
- other:+90 added−44 removed
Provenance
- Commit
5304229- Tree
27a6e6b- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
2feed1d
6 files changed+91 added−52 removed
modified:jinja2/compiler.py+5 added-2 removed
676 unmodified lines677 def visit_Import(self, node, frame):678 """Visit regular imports."""679 self.writeline('l_%s = ' % node.target, node)680 if frame.toplevel:681- self.write('context[%r] = ' % node.target)681+ self.write('context.vars[%r] = ' % node.target)682 self.write('environment.get_template(')683 self.visit(node.template, frame)684 self.write(', %r).include(context)' % self.name)685+ if frame.toplevel:686+ self.writeline('context.exported_vars.discard(%r)' % node.target)687 688 def visit_FromImport(self, node, frame):689 """Visit named imports."""690 self.newline(node)14 unmodified lines705 (alias, 'the template %r does not export '706 'the requested name ' + repr(name)))707 self.outdent()708 if frame.toplevel:707- self.writeline('context[%r] = l_%s' % (alias, alias))709+ self.writeline('context.vars[%r] = l_%s' % (alias, alias))710+ self.writeline('context.exported_vars.discard(%r)' % alias)711 712 def visit_For(self, node, frame):713 loop_frame = frame.inner()714 loop_frame.inspect(node.iter_child_nodes(exclude=('iter',)))442 unmodified linesmodified:jinja2/environment.py+18 added-13 removed
236 unmodified lines237 def from_string(self, source, globals=None, template_class=None):238 """Load a template from a string."""239 globals = self.make_globals(globals)240 return template_from_code(self, self.compile(source, globals=globals),241- globals, template_class)241+ globals, None, template_class)242 243 def make_globals(self, d):244 """Return a dict for the globals."""245 if d is None:138 unmodified lines384 return [tuple(map(int, x.split('='))) for x in385 self._debug_info.split('&')]386 387 def __repr__(self):388- return '<%s %r>' % (389- self.__class__.__name__,390- self.name or '<from string>'391- )388+ if self.name is None:389+ name = 'memory:%x' % id(self)390+ else:391+ name = repr(self.name)392+ return '<%s %s>' % (self.__class__.__name__, name)393 394 395 class IncludedTemplate(object):395- """Represents an included template."""396+ """Represents an included template. All the exported names of the397+ template are available as attributes on this object. Additionally398+ converting it into an unicode- or bytestrings renders the contents.399+ """400 401 def __init__(self, template, context):398- self._body_stream = tuple(template.root_render_func(context))402+ self.__body_stream = tuple(template.root_render_func(context))403 self.__dict__.update(context.get_exported())404 self.__name__ = template.name405 402- __html__ = lambda x: Markup(concat(x._body_stream))403- __unicode__ = lambda x: unicode(concat(x._body_stream))406+ __html__ = lambda x: Markup(concat(x.__body_stream))407+ __unicode__ = lambda x: unicode(concat(x.__body_stream))408 409 def __str__(self):410 return unicode(self).encode('utf-8')411 412 def __repr__(self):409- return '<%s %r>' % (410- self.__class__.__name__,411- self.__name__412- )413+ if self.__name__ is None:414+ name = 'memory:%x' % id(self)415+ else:416+ name = repr(self.name)417+ return '<%s %s>' % (self.__class__.__name__, name)418 419 420 class TemplateStream(object):421 """This class wraps a generator returned from `Template.generate` so that50 unmodified linesmodified:jinja2/exceptions.py+1 added-5 removed
34 unmodified lines35 self.lineno = lineno36 self.name = name37 38 39-class TemplateAssertionError(AssertionError, TemplateSyntaxError):39+class TemplateAssertionError(TemplateSyntaxError):40 """Like a template syntax error, but covers cases where something in the41 template caused an error at compile time that wasn't necessarily caused42 by a syntax error.43 """44 45- def __init__(self, message, lineno, name):46- AssertionError.__init__(self, message)47- TemplateSyntaxError.__init__(self, message, lineno, name)45 49-46 class TemplateRuntimeError(TemplateError):47 """Raised by the template engine if a tag encountered an error when48 rendering.49 """modified:jinja2/runtime.py+31 added-16 removed
7 unmodified lines8 :copyright: Copyright 2008 by Armin Ronacher.9 :license: GNU GPL.10 """11 from types import FunctionType12-from itertools import izip12 from jinja2.utils import Markup, partial13 from jinja2.exceptions import UndefinedError14 15 16 # these variables are exported to the template runtime17 __all__ = ['LoopContext', 'StaticLoopContext', 'TemplateContext',19- 'Macro', 'Markup', 'missing', 'concat', 'izip']18+ 'Macro', 'Markup', 'missing', 'concat']19 20 21 # special singleton representing missing values for the runtime22 missing = object()41 unmodified lines64 return self.environment.undefined('there is no parent block '65 'called %r.' % block)66 return SuperBlock(block, self, last)67 69- def get(self, name, default=None):68+ def get(self, key, default=None):69 """For dict compatibility"""71- try:72- return self[name]73- except KeyError:74- return default70+ if key in self.vars:71+ return self.vars[key]72+ if key in self.parent:73+ return self.parent[key]74+ return default75 76- def update(self, mapping):76+ def setdefault(self, key, default=None):77+ """For dict compatibility"""78+ self.exported_vars.add(key)79+ return self.vars.setdefault(key, default)80+81+ def update(self, *args, **kwargs):82 """Update vars from a mapping but don't export them."""83+ d = dict(*args, **kwargs)78- self.vars.update(mapping)84+ self.vars.update(d)85+ self.exported_vars.update(d)86 87 def get_exported(self):88 """Get a new dict with the exported variables."""89 return dict((k, self.vars[k]) for k in self.exported_vars16 unmodified lines106 107 def __getitem__(self, key):108 if key in self.vars:109 return self.vars[key]103- try:110+ if key in self.parent:111 return self.parent[key]105- except KeyError:106- return self.environment.undefined(name=key)112+ return self.environment.undefined(name=key)113 114 def __repr__(self):115 return '<%s %s of %r>' % (116 self.__class__.__name__,190 unmodified lines307 """The default undefined implementation. This undefined implementation308 can be printed and iterated over, but every other access will raise a309 `NameError`. Custom undefined classes must subclass this.310 """311+ __slots__ = ('_undefined_hint', '_undefined_obj', '_undefined_name')312 313 def __init__(self, hint=None, obj=None, name=None):314 self._undefined_hint = hint315 self._undefined_obj = obj1 unmodified line317 318 __add__ = __radd__ = __mul__ = __rmul__ = __div__ = __rdiv__ = \319 __realdiv__ = __rrealdiv__ = __floordiv__ = __rfloordiv__ = \320 __mod__ = __rmod__ = __pos__ = __neg__ = __call__ = \314- __getattr__ = __getitem__ = fail_with_undefined_error321+ __getattr__ = __getitem__ = __lt__ = __le__ = __gt__ = __ge__ = \322+ fail_with_undefined_error323 324 def __str__(self):325 return self.__unicode__().encode('utf-8')326 15 unmodified lines342 343 344 class DebugUndefined(Undefined):345 """An undefined that returns the debug info when printed."""346+ __slots__ = ()347 348 def __unicode__(self):349 if self._undefined_hint is None:350 if self._undefined_obj is None:6 unmodified lines357 358 359 class StrictUndefined(Undefined):360 """An undefined that barks on print and iteration as well as boolean352- tests. In other words: you can do nothing with it except checking if it's353- defined using the `defined` test.361+ tests and all kinds of comparisons. In other words: you can do nothing362+ with it except checking if it's defined using the `defined` test.363 """364+ __slots__ = ()365+ __iter__ = __unicode__ = __len__ = __nonzero__ = __eq__ = __ne__ = \366+ fail_with_undefined_error367 356- __iter__ = __unicode__ = __len__ = __nonzero__ = fail_with_undefined_error368+369+# remove remaining slots attributes, after the metaclass did the magic they370+# are unneeded and irritating as they contain wrong data for the subclasses.371+del Undefined.__slots__, DebugUndefined.__slots__, StrictUndefined.__slots__modified:jinja2/tests.py+35 added-8 removed
46 unmodified lines47 """48 return not isinstance(value, Undefined)49 50 51+def test_undefined(value):52+ """Like `defined` but the other way round."""53+ return isinstance(value, Undefined)54+55+56+def test_none(value):57+ """Return true if the variable is none."""58+ return value is None59+60+61 def test_lower(value):52- """Return true if the variable is lowercase."""62+ """Return true if the variable is lowercased."""63 return unicode(value).islower()64 65 66 def test_upper(value):57- """Return true if the variable is uppercase."""67+ """Return true if the variable is uppercased."""68 return unicode(value).isupper()69 70 61-def test_numeric(value):62- """Return true if the variable is numeric."""63- return isinstance(value, (int, long, float)) or (64- isinstance(value, basestring) and65- number_re.match(value) is not None)71+def test_string(value):72+ """Return true if the object is a string."""73+ return isinstance(value, basestring)74 75 76+def test_number(value):77+ """Return true if the variable is a number."""78+ return isinstance(value, (int, long, float, complex))79+80+81 def test_sequence(value):82 """Return true if the variable is a sequence. Sequences are variables83 that are iterable.84 """17 unmodified lines102 """103 return value is other104 105 106+def test_iterable(value):107+ """Check if it's possible to iterate over an object."""108+ try:109+ iter(value)110+ except TypeError:111+ return False112+ return True113+114+115 TESTS = {116 'odd': test_odd,117 'even': test_even,118 'divisibleby': test_divisibleby,119 'defined': test_defined,120+ 'undefined': test_undefined,121+ 'none': test_none,122 'lower': test_lower,123 'upper': test_upper,100- 'numeric': test_numeric,124+ 'string': test_string,125+ 'number': test_number,126 'sequence': test_sequence,127+ 'iterable': test_iterable,128+ 'callable': callable,129 'sameas': test_sameas130 }modified:tests/test_tests.py+1 added-8 removed
8 unmodified lines9 10 DEFINED = '''{{ missing is defined }}|{{ true is defined }}'''11 EVEN = '''{{ 1 is even }}|{{ 2 is even }}'''12 LOWER = '''{{ "foo" is lower }}|{{ "FOO" is lower }}'''13-NUMERIC = '''{{ "43" is numeric }}|{{ "foo" is numeric }}|\14-{{ 42 is numeric }}'''13 ODD = '''{{ 1 is odd }}|{{ 2 is odd }}'''14 SEQUENCE = '''{{ [1, 2, 3] is sequence }}|\15 {{ "foo" is sequence }}|\16 {{ 42 is sequence }}'''17 UPPER = '''{{ "FOO" is upper }}|{{ "foo" is upper }}'''20-SAMEAS = '''{{ foo is sameas(false) }}|{{ 0 is sameas(false) }}'''18+SAMEAS = '''{{ foo is sameas false }}|{{ 0 is sameas false }}'''19 NOPARENFORARG1 = '''{{ foo is sameas none }}'''20 21 22 def test_defined(env):10 unmodified lines33 tmpl = env.from_string(LOWER)34 assert tmpl.render() == 'True|False'35 36 39-def test_numeric(env):40- tmpl = env.from_string(NUMERIC)41- assert tmpl.render() == 'True|False|True'42-43-37 def test_odd(env):38 tmpl = env.from_string(ODD)39 assert tmpl.render() == 'True|False'40 19 unmodified lines