|
2 | 2 | import pickle
|
3 | 3 | import re
|
4 | 4 | import sys
|
| 5 | +import unittest |
5 | 6 | from collections import ChainMap
|
6 | 7 | from collections.abc import Mapping
|
7 | 8 |
|
@@ -783,3 +784,63 @@ def test_nested_key(self):
|
783 | 784 | ret = {'a': 1}
|
784 | 785 | self.s.set_value(ret, ['x', 'y'], 2)
|
785 | 786 | assert ret == {'a': 1, 'x': {'y': 2}}
|
| 787 | + |
| 788 | + |
| 789 | +class MyClass(models.Model): |
| 790 | + name = models.CharField(max_length=100) |
| 791 | + value = models.CharField(max_length=100, blank=True) |
| 792 | + |
| 793 | + app_label = "test" |
| 794 | + |
| 795 | + @property |
| 796 | + def is_valid(self): |
| 797 | + return self.name == 'valid' |
| 798 | + |
| 799 | + |
| 800 | +class MyClassSerializer(serializers.ModelSerializer): |
| 801 | + class Meta: |
| 802 | + model = MyClass |
| 803 | + fields = ('id', 'name', 'value') |
| 804 | + |
| 805 | + def validate_value(self, value): |
| 806 | + if value and not self.instance.is_valid: |
| 807 | + raise serializers.ValidationError( |
| 808 | + 'Status cannot be set for invalid instance') |
| 809 | + return value |
| 810 | + |
| 811 | + |
| 812 | +class TestMultipleObjectsValidation(unittest.TestCase): |
| 813 | + def setUp(self): |
| 814 | + self.objs = [ |
| 815 | + MyClass(name='valid'), |
| 816 | + MyClass(name='invalid'), |
| 817 | + MyClass(name='other'), |
| 818 | + ] |
| 819 | + |
| 820 | + def test_multiple_objects_are_validated_separately(self): |
| 821 | + |
| 822 | + serializer = MyClassSerializer( |
| 823 | + data=[{'value': 'set', 'id': instance.id} for instance in |
| 824 | + self.objs], |
| 825 | + instance=self.objs, |
| 826 | + many=True, |
| 827 | + partial=True, |
| 828 | + ) |
| 829 | + |
| 830 | + assert not serializer.is_valid() |
| 831 | + assert serializer.errors == [ |
| 832 | + {}, |
| 833 | + {'value': ['Status cannot be set for invalid instance']}, |
| 834 | + {'value': ['Status cannot be set for invalid instance']} |
| 835 | + ] |
| 836 | + |
| 837 | + def test_exception_raised_when_data_and_instance_length_different(self): |
| 838 | + |
| 839 | + with self.assertRaises(AssertionError): |
| 840 | + MyClassSerializer( |
| 841 | + data=[{'value': 'set', 'id': instance.id} for instance in |
| 842 | + self.objs], |
| 843 | + instance=self.objs[:-1], |
| 844 | + many=True, |
| 845 | + partial=True, |
| 846 | + ) |
0 commit comments