Skip to content
Myr

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

6 files+91 added−52 removed

modified:jinja2/compiler.py+5 added-2 removed
676 unmodified lines
677 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)687688 def visit_FromImport(self, node, frame):689 """Visit named imports."""690 self.newline(node)
14 unmodified lines
705 (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)711712 def visit_For(self, node, frame):713 loop_frame = frame.inner()714 loop_frame.inspect(node.iter_child_nodes(exclude=('iter',)))
442 unmodified lines
modified:jinja2/environment.py+18 added-13 removed
236 unmodified lines
237 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)242243 def make_globals(self, d):244 """Return a dict for the globals."""245 if d is None:
138 unmodified lines
384 return [tuple(map(int, x.split('='))) for x in385 self._debug_info.split('&')]386387 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)393394395class 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 """400401 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.name405402 __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))408409 def __str__(self):410 return unicode(self).encode('utf-8')411412 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)418419420class TemplateStream(object):421 """This class wraps a generator returned from `Template.generate` so that
50 unmodified lines
modified:jinja2/exceptions.py+1 added-5 removed
34 unmodified lines
35 self.lineno = lineno36 self.name = name373839class TemplateAssertionError(AssertionError, TemplateSyntaxError):39class 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 """4445 def __init__(self, message, lineno, name):46 AssertionError.__init__(self, message)47 TemplateSyntaxError.__init__(self, message, lineno, name)454946class 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 lines
8 :copyright: Copyright 2008 by Armin Ronacher.9 :license: GNU GPL.10"""11from types import FunctionType12from itertools import izip12from jinja2.utils import Markup, partial13from jinja2.exceptions import UndefinedError141516# these variables are exported to the template runtime17__all__ = ['LoopContext', 'StaticLoopContext', 'TemplateContext',19 'Macro', 'Markup', 'missing', 'concat', 'izip']18 'Macro', 'Markup', 'missing', 'concat']192021# special singleton representing missing values for the runtime22missing = object()
41 unmodified lines
64 return self.environment.undefined('there is no parent block '65 'called %r.' % block)66 return SuperBlock(block, self, last)6769 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 default7576 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)8081 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)8687 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_vars
16 unmodified lines
106107 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)113114 def __repr__(self):115 return '<%s %s of %r>' % (116 self.__class__.__name__,
190 unmodified lines
307 """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')312313 def __init__(self, hint=None, obj=None, name=None):314 self._undefined_hint = hint315 self._undefined_obj = obj
1 unmodified line
317318 __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_error323324 def __str__(self):325 return self.__unicode__().encode('utf-8')326
15 unmodified lines
342343344class DebugUndefined(Undefined):345 """An undefined that returns the debug info when printed."""346 __slots__ = ()347348 def __unicode__(self):349 if self._undefined_hint is None:350 if self._undefined_obj is None:
6 unmodified lines
357358359class 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_error367356 __iter__ = __unicode__ = __len__ = __nonzero__ = fail_with_undefined_error368369# remove remaining slots attributes, after the metaclass did the magic they370# are unneeded and irritating as they contain wrong data for the subclasses.371del Undefined.__slots__, DebugUndefined.__slots__, StrictUndefined.__slots__
modified:jinja2/tests.py+35 added-8 removed
46 unmodified lines
47 """48 return not isinstance(value, Undefined)495051def test_undefined(value):52 """Like `defined` but the other way round."""53 return isinstance(value, Undefined)545556def test_none(value):57 """Return true if the variable is none."""58 return value is None596061def test_lower(value):52 """Return true if the variable is lowercase."""62 """Return true if the variable is lowercased."""63 return unicode(value).islower()646566def test_upper(value):57 """Return true if the variable is uppercase."""67 """Return true if the variable is uppercased."""68 return unicode(value).isupper()697061def 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)71def test_string(value):72 """Return true if the object is a string."""73 return isinstance(value, basestring)747576def test_number(value):77 """Return true if the variable is a number."""78 return isinstance(value, (int, long, float, complex))798081def test_sequence(value):82 """Return true if the variable is a sequence. Sequences are variables83 that are iterable.84 """
17 unmodified lines
102 """103 return value is other104105106def 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 True113114115TESTS = {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 lines
910DEFINED = '''{{ missing is defined }}|{{ true is defined }}'''11EVEN = '''{{ 1 is even }}|{{ 2 is even }}'''12LOWER = '''{{ "foo" is lower }}|{{ "FOO" is lower }}'''13NUMERIC = '''{{ "43" is numeric }}|{{ "foo" is numeric }}|\14{{ 42 is numeric }}'''13ODD = '''{{ 1 is odd }}|{{ 2 is odd }}'''14SEQUENCE = '''{{ [1, 2, 3] is sequence }}|\15{{ "foo" is sequence }}|\16{{ 42 is sequence }}'''17UPPER = '''{{ "FOO" is upper }}|{{ "foo" is upper }}'''20SAMEAS = '''{{ foo is sameas(false) }}|{{ 0 is sameas(false) }}'''18SAMEAS = '''{{ foo is sameas false }}|{{ 0 is sameas false }}'''19NOPARENFORARG1 = '''{{ foo is sameas none }}'''202122def test_defined(env):
10 unmodified lines
33 tmpl = env.from_string(LOWER)34 assert tmpl.render() == 'True|False'353639def test_numeric(env):40 tmpl = env.from_string(NUMERIC)41 assert tmpl.render() == 'True|False|True'424337def test_odd(env):38 tmpl = env.from_string(ODD)39 assert tmpl.render() == 'True|False'40
19 unmodified lines