PageRenderTime 44ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 0ms

/test/rql_test/connections/http_support/jinja2/testsuite/ext.py

https://gitlab.com/Mashamba/rethinkdb
Python | 459 lines | 415 code | 34 blank | 10 comment | 11 complexity | 4b64acf2cc6ed8feb646af0f9486211f MD5 | raw file
  1. # -*- coding: utf-8 -*-
  2. """
  3. jinja2.testsuite.ext
  4. ~~~~~~~~~~~~~~~~~~~~
  5. Tests for the extensions.
  6. :copyright: (c) 2010 by the Jinja Team.
  7. :license: BSD, see LICENSE for more details.
  8. """
  9. import re
  10. import unittest
  11. from jinja2.testsuite import JinjaTestCase
  12. from jinja2 import Environment, DictLoader, contextfunction, nodes
  13. from jinja2.exceptions import TemplateAssertionError
  14. from jinja2.ext import Extension
  15. from jinja2.lexer import Token, count_newlines
  16. from jinja2._compat import next, BytesIO, itervalues, text_type
  17. importable_object = 23
  18. _gettext_re = re.compile(r'_\((.*?)\)(?s)')
  19. i18n_templates = {
  20. 'master.html': '<title>{{ page_title|default(_("missing")) }}</title>'
  21. '{% block body %}{% endblock %}',
  22. 'child.html': '{% extends "master.html" %}{% block body %}'
  23. '{% trans %}watch out{% endtrans %}{% endblock %}',
  24. 'plural.html': '{% trans user_count %}One user online{% pluralize %}'
  25. '{{ user_count }} users online{% endtrans %}',
  26. 'plural2.html': '{% trans user_count=get_user_count() %}{{ user_count }}s'
  27. '{% pluralize %}{{ user_count }}p{% endtrans %}',
  28. 'stringformat.html': '{{ _("User: %(num)s")|format(num=user_count) }}'
  29. }
  30. newstyle_i18n_templates = {
  31. 'master.html': '<title>{{ page_title|default(_("missing")) }}</title>'
  32. '{% block body %}{% endblock %}',
  33. 'child.html': '{% extends "master.html" %}{% block body %}'
  34. '{% trans %}watch out{% endtrans %}{% endblock %}',
  35. 'plural.html': '{% trans user_count %}One user online{% pluralize %}'
  36. '{{ user_count }} users online{% endtrans %}',
  37. 'stringformat.html': '{{ _("User: %(num)s", num=user_count) }}',
  38. 'ngettext.html': '{{ ngettext("%(num)s apple", "%(num)s apples", apples) }}',
  39. 'ngettext_long.html': '{% trans num=apples %}{{ num }} apple{% pluralize %}'
  40. '{{ num }} apples{% endtrans %}',
  41. 'transvars1.html': '{% trans %}User: {{ num }}{% endtrans %}',
  42. 'transvars2.html': '{% trans num=count %}User: {{ num }}{% endtrans %}',
  43. 'transvars3.html': '{% trans count=num %}User: {{ count }}{% endtrans %}',
  44. 'novars.html': '{% trans %}%(hello)s{% endtrans %}',
  45. 'vars.html': '{% trans %}{{ foo }}%(foo)s{% endtrans %}',
  46. 'explicitvars.html': '{% trans foo="42" %}%(foo)s{% endtrans %}'
  47. }
  48. languages = {
  49. 'de': {
  50. 'missing': u'fehlend',
  51. 'watch out': u'pass auf',
  52. 'One user online': u'Ein Benutzer online',
  53. '%(user_count)s users online': u'%(user_count)s Benutzer online',
  54. 'User: %(num)s': u'Benutzer: %(num)s',
  55. 'User: %(count)s': u'Benutzer: %(count)s',
  56. '%(num)s apple': u'%(num)s Apfel',
  57. '%(num)s apples': u'%(num)s Äpfel'
  58. }
  59. }
  60. @contextfunction
  61. def gettext(context, string):
  62. language = context.get('LANGUAGE', 'en')
  63. return languages.get(language, {}).get(string, string)
  64. @contextfunction
  65. def ngettext(context, s, p, n):
  66. language = context.get('LANGUAGE', 'en')
  67. if n != 1:
  68. return languages.get(language, {}).get(p, p)
  69. return languages.get(language, {}).get(s, s)
  70. i18n_env = Environment(
  71. loader=DictLoader(i18n_templates),
  72. extensions=['jinja2.ext.i18n']
  73. )
  74. i18n_env.globals.update({
  75. '_': gettext,
  76. 'gettext': gettext,
  77. 'ngettext': ngettext
  78. })
  79. newstyle_i18n_env = Environment(
  80. loader=DictLoader(newstyle_i18n_templates),
  81. extensions=['jinja2.ext.i18n']
  82. )
  83. newstyle_i18n_env.install_gettext_callables(gettext, ngettext, newstyle=True)
  84. class TestExtension(Extension):
  85. tags = set(['test'])
  86. ext_attr = 42
  87. def parse(self, parser):
  88. return nodes.Output([self.call_method('_dump', [
  89. nodes.EnvironmentAttribute('sandboxed'),
  90. self.attr('ext_attr'),
  91. nodes.ImportedName(__name__ + '.importable_object'),
  92. nodes.ContextReference()
  93. ])]).set_lineno(next(parser.stream).lineno)
  94. def _dump(self, sandboxed, ext_attr, imported_object, context):
  95. return '%s|%s|%s|%s' % (
  96. sandboxed,
  97. ext_attr,
  98. imported_object,
  99. context.blocks
  100. )
  101. class PreprocessorExtension(Extension):
  102. def preprocess(self, source, name, filename=None):
  103. return source.replace('[[TEST]]', '({{ foo }})')
  104. class StreamFilterExtension(Extension):
  105. def filter_stream(self, stream):
  106. for token in stream:
  107. if token.type == 'data':
  108. for t in self.interpolate(token):
  109. yield t
  110. else:
  111. yield token
  112. def interpolate(self, token):
  113. pos = 0
  114. end = len(token.value)
  115. lineno = token.lineno
  116. while 1:
  117. match = _gettext_re.search(token.value, pos)
  118. if match is None:
  119. break
  120. value = token.value[pos:match.start()]
  121. if value:
  122. yield Token(lineno, 'data', value)
  123. lineno += count_newlines(token.value)
  124. yield Token(lineno, 'variable_begin', None)
  125. yield Token(lineno, 'name', 'gettext')
  126. yield Token(lineno, 'lparen', None)
  127. yield Token(lineno, 'string', match.group(1))
  128. yield Token(lineno, 'rparen', None)
  129. yield Token(lineno, 'variable_end', None)
  130. pos = match.end()
  131. if pos < end:
  132. yield Token(lineno, 'data', token.value[pos:])
  133. class ExtensionsTestCase(JinjaTestCase):
  134. def test_extend_late(self):
  135. env = Environment()
  136. env.add_extension('jinja2.ext.autoescape')
  137. t = env.from_string('{% autoescape true %}{{ "<test>" }}{% endautoescape %}')
  138. assert t.render() == '&lt;test&gt;'
  139. def test_loop_controls(self):
  140. env = Environment(extensions=['jinja2.ext.loopcontrols'])
  141. tmpl = env.from_string('''
  142. {%- for item in [1, 2, 3, 4] %}
  143. {%- if item % 2 == 0 %}{% continue %}{% endif -%}
  144. {{ item }}
  145. {%- endfor %}''')
  146. assert tmpl.render() == '13'
  147. tmpl = env.from_string('''
  148. {%- for item in [1, 2, 3, 4] %}
  149. {%- if item > 2 %}{% break %}{% endif -%}
  150. {{ item }}
  151. {%- endfor %}''')
  152. assert tmpl.render() == '12'
  153. def test_do(self):
  154. env = Environment(extensions=['jinja2.ext.do'])
  155. tmpl = env.from_string('''
  156. {%- set items = [] %}
  157. {%- for char in "foo" %}
  158. {%- do items.append(loop.index0 ~ char) %}
  159. {%- endfor %}{{ items|join(', ') }}''')
  160. assert tmpl.render() == '0f, 1o, 2o'
  161. def test_with(self):
  162. env = Environment(extensions=['jinja2.ext.with_'])
  163. tmpl = env.from_string('''\
  164. {% with a=42, b=23 -%}
  165. {{ a }} = {{ b }}
  166. {% endwith -%}
  167. {{ a }} = {{ b }}\
  168. ''')
  169. assert [x.strip() for x in tmpl.render(a=1, b=2).splitlines()] \
  170. == ['42 = 23', '1 = 2']
  171. def test_extension_nodes(self):
  172. env = Environment(extensions=[TestExtension])
  173. tmpl = env.from_string('{% test %}')
  174. assert tmpl.render() == 'False|42|23|{}'
  175. def test_identifier(self):
  176. assert TestExtension.identifier == __name__ + '.TestExtension'
  177. def test_rebinding(self):
  178. original = Environment(extensions=[TestExtension])
  179. overlay = original.overlay()
  180. for env in original, overlay:
  181. for ext in itervalues(env.extensions):
  182. assert ext.environment is env
  183. def test_preprocessor_extension(self):
  184. env = Environment(extensions=[PreprocessorExtension])
  185. tmpl = env.from_string('{[[TEST]]}')
  186. assert tmpl.render(foo=42) == '{(42)}'
  187. def test_streamfilter_extension(self):
  188. env = Environment(extensions=[StreamFilterExtension])
  189. env.globals['gettext'] = lambda x: x.upper()
  190. tmpl = env.from_string('Foo _(bar) Baz')
  191. out = tmpl.render()
  192. assert out == 'Foo BAR Baz'
  193. def test_extension_ordering(self):
  194. class T1(Extension):
  195. priority = 1
  196. class T2(Extension):
  197. priority = 2
  198. env = Environment(extensions=[T1, T2])
  199. ext = list(env.iter_extensions())
  200. assert ext[0].__class__ is T1
  201. assert ext[1].__class__ is T2
  202. class InternationalizationTestCase(JinjaTestCase):
  203. def test_trans(self):
  204. tmpl = i18n_env.get_template('child.html')
  205. assert tmpl.render(LANGUAGE='de') == '<title>fehlend</title>pass auf'
  206. def test_trans_plural(self):
  207. tmpl = i18n_env.get_template('plural.html')
  208. assert tmpl.render(LANGUAGE='de', user_count=1) == 'Ein Benutzer online'
  209. assert tmpl.render(LANGUAGE='de', user_count=2) == '2 Benutzer online'
  210. def test_trans_plural_with_functions(self):
  211. tmpl = i18n_env.get_template('plural2.html')
  212. def get_user_count():
  213. get_user_count.called += 1
  214. return 1
  215. get_user_count.called = 0
  216. assert tmpl.render(LANGUAGE='de', get_user_count=get_user_count) == '1s'
  217. assert get_user_count.called == 1
  218. def test_complex_plural(self):
  219. tmpl = i18n_env.from_string('{% trans foo=42, count=2 %}{{ count }} item{% '
  220. 'pluralize count %}{{ count }} items{% endtrans %}')
  221. assert tmpl.render() == '2 items'
  222. self.assert_raises(TemplateAssertionError, i18n_env.from_string,
  223. '{% trans foo %}...{% pluralize bar %}...{% endtrans %}')
  224. def test_trans_stringformatting(self):
  225. tmpl = i18n_env.get_template('stringformat.html')
  226. assert tmpl.render(LANGUAGE='de', user_count=5) == 'Benutzer: 5'
  227. def test_extract(self):
  228. from jinja2.ext import babel_extract
  229. source = BytesIO('''
  230. {{ gettext('Hello World') }}
  231. {% trans %}Hello World{% endtrans %}
  232. {% trans %}{{ users }} user{% pluralize %}{{ users }} users{% endtrans %}
  233. '''.encode('ascii')) # make python 3 happy
  234. assert list(babel_extract(source, ('gettext', 'ngettext', '_'), [], {})) == [
  235. (2, 'gettext', u'Hello World', []),
  236. (3, 'gettext', u'Hello World', []),
  237. (4, 'ngettext', (u'%(users)s user', u'%(users)s users', None), [])
  238. ]
  239. def test_comment_extract(self):
  240. from jinja2.ext import babel_extract
  241. source = BytesIO('''
  242. {# trans first #}
  243. {{ gettext('Hello World') }}
  244. {% trans %}Hello World{% endtrans %}{# trans second #}
  245. {#: third #}
  246. {% trans %}{{ users }} user{% pluralize %}{{ users }} users{% endtrans %}
  247. '''.encode('utf-8')) # make python 3 happy
  248. assert list(babel_extract(source, ('gettext', 'ngettext', '_'), ['trans', ':'], {})) == [
  249. (3, 'gettext', u'Hello World', ['first']),
  250. (4, 'gettext', u'Hello World', ['second']),
  251. (6, 'ngettext', (u'%(users)s user', u'%(users)s users', None), ['third'])
  252. ]
  253. class NewstyleInternationalizationTestCase(JinjaTestCase):
  254. def test_trans(self):
  255. tmpl = newstyle_i18n_env.get_template('child.html')
  256. assert tmpl.render(LANGUAGE='de') == '<title>fehlend</title>pass auf'
  257. def test_trans_plural(self):
  258. tmpl = newstyle_i18n_env.get_template('plural.html')
  259. assert tmpl.render(LANGUAGE='de', user_count=1) == 'Ein Benutzer online'
  260. assert tmpl.render(LANGUAGE='de', user_count=2) == '2 Benutzer online'
  261. def test_complex_plural(self):
  262. tmpl = newstyle_i18n_env.from_string('{% trans foo=42, count=2 %}{{ count }} item{% '
  263. 'pluralize count %}{{ count }} items{% endtrans %}')
  264. assert tmpl.render() == '2 items'
  265. self.assert_raises(TemplateAssertionError, i18n_env.from_string,
  266. '{% trans foo %}...{% pluralize bar %}...{% endtrans %}')
  267. def test_trans_stringformatting(self):
  268. tmpl = newstyle_i18n_env.get_template('stringformat.html')
  269. assert tmpl.render(LANGUAGE='de', user_count=5) == 'Benutzer: 5'
  270. def test_newstyle_plural(self):
  271. tmpl = newstyle_i18n_env.get_template('ngettext.html')
  272. assert tmpl.render(LANGUAGE='de', apples=1) == '1 Apfel'
  273. assert tmpl.render(LANGUAGE='de', apples=5) == u'5 Äpfel'
  274. def test_autoescape_support(self):
  275. env = Environment(extensions=['jinja2.ext.autoescape',
  276. 'jinja2.ext.i18n'])
  277. env.install_gettext_callables(lambda x: u'<strong>Wert: %(name)s</strong>',
  278. lambda s, p, n: s, newstyle=True)
  279. t = env.from_string('{% autoescape ae %}{{ gettext("foo", name='
  280. '"<test>") }}{% endautoescape %}')
  281. assert t.render(ae=True) == '<strong>Wert: &lt;test&gt;</strong>'
  282. assert t.render(ae=False) == '<strong>Wert: <test></strong>'
  283. def test_num_used_twice(self):
  284. tmpl = newstyle_i18n_env.get_template('ngettext_long.html')
  285. assert tmpl.render(apples=5, LANGUAGE='de') == u'5 Äpfel'
  286. def test_num_called_num(self):
  287. source = newstyle_i18n_env.compile('''
  288. {% trans num=3 %}{{ num }} apple{% pluralize
  289. %}{{ num }} apples{% endtrans %}
  290. ''', raw=True)
  291. # quite hacky, but the only way to properly test that. The idea is
  292. # that the generated code does not pass num twice (although that
  293. # would work) for better performance. This only works on the
  294. # newstyle gettext of course
  295. assert re.search(r"l_ngettext, u?'\%\(num\)s apple', u?'\%\(num\)s "
  296. r"apples', 3", source) is not None
  297. def test_trans_vars(self):
  298. t1 = newstyle_i18n_env.get_template('transvars1.html')
  299. t2 = newstyle_i18n_env.get_template('transvars2.html')
  300. t3 = newstyle_i18n_env.get_template('transvars3.html')
  301. assert t1.render(num=1, LANGUAGE='de') == 'Benutzer: 1'
  302. assert t2.render(count=23, LANGUAGE='de') == 'Benutzer: 23'
  303. assert t3.render(num=42, LANGUAGE='de') == 'Benutzer: 42'
  304. def test_novars_vars_escaping(self):
  305. t = newstyle_i18n_env.get_template('novars.html')
  306. assert t.render() == '%(hello)s'
  307. t = newstyle_i18n_env.get_template('vars.html')
  308. assert t.render(foo='42') == '42%(foo)s'
  309. t = newstyle_i18n_env.get_template('explicitvars.html')
  310. assert t.render() == '%(foo)s'
  311. class AutoEscapeTestCase(JinjaTestCase):
  312. def test_scoped_setting(self):
  313. env = Environment(extensions=['jinja2.ext.autoescape'],
  314. autoescape=True)
  315. tmpl = env.from_string('''
  316. {{ "<HelloWorld>" }}
  317. {% autoescape false %}
  318. {{ "<HelloWorld>" }}
  319. {% endautoescape %}
  320. {{ "<HelloWorld>" }}
  321. ''')
  322. assert tmpl.render().split() == \
  323. [u'&lt;HelloWorld&gt;', u'<HelloWorld>', u'&lt;HelloWorld&gt;']
  324. env = Environment(extensions=['jinja2.ext.autoescape'],
  325. autoescape=False)
  326. tmpl = env.from_string('''
  327. {{ "<HelloWorld>" }}
  328. {% autoescape true %}
  329. {{ "<HelloWorld>" }}
  330. {% endautoescape %}
  331. {{ "<HelloWorld>" }}
  332. ''')
  333. assert tmpl.render().split() == \
  334. [u'<HelloWorld>', u'&lt;HelloWorld&gt;', u'<HelloWorld>']
  335. def test_nonvolatile(self):
  336. env = Environment(extensions=['jinja2.ext.autoescape'],
  337. autoescape=True)
  338. tmpl = env.from_string('{{ {"foo": "<test>"}|xmlattr|escape }}')
  339. assert tmpl.render() == ' foo="&lt;test&gt;"'
  340. tmpl = env.from_string('{% autoescape false %}{{ {"foo": "<test>"}'
  341. '|xmlattr|escape }}{% endautoescape %}')
  342. assert tmpl.render() == ' foo=&#34;&amp;lt;test&amp;gt;&#34;'
  343. def test_volatile(self):
  344. env = Environment(extensions=['jinja2.ext.autoescape'],
  345. autoescape=True)
  346. tmpl = env.from_string('{% autoescape foo %}{{ {"foo": "<test>"}'
  347. '|xmlattr|escape }}{% endautoescape %}')
  348. assert tmpl.render(foo=False) == ' foo=&#34;&amp;lt;test&amp;gt;&#34;'
  349. assert tmpl.render(foo=True) == ' foo="&lt;test&gt;"'
  350. def test_scoping(self):
  351. env = Environment(extensions=['jinja2.ext.autoescape'])
  352. tmpl = env.from_string('{% autoescape true %}{% set x = "<x>" %}{{ x }}'
  353. '{% endautoescape %}{{ x }}{{ "<y>" }}')
  354. assert tmpl.render(x=1) == '&lt;x&gt;1<y>'
  355. def test_volatile_scoping(self):
  356. env = Environment(extensions=['jinja2.ext.autoescape'])
  357. tmplsource = '''
  358. {% autoescape val %}
  359. {% macro foo(x) %}
  360. [{{ x }}]
  361. {% endmacro %}
  362. {{ foo().__class__.__name__ }}
  363. {% endautoescape %}
  364. {{ '<testing>' }}
  365. '''
  366. tmpl = env.from_string(tmplsource)
  367. assert tmpl.render(val=True).split()[0] == 'Markup'
  368. assert tmpl.render(val=False).split()[0] == text_type.__name__
  369. # looking at the source we should see <testing> there in raw
  370. # (and then escaped as well)
  371. env = Environment(extensions=['jinja2.ext.autoescape'])
  372. pysource = env.compile(tmplsource, raw=True)
  373. assert '<testing>\\n' in pysource
  374. env = Environment(extensions=['jinja2.ext.autoescape'],
  375. autoescape=True)
  376. pysource = env.compile(tmplsource, raw=True)
  377. assert '&lt;testing&gt;\\n' in pysource
  378. def suite():
  379. suite = unittest.TestSuite()
  380. suite.addTest(unittest.makeSuite(ExtensionsTestCase))
  381. suite.addTest(unittest.makeSuite(InternationalizationTestCase))
  382. suite.addTest(unittest.makeSuite(NewstyleInternationalizationTestCase))
  383. suite.addTest(unittest.makeSuite(AutoEscapeTestCase))
  384. return suite