Skip to content

Improve warnings on undefined template errors#48713

Merged
balloob merged 3 commits intohome-assistant:devfrom
emontnemery:template_warn_undefined_improve
Apr 6, 2021
Merged

Improve warnings on undefined template errors#48713
balloob merged 3 commits intohome-assistant:devfrom
emontnemery:template_warn_undefined_improve

Conversation

@emontnemery
Copy link
Copy Markdown
Contributor

@emontnemery emontnemery commented Apr 6, 2021

Proposed change

Improve warnings for undefined variables in templates introduced in #48140

Example: rendering template "{{ no_such_variable }}" will result in this error message:

"Template variable warning when rendering '{{ no_such_variable }}': 'no_such_variable' is undefined"

Also fix some incorrect type annotations.

Type of change

  • Dependency upgrade
  • Bugfix (non-breaking change which fixes an issue)
  • New integration (thank you!)
  • New feature (which adds functionality to an existing integration)
  • Breaking change (fix/feature causing existing functionality to break)
  • Code quality improvements to existing code or addition of tests

Example entry for configuration.yaml:

# Example configuration.yaml

Additional information

Checklist

  • The code change is tested and works locally.
  • Local tests pass. Your PR cannot be merged unless tests pass
  • There is no commented out code in this PR.
  • I have followed the development checklist
  • The code has been formatted using Black (black --fast homeassistant tests)
  • Tests have been added to verify that the new code works.

If user exposed functionality or configuration variables are added/changed:

If the code communicates with devices, web services, or third-party tools:

  • The manifest file has all fields filled out correctly.
    Updated and included derived files by running: python3 -m script.hassfest.
  • New or updated dependencies have been added to requirements_all.txt.
    Updated by running python3 -m script.gen_requirements_all.
  • Untested files have been added to .coveragerc.

The integration reached or maintains the following Integration Quality Scale:

  • No score or internal
  • 🥈 Silver
  • 🥇 Gold
  • 🏆 Platinum

To help with the load of incoming pull requests:

@frenck
Copy link
Copy Markdown
Member

frenck commented Apr 6, 2021

ℹ️ EDIT: Looking more closely, it is the comparison that breaks it. This is existing behavior and correct.


It works pretty well in most cases. I've pasted a piece of a larger, random template into this and got an additional exception.

2021-04-06 20:10:07 DEBUG (MainThread) [homeassistant.components.websocket_api.http.connection] [140173965960000] Received {'type': 'render_template', 'template': '    {% if brightness is defined %}\n      {{ brightness }}\n    {% elif percent > 0 %}\n      {{ max_brightness }}\n    {% else %}\n      {{\n        (\n          (\n            (max_brightness - min_brightness) * ((100 + percent) / 100)\n          ) + min_brightness\n        ) | round\n      }}\n    {% endif %}', 'timeout': 3, 'id': 58}
2021-04-06 20:10:07 ERROR (Thread-17) [root] Uncaught thread exception
Traceback (most recent call last):
  File "/home/frenck/.pyenv/versions/3.9.2/lib/python3.9/threading.py", line 954, in _bootstrap_inner
    self.run()
  File "/home/frenck/.pyenv/versions/3.9.2/lib/python3.9/threading.py", line 892, in run
    self._target(*self._args, **self._kwargs)
  File "/home/frenck/code/home-assistant/core/homeassistant/helpers/template.py", line 448, in _render_template
    _render_with_context(self.template, compiled, **kwargs)
  File "/home/frenck/code/home-assistant/core/homeassistant/helpers/template.py", line 1327, in _render_with_context
    return template.render(**kwargs)
  File "/home/frenck/code/home-assistant/core/venv/lib/python3.9/site-packages/jinja2/environment.py", line 1090, in render
    self.environment.handle_exception()
  File "/home/frenck/code/home-assistant/core/venv/lib/python3.9/site-packages/jinja2/environment.py", line 832, in handle_exception
    reraise(*rewrite_traceback_stack(source=source))
  File "/home/frenck/code/home-assistant/core/venv/lib/python3.9/site-packages/jinja2/_compat.py", line 28, in reraise
    raise value.with_traceback(tb)
  File "<template>", line 3, in top-level template code
jinja2.exceptions.UndefinedError: 'percent' is undefined
2021-04-06 20:13:20 DEBUG (MainThread) [homeassistant.components.websocket_api.http.connection] [140173965960000] Sending {"id": 60, "type": "result", "success": false, "error": {"code": "template_error", "message": "UndefinedError: 'percent' is undefined"}}

Template used:

{% if brightness is defined %}
  {{ brightness }}
{% elif percent > 0 %}
  {{ max_brightness }}
{% else %}
  {{
    (
      (
        (max_brightness - min_brightness) * ((100 + percent) / 100)
      ) + min_brightness
    ) | round
  }}
{% endif %}

Comment on lines +1326 to +1327
template_cv.set(template_str)
return template.render(**kwargs)
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we set it to None after the render?

Copy link
Copy Markdown
Contributor Author

@emontnemery emontnemery Apr 6, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was thinking about that. Is there any scenario in which we could print a stale ContextVar?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's mainly for garbage collection purposes.



def _render_with_context(
template_str: str, template: jinja2.Template, **kwargs: Any
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It took me a bit to realize, this is wrapping Jinja2 objects. Why don't we store our own template objects in it so we can access the template string too?

In the future we can then add "names" to templates, ie sensor.kitchen_temp - attribute name

@balloob balloob merged commit 9f5db2c into home-assistant:dev Apr 6, 2021
@github-actions github-actions Bot locked and limited conversation to collaborators Apr 7, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Template variable warnings not descriptive enough to debug (2021.4.0b2)

4 participants