1 ##############################################################################
2 # Copyright (c) 2015 Huawei Technologies Co.,Ltd and others.
4 # All rights reserved. This program and the accompanying materials
5 # are made available under the terms of the Apache License, Version 2.0
6 # which accompanies this distribution, and is available at
7 # http://www.apache.org/licenses/LICENSE-2.0
8 # yardstick: this file is copied from rally and slightly modified
9 ##############################################################################
10 from __future__ import absolute_import
17 def finalize_for_yaml(elem):
18 """Render Jinja2 output specifically for YAML files"""
19 # Jinaj2 by default converts None to 'None', we can't allow this
20 # we could convert to empty string '', or we can convert to null, aka ~
23 # convert data structures to inline YAML
24 # match builtin types because we shouldn't be trying to render complex types
25 if isinstance(elem, (dict, list)):
26 # remove newlines because we are injecting back into YAML
27 # use block style for single line
28 return yaml.safe_dump(elem, default_flow_style=True).replace('\n', '')
32 class TaskTemplate(object):
35 def render(cls, task_template, **kwargs):
36 """Render jinja2 task template to Yardstick input task.
38 :param task_template: string that contains template
39 :param kwargs: Dict with template arguments
40 :returns:rendered template str
43 from six.moves import builtins
45 ast = jinja2.Environment().parse(task_template)
46 required_kwargs = jinja2.meta.find_undeclared_variables(ast)
48 missing = set(required_kwargs) - set(kwargs) - set(dir(builtins))
49 real_missing = [mis for mis in missing
50 if is_really_missing(mis, task_template)]
53 multi_msg = ("Please specify next template task arguments:%s")
54 single_msg = ("Please specify template task argument:%s")
55 raise TypeError((len(real_missing) > 1 and multi_msg or single_msg)
56 % ", ".join(real_missing))
57 return jinja2.Template(task_template, finalize=finalize_for_yaml).render(**kwargs)
60 def is_really_missing(mis, task_template):
61 # Removing variables that have default values from
62 # missing. Construction that won't be properly
63 # check is {% set x = x or 1}
64 if re.search(mis.join([r"{%\s*set\s+", "\s*=\s*", r"[^\w]+"]),
67 # Also check for a default filter which can show up as
69 if re.search(mis + r"\s*\|\s*default\(", task_template):