From 28b1135252289a5487f705806ec753790e637f95 Mon Sep 17 00:00:00 2001 From: Boris Pavlovic Date: Thu, 22 Jan 2015 06:07:25 +0300 Subject: [PATCH] Allow using builtin functions in task templates Remove builtin from missing arguments, now we can use them in templates. So such usefull consturction: {% for i in range(10) %} will work. Corresponding unit tests added Change-Id: Ibcbb768c24b512527c4b1cad6abe2e529f0fbfce Closes-bug: #1413432 --- rally/api.py | 8 +++++++- tests/unit/test_api.py | 4 ++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/rally/api.py b/rally/api.py index cbdd87a8d1..c8213cc080 100644 --- a/rally/api.py +++ b/rally/api.py @@ -102,10 +102,16 @@ def task_template_render(task_template, **kwargs): :param kwargs: Dict with template arguments :returns: rendered template str """ + + # NOTE(boris-42): We have to import __builtin__ to get full list of builtin + # functions (e.g. range()). Unfortunately __builtins__ + # doesn't return them (when it is not main module) + import __builtin__ + ast = jinja2.Environment().parse(task_template) required_kwargs = jinja2.meta.find_undeclared_variables(ast) - missing = set(required_kwargs) - set(kwargs) + missing = set(required_kwargs) - set(kwargs) - set(dir(__builtin__)) # NOTE(boris-42): Removing variables that have default values from missing. # Construction that won't be properly checked is # {% set x = x or 1} diff --git a/tests/unit/test_api.py b/tests/unit/test_api.py index c7f73b4357..a1beabd021 100644 --- a/tests/unit/test_api.py +++ b/tests/unit/test_api.py @@ -103,6 +103,10 @@ class APITestCase(test.TestCase): self.assertEqual( "5 = 5", api.task_template_render(template, a=2, b=3, c=5)) + def test_task_template_render_builtin(self): + template = "{% for i in range(4) %}{{i}}{% endfor %}" + self.assertEqual("0123", api.task_template_render(template)) + def test_task_template_render_missing_args(self): self.assertRaises(TypeError, api.task_template_render, "{{a}}")