|
| 1 | +import pytest |
1 | 2 | from django.http import QueryDict
|
2 | 3 | from django.utils.datastructures import MultiValueDict
|
3 | 4 |
|
4 | 5 | from rest_framework import serializers
|
| 6 | +from rest_framework.exceptions import ErrorDetail |
5 | 7 |
|
6 | 8 |
|
7 | 9 | class BasicObject:
|
@@ -223,6 +225,49 @@ def test_validate_html_input(self):
|
223 | 225 | assert serializer.validated_data == expected_output
|
224 | 226 |
|
225 | 227 |
|
| 228 | +class TestNestedListSerializerAllowEmpty: |
| 229 | + """Tests the behaviour of allow_empty=False when a ListSerializer is used as a field.""" |
| 230 | + |
| 231 | + @pytest.mark.parametrize('partial', (False, True)) |
| 232 | + def test_allow_empty_true(self, partial): |
| 233 | + """ |
| 234 | + If allow_empty is True, empty lists should be allowed regardless of the value |
| 235 | + of partial on the parent serializer. |
| 236 | + """ |
| 237 | + class ChildSerializer(serializers.Serializer): |
| 238 | + id = serializers.IntegerField() |
| 239 | + |
| 240 | + class ParentSerializer(serializers.Serializer): |
| 241 | + ids = ChildSerializer(many=True, allow_empty=True) |
| 242 | + |
| 243 | + serializer = ParentSerializer(data={'ids': []}, partial=partial) |
| 244 | + assert serializer.is_valid() |
| 245 | + assert serializer.validated_data == { |
| 246 | + 'ids': [], |
| 247 | + } |
| 248 | + |
| 249 | + @pytest.mark.parametrize('partial', (False, True)) |
| 250 | + def test_allow_empty_false(self, partial): |
| 251 | + """ |
| 252 | + If allow_empty is False, empty lists should fail validation regardless of the value |
| 253 | + of partial on the parent serializer. |
| 254 | + """ |
| 255 | + class ChildSerializer(serializers.Serializer): |
| 256 | + id = serializers.IntegerField() |
| 257 | + |
| 258 | + class ParentSerializer(serializers.Serializer): |
| 259 | + ids = ChildSerializer(many=True, allow_empty=False) |
| 260 | + |
| 261 | + serializer = ParentSerializer(data={'ids': []}, partial=partial) |
| 262 | + assert not serializer.is_valid() |
| 263 | + assert serializer.errors == { |
| 264 | + 'ids': { |
| 265 | + 'non_field_errors': [ |
| 266 | + ErrorDetail(string='This list may not be empty.', code='empty')], |
| 267 | + } |
| 268 | + } |
| 269 | + |
| 270 | + |
226 | 271 | class TestNestedListOfListsSerializer:
|
227 | 272 | def setup(self):
|
228 | 273 | class TestSerializer(serializers.Serializer):
|
|
0 commit comments