Files
hass-oidc-auth/tests/test_view_template.py
Andrew Garrett b2d07c28f0 Enable Jinja2 autoescaping (#200)
- Enable Jinja2 autoescape by default in the template environment.
- Use json.dumps to safely inject sso_name into JavaScript context.
- Fix linting issue (line too long) in injected_auth_page.py.
- Update tests to verify escaping and safe injection.

---------

Co-authored-by: google-labs-jules[bot] <161369871+google-labs-jules[bot]@users.noreply.github.com>
Co-authored-by: werdnum <271070+werdnum@users.noreply.github.com>
2026-02-06 09:07:54 +01:00

55 lines
1.7 KiB
Python

"""Tests for the view templates"""
import pytest
from os import path
from custom_components.auth_oidc.views.loader import AsyncTemplateRenderer
FAKE_TEMPLATE_PATH = path.join(
path.dirname(path.abspath(__file__)), "resources", "fake_templates"
)
@pytest.mark.asyncio
async def test_real_template_render():
"""Test that view template can render an real existing template."""
renderer = AsyncTemplateRenderer()
await renderer.fetch_templates()
rendered = await renderer.render_template(
"welcome.html", name="<script>alert(1)</script>"
)
assert "<!DOCTYPE html>" in rendered
assert "&lt;script&gt;alert(1)&lt;/script&gt;" in rendered
assert "<script>alert(1)</script>" not in rendered
@pytest.mark.asyncio
async def test_fake_template_render():
"""Test that view template can render an fake existing template."""
renderer = AsyncTemplateRenderer(template_dir=FAKE_TEMPLATE_PATH)
await renderer.fetch_templates()
rendered = await renderer.render_template("index.html")
assert "<p>Example template</p>" in rendered
@pytest.mark.asyncio
async def test_dir_render_error():
"""Test that view template sends correct error if you try to render directory."""
renderer = AsyncTemplateRenderer(template_dir=FAKE_TEMPLATE_PATH)
await renderer.fetch_templates()
with pytest.raises(ValueError):
await renderer.render_template("folder.html")
@pytest.mark.asyncio
async def test_random_render_error():
"""Test that view template sends correct error if you try to render non-existing."""
renderer = AsyncTemplateRenderer(template_dir=FAKE_TEMPLATE_PATH)
await renderer.fetch_templates()
with pytest.raises(ValueError):
await renderer.render_template("non_existing.html")