-
-
Save FlowFX/8f202696bbd3ceae50b736e9f615e156 to your computer and use it in GitHub Desktop.
Unit test to validate django templates
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""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