diff --git a/unit_tests/test_zaza_charm_lifecycle_deploy.py b/unit_tests/test_zaza_charm_lifecycle_deploy.py index 4f38dd8..df84ab7 100644 --- a/unit_tests/test_zaza_charm_lifecycle_deploy.py +++ b/unit_tests/test_zaza_charm_lifecycle_deploy.py @@ -128,6 +128,23 @@ class TestCharmLifecycleDeploy(ut_utils.BaseTestCase): template_mock, '/tmp/special-dir/my_overlay.yaml') + def test_template_missing_required_variables(self): + self.patch_object(lc_deploy, 'get_template_overlay_context') + self.get_template_overlay_context.return_value = {} + self.patch_object(lc_deploy.sys, 'exit') + self.patch_object(lc_deploy.logging, 'error') + jinja2_env = lc_deploy.get_jinja2_env() + template = jinja2_env.from_string('{{required_variable}}') + m = mock.mock_open() + with mock.patch('zaza.charm_lifecycle.deploy.open', m, create=True): + lc_deploy.render_template(template, '/tmp/mybundle.yaml') + m.assert_called_once_with('/tmp/mybundle.yaml', 'w') + self.error.assert_called_once_with( + "Template error. You may be missing" + " a mandatory environment variable : " + "'required_variable' is undefined") + self.exit.assert_called_once_with(1) + def test_render_overlay_no_template(self): self.patch_object(lc_deploy, 'get_template') self.get_template.return_value = None diff --git a/zaza/charm_lifecycle/deploy.py b/zaza/charm_lifecycle/deploy.py index 4264c67..8749251 100755 --- a/zaza/charm_lifecycle/deploy.py +++ b/zaza/charm_lifecycle/deploy.py @@ -118,7 +118,8 @@ def get_jinja2_env(): """ template_dir = get_overlay_template_dir() return jinja2.Environment( - loader=jinja2.FileSystemLoader(template_dir) + loader=jinja2.FileSystemLoader(template_dir), + undefined=jinja2.StrictUndefined ) @@ -158,10 +159,14 @@ def render_template(template, target_file): :param target_file: File name for rendered template :type target_file: str """ - with open(target_file, "w") as fh: - fh.write( - template.render(get_template_overlay_context())) - + try: + with open(target_file, "w") as fh: + fh.write( + template.render(get_template_overlay_context())) + except jinja2.exceptions.UndefinedError as e: + logging.error("Template error. You may be missing" + " a mandatory environment variable : {}".format(e)) + sys.exit(1) logging.info("Rendered template '{}' to file '{}'".format(template, target_file))