Add more tests

This commit is contained in:
Pablo Martín 2013-11-26 20:04:41 +01:00
parent 058ed37f74
commit 4a21116fbc
4 changed files with 32 additions and 11 deletions

View File

@ -19,11 +19,11 @@ from django.db import models
from multiselectfield import MultiSelectField
CATEGORY_CHOICES = (
(1, 'Handbooks and manuals by discipline'),
(2, 'Business books'),
(3, 'Books of literary criticism'),
(1, 'Handbooks and manuals by discipline'),
(2, 'Business books2'),
(3, 'Books of literary criticism'),
(4, 'Books about literary theory'),
(5, 'Books about literature')
(5, 'Books about literature')
)
TAGS_CHOICES = (

View File

@ -14,6 +14,7 @@
# You should have received a copy of the GNU Lesser General Public License
# along with this software. If not, see <http://www.gnu.org/licenses/>.
from django.forms.models import modelform_factory
from django.test import TestCase
from example.app.models import Book
@ -24,3 +25,16 @@ class MultiSelectTestCase(TestCase):
def test_filter(self):
self.assertEqual(Book.objects.filter(tags__contains='sex').count(), 1)
self.assertEqual(Book.objects.filter(tags__contains='boring').count(), 0)
def test_form(self):
form_class = modelform_factory(Book)
self.assertEqual(len(form_class.base_fields), 3)
form = form_class({'title': 'new book',
'categories': '1,2'})
if form.is_valid():
form.save()
def test_object(self):
book = Book.objects.all()[0]
self.assertEqual(book.get_tags_display(), 'Sex, Work, Happy')
self.assertEqual(book.get_categories_display(), 'Handbooks and manuals by discipline, Books of literary criticism, Books about literature')

View File

@ -69,10 +69,6 @@ class MultiSelectField(models.CharField):
list.append(string_type(choice_selected[0]))
return list
def _get_FIELD_display(self, field):
value = getattr(self, field.attname)
choicedict = dict(field.choices)
def value_to_string(self, obj):
value = self._get_val_from_obj(obj)
return self.get_prep_value(value)
@ -110,9 +106,20 @@ class MultiSelectField(models.CharField):
def contribute_to_class(self, cls, name):
super(MultiSelectField, self).contribute_to_class(cls, name)
if self.choices:
func = lambda self, fieldname = name, choicedict = dict(self.choices): ",".join([string_type(choicedict.get(value, value)) for value in getattr(self, fieldname)])
setattr(cls, 'get_%s_display' % self.name, func)
def get_display(obj):
fieldname = name
choicedict = dict(self.choices)
display = []
for value in getattr(obj, fieldname):
item_display = choicedict.get(value, None)
if item_display is None:
try:
item_display = choicedict.get(int(value), value)
except (ValueError, TypeError):
item_display = value
display.append(string_type(item_display))
return ", ".join(display)
setattr(cls, 'get_%s_display' % self.name, get_display)
MultiSelectField = add_metaclass(models.SubfieldBase)(MultiSelectField)