Skip to content

Instantly share code, notes, and snippets.

@FlowFX
Forked from magopian/tests.py
Last active July 5, 2017 14:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FlowFX/8f202696bbd3ceae50b736e9f615e156 to your computer and use it in GitHub Desktop.
Save FlowFX/8f202696bbd3ceae50b736e9f615e156 to your computer and use it in GitHub Desktop.
Unit test to validate django templates
"""Test templates for syntax errors."""
import os
import glob
from importlib import import_module
from django.conf import settings
from django.template import TemplateSyntaxError, Template
def test_templates():
"""Templates can compile properly and there's no mismatched tags"""
# get app template dirs
template_dirs = []
apps = [app for app in settings.INSTALLED_APPS if app.startswith('my_app')]
for app in apps:
mod = import_module(app)
template_dirs.append(os.path.join(os.path.dirname(mod.__file__), 'templates'))
# get template dirs from settings
for template in settings.TEMPLATES:
for template_dir in template.get('DIRS'):
template_dirs.append(template_dir)
# find all templates (*.html and *.txt)
templates = []
for template_dir in template_dirs:
templates += glob.glob('%s/*.html' % template_dir)
templates += glob.glob('%s/*.txt' % template_dir)
for root, dirnames, filenames in os.walk(template_dir): # pylint: disable=unused-variable
for dirname in dirnames:
template_folder = os.path.join(root, dirname)
templates += glob.glob('%s/*.html' % template_folder)
templates += glob.glob('%s/*.txt' % template_folder)
for template in templates:
with open(template, 'r') as f:
source = f.read()
# template compilation fails on impaired or invalid blocks tags
try:
Template(source)
except TemplateSyntaxError as e:
raise TemplateSyntaxError('%s in %s' % (e, template))
# check for badly formated tags or filters
assert source.count('{%') == source.count('%}'), 'Found impaired {{% %}} in {}'.format(template)
assert source.count('{{') == source.count('}}'), 'Found impaired {{ and }} in {}'.format(template)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment