You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@ambari.apache.org by nc...@apache.org on 2014/09/05 00:36:09 UTC
[30/59] [abbrv] AMBARI-7138. Ambari RPM deals with jinja2 dependency
incorrectly (aonishuk)
http://git-wip-us.apache.org/repos/asf/ambari/blob/658360a5/ambari-common/src/main/python/jinja2/jinja2/testsuite/lexnparse.py
----------------------------------------------------------------------
diff --git a/ambari-common/src/main/python/jinja2/jinja2/testsuite/lexnparse.py b/ambari-common/src/main/python/jinja2/jinja2/testsuite/lexnparse.py
deleted file mode 100644
index 008a0a9..0000000
--- a/ambari-common/src/main/python/jinja2/jinja2/testsuite/lexnparse.py
+++ /dev/null
@@ -1,390 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
- jinja2.testsuite.lexnparse
- ~~~~~~~~~~~~~~~~~~~~~~~~~~
-
- All the unittests regarding lexing, parsing and syntax.
-
- :copyright: (c) 2010 by the Jinja Team.
- :license: BSD, see LICENSE for more details.
-"""
-import os
-import sys
-import time
-import tempfile
-import unittest
-
-from jinja2.testsuite import JinjaTestCase
-
-from jinja2 import Environment, Template, TemplateSyntaxError, \
- UndefinedError, nodes
-
-env = Environment()
-
-
-# how does a string look like in jinja syntax?
-if sys.version_info < (3, 0):
- def jinja_string_repr(string):
- return repr(string)[1:]
-else:
- jinja_string_repr = repr
-
-
-class LexerTestCase(JinjaTestCase):
-
- def test_raw1(self):
- tmpl = env.from_string('{% raw %}foo{% endraw %}|'
- '{%raw%}{{ bar }}|{% baz %}{% endraw %}')
- assert tmpl.render() == 'foo|{{ bar }}|{% baz %}'
-
- def test_raw2(self):
- tmpl = env.from_string('1 {%- raw -%} 2 {%- endraw -%} 3')
- assert tmpl.render() == '123'
-
- def test_balancing(self):
- env = Environment('{%', '%}', '${', '}')
- tmpl = env.from_string('''{% for item in seq
- %}${{'foo': item}|upper}{% endfor %}''')
- assert tmpl.render(seq=range(3)) == "{'FOO': 0}{'FOO': 1}{'FOO': 2}"
-
- def test_comments(self):
- env = Environment('<!--', '-->', '{', '}')
- tmpl = env.from_string('''\
-<ul>
-<!--- for item in seq -->
- <li>{item}</li>
-<!--- endfor -->
-</ul>''')
- assert tmpl.render(seq=range(3)) == ("<ul>\n <li>0</li>\n "
- "<li>1</li>\n <li>2</li>\n</ul>")
-
- def test_string_escapes(self):
- for char in u'\0', u'\u2668', u'\xe4', u'\t', u'\r', u'\n':
- tmpl = env.from_string('{{ %s }}' % jinja_string_repr(char))
- assert tmpl.render() == char
- assert env.from_string('{{ "\N{HOT SPRINGS}" }}').render() == u'\u2668'
-
- def test_bytefallback(self):
- from pprint import pformat
- tmpl = env.from_string(u'''{{ 'foo'|pprint }}|{{ 'bär'|pprint }}''')
- assert tmpl.render() == pformat('foo') + '|' + pformat(u'bär')
-
- def test_operators(self):
- from jinja2.lexer import operators
- for test, expect in operators.iteritems():
- if test in '([{}])':
- continue
- stream = env.lexer.tokenize('{{ %s }}' % test)
- stream.next()
- assert stream.current.type == expect
-
- def test_normalizing(self):
- for seq in '\r', '\r\n', '\n':
- env = Environment(newline_sequence=seq)
- tmpl = env.from_string('1\n2\r\n3\n4\n')
- result = tmpl.render()
- assert result.replace(seq, 'X') == '1X2X3X4'
-
-
-class ParserTestCase(JinjaTestCase):
-
- def test_php_syntax(self):
- env = Environment('<?', '?>', '<?=', '?>', '<!--', '-->')
- tmpl = env.from_string('''\
-<!-- I'm a comment, I'm not interesting -->\
-<? for item in seq -?>
- <?= item ?>
-<?- endfor ?>''')
- assert tmpl.render(seq=range(5)) == '01234'
-
- def test_erb_syntax(self):
- env = Environment('<%', '%>', '<%=', '%>', '<%#', '%>')
- tmpl = env.from_string('''\
-<%# I'm a comment, I'm not interesting %>\
-<% for item in seq -%>
- <%= item %>
-<%- endfor %>''')
- assert tmpl.render(seq=range(5)) == '01234'
-
- def test_comment_syntax(self):
- env = Environment('<!--', '-->', '${', '}', '<!--#', '-->')
- tmpl = env.from_string('''\
-<!--# I'm a comment, I'm not interesting -->\
-<!-- for item in seq --->
- ${item}
-<!--- endfor -->''')
- assert tmpl.render(seq=range(5)) == '01234'
-
- def test_balancing(self):
- tmpl = env.from_string('''{{{'foo':'bar'}.foo}}''')
- assert tmpl.render() == 'bar'
-
- def test_start_comment(self):
- tmpl = env.from_string('''{# foo comment
-and bar comment #}
-{% macro blub() %}foo{% endmacro %}
-{{ blub() }}''')
- assert tmpl.render().strip() == 'foo'
-
- def test_line_syntax(self):
- env = Environment('<%', '%>', '${', '}', '<%#', '%>', '%')
- tmpl = env.from_string('''\
-<%# regular comment %>
-% for item in seq:
- ${item}
-% endfor''')
- assert [int(x.strip()) for x in tmpl.render(seq=range(5)).split()] == \
- range(5)
-
- env = Environment('<%', '%>', '${', '}', '<%#', '%>', '%', '##')
- tmpl = env.from_string('''\
-<%# regular comment %>
-% for item in seq:
- ${item} ## the rest of the stuff
-% endfor''')
- assert [int(x.strip()) for x in tmpl.render(seq=range(5)).split()] == \
- range(5)
-
- def test_line_syntax_priority(self):
- # XXX: why is the whitespace there in front of the newline?
- env = Environment('{%', '%}', '${', '}', '/*', '*/', '##', '#')
- tmpl = env.from_string('''\
-/* ignore me.
- I'm a multiline comment */
-## for item in seq:
-* ${item} # this is just extra stuff
-## endfor''')
- assert tmpl.render(seq=[1, 2]).strip() == '* 1\n* 2'
- env = Environment('{%', '%}', '${', '}', '/*', '*/', '#', '##')
- tmpl = env.from_string('''\
-/* ignore me.
- I'm a multiline comment */
-# for item in seq:
-* ${item} ## this is just extra stuff
- ## extra stuff i just want to ignore
-# endfor''')
- assert tmpl.render(seq=[1, 2]).strip() == '* 1\n\n* 2'
-
- def test_error_messages(self):
- def assert_error(code, expected):
- try:
- Template(code)
- except TemplateSyntaxError, e:
- assert str(e) == expected, 'unexpected error message'
- else:
- assert False, 'that was suposed to be an error'
-
- assert_error('{% for item in seq %}...{% endif %}',
- "Encountered unknown tag 'endif'. Jinja was looking "
- "for the following tags: 'endfor' or 'else'. The "
- "innermost block that needs to be closed is 'for'.")
- assert_error('{% if foo %}{% for item in seq %}...{% endfor %}{% endfor %}',
- "Encountered unknown tag 'endfor'. Jinja was looking for "
- "the following tags: 'elif' or 'else' or 'endif'. The "
- "innermost block that needs to be closed is 'if'.")
- assert_error('{% if foo %}',
- "Unexpected end of template. Jinja was looking for the "
- "following tags: 'elif' or 'else' or 'endif'. The "
- "innermost block that needs to be closed is 'if'.")
- assert_error('{% for item in seq %}',
- "Unexpected end of template. Jinja was looking for the "
- "following tags: 'endfor' or 'else'. The innermost block "
- "that needs to be closed is 'for'.")
- assert_error('{% block foo-bar-baz %}',
- "Block names in Jinja have to be valid Python identifiers "
- "and may not contain hypens, use an underscore instead.")
- assert_error('{% unknown_tag %}',
- "Encountered unknown tag 'unknown_tag'.")
-
-
-class SyntaxTestCase(JinjaTestCase):
-
- def test_call(self):
- env = Environment()
- env.globals['foo'] = lambda a, b, c, e, g: a + b + c + e + g
- tmpl = env.from_string("{{ foo('a', c='d', e='f', *['b'], **{'g': 'h'}) }}")
- assert tmpl.render() == 'abdfh'
-
- def test_slicing(self):
- tmpl = env.from_string('{{ [1, 2, 3][:] }}|{{ [1, 2, 3][::-1] }}')
- assert tmpl.render() == '[1, 2, 3]|[3, 2, 1]'
-
- def test_attr(self):
- tmpl = env.from_string("{{ foo.bar }}|{{ foo['bar'] }}")
- assert tmpl.render(foo={'bar': 42}) == '42|42'
-
- def test_subscript(self):
- tmpl = env.from_string("{{ foo[0] }}|{{ foo[-1] }}")
- assert tmpl.render(foo=[0, 1, 2]) == '0|2'
-
- def test_tuple(self):
- tmpl = env.from_string('{{ () }}|{{ (1,) }}|{{ (1, 2) }}')
- assert tmpl.render() == '()|(1,)|(1, 2)'
-
- def test_math(self):
- tmpl = env.from_string('{{ (1 + 1 * 2) - 3 / 2 }}|{{ 2**3 }}')
- assert tmpl.render() == '1.5|8'
-
- def test_div(self):
- tmpl = env.from_string('{{ 3 // 2 }}|{{ 3 / 2 }}|{{ 3 % 2 }}')
- assert tmpl.render() == '1|1.5|1'
-
- def test_unary(self):
- tmpl = env.from_string('{{ +3 }}|{{ -3 }}')
- assert tmpl.render() == '3|-3'
-
- def test_concat(self):
- tmpl = env.from_string("{{ [1, 2] ~ 'foo' }}")
- assert tmpl.render() == '[1, 2]foo'
-
- def test_compare(self):
- tmpl = env.from_string('{{ 1 > 0 }}|{{ 1 >= 1 }}|{{ 2 < 3 }}|'
- '{{ 2 == 2 }}|{{ 1 <= 1 }}')
- assert tmpl.render() == 'True|True|True|True|True'
-
- def test_inop(self):
- tmpl = env.from_string('{{ 1 in [1, 2, 3] }}|{{ 1 not in [1, 2, 3] }}')
- assert tmpl.render() == 'True|False'
-
- def test_literals(self):
- tmpl = env.from_string('{{ [] }}|{{ {} }}|{{ () }}')
- assert tmpl.render().lower() == '[]|{}|()'
-
- def test_bool(self):
- tmpl = env.from_string('{{ true and false }}|{{ false '
- 'or true }}|{{ not false }}')
- assert tmpl.render() == 'False|True|True'
-
- def test_grouping(self):
- tmpl = env.from_string('{{ (true and false) or (false and true) and not false }}')
- assert tmpl.render() == 'False'
-
- def test_django_attr(self):
- tmpl = env.from_string('{{ [1, 2, 3].0 }}|{{ [[1]].0.0 }}')
- assert tmpl.render() == '1|1'
-
- def test_conditional_expression(self):
- tmpl = env.from_string('''{{ 0 if true else 1 }}''')
- assert tmpl.render() == '0'
-
- def test_short_conditional_expression(self):
- tmpl = env.from_string('<{{ 1 if false }}>')
- assert tmpl.render() == '<>'
-
- tmpl = env.from_string('<{{ (1 if false).bar }}>')
- self.assert_raises(UndefinedError, tmpl.render)
-
- def test_filter_priority(self):
- tmpl = env.from_string('{{ "foo"|upper + "bar"|upper }}')
- assert tmpl.render() == 'FOOBAR'
-
- def test_function_calls(self):
- tests = [
- (True, '*foo, bar'),
- (True, '*foo, *bar'),
- (True, '*foo, bar=42'),
- (True, '**foo, *bar'),
- (True, '**foo, bar'),
- (False, 'foo, bar'),
- (False, 'foo, bar=42'),
- (False, 'foo, bar=23, *args'),
- (False, 'a, b=c, *d, **e'),
- (False, '*foo, **bar')
- ]
- for should_fail, sig in tests:
- if should_fail:
- self.assert_raises(TemplateSyntaxError,
- env.from_string, '{{ foo(%s) }}' % sig)
- else:
- env.from_string('foo(%s)' % sig)
-
- def test_tuple_expr(self):
- for tmpl in [
- '{{ () }}',
- '{{ (1, 2) }}',
- '{{ (1, 2,) }}',
- '{{ 1, }}',
- '{{ 1, 2 }}',
- '{% for foo, bar in seq %}...{% endfor %}',
- '{% for x in foo, bar %}...{% endfor %}',
- '{% for x in foo, %}...{% endfor %}'
- ]:
- assert env.from_string(tmpl)
-
- def test_trailing_comma(self):
- tmpl = env.from_string('{{ (1, 2,) }}|{{ [1, 2,] }}|{{ {1: 2,} }}')
- assert tmpl.render().lower() == '(1, 2)|[1, 2]|{1: 2}'
-
- def test_block_end_name(self):
- env.from_string('{% block foo %}...{% endblock foo %}')
- self.assert_raises(TemplateSyntaxError, env.from_string,
- '{% block x %}{% endblock y %}')
-
- def test_contant_casing(self):
- for const in True, False, None:
- tmpl = env.from_string('{{ %s }}|{{ %s }}|{{ %s }}' % (
- str(const), str(const).lower(), str(const).upper()
- ))
- assert tmpl.render() == '%s|%s|' % (const, const)
-
- def test_test_chaining(self):
- self.assert_raises(TemplateSyntaxError, env.from_string,
- '{{ foo is string is sequence }}')
- env.from_string('{{ 42 is string or 42 is number }}'
- ).render() == 'True'
-
- def test_string_concatenation(self):
- tmpl = env.from_string('{{ "foo" "bar" "baz" }}')
- assert tmpl.render() == 'foobarbaz'
-
- def test_notin(self):
- bar = xrange(100)
- tmpl = env.from_string('''{{ not 42 in bar }}''')
- assert tmpl.render(bar=bar) == unicode(not 42 in bar)
-
- def test_implicit_subscribed_tuple(self):
- class Foo(object):
- def __getitem__(self, x):
- return x
- t = env.from_string('{{ foo[1, 2] }}')
- assert t.render(foo=Foo()) == u'(1, 2)'
-
- def test_raw2(self):
- tmpl = env.from_string('{% raw %}{{ FOO }} and {% BAR %}{% endraw %}')
- assert tmpl.render() == '{{ FOO }} and {% BAR %}'
-
- def test_const(self):
- tmpl = env.from_string('{{ true }}|{{ false }}|{{ none }}|'
- '{{ none is defined }}|{{ missing is defined }}')
- assert tmpl.render() == 'True|False|None|True|False'
-
- def test_neg_filter_priority(self):
- node = env.parse('{{ -1|foo }}')
- assert isinstance(node.body[0].nodes[0], nodes.Filter)
- assert isinstance(node.body[0].nodes[0].node, nodes.Neg)
-
- def test_const_assign(self):
- constass1 = '''{% set true = 42 %}'''
- constass2 = '''{% for none in seq %}{% endfor %}'''
- for tmpl in constass1, constass2:
- self.assert_raises(TemplateSyntaxError, env.from_string, tmpl)
-
- def test_localset(self):
- tmpl = env.from_string('''{% set foo = 0 %}\
-{% for item in [1, 2] %}{% set foo = 1 %}{% endfor %}\
-{{ foo }}''')
- assert tmpl.render() == '0'
-
- def test_parse_unary(self):
- tmpl = env.from_string('{{ -foo["bar"] }}')
- assert tmpl.render(foo={'bar': 42}) == '-42'
- tmpl = env.from_string('{{ -foo["bar"]|abs }}')
- assert tmpl.render(foo={'bar': 42}) == '42'
-
-
-def suite():
- suite = unittest.TestSuite()
- suite.addTest(unittest.makeSuite(LexerTestCase))
- suite.addTest(unittest.makeSuite(ParserTestCase))
- suite.addTest(unittest.makeSuite(SyntaxTestCase))
- return suite
http://git-wip-us.apache.org/repos/asf/ambari/blob/658360a5/ambari-common/src/main/python/jinja2/jinja2/testsuite/loader.py
----------------------------------------------------------------------
diff --git a/ambari-common/src/main/python/jinja2/jinja2/testsuite/loader.py b/ambari-common/src/main/python/jinja2/jinja2/testsuite/loader.py
deleted file mode 100644
index 0ff0d04..0000000
--- a/ambari-common/src/main/python/jinja2/jinja2/testsuite/loader.py
+++ /dev/null
@@ -1,191 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
- jinja2.testsuite.loader
- ~~~~~~~~~~~~~~~~~~~~~~~
-
- Test the loaders.
-
- :copyright: (c) 2010 by the Jinja Team.
- :license: BSD, see LICENSE for more details.
-"""
-import os
-import sys
-import time
-import tempfile
-import shutil
-import unittest
-
-from jinja2.testsuite import JinjaTestCase, dict_loader, \
- package_loader, filesystem_loader, function_loader, \
- choice_loader, prefix_loader
-
-from jinja2 import Environment, loaders
-from jinja2.loaders import split_template_path
-from jinja2.exceptions import TemplateNotFound
-
-
-class LoaderTestCase(JinjaTestCase):
-
- def test_dict_loader(self):
- env = Environment(loader=dict_loader)
- tmpl = env.get_template('justdict.html')
- assert tmpl.render().strip() == 'FOO'
- self.assert_raises(TemplateNotFound, env.get_template, 'missing.html')
-
- def test_package_loader(self):
- env = Environment(loader=package_loader)
- tmpl = env.get_template('test.html')
- assert tmpl.render().strip() == 'BAR'
- self.assert_raises(TemplateNotFound, env.get_template, 'missing.html')
-
- def test_filesystem_loader(self):
- env = Environment(loader=filesystem_loader)
- tmpl = env.get_template('test.html')
- assert tmpl.render().strip() == 'BAR'
- tmpl = env.get_template('foo/test.html')
- assert tmpl.render().strip() == 'FOO'
- self.assert_raises(TemplateNotFound, env.get_template, 'missing.html')
-
- def test_choice_loader(self):
- env = Environment(loader=choice_loader)
- tmpl = env.get_template('justdict.html')
- assert tmpl.render().strip() == 'FOO'
- tmpl = env.get_template('test.html')
- assert tmpl.render().strip() == 'BAR'
- self.assert_raises(TemplateNotFound, env.get_template, 'missing.html')
-
- def test_function_loader(self):
- env = Environment(loader=function_loader)
- tmpl = env.get_template('justfunction.html')
- assert tmpl.render().strip() == 'FOO'
- self.assert_raises(TemplateNotFound, env.get_template, 'missing.html')
-
- def test_prefix_loader(self):
- env = Environment(loader=prefix_loader)
- tmpl = env.get_template('a/test.html')
- assert tmpl.render().strip() == 'BAR'
- tmpl = env.get_template('b/justdict.html')
- assert tmpl.render().strip() == 'FOO'
- self.assert_raises(TemplateNotFound, env.get_template, 'missing')
-
- def test_caching(self):
- changed = False
- class TestLoader(loaders.BaseLoader):
- def get_source(self, environment, template):
- return u'foo', None, lambda: not changed
- env = Environment(loader=TestLoader(), cache_size=-1)
- tmpl = env.get_template('template')
- assert tmpl is env.get_template('template')
- changed = True
- assert tmpl is not env.get_template('template')
- changed = False
-
- env = Environment(loader=TestLoader(), cache_size=0)
- assert env.get_template('template') \
- is not env.get_template('template')
-
- env = Environment(loader=TestLoader(), cache_size=2)
- t1 = env.get_template('one')
- t2 = env.get_template('two')
- assert t2 is env.get_template('two')
- assert t1 is env.get_template('one')
- t3 = env.get_template('three')
- assert 'one' in env.cache
- assert 'two' not in env.cache
- assert 'three' in env.cache
-
- def test_split_template_path(self):
- assert split_template_path('foo/bar') == ['foo', 'bar']
- assert split_template_path('./foo/bar') == ['foo', 'bar']
- self.assert_raises(TemplateNotFound, split_template_path, '../foo')
-
-
-class ModuleLoaderTestCase(JinjaTestCase):
- archive = None
-
- def compile_down(self, zip='deflated', py_compile=False):
- super(ModuleLoaderTestCase, self).setup()
- log = []
- self.reg_env = Environment(loader=prefix_loader)
- if zip is not None:
- self.archive = tempfile.mkstemp(suffix='.zip')[1]
- else:
- self.archive = tempfile.mkdtemp()
- self.reg_env.compile_templates(self.archive, zip=zip,
- log_function=log.append,
- py_compile=py_compile)
- self.mod_env = Environment(loader=loaders.ModuleLoader(self.archive))
- return ''.join(log)
-
- def teardown(self):
- super(ModuleLoaderTestCase, self).teardown()
- if hasattr(self, 'mod_env'):
- if os.path.isfile(self.archive):
- os.remove(self.archive)
- else:
- shutil.rmtree(self.archive)
- self.archive = None
-
- def test_log(self):
- log = self.compile_down()
- assert 'Compiled "a/foo/test.html" as ' \
- 'tmpl_a790caf9d669e39ea4d280d597ec891c4ef0404a' in log
- assert 'Finished compiling templates' in log
- assert 'Could not compile "a/syntaxerror.html": ' \
- 'Encountered unknown tag \'endif\'' in log
-
- def _test_common(self):
- tmpl1 = self.reg_env.get_template('a/test.html')
- tmpl2 = self.mod_env.get_template('a/test.html')
- assert tmpl1.render() == tmpl2.render()
-
- tmpl1 = self.reg_env.get_template('b/justdict.html')
- tmpl2 = self.mod_env.get_template('b/justdict.html')
- assert tmpl1.render() == tmpl2.render()
-
- def test_deflated_zip_compile(self):
- self.compile_down(zip='deflated')
- self._test_common()
-
- def test_stored_zip_compile(self):
- self.compile_down(zip='stored')
- self._test_common()
-
- def test_filesystem_compile(self):
- self.compile_down(zip=None)
- self._test_common()
-
- def test_weak_references(self):
- self.compile_down()
- tmpl = self.mod_env.get_template('a/test.html')
- key = loaders.ModuleLoader.get_template_key('a/test.html')
- name = self.mod_env.loader.module.__name__
-
- assert hasattr(self.mod_env.loader.module, key)
- assert name in sys.modules
-
- # unset all, ensure the module is gone from sys.modules
- self.mod_env = tmpl = None
-
- try:
- import gc
- gc.collect()
- except:
- pass
-
- assert name not in sys.modules
-
- def test_byte_compilation(self):
- log = self.compile_down(py_compile=True)
- assert 'Byte-compiled "a/test.html"' in log
- tmpl1 = self.mod_env.get_template('a/test.html')
- mod = self.mod_env.loader.module. \
- tmpl_3c4ddf650c1a73df961a6d3d2ce2752f1b8fd490
- assert mod.__file__.endswith('.pyc')
-
-
-def suite():
- suite = unittest.TestSuite()
- suite.addTest(unittest.makeSuite(LoaderTestCase))
- suite.addTest(unittest.makeSuite(ModuleLoaderTestCase))
- return suite
http://git-wip-us.apache.org/repos/asf/ambari/blob/658360a5/ambari-common/src/main/python/jinja2/jinja2/testsuite/regression.py
----------------------------------------------------------------------
diff --git a/ambari-common/src/main/python/jinja2/jinja2/testsuite/regression.py b/ambari-common/src/main/python/jinja2/jinja2/testsuite/regression.py
deleted file mode 100644
index a39c3cb..0000000
--- a/ambari-common/src/main/python/jinja2/jinja2/testsuite/regression.py
+++ /dev/null
@@ -1,258 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
- jinja2.testsuite.regression
- ~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
- Tests corner cases and bugs.
-
- :copyright: (c) 2010 by the Jinja Team.
- :license: BSD, see LICENSE for more details.
-"""
-import os
-import time
-import tempfile
-import unittest
-
-from jinja2.testsuite import JinjaTestCase
-
-from jinja2 import Template, Environment, DictLoader, TemplateSyntaxError, \
- TemplateNotFound, PrefixLoader
-
-env = Environment()
-
-
-class CornerTestCase(JinjaTestCase):
-
- def test_assigned_scoping(self):
- t = env.from_string('''
- {%- for item in (1, 2, 3, 4) -%}
- [{{ item }}]
- {%- endfor %}
- {{- item -}}
- ''')
- assert t.render(item=42) == '[1][2][3][4]42'
-
- t = env.from_string('''
- {%- for item in (1, 2, 3, 4) -%}
- [{{ item }}]
- {%- endfor %}
- {%- set item = 42 %}
- {{- item -}}
- ''')
- assert t.render() == '[1][2][3][4]42'
-
- t = env.from_string('''
- {%- set item = 42 %}
- {%- for item in (1, 2, 3, 4) -%}
- [{{ item }}]
- {%- endfor %}
- {{- item -}}
- ''')
- assert t.render() == '[1][2][3][4]42'
-
- def test_closure_scoping(self):
- t = env.from_string('''
- {%- set wrapper = "<FOO>" %}
- {%- for item in (1, 2, 3, 4) %}
- {%- macro wrapper() %}[{{ item }}]{% endmacro %}
- {{- wrapper() }}
- {%- endfor %}
- {{- wrapper -}}
- ''')
- assert t.render() == '[1][2][3][4]<FOO>'
-
- t = env.from_string('''
- {%- for item in (1, 2, 3, 4) %}
- {%- macro wrapper() %}[{{ item }}]{% endmacro %}
- {{- wrapper() }}
- {%- endfor %}
- {%- set wrapper = "<FOO>" %}
- {{- wrapper -}}
- ''')
- assert t.render() == '[1][2][3][4]<FOO>'
-
- t = env.from_string('''
- {%- for item in (1, 2, 3, 4) %}
- {%- macro wrapper() %}[{{ item }}]{% endmacro %}
- {{- wrapper() }}
- {%- endfor %}
- {{- wrapper -}}
- ''')
- assert t.render(wrapper=23) == '[1][2][3][4]23'
-
-
-class BugTestCase(JinjaTestCase):
-
- def test_keyword_folding(self):
- env = Environment()
- env.filters['testing'] = lambda value, some: value + some
- assert env.from_string("{{ 'test'|testing(some='stuff') }}") \
- .render() == 'teststuff'
-
- def test_extends_output_bugs(self):
- env = Environment(loader=DictLoader({
- 'parent.html': '(({% block title %}{% endblock %}))'
- }))
-
- t = env.from_string('{% if expr %}{% extends "parent.html" %}{% endif %}'
- '[[{% block title %}title{% endblock %}]]'
- '{% for item in [1, 2, 3] %}({{ item }}){% endfor %}')
- assert t.render(expr=False) == '[[title]](1)(2)(3)'
- assert t.render(expr=True) == '((title))'
-
- def test_urlize_filter_escaping(self):
- tmpl = env.from_string('{{ "http://www.example.org/<foo"|urlize }}')
- assert tmpl.render() == '<a href="http://www.example.org/<foo">http://www.example.org/<foo</a>'
-
- def test_loop_call_loop(self):
- tmpl = env.from_string('''
-
- {% macro test() %}
- {{ caller() }}
- {% endmacro %}
-
- {% for num1 in range(5) %}
- {% call test() %}
- {% for num2 in range(10) %}
- {{ loop.index }}
- {% endfor %}
- {% endcall %}
- {% endfor %}
-
- ''')
-
- assert tmpl.render().split() == map(unicode, range(1, 11)) * 5
-
- def test_weird_inline_comment(self):
- env = Environment(line_statement_prefix='%')
- self.assert_raises(TemplateSyntaxError, env.from_string,
- '% for item in seq {# missing #}\n...% endfor')
-
- def test_old_macro_loop_scoping_bug(self):
- tmpl = env.from_string('{% for i in (1, 2) %}{{ i }}{% endfor %}'
- '{% macro i() %}3{% endmacro %}{{ i() }}')
- assert tmpl.render() == '123'
-
- def test_partial_conditional_assignments(self):
- tmpl = env.from_string('{% if b %}{% set a = 42 %}{% endif %}{{ a }}')
- assert tmpl.render(a=23) == '23'
- assert tmpl.render(b=True) == '42'
-
- def test_stacked_locals_scoping_bug(self):
- env = Environment(line_statement_prefix='#')
- t = env.from_string('''\
-# for j in [1, 2]:
-# set x = 1
-# for i in [1, 2]:
-# print x
-# if i % 2 == 0:
-# set x = x + 1
-# endif
-# endfor
-# endfor
-# if a
-# print 'A'
-# elif b
-# print 'B'
-# elif c == d
-# print 'C'
-# else
-# print 'D'
-# endif
- ''')
- assert t.render(a=0, b=False, c=42, d=42.0) == '1111C'
-
- def test_stacked_locals_scoping_bug_twoframe(self):
- t = Template('''
- {% set x = 1 %}
- {% for item in foo %}
- {% if item == 1 %}
- {% set x = 2 %}
- {% endif %}
- {% endfor %}
- {{ x }}
- ''')
- rv = t.render(foo=[1]).strip()
- assert rv == u'1'
-
- def test_call_with_args(self):
- t = Template("""{% macro dump_users(users) -%}
- <ul>
- {%- for user in users -%}
- <li><p>{{ user.username|e }}</p>{{ caller(user) }}</li>
- {%- endfor -%}
- </ul>
- {%- endmacro -%}
-
- {% call(user) dump_users(list_of_user) -%}
- <dl>
- <dl>Realname</dl>
- <dd>{{ user.realname|e }}</dd>
- <dl>Description</dl>
- <dd>{{ user.description }}</dd>
- </dl>
- {% endcall %}""")
-
- assert [x.strip() for x in t.render(list_of_user=[{
- 'username':'apo',
- 'realname':'something else',
- 'description':'test'
- }]).splitlines()] == [
- u'<ul><li><p>apo</p><dl>',
- u'<dl>Realname</dl>',
- u'<dd>something else</dd>',
- u'<dl>Description</dl>',
- u'<dd>test</dd>',
- u'</dl>',
- u'</li></ul>'
- ]
-
- def test_empty_if_condition_fails(self):
- self.assert_raises(TemplateSyntaxError, Template, '{% if %}....{% endif %}')
- self.assert_raises(TemplateSyntaxError, Template, '{% if foo %}...{% elif %}...{% endif %}')
- self.assert_raises(TemplateSyntaxError, Template, '{% for x in %}..{% endfor %}')
-
- def test_recursive_loop_bug(self):
- tpl1 = Template("""
- {% for p in foo recursive%}
- {{p.bar}}
- {% for f in p.fields recursive%}
- {{f.baz}}
- {{p.bar}}
- {% if f.rec %}
- {{ loop(f.sub) }}
- {% endif %}
- {% endfor %}
- {% endfor %}
- """)
-
- tpl2 = Template("""
- {% for p in foo%}
- {{p.bar}}
- {% for f in p.fields recursive%}
- {{f.baz}}
- {{p.bar}}
- {% if f.rec %}
- {{ loop(f.sub) }}
- {% endif %}
- {% endfor %}
- {% endfor %}
- """)
-
- def test_correct_prefix_loader_name(self):
- env = Environment(loader=PrefixLoader({
- 'foo': DictLoader({})
- }))
- try:
- env.get_template('foo/bar.html')
- except TemplateNotFound, e:
- assert e.name == 'foo/bar.html'
- else:
- assert False, 'expected error here'
-
-
-def suite():
- suite = unittest.TestSuite()
- suite.addTest(unittest.makeSuite(CornerTestCase))
- suite.addTest(unittest.makeSuite(BugTestCase))
- return suite
http://git-wip-us.apache.org/repos/asf/ambari/blob/658360a5/ambari-common/src/main/python/jinja2/jinja2/testsuite/res/__init__.py
----------------------------------------------------------------------
diff --git a/ambari-common/src/main/python/jinja2/jinja2/testsuite/res/__init__.py b/ambari-common/src/main/python/jinja2/jinja2/testsuite/res/__init__.py
deleted file mode 100644
index e69de29..0000000
http://git-wip-us.apache.org/repos/asf/ambari/blob/658360a5/ambari-common/src/main/python/jinja2/jinja2/testsuite/res/templates/broken.html
----------------------------------------------------------------------
diff --git a/ambari-common/src/main/python/jinja2/jinja2/testsuite/res/templates/broken.html b/ambari-common/src/main/python/jinja2/jinja2/testsuite/res/templates/broken.html
deleted file mode 100644
index 77669fa..0000000
--- a/ambari-common/src/main/python/jinja2/jinja2/testsuite/res/templates/broken.html
+++ /dev/null
@@ -1,3 +0,0 @@
-Before
-{{ fail() }}
-After
http://git-wip-us.apache.org/repos/asf/ambari/blob/658360a5/ambari-common/src/main/python/jinja2/jinja2/testsuite/res/templates/foo/test.html
----------------------------------------------------------------------
diff --git a/ambari-common/src/main/python/jinja2/jinja2/testsuite/res/templates/foo/test.html b/ambari-common/src/main/python/jinja2/jinja2/testsuite/res/templates/foo/test.html
deleted file mode 100644
index b7d6715..0000000
--- a/ambari-common/src/main/python/jinja2/jinja2/testsuite/res/templates/foo/test.html
+++ /dev/null
@@ -1 +0,0 @@
-FOO
http://git-wip-us.apache.org/repos/asf/ambari/blob/658360a5/ambari-common/src/main/python/jinja2/jinja2/testsuite/res/templates/syntaxerror.html
----------------------------------------------------------------------
diff --git a/ambari-common/src/main/python/jinja2/jinja2/testsuite/res/templates/syntaxerror.html b/ambari-common/src/main/python/jinja2/jinja2/testsuite/res/templates/syntaxerror.html
deleted file mode 100644
index f21b817..0000000
--- a/ambari-common/src/main/python/jinja2/jinja2/testsuite/res/templates/syntaxerror.html
+++ /dev/null
@@ -1,4 +0,0 @@
-Foo
-{% for item in broken %}
- ...
-{% endif %}
http://git-wip-us.apache.org/repos/asf/ambari/blob/658360a5/ambari-common/src/main/python/jinja2/jinja2/testsuite/res/templates/test.html
----------------------------------------------------------------------
diff --git a/ambari-common/src/main/python/jinja2/jinja2/testsuite/res/templates/test.html b/ambari-common/src/main/python/jinja2/jinja2/testsuite/res/templates/test.html
deleted file mode 100644
index ba578e4..0000000
--- a/ambari-common/src/main/python/jinja2/jinja2/testsuite/res/templates/test.html
+++ /dev/null
@@ -1 +0,0 @@
-BAR
http://git-wip-us.apache.org/repos/asf/ambari/blob/658360a5/ambari-common/src/main/python/jinja2/jinja2/testsuite/security.py
----------------------------------------------------------------------
diff --git a/ambari-common/src/main/python/jinja2/jinja2/testsuite/security.py b/ambari-common/src/main/python/jinja2/jinja2/testsuite/security.py
deleted file mode 100644
index b2b4cf1..0000000
--- a/ambari-common/src/main/python/jinja2/jinja2/testsuite/security.py
+++ /dev/null
@@ -1,134 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
- jinja2.testsuite.security
- ~~~~~~~~~~~~~~~~~~~~~~~~~
-
- Checks the sandbox and other security features.
-
- :copyright: (c) 2010 by the Jinja Team.
- :license: BSD, see LICENSE for more details.
-"""
-import os
-import time
-import tempfile
-import unittest
-
-from jinja2.testsuite import JinjaTestCase
-
-from jinja2 import Environment
-from jinja2.sandbox import SandboxedEnvironment, \
- ImmutableSandboxedEnvironment, unsafe
-from jinja2 import Markup, escape
-from jinja2.exceptions import SecurityError, TemplateSyntaxError
-
-
-class PrivateStuff(object):
-
- def bar(self):
- return 23
-
- @unsafe
- def foo(self):
- return 42
-
- def __repr__(self):
- return 'PrivateStuff'
-
-
-class PublicStuff(object):
- bar = lambda self: 23
- _foo = lambda self: 42
-
- def __repr__(self):
- return 'PublicStuff'
-
-
-class SandboxTestCase(JinjaTestCase):
-
- def test_unsafe(self):
- env = SandboxedEnvironment()
- self.assert_raises(SecurityError, env.from_string("{{ foo.foo() }}").render,
- foo=PrivateStuff())
- self.assert_equal(env.from_string("{{ foo.bar() }}").render(foo=PrivateStuff()), '23')
-
- self.assert_raises(SecurityError, env.from_string("{{ foo._foo() }}").render,
- foo=PublicStuff())
- self.assert_equal(env.from_string("{{ foo.bar() }}").render(foo=PublicStuff()), '23')
- self.assert_equal(env.from_string("{{ foo.__class__ }}").render(foo=42), '')
- self.assert_equal(env.from_string("{{ foo.func_code }}").render(foo=lambda:None), '')
- self.assert_raises(SecurityError, env.from_string(
- "{{ foo.__class__.__subclasses__() }}").render, foo=42)
-
- def test_immutable_environment(self):
- env = ImmutableSandboxedEnvironment()
- self.assert_raises(SecurityError, env.from_string(
- '{{ [].append(23) }}').render)
- self.assert_raises(SecurityError, env.from_string(
- '{{ {1:2}.clear() }}').render)
-
- def test_restricted(self):
- env = SandboxedEnvironment()
- self.assert_raises(TemplateSyntaxError, env.from_string,
- "{% for item.attribute in seq %}...{% endfor %}")
- self.assert_raises(TemplateSyntaxError, env.from_string,
- "{% for foo, bar.baz in seq %}...{% endfor %}")
-
- def test_markup_operations(self):
- # adding two strings should escape the unsafe one
- unsafe = '<script type="application/x-some-script">alert("foo");</script>'
- safe = Markup('<em>username</em>')
- assert unsafe + safe == unicode(escape(unsafe)) + unicode(safe)
-
- # string interpolations are safe to use too
- assert Markup('<em>%s</em>') % '<bad user>' == \
- '<em><bad user></em>'
- assert Markup('<em>%(username)s</em>') % {
- 'username': '<bad user>'
- } == '<em><bad user></em>'
-
- # an escaped object is markup too
- assert type(Markup('foo') + 'bar') is Markup
-
- # and it implements __html__ by returning itself
- x = Markup("foo")
- assert x.__html__() is x
-
- # it also knows how to treat __html__ objects
- class Foo(object):
- def __html__(self):
- return '<em>awesome</em>'
- def __unicode__(self):
- return 'awesome'
- assert Markup(Foo()) == '<em>awesome</em>'
- assert Markup('<strong>%s</strong>') % Foo() == \
- '<strong><em>awesome</em></strong>'
-
- # escaping and unescaping
- assert escape('"<>&\'') == '"<>&''
- assert Markup("<em>Foo & Bar</em>").striptags() == "Foo & Bar"
- assert Markup("<test>").unescape() == "<test>"
-
-
- def test_template_data(self):
- env = Environment(autoescape=True)
- t = env.from_string('{% macro say_hello(name) %}'
- '<p>Hello {{ name }}!</p>{% endmacro %}'
- '{{ say_hello("<blink>foo</blink>") }}')
- escaped_out = '<p>Hello <blink>foo</blink>!</p>'
- assert t.render() == escaped_out
- assert unicode(t.module) == escaped_out
- assert escape(t.module) == escaped_out
- assert t.module.say_hello('<blink>foo</blink>') == escaped_out
- assert escape(t.module.say_hello('<blink>foo</blink>')) == escaped_out
-
-
- def test_attr_filter(self):
- env = SandboxedEnvironment()
- tmpl = env.from_string('{{ 42|attr("__class__")|attr("__subclasses__")() }}')
- self.assert_raises(SecurityError, tmpl.render)
-
-
-def suite():
- suite = unittest.TestSuite()
- suite.addTest(unittest.makeSuite(SandboxTestCase))
- return suite
http://git-wip-us.apache.org/repos/asf/ambari/blob/658360a5/ambari-common/src/main/python/jinja2/jinja2/testsuite/tests.py
----------------------------------------------------------------------
diff --git a/ambari-common/src/main/python/jinja2/jinja2/testsuite/tests.py b/ambari-common/src/main/python/jinja2/jinja2/testsuite/tests.py
deleted file mode 100644
index cd5006f..0000000
--- a/ambari-common/src/main/python/jinja2/jinja2/testsuite/tests.py
+++ /dev/null
@@ -1,87 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
- jinja2.testsuite.tests
- ~~~~~~~~~~~~~~~~~~~~~~
-
- Who tests the tests?
-
- :copyright: (c) 2010 by the Jinja Team.
- :license: BSD, see LICENSE for more details.
-"""
-import unittest
-from jinja2.testsuite import JinjaTestCase
-
-from jinja2 import Markup, Environment
-
-env = Environment()
-
-
-class TestsTestCase(JinjaTestCase):
-
- def test_defined(self):
- tmpl = env.from_string('{{ missing is defined }}|{{ true is defined }}')
- assert tmpl.render() == 'False|True'
-
- def test_even(self):
- tmpl = env.from_string('''{{ 1 is even }}|{{ 2 is even }}''')
- assert tmpl.render() == 'False|True'
-
- def test_odd(self):
- tmpl = env.from_string('''{{ 1 is odd }}|{{ 2 is odd }}''')
- assert tmpl.render() == 'True|False'
-
- def test_lower(self):
- tmpl = env.from_string('''{{ "foo" is lower }}|{{ "FOO" is lower }}''')
- assert tmpl.render() == 'True|False'
-
- def test_typechecks(self):
- tmpl = env.from_string('''
- {{ 42 is undefined }}
- {{ 42 is defined }}
- {{ 42 is none }}
- {{ none is none }}
- {{ 42 is number }}
- {{ 42 is string }}
- {{ "foo" is string }}
- {{ "foo" is sequence }}
- {{ [1] is sequence }}
- {{ range is callable }}
- {{ 42 is callable }}
- {{ range(5) is iterable }}
- ''')
- assert tmpl.render().split() == [
- 'False', 'True', 'False', 'True', 'True', 'False',
- 'True', 'True', 'True', 'True', 'False', 'True'
- ]
-
- def test_sequence(self):
- tmpl = env.from_string(
- '{{ [1, 2, 3] is sequence }}|'
- '{{ "foo" is sequence }}|'
- '{{ 42 is sequence }}'
- )
- assert tmpl.render() == 'True|True|False'
-
- def test_upper(self):
- tmpl = env.from_string('{{ "FOO" is upper }}|{{ "foo" is upper }}')
- assert tmpl.render() == 'True|False'
-
- def test_sameas(self):
- tmpl = env.from_string('{{ foo is sameas false }}|'
- '{{ 0 is sameas false }}')
- assert tmpl.render(foo=False) == 'True|False'
-
- def test_no_paren_for_arg1(self):
- tmpl = env.from_string('{{ foo is sameas none }}')
- assert tmpl.render(foo=None) == 'True'
-
- def test_escaped(self):
- env = Environment(autoescape=True)
- tmpl = env.from_string('{{ x is escaped }}|{{ y is escaped }}')
- assert tmpl.render(x='foo', y=Markup('foo')) == 'False|True'
-
-
-def suite():
- suite = unittest.TestSuite()
- suite.addTest(unittest.makeSuite(TestsTestCase))
- return suite
http://git-wip-us.apache.org/repos/asf/ambari/blob/658360a5/ambari-common/src/main/python/jinja2/jinja2/testsuite/utils.py
----------------------------------------------------------------------
diff --git a/ambari-common/src/main/python/jinja2/jinja2/testsuite/utils.py b/ambari-common/src/main/python/jinja2/jinja2/testsuite/utils.py
deleted file mode 100644
index a402bbc..0000000
--- a/ambari-common/src/main/python/jinja2/jinja2/testsuite/utils.py
+++ /dev/null
@@ -1,85 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
- jinja2.testsuite.utils
- ~~~~~~~~~~~~~~~~~~~~~~
-
- Tests utilities jinja uses.
-
- :copyright: (c) 2010 by the Jinja Team.
- :license: BSD, see LICENSE for more details.
-"""
-import os
-import gc
-import unittest
-
-import pickle
-
-from jinja2.testsuite import JinjaTestCase
-
-from jinja2 import Environment, Undefined, DebugUndefined, \
- StrictUndefined, UndefinedError, Template, meta
-from jinja2.utils import LRUCache, escape, object_type_repr
-
-
-class LRUCacheTestCase(JinjaTestCase):
-
- def test_simple(self):
- d = LRUCache(3)
- d["a"] = 1
- d["b"] = 2
- d["c"] = 3
- d["a"]
- d["d"] = 4
- assert len(d) == 3
- assert 'a' in d and 'c' in d and 'd' in d and 'b' not in d
-
- def test_pickleable(self):
- cache = LRUCache(2)
- cache["foo"] = 42
- cache["bar"] = 23
- cache["foo"]
-
- for protocol in range(3):
- copy = pickle.loads(pickle.dumps(cache, protocol))
- assert copy.capacity == cache.capacity
- assert copy._mapping == cache._mapping
- assert copy._queue == cache._queue
-
-
-class HelpersTestCase(JinjaTestCase):
-
- def test_object_type_repr(self):
- class X(object):
- pass
- self.assert_equal(object_type_repr(42), 'int object')
- self.assert_equal(object_type_repr([]), 'list object')
- self.assert_equal(object_type_repr(X()),
- 'jinja2.testsuite.utils.X object')
- self.assert_equal(object_type_repr(None), 'None')
- self.assert_equal(object_type_repr(Ellipsis), 'Ellipsis')
-
-
-class MarkupLeakTestCase(JinjaTestCase):
-
- def test_markup_leaks(self):
- counts = set()
- for count in xrange(20):
- for item in xrange(1000):
- escape("foo")
- escape("<foo>")
- escape(u"foo")
- escape(u"<foo>")
- counts.add(len(gc.get_objects()))
- assert len(counts) == 1, 'ouch, c extension seems to leak objects'
-
-
-def suite():
- suite = unittest.TestSuite()
- suite.addTest(unittest.makeSuite(LRUCacheTestCase))
- suite.addTest(unittest.makeSuite(HelpersTestCase))
-
- # this test only tests the c extension
- if not hasattr(escape, 'func_code'):
- suite.addTest(unittest.makeSuite(MarkupLeakTestCase))
-
- return suite
http://git-wip-us.apache.org/repos/asf/ambari/blob/658360a5/ambari-common/src/main/python/jinja2/jinja2/utils.py
----------------------------------------------------------------------
diff --git a/ambari-common/src/main/python/jinja2/jinja2/utils.py b/ambari-common/src/main/python/jinja2/jinja2/utils.py
deleted file mode 100644
index 7b77b8e..0000000
--- a/ambari-common/src/main/python/jinja2/jinja2/utils.py
+++ /dev/null
@@ -1,601 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
- jinja2.utils
- ~~~~~~~~~~~~
-
- Utility functions.
-
- :copyright: (c) 2010 by the Jinja Team.
- :license: BSD, see LICENSE for more details.
-"""
-import re
-import sys
-import errno
-try:
- from thread import allocate_lock
-except ImportError:
- from dummy_thread import allocate_lock
-from collections import deque
-from itertools import imap
-
-
-_word_split_re = re.compile(r'(\s+)')
-_punctuation_re = re.compile(
- '^(?P<lead>(?:%s)*)(?P<middle>.*?)(?P<trail>(?:%s)*)$' % (
- '|'.join(imap(re.escape, ('(', '<', '<'))),
- '|'.join(imap(re.escape, ('.', ',', ')', '>', '\n', '>')))
- )
-)
-_simple_email_re = re.compile(r'^\S+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+$')
-_striptags_re = re.compile(r'(<!--.*?-->|<[^>]*>)')
-_entity_re = re.compile(r'&([^;]+);')
-_letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
-_digits = '0123456789'
-
-# special singleton representing missing values for the runtime
-missing = type('MissingType', (), {'__repr__': lambda x: 'missing'})()
-
-# internal code
-internal_code = set()
-
-
-# concatenate a list of strings and convert them to unicode.
-# unfortunately there is a bug in python 2.4 and lower that causes
-# unicode.join trash the traceback.
-_concat = u''.join
-try:
- def _test_gen_bug():
- raise TypeError(_test_gen_bug)
- yield None
- _concat(_test_gen_bug())
-except TypeError, _error:
- if not _error.args or _error.args[0] is not _test_gen_bug:
- def concat(gen):
- try:
- return _concat(list(gen))
- except:
- # this hack is needed so that the current frame
- # does not show up in the traceback.
- exc_type, exc_value, tb = sys.exc_info()
- raise exc_type, exc_value, tb.tb_next
- else:
- concat = _concat
- del _test_gen_bug, _error
-
-
-# for python 2.x we create outselves a next() function that does the
-# basics without exception catching.
-try:
- next = next
-except NameError:
- def next(x):
- return x.next()
-
-
-# if this python version is unable to deal with unicode filenames
-# when passed to encode we let this function encode it properly.
-# This is used in a couple of places. As far as Jinja is concerned
-# filenames are unicode *or* bytestrings in 2.x and unicode only in
-# 3.x because compile cannot handle bytes
-if sys.version_info < (3, 0):
- def _encode_filename(filename):
- if isinstance(filename, unicode):
- return filename.encode('utf-8')
- return filename
-else:
- def _encode_filename(filename):
- assert filename is None or isinstance(filename, str), \
- 'filenames must be strings'
- return filename
-
-from keyword import iskeyword as is_python_keyword
-
-
-# common types. These do exist in the special types module too which however
-# does not exist in IronPython out of the box. Also that way we don't have
-# to deal with implementation specific stuff here
-class _C(object):
- def method(self): pass
-def _func():
- yield None
-FunctionType = type(_func)
-GeneratorType = type(_func())
-MethodType = type(_C.method)
-CodeType = type(_C.method.func_code)
-try:
- raise TypeError()
-except TypeError:
- _tb = sys.exc_info()[2]
- TracebackType = type(_tb)
- FrameType = type(_tb.tb_frame)
-del _C, _tb, _func
-
-
-def contextfunction(f):
- """This decorator can be used to mark a function or method context callable.
- A context callable is passed the active :class:`Context` as first argument when
- called from the template. This is useful if a function wants to get access
- to the context or functions provided on the context object. For example
- a function that returns a sorted list of template variables the current
- template exports could look like this::
-
- @contextfunction
- def get_exported_names(context):
- return sorted(context.exported_vars)
- """
- f.contextfunction = True
- return f
-
-
-def evalcontextfunction(f):
- """This decoraotr can be used to mark a function or method as an eval
- context callable. This is similar to the :func:`contextfunction`
- but instead of passing the context, an evaluation context object is
- passed. For more information about the eval context, see
- :ref:`eval-context`.
-
- .. versionadded:: 2.4
- """
- f.evalcontextfunction = True
- return f
-
-
-def environmentfunction(f):
- """This decorator can be used to mark a function or method as environment
- callable. This decorator works exactly like the :func:`contextfunction`
- decorator just that the first argument is the active :class:`Environment`
- and not context.
- """
- f.environmentfunction = True
- return f
-
-
-def internalcode(f):
- """Marks the function as internally used"""
- internal_code.add(f.func_code)
- return f
-
-
-def is_undefined(obj):
- """Check if the object passed is undefined. This does nothing more than
- performing an instance check against :class:`Undefined` but looks nicer.
- This can be used for custom filters or tests that want to react to
- undefined variables. For example a custom default filter can look like
- this::
-
- def default(var, default=''):
- if is_undefined(var):
- return default
- return var
- """
- from jinja2.runtime import Undefined
- return isinstance(obj, Undefined)
-
-
-def consume(iterable):
- """Consumes an iterable without doing anything with it."""
- for event in iterable:
- pass
-
-
-def clear_caches():
- """Jinja2 keeps internal caches for environments and lexers. These are
- used so that Jinja2 doesn't have to recreate environments and lexers all
- the time. Normally you don't have to care about that but if you are
- messuring memory consumption you may want to clean the caches.
- """
- from jinja2.environment import _spontaneous_environments
- from jinja2.lexer import _lexer_cache
- _spontaneous_environments.clear()
- _lexer_cache.clear()
-
-
-def import_string(import_name, silent=False):
- """Imports an object based on a string. This use useful if you want to
- use import paths as endpoints or something similar. An import path can
- be specified either in dotted notation (``xml.sax.saxutils.escape``)
- or with a colon as object delimiter (``xml.sax.saxutils:escape``).
-
- If the `silent` is True the return value will be `None` if the import
- fails.
-
- :return: imported object
- """
- try:
- if ':' in import_name:
- module, obj = import_name.split(':', 1)
- elif '.' in import_name:
- items = import_name.split('.')
- module = '.'.join(items[:-1])
- obj = items[-1]
- else:
- return __import__(import_name)
- return getattr(__import__(module, None, None, [obj]), obj)
- except (ImportError, AttributeError):
- if not silent:
- raise
-
-
-def open_if_exists(filename, mode='rb'):
- """Returns a file descriptor for the filename if that file exists,
- otherwise `None`.
- """
- try:
- return open(filename, mode)
- except IOError, e:
- if e.errno not in (errno.ENOENT, errno.EISDIR):
- raise
-
-
-def object_type_repr(obj):
- """Returns the name of the object's type. For some recognized
- singletons the name of the object is returned instead. (For
- example for `None` and `Ellipsis`).
- """
- if obj is None:
- return 'None'
- elif obj is Ellipsis:
- return 'Ellipsis'
- # __builtin__ in 2.x, builtins in 3.x
- if obj.__class__.__module__ in ('__builtin__', 'builtins'):
- name = obj.__class__.__name__
- else:
- name = obj.__class__.__module__ + '.' + obj.__class__.__name__
- return '%s object' % name
-
-
-def pformat(obj, verbose=False):
- """Prettyprint an object. Either use the `pretty` library or the
- builtin `pprint`.
- """
- try:
- from pretty import pretty
- return pretty(obj, verbose=verbose)
- except ImportError:
- from pprint import pformat
- return pformat(obj)
-
-
-def urlize(text, trim_url_limit=None, nofollow=False):
- """Converts any URLs in text into clickable links. Works on http://,
- https:// and www. links. Links can have trailing punctuation (periods,
- commas, close-parens) and leading punctuation (opening parens) and
- it'll still do the right thing.
-
- If trim_url_limit is not None, the URLs in link text will be limited
- to trim_url_limit characters.
-
- If nofollow is True, the URLs in link text will get a rel="nofollow"
- attribute.
- """
- trim_url = lambda x, limit=trim_url_limit: limit is not None \
- and (x[:limit] + (len(x) >=limit and '...'
- or '')) or x
- words = _word_split_re.split(unicode(escape(text)))
- nofollow_attr = nofollow and ' rel="nofollow"' or ''
- for i, word in enumerate(words):
- match = _punctuation_re.match(word)
- if match:
- lead, middle, trail = match.groups()
- if middle.startswith('www.') or (
- '@' not in middle and
- not middle.startswith('http://') and
- len(middle) > 0 and
- middle[0] in _letters + _digits and (
- middle.endswith('.org') or
- middle.endswith('.net') or
- middle.endswith('.com')
- )):
- middle = '<a href="http://%s"%s>%s</a>' % (middle,
- nofollow_attr, trim_url(middle))
- if middle.startswith('http://') or \
- middle.startswith('https://'):
- middle = '<a href="%s"%s>%s</a>' % (middle,
- nofollow_attr, trim_url(middle))
- if '@' in middle and not middle.startswith('www.') and \
- not ':' in middle and _simple_email_re.match(middle):
- middle = '<a href="mailto:%s">%s</a>' % (middle, middle)
- if lead + middle + trail != word:
- words[i] = lead + middle + trail
- return u''.join(words)
-
-
-def generate_lorem_ipsum(n=5, html=True, min=20, max=100):
- """Generate some lorem impsum for the template."""
- from jinja2.constants import LOREM_IPSUM_WORDS
- from random import choice, randrange
- words = LOREM_IPSUM_WORDS.split()
- result = []
-
- for _ in xrange(n):
- next_capitalized = True
- last_comma = last_fullstop = 0
- word = None
- last = None
- p = []
-
- # each paragraph contains out of 20 to 100 words.
- for idx, _ in enumerate(xrange(randrange(min, max))):
- while True:
- word = choice(words)
- if word != last:
- last = word
- break
- if next_capitalized:
- word = word.capitalize()
- next_capitalized = False
- # add commas
- if idx - randrange(3, 8) > last_comma:
- last_comma = idx
- last_fullstop += 2
- word += ','
- # add end of sentences
- if idx - randrange(10, 20) > last_fullstop:
- last_comma = last_fullstop = idx
- word += '.'
- next_capitalized = True
- p.append(word)
-
- # ensure that the paragraph ends with a dot.
- p = u' '.join(p)
- if p.endswith(','):
- p = p[:-1] + '.'
- elif not p.endswith('.'):
- p += '.'
- result.append(p)
-
- if not html:
- return u'\n\n'.join(result)
- return Markup(u'\n'.join(u'<p>%s</p>' % escape(x) for x in result))
-
-
-class LRUCache(object):
- """A simple LRU Cache implementation."""
-
- # this is fast for small capacities (something below 1000) but doesn't
- # scale. But as long as it's only used as storage for templates this
- # won't do any harm.
-
- def __init__(self, capacity):
- self.capacity = capacity
- self._mapping = {}
- self._queue = deque()
- self._postinit()
-
- def _postinit(self):
- # alias all queue methods for faster lookup
- self._popleft = self._queue.popleft
- self._pop = self._queue.pop
- if hasattr(self._queue, 'remove'):
- self._remove = self._queue.remove
- self._wlock = allocate_lock()
- self._append = self._queue.append
-
- def _remove(self, obj):
- """Python 2.4 compatibility."""
- for idx, item in enumerate(self._queue):
- if item == obj:
- del self._queue[idx]
- break
-
- def __getstate__(self):
- return {
- 'capacity': self.capacity,
- '_mapping': self._mapping,
- '_queue': self._queue
- }
-
- def __setstate__(self, d):
- self.__dict__.update(d)
- self._postinit()
-
- def __getnewargs__(self):
- return (self.capacity,)
-
- def copy(self):
- """Return an shallow copy of the instance."""
- rv = self.__class__(self.capacity)
- rv._mapping.update(self._mapping)
- rv._queue = deque(self._queue)
- return rv
-
- def get(self, key, default=None):
- """Return an item from the cache dict or `default`"""
- try:
- return self[key]
- except KeyError:
- return default
-
- def setdefault(self, key, default=None):
- """Set `default` if the key is not in the cache otherwise
- leave unchanged. Return the value of this key.
- """
- try:
- return self[key]
- except KeyError:
- self[key] = default
- return default
-
- def clear(self):
- """Clear the cache."""
- self._wlock.acquire()
- try:
- self._mapping.clear()
- self._queue.clear()
- finally:
- self._wlock.release()
-
- def __contains__(self, key):
- """Check if a key exists in this cache."""
- return key in self._mapping
-
- def __len__(self):
- """Return the current size of the cache."""
- return len(self._mapping)
-
- def __repr__(self):
- return '<%s %r>' % (
- self.__class__.__name__,
- self._mapping
- )
-
- def __getitem__(self, key):
- """Get an item from the cache. Moves the item up so that it has the
- highest priority then.
-
- Raise an `KeyError` if it does not exist.
- """
- rv = self._mapping[key]
- if self._queue[-1] != key:
- try:
- self._remove(key)
- except ValueError:
- # if something removed the key from the container
- # when we read, ignore the ValueError that we would
- # get otherwise.
- pass
- self._append(key)
- return rv
-
- def __setitem__(self, key, value):
- """Sets the value for an item. Moves the item up so that it
- has the highest priority then.
- """
- self._wlock.acquire()
- try:
- if key in self._mapping:
- try:
- self._remove(key)
- except ValueError:
- # __getitem__ is not locked, it might happen
- pass
- elif len(self._mapping) == self.capacity:
- del self._mapping[self._popleft()]
- self._append(key)
- self._mapping[key] = value
- finally:
- self._wlock.release()
-
- def __delitem__(self, key):
- """Remove an item from the cache dict.
- Raise an `KeyError` if it does not exist.
- """
- self._wlock.acquire()
- try:
- del self._mapping[key]
- try:
- self._remove(key)
- except ValueError:
- # __getitem__ is not locked, it might happen
- pass
- finally:
- self._wlock.release()
-
- def items(self):
- """Return a list of items."""
- result = [(key, self._mapping[key]) for key in list(self._queue)]
- result.reverse()
- return result
-
- def iteritems(self):
- """Iterate over all items."""
- return iter(self.items())
-
- def values(self):
- """Return a list of all values."""
- return [x[1] for x in self.items()]
-
- def itervalue(self):
- """Iterate over all values."""
- return iter(self.values())
-
- def keys(self):
- """Return a list of all keys ordered by most recent usage."""
- return list(self)
-
- def iterkeys(self):
- """Iterate over all keys in the cache dict, ordered by
- the most recent usage.
- """
- return reversed(tuple(self._queue))
-
- __iter__ = iterkeys
-
- def __reversed__(self):
- """Iterate over the values in the cache dict, oldest items
- coming first.
- """
- return iter(tuple(self._queue))
-
- __copy__ = copy
-
-
-# register the LRU cache as mutable mapping if possible
-try:
- from collections import MutableMapping
- MutableMapping.register(LRUCache)
-except ImportError:
- pass
-
-
-class Cycler(object):
- """A cycle helper for templates."""
-
- def __init__(self, *items):
- if not items:
- raise RuntimeError('at least one item has to be provided')
- self.items = items
- self.reset()
-
- def reset(self):
- """Resets the cycle."""
- self.pos = 0
-
- @property
- def current(self):
- """Returns the current item."""
- return self.items[self.pos]
-
- def next(self):
- """Goes one item ahead and returns it."""
- rv = self.current
- self.pos = (self.pos + 1) % len(self.items)
- return rv
-
-
-class Joiner(object):
- """A joining helper for templates."""
-
- def __init__(self, sep=u', '):
- self.sep = sep
- self.used = False
-
- def __call__(self):
- if not self.used:
- self.used = True
- return u''
- return self.sep
-
-
-# try markupsafe first, if that fails go with Jinja2's bundled version
-# of markupsafe. Markupsafe was previously Jinja2's implementation of
-# the Markup object but was moved into a separate package in a patchleve
-# release
-try:
- from markupsafe import Markup, escape, soft_unicode
-except ImportError:
- from jinja2._markupsafe import Markup, escape, soft_unicode
-
-
-# partials
-try:
- from functools import partial
-except ImportError:
- class partial(object):
- def __init__(self, _func, *args, **kwargs):
- self._func = _func
- self._args = args
- self._kwargs = kwargs
- def __call__(self, *args, **kwargs):
- kwargs.update(self._kwargs)
- return self._func(*(self._args + args), **kwargs)
http://git-wip-us.apache.org/repos/asf/ambari/blob/658360a5/ambari-common/src/main/python/jinja2/jinja2/visitor.py
----------------------------------------------------------------------
diff --git a/ambari-common/src/main/python/jinja2/jinja2/visitor.py b/ambari-common/src/main/python/jinja2/jinja2/visitor.py
deleted file mode 100644
index 413e7c3..0000000
--- a/ambari-common/src/main/python/jinja2/jinja2/visitor.py
+++ /dev/null
@@ -1,87 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
- jinja2.visitor
- ~~~~~~~~~~~~~~
-
- This module implements a visitor for the nodes.
-
- :copyright: (c) 2010 by the Jinja Team.
- :license: BSD.
-"""
-from jinja2.nodes import Node
-
-
-class NodeVisitor(object):
- """Walks the abstract syntax tree and call visitor functions for every
- node found. The visitor functions may return values which will be
- forwarded by the `visit` method.
-
- Per default the visitor functions for the nodes are ``'visit_'`` +
- class name of the node. So a `TryFinally` node visit function would
- be `visit_TryFinally`. This behavior can be changed by overriding
- the `get_visitor` function. If no visitor function exists for a node
- (return value `None`) the `generic_visit` visitor is used instead.
- """
-
- def get_visitor(self, node):
- """Return the visitor function for this node or `None` if no visitor
- exists for this node. In that case the generic visit function is
- used instead.
- """
- method = 'visit_' + node.__class__.__name__
- return getattr(self, method, None)
-
- def visit(self, node, *args, **kwargs):
- """Visit a node."""
- f = self.get_visitor(node)
- if f is not None:
- return f(node, *args, **kwargs)
- return self.generic_visit(node, *args, **kwargs)
-
- def generic_visit(self, node, *args, **kwargs):
- """Called if no explicit visitor function exists for a node."""
- for node in node.iter_child_nodes():
- self.visit(node, *args, **kwargs)
-
-
-class NodeTransformer(NodeVisitor):
- """Walks the abstract syntax tree and allows modifications of nodes.
-
- The `NodeTransformer` will walk the AST and use the return value of the
- visitor functions to replace or remove the old node. If the return
- value of the visitor function is `None` the node will be removed
- from the previous location otherwise it's replaced with the return
- value. The return value may be the original node in which case no
- replacement takes place.
- """
-
- def generic_visit(self, node, *args, **kwargs):
- for field, old_value in node.iter_fields():
- if isinstance(old_value, list):
- new_values = []
- for value in old_value:
- if isinstance(value, Node):
- value = self.visit(value, *args, **kwargs)
- if value is None:
- continue
- elif not isinstance(value, Node):
- new_values.extend(value)
- continue
- new_values.append(value)
- old_value[:] = new_values
- elif isinstance(old_value, Node):
- new_node = self.visit(old_value, *args, **kwargs)
- if new_node is None:
- delattr(node, field)
- else:
- setattr(node, field, new_node)
- return node
-
- def visit_list(self, node, *args, **kwargs):
- """As transformers may return lists in some places this method
- can be used to enforce a list as return value.
- """
- rv = self.visit(node, *args, **kwargs)
- if not isinstance(rv, list):
- rv = [rv]
- return rv
http://git-wip-us.apache.org/repos/asf/ambari/blob/658360a5/ambari-common/src/main/python/jinja2/scripts/pylintrc
----------------------------------------------------------------------
diff --git a/ambari-common/src/main/python/jinja2/scripts/pylintrc b/ambari-common/src/main/python/jinja2/scripts/pylintrc
deleted file mode 100644
index 4f85b49..0000000
--- a/ambari-common/src/main/python/jinja2/scripts/pylintrc
+++ /dev/null
@@ -1,301 +0,0 @@
-# lint Python modules using external checkers.
-#
-# This is the main checker controling the other ones and the reports
-# generation. It is itself both a raw checker and an astng checker in order
-# to:
-# * handle message activation / deactivation at the module level
-# * handle some basic but necessary stats'data (number of classes, methods...)
-#
-[MASTER]
-
-# Specify a configuration file.
-#rcfile=
-
-# Profiled execution.
-profile=no
-
-# Add <file or directory> to the black list. It should be a base name, not a
-# path. You may set this option multiple times.
-ignore=.svn
-
-# Pickle collected data for later comparisons.
-persistent=yes
-
-# Set the cache size for astng objects.
-cache-size=500
-
-# List of plugins (as comma separated values of python modules names) to load,
-# usually to register additional checkers.
-load-plugins=
-
-
-[MESSAGES CONTROL]
-
-# Enable only checker(s) with the given id(s). This option conflict with the
-# disable-checker option
-#enable-checker=
-
-# Enable all checker(s) except those with the given id(s). This option conflict
-# with the disable-checker option
-#disable-checker=
-
-# Enable all messages in the listed categories.
-#enable-msg-cat=
-
-# Disable all messages in the listed categories.
-#disable-msg-cat=
-
-# Enable the message(s) with the given id(s).
-#enable-msg=
-
-# Disable the message(s) with the given id(s).
-disable-msg=C0323,W0142,C0301,C0103,C0111,E0213,C0302,C0203,W0703,R0201
-
-
-[REPORTS]
-
-# set the output format. Available formats are text, parseable, colorized and
-# html
-output-format=colorized
-
-# Include message's id in output
-include-ids=yes
-
-# Put messages in a separate file for each module / package specified on the
-# command line instead of printing them on stdout. Reports (if any) will be
-# written in a file name "pylint_global.[txt|html]".
-files-output=no
-
-# Tells wether to display a full report or only the messages
-reports=yes
-
-# Python expression which should return a note less than 10 (10 is the highest
-# note).You have access to the variables errors warning, statement which
-# respectivly contain the number of errors / warnings messages and the total
-# number of statements analyzed. This is used by the global evaluation report
-# (R0004).
-evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10)
-
-# Add a comment according to your evaluation note. This is used by the global
-# evaluation report (R0004).
-comment=no
-
-# Enable the report(s) with the given id(s).
-#enable-report=
-
-# Disable the report(s) with the given id(s).
-#disable-report=
-
-
-# checks for
-# * unused variables / imports
-# * undefined variables
-# * redefinition of variable from builtins or from an outer scope
-# * use of variable before assigment
-#
-[VARIABLES]
-
-# Tells wether we should check for unused import in __init__ files.
-init-import=no
-
-# A regular expression matching names used for dummy variables (i.e. not used).
-dummy-variables-rgx=_|dummy
-
-# List of additional names supposed to be defined in builtins. Remember that
-# you should avoid to define new builtins when possible.
-additional-builtins=
-
-
-# try to find bugs in the code using type inference
-#
-[TYPECHECK]
-
-# Tells wether missing members accessed in mixin class should be ignored. A
-# mixin class is detected if its name ends with "mixin" (case insensitive).
-ignore-mixin-members=yes
-
-# When zope mode is activated, consider the acquired-members option to ignore
-# access to some undefined attributes.
-zope=no
-
-# List of members which are usually get through zope's acquisition mecanism and
-# so shouldn't trigger E0201 when accessed (need zope=yes to be considered).
-acquired-members=REQUEST,acl_users,aq_parent
-
-
-# checks for :
-# * doc strings
-# * modules / classes / functions / methods / arguments / variables name
-# * number of arguments, local variables, branchs, returns and statements in
-# functions, methods
-# * required module attributes
-# * dangerous default values as arguments
-# * redefinition of function / method / class
-# * uses of the global statement
-#
-[BASIC]
-
-# Required attributes for module, separated by a comma
-required-attributes=
-
-# Regular expression which should only match functions or classes name which do
-# not require a docstring
-no-docstring-rgx=__.*__
-
-# Regular expression which should only match correct module names
-module-rgx=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$
-
-# Regular expression which should only match correct module level names
-const-rgx=(([A-Z_][A-Z1-9_]*)|(__.*__))$
-
-# Regular expression which should only match correct class names
-class-rgx=[A-Z_][a-zA-Z0-9]+$
-
-# Regular expression which should only match correct function names
-function-rgx=[a-z_][a-z0-9_]*$
-
-# Regular expression which should only match correct method names
-method-rgx=[a-z_][a-z0-9_]*$
-
-# Regular expression which should only match correct instance attribute names
-attr-rgx=[a-z_][a-z0-9_]*$
-
-# Regular expression which should only match correct argument names
-argument-rgx=[a-z_][a-z0-9_]*$
-
-# Regular expression which should only match correct variable names
-variable-rgx=[a-z_][a-z0-9_]*$
-
-# Regular expression which should only match correct list comprehension /
-# generator expression variable names
-inlinevar-rgx=[A-Za-z_][A-Za-z0-9_]*$
-
-# Good variable names which should always be accepted, separated by a comma
-good-names=i,j,k,ex,Run,_
-
-# Bad variable names which should always be refused, separated by a comma
-bad-names=foo,bar,baz,toto,tutu,tata
-
-# List of builtins function names that should not be used, separated by a comma
-bad-functions=apply,input
-
-
-# checks for sign of poor/misdesign:
-# * number of methods, attributes, local variables...
-# * size, complexity of functions, methods
-#
-[DESIGN]
-
-# Maximum number of arguments for function / method
-max-args=12
-
-# Maximum number of locals for function / method body
-max-locals=30
-
-# Maximum number of return / yield for function / method body
-max-returns=12
-
-# Maximum number of branch for function / method body
-max-branchs=30
-
-# Maximum number of statements in function / method body
-max-statements=60
-
-# Maximum number of parents for a class (see R0901).
-max-parents=7
-
-# Maximum number of attributes for a class (see R0902).
-max-attributes=20
-
-# Minimum number of public methods for a class (see R0903).
-min-public-methods=0
-
-# Maximum number of public methods for a class (see R0904).
-max-public-methods=20
-
-
-# checks for
-# * external modules dependencies
-# * relative / wildcard imports
-# * cyclic imports
-# * uses of deprecated modules
-#
-[IMPORTS]
-
-# Deprecated modules which should not be used, separated by a comma
-deprecated-modules=regsub,string,TERMIOS,Bastion,rexec
-
-# Create a graph of every (i.e. internal and external) dependencies in the
-# given file (report R0402 must not be disabled)
-import-graph=
-
-# Create a graph of external dependencies in the given file (report R0402 must
-# not be disabled)
-ext-import-graph=
-
-# Create a graph of internal dependencies in the given file (report R0402 must
-# not be disabled)
-int-import-graph=
-
-
-# checks for :
-# * methods without self as first argument
-# * overridden methods signature
-# * access only to existant members via self
-# * attributes not defined in the __init__ method
-# * supported interfaces implementation
-# * unreachable code
-#
-[CLASSES]
-
-# List of interface methods to ignore, separated by a comma. This is used for
-# instance to not check methods defines in Zope's Interface base class.
-ignore-iface-methods=isImplementedBy,deferred,extends,names,namesAndDescriptions,queryDescriptionFor,getBases,getDescriptionFor,getDoc,getName,getTaggedValue,getTaggedValueTags,isEqualOrExtendedBy,setTaggedValue,isImplementedByInstancesOf,adaptWith,is_implemented_by
-
-# List of method names used to declare (i.e. assign) instance attributes.
-defining-attr-methods=__init__,__new__,setUp
-
-
-# checks for similarities and duplicated code. This computation may be
-# memory / CPU intensive, so you should disable it if you experiments some
-# problems.
-#
-[SIMILARITIES]
-
-# Minimum lines number of a similarity.
-min-similarity-lines=10
-
-# Ignore comments when computing similarities.
-ignore-comments=yes
-
-# Ignore docstrings when computing similarities.
-ignore-docstrings=yes
-
-
-# checks for:
-# * warning notes in the code like FIXME, XXX
-# * PEP 263: source code with non ascii character but no encoding declaration
-#
-[MISCELLANEOUS]
-
-# List of note tags to take in consideration, separated by a comma.
-notes=FIXME,XXX,TODO
-
-
-# checks for :
-# * unauthorized constructions
-# * strict indentation
-# * line length
-# * use of <> instead of !=
-#
-[FORMAT]
-
-# Maximum number of characters on a single line.
-max-line-length=90
-
-# Maximum number of lines in a module
-max-module-lines=1000
-
-# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1
-# tab).
-indent-string=' '
http://git-wip-us.apache.org/repos/asf/ambari/blob/658360a5/ambari-common/src/main/python/jinja2/setup.cfg
----------------------------------------------------------------------
diff --git a/ambari-common/src/main/python/jinja2/setup.cfg b/ambari-common/src/main/python/jinja2/setup.cfg
deleted file mode 100644
index 2d74c58..0000000
--- a/ambari-common/src/main/python/jinja2/setup.cfg
+++ /dev/null
@@ -1,6 +0,0 @@
-[egg_info]
-tag_build = dev
-tag_date = true
-
-[aliases]
-release = egg_info -RDb ''
http://git-wip-us.apache.org/repos/asf/ambari/blob/658360a5/ambari-common/src/main/python/jinja2/setup.py
----------------------------------------------------------------------
diff --git a/ambari-common/src/main/python/jinja2/setup.py b/ambari-common/src/main/python/jinja2/setup.py
deleted file mode 100644
index 7956d19..0000000
--- a/ambari-common/src/main/python/jinja2/setup.py
+++ /dev/null
@@ -1,110 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
-Jinja2
-~~~~~~
-
-Jinja2 is a template engine written in pure Python. It provides a
-`Django`_ inspired non-XML syntax but supports inline expressions and
-an optional `sandboxed`_ environment.
-
-Nutshell
---------
-
-Here a small example of a Jinja template::
-
- {% extends 'base.html' %}
- {% block title %}Memberlist{% endblock %}
- {% block content %}
- <ul>
- {% for user in users %}
- <li><a href="{{ user.url }}">{{ user.username }}</a></li>
- {% endfor %}
- </ul>
- {% endblock %}
-
-Philosophy
-----------
-
-Application logic is for the controller but don't try to make the life
-for the template designer too hard by giving him too few functionality.
-
-For more informations visit the new `Jinja2 webpage`_ and `documentation`_.
-
-.. _sandboxed: http://en.wikipedia.org/wiki/Sandbox_(computer_security)
-.. _Django: http://www.djangoproject.com/
-.. _Jinja2 webpage: http://jinja.pocoo.org/
-.. _documentation: http://jinja.pocoo.org/2/documentation/
-"""
-import sys
-
-from setuptools import setup, Extension, Feature
-
-debugsupport = Feature(
- 'optional C debug support',
- standard=False,
- ext_modules = [
- Extension('jinja2._debugsupport', ['jinja2/_debugsupport.c']),
- ],
-)
-
-
-# tell distribute to use 2to3 with our own fixers.
-extra = {}
-if sys.version_info >= (3, 0):
- extra.update(
- use_2to3=True,
- use_2to3_fixers=['custom_fixers']
- )
-
-# ignore the old '--with-speedups' flag
-try:
- speedups_pos = sys.argv.index('--with-speedups')
-except ValueError:
- pass
-else:
- sys.argv[speedups_pos] = '--with-debugsupport'
- sys.stderr.write('*' * 74 + '\n')
- sys.stderr.write('WARNING:\n')
- sys.stderr.write(' the --with-speedups flag is deprecated, assuming '
- '--with-debugsupport\n')
- sys.stderr.write(' For the actual speedups install the MarkupSafe '
- 'package.\n')
- sys.stderr.write('*' * 74 + '\n')
-
-
-setup(
- name='Jinja2',
- version='2.5.5',
- url='http://jinja.pocoo.org/',
- license='BSD',
- author='Armin Ronacher',
- author_email='armin.ronacher@active-4.com',
- description='A small but fast and easy to use stand-alone template '
- 'engine written in pure python.',
- long_description=__doc__,
- # jinja is egg safe. But we hate eggs
- zip_safe=False,
- classifiers=[
- 'Development Status :: 5 - Production/Stable',
- 'Environment :: Web Environment',
- 'Intended Audience :: Developers',
- 'License :: OSI Approved :: BSD License',
- 'Operating System :: OS Independent',
- 'Programming Language :: Python',
- 'Programming Language :: Python :: 3',
- 'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
- 'Topic :: Software Development :: Libraries :: Python Modules',
- 'Topic :: Text Processing :: Markup :: HTML'
- ],
- packages=['jinja2', 'jinja2.testsuite', 'jinja2.testsuite.res',
- 'jinja2._markupsafe'],
- extras_require={'i18n': ['Babel>=0.8']},
- test_suite='jinja2.testsuite.suite',
- include_package_data=True,
- entry_points="""
- [babel.extractors]
- jinja2 = jinja2.ext:babel_extract[i18n]
- """,
- features={'debugsupport': debugsupport},
- **extra
-)
http://git-wip-us.apache.org/repos/asf/ambari/blob/658360a5/ambari-common/src/main/python/resource_management/core/source.py
----------------------------------------------------------------------
diff --git a/ambari-common/src/main/python/resource_management/core/source.py b/ambari-common/src/main/python/resource_management/core/source.py
index c2a4c24..22e1c6d 100644
--- a/ambari-common/src/main/python/resource_management/core/source.py
+++ b/ambari-common/src/main/python/resource_management/core/source.py
@@ -72,7 +72,7 @@ class StaticFile(Source):
try:
- from jinja2 import Environment as JinjaEnvironment, BaseLoader, TemplateNotFound, FunctionLoader, StrictUndefined
+ from ambari_jinja2 import Environment as JinjaEnvironment, BaseLoader, TemplateNotFound, FunctionLoader, StrictUndefined
except ImportError:
class Template(Source):
def __init__(self, name, variables=None, env=None):
http://git-wip-us.apache.org/repos/asf/ambari/blob/658360a5/ambari-server/pom.xml
----------------------------------------------------------------------
diff --git a/ambari-server/pom.xml b/ambari-server/pom.xml
index d7d2491..e6c2546 100644
--- a/ambari-server/pom.xml
+++ b/ambari-server/pom.xml
@@ -955,7 +955,7 @@
<argument>${custom.tests}</argument>
</arguments>
<environmentVariables>
- <PYTHONPATH>${project.basedir}/../ambari-common/src/main/python:${project.basedir}/../ambari-agent/src/main/python:${project.basedir}/../ambari-common/src/main/python/jinja2:${project.basedir}/../ambari-common/src/main/python/ambari_commons:${project.basedir}/../ambari-common/src/test/python:${project.basedir}/src/main/python:${project.basedir}/src/main/python/ambari-server-state:${project.basedir}/src/test/python:$PYTHONPATH</PYTHONPATH>
+ <PYTHONPATH>${project.basedir}/../ambari-common/src/main/python:${project.basedir}/../ambari-agent/src/main/python:${project.basedir}/../ambari-common/src/main/python/ambari_jinja2:${project.basedir}/../ambari-common/src/main/python/ambari_commons:${project.basedir}/../ambari-common/src/test/python:${project.basedir}/src/main/python:${project.basedir}/src/main/python/ambari-server-state:${project.basedir}/src/test/python:$PYTHONPATH</PYTHONPATH>
</environmentVariables>
<skip>${skipTests}</skip>
</configuration>
http://git-wip-us.apache.org/repos/asf/ambari/blob/658360a5/ambari-server/src/test/python/unitTests.py
----------------------------------------------------------------------
diff --git a/ambari-server/src/test/python/unitTests.py b/ambari-server/src/test/python/unitTests.py
index ab99cce..773a698 100644
--- a/ambari-server/src/test/python/unitTests.py
+++ b/ambari-server/src/test/python/unitTests.py
@@ -117,7 +117,7 @@ def main():
ambari_agent_folder = os.path.join(ambari_server_folder,"../ambari-agent")
ambari_common_folder = os.path.join(ambari_server_folder,"../ambari-common")
sys.path.append(ambari_common_folder + "/src/main/python")
- sys.path.append(ambari_common_folder + "/src/main/python/jinja2")
+ sys.path.append(ambari_common_folder + "/src/main/python/ambari_jinja2")
sys.path.append(ambari_common_folder + "/src/main/python")
sys.path.append(ambari_common_folder + "/src/test/python")
sys.path.append(ambari_agent_folder + "/src/main/python")
http://git-wip-us.apache.org/repos/asf/ambari/blob/658360a5/pom.xml
----------------------------------------------------------------------
diff --git a/pom.xml b/pom.xml
index bf62fd2..cb47889 100644
--- a/pom.xml
+++ b/pom.xml
@@ -184,6 +184,7 @@
<!--IDE and GIT files-->
<exclude>.idea/</exclude>
<exclude>.git/</exclude>
+ <exclude>.pydevproject</exclude>
<exclude>**/.gitignore</exclude>
<exclude>**/.gitattributes</exclude>
<exclude>**/.gitkeep</exclude>
@@ -204,6 +205,7 @@
<!--Python Mock library (BSD license)-->
<exclude>ambari-common/src/test/python/mock/**</exclude>
<!--Jinja2 library (BSD license)-->
+ <exclude>ambari-common/src/main/python/ambari_jinja2/**</exclude>
<exclude>ambari-common/src/main/python/jinja2/**</exclude>
<!--Contributions-->