Fix templating when data is empty

Fixes base_template.load and remove_template_definition which fail when
the userdata is empty / None or when the userdata has only one line.

Change-Id: I2ba0e16489049be390b2c9bc1fdf1e1059f54eb1
This commit is contained in:
Adrian Vladu 2020-01-23 13:16:27 +02:00
parent 1ec8cd06d4
commit fd2c15bef3
3 changed files with 23 additions and 0 deletions

View File

@ -22,6 +22,7 @@ from cloudbaseinit.utils.template_engine import base_template as bt
class TestBaseTemplateEngine(unittest.TestCase):
@ddt.data((b'', b''),
(None, None),
(b'## template:jinja test', b''),
(b'## template:jinja \ntest', b'test'))
@ddt.unpack

View File

@ -13,6 +13,7 @@
# under the License.
import ddt
import unittest
try:
import unittest.mock as mock
@ -23,6 +24,7 @@ from cloudbaseinit.utils.template_engine.jinja2_template import (
Jinja2TemplateEngine)
@ddt.ddt
class TestJinja2TemplateEngine(unittest.TestCase):
@mock.patch('cloudbaseinit.utils.template_engine.base_template'
@ -80,3 +82,13 @@ class TestJinja2TemplateEngine(unittest.TestCase):
fake_instance_data=fake_instance_data,
expected_result=expected_result,
fake_template=fake_template)
@ddt.data((b'', None),
(None, None),
(b'## template:jinja \n#ps1 \nmkdir', True),
(b'## template:jinja test', None),
(b'## template:jinjanone \ntest', None))
@ddt.unpack
def test_load_template_definition(self, userdata, expected_output):
output = Jinja2TemplateEngine().load(userdata)
self.assertEqual(expected_output, output)

View File

@ -42,13 +42,23 @@ class BaseTemplateEngine(object):
def load(self, data):
"""Returns True if the template header matches, False otherwise"""
if not data:
return
template_type_matcher = self._template_matcher.match(data.decode())
if not template_type_matcher:
return
template_type = template_type_matcher.group(1).lower().strip()
if self.get_template_type() == template_type:
return True
@staticmethod
def remove_template_definition(raw_template):
# return the raw template as is if it is None or empty array / dict
if not raw_template:
return raw_template
# Remove the first line, as it contains the template definition
template_split = raw_template.split(b"\n", 1)