Skip to content
Myr

Down to 7 failures for Python 3. We're onto something.

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 acbd408 · Browse files · 8 files+77 added−34 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

8 files+77 added−34 removed

  • other:+77 added−34 removed

8 files+77 added−34 removed

added:custom_fixers/fix_broken_reraising.py+21 added
1from lib2to3 import fixer_base, pytree2from lib2to3.fixer_util import Name, BlankLine, Name, Attr, ArgList345class FixBrokenReraising(fixer_base.BaseFix):6 PATTERN = """7 raise_stmt< 'raise' any ',' val=any ',' tb=any >8 """910 # run before the broken 2to3 checker with the same goal11 # tries to rewrite it with a rule that does not work out for jinja12 run_order = 11314 def transform(self, node, results):15 tb = results['tb'].clone()16 tb.prefix = ''17 with_tb = Attr(results['val'].clone(), Name('with_traceback')) + \18 [ArgList([tb])]19 new = pytree.Node(self.syms.simple_stmt, [Name("raise")] + with_tb)20 new.prefix = node.prefix21 return new
modified:jinja2/testsuite/ext.py+12 added-7 removed
15 unmodified lines
16from jinja2 import Environment, DictLoader, contextfunction, nodes17from jinja2.exceptions import TemplateAssertionError18from jinja2.ext import Extension19from jinja2.lexer import Token, count_newlines20from jinja2.utils import next2122# 2.x / 3.x23try:24 from io import BytesIO25except ImportError:26 from StringIO import StringIO as BytesIO272829importable_object = 233031_gettext_re = re.compile(r'_\((.*?)\)(?s)')32
54 unmodified lines
87 nodes.EnvironmentAttribute('sandboxed'),88 self.attr('ext_attr'),89 nodes.ImportedName(__name__ + '.importable_object'),90 nodes.ContextReference()84 ])]).set_lineno(parser.stream.next().lineno)91 ])]).set_lineno(next(parser.stream).lineno)9293 def _dump(self, sandboxed, ext_attr, imported_object, context):94 return '%s|%s|%s|%s' % (95 sandboxed,
132 unmodified lines
228 assert tmpl.render(LANGUAGE='de', user_count=5) == 'Benutzer: 5'229230 def test_extract(self):231 from jinja2.ext import babel_extract225 from StringIO import StringIO226 source = StringIO('''232 source = BytesIO('''233 {{ gettext('Hello World') }}234 {% trans %}Hello World{% endtrans %}235 {% trans %}{{ users }} user{% pluralize %}{{ users }} users{% endtrans %}230 ''')236 '''.encode('ascii')) # make python 3 happy237 assert list(babel_extract(source, ('gettext', 'ngettext', '_'), [], {})) == [238 (2, 'gettext', u'Hello World', []),239 (3, 'gettext', u'Hello World', []),240 (4, 'ngettext', (u'%(users)s user', u'%(users)s users', None), [])241 ]242243 def test_comment_extract(self):244 from jinja2.ext import babel_extract239 from StringIO import StringIO240 source = StringIO('''245 source = BytesIO('''246 {# trans first #}247 {{ gettext('Hello World') }}248 {% trans %}Hello World{% endtrans %}{# trans second #}249 {#: third #}250 {% trans %}{{ users }} user{% pluralize %}{{ users }} users{% endtrans %}246 ''')251 '''.encode('utf-8')) # make python 3 happy252 assert list(babel_extract(source, ('gettext', 'ngettext', '_'), ['trans', ':'], {})) == [253 (3, 'gettext', u'Hello World', ['first']),254 (4, 'gettext', u'Hello World', ['second']),255 (6, 'ngettext', (u'%(users)s user', u'%(users)s users', None), ['third'])
8 unmodified lines
modified:jinja2/compiler.py+9 added-1 removed
34 unmodified lines
35else:36 have_condexpr = True373839# what method to iterate over items do we want to use for dict iteration40# in generated code? on 2.x let's go with iteritems, on 3.x with items41if hasattr(dict, 'iteritems'):42 dict_item_iter = 'iteritems'43else:44 dict_item_iter = 'items'454647def generate(node, environment, name, filename, stream=None):48 """Generate the python source for a node tree."""49 if not isinstance(node, nodes.Template):50 raise TypeError('Can\'t compile non template nodes')
823 unmodified lines
874 self.writeline('parent_template = environment.get_template(', node)875 self.visit(node.template, frame)876 self.write(', %r)' % self.name)877 self.writeline('for name, parent_block in parent_template.'870 'blocks.iteritems():')878 'blocks.%s():' % dict_item_iter)879 self.indent()880 self.writeline('context.blocks.setdefault(name, []).'881 'append(parent_block)')882 self.outdent()
675 unmodified lines
modified:jinja2/environment.py+4 added-6 removed
17 unmodified lines
18from jinja2.runtime import Undefined, new_context19from jinja2.exceptions import TemplateSyntaxError, TemplateNotFound, \20 TemplatesNotFound21from jinja2.utils import import_string, LRUCache, Markup, missing, \22 concat, consume, internalcode22 concat, consume, internalcode, _encode_filename232425# for direct template usage we have up to ten living environments26_spontaneous_environments = LRUCache(10)
347 unmodified lines
374 self.handle_exception(exc_info, source_hint=source)375376 def _parse(self, source, name, filename):377 """Internal parsing function used by `parse` and `compile`."""378 if isinstance(filename, unicode):379 filename = filename.encode('utf-8')380 return Parser(self, source, name, filename).parse()378 return Parser(self, source, name, _encode_filename(filename)).parse()379380 def lex(self, source, name=None, filename=None):381 """Lex the given sourcecode and return a generator that yields382 tokens as tuples in the form ``(lineno, token_type, value)``.
56 unmodified lines
439 if raw:440 return source441 if filename is None:442 filename = '<template>'445 elif isinstance(filename, unicode):446 filename = filename.encode('utf-8')443 else:444 filename = _encode_filename(filename)445 return compile(source, filename, 'exec')446 except TemplateSyntaxError:447 exc_info = sys.exc_info()448 self.handle_exception(exc_info, source_hint=source)
484 unmodified lines
modified:jinja2/exceptions.py+1 added-1 removed
90 unmodified lines
91 # it override at runtime.92 def __unicode__(self):93 # for translated errors we only return the message94 if self.translated:95 return self.message.encode('utf-8')95 return self.message9697 # otherwise attach some stuff98 location = 'line %d' % self.lineno99 name = self.filename or self.name
44 unmodified lines
modified:jinja2/lexer.py+2 added-1 removed
528 unmodified lines
529 msg = str(e).split(':')[-1].strip()530 raise TemplateSyntaxError(msg, lineno, name, filename)531 # if we can express it as bytestring (ascii only)532 # we do that for support of semi broken APIs533 # as datetime.datetime.strftime533 # as datetime.datetime.strftime. On python 3 this534 # call becomes a noop thanks to 2to3535 try:536 value = str(value)537 except UnicodeError:538 pass
142 unmodified lines
modified:jinja2/nodes.py+9 added-4 removed
492 unmodified lines
493494 def as_const(self, obj=None):495 if self.node is obj is None:496 raise Impossible()497 # we have to be careful here because we call filter_ below.498 # if this variable would be called filter, 2to3 would wrap the499 # call in a list beause it is assuming we are talking about the500 # builtin filter function here which no longer returns a list in501 # python 3. because of that, do not rename filter_ to filter!497 filter = self.environment.filters.get(self.name)498 if filter is None or getattr(filter, 'contextfilter', False):502 filter_ = self.environment.filters.get(self.name)503 if filter_ is None or getattr(filter_, 'contextfilter', False):504 raise Impossible()505 if obj is None:506 obj = self.node.as_const()507 args = [x.as_const() for x in self.args]503 if getattr(filter, 'environmentfilter', False):508 if getattr(filter_, 'environmentfilter', False):509 args.insert(0, self.environment)510 kwargs = dict(x.as_const() for x in self.kwargs)511 if self.dyn_args is not None:512 try:
5 unmodified lines
518 kwargs.update(self.dyn_kwargs.as_const())519 except:520 raise Impossible()521 try:517 return filter(obj, *args, **kwargs)522 return filter_(obj, *args, **kwargs)523 except:524 raise Impossible()525526
270 unmodified lines
modified:jinja2/utils.py+19 added-14 removed
70 unmodified lines
71 def next(x):72 return x.next()737475# ironpython without stdlib doesn't have keyword76try:77 from keyword import iskeyword as is_python_keyword78except ImportError:79 _py_identifier_re = re.compile(r'^[a-zA-Z_][a-zA-Z0-9]*$')80 def is_python_keyword(name):81 if _py_identifier_re.search(name) is None:82 return False83 try:84 exec name + " = 42"85 except SyntaxError:86 return False87 return True75# if this python version is unable to deal with unicode filenames76# when passed to encode we let this function encode it properly.77# This is used in a couple of places. As far as Jinja is concerned78# filenames are unicode *or* bytestrings in 2.x and unicode only in79# 3.x because compile cannot handle bytes80if sys.version_info < (3, 0):81 def _encode_filename(filename):82 if isinstance(filename, unicode):83 return filename.encode('utf-8')84 return filename85else:86 def _encode_filename(filename):87 assert filename is None or isinstance(filename, str), \88 'filenames must be strings'89 return filename9091from keyword import iskeyword as is_python_keyword929394# common types. These do exist in the special types module too which however91# does not exist in IronPython out of the box.95# does not exist in IronPython out of the box. Also that way we don't have96# to deal with implementation specific stuff here97class _C(object):98 def method(self): pass99def _func():100 yield None
689 unmodified lines