Skip to content

Commit

Permalink
[utils] Fixed evaluation of multiple vars #55
Browse files Browse the repository at this point in the history
Multiple variables were being evaluated with the same value
because the implementation was too naive.
This commit fixes issue #55.
  • Loading branch information
nemesifier committed Dec 28, 2016
1 parent b55e319 commit cbec128
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 2 deletions.
14 changes: 12 additions & 2 deletions netjsonconfig/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,10 +57,20 @@ def evaluate_vars(data, context={}):
for key, value in loop_items:
data[key] = evaluate_vars(value, context)
elif isinstance(data, six.string_types):
for var in var_pattern.findall(data):
vars_found = var_pattern.findall(data)
for var in vars_found:
var = var.strip()
# if found multiple variables, create a new regexp pattern for each
# variable, otherwise different variables would get the same value
# (see https://github.com/openwisp/netjsonconfig/issues/55)
if len(vars_found) > 1:
pattern = r'\{\{(\s*%s\s*)\}\}' % var
# in case of single variables, use the precompiled
# regexp pattern to save computation
else:
pattern = var_pattern
if var in context:
data = re.sub(var_pattern, context[var], data)
data = re.sub(pattern, context[var], data)
return data


Expand Down
19 changes: 19 additions & 0 deletions tests/openwrt/test_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,3 +58,22 @@ def test_no_variables_found(self):
o = OpenWrt(config, context={"a": "b"})
output = o.render()
self.assertIn("option description '{{ desc }}'", output)

def test_context_bug(self):
"""
see https://github.com/openwisp/netjsonconfig/issues/55
"""
config = {"general": {"hostname": "test-context"}}
template = {
"files": [
{
"path": "/etc/vpnserver1",
"mode": "0644",
"contents": "{{ name }}\n{{ vpnserver1 }}\n"
}
]
}
context = {"name": "test-context",
"vpnserver1": "vpn.testdomain.com"}
o = OpenWrt(config, context=context, templates=[template])
self.assertIn("vpn.testdomain.com", o.render())
6 changes: 6 additions & 0 deletions tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,5 +143,11 @@ def test_evaluate_vars_doublewhitespace(self):
def test_evaluate_vars_strangewhitespace(self):
self.assertEqual(evaluate_vars('{{ tz}}', {'tz': 'UTC'}), 'UTC')

def test_evaluate_vars_multiple_newline(self):
"""
see https://github.com/openwisp/netjsonconfig/issues/55
"""
output = evaluate_vars('{{ a }}\n{{ b }}\n', {'a': 'a', 'b': 'b'})
self.assertEqual(output, 'a\nb\n')
def test_evaluate_vars_one_char(self):
self.assertEqual(evaluate_vars('{{ a }}', {'a': 'letter-A'}), 'letter-A')

0 comments on commit cbec128

Please sign in to comment.