Skip to content

Commit

Permalink
Option to error on missing Jinja2 variables (#27)
Browse files Browse the repository at this point in the history
This allows a user to specify if they want to allow missing variables in a jinja2 template. If allow_missing == False, a NameError will be raised with the name of the variable that is undefined. The default is True, which is the current behavior.
  • Loading branch information
DavidHuber-NOAA authored May 22, 2024
1 parent 71f6b10 commit 8406bee
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 3 deletions.
2 changes: 1 addition & 1 deletion src/wxflow/jinja.py
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,7 @@ def _render_template(self, template: jinja2.Template) -> str:
try:
rendered = template.render(**self.data)
except jinja2.UndefinedError as ee:
raise Exception(f"Undefined variable in Jinja2 template\n{ee}")
raise NameError(f"Undefined variable in Jinja2 template\n{ee}")

return rendered

Expand Down
6 changes: 4 additions & 2 deletions src/wxflow/yaml_file.py
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,7 @@ def vanilla_yaml(ctx):
return ctx


def parse_j2yaml(path: str, data: Dict, searchpath: Union[str, List] = '/') -> Dict[str, Any]:
def parse_j2yaml(path: str, data: Dict, searchpath: Union[str, List] = '/', allow_missing: bool = True) -> Dict[str, Any]:
"""
Description
-----------
Expand All @@ -171,6 +171,8 @@ def parse_j2yaml(path: str, data: Dict, searchpath: Union[str, List] = '/') -> D
the context for jinja2 templating
searchpath: str | List
additional search paths for included jinja2 templates
allow_missing: bool
whether to allow missing variables in a jinja2 template or not
Returns
-------
Dict[str, Any]
Expand All @@ -180,4 +182,4 @@ def parse_j2yaml(path: str, data: Dict, searchpath: Union[str, List] = '/') -> D
if not os.path.exists(path):
raise FileNotFoundError(f"Input j2yaml file {path} does not exist!")

return YAMLFile(data=Jinja(path, data, searchpath=searchpath).render)
return YAMLFile(data=Jinja(path, data, searchpath=searchpath, allow_missing=allow_missing).render)
9 changes: 9 additions & 0 deletions tests/test_yaml_file.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,15 @@ def test_yaml_file(tmp_path, create_template):
assert yaml_in == conf


def test_j2template_missing_var(tmp_path, create_template):

# Try to parse a j2yaml with an undefined variable (user)
os.environ['TMP_PATH'] = str(tmp_path)
with pytest.raises(NameError) as e_info:
data = {'current_cycle': datetime.now()}
conf = parse_j2yaml(path=str(tmp_path / 'j2tmpl.yaml'), data=data, allow_missing=False)


def test_yaml_file_with_j2templates(tmp_path, create_template):

# Set env. variable
Expand Down

0 comments on commit 8406bee

Please sign in to comment.