Add non braces matching and a few more tests

This commit is contained in:
Joshua Harlow 2014-07-18 10:52:11 -07:00
parent d8875ea60c
commit 5311e4939c
2 changed files with 47 additions and 4 deletions

View File

@ -42,18 +42,25 @@ from cloudinit import util
LOG = logging.getLogger(__name__)
TYPE_MATCHER = re.compile(r"##\s*template:(.*)", re.I)
BASIC_MATCHER = re.compile(r'\$\{([A-Za-z0-9_.]+)\}')
BASIC_MATCHER = re.compile(r'\$\{([A-Za-z0-9_.]+)\}|\$([A-Za-z0-9_.]+)')
def basic_render(content, params):
"""This does simple replacement of bash variable like templates.
It identifies patterns like ${a} and can also identify patterns like
${a.b} which will look for a key 'b' in the dictionary rooted by key 'a'.
It identifies patterns like ${a} or $a and can also identify patterns like
${a.b} or $a.b which will look for a key 'b' in the dictionary rooted
by key 'a'.
"""
def replacer(match):
path = collections.deque(match.group(1).split("."))
# Only 1 of the 2 groups will actually have a valid entry.
name = match.group(1)
if name is None:
name = match.group(2)
if name is None:
raise RuntimeError("Match encountered but no valid group present")
path = collections.deque(name.split("."))
selected_params = params
while len(path) > 1:
key = path.popleft()

View File

@ -68,3 +68,39 @@ $a,$b'''
blob = '''$a,$b'''
c = templater.render_string(blob, {"a": 1, "b": 2})
self.assertEquals("1,2", c)
def test_render_basic_deeper(self):
hn = 'myfoohost.yahoo.com'
expected_data = "h=%s\nc=d\n" % hn
in_data = "h=$hostname.canonical_name\nc=d\n"
params = {
"hostname": {
"canonical_name": hn,
},
}
out_data = templater.render_string(in_data, params)
self.assertEqual(expected_data, out_data)
def test_render_basic_no_parens(self):
hn = "myfoohost"
in_data = "h=$hostname\nc=d\n"
expected_data = "h=%s\nc=d\n" % hn
out_data = templater.basic_render(in_data, {'hostname': hn})
self.assertEqual(expected_data, out_data)
def test_render_basic_parens(self):
hn = "myfoohost"
in_data = "h = ${hostname}\nc=d\n"
expected_data = "h = %s\nc=d\n" % hn
out_data = templater.basic_render(in_data, {'hostname': hn})
self.assertEqual(expected_data, out_data)
def test_render_basic2(self):
mirror = "mymirror"
codename = "zany"
in_data = "deb $mirror $codename-updates main contrib non-free"
ex_data = "deb %s %s-updates main contrib non-free" % (mirror, codename)
out_data = templater.basic_render(in_data,
{'mirror': mirror, 'codename': codename})
self.assertEqual(ex_data, out_data)