Skip to content

Instantly share code, notes, and snippets.

@lightstrike
Created June 16, 2014 22:44
Show Gist options
  • Save lightstrike/6704e8586d8b839389c1 to your computer and use it in GitHub Desktop.
Save lightstrike/6704e8586d8b839389c1 to your computer and use it in GitHub Desktop.
Testing ModelForm template tag with Factory Boy
### factories.py ###
from factory.django import DjangoModelFactory
from django.forms import ModelForm
from .models import Product, ProductQuerySet
class TestProduct(Product):
pass
class TestProductForm(ModelForm):
class Meta:
model = TestProduct
### templatetags/class_filters.py ###
from django import template
register = template.Library()
def get_class_name(value):
return value.__class__.__name__
def get_model_name(value):
return value._meta.model.__name__
register.filter('get_class_name', get_class_name)
register.filter('get_model_name', get_model_name)
### tests/templatetags.py ###
from django.test import TestCase
from django.template import Template, Context
from .factories import TestProductFactory, TestProductForm
class ClassFilters(TestCase):
def setUp(self):
self.product = TestProductFactory()
self.form = TestProductForm(instance=self.product)
def test_class_name(self):
actual = Template(
"{% load class_filters %}"
"{{ product|get_class_name }}"
).render(Context({'product': self.product}))
expected = 'TestProduct'
self.assertEqual(actual, expected)
def test_model_name(self):
actual = Template(
"{% load class_filters %}"
"{{ form|get_model_name }}"
).render(Context({'form': self.form}))
expected = 'TestProduct'
self.assertEqual(actual, expected)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment