python / intermediate
Snippet
Isolation Unit Testing for Custom Django Template Tags
Custom Django template tags can be tested without a database using SimpleTestCase by constructing string templates, compiling them with Template(), and rendering them with a Context object.
snippet.py
python
1
2
3
4
5
6
7
8
9
10
11
12
13
from django.test import SimpleTestCasefrom django.template import Context, Templateclass FormatBadgeTagTest(SimpleTestCase):def test_custom_badge_rendering(self):template_str = "{% load custom_tags %}{% format_badge status='active' %}"rendered = Template(template_str).render(Context({}))self.assertIn('<span class="badge-active">active</span>', rendered)def test_custom_badge_invalid_status(self):template_str = "{% load custom_tags %}{% format_badge status='unknown' %}"rendered = Template(template_str).render(Context({}))self.assertEqual(rendered, '<span class="badge-default">unknown</span>')
django
Breakdown
1
from django.test import SimpleTestCase
Import SimpleTestCase for fast tests that do not require database transaction setup.
2
template_str = "{% load custom_tags %}{% format_badge status='active' %}"
Define inline template string loading the custom tag library and executing the tag under test.
3
rendered = Template(template_str).render(Context({}))
Compile the template string and evaluate it with context data to generate output HTML.
4
self.assertIn('<span class="badge-active">active</span>', rendered)
Assert that expected HTML output structure is present in rendered string result.