Skip to content

Instantly share code, notes, and snippets.

@mathiasose
Forked from jleclanche/test_templates.py
Last active March 14, 2018 16:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mathiasose/7e545ece9790e95f86da036287c13dfa to your computer and use it in GitHub Desktop.
Save mathiasose/7e545ece9790e95f86da036287c13dfa to your computer and use it in GitHub Desktop.
Test that Django templates render without errors

Django test (pytest) that checks that templates render without errors.

Uses pytest.mark.parameterize to test each template as an individual test.

Uses Django's Loader to find templates. This will also find templates in third-party apps (i.e. in your virtualenv). If you want to exclude these from being tested you will need to modify the code to fit your own project structure. The above code assumes a list of local apps in the settings file (INSTALLED_APPS = VENV_APPS + LOCAL_APPS).

License: CC0

# License: CC0
# https://creativecommons.org/publicdomain/zero/1.0/
# https://creativecommons.org/share-your-work/public-domain/cc0/
import os
from pathlib import Path
import pytest
from django.conf import settings
from django.template import Template
from django.template.loaders.app_directories import Loader
TEMPLATE_BACKEND = settings.TEMPLATES[0]['BACKEND']
TEMPLATE_FORMATS = ['.html', '.txt']
APPS_ROOT = Path(settings.BASE_DIR)
LOCAL_APPS = settings.LOCAL_APPS
def template_paths():
loader = Loader(TEMPLATE_BACKEND)
template_dirs = loader.get_dirs()
# Loader will also find templates in third party Django apps (i.e. in your virtualenv).
# Skip these and only return templates of local apps.
def _is_local_app_path(path):
path = Path(path)
return any(APPS_ROOT / local_app in path.parents for local_app in settings.LOCAL_APPS)
template_dirs = [
path for path in template_dirs if _is_local_app_path(path)
]
for template_dir in template_dirs:
for basepath, _, filenames in os.walk(template_dir):
for filename in filenames:
path = Path(basepath) / filename
if path.suffix not in TEMPLATE_FORMATS:
continue
yield str(path.resolve())
@pytest.mark.parametrize("template_path", template_paths())
def test_compile_templates(template_path: str):
with open(template_path, 'r') as template_file:
# This will fail if the template cannot compile
rendered_template = Template(template_file.read())
assert rendered_template
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment