Ticket #19671: test_m2m_validator_called.diff

File test_m2m_validator_called.diff, 2.2 KB (added by fhahn, 12 years ago)

test that checks if a custom validator of a m2m field gets called during form validation

  • tests/modeltests/validation/models.py

    diff --git a/tests/modeltests/validation/models.py b/tests/modeltests/validation/models.py
    index db08329..a2fd24c 100644
    a b def validate_answer_to_universe(value):  
    1111    if value != 42:
    1212        raise ValidationError('This is not the answer to life, universe and everything!', code='not42')
    1313
     14def validate_m2m_fied(value):
     15    raise ValidationError('Many to many validator called')
     16
     17
    1418class ModelToValidate(models.Model):
    1519    name = models.CharField(max_length=100)
    1620    created = models.DateTimeField(default=datetime.now)
    try:  
    108112except AssertionError as exc:
    109113    assertion_error = exc
    110114assert str(assertion_error) == "A model can't have more than one AutoField."
     115
     116
     117class M2mModel(models.Model):
     118    authors = models.ManyToManyField(Author, validators=[validate_m2m_fied])
  • tests/modeltests/validation/tests.py

    diff --git a/tests/modeltests/validation/tests.py b/tests/modeltests/validation/tests.py
    index 58b7b94..65678b9 100644
    a b from django.test import TestCase  
    66
    77from . import ValidationTestCase
    88from .models import (Author, Article, ModelToValidate,
    9     GenericIPAddressTestModel, GenericIPAddrUnpackUniqueTest)
     9    GenericIPAddressTestModel, GenericIPAddrUnpackUniqueTest, M2mModel)
    1010
    1111# Import other tests for this package.
    1212from .test_custom_messages import CustomMessagesTest
    class ArticleForm(forms.ModelForm):  
    6767        model = Article
    6868        exclude = ['author']
    6969
     70
     71class M2mForm(forms.ModelForm):
     72    class Meta:
     73        model = M2mModel
     74
     75
    7076class ModelFormsTests(TestCase):
    7177    def setUp(self):
    7278        self.author = Author.objects.create(name='Joseph Kocherhans')
    class ModelFormsTests(TestCase):  
    110116        form = ArticleForm(data, instance=article)
    111117        self.assertEqual(list(form.errors), ['pub_date'])
    112118
     119    def test_m2m_validator_gets_called(self):
     120        # checks if the custom validator on the m2m field authors gets called
     121        form = M2mForm({'authors': [self.author.pk]})
     122        self.assertEqual(list(form.errors), ['authors'])
     123
    113124
    114125class GenericIPAddressFieldTests(ValidationTestCase):
    115126
Back to Top