Code

Ticket #19671: test_m2m_validator_called.diff

File test_m2m_validator_called.diff, 2.2 KB (added by fhahn, 17 months ago)

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

Line 
1diff --git a/tests/modeltests/validation/models.py b/tests/modeltests/validation/models.py
2index db08329..a2fd24c 100644
3--- a/tests/modeltests/validation/models.py
4+++ b/tests/modeltests/validation/models.py
5@@ -11,6 +11,10 @@ def validate_answer_to_universe(value):
6     if value != 42:
7         raise ValidationError('This is not the answer to life, universe and everything!', code='not42')
8 
9+def validate_m2m_fied(value):
10+    raise ValidationError('Many to many validator called')
11+
12+
13 class ModelToValidate(models.Model):
14     name = models.CharField(max_length=100)
15     created = models.DateTimeField(default=datetime.now)
16@@ -108,3 +112,7 @@ try:
17 except AssertionError as exc:
18     assertion_error = exc
19 assert str(assertion_error) == "A model can't have more than one AutoField."
20+
21+
22+class M2mModel(models.Model):
23+    authors = models.ManyToManyField(Author, validators=[validate_m2m_fied])
24diff --git a/tests/modeltests/validation/tests.py b/tests/modeltests/validation/tests.py
25index 58b7b94..65678b9 100644
26--- a/tests/modeltests/validation/tests.py
27+++ b/tests/modeltests/validation/tests.py
28@@ -6,7 +6,7 @@ from django.test import TestCase
29 
30 from . import ValidationTestCase
31 from .models import (Author, Article, ModelToValidate,
32-    GenericIPAddressTestModel, GenericIPAddrUnpackUniqueTest)
33+    GenericIPAddressTestModel, GenericIPAddrUnpackUniqueTest, M2mModel)
34 
35 # Import other tests for this package.
36 from .test_custom_messages import CustomMessagesTest
37@@ -67,6 +67,12 @@ class ArticleForm(forms.ModelForm):
38         model = Article
39         exclude = ['author']
40 
41+
42+class M2mForm(forms.ModelForm):
43+    class Meta:
44+        model = M2mModel
45+
46+
47 class ModelFormsTests(TestCase):
48     def setUp(self):
49         self.author = Author.objects.create(name='Joseph Kocherhans')
50@@ -110,6 +116,11 @@ class ModelFormsTests(TestCase):
51         form = ArticleForm(data, instance=article)
52         self.assertEqual(list(form.errors), ['pub_date'])
53 
54+    def test_m2m_validator_gets_called(self):
55+        # checks if the custom validator on the m2m field authors gets called
56+        form = M2mForm({'authors': [self.author.pk]})
57+        self.assertEqual(list(form.errors), ['authors'])
58+
59 
60 class GenericIPAddressFieldTests(ValidationTestCase):
61