| 1 |
import datetime |
| 2 |
import math |
| 3 |
import os |
| 4 |
import re |
| 5 |
import uuid |
| 6 |
import warnings |
| 7 |
from decimal import ROUND_DOWN, ROUND_UP, Decimal |
| 8 |
from enum import auto |
| 9 |
from unittest.mock import patch |
| 10 |
from zoneinfo import ZoneInfo |
| 11 |
|
| 12 |
import pytest |
| 13 |
from django.core.exceptions import ValidationError as DjangoValidationError |
| 14 |
from django.db.models import IntegerChoices, TextChoices |
| 15 |
from django.http import QueryDict |
| 16 |
from django.test import TestCase, override_settings |
| 17 |
from django.utils.timezone import activate, deactivate, override |
| 18 |
|
| 19 |
import rest_framework |
| 20 |
from rest_framework import exceptions, serializers |
| 21 |
from rest_framework.fields import ( |
| 22 |
BuiltinSignatureError, DjangoImageField, SkipField, empty, |
| 23 |
is_simple_callable |
| 24 |
) |
| 25 |
from rest_framework.utils import json |
| 26 |
from tests.models import UUIDForeignKeyTarget |
| 27 |
|
| 28 |
utc = datetime.timezone.utc |
| 29 |
|
| 30 |
# Tests for helper functions. |
| 31 |
# --------------------------- |
| 32 |
|
| 33 |
|
| 34 |
class TestIsSimpleCallable: |
| 35 |
|
| 36 |
def test_method(self): |
| 37 |
class Foo: |
| 38 |
@classmethod |
| 39 |
def classmethod(cls): |
| 40 |
pass |
| 41 |
|
| 42 |
def valid(self): |
| 43 |
pass |
| 44 |
|
| 45 |
def valid_kwargs(self, param='value'): |
| 46 |
pass |
| 47 |
|
| 48 |
def valid_vargs_kwargs(self, *args, **kwargs): |
| 49 |
pass |
| 50 |
|
| 51 |
def invalid(self, param): |
| 52 |
pass |
| 53 |
|
| 54 |
assert is_simple_callable(Foo.classmethod) |
| 55 |
|
| 56 |
# unbound methods |
| 57 |
assert not is_simple_callable(Foo.valid) |
| 58 |
assert not is_simple_callable(Foo.valid_kwargs) |
| 59 |
assert not is_simple_callable(Foo.valid_vargs_kwargs) |
| 60 |
assert not is_simple_callable(Foo.invalid) |
| 61 |
|
| 62 |
# bound methods |
| 63 |
assert is_simple_callable(Foo().valid) |
| 64 |
assert is_simple_callable(Foo().valid_kwargs) |
| 65 |
assert is_simple_callable(Foo().valid_vargs_kwargs) |
| 66 |
assert not is_simple_callable(Foo().invalid) |
| 67 |
|
| 68 |
def test_function(self): |
| 69 |
def simple(): |
| 70 |
pass |
| 71 |
|
| 72 |
def valid(param='value', param2='value'): |
| 73 |
pass |
| 74 |
|
| 75 |
def valid_vargs_kwargs(*args, **kwargs): |
| 76 |
pass |
| 77 |
|
| 78 |
def invalid(param, param2='value'): |
| 79 |
pass |
| 80 |
|
| 81 |
assert is_simple_callable(simple) |
| 82 |
assert is_simple_callable(valid) |
| 83 |
assert is_simple_callable(valid_vargs_kwargs) |
| 84 |
assert not is_simple_callable(invalid) |
| 85 |
|
| 86 |
@pytest.mark.parametrize('obj', (True, None, "str", b'bytes', 123, 1.23)) |
| 87 |
def test_not_callable(self, obj): |
| 88 |
assert not is_simple_callable(obj) |
| 89 |
|
| 90 |
def test_4602_regression(self): |
| 91 |
from django.db import models |
| 92 |
|
| 93 |
class ChoiceModel(models.Model): |
| 94 |
choice_field = models.CharField( |
| 95 |
max_length=1, default='a', |
| 96 |
choices=(('a', 'A'), ('b', 'B')), |
| 97 |
) |
| 98 |
|
| 99 |
class Meta: |
| 100 |
app_label = 'tests' |
| 101 |
|
| 102 |
assert is_simple_callable(ChoiceModel().get_choice_field_display) |
| 103 |
|
| 104 |
def test_builtin_function(self): |
| 105 |
# Built-in function signatures are not easily inspectable, so the |
| 106 |
# current expectation is to just raise a helpful error message. |
| 107 |
timestamp = datetime.datetime.now() |
| 108 |
|
| 109 |
with pytest.raises(BuiltinSignatureError) as exc_info: |
| 110 |
is_simple_callable(timestamp.date) |
| 111 |
|
| 112 |
assert str(exc_info.value) == ( |
| 113 |
'Built-in function signatures are not inspectable. Wrap the ' |
| 114 |
'function call in a simple, pure Python function.') |
| 115 |
|
| 116 |
def test_type_annotation(self): |
| 117 |
# The annotation will otherwise raise a syntax error in python < 3.5 |
| 118 |
locals = {} |
| 119 |
exec("def valid(param: str='value'): pass", locals) |
| 120 |
valid = locals['valid'] |
| 121 |
|
| 122 |
assert is_simple_callable(valid) |
| 123 |
|
| 124 |
|
| 125 |
# Tests for field keyword arguments and core functionality. |
| 126 |
# --------------------------------------------------------- |
| 127 |
|
| 128 |
class TestEmpty: |
| 129 |
""" |
| 130 |
Tests for `required`, `allow_null`, `allow_blank`, `default`. |
| 131 |
""" |
| 132 |
def test_required(self): |
| 133 |
""" |
| 134 |
By default a field must be included in the input. |
| 135 |
""" |
| 136 |
field = serializers.IntegerField() |
| 137 |
with pytest.raises(serializers.ValidationError) as exc_info: |
| 138 |
field.run_validation() |
| 139 |
assert exc_info.value.detail == ['This field is required.'] |
| 140 |
|
| 141 |
def test_not_required(self): |
| 142 |
""" |
| 143 |
If `required=False` then a field may be omitted from the input. |
| 144 |
""" |
| 145 |
field = serializers.IntegerField(required=False) |
| 146 |
with pytest.raises(serializers.SkipField): |
| 147 |
field.run_validation() |
| 148 |
|
| 149 |
def test_disallow_null(self): |
| 150 |
""" |
| 151 |
By default `None` is not a valid input. |
| 152 |
""" |
| 153 |
field = serializers.IntegerField() |
| 154 |
with pytest.raises(serializers.ValidationError) as exc_info: |
| 155 |
field.run_validation(None) |
| 156 |
assert exc_info.value.detail == ['This field may not be null.'] |
| 157 |
|
| 158 |
def test_allow_null(self): |
| 159 |
""" |
| 160 |
If `allow_null=True` then `None` is a valid input. |
| 161 |
""" |
| 162 |
field = serializers.IntegerField(allow_null=True) |
| 163 |
output = field.run_validation(None) |
| 164 |
assert output is None |
| 165 |
|
| 166 |
def test_disallow_blank(self): |
| 167 |
""" |
| 168 |
By default '' is not a valid input. |
| 169 |
""" |
| 170 |
field = serializers.CharField() |
| 171 |
with pytest.raises(serializers.ValidationError) as exc_info: |
| 172 |
field.run_validation('') |
| 173 |
assert exc_info.value.detail == ['This field may not be blank.'] |
| 174 |
|
| 175 |
def test_allow_blank(self): |
| 176 |
""" |
| 177 |
If `allow_blank=True` then '' is a valid input. |
| 178 |
""" |
| 179 |
field = serializers.CharField(allow_blank=True) |
| 180 |
output = field.run_validation('') |
| 181 |
assert output == '' |
| 182 |
|
| 183 |
def test_default(self): |
| 184 |
""" |
| 185 |
If `default` is set, then omitted values get the default input. |
| 186 |
""" |
| 187 |
field = serializers.IntegerField(default=123) |
| 188 |
output = field.run_validation() |
| 189 |
assert output == 123 |
| 190 |
|
| 191 |
|
| 192 |
class TestSource: |
| 193 |
def test_source(self): |
| 194 |
class ExampleSerializer(serializers.Serializer): |
| 195 |
example_field = serializers.CharField(source='other') |
| 196 |
serializer = ExampleSerializer(data={'example_field': 'abc'}) |
| 197 |
assert serializer.is_valid() |
| 198 |
assert serializer.validated_data == {'other': 'abc'} |
| 199 |
|
| 200 |
def test_redundant_source(self): |
| 201 |
class ExampleSerializer(serializers.Serializer): |
| 202 |
example_field = serializers.CharField(source='example_field') |
| 203 |
with pytest.raises(AssertionError) as exc_info: |
| 204 |
ExampleSerializer().fields |
| 205 |
assert str(exc_info.value) == ( |
| 206 |
"It is redundant to specify `source='example_field'` on field " |
| 207 |
"'CharField' in serializer 'ExampleSerializer', because it is the " |
| 208 |
"same as the field name. Remove the `source` keyword argument." |
| 209 |
) |
| 210 |
|
| 211 |
def test_callable_source(self): |
| 212 |
class ExampleSerializer(serializers.Serializer): |
| 213 |
example_field = serializers.CharField(source='example_callable') |
| 214 |
|
| 215 |
class ExampleInstance: |
| 216 |
def example_callable(self): |
| 217 |
return 'example callable value' |
| 218 |
|
| 219 |
serializer = ExampleSerializer(ExampleInstance()) |
| 220 |
assert serializer.data['example_field'] == 'example callable value' |
| 221 |
|
| 222 |
def test_callable_source_raises(self): |
| 223 |
class ExampleSerializer(serializers.Serializer): |
| 224 |
example_field = serializers.CharField(source='example_callable', read_only=True) |
| 225 |
|
| 226 |
class ExampleInstance: |
| 227 |
def example_callable(self): |
| 228 |
raise AttributeError('method call failed') |
| 229 |
|
| 230 |
with pytest.raises(ValueError) as exc_info: |
| 231 |
serializer = ExampleSerializer(ExampleInstance()) |
| 232 |
serializer.data.items() |
| 233 |
|
| 234 |
assert 'method call failed' in str(exc_info.value) |
| 235 |
|
| 236 |
def test_builtin_callable_source_raises(self): |
| 237 |
class BuiltinSerializer(serializers.Serializer): |
| 238 |
date = serializers.ReadOnlyField(source='timestamp.date') |
| 239 |
|
| 240 |
with pytest.raises(BuiltinSignatureError) as exc_info: |
| 241 |
BuiltinSerializer({'timestamp': datetime.datetime.now()}).data |
| 242 |
|
| 243 |
assert str(exc_info.value) == ( |
| 244 |
'Field source for `BuiltinSerializer.date` maps to a built-in ' |
| 245 |
'function type and is invalid. Define a property or method on ' |
| 246 |
'the `dict` instance that wraps the call to the built-in function.') |
| 247 |
|
| 248 |
|
| 249 |
class TestReadOnly: |
| 250 |
def setup_method(self): |
| 251 |
class TestSerializer(serializers.Serializer): |
| 252 |
read_only = serializers.ReadOnlyField(default="789") |
| 253 |
writable = serializers.IntegerField() |
| 254 |
self.Serializer = TestSerializer |
| 255 |
|
| 256 |
def test_writable_fields(self): |
| 257 |
""" |
| 258 |
Read-only fields should not be writable, even with default () |
| 259 |
""" |
| 260 |
serializer = self.Serializer() |
| 261 |
assert len(list(serializer._writable_fields)) == 1 |
| 262 |
|
| 263 |
def test_validate_read_only(self): |
| 264 |
""" |
| 265 |
Read-only serializers.should not be included in validation. |
| 266 |
""" |
| 267 |
data = {'read_only': 123, 'writable': 456} |
| 268 |
serializer = self.Serializer(data=data) |
| 269 |
assert serializer.is_valid() |
| 270 |
assert serializer.validated_data == {'writable': 456} |
| 271 |
|
| 272 |
def test_serialize_read_only(self): |
| 273 |
""" |
| 274 |
Read-only serializers.should be serialized. |
| 275 |
""" |
| 276 |
instance = {'read_only': 123, 'writable': 456} |
| 277 |
serializer = self.Serializer(instance) |
| 278 |
assert serializer.data == {'read_only': 123, 'writable': 456} |
| 279 |
|
| 280 |
|
| 281 |
class TestWriteOnly: |
| 282 |
def setup_method(self): |
| 283 |
class TestSerializer(serializers.Serializer): |
| 284 |
write_only = serializers.IntegerField(write_only=True) |
| 285 |
readable = serializers.IntegerField() |
| 286 |
self.Serializer = TestSerializer |
| 287 |
|
| 288 |
def test_validate_write_only(self): |
| 289 |
""" |
| 290 |
Write-only serializers.should be included in validation. |
| 291 |
""" |
| 292 |
data = {'write_only': 123, 'readable': 456} |
| 293 |
serializer = self.Serializer(data=data) |
| 294 |
assert serializer.is_valid() |
| 295 |
assert serializer.validated_data == {'write_only': 123, 'readable': 456} |
| 296 |
|
| 297 |
def test_serialize_write_only(self): |
| 298 |
""" |
| 299 |
Write-only serializers.should not be serialized. |
| 300 |
""" |
| 301 |
instance = {'write_only': 123, 'readable': 456} |
| 302 |
serializer = self.Serializer(instance) |
| 303 |
assert serializer.data == {'readable': 456} |
| 304 |
|
| 305 |
|
| 306 |
class TestInitial: |
| 307 |
def setup_method(self): |
| 308 |
class TestSerializer(serializers.Serializer): |
| 309 |
initial_field = serializers.IntegerField(initial=123) |
| 310 |
blank_field = serializers.IntegerField() |
| 311 |
self.serializer = TestSerializer() |
| 312 |
|
| 313 |
def test_initial(self): |
| 314 |
""" |
| 315 |
Initial values should be included when serializing a new representation. |
| 316 |
""" |
| 317 |
assert self.serializer.data == { |
| 318 |
'initial_field': 123, |
| 319 |
'blank_field': None |
| 320 |
} |
| 321 |
|
| 322 |
|
| 323 |
class TestInitialWithCallable: |
| 324 |
def setup_method(self): |
| 325 |
def initial_value(): |
| 326 |
return 123 |
| 327 |
|
| 328 |
class TestSerializer(serializers.Serializer): |
| 329 |
initial_field = serializers.IntegerField(initial=initial_value) |
| 330 |
self.serializer = TestSerializer() |
| 331 |
|
| 332 |
def test_initial_should_accept_callable(self): |
| 333 |
""" |
| 334 |
Follows the default ``Field.initial`` behavior where they accept a |
| 335 |
callable to produce the initial value""" |
| 336 |
assert self.serializer.data == { |
| 337 |
'initial_field': 123, |
| 338 |
} |
| 339 |
|
| 340 |
|
| 341 |
class TestLabel: |
| 342 |
def setup_method(self): |
| 343 |
class TestSerializer(serializers.Serializer): |
| 344 |
labeled = serializers.IntegerField(label='My label') |
| 345 |
self.serializer = TestSerializer() |
| 346 |
|
| 347 |
def test_label(self): |
| 348 |
""" |
| 349 |
A field's label may be set with the `label` argument. |
| 350 |
""" |
| 351 |
fields = self.serializer.fields |
| 352 |
assert fields['labeled'].label == 'My label' |
| 353 |
|
| 354 |
|
| 355 |
class TestInvalidErrorKey: |
| 356 |
def setup_method(self): |
| 357 |
class ExampleField(serializers.Field): |
| 358 |
def to_native(self, data): |
| 359 |
self.fail('incorrect') |
| 360 |
self.field = ExampleField() |
| 361 |
|
| 362 |
def test_invalid_error_key(self): |
| 363 |
""" |
| 364 |
If a field raises a validation error, but does not have a corresponding |
| 365 |
error message, then raise an appropriate assertion error. |
| 366 |
""" |
| 367 |
with pytest.raises(AssertionError) as exc_info: |
| 368 |
self.field.to_native(123) |
| 369 |
expected = ( |
| 370 |
'ValidationError raised by `ExampleField`, but error key ' |
| 371 |
'`incorrect` does not exist in the `error_messages` dictionary.' |
| 372 |
) |
| 373 |
assert str(exc_info.value) == expected |
| 374 |
|
| 375 |
|
| 376 |
class TestBooleanHTMLInput: |
| 377 |
def test_empty_html_checkbox(self): |
| 378 |
""" |
| 379 |
HTML checkboxes do not send any value, but should be treated |
| 380 |
as `False` by BooleanField if allow_null=False. |
| 381 |
""" |
| 382 |
class TestSerializer(serializers.Serializer): |
| 383 |
archived = serializers.BooleanField() |
| 384 |
|
| 385 |
serializer = TestSerializer(data=QueryDict('')) |
| 386 |
assert serializer.is_valid() |
| 387 |
assert serializer.validated_data == {'archived': False} |
| 388 |
|
| 389 |
def test_empty_html_checkbox_not_required(self): |
| 390 |
""" |
| 391 |
HTML checkboxes do not send any value, but should be treated |
| 392 |
as `False` by BooleanField when the field is required=False |
| 393 |
and allow_null=False. |
| 394 |
""" |
| 395 |
class TestSerializer(serializers.Serializer): |
| 396 |
archived = serializers.BooleanField(required=False) |
| 397 |
|
| 398 |
serializer = TestSerializer(data=QueryDict('')) |
| 399 |
assert serializer.is_valid() |
| 400 |
assert serializer.validated_data == {'archived': False} |
| 401 |
|
| 402 |
def test_empty_html_checkbox_allow_null(self): |
| 403 |
""" |
| 404 |
HTML checkboxes do not send any value and should be treated |
| 405 |
as `None` by BooleanField if allow_null is True. |
| 406 |
""" |
| 407 |
class TestSerializer(serializers.Serializer): |
| 408 |
archived = serializers.BooleanField(allow_null=True) |
| 409 |
|
| 410 |
serializer = TestSerializer(data=QueryDict('')) |
| 411 |
assert serializer.is_valid() |
| 412 |
assert serializer.validated_data == {'archived': None} |
| 413 |
|
| 414 |
def test_empty_html_checkbox_allow_null_with_default(self): |
| 415 |
""" |
| 416 |
BooleanField should respect default if set and still allow |
| 417 |
setting null values. |
| 418 |
""" |
| 419 |
class TestSerializer(serializers.Serializer): |
| 420 |
archived = serializers.BooleanField(allow_null=True, default=True) |
| 421 |
|
| 422 |
serializer = TestSerializer(data=QueryDict('')) |
| 423 |
assert serializer.is_valid() |
| 424 |
assert serializer.validated_data == {'archived': True} |
| 425 |
|
| 426 |
serializer = TestSerializer(data=QueryDict('archived=')) |
| 427 |
assert serializer.is_valid() |
| 428 |
assert serializer.validated_data == {'archived': None} |
| 429 |
|
| 430 |
|
| 431 |
class TestHTMLInput: |
| 432 |
def test_empty_html_charfield_with_default(self): |
| 433 |
class TestSerializer(serializers.Serializer): |
| 434 |
message = serializers.CharField(default='happy') |
| 435 |
|
| 436 |
serializer = TestSerializer(data=QueryDict('')) |
| 437 |
assert serializer.is_valid() |
| 438 |
assert serializer.validated_data == {'message': 'happy'} |
| 439 |
|
| 440 |
def test_empty_html_charfield_without_default(self): |
| 441 |
class TestSerializer(serializers.Serializer): |
| 442 |
message = serializers.CharField(allow_blank=True) |
| 443 |
|
| 444 |
serializer = TestSerializer(data=QueryDict('message=')) |
| 445 |
assert serializer.is_valid() |
| 446 |
assert serializer.validated_data == {'message': ''} |
| 447 |
|
| 448 |
def test_empty_html_charfield_without_default_not_required(self): |
| 449 |
class TestSerializer(serializers.Serializer): |
| 450 |
message = serializers.CharField(allow_blank=True, required=False) |
| 451 |
|
| 452 |
serializer = TestSerializer(data=QueryDict('message=')) |
| 453 |
assert serializer.is_valid() |
| 454 |
assert serializer.validated_data == {'message': ''} |
| 455 |
|
| 456 |
def test_empty_html_integerfield(self): |
| 457 |
class TestSerializer(serializers.Serializer): |
| 458 |
message = serializers.IntegerField(default=123) |
| 459 |
|
| 460 |
serializer = TestSerializer(data=QueryDict('message=')) |
| 461 |
assert serializer.is_valid() |
| 462 |
assert serializer.validated_data == {'message': 123} |
| 463 |
|
| 464 |
def test_empty_html_uuidfield_with_default(self): |
| 465 |
class TestSerializer(serializers.Serializer): |
| 466 |
message = serializers.UUIDField(default=uuid.uuid4) |
| 467 |
|
| 468 |
serializer = TestSerializer(data=QueryDict('message=')) |
| 469 |
assert serializer.is_valid() |
| 470 |
assert list(serializer.validated_data) == ['message'] |
| 471 |
|
| 472 |
def test_empty_html_uuidfield_with_optional(self): |
| 473 |
class TestSerializer(serializers.Serializer): |
| 474 |
message = serializers.UUIDField(required=False) |
| 475 |
|
| 476 |
serializer = TestSerializer(data=QueryDict('message=')) |
| 477 |
assert serializer.is_valid() |
| 478 |
assert list(serializer.validated_data) == [] |
| 479 |
|
| 480 |
def test_empty_html_charfield_allow_null(self): |
| 481 |
class TestSerializer(serializers.Serializer): |
| 482 |
message = serializers.CharField(allow_null=True) |
| 483 |
|
| 484 |
serializer = TestSerializer(data=QueryDict('message=')) |
| 485 |
assert serializer.is_valid() |
| 486 |
assert serializer.validated_data == {'message': None} |
| 487 |
|
| 488 |
def test_empty_html_datefield_allow_null(self): |
| 489 |
class TestSerializer(serializers.Serializer): |
| 490 |
expiry = serializers.DateField(allow_null=True) |
| 491 |
|
| 492 |
serializer = TestSerializer(data=QueryDict('expiry=')) |
| 493 |
assert serializer.is_valid() |
| 494 |
assert serializer.validated_data == {'expiry': None} |
| 495 |
|
| 496 |
def test_empty_html_charfield_allow_null_allow_blank(self): |
| 497 |
class TestSerializer(serializers.Serializer): |
| 498 |
message = serializers.CharField(allow_null=True, allow_blank=True) |
| 499 |
|
| 500 |
serializer = TestSerializer(data=QueryDict('message=')) |
| 501 |
assert serializer.is_valid() |
| 502 |
assert serializer.validated_data == {'message': ''} |
| 503 |
|
| 504 |
def test_empty_html_charfield_required_false(self): |
| 505 |
class TestSerializer(serializers.Serializer): |
| 506 |
message = serializers.CharField(required=False) |
| 507 |
|
| 508 |
serializer = TestSerializer(data=QueryDict('')) |
| 509 |
assert serializer.is_valid() |
| 510 |
assert serializer.validated_data == {} |
| 511 |
|
| 512 |
def test_querydict_list_input(self): |
| 513 |
class TestSerializer(serializers.Serializer): |
| 514 |
scores = serializers.ListField(child=serializers.IntegerField()) |
| 515 |
|
| 516 |
serializer = TestSerializer(data=QueryDict('scores=1&scores=3')) |
| 517 |
assert serializer.is_valid() |
| 518 |
assert serializer.validated_data == {'scores': [1, 3]} |
| 519 |
|
| 520 |
def test_querydict_list_input_only_one_input(self): |
| 521 |
class TestSerializer(serializers.Serializer): |
| 522 |
scores = serializers.ListField(child=serializers.IntegerField()) |
| 523 |
|
| 524 |
serializer = TestSerializer(data=QueryDict('scores=1&')) |
| 525 |
assert serializer.is_valid() |
| 526 |
assert serializer.validated_data == {'scores': [1]} |
| 527 |
|
| 528 |
def test_querydict_list_input_no_values_uses_default(self): |
| 529 |
""" |
| 530 |
When there are no values passed in, and default is set |
| 531 |
The field should return the default value |
| 532 |
""" |
| 533 |
class TestSerializer(serializers.Serializer): |
| 534 |
a = serializers.IntegerField(required=True) |
| 535 |
scores = serializers.ListField(default=lambda: [1, 3]) |
| 536 |
|
| 537 |
serializer = TestSerializer(data=QueryDict('a=1&')) |
| 538 |
assert serializer.is_valid() |
| 539 |
assert serializer.validated_data == {'a': 1, 'scores': [1, 3]} |
| 540 |
|
| 541 |
def test_querydict_list_input_supports_indexed_keys(self): |
| 542 |
""" |
| 543 |
When data is passed in the format `scores[0]=1&scores[1]=3` |
| 544 |
The field should return the correct list, ignoring the default |
| 545 |
""" |
| 546 |
class TestSerializer(serializers.Serializer): |
| 547 |
scores = serializers.ListField(default=lambda: [1, 3]) |
| 548 |
|
| 549 |
serializer = TestSerializer(data=QueryDict("scores[0]=5&scores[1]=6")) |
| 550 |
assert serializer.is_valid() |
| 551 |
assert serializer.validated_data == {'scores': ['5', '6']} |
| 552 |
|
| 553 |
def test_querydict_list_input_no_values_no_default_and_not_required(self): |
| 554 |
""" |
| 555 |
When there are no keys passed, there is no default, and required=False |
| 556 |
The field should be skipped |
| 557 |
""" |
| 558 |
class TestSerializer(serializers.Serializer): |
| 559 |
scores = serializers.ListField(required=False) |
| 560 |
|
| 561 |
serializer = TestSerializer(data=QueryDict('')) |
| 562 |
assert serializer.is_valid() |
| 563 |
assert serializer.validated_data == {} |
| 564 |
|
| 565 |
def test_querydict_list_input_posts_key_but_no_values(self): |
| 566 |
""" |
| 567 |
When there are no keys passed, there is no default, and required=False |
| 568 |
The field should return an array of 1 item, blank |
| 569 |
""" |
| 570 |
class TestSerializer(serializers.Serializer): |
| 571 |
scores = serializers.ListField(required=False) |
| 572 |
|
| 573 |
serializer = TestSerializer(data=QueryDict('scores=&')) |
| 574 |
assert serializer.is_valid() |
| 575 |
assert serializer.validated_data == {'scores': ['']} |
| 576 |
|
| 577 |
def test_partial_update_with_indexed_keys(self): |
| 578 |
""" |
| 579 |
Regression test for indexed HTML form keys with partial=True. |
| 580 |
When data is passed as `colors[0]=#ffffff&colors[1]=#000000` |
| 581 |
with partial=True, the field should parse indexed keys correctly. |
| 582 |
""" |
| 583 |
class TestSerializer(serializers.Serializer): |
| 584 |
colors = serializers.ListField( |
| 585 |
allow_null=True, |
| 586 |
child=serializers.CharField(max_length=7), |
| 587 |
required=False |
| 588 |
) |
| 589 |
name = serializers.CharField(max_length=100, required=False) |
| 590 |
|
| 591 |
serializer = TestSerializer( |
| 592 |
data=QueryDict('colors[0]=#ffffff&colors[1]=#000000'), |
| 593 |
partial=True |
| 594 |
) |
| 595 |
assert serializer.is_valid() |
| 596 |
assert serializer.validated_data == {'colors': ['#ffffff', '#000000']} |
| 597 |
|
| 598 |
def test_partial_update_omitted_list_field(self): |
| 599 |
""" |
| 600 |
When a ListField is omitted in a partial update (and there are no |
| 601 |
indexed keys for it), the field should be skipped and not included in |
| 602 |
the validated data. |
| 603 |
""" |
| 604 |
class TestSerializer(serializers.Serializer): |
| 605 |
colors = serializers.ListField( |
| 606 |
child=serializers.CharField(max_length=7), |
| 607 |
required=False |
| 608 |
) |
| 609 |
name = serializers.CharField(max_length=100) |
| 610 |
|
| 611 |
# colors is omitted, only name is provided |
| 612 |
serializer = TestSerializer( |
| 613 |
data=QueryDict('name=Test'), |
| 614 |
partial=True |
| 615 |
) |
| 616 |
assert serializer.is_valid() |
| 617 |
assert serializer.validated_data == {'name': 'Test'} |
| 618 |
assert 'colors' not in serializer.validated_data |
| 619 |
|
| 620 |
def test_partial_update_indexed_keys_ordering(self): |
| 621 |
""" |
| 622 |
Indexed keys should preserve the correct order even when |
| 623 |
they appear out of order in the QueryDict. |
| 624 |
""" |
| 625 |
class TestSerializer(serializers.Serializer): |
| 626 |
items = serializers.ListField( |
| 627 |
child=serializers.IntegerField(), |
| 628 |
required=False |
| 629 |
) |
| 630 |
|
| 631 |
serializer = TestSerializer( |
| 632 |
data=QueryDict('items[2]=3&items[0]=1&items[1]=2'), |
| 633 |
partial=True |
| 634 |
) |
| 635 |
assert serializer.is_valid() |
| 636 |
assert serializer.validated_data == {'items': [1, 2, 3]} |
| 637 |
|
| 638 |
|
| 639 |
class TestCreateOnlyDefault: |
| 640 |
def setup_method(self): |
| 641 |
default = serializers.CreateOnlyDefault('2001-01-01') |
| 642 |
|
| 643 |
class TestSerializer(serializers.Serializer): |
| 644 |
published = serializers.HiddenField(default=default) |
| 645 |
text = serializers.CharField() |
| 646 |
self.Serializer = TestSerializer |
| 647 |
|
| 648 |
def test_create_only_default_is_provided(self): |
| 649 |
serializer = self.Serializer(data={'text': 'example'}) |
| 650 |
assert serializer.is_valid() |
| 651 |
assert serializer.validated_data == { |
| 652 |
'text': 'example', 'published': '2001-01-01' |
| 653 |
} |
| 654 |
|
| 655 |
def test_create_only_default_is_not_provided_on_update(self): |
| 656 |
instance = { |
| 657 |
'text': 'example', 'published': '2001-01-01' |
| 658 |
} |
| 659 |
serializer = self.Serializer(instance, data={'text': 'example'}) |
| 660 |
assert serializer.is_valid() |
| 661 |
assert serializer.validated_data == { |
| 662 |
'text': 'example', |
| 663 |
} |
| 664 |
|
| 665 |
def test_create_only_default_callable_sets_context(self): |
| 666 |
""" |
| 667 |
CreateOnlyDefault instances with a callable default should set context |
| 668 |
on the callable if possible |
| 669 |
""" |
| 670 |
class TestCallableDefault: |
| 671 |
requires_context = True |
| 672 |
|
| 673 |
def __call__(self, field=None): |
| 674 |
return "success" if field is not None else "failure" |
| 675 |
|
| 676 |
class TestSerializer(serializers.Serializer): |
| 677 |
context_set = serializers.CharField(default=serializers.CreateOnlyDefault(TestCallableDefault())) |
| 678 |
|
| 679 |
serializer = TestSerializer(data={}) |
| 680 |
assert serializer.is_valid() |
| 681 |
assert serializer.validated_data['context_set'] == 'success' |
| 682 |
|
| 683 |
|
| 684 |
class Test5087Regression: |
| 685 |
def test_parent_binding(self): |
| 686 |
parent = serializers.Serializer() |
| 687 |
field = serializers.CharField() |
| 688 |
|
| 689 |
assert field.root is field |
| 690 |
field.bind('name', parent) |
| 691 |
assert field.root is parent |
| 692 |
|
| 693 |
|
| 694 |
class TestTyping(TestCase): |
| 695 |
def test_field_is_subscriptable(self): |
| 696 |
assert serializers.Field is serializers.Field["foo"] |
| 697 |
|
| 698 |
|
| 699 |
# Tests for field input and output values. |
| 700 |
# ---------------------------------------- |
| 701 |
|
| 702 |
def get_items(mapping_or_list_of_two_tuples): |
| 703 |
# Tests accept either lists of two tuples, or dictionaries. |
| 704 |
if isinstance(mapping_or_list_of_two_tuples, dict): |
| 705 |
# {value: expected} |
| 706 |
return mapping_or_list_of_two_tuples.items() |
| 707 |
# [(value, expected), ...] |
| 708 |
return mapping_or_list_of_two_tuples |
| 709 |
|
| 710 |
|
| 711 |
class FieldValues: |
| 712 |
""" |
| 713 |
Base class for testing valid and invalid input values. |
| 714 |
""" |
| 715 |
def test_valid_inputs(self, *args): |
| 716 |
""" |
| 717 |
Ensure that valid values return the expected validated data. |
| 718 |
""" |
| 719 |
for input_value, expected_output in get_items(self.valid_inputs): |
| 720 |
assert self.field.run_validation(input_value) == expected_output, \ |
| 721 |
f'input value: {repr(input_value)}' |
| 722 |
|
| 723 |
def test_invalid_inputs(self, *args): |
| 724 |
""" |
| 725 |
Ensure that invalid values raise the expected validation error. |
| 726 |
""" |
| 727 |
for input_value, expected_failure in get_items(self.invalid_inputs): |
| 728 |
with pytest.raises(serializers.ValidationError) as exc_info: |
| 729 |
self.field.run_validation(input_value) |
| 730 |
assert exc_info.value.detail == expected_failure, \ |
| 731 |
f'input value: {repr(input_value)}' |
| 732 |
|
| 733 |
def test_outputs(self, *args): |
| 734 |
for output_value, expected_output in get_items(self.outputs): |
| 735 |
assert self.field.to_representation(output_value) == expected_output, \ |
| 736 |
f'output value: {repr(output_value)}' |
| 737 |
|
| 738 |
|
| 739 |
# Boolean types... |
| 740 |
|
| 741 |
class TestBooleanField(FieldValues): |
| 742 |
""" |
| 743 |
Valid and invalid values for `BooleanField`. |
| 744 |
""" |
| 745 |
valid_inputs = { |
| 746 |
'True': True, |
| 747 |
'TRUE': True, |
| 748 |
'tRuE': True, |
| 749 |
't': True, |
| 750 |
'T': True, |
| 751 |
'true': True, |
| 752 |
'on': True, |
| 753 |
'ON': True, |
| 754 |
'oN': True, |
| 755 |
'False': False, |
| 756 |
'FALSE': False, |
| 757 |
'fALse': False, |
| 758 |
'f': False, |
| 759 |
'F': False, |
| 760 |
'false': False, |
| 761 |
'off': False, |
| 762 |
'OFF': False, |
| 763 |
'oFf': False, |
| 764 |
'1': True, |
| 765 |
'0': False, |
| 766 |
1: True, |
| 767 |
0: False, |
| 768 |
True: True, |
| 769 |
False: False, |
| 770 |
} |
| 771 |
invalid_inputs = { |
| 772 |
'foo': ['Must be a valid boolean.'], |
| 773 |
None: ['This field may not be null.'] |
| 774 |
} |
| 775 |
outputs = [ |
| 776 |
('True', True), |
| 777 |
('TRUE', True), |
| 778 |
('tRuE', True), |
| 779 |
('t', True), |
| 780 |
('T', True), |
| 781 |
('true', True), |
| 782 |
('on', True), |
| 783 |
('ON', True), |
| 784 |
('oN', True), |
| 785 |
('False', False), |
| 786 |
('FALSE', False), |
| 787 |
('fALse', False), |
| 788 |
('f', False), |
| 789 |
('F', False), |
| 790 |
('false', False), |
| 791 |
('off', False), |
| 792 |
('OFF', False), |
| 793 |
('oFf', False), |
| 794 |
('1', True), |
| 795 |
('0', False), |
| 796 |
(1, True), |
| 797 |
(0, False), |
| 798 |
(True, True), |
| 799 |
(False, False), |
| 800 |
('other', True), |
| 801 |
([], False), |
| 802 |
({}, False), |
| 803 |
(set(), False), |
| 804 |
([1], True), |
| 805 |
({'example': 'value'}, True), |
| 806 |
] |
| 807 |
field = serializers.BooleanField() |
| 808 |
|
| 809 |
def test_disallow_unhashable_collection_types(self): |
| 810 |
inputs = ( |
| 811 |
[], |
| 812 |
{}, |
| 813 |
) |
| 814 |
field = self.field |
| 815 |
for input_value in inputs: |
| 816 |
with pytest.raises(serializers.ValidationError) as exc_info: |
| 817 |
field.run_validation(input_value) |
| 818 |
expected = ['Must be a valid boolean.'] |
| 819 |
assert exc_info.value.detail == expected |
| 820 |
|
| 821 |
|
| 822 |
class TestNullableBooleanField(TestBooleanField): |
| 823 |
""" |
| 824 |
Valid and invalid values for `BooleanField` when `allow_null=True`. |
| 825 |
""" |
| 826 |
valid_inputs = { |
| 827 |
'true': True, |
| 828 |
'false': False, |
| 829 |
'null': None, |
| 830 |
True: True, |
| 831 |
False: False, |
| 832 |
None: None |
| 833 |
} |
| 834 |
invalid_inputs = { |
| 835 |
'foo': ['Must be a valid boolean.'], |
| 836 |
} |
| 837 |
outputs = { |
| 838 |
'true': True, |
| 839 |
'false': False, |
| 840 |
'null': None, |
| 841 |
True: True, |
| 842 |
False: False, |
| 843 |
None: None, |
| 844 |
'other': True |
| 845 |
} |
| 846 |
field = serializers.BooleanField(allow_null=True) |
| 847 |
|
| 848 |
|
| 849 |
# String types... |
| 850 |
|
| 851 |
class TestCharField(FieldValues): |
| 852 |
""" |
| 853 |
Valid and invalid values for `CharField`. |
| 854 |
""" |
| 855 |
valid_inputs = { |
| 856 |
1: '1', |
| 857 |
'abc': 'abc' |
| 858 |
} |
| 859 |
invalid_inputs = { |
| 860 |
(): ['Not a valid string.'], |
| 861 |
True: ['Not a valid string.'], |
| 862 |
'': ['This field may not be blank.'] |
| 863 |
} |
| 864 |
outputs = { |
| 865 |
1: '1', |
| 866 |
'abc': 'abc' |
| 867 |
} |
| 868 |
field = serializers.CharField() |
| 869 |
|
| 870 |
def test_trim_whitespace_default(self): |
| 871 |
field = serializers.CharField() |
| 872 |
assert field.to_internal_value(' abc ') == 'abc' |
| 873 |
|
| 874 |
def test_trim_whitespace_disabled(self): |
| 875 |
field = serializers.CharField(trim_whitespace=False) |
| 876 |
assert field.to_internal_value(' abc ') == ' abc ' |
| 877 |
|
| 878 |
def test_disallow_blank_with_trim_whitespace(self): |
| 879 |
field = serializers.CharField(allow_blank=False, trim_whitespace=True) |
| 880 |
|
| 881 |
with pytest.raises(serializers.ValidationError) as exc_info: |
| 882 |
field.run_validation(' ') |
| 883 |
assert exc_info.value.detail == ['This field may not be blank.'] |
| 884 |
|
| 885 |
def test_null_bytes(self): |
| 886 |
field = serializers.CharField() |
| 887 |
|
| 888 |
for value in ('\0', 'foo\0', '\0foo', 'foo\0foo'): |
| 889 |
with pytest.raises(serializers.ValidationError) as exc_info: |
| 890 |
field.run_validation(value) |
| 891 |
assert exc_info.value.detail == [ |
| 892 |
'Null characters are not allowed.' |
| 893 |
] |
| 894 |
|
| 895 |
def test_surrogate_characters(self): |
| 896 |
field = serializers.CharField() |
| 897 |
|
| 898 |
for code_point, expected_message in ( |
| 899 |
(0xD800, 'Surrogate characters are not allowed: U+D800.'), |
| 900 |
(0xDFFF, 'Surrogate characters are not allowed: U+DFFF.'), |
| 901 |
): |
| 902 |
with pytest.raises(serializers.ValidationError) as exc_info: |
| 903 |
field.run_validation(chr(code_point)) |
| 904 |
assert exc_info.value.detail[0].code == 'surrogate_characters_not_allowed' |
| 905 |
assert str(exc_info.value.detail[0]) == expected_message |
| 906 |
|
| 907 |
for code_point in (0xD800 - 1, 0xDFFF + 1): |
| 908 |
field.run_validation(chr(code_point)) |
| 909 |
|
| 910 |
def test_iterable_validators(self): |
| 911 |
""" |
| 912 |
Ensure `validators` parameter is compatible with reasonable iterables. |
| 913 |
""" |
| 914 |
value = 'example' |
| 915 |
|
| 916 |
for validators in ([], (), set()): |
| 917 |
field = serializers.CharField(validators=validators) |
| 918 |
field.run_validation(value) |
| 919 |
|
| 920 |
def raise_exception(value): |
| 921 |
raise exceptions.ValidationError('Raised error') |
| 922 |
|
| 923 |
for validators in ([raise_exception], (raise_exception,), {raise_exception}): |
| 924 |
field = serializers.CharField(validators=validators) |
| 925 |
with pytest.raises(serializers.ValidationError) as exc_info: |
| 926 |
field.run_validation(value) |
| 927 |
assert exc_info.value.detail == ['Raised error'] |
| 928 |
|
| 929 |
|
| 930 |
class TestEmailField(FieldValues): |
| 931 |
""" |
| 932 |
Valid and invalid values for `EmailField`. |
| 933 |
""" |
| 934 |
valid_inputs = { |
| 935 |
'[email protected]': '[email protected]', |
| 936 |
' [email protected] ': '[email protected]', |
| 937 |
} |
| 938 |
invalid_inputs = { |
| 939 |
'examplecom': ['Enter a valid email address.'] |
| 940 |
} |
| 941 |
outputs = {} |
| 942 |
field = serializers.EmailField() |
| 943 |
|
| 944 |
|
| 945 |
class TestRegexField(FieldValues): |
| 946 |
""" |
| 947 |
Valid and invalid values for `RegexField`. |
| 948 |
""" |
| 949 |
valid_inputs = { |
| 950 |
'a9': 'a9', |
| 951 |
} |
| 952 |
invalid_inputs = { |
| 953 |
'A9': ["This value does not match the required pattern."] |
| 954 |
} |
| 955 |
outputs = {} |
| 956 |
field = serializers.RegexField(regex='[a-z][0-9]') |
| 957 |
|
| 958 |
|
| 959 |
class TestiCompiledRegexField(FieldValues): |
| 960 |
""" |
| 961 |
Valid and invalid values for `RegexField`. |
| 962 |
""" |
| 963 |
valid_inputs = { |
| 964 |
'a9': 'a9', |
| 965 |
} |
| 966 |
invalid_inputs = { |
| 967 |
'A9': ["This value does not match the required pattern."] |
| 968 |
} |
| 969 |
outputs = {} |
| 970 |
field = serializers.RegexField(regex=re.compile('[a-z][0-9]')) |
| 971 |
|
| 972 |
|
| 973 |
class TestSlugField(FieldValues): |
| 974 |
""" |
| 975 |
Valid and invalid values for `SlugField`. |
| 976 |
""" |
| 977 |
valid_inputs = { |
| 978 |
'slug-99': 'slug-99', |
| 979 |
} |
| 980 |
invalid_inputs = { |
| 981 |
'slug 99': ['Enter a valid "slug" consisting of letters, numbers, underscores or hyphens.'] |
| 982 |
} |
| 983 |
outputs = {} |
| 984 |
field = serializers.SlugField() |
| 985 |
|
| 986 |
def test_allow_unicode_true(self): |
| 987 |
field = serializers.SlugField(allow_unicode=True) |
| 988 |
|
| 989 |
validation_error = False |
| 990 |
try: |
| 991 |
field.run_validation('slug-99-\u0420') |
| 992 |
except serializers.ValidationError: |
| 993 |
validation_error = True |
| 994 |
|
| 995 |
assert not validation_error |
| 996 |
|
| 997 |
|
| 998 |
class TestURLField(FieldValues): |
| 999 |
""" |
| 1000 |
Valid and invalid values for `URLField`. |
| 1001 |
""" |
| 1002 |
valid_inputs = { |
| 1003 |
'http://example.com': 'http://example.com', |
| 1004 |
} |
| 1005 |
invalid_inputs = { |
| 1006 |
'example.com': ['Enter a valid URL.'] |
| 1007 |
} |
| 1008 |
outputs = {} |
| 1009 |
field = serializers.URLField() |
| 1010 |
|
| 1011 |
|
| 1012 |
class TestUUIDField(FieldValues): |
| 1013 |
""" |
| 1014 |
Valid and invalid values for `UUIDField`. |
| 1015 |
""" |
| 1016 |
valid_inputs = { |
| 1017 |
'825d7aeb-05a9-45b5-a5b7-05df87923cda': uuid.UUID('825d7aeb-05a9-45b5-a5b7-05df87923cda'), |
| 1018 |
'825d7aeb05a945b5a5b705df87923cda': uuid.UUID('825d7aeb-05a9-45b5-a5b7-05df87923cda'), |
| 1019 |
'urn:uuid:213b7d9b-244f-410d-828c-dabce7a2615d': uuid.UUID('213b7d9b-244f-410d-828c-dabce7a2615d'), |
| 1020 |
284758210125106368185219588917561929842: uuid.UUID('d63a6fb6-88d5-40c7-a91c-9edf73283072') |
| 1021 |
} |
| 1022 |
invalid_inputs = { |
| 1023 |
'825d7aeb-05a9-45b5-a5b7': ['Must be a valid UUID.'], |
| 1024 |
(1, 2, 3): ['Must be a valid UUID.'] |
| 1025 |
} |
| 1026 |
outputs = { |
| 1027 |
uuid.UUID('825d7aeb-05a9-45b5-a5b7-05df87923cda'): '825d7aeb-05a9-45b5-a5b7-05df87923cda' |
| 1028 |
} |
| 1029 |
field = serializers.UUIDField() |
| 1030 |
|
| 1031 |
def _test_format(self, uuid_format, formatted_uuid_0): |
| 1032 |
field = serializers.UUIDField(format=uuid_format) |
| 1033 |
assert field.to_representation(uuid.UUID(int=0)) == formatted_uuid_0 |
| 1034 |
assert field.to_internal_value(formatted_uuid_0) == uuid.UUID(int=0) |
| 1035 |
|
| 1036 |
def test_formats(self): |
| 1037 |
self._test_format('int', 0) |
| 1038 |
self._test_format('hex_verbose', '00000000-0000-0000-0000-000000000000') |
| 1039 |
self._test_format('urn', 'urn:uuid:00000000-0000-0000-0000-000000000000') |
| 1040 |
self._test_format('hex', '0' * 32) |
| 1041 |
|
| 1042 |
|
| 1043 |
class TestIPAddressField(FieldValues): |
| 1044 |
""" |
| 1045 |
Valid and invalid values for `IPAddressField` |
| 1046 |
""" |
| 1047 |
valid_inputs = { |
| 1048 |
'127.0.0.1': '127.0.0.1', |
| 1049 |
'192.168.33.255': '192.168.33.255', |
| 1050 |
'2001:0db8:85a3:0042:1000:8a2e:0370:7334': '2001:db8:85a3:42:1000:8a2e:370:7334', |
| 1051 |
'2001:cdba:0:0:0:0:3257:9652': '2001:cdba::3257:9652', |
| 1052 |
'2001:cdba::3257:9652': '2001:cdba::3257:9652' |
| 1053 |
} |
| 1054 |
invalid_inputs = { |
| 1055 |
'127001': ['Enter a valid IPv4 or IPv6 address.'], |
| 1056 |
'127.122.111.2231': ['Enter a valid IPv4 or IPv6 address.'], |
| 1057 |
'2001:::9652': ['Enter a valid IPv4 or IPv6 address.'], |
| 1058 |
'2001:0db8:85a3:0042:1000:8a2e:0370:73341': ['Enter a valid IPv4 or IPv6 address.'], |
| 1059 |
1000: ['Enter a valid IPv4 or IPv6 address.'], |
| 1060 |
} |
| 1061 |
outputs = {} |
| 1062 |
field = serializers.IPAddressField() |
| 1063 |
|
| 1064 |
|
| 1065 |
class TestIPv4AddressField(FieldValues): |
| 1066 |
""" |
| 1067 |
Valid and invalid values for `IPAddressField` |
| 1068 |
""" |
| 1069 |
valid_inputs = { |
| 1070 |
'127.0.0.1': '127.0.0.1', |
| 1071 |
'192.168.33.255': '192.168.33.255', |
| 1072 |
} |
| 1073 |
invalid_inputs = { |
| 1074 |
'127001': ['Enter a valid IPv4 address.'], |
| 1075 |
'127.122.111.2231': ['Enter a valid IPv4 address.'], |
| 1076 |
} |
| 1077 |
outputs = {} |
| 1078 |
field = serializers.IPAddressField(protocol='IPv4') |
| 1079 |
|
| 1080 |
|
| 1081 |
class TestIPv6AddressField(FieldValues): |
| 1082 |
""" |
| 1083 |
Valid and invalid values for `IPAddressField` |
| 1084 |
""" |
| 1085 |
valid_inputs = { |
| 1086 |
'2001:0db8:85a3:0042:1000:8a2e:0370:7334': '2001:db8:85a3:42:1000:8a2e:370:7334', |
| 1087 |
'2001:cdba:0:0:0:0:3257:9652': '2001:cdba::3257:9652', |
| 1088 |
'2001:cdba::3257:9652': '2001:cdba::3257:9652' |
| 1089 |
} |
| 1090 |
invalid_inputs = { |
| 1091 |
'2001:::9652': ['Enter a valid IPv4 or IPv6 address.'], |
| 1092 |
'2001:0db8:85a3:0042:1000:8a2e:0370:73341': ['Enter a valid IPv4 or IPv6 address.'], |
| 1093 |
} |
| 1094 |
outputs = {} |
| 1095 |
field = serializers.IPAddressField(protocol='IPv6') |
| 1096 |
|
| 1097 |
|
| 1098 |
class TestFilePathField(FieldValues): |
| 1099 |
""" |
| 1100 |
Valid and invalid values for `FilePathField` |
| 1101 |
""" |
| 1102 |
|
| 1103 |
valid_inputs = { |
| 1104 |
__file__: __file__, |
| 1105 |
} |
| 1106 |
invalid_inputs = { |
| 1107 |
'wrong_path': ['"wrong_path" is not a valid path choice.'] |
| 1108 |
} |
| 1109 |
outputs = { |
| 1110 |
} |
| 1111 |
field = serializers.FilePathField( |
| 1112 |
path=os.path.abspath(os.path.dirname(__file__)) |
| 1113 |
) |
| 1114 |
|
| 1115 |
|
| 1116 |
# Number types... |
| 1117 |
|
| 1118 |
class TestIntegerField(FieldValues): |
| 1119 |
""" |
| 1120 |
Valid and invalid values for `IntegerField`. |
| 1121 |
""" |
| 1122 |
valid_inputs = { |
| 1123 |
'1': 1, |
| 1124 |
'0': 0, |
| 1125 |
1: 1, |
| 1126 |
0: 0, |
| 1127 |
1.0: 1, |
| 1128 |
0.0: 0, |
| 1129 |
'1.0': 1 |
| 1130 |
} |
| 1131 |
invalid_inputs = { |
| 1132 |
0.5: ['A valid integer is required.'], |
| 1133 |
'abc': ['A valid integer is required.'], |
| 1134 |
'0.5': ['A valid integer is required.'], |
| 1135 |
'inf': ['A valid integer is required.'], |
| 1136 |
'nan': ['A valid integer is required.'], |
| 1137 |
'1e400': ['A valid integer is required.'], |
| 1138 |
} |
| 1139 |
outputs = { |
| 1140 |
'1': 1, |
| 1141 |
'0': 0, |
| 1142 |
1: 1, |
| 1143 |
0: 0, |
| 1144 |
1.0: 1, |
| 1145 |
0.0: 0 |
| 1146 |
} |
| 1147 |
field = serializers.IntegerField() |
| 1148 |
|
| 1149 |
|
| 1150 |
class TestMinMaxIntegerField(FieldValues): |
| 1151 |
""" |
| 1152 |
Valid and invalid values for `IntegerField` with min and max limits. |
| 1153 |
""" |
| 1154 |
valid_inputs = { |
| 1155 |
'1': 1, |
| 1156 |
'3': 3, |
| 1157 |
1: 1, |
| 1158 |
3: 3, |
| 1159 |
} |
| 1160 |
invalid_inputs = { |
| 1161 |
0: ['Ensure this value is greater than or equal to 1.'], |
| 1162 |
4: ['Ensure this value is less than or equal to 3.'], |
| 1163 |
'0': ['Ensure this value is greater than or equal to 1.'], |
| 1164 |
'4': ['Ensure this value is less than or equal to 3.'], |
| 1165 |
} |
| 1166 |
outputs = {} |
| 1167 |
field = serializers.IntegerField(min_value=1, max_value=3) |
| 1168 |
|
| 1169 |
|
| 1170 |
class TestBigIntegerField(FieldValues): |
| 1171 |
""" |
| 1172 |
Valid and invalid values for `BigIntegerField`. |
| 1173 |
""" |
| 1174 |
valid_inputs = { |
| 1175 |
'1': 1, |
| 1176 |
'0': 0, |
| 1177 |
1: 1, |
| 1178 |
0: 0, |
| 1179 |
123: 123, |
| 1180 |
-123: -123, |
| 1181 |
'999999999999999999999999999': 999999999999999999999999999, |
| 1182 |
-999999999999999999999999999: -999999999999999999999999999, |
| 1183 |
1.0: 1, |
| 1184 |
0.0: 0, |
| 1185 |
'1.0': 1 |
| 1186 |
} |
| 1187 |
invalid_inputs = { |
| 1188 |
0.5: ['A valid biginteger is required.'], |
| 1189 |
'abc': ['A valid biginteger is required.'], |
| 1190 |
'0.5': ['A valid biginteger is required.'] |
| 1191 |
} |
| 1192 |
outputs = { |
| 1193 |
'1': 1, |
| 1194 |
'0': 0, |
| 1195 |
1: 1, |
| 1196 |
0: 0, |
| 1197 |
1.0: 1, |
| 1198 |
0.0: 0, |
| 1199 |
'999999999999999999999999999': 999999999999999999999999999, |
| 1200 |
-999999999999999999999999999: -999999999999999999999999999 |
| 1201 |
} |
| 1202 |
field = serializers.BigIntegerField() |
| 1203 |
|
| 1204 |
|
| 1205 |
class TestMinMaxBigIntegerField(FieldValues): |
| 1206 |
""" |
| 1207 |
Valid and invalid values for `BigIntegerField` with min and max limits. |
| 1208 |
""" |
| 1209 |
valid_inputs = { |
| 1210 |
'1': 1, |
| 1211 |
'3': 3, |
| 1212 |
1: 1, |
| 1213 |
3: 3, |
| 1214 |
} |
| 1215 |
invalid_inputs = { |
| 1216 |
0: ['Ensure this value is greater than or equal to 1.'], |
| 1217 |
4: ['Ensure this value is less than or equal to 3.'], |
| 1218 |
'0': ['Ensure this value is greater than or equal to 1.'], |
| 1219 |
'4': ['Ensure this value is less than or equal to 3.'], |
| 1220 |
} |
| 1221 |
outputs = {} |
| 1222 |
field = serializers.BigIntegerField(min_value=1, max_value=3) |
| 1223 |
|
| 1224 |
|
| 1225 |
class TestCoercionBigIntegerField(TestCase): |
| 1226 |
|
| 1227 |
def test_force_coerce_to_string(self): |
| 1228 |
field = serializers.BigIntegerField(coerce_to_string=True) |
| 1229 |
value = field.to_representation(1) |
| 1230 |
assert isinstance(value, str) |
| 1231 |
assert value == "1" |
| 1232 |
|
| 1233 |
|
| 1234 |
class TestFloatField(FieldValues): |
| 1235 |
""" |
| 1236 |
Valid and invalid values for `FloatField`. |
| 1237 |
""" |
| 1238 |
valid_inputs = { |
| 1239 |
'1': 1.0, |
| 1240 |
'0': 0.0, |
| 1241 |
1: 1.0, |
| 1242 |
0: 0.0, |
| 1243 |
1.0: 1.0, |
| 1244 |
0.0: 0.0, |
| 1245 |
} |
| 1246 |
invalid_inputs = { |
| 1247 |
'abc': ["A valid number is required."], |
| 1248 |
'nan': ["A valid number is required."], |
| 1249 |
'inf': ["A valid number is required."], |
| 1250 |
'-inf': ["A valid number is required."], |
| 1251 |
'1e400': ["A valid number is required."], |
| 1252 |
float('nan'): ["A valid number is required."], |
| 1253 |
float('inf'): ["A valid number is required."], |
| 1254 |
} |
| 1255 |
outputs = { |
| 1256 |
'1': 1.0, |
| 1257 |
'0': 0.0, |
| 1258 |
1: 1.0, |
| 1259 |
0: 0.0, |
| 1260 |
1.0: 1.0, |
| 1261 |
0.0: 0.0, |
| 1262 |
} |
| 1263 |
field = serializers.FloatField() |
| 1264 |
|
| 1265 |
|
| 1266 |
class TestMinMaxFloatField(FieldValues): |
| 1267 |
""" |
| 1268 |
Valid and invalid values for `FloatField` with min and max limits. |
| 1269 |
""" |
| 1270 |
valid_inputs = { |
| 1271 |
'1': 1, |
| 1272 |
'3': 3, |
| 1273 |
1: 1, |
| 1274 |
3: 3, |
| 1275 |
1.0: 1.0, |
| 1276 |
3.0: 3.0, |
| 1277 |
} |
| 1278 |
invalid_inputs = { |
| 1279 |
0.9: ['Ensure this value is greater than or equal to 1.'], |
| 1280 |
3.1: ['Ensure this value is less than or equal to 3.'], |
| 1281 |
'0.0': ['Ensure this value is greater than or equal to 1.'], |
| 1282 |
'3.1': ['Ensure this value is less than or equal to 3.'], |
| 1283 |
} |
| 1284 |
outputs = {} |
| 1285 |
field = serializers.FloatField(min_value=1, max_value=3) |
| 1286 |
|
| 1287 |
|
| 1288 |
class TestFloatFieldOverFlowError(TestCase): |
| 1289 |
def test_overflow_error_float_field(self): |
| 1290 |
field = serializers.FloatField() |
| 1291 |
with pytest.raises(serializers.ValidationError) as exec_info: |
| 1292 |
field.to_internal_value(data=math.factorial(171)) |
| 1293 |
assert "Integer value too large to convert to float" in str(exec_info.value.detail) |
| 1294 |
|
| 1295 |
|
| 1296 |
class TestDecimalField(FieldValues): |
| 1297 |
""" |
| 1298 |
Valid and invalid values for `DecimalField`. |
| 1299 |
""" |
| 1300 |
valid_inputs = { |
| 1301 |
'12.3': Decimal('12.3'), |
| 1302 |
'0.1': Decimal('0.1'), |
| 1303 |
10: Decimal('10'), |
| 1304 |
0: Decimal('0'), |
| 1305 |
12.3: Decimal('12.3'), |
| 1306 |
0.1: Decimal('0.1'), |
| 1307 |
'2E+1': Decimal('20'), |
| 1308 |
} |
| 1309 |
invalid_inputs = ( |
| 1310 |
(None, ["This field may not be null."]), |
| 1311 |
('', ["A valid number is required."]), |
| 1312 |
(' ', ["A valid number is required."]), |
| 1313 |
('abc', ["A valid number is required."]), |
| 1314 |
(Decimal('Nan'), ["A valid number is required."]), |
| 1315 |
(Decimal('Snan'), ["A valid number is required."]), |
| 1316 |
(Decimal('Inf'), ["A valid number is required."]), |
| 1317 |
('12.345', ["Ensure that there are no more than 3 digits in total."]), |
| 1318 |
(200000000000.0, ["Ensure that there are no more than 3 digits in total."]), |
| 1319 |
('0.01', ["Ensure that there are no more than 1 decimal places."]), |
| 1320 |
(123, ["Ensure that there are no more than 2 digits before the decimal point."]), |
| 1321 |
('2E+2', ["Ensure that there are no more than 2 digits before the decimal point."]) |
| 1322 |
) |
| 1323 |
outputs = { |
| 1324 |
'1': '1.0', |
| 1325 |
'0': '0.0', |
| 1326 |
'1.09': '1.1', |
| 1327 |
'0.04': '0.0', |
| 1328 |
1: '1.0', |
| 1329 |
0: '0.0', |
| 1330 |
Decimal('1.0'): '1.0', |
| 1331 |
Decimal('0.0'): '0.0', |
| 1332 |
Decimal('1.09'): '1.1', |
| 1333 |
Decimal('0.04'): '0.0' |
| 1334 |
} |
| 1335 |
field = serializers.DecimalField(max_digits=3, decimal_places=1) |
| 1336 |
|
| 1337 |
|
| 1338 |
class TestAllowNullDecimalField(FieldValues): |
| 1339 |
valid_inputs = { |
| 1340 |
None: None, |
| 1341 |
'': None, |
| 1342 |
' ': None, |
| 1343 |
} |
| 1344 |
invalid_inputs = {} |
| 1345 |
outputs = { |
| 1346 |
None: '', |
| 1347 |
} |
| 1348 |
field = serializers.DecimalField(max_digits=3, decimal_places=1, allow_null=True) |
| 1349 |
|
| 1350 |
|
| 1351 |
class TestAllowNullNoStringCoercionDecimalField(FieldValues): |
| 1352 |
valid_inputs = { |
| 1353 |
None: None, |
| 1354 |
'': None, |
| 1355 |
' ': None, |
| 1356 |
} |
| 1357 |
invalid_inputs = {} |
| 1358 |
outputs = { |
| 1359 |
None: None, |
| 1360 |
} |
| 1361 |
field = serializers.DecimalField(max_digits=3, decimal_places=1, allow_null=True, coerce_to_string=False) |
| 1362 |
|
| 1363 |
|
| 1364 |
class TestMinMaxDecimalField(FieldValues): |
| 1365 |
""" |
| 1366 |
Valid and invalid values for `DecimalField` with min and max limits. |
| 1367 |
""" |
| 1368 |
valid_inputs = { |
| 1369 |
'10.0': Decimal('10.0'), |
| 1370 |
'20.0': Decimal('20.0'), |
| 1371 |
} |
| 1372 |
invalid_inputs = { |
| 1373 |
'9.9': ['Ensure this value is greater than or equal to 10.0.'], |
| 1374 |
'20.1': ['Ensure this value is less than or equal to 20.0.'], |
| 1375 |
} |
| 1376 |
outputs = {} |
| 1377 |
field = serializers.DecimalField( |
| 1378 |
max_digits=3, decimal_places=1, |
| 1379 |
min_value=10.0, max_value=20.0 |
| 1380 |
) |
| 1381 |
|
| 1382 |
def test_warning_when_not_decimal_types(self, caplog): |
| 1383 |
with warnings.catch_warnings(record=True) as w: |
| 1384 |
warnings.simplefilter('always') |
| 1385 |
|
| 1386 |
serializers.DecimalField( |
| 1387 |
max_digits=3, decimal_places=1, |
| 1388 |
min_value=10.0, max_value=20.0 |
| 1389 |
) |
| 1390 |
|
| 1391 |
assert len(w) == 2 |
| 1392 |
assert all(issubclass(i.category, UserWarning) for i in w) |
| 1393 |
|
| 1394 |
assert 'max_value should be an integer or Decimal instance' in str(w[0].message) |
| 1395 |
assert 'min_value should be an integer or Decimal instance' in str(w[1].message) |
| 1396 |
|
| 1397 |
|
| 1398 |
class TestAllowEmptyStrDecimalFieldWithValidators(FieldValues): |
| 1399 |
""" |
| 1400 |
Check that empty string ('', ' ') is acceptable value for the DecimalField |
| 1401 |
if allow_null=True and there are max/min validators |
| 1402 |
""" |
| 1403 |
valid_inputs = { |
| 1404 |
None: None, |
| 1405 |
'': None, |
| 1406 |
' ': None, |
| 1407 |
' ': None, |
| 1408 |
5: Decimal('5'), |
| 1409 |
'0': Decimal('0'), |
| 1410 |
'10': Decimal('10'), |
| 1411 |
} |
| 1412 |
invalid_inputs = { |
| 1413 |
-1: ['Ensure this value is greater than or equal to 0.'], |
| 1414 |
11: ['Ensure this value is less than or equal to 10.'], |
| 1415 |
} |
| 1416 |
outputs = { |
| 1417 |
None: '', |
| 1418 |
} |
| 1419 |
field = serializers.DecimalField(max_digits=3, decimal_places=1, allow_null=True, min_value=0, max_value=10) |
| 1420 |
|
| 1421 |
|
| 1422 |
class TestNoMaxDigitsDecimalField(FieldValues): |
| 1423 |
field = serializers.DecimalField( |
| 1424 |
max_value=100, min_value=0, |
| 1425 |
decimal_places=2, max_digits=None |
| 1426 |
) |
| 1427 |
valid_inputs = { |
| 1428 |
'10': Decimal('10.00') |
| 1429 |
} |
| 1430 |
invalid_inputs = {} |
| 1431 |
outputs = {} |
| 1432 |
|
| 1433 |
|
| 1434 |
class TestNoStringCoercionDecimalField(FieldValues): |
| 1435 |
""" |
| 1436 |
Output values for `DecimalField` with `coerce_to_string=False`. |
| 1437 |
""" |
| 1438 |
valid_inputs = {} |
| 1439 |
invalid_inputs = {} |
| 1440 |
outputs = { |
| 1441 |
1.09: Decimal('1.1'), |
| 1442 |
0.04: Decimal('0.0'), |
| 1443 |
'1.09': Decimal('1.1'), |
| 1444 |
'0.04': Decimal('0.0'), |
| 1445 |
Decimal('1.09'): Decimal('1.1'), |
| 1446 |
Decimal('0.04'): Decimal('0.0'), |
| 1447 |
} |
| 1448 |
field = serializers.DecimalField( |
| 1449 |
max_digits=3, decimal_places=1, |
| 1450 |
coerce_to_string=False |
| 1451 |
) |
| 1452 |
|
| 1453 |
|
| 1454 |
class TestLocalizedDecimalField(TestCase): |
| 1455 |
@override_settings(LANGUAGE_CODE='pl') |
| 1456 |
def test_to_internal_value(self): |
| 1457 |
field = serializers.DecimalField(max_digits=2, decimal_places=1, localize=True) |
| 1458 |
assert field.to_internal_value('1,1') == Decimal('1.1') |
| 1459 |
|
| 1460 |
@override_settings(LANGUAGE_CODE='pl') |
| 1461 |
def test_to_representation(self): |
| 1462 |
field = serializers.DecimalField(max_digits=2, decimal_places=1, localize=True) |
| 1463 |
assert field.to_representation(Decimal('1.1')) == '1,1' |
| 1464 |
|
| 1465 |
def test_localize_forces_coerce_to_string(self): |
| 1466 |
field = serializers.DecimalField(max_digits=2, decimal_places=1, coerce_to_string=False, localize=True) |
| 1467 |
assert isinstance(field.to_representation(Decimal('1.1')), str) |
| 1468 |
|
| 1469 |
|
| 1470 |
class TestQuantizedValueForDecimal(TestCase): |
| 1471 |
def test_int_quantized_value_for_decimal(self): |
| 1472 |
field = serializers.DecimalField(max_digits=4, decimal_places=2) |
| 1473 |
value = field.to_internal_value(12).as_tuple() |
| 1474 |
expected_digit_tuple = (0, (1, 2, 0, 0), -2) |
| 1475 |
assert value == expected_digit_tuple |
| 1476 |
|
| 1477 |
def test_string_quantized_value_for_decimal(self): |
| 1478 |
field = serializers.DecimalField(max_digits=4, decimal_places=2) |
| 1479 |
value = field.to_internal_value('12').as_tuple() |
| 1480 |
expected_digit_tuple = (0, (1, 2, 0, 0), -2) |
| 1481 |
assert value == expected_digit_tuple |
| 1482 |
|
| 1483 |
def test_part_precision_string_quantized_value_for_decimal(self): |
| 1484 |
field = serializers.DecimalField(max_digits=4, decimal_places=2) |
| 1485 |
value = field.to_internal_value('12.0').as_tuple() |
| 1486 |
expected_digit_tuple = (0, (1, 2, 0, 0), -2) |
| 1487 |
assert value == expected_digit_tuple |
| 1488 |
|
| 1489 |
|
| 1490 |
class TestNormalizedOutputValueDecimalField(TestCase): |
| 1491 |
""" |
| 1492 |
Test that we get the expected behavior of on DecimalField when normalize=True |
| 1493 |
""" |
| 1494 |
|
| 1495 |
def test_normalize_output(self): |
| 1496 |
field = serializers.DecimalField(max_digits=4, decimal_places=3, normalize_output=True) |
| 1497 |
output = field.to_representation(Decimal('1.000')) |
| 1498 |
assert output == '1' |
| 1499 |
|
| 1500 |
def test_non_normalize_output(self): |
| 1501 |
field = serializers.DecimalField(max_digits=4, decimal_places=3, normalize_output=False) |
| 1502 |
output = field.to_representation(Decimal('1.000')) |
| 1503 |
assert output == '1.000' |
| 1504 |
|
| 1505 |
def test_normalize_coeherce_to_string(self): |
| 1506 |
field = serializers.DecimalField(max_digits=4, decimal_places=3, normalize_output=True, coerce_to_string=False) |
| 1507 |
output = field.to_representation(Decimal('1.000')) |
| 1508 |
assert output == Decimal('1') |
| 1509 |
|
| 1510 |
|
| 1511 |
class TestNoDecimalPlaces(FieldValues): |
| 1512 |
valid_inputs = { |
| 1513 |
'0.12345': Decimal('0.12345'), |
| 1514 |
} |
| 1515 |
invalid_inputs = { |
| 1516 |
'0.1234567': ['Ensure that there are no more than 6 digits in total.'] |
| 1517 |
} |
| 1518 |
outputs = { |
| 1519 |
'1.2345': '1.2345', |
| 1520 |
'0': '0', |
| 1521 |
'1.1': '1.1', |
| 1522 |
} |
| 1523 |
field = serializers.DecimalField(max_digits=6, decimal_places=None) |
| 1524 |
|
| 1525 |
|
| 1526 |
class TestRoundingDecimalField(TestCase): |
| 1527 |
def test_valid_rounding(self): |
| 1528 |
field = serializers.DecimalField(max_digits=4, decimal_places=2, rounding=ROUND_UP) |
| 1529 |
assert field.to_representation(Decimal('1.234')) == '1.24' |
| 1530 |
|
| 1531 |
field = serializers.DecimalField(max_digits=4, decimal_places=2, rounding=ROUND_DOWN) |
| 1532 |
assert field.to_representation(Decimal('1.234')) == '1.23' |
| 1533 |
|
| 1534 |
def test_invalid_rounding(self): |
| 1535 |
with pytest.raises(AssertionError) as excinfo: |
| 1536 |
serializers.DecimalField(max_digits=1, decimal_places=1, rounding='ROUND_UNKNOWN') |
| 1537 |
assert 'Invalid rounding option' in str(excinfo.value) |
| 1538 |
|
| 1539 |
|
| 1540 |
# Date & time serializers... |
| 1541 |
class TestDateField(FieldValues): |
| 1542 |
""" |
| 1543 |
Valid and invalid values for `DateField`. |
| 1544 |
""" |
| 1545 |
valid_inputs = { |
| 1546 |
'2001-01-01': datetime.date(2001, 1, 1), |
| 1547 |
datetime.date(2001, 1, 1): datetime.date(2001, 1, 1), |
| 1548 |
} |
| 1549 |
invalid_inputs = { |
| 1550 |
'abc': ['Date has wrong format. Use one of these formats instead: YYYY-MM-DD.'], |
| 1551 |
'2001-99-99': ['Date has wrong format. Use one of these formats instead: YYYY-MM-DD.'], |
| 1552 |
'2001-01': ['Date has wrong format. Use one of these formats instead: YYYY-MM-DD.'], |
| 1553 |
'2001': ['Date has wrong format. Use one of these formats instead: YYYY-MM-DD.'], |
| 1554 |
datetime.datetime(2001, 1, 1, 12, 00): ['Expected a date but got a datetime.'], |
| 1555 |
} |
| 1556 |
outputs = { |
| 1557 |
datetime.date(2001, 1, 1): '2001-01-01', |
| 1558 |
'2001-01-01': '2001-01-01', |
| 1559 |
'2016-01-10': '2016-01-10', |
| 1560 |
None: None, |
| 1561 |
'': None, |
| 1562 |
} |
| 1563 |
field = serializers.DateField() |
| 1564 |
|
| 1565 |
|
| 1566 |
class TestCustomInputFormatDateField(FieldValues): |
| 1567 |
""" |
| 1568 |
Valid and invalid values for `DateField` with a custom input format. |
| 1569 |
""" |
| 1570 |
valid_inputs = { |
| 1571 |
'1 Jan 2001': datetime.date(2001, 1, 1), |
| 1572 |
} |
| 1573 |
invalid_inputs = { |
| 1574 |
'2001-01-01': ['Date has wrong format. Use one of these formats instead: DD [Jan-Dec] YYYY.'] |
| 1575 |
} |
| 1576 |
outputs = {} |
| 1577 |
field = serializers.DateField(input_formats=['%d %b %Y']) |
| 1578 |
|
| 1579 |
|
| 1580 |
class TestCustomOutputFormatDateField(FieldValues): |
| 1581 |
""" |
| 1582 |
Values for `DateField` with a custom output format. |
| 1583 |
""" |
| 1584 |
valid_inputs = {} |
| 1585 |
invalid_inputs = {} |
| 1586 |
outputs = { |
| 1587 |
datetime.date(2001, 1, 1): '01 Jan 2001' |
| 1588 |
} |
| 1589 |
field = serializers.DateField(format='%d %b %Y') |
| 1590 |
|
| 1591 |
|
| 1592 |
class TestNoOutputFormatDateField(FieldValues): |
| 1593 |
""" |
| 1594 |
Values for `DateField` with no output format. |
| 1595 |
""" |
| 1596 |
valid_inputs = {} |
| 1597 |
invalid_inputs = {} |
| 1598 |
outputs = { |
| 1599 |
datetime.date(2001, 1, 1): datetime.date(2001, 1, 1) |
| 1600 |
} |
| 1601 |
field = serializers.DateField(format=None) |
| 1602 |
|
| 1603 |
|
| 1604 |
class TestDateTimeField(FieldValues): |
| 1605 |
""" |
| 1606 |
Valid and invalid values for `DateTimeField`. |
| 1607 |
""" |
| 1608 |
valid_inputs = { |
| 1609 |
'2001-01-01 13:00': datetime.datetime(2001, 1, 1, 13, 00, tzinfo=utc), |
| 1610 |
'2001-01-01T13:00': datetime.datetime(2001, 1, 1, 13, 00, tzinfo=utc), |
| 1611 |
'2001-01-01T13:00Z': datetime.datetime(2001, 1, 1, 13, 00, tzinfo=utc), |
| 1612 |
datetime.datetime(2001, 1, 1, 13, 00): datetime.datetime(2001, 1, 1, 13, 00, tzinfo=utc), |
| 1613 |
datetime.datetime(2001, 1, 1, 13, 00, tzinfo=utc): datetime.datetime(2001, 1, 1, 13, 00, tzinfo=utc), |
| 1614 |
} |
| 1615 |
invalid_inputs = { |
| 1616 |
'abc': ['Datetime has wrong format. Use one of these formats instead: YYYY-MM-DDThh:mm[:ss[.uuuuuu]][+HH:MM|-HH:MM|Z].'], |
| 1617 |
'2001-99-99T99:00': ['Datetime has wrong format. Use one of these formats instead: YYYY-MM-DDThh:mm[:ss[.uuuuuu]][+HH:MM|-HH:MM|Z].'], |
| 1618 |
'2018-08-16 22:00-24:00': ['Datetime has wrong format. Use one of these formats instead: YYYY-MM-DDThh:mm[:ss[.uuuuuu]][+HH:MM|-HH:MM|Z].'], |
| 1619 |
datetime.date(2001, 1, 1): ['Expected a datetime but got a date.'], |
| 1620 |
'9999-12-31T21:59:59.99990-03:00': ['Datetime value out of range.'], |
| 1621 |
} |
| 1622 |
outputs = { |
| 1623 |
datetime.datetime(2001, 1, 1, 13, 00): '2001-01-01T13:00:00Z', |
| 1624 |
datetime.datetime(2001, 1, 1, 13, 00, tzinfo=utc): '2001-01-01T13:00:00Z', |
| 1625 |
'2001-01-01T00:00:00': '2001-01-01T00:00:00', |
| 1626 |
'2016-01-10T00:00:00': '2016-01-10T00:00:00', |
| 1627 |
None: None, |
| 1628 |
'': None, |
| 1629 |
} |
| 1630 |
field = serializers.DateTimeField(default_timezone=utc) |
| 1631 |
|
| 1632 |
|
| 1633 |
class TestCustomInputFormatDateTimeField(FieldValues): |
| 1634 |
""" |
| 1635 |
Valid and invalid values for `DateTimeField` with a custom input format. |
| 1636 |
""" |
| 1637 |
valid_inputs = { |
| 1638 |
'1:35pm, 1 Jan 2001': datetime.datetime(2001, 1, 1, 13, 35, tzinfo=utc), |
| 1639 |
} |
| 1640 |
invalid_inputs = { |
| 1641 |
'2001-01-01T20:50': ['Datetime has wrong format. Use one of these formats instead: hh:mm[AM|PM], DD [Jan-Dec] YYYY.'] |
| 1642 |
} |
| 1643 |
outputs = {} |
| 1644 |
field = serializers.DateTimeField(default_timezone=utc, input_formats=['%I:%M%p, %d %b %Y']) |
| 1645 |
|
| 1646 |
|
| 1647 |
class TestCustomOutputFormatDateTimeField(FieldValues): |
| 1648 |
""" |
| 1649 |
Values for `DateTimeField` with a custom output format. |
| 1650 |
""" |
| 1651 |
valid_inputs = {} |
| 1652 |
invalid_inputs = {} |
| 1653 |
outputs = { |
| 1654 |
datetime.datetime(2001, 1, 1, 13, 00): '01:00PM, 01 Jan 2001', |
| 1655 |
} |
| 1656 |
field = serializers.DateTimeField(format='%I:%M%p, %d %b %Y') |
| 1657 |
|
| 1658 |
|
| 1659 |
class TestNoOutputFormatDateTimeField(FieldValues): |
| 1660 |
""" |
| 1661 |
Values for `DateTimeField` with no output format. |
| 1662 |
""" |
| 1663 |
valid_inputs = {} |
| 1664 |
invalid_inputs = {} |
| 1665 |
outputs = { |
| 1666 |
datetime.datetime(2001, 1, 1, 13, 00): datetime.datetime(2001, 1, 1, 13, 00), |
| 1667 |
} |
| 1668 |
field = serializers.DateTimeField(format=None) |
| 1669 |
|
| 1670 |
|
| 1671 |
@override_settings(TIME_ZONE='UTC', USE_TZ=False) |
| 1672 |
class TestNaiveDateTimeField(FieldValues, TestCase): |
| 1673 |
""" |
| 1674 |
Valid and invalid values for `DateTimeField` with naive datetimes. |
| 1675 |
""" |
| 1676 |
valid_inputs = { |
| 1677 |
datetime.datetime(2001, 1, 1, 13, 00, tzinfo=utc): datetime.datetime(2001, 1, 1, 13, 00), |
| 1678 |
'2001-01-01 13:00': datetime.datetime(2001, 1, 1, 13, 00), |
| 1679 |
} |
| 1680 |
invalid_inputs = {} |
| 1681 |
outputs = { |
| 1682 |
datetime.datetime(2001, 1, 1, 13, 00): '2001-01-01T13:00:00', |
| 1683 |
datetime.datetime(2001, 1, 1, 13, 00, tzinfo=utc): '2001-01-01T13:00:00', |
| 1684 |
} |
| 1685 |
field = serializers.DateTimeField(default_timezone=None) |
| 1686 |
|
| 1687 |
|
| 1688 |
class TestTZWithDateTimeField(FieldValues): |
| 1689 |
""" |
| 1690 |
Valid and invalid values for `DateTimeField` when not using UTC as the timezone. |
| 1691 |
""" |
| 1692 |
@classmethod |
| 1693 |
def setup_class(cls): |
| 1694 |
# use class setup method, as class-level attribute will still be evaluated even if test is skipped |
| 1695 |
kolkata = ZoneInfo('Asia/Kolkata') |
| 1696 |
|
| 1697 |
cls.valid_inputs = { |
| 1698 |
'2016-12-19T10:00:00': datetime.datetime(2016, 12, 19, 10, tzinfo=kolkata), |
| 1699 |
'2016-12-19T10:00:00+05:30': datetime.datetime(2016, 12, 19, 10, tzinfo=kolkata), |
| 1700 |
datetime.datetime(2016, 12, 19, 10): datetime.datetime(2016, 12, 19, 10, tzinfo=kolkata), |
| 1701 |
} |
| 1702 |
cls.invalid_inputs = {} |
| 1703 |
cls.outputs = { |
| 1704 |
datetime.datetime(2016, 12, 19, 10): '2016-12-19T10:00:00+05:30', |
| 1705 |
datetime.datetime(2016, 12, 19, 4, 30, tzinfo=utc): '2016-12-19T10:00:00+05:30', |
| 1706 |
} |
| 1707 |
cls.field = serializers.DateTimeField(default_timezone=kolkata) |
| 1708 |
|
| 1709 |
|
| 1710 |
@override_settings(TIME_ZONE='UTC', USE_TZ=True) |
| 1711 |
class TestDefaultTZDateTimeField(TestCase): |
| 1712 |
""" |
| 1713 |
Test the current/default timezone handling in `DateTimeField`. |
| 1714 |
""" |
| 1715 |
|
| 1716 |
@classmethod |
| 1717 |
def setup_class(cls): |
| 1718 |
cls.field = serializers.DateTimeField() |
| 1719 |
cls.kolkata = ZoneInfo('Asia/Kolkata') |
| 1720 |
|
| 1721 |
def assertUTC(self, tzinfo): |
| 1722 |
""" |
| 1723 |
Check UTC for datetime.timezone, ZoneInfo. |
| 1724 |
""" |
| 1725 |
assert ( |
| 1726 |
tzinfo is utc or |
| 1727 |
(getattr(tzinfo, "key", None) or getattr(tzinfo, "zone", None)) == "UTC" |
| 1728 |
) |
| 1729 |
|
| 1730 |
def test_default_timezone(self): |
| 1731 |
self.assertUTC(self.field.default_timezone()) |
| 1732 |
|
| 1733 |
def test_current_timezone(self): |
| 1734 |
self.assertUTC(self.field.default_timezone()) |
| 1735 |
activate(self.kolkata) |
| 1736 |
assert self.field.default_timezone() == self.kolkata |
| 1737 |
deactivate() |
| 1738 |
self.assertUTC(self.field.default_timezone()) |
| 1739 |
|
| 1740 |
|
| 1741 |
@override_settings(TIME_ZONE='UTC', USE_TZ=True) |
| 1742 |
class TestCustomTimezoneForDateTimeField(TestCase): |
| 1743 |
|
| 1744 |
@classmethod |
| 1745 |
def setup_class(cls): |
| 1746 |
cls.kolkata = ZoneInfo('Asia/Kolkata') |
| 1747 |
cls.date_format = '%d/%m/%Y %H:%M' |
| 1748 |
|
| 1749 |
def test_should_render_date_time_in_default_timezone(self): |
| 1750 |
field = serializers.DateTimeField(default_timezone=self.kolkata, format=self.date_format) |
| 1751 |
dt = datetime.datetime(2018, 2, 8, 14, 15, 16, tzinfo=ZoneInfo("UTC")) |
| 1752 |
|
| 1753 |
with override(self.kolkata): |
| 1754 |
rendered_date = field.to_representation(dt) |
| 1755 |
|
| 1756 |
rendered_date_in_timezone = dt.astimezone(self.kolkata).strftime(self.date_format) |
| 1757 |
|
| 1758 |
assert rendered_date == rendered_date_in_timezone |
| 1759 |
|
| 1760 |
|
| 1761 |
@patch('rest_framework.utils.timezone.datetime_ambiguous', return_value=True) |
| 1762 |
class TestNaiveDayLightSavingTimeTimeZoneDateTimeField(FieldValues): |
| 1763 |
""" |
| 1764 |
Invalid values for `DateTimeField` with datetime in DST shift (non-existing or ambiguous) and timezone with DST. |
| 1765 |
Timezone America/New_York has DST shift from 2017-03-12T02:00:00 to 2017-03-12T03:00:00 and |
| 1766 |
from 2017-11-05T02:00:00 to 2017-11-05T01:00:00 in 2017. |
| 1767 |
""" |
| 1768 |
valid_inputs = {} |
| 1769 |
invalid_inputs = { |
| 1770 |
'2017-03-12T02:30:00': ['Invalid datetime for the timezone "America/New_York".'], |
| 1771 |
'2017-11-05T01:30:00': ['Invalid datetime for the timezone "America/New_York".'] |
| 1772 |
} |
| 1773 |
outputs = {} |
| 1774 |
|
| 1775 |
class MockZoneInfoTimezone(datetime.tzinfo): |
| 1776 |
def __str__(self): |
| 1777 |
return 'America/New_York' |
| 1778 |
|
| 1779 |
field = serializers.DateTimeField(default_timezone=MockZoneInfoTimezone()) |
| 1780 |
|
| 1781 |
|
| 1782 |
class TestTimeField(FieldValues): |
| 1783 |
""" |
| 1784 |
Valid and invalid values for `TimeField`. |
| 1785 |
""" |
| 1786 |
valid_inputs = { |
| 1787 |
'13:00': datetime.time(13, 00), |
| 1788 |
datetime.time(13, 00): datetime.time(13, 00), |
| 1789 |
} |
| 1790 |
invalid_inputs = { |
| 1791 |
'abc': ['Time has wrong format. Use one of these formats instead: hh:mm[:ss[.uuuuuu]].'], |
| 1792 |
'99:99': ['Time has wrong format. Use one of these formats instead: hh:mm[:ss[.uuuuuu]].'], |
| 1793 |
} |
| 1794 |
outputs = { |
| 1795 |
datetime.time(13, 0): '13:00:00', |
| 1796 |
datetime.time(0, 0): '00:00:00', |
| 1797 |
'00:00:00': '00:00:00', |
| 1798 |
None: None, |
| 1799 |
'': None, |
| 1800 |
} |
| 1801 |
field = serializers.TimeField() |
| 1802 |
|
| 1803 |
|
| 1804 |
class TestCustomInputFormatTimeField(FieldValues): |
| 1805 |
""" |
| 1806 |
Valid and invalid values for `TimeField` with a custom input format. |
| 1807 |
""" |
| 1808 |
valid_inputs = { |
| 1809 |
'1:00pm': datetime.time(13, 00), |
| 1810 |
} |
| 1811 |
invalid_inputs = { |
| 1812 |
'13:00': ['Time has wrong format. Use one of these formats instead: hh:mm[AM|PM].'], |
| 1813 |
} |
| 1814 |
outputs = {} |
| 1815 |
field = serializers.TimeField(input_formats=['%I:%M%p']) |
| 1816 |
|
| 1817 |
|
| 1818 |
class TestCustomOutputFormatTimeField(FieldValues): |
| 1819 |
""" |
| 1820 |
Values for `TimeField` with a custom output format. |
| 1821 |
""" |
| 1822 |
valid_inputs = {} |
| 1823 |
invalid_inputs = {} |
| 1824 |
outputs = { |
| 1825 |
datetime.time(13, 00): '01:00PM' |
| 1826 |
} |
| 1827 |
field = serializers.TimeField(format='%I:%M%p') |
| 1828 |
|
| 1829 |
|
| 1830 |
class TestNoOutputFormatTimeField(FieldValues): |
| 1831 |
""" |
| 1832 |
Values for `TimeField` with a no output format. |
| 1833 |
""" |
| 1834 |
valid_inputs = {} |
| 1835 |
invalid_inputs = {} |
| 1836 |
outputs = { |
| 1837 |
datetime.time(13, 00): datetime.time(13, 00) |
| 1838 |
} |
| 1839 |
field = serializers.TimeField(format=None) |
| 1840 |
|
| 1841 |
|
| 1842 |
class TestMinMaxDurationField(FieldValues): |
| 1843 |
""" |
| 1844 |
Valid and invalid values for `DurationField` with min and max limits. |
| 1845 |
""" |
| 1846 |
valid_inputs = { |
| 1847 |
'3 08:32:01.000123': datetime.timedelta(days=3, hours=8, minutes=32, seconds=1, microseconds=123), |
| 1848 |
86401: datetime.timedelta(days=1, seconds=1), |
| 1849 |
} |
| 1850 |
invalid_inputs = { |
| 1851 |
3600: ['Ensure this value is greater than or equal to 1 day, 0:00:00.'], |
| 1852 |
'4 08:32:01.000123': ['Ensure this value is less than or equal to 4 days, 0:00:00.'], |
| 1853 |
'3600': ['Ensure this value is greater than or equal to 1 day, 0:00:00.'], |
| 1854 |
} |
| 1855 |
outputs = {} |
| 1856 |
field = serializers.DurationField(min_value=datetime.timedelta(days=1), max_value=datetime.timedelta(days=4)) |
| 1857 |
|
| 1858 |
|
| 1859 |
class TestDurationField(FieldValues): |
| 1860 |
""" |
| 1861 |
Valid and invalid values for `DurationField`. |
| 1862 |
""" |
| 1863 |
valid_inputs = { |
| 1864 |
'13': datetime.timedelta(seconds=13), |
| 1865 |
'3 08:32:01.000123': datetime.timedelta(days=3, hours=8, minutes=32, seconds=1, microseconds=123), |
| 1866 |
'08:01': datetime.timedelta(minutes=8, seconds=1), |
| 1867 |
datetime.timedelta(days=3, hours=8, minutes=32, seconds=1, microseconds=123): datetime.timedelta(days=3, hours=8, minutes=32, seconds=1, microseconds=123), |
| 1868 |
3600: datetime.timedelta(hours=1), |
| 1869 |
'-999999999 00': datetime.timedelta(days=-999999999), |
| 1870 |
'999999999 00': datetime.timedelta(days=999999999), |
| 1871 |
} |
| 1872 |
invalid_inputs = { |
| 1873 |
'abc': ['Duration has wrong format. Use one of these formats instead: [DD] [HH:[MM:]]ss[.uuuuuu].'], |
| 1874 |
'3 08:32 01.123': ['Duration has wrong format. Use one of these formats instead: [DD] [HH:[MM:]]ss[.uuuuuu].'], |
| 1875 |
'-1000000000 00': ['The number of days must be between -999999999 and 999999999.'], |
| 1876 |
'1000000000 00': ['The number of days must be between -999999999 and 999999999.'], |
| 1877 |
} |
| 1878 |
outputs = { |
| 1879 |
datetime.timedelta(days=3, hours=8, minutes=32, seconds=1, microseconds=123): '3 08:32:01.000123', |
| 1880 |
} |
| 1881 |
field = serializers.DurationField() |
| 1882 |
|
| 1883 |
def test_invalid_format(self): |
| 1884 |
with pytest.raises(ValueError) as exc_info: |
| 1885 |
serializers.DurationField(format='unknown') |
| 1886 |
assert str(exc_info.value) == ( |
| 1887 |
"Unknown duration format provided, got 'unknown'" |
| 1888 |
" while expecting 'django', 'iso-8601' or `None`." |
| 1889 |
) |
| 1890 |
with pytest.raises(TypeError) as exc_info: |
| 1891 |
serializers.DurationField(format=123) |
| 1892 |
assert str(exc_info.value) == ( |
| 1893 |
"duration format must be either str or `None`, not int" |
| 1894 |
) |
| 1895 |
|
| 1896 |
def test_invalid_format_in_config(self): |
| 1897 |
field = serializers.DurationField() |
| 1898 |
|
| 1899 |
with override_settings(REST_FRAMEWORK={'DURATION_FORMAT': 'unknown'}): |
| 1900 |
with pytest.raises(ValueError) as exc_info: |
| 1901 |
field.to_representation(datetime.timedelta(days=1)) |
| 1902 |
|
| 1903 |
assert str(exc_info.value) == ( |
| 1904 |
"Unknown duration format provided, got 'unknown'" |
| 1905 |
" while expecting 'django', 'iso-8601' or `None`." |
| 1906 |
) |
| 1907 |
with override_settings(REST_FRAMEWORK={'DURATION_FORMAT': 123}): |
| 1908 |
with pytest.raises(TypeError) as exc_info: |
| 1909 |
field.to_representation(datetime.timedelta(days=1)) |
| 1910 |
assert str(exc_info.value) == ( |
| 1911 |
"duration format must be either str or `None`, not int" |
| 1912 |
) |
| 1913 |
|
| 1914 |
|
| 1915 |
class TestNoOutputFormatDurationField(FieldValues): |
| 1916 |
""" |
| 1917 |
Values for `DurationField` with a no output format. |
| 1918 |
""" |
| 1919 |
valid_inputs = {} |
| 1920 |
invalid_inputs = {} |
| 1921 |
outputs = { |
| 1922 |
datetime.timedelta(1): datetime.timedelta(1) |
| 1923 |
} |
| 1924 |
field = serializers.DurationField(format=None) |
| 1925 |
|
| 1926 |
|
| 1927 |
class TestISOOutputFormatDurationField(FieldValues): |
| 1928 |
""" |
| 1929 |
Values for `DurationField` with a custom output format. |
| 1930 |
""" |
| 1931 |
valid_inputs = { |
| 1932 |
'13': datetime.timedelta(seconds=13), |
| 1933 |
'P3DT08H32M01.000123S': datetime.timedelta(days=3, hours=8, minutes=32, seconds=1, microseconds=123), |
| 1934 |
'PT8H1M': datetime.timedelta(hours=8, minutes=1), |
| 1935 |
'-P999999999D': datetime.timedelta(days=-999999999), |
| 1936 |
'P999999999D': datetime.timedelta(days=999999999) |
| 1937 |
} |
| 1938 |
invalid_inputs = {} |
| 1939 |
outputs = { |
| 1940 |
datetime.timedelta(days=3, hours=8, minutes=32, seconds=1, microseconds=123): 'P3DT08H32M01.000123S' |
| 1941 |
} |
| 1942 |
field = serializers.DurationField(format='iso-8601') |
| 1943 |
|
| 1944 |
|
| 1945 |
# Choice types... |
| 1946 |
class TestChoiceField(FieldValues): |
| 1947 |
""" |
| 1948 |
Valid and invalid values for `ChoiceField`. |
| 1949 |
""" |
| 1950 |
valid_inputs = { |
| 1951 |
'poor': 'poor', |
| 1952 |
'medium': 'medium', |
| 1953 |
'good': 'good', |
| 1954 |
} |
| 1955 |
invalid_inputs = { |
| 1956 |
'amazing': ['"amazing" is not a valid choice.'] |
| 1957 |
} |
| 1958 |
outputs = { |
| 1959 |
'good': 'good', |
| 1960 |
'': '', |
| 1961 |
'amazing': 'amazing', |
| 1962 |
} |
| 1963 |
field = serializers.ChoiceField( |
| 1964 |
choices=[ |
| 1965 |
('poor', 'Poor quality'), |
| 1966 |
('medium', 'Medium quality'), |
| 1967 |
('good', 'Good quality'), |
| 1968 |
] |
| 1969 |
) |
| 1970 |
|
| 1971 |
def test_allow_blank(self): |
| 1972 |
""" |
| 1973 |
If `allow_blank=True` then '' is a valid input. |
| 1974 |
""" |
| 1975 |
field = serializers.ChoiceField( |
| 1976 |
allow_blank=True, |
| 1977 |
choices=[ |
| 1978 |
('poor', 'Poor quality'), |
| 1979 |
('medium', 'Medium quality'), |
| 1980 |
('good', 'Good quality'), |
| 1981 |
] |
| 1982 |
) |
| 1983 |
output = field.run_validation('') |
| 1984 |
assert output == '' |
| 1985 |
|
| 1986 |
def test_allow_null(self): |
| 1987 |
""" |
| 1988 |
If `allow_null=True` then '' on HTML forms is treated as None. |
| 1989 |
""" |
| 1990 |
field = serializers.ChoiceField( |
| 1991 |
allow_null=True, |
| 1992 |
choices=[ |
| 1993 |
1, 2, 3 |
| 1994 |
] |
| 1995 |
) |
| 1996 |
field.field_name = 'example' |
| 1997 |
value = field.get_value(QueryDict('example=')) |
| 1998 |
assert value is None |
| 1999 |
output = field.run_validation(None) |
| 2000 |
assert output is None |
| 2001 |
|
| 2002 |
def test_iter_options(self): |
| 2003 |
""" |
| 2004 |
iter_options() should return a list of options and option groups. |
| 2005 |
""" |
| 2006 |
field = serializers.ChoiceField( |
| 2007 |
choices=[ |
| 2008 |
('Numbers', ['integer', 'float']), |
| 2009 |
('Strings', ['text', 'email', 'url']), |
| 2010 |
'boolean' |
| 2011 |
] |
| 2012 |
) |
| 2013 |
items = list(field.iter_options()) |
| 2014 |
|
| 2015 |
assert items[0].start_option_group |
| 2016 |
assert items[0].label == 'Numbers' |
| 2017 |
assert items[1].value == 'integer' |
| 2018 |
assert items[2].value == 'float' |
| 2019 |
assert items[3].end_option_group |
| 2020 |
|
| 2021 |
assert items[4].start_option_group |
| 2022 |
assert items[4].label == 'Strings' |
| 2023 |
assert items[5].value == 'text' |
| 2024 |
assert items[6].value == 'email' |
| 2025 |
assert items[7].value == 'url' |
| 2026 |
assert items[8].end_option_group |
| 2027 |
|
| 2028 |
assert items[9].value == 'boolean' |
| 2029 |
|
| 2030 |
def test_edit_choices(self): |
| 2031 |
field = serializers.ChoiceField( |
| 2032 |
allow_null=True, |
| 2033 |
choices=[ |
| 2034 |
1, 2, |
| 2035 |
] |
| 2036 |
) |
| 2037 |
field.choices = [1] |
| 2038 |
assert field.run_validation(1) == 1 |
| 2039 |
with pytest.raises(serializers.ValidationError) as exc_info: |
| 2040 |
field.run_validation(2) |
| 2041 |
assert exc_info.value.detail == ['"2" is not a valid choice.'] |
| 2042 |
|
| 2043 |
def test_enum_integer_choices(self): |
| 2044 |
from enum import IntEnum |
| 2045 |
|
| 2046 |
class ChoiceCase(IntEnum): |
| 2047 |
first = auto() |
| 2048 |
second = auto() |
| 2049 |
# Enum validate |
| 2050 |
choices = [ |
| 2051 |
(ChoiceCase.first, "1"), |
| 2052 |
(ChoiceCase.second, "2") |
| 2053 |
] |
| 2054 |
field = serializers.ChoiceField(choices=choices) |
| 2055 |
assert field.run_validation(1) == 1 |
| 2056 |
assert field.run_validation(ChoiceCase.first) == 1 |
| 2057 |
assert field.run_validation("1") == 1 |
| 2058 |
# Enum.value validate |
| 2059 |
choices = [ |
| 2060 |
(ChoiceCase.first.value, "1"), |
| 2061 |
(ChoiceCase.second.value, "2") |
| 2062 |
] |
| 2063 |
field = serializers.ChoiceField(choices=choices) |
| 2064 |
assert field.run_validation(1) == 1 |
| 2065 |
assert field.run_validation(ChoiceCase.first) == 1 |
| 2066 |
assert field.run_validation("1") == 1 |
| 2067 |
|
| 2068 |
def test_integer_choices(self): |
| 2069 |
class ChoiceCase(IntegerChoices): |
| 2070 |
first = auto() |
| 2071 |
second = auto() |
| 2072 |
# Enum validate |
| 2073 |
choices = [ |
| 2074 |
(ChoiceCase.first, "1"), |
| 2075 |
(ChoiceCase.second, "2") |
| 2076 |
] |
| 2077 |
|
| 2078 |
field = serializers.ChoiceField(choices=choices) |
| 2079 |
assert field.run_validation(1) == 1 |
| 2080 |
assert field.run_validation(ChoiceCase.first) == 1 |
| 2081 |
assert field.run_validation("1") == 1 |
| 2082 |
|
| 2083 |
choices = [ |
| 2084 |
(ChoiceCase.first.value, "1"), |
| 2085 |
(ChoiceCase.second.value, "2") |
| 2086 |
] |
| 2087 |
|
| 2088 |
field = serializers.ChoiceField(choices=choices) |
| 2089 |
assert field.run_validation(1) == 1 |
| 2090 |
assert field.run_validation(ChoiceCase.first) == 1 |
| 2091 |
assert field.run_validation("1") == 1 |
| 2092 |
|
| 2093 |
def test_text_choices(self): |
| 2094 |
class ChoiceCase(TextChoices): |
| 2095 |
first = auto() |
| 2096 |
second = auto() |
| 2097 |
# Enum validate |
| 2098 |
choices = [ |
| 2099 |
(ChoiceCase.first, "first"), |
| 2100 |
(ChoiceCase.second, "second") |
| 2101 |
] |
| 2102 |
|
| 2103 |
field = serializers.ChoiceField(choices=choices) |
| 2104 |
assert field.run_validation(ChoiceCase.first) == "first" |
| 2105 |
assert field.run_validation("first") == "first" |
| 2106 |
|
| 2107 |
choices = [ |
| 2108 |
(ChoiceCase.first.value, "first"), |
| 2109 |
(ChoiceCase.second.value, "second") |
| 2110 |
] |
| 2111 |
|
| 2112 |
field = serializers.ChoiceField(choices=choices) |
| 2113 |
assert field.run_validation(ChoiceCase.first) == "first" |
| 2114 |
assert field.run_validation("first") == "first" |
| 2115 |
|
| 2116 |
|
| 2117 |
class TestChoiceFieldWithType(FieldValues): |
| 2118 |
""" |
| 2119 |
Valid and invalid values for a `Choice` field that uses an integer type, |
| 2120 |
instead of a char type. |
| 2121 |
""" |
| 2122 |
valid_inputs = { |
| 2123 |
'1': 1, |
| 2124 |
3: 3, |
| 2125 |
} |
| 2126 |
invalid_inputs = { |
| 2127 |
5: ['"5" is not a valid choice.'], |
| 2128 |
'abc': ['"abc" is not a valid choice.'] |
| 2129 |
} |
| 2130 |
outputs = { |
| 2131 |
'1': 1, |
| 2132 |
1: 1 |
| 2133 |
} |
| 2134 |
field = serializers.ChoiceField( |
| 2135 |
choices=[ |
| 2136 |
(1, 'Poor quality'), |
| 2137 |
(2, 'Medium quality'), |
| 2138 |
(3, 'Good quality'), |
| 2139 |
] |
| 2140 |
) |
| 2141 |
|
| 2142 |
|
| 2143 |
class TestChoiceFieldWithListChoices(FieldValues): |
| 2144 |
""" |
| 2145 |
Valid and invalid values for a `Choice` field that uses a flat list for the |
| 2146 |
choices, rather than a list of pairs of (`value`, `description`). |
| 2147 |
""" |
| 2148 |
valid_inputs = { |
| 2149 |
'poor': 'poor', |
| 2150 |
'medium': 'medium', |
| 2151 |
'good': 'good', |
| 2152 |
} |
| 2153 |
invalid_inputs = { |
| 2154 |
'awful': ['"awful" is not a valid choice.'] |
| 2155 |
} |
| 2156 |
outputs = { |
| 2157 |
'good': 'good' |
| 2158 |
} |
| 2159 |
field = serializers.ChoiceField(choices=('poor', 'medium', 'good')) |
| 2160 |
|
| 2161 |
|
| 2162 |
class TestChoiceFieldWithGroupedChoices(FieldValues): |
| 2163 |
""" |
| 2164 |
Valid and invalid values for a `Choice` field that uses a grouped list for the |
| 2165 |
choices, rather than a list of pairs of (`value`, `description`). |
| 2166 |
""" |
| 2167 |
valid_inputs = { |
| 2168 |
'poor': 'poor', |
| 2169 |
'medium': 'medium', |
| 2170 |
'good': 'good', |
| 2171 |
} |
| 2172 |
invalid_inputs = { |
| 2173 |
'awful': ['"awful" is not a valid choice.'] |
| 2174 |
} |
| 2175 |
outputs = { |
| 2176 |
'good': 'good' |
| 2177 |
} |
| 2178 |
field = serializers.ChoiceField( |
| 2179 |
choices=[ |
| 2180 |
( |
| 2181 |
'Category', |
| 2182 |
( |
| 2183 |
('poor', 'Poor quality'), |
| 2184 |
('medium', 'Medium quality'), |
| 2185 |
), |
| 2186 |
), |
| 2187 |
('good', 'Good quality'), |
| 2188 |
] |
| 2189 |
) |
| 2190 |
|
| 2191 |
|
| 2192 |
class TestChoiceFieldWithMixedChoices(FieldValues): |
| 2193 |
""" |
| 2194 |
Valid and invalid values for a `Choice` field that uses a single paired or |
| 2195 |
grouped. |
| 2196 |
""" |
| 2197 |
valid_inputs = { |
| 2198 |
'poor': 'poor', |
| 2199 |
'medium': 'medium', |
| 2200 |
'good': 'good', |
| 2201 |
} |
| 2202 |
invalid_inputs = { |
| 2203 |
'awful': ['"awful" is not a valid choice.'] |
| 2204 |
} |
| 2205 |
outputs = { |
| 2206 |
'good': 'good' |
| 2207 |
} |
| 2208 |
field = serializers.ChoiceField( |
| 2209 |
choices=[ |
| 2210 |
( |
| 2211 |
'Category', |
| 2212 |
( |
| 2213 |
('poor', 'Poor quality'), |
| 2214 |
), |
| 2215 |
), |
| 2216 |
'medium', |
| 2217 |
('good', 'Good quality'), |
| 2218 |
] |
| 2219 |
) |
| 2220 |
|
| 2221 |
|
| 2222 |
class TestMultipleChoiceField(FieldValues): |
| 2223 |
""" |
| 2224 |
Valid and invalid values for `MultipleChoiceField`. |
| 2225 |
""" |
| 2226 |
valid_inputs = { |
| 2227 |
(): list(), |
| 2228 |
('aircon',): ['aircon'], |
| 2229 |
('aircon', 'aircon'): ['aircon'], |
| 2230 |
('aircon', 'manual'): ['aircon', 'manual'], |
| 2231 |
('manual', 'aircon'): ['manual', 'aircon'], |
| 2232 |
} |
| 2233 |
invalid_inputs = { |
| 2234 |
'abc': ['Expected a list of items but got type "str".'], |
| 2235 |
('aircon', 'incorrect'): ['"incorrect" is not a valid choice.'] |
| 2236 |
} |
| 2237 |
outputs = [ |
| 2238 |
(['aircon', 'manual', 'incorrect'], ['aircon', 'manual', 'incorrect']), |
| 2239 |
(['manual', 'aircon', 'incorrect'], ['manual', 'aircon', 'incorrect']), |
| 2240 |
(['aircon', 'manual', 'aircon'], ['aircon', 'manual']), |
| 2241 |
] |
| 2242 |
field = serializers.MultipleChoiceField( |
| 2243 |
choices=[ |
| 2244 |
('aircon', 'AirCon'), |
| 2245 |
('manual', 'Manual drive'), |
| 2246 |
('diesel', 'Diesel'), |
| 2247 |
] |
| 2248 |
) |
| 2249 |
|
| 2250 |
def test_against_partial_and_full_updates(self): |
| 2251 |
field = serializers.MultipleChoiceField(choices=(('a', 'a'), ('b', 'b'))) |
| 2252 |
field.partial = False |
| 2253 |
assert field.get_value(QueryDict('')) == [] |
| 2254 |
field.partial = True |
| 2255 |
assert field.get_value(QueryDict('')) == rest_framework.fields.empty |
| 2256 |
|
| 2257 |
def test_valid_inputs_is_json_serializable(self): |
| 2258 |
for input_value, _ in get_items(self.valid_inputs): |
| 2259 |
validated = self.field.run_validation(input_value) |
| 2260 |
|
| 2261 |
try: |
| 2262 |
json.dumps(validated) |
| 2263 |
except TypeError as e: |
| 2264 |
pytest.fail(f'Validated output not JSON serializable: {repr(validated)}; Error: {e}') |
| 2265 |
|
| 2266 |
def test_output_is_json_serializable(self): |
| 2267 |
for output_value, _ in get_items(self.outputs): |
| 2268 |
representation = self.field.to_representation(output_value) |
| 2269 |
|
| 2270 |
try: |
| 2271 |
json.dumps(representation) |
| 2272 |
except TypeError as e: |
| 2273 |
pytest.fail( |
| 2274 |
f'to_representation output not JSON serializable: ' |
| 2275 |
f'{repr(representation)}; Error: {e}' |
| 2276 |
) |
| 2277 |
|
| 2278 |
|
| 2279 |
class TestEmptyMultipleChoiceField(FieldValues): |
| 2280 |
""" |
| 2281 |
Invalid values for `MultipleChoiceField(allow_empty=False)`. |
| 2282 |
""" |
| 2283 |
valid_inputs = { |
| 2284 |
} |
| 2285 |
invalid_inputs = ( |
| 2286 |
([], ['This selection may not be empty.']), |
| 2287 |
) |
| 2288 |
outputs = [ |
| 2289 |
] |
| 2290 |
field = serializers.MultipleChoiceField( |
| 2291 |
choices=[ |
| 2292 |
('consistency', 'Consistency'), |
| 2293 |
('availability', 'Availability'), |
| 2294 |
('partition', 'Partition tolerance'), |
| 2295 |
], |
| 2296 |
allow_empty=False |
| 2297 |
) |
| 2298 |
|
| 2299 |
|
| 2300 |
# File serializers... |
| 2301 |
|
| 2302 |
class MockFile: |
| 2303 |
def __init__(self, name='', size=0, url=''): |
| 2304 |
self.name = name |
| 2305 |
self.size = size |
| 2306 |
self.url = url |
| 2307 |
|
| 2308 |
def __eq__(self, other): |
| 2309 |
return ( |
| 2310 |
isinstance(other, MockFile) and |
| 2311 |
self.name == other.name and |
| 2312 |
self.size == other.size and |
| 2313 |
self.url == other.url |
| 2314 |
) |
| 2315 |
|
| 2316 |
|
| 2317 |
class TestFileField(FieldValues): |
| 2318 |
""" |
| 2319 |
Values for `FileField`. |
| 2320 |
""" |
| 2321 |
valid_inputs = [ |
| 2322 |
(MockFile(name='example', size=10), MockFile(name='example', size=10)) |
| 2323 |
] |
| 2324 |
invalid_inputs = [ |
| 2325 |
('invalid', ['The submitted data was not a file. Check the encoding type on the form.']), |
| 2326 |
(MockFile(name='example.txt', size=0), ['The submitted file is empty.']), |
| 2327 |
(MockFile(name='', size=10), ['No filename could be determined.']), |
| 2328 |
(MockFile(name='x' * 100, size=10), ['Ensure this filename has at most 10 characters (it has 100).']) |
| 2329 |
] |
| 2330 |
outputs = [ |
| 2331 |
(MockFile(name='example.txt', url='/example.txt'), '/example.txt'), |
| 2332 |
('', None) |
| 2333 |
] |
| 2334 |
field = serializers.FileField(max_length=10) |
| 2335 |
|
| 2336 |
|
| 2337 |
class TestFieldFieldWithName(FieldValues): |
| 2338 |
""" |
| 2339 |
Values for `FileField` with a filename output instead of URLs. |
| 2340 |
""" |
| 2341 |
valid_inputs = {} |
| 2342 |
invalid_inputs = {} |
| 2343 |
outputs = [ |
| 2344 |
(MockFile(name='example.txt', url='/example.txt'), 'example.txt') |
| 2345 |
] |
| 2346 |
field = serializers.FileField(use_url=False) |
| 2347 |
|
| 2348 |
|
| 2349 |
def ext_validator(value): |
| 2350 |
if not value.name.endswith('.png'): |
| 2351 |
raise serializers.ValidationError('File extension is not allowed. Allowed extensions is png.') |
| 2352 |
|
| 2353 |
|
| 2354 |
# Stub out mock Django `forms.ImageField` class so we don't *actually* |
| 2355 |
# call into it's regular validation, or require PIL for testing. |
| 2356 |
class PassImageValidation(DjangoImageField): |
| 2357 |
default_validators = [ext_validator] |
| 2358 |
|
| 2359 |
def to_python(self, value): |
| 2360 |
return value |
| 2361 |
|
| 2362 |
|
| 2363 |
class FailImageValidation(PassImageValidation): |
| 2364 |
def to_python(self, value): |
| 2365 |
if value.name == 'badimage.png': |
| 2366 |
raise serializers.ValidationError(self.error_messages['invalid_image']) |
| 2367 |
return value |
| 2368 |
|
| 2369 |
|
| 2370 |
class TestInvalidImageField(FieldValues): |
| 2371 |
""" |
| 2372 |
Values for an invalid `ImageField`. |
| 2373 |
""" |
| 2374 |
valid_inputs = {} |
| 2375 |
invalid_inputs = [ |
| 2376 |
(MockFile(name='badimage.png', size=10), ['Upload a valid image. The file you uploaded was either not an image or a corrupted image.']), |
| 2377 |
(MockFile(name='goodimage.html', size=10), ['File extension is not allowed. Allowed extensions is png.']) |
| 2378 |
] |
| 2379 |
outputs = {} |
| 2380 |
field = serializers.ImageField(_DjangoImageField=FailImageValidation) |
| 2381 |
|
| 2382 |
|
| 2383 |
class TestValidImageField(FieldValues): |
| 2384 |
""" |
| 2385 |
Values for an valid `ImageField`. |
| 2386 |
""" |
| 2387 |
valid_inputs = [ |
| 2388 |
(MockFile(name='example.png', size=10), MockFile(name='example.png', size=10)) |
| 2389 |
] |
| 2390 |
invalid_inputs = {} |
| 2391 |
outputs = {} |
| 2392 |
field = serializers.ImageField(_DjangoImageField=PassImageValidation) |
| 2393 |
|
| 2394 |
|
| 2395 |
# Composite serializers... |
| 2396 |
|
| 2397 |
class TestListField(FieldValues): |
| 2398 |
""" |
| 2399 |
Values for `ListField` with IntegerField as child. |
| 2400 |
""" |
| 2401 |
valid_inputs = [ |
| 2402 |
([1, 2, 3], [1, 2, 3]), |
| 2403 |
(['1', '2', '3'], [1, 2, 3]), |
| 2404 |
([], []) |
| 2405 |
] |
| 2406 |
invalid_inputs = [ |
| 2407 |
('not a list', ['Expected a list of items but got type "str".']), |
| 2408 |
([1, 2, 'error', 'error'], {2: ['A valid integer is required.'], 3: ['A valid integer is required.']}), |
| 2409 |
({'one': 'two'}, ['Expected a list of items but got type "dict".']) |
| 2410 |
] |
| 2411 |
outputs = [ |
| 2412 |
([1, 2, 3], [1, 2, 3]), |
| 2413 |
(['1', '2', '3'], [1, 2, 3]) |
| 2414 |
] |
| 2415 |
field = serializers.ListField(child=serializers.IntegerField()) |
| 2416 |
|
| 2417 |
def test_no_source_on_child(self): |
| 2418 |
with pytest.raises(AssertionError) as exc_info: |
| 2419 |
serializers.ListField(child=serializers.IntegerField(source='other')) |
| 2420 |
|
| 2421 |
assert str(exc_info.value) == ( |
| 2422 |
"The `source` argument is not meaningful when applied to a `child=` field. " |
| 2423 |
"Remove `source=` from the field declaration." |
| 2424 |
) |
| 2425 |
|
| 2426 |
def test_collection_types_are_invalid_input(self): |
| 2427 |
field = serializers.ListField(child=serializers.CharField()) |
| 2428 |
input_value = ({'one': 'two'}) |
| 2429 |
|
| 2430 |
with pytest.raises(serializers.ValidationError) as exc_info: |
| 2431 |
field.to_internal_value(input_value) |
| 2432 |
assert exc_info.value.detail == ['Expected a list of items but got type "dict".'] |
| 2433 |
|
| 2434 |
def test_constructor_misuse_raises(self): |
| 2435 |
# Test that `ListField` can only be instantiated with keyword arguments |
| 2436 |
with pytest.raises(TypeError): |
| 2437 |
serializers.ListField(serializers.CharField()) |
| 2438 |
|
| 2439 |
|
| 2440 |
class TestNestedListField(FieldValues): |
| 2441 |
""" |
| 2442 |
Values for nested `ListField` with IntegerField as child. |
| 2443 |
""" |
| 2444 |
valid_inputs = [ |
| 2445 |
([[1, 2], [3]], [[1, 2], [3]]), |
| 2446 |
([[]], [[]]) |
| 2447 |
] |
| 2448 |
invalid_inputs = [ |
| 2449 |
(['not a list'], {0: ['Expected a list of items but got type "str".']}), |
| 2450 |
([[1, 2, 'error'], ['error']], {0: {2: ['A valid integer is required.']}, 1: {0: ['A valid integer is required.']}}), |
| 2451 |
([{'one': 'two'}], {0: ['Expected a list of items but got type "dict".']}) |
| 2452 |
] |
| 2453 |
outputs = [ |
| 2454 |
([[1, 2], [3]], [[1, 2], [3]]), |
| 2455 |
] |
| 2456 |
field = serializers.ListField(child=serializers.ListField(child=serializers.IntegerField())) |
| 2457 |
|
| 2458 |
|
| 2459 |
class TestListFieldWithDjangoValidationErrors(FieldValues, TestCase): |
| 2460 |
""" |
| 2461 |
Values for `ListField` with UUIDField as child |
| 2462 |
(since UUIDField can throw ValidationErrors from Django). |
| 2463 |
The idea is to test that Django's ValidationErrors raised |
| 2464 |
from Django internals are caught and serializers in a way |
| 2465 |
that is structurally consistent with DRF's ValidationErrors. |
| 2466 |
""" |
| 2467 |
|
| 2468 |
valid_inputs = [] |
| 2469 |
invalid_inputs = [ |
| 2470 |
( |
| 2471 |
['not-a-valid-uuid', 'd7364368-d1b3-4455-aaa3-56439b460ca2', 'some-other-invalid-uuid'], |
| 2472 |
{ |
| 2473 |
0: [exceptions.ErrorDetail(string='“not-a-valid-uuid” is not a valid UUID.', code='invalid')], |
| 2474 |
1: [ |
| 2475 |
exceptions.ErrorDetail( |
| 2476 |
string='Invalid pk "d7364368-d1b3-4455-aaa3-56439b460ca2" - object does not exist.', |
| 2477 |
code='does_not_exist', |
| 2478 |
) |
| 2479 |
], |
| 2480 |
2: [exceptions.ErrorDetail(string='“some-other-invalid-uuid” is not a valid UUID.', code='invalid')], |
| 2481 |
}, |
| 2482 |
), |
| 2483 |
] |
| 2484 |
outputs = {} |
| 2485 |
field = serializers.ListField(child=serializers.PrimaryKeyRelatedField(queryset=UUIDForeignKeyTarget.objects.all())) |
| 2486 |
|
| 2487 |
|
| 2488 |
class TestEmptyListField(FieldValues): |
| 2489 |
""" |
| 2490 |
Values for `ListField` with allow_empty=False flag. |
| 2491 |
""" |
| 2492 |
valid_inputs = {} |
| 2493 |
invalid_inputs = [ |
| 2494 |
([], ['This list may not be empty.']) |
| 2495 |
] |
| 2496 |
outputs = {} |
| 2497 |
field = serializers.ListField(child=serializers.IntegerField(), allow_empty=False) |
| 2498 |
|
| 2499 |
|
| 2500 |
class TestListFieldLengthLimit(FieldValues): |
| 2501 |
valid_inputs = () |
| 2502 |
invalid_inputs = [ |
| 2503 |
((0, 1), ['Ensure this field has at least 3 elements.']), |
| 2504 |
((0, 1, 2, 3, 4, 5), ['Ensure this field has no more than 4 elements.']), |
| 2505 |
] |
| 2506 |
outputs = () |
| 2507 |
field = serializers.ListField(child=serializers.IntegerField(), min_length=3, max_length=4) |
| 2508 |
|
| 2509 |
|
| 2510 |
class TestUnvalidatedListField(FieldValues): |
| 2511 |
""" |
| 2512 |
Values for `ListField` with no `child` argument. |
| 2513 |
""" |
| 2514 |
valid_inputs = [ |
| 2515 |
([1, '2', True, [4, 5, 6]], [1, '2', True, [4, 5, 6]]), |
| 2516 |
] |
| 2517 |
invalid_inputs = [ |
| 2518 |
('not a list', ['Expected a list of items but got type "str".']), |
| 2519 |
] |
| 2520 |
outputs = [ |
| 2521 |
([1, '2', True, [4, 5, 6]], [1, '2', True, [4, 5, 6]]), |
| 2522 |
] |
| 2523 |
field = serializers.ListField() |
| 2524 |
|
| 2525 |
|
| 2526 |
class TestDictField(FieldValues): |
| 2527 |
""" |
| 2528 |
Values for `DictField` with CharField as child. |
| 2529 |
""" |
| 2530 |
valid_inputs = [ |
| 2531 |
({'a': 1, 'b': '2', 3: 3}, {'a': '1', 'b': '2', '3': '3'}), |
| 2532 |
({}, {}), |
| 2533 |
] |
| 2534 |
invalid_inputs = [ |
| 2535 |
({'a': 1, 'b': None, 'c': None}, {'b': ['This field may not be null.'], 'c': ['This field may not be null.']}), |
| 2536 |
('not a dict', ['Expected a dictionary of items but got type "str".']), |
| 2537 |
] |
| 2538 |
outputs = [ |
| 2539 |
({'a': 1, 'b': '2', 3: 3}, {'a': '1', 'b': '2', '3': '3'}), |
| 2540 |
] |
| 2541 |
field = serializers.DictField(child=serializers.CharField()) |
| 2542 |
|
| 2543 |
def test_no_source_on_child(self): |
| 2544 |
with pytest.raises(AssertionError) as exc_info: |
| 2545 |
serializers.DictField(child=serializers.CharField(source='other')) |
| 2546 |
|
| 2547 |
assert str(exc_info.value) == ( |
| 2548 |
"The `source` argument is not meaningful when applied to a `child=` field. " |
| 2549 |
"Remove `source=` from the field declaration." |
| 2550 |
) |
| 2551 |
|
| 2552 |
def test_allow_null(self): |
| 2553 |
""" |
| 2554 |
If `allow_null=True` then `None` is a valid input. |
| 2555 |
""" |
| 2556 |
field = serializers.DictField(allow_null=True) |
| 2557 |
output = field.run_validation(None) |
| 2558 |
assert output is None |
| 2559 |
|
| 2560 |
def test_allow_empty_disallowed(self): |
| 2561 |
""" |
| 2562 |
If allow_empty is False then an empty dict is not a valid input. |
| 2563 |
""" |
| 2564 |
field = serializers.DictField(allow_empty=False) |
| 2565 |
with pytest.raises(serializers.ValidationError) as exc_info: |
| 2566 |
field.run_validation({}) |
| 2567 |
|
| 2568 |
assert exc_info.value.detail == ['This dictionary may not be empty.'] |
| 2569 |
|
| 2570 |
def test_query_dict_input_with_dot_separated_keys(self): |
| 2571 |
""" |
| 2572 |
DictField should correctly parse HTML form (QueryDict) input |
| 2573 |
with dot-separated keys. |
| 2574 |
""" |
| 2575 |
class TestSerializer(serializers.Serializer): |
| 2576 |
data = serializers.DictField(child=serializers.CharField()) |
| 2577 |
|
| 2578 |
serializer = TestSerializer(data=QueryDict('data.a=1&data.b=2')) |
| 2579 |
assert serializer.is_valid(), serializer.errors |
| 2580 |
assert serializer.validated_data == {'data': {'a': '1', 'b': '2'}} |
| 2581 |
|
| 2582 |
def test_query_dict_input_no_values_uses_default(self): |
| 2583 |
""" |
| 2584 |
When no matching keys are present in the QueryDict and a default |
| 2585 |
is set, the field should return the default value. |
| 2586 |
""" |
| 2587 |
class TestSerializer(serializers.Serializer): |
| 2588 |
a = serializers.IntegerField(required=True) |
| 2589 |
data = serializers.DictField(default=lambda: {'x': 'y'}) |
| 2590 |
|
| 2591 |
serializer = TestSerializer(data=QueryDict('a=1')) |
| 2592 |
assert serializer.is_valid(), serializer.errors |
| 2593 |
assert serializer.validated_data == {'a': 1, 'data': {'x': 'y'}} |
| 2594 |
|
| 2595 |
def test_query_dict_input_no_values_no_default_and_not_required(self): |
| 2596 |
""" |
| 2597 |
When no matching keys are present in the QueryDict, there is no |
| 2598 |
default, and the field is not required, the field should be |
| 2599 |
skipped entirely from validated_data. |
| 2600 |
""" |
| 2601 |
class TestSerializer(serializers.Serializer): |
| 2602 |
data = serializers.DictField(required=False) |
| 2603 |
|
| 2604 |
serializer = TestSerializer(data=QueryDict('')) |
| 2605 |
assert serializer.is_valid(), serializer.errors |
| 2606 |
assert serializer.validated_data == {} |
| 2607 |
|
| 2608 |
def test_query_dict_input_no_values_required(self): |
| 2609 |
""" |
| 2610 |
When no matching keys are present in the QueryDict and the field |
| 2611 |
is required, validation should fail. |
| 2612 |
""" |
| 2613 |
class TestSerializer(serializers.Serializer): |
| 2614 |
data = serializers.DictField(required=True) |
| 2615 |
|
| 2616 |
serializer = TestSerializer(data=QueryDict('')) |
| 2617 |
assert not serializer.is_valid() |
| 2618 |
assert 'data' in serializer.errors |
| 2619 |
|
| 2620 |
def test_partial_update_can_clear_html_dict_field(self): |
| 2621 |
""" |
| 2622 |
Test that a partial update can clear a DictField when provided with an |
| 2623 |
empty string value through a QueryDict. |
| 2624 |
""" |
| 2625 |
class TestSerializer(serializers.Serializer): |
| 2626 |
field_name = serializers.DictField(required=False) |
| 2627 |
other_field = serializers.CharField(required=False) |
| 2628 |
|
| 2629 |
serializer = TestSerializer( |
| 2630 |
data=QueryDict('field_name='), |
| 2631 |
partial=True, |
| 2632 |
) |
| 2633 |
assert serializer.is_valid() |
| 2634 |
assert 'field_name' in serializer.validated_data |
| 2635 |
assert serializer.validated_data['field_name'] == {} |
| 2636 |
assert 'other_field' not in serializer.validated_data |
| 2637 |
|
| 2638 |
|
| 2639 |
class TestNestedDictField(FieldValues): |
| 2640 |
""" |
| 2641 |
Values for nested `DictField` with CharField as child. |
| 2642 |
""" |
| 2643 |
valid_inputs = [ |
| 2644 |
({0: {'a': 1, 'b': '2'}, 1: {3: 3}}, {'0': {'a': '1', 'b': '2'}, '1': {'3': '3'}}), |
| 2645 |
] |
| 2646 |
invalid_inputs = [ |
| 2647 |
({0: {'a': 1, 'b': None}, 1: {'c': None}}, {'0': {'b': ['This field may not be null.']}, '1': {'c': ['This field may not be null.']}}), |
| 2648 |
({0: 'not a dict'}, {'0': ['Expected a dictionary of items but got type "str".']}), |
| 2649 |
] |
| 2650 |
outputs = [ |
| 2651 |
({0: {'a': 1, 'b': '2'}, 1: {3: 3}}, {'0': {'a': '1', 'b': '2'}, '1': {'3': '3'}}), |
| 2652 |
] |
| 2653 |
field = serializers.DictField(child=serializers.DictField(child=serializers.CharField())) |
| 2654 |
|
| 2655 |
|
| 2656 |
class TestDictFieldWithNullChild(FieldValues): |
| 2657 |
""" |
| 2658 |
Values for `DictField` with allow_null CharField as child. |
| 2659 |
""" |
| 2660 |
valid_inputs = [ |
| 2661 |
({'a': None, 'b': '2', 3: 3}, {'a': None, 'b': '2', '3': '3'}), |
| 2662 |
] |
| 2663 |
invalid_inputs = [ |
| 2664 |
] |
| 2665 |
outputs = [ |
| 2666 |
({'a': None, 'b': '2', 3: 3}, {'a': None, 'b': '2', '3': '3'}), |
| 2667 |
] |
| 2668 |
field = serializers.DictField(child=serializers.CharField(allow_null=True)) |
| 2669 |
|
| 2670 |
|
| 2671 |
class TestUnvalidatedDictField(FieldValues): |
| 2672 |
""" |
| 2673 |
Values for `DictField` with no `child` argument. |
| 2674 |
""" |
| 2675 |
valid_inputs = [ |
| 2676 |
({'a': 1, 'b': [4, 5, 6], 1: 123}, {'a': 1, 'b': [4, 5, 6], '1': 123}), |
| 2677 |
] |
| 2678 |
invalid_inputs = [ |
| 2679 |
('not a dict', ['Expected a dictionary of items but got type "str".']), |
| 2680 |
] |
| 2681 |
outputs = [ |
| 2682 |
({'a': 1, 'b': [4, 5, 6]}, {'a': 1, 'b': [4, 5, 6]}), |
| 2683 |
] |
| 2684 |
field = serializers.DictField() |
| 2685 |
|
| 2686 |
|
| 2687 |
class TestHStoreField(FieldValues): |
| 2688 |
""" |
| 2689 |
Values for `ListField` with CharField as child. |
| 2690 |
""" |
| 2691 |
valid_inputs = [ |
| 2692 |
({'a': 1, 'b': '2', 3: 3}, {'a': '1', 'b': '2', '3': '3'}), |
| 2693 |
({'a': 1, 'b': None}, {'a': '1', 'b': None}), |
| 2694 |
] |
| 2695 |
invalid_inputs = [ |
| 2696 |
('not a dict', ['Expected a dictionary of items but got type "str".']), |
| 2697 |
] |
| 2698 |
outputs = [ |
| 2699 |
({'a': 1, 'b': '2', 3: 3}, {'a': '1', 'b': '2', '3': '3'}), |
| 2700 |
] |
| 2701 |
field = serializers.HStoreField() |
| 2702 |
|
| 2703 |
def test_child_is_charfield(self): |
| 2704 |
with pytest.raises(AssertionError) as exc_info: |
| 2705 |
serializers.HStoreField(child=serializers.IntegerField()) |
| 2706 |
|
| 2707 |
assert str(exc_info.value) == ( |
| 2708 |
"The `child` argument must be an instance of `CharField`, " |
| 2709 |
"as the hstore extension stores values as strings." |
| 2710 |
) |
| 2711 |
|
| 2712 |
def test_no_source_on_child(self): |
| 2713 |
with pytest.raises(AssertionError) as exc_info: |
| 2714 |
serializers.HStoreField(child=serializers.CharField(source='other')) |
| 2715 |
|
| 2716 |
assert str(exc_info.value) == ( |
| 2717 |
"The `source` argument is not meaningful when applied to a `child=` field. " |
| 2718 |
"Remove `source=` from the field declaration." |
| 2719 |
) |
| 2720 |
|
| 2721 |
def test_allow_null(self): |
| 2722 |
""" |
| 2723 |
If `allow_null=True` then `None` is a valid input. |
| 2724 |
""" |
| 2725 |
field = serializers.HStoreField(allow_null=True) |
| 2726 |
output = field.run_validation(None) |
| 2727 |
assert output is None |
| 2728 |
|
| 2729 |
|
| 2730 |
class TestJSONField(FieldValues): |
| 2731 |
""" |
| 2732 |
Values for `JSONField`. |
| 2733 |
""" |
| 2734 |
valid_inputs = [ |
| 2735 |
({ |
| 2736 |
'a': 1, |
| 2737 |
'b': ['some', 'list', True, 1.23], |
| 2738 |
'3': None |
| 2739 |
}, { |
| 2740 |
'a': 1, |
| 2741 |
'b': ['some', 'list', True, 1.23], |
| 2742 |
'3': None |
| 2743 |
}), |
| 2744 |
] |
| 2745 |
invalid_inputs = [ |
| 2746 |
({'a': set()}, ['Value must be valid JSON.']), |
| 2747 |
({'a': float('inf')}, ['Value must be valid JSON.']), |
| 2748 |
] |
| 2749 |
outputs = [ |
| 2750 |
({ |
| 2751 |
'a': 1, |
| 2752 |
'b': ['some', 'list', True, 1.23], |
| 2753 |
'3': 3 |
| 2754 |
}, { |
| 2755 |
'a': 1, |
| 2756 |
'b': ['some', 'list', True, 1.23], |
| 2757 |
'3': 3 |
| 2758 |
}), |
| 2759 |
] |
| 2760 |
field = serializers.JSONField() |
| 2761 |
|
| 2762 |
def test_html_input_as_json_string(self): |
| 2763 |
""" |
| 2764 |
HTML inputs should be treated as a serialized JSON string. |
| 2765 |
""" |
| 2766 |
class TestSerializer(serializers.Serializer): |
| 2767 |
config = serializers.JSONField() |
| 2768 |
|
| 2769 |
data = QueryDict(mutable=True) |
| 2770 |
data.update({'config': '{"a":1}'}) |
| 2771 |
serializer = TestSerializer(data=data) |
| 2772 |
assert serializer.is_valid() |
| 2773 |
assert serializer.validated_data == {'config': {"a": 1}} |
| 2774 |
|
| 2775 |
|
| 2776 |
class TestBinaryJSONField(FieldValues): |
| 2777 |
""" |
| 2778 |
Values for `JSONField` with binary=True. |
| 2779 |
""" |
| 2780 |
valid_inputs = [ |
| 2781 |
(b'{"a": 1, "3": null, "b": ["some", "list", true, 1.23]}', { |
| 2782 |
'a': 1, |
| 2783 |
'b': ['some', 'list', True, 1.23], |
| 2784 |
'3': None |
| 2785 |
}), |
| 2786 |
] |
| 2787 |
invalid_inputs = [ |
| 2788 |
('{"a": "unterminated string}', ['Value must be valid JSON.']), |
| 2789 |
] |
| 2790 |
outputs = [ |
| 2791 |
(['some', 'list', True, 1.23], b'["some", "list", true, 1.23]'), |
| 2792 |
] |
| 2793 |
field = serializers.JSONField(binary=True) |
| 2794 |
|
| 2795 |
|
| 2796 |
# Tests for FileField. |
| 2797 |
# -------------------- |
| 2798 |
|
| 2799 |
class MockRequest: |
| 2800 |
def build_absolute_uri(self, value): |
| 2801 |
return 'http://example.com' + value |
| 2802 |
|
| 2803 |
|
| 2804 |
class TestFileFieldContext: |
| 2805 |
def test_fully_qualified_when_request_in_context(self): |
| 2806 |
field = serializers.FileField(max_length=10) |
| 2807 |
field._context = {'request': MockRequest()} |
| 2808 |
obj = MockFile(name='example.txt', url='/example.txt') |
| 2809 |
value = field.to_representation(obj) |
| 2810 |
assert value == 'http://example.com/example.txt' |
| 2811 |
|
| 2812 |
|
| 2813 |
# Tests for FilePathField. |
| 2814 |
# -------------------- |
| 2815 |
|
| 2816 |
class TestFilePathFieldRequired: |
| 2817 |
def test_required_passed_to_both_django_file_path_field_and_base(self): |
| 2818 |
field = serializers.FilePathField( |
| 2819 |
path=os.path.abspath(os.path.dirname(__file__)), |
| 2820 |
required=False, |
| 2821 |
) |
| 2822 |
assert "" in field.choices # Django adds empty choice if not required |
| 2823 |
assert field.required is False |
| 2824 |
with pytest.raises(SkipField): |
| 2825 |
field.run_validation(empty) |
| 2826 |
|
| 2827 |
|
| 2828 |
# Tests for SerializerMethodField. |
| 2829 |
# -------------------------------- |
| 2830 |
|
| 2831 |
class TestSerializerMethodField: |
| 2832 |
def test_serializer_method_field(self): |
| 2833 |
class ExampleSerializer(serializers.Serializer): |
| 2834 |
example_field = serializers.SerializerMethodField() |
| 2835 |
|
| 2836 |
def get_example_field(self, obj): |
| 2837 |
return 'ran get_example_field(%d)' % obj['example_field'] |
| 2838 |
|
| 2839 |
serializer = ExampleSerializer({'example_field': 123}) |
| 2840 |
assert serializer.data == { |
| 2841 |
'example_field': 'ran get_example_field(123)' |
| 2842 |
} |
| 2843 |
|
| 2844 |
def test_redundant_method_name(self): |
| 2845 |
# Prior to v3.10, redundant method names were not allowed. |
| 2846 |
# This restriction has since been removed. |
| 2847 |
class ExampleSerializer(serializers.Serializer): |
| 2848 |
example_field = serializers.SerializerMethodField('get_example_field') |
| 2849 |
|
| 2850 |
field = ExampleSerializer().fields['example_field'] |
| 2851 |
assert field.method_name == 'get_example_field' |
| 2852 |
|
| 2853 |
|
| 2854 |
# Tests for ModelField. |
| 2855 |
# --------------------- |
| 2856 |
|
| 2857 |
class TestModelField: |
| 2858 |
def test_max_length_init(self): |
| 2859 |
field = serializers.ModelField(None) |
| 2860 |
assert len(field.validators) == 0 |
| 2861 |
|
| 2862 |
field = serializers.ModelField(None, max_length=10) |
| 2863 |
assert len(field.validators) == 1 |
| 2864 |
|
| 2865 |
|
| 2866 |
# Tests for validation errors |
| 2867 |
# --------------------------- |
| 2868 |
|
| 2869 |
class TestValidationErrorCode: |
| 2870 |
@pytest.mark.parametrize('use_list', (False, True)) |
| 2871 |
def test_validationerror_code_with_msg(self, use_list): |
| 2872 |
|
| 2873 |
class ExampleSerializer(serializers.Serializer): |
| 2874 |
password = serializers.CharField() |
| 2875 |
|
| 2876 |
def validate_password(self, obj): |
| 2877 |
err = DjangoValidationError( |
| 2878 |
'exc_msg %s', code='exc_code', params=('exc_param',), |
| 2879 |
) |
| 2880 |
if use_list: |
| 2881 |
err = DjangoValidationError([err]) |
| 2882 |
raise err |
| 2883 |
|
| 2884 |
serializer = ExampleSerializer(data={'password': 123}) |
| 2885 |
serializer.is_valid() |
| 2886 |
assert serializer.errors == {'password': ['exc_msg exc_param']} |
| 2887 |
assert serializer.errors['password'][0].code == 'exc_code' |
| 2888 |
|
| 2889 |
@pytest.mark.parametrize('use_list', (False, True)) |
| 2890 |
def test_validationerror_code_with_msg_including_percent(self, use_list): |
| 2891 |
|
| 2892 |
class ExampleSerializer(serializers.Serializer): |
| 2893 |
password = serializers.CharField() |
| 2894 |
|
| 2895 |
def validate_password(self, obj): |
| 2896 |
err = DjangoValidationError('exc_msg with %', code='exc_code') |
| 2897 |
if use_list: |
| 2898 |
err = DjangoValidationError([err]) |
| 2899 |
raise err |
| 2900 |
|
| 2901 |
serializer = ExampleSerializer(data={'password': 123}) |
| 2902 |
serializer.is_valid() |
| 2903 |
assert serializer.errors == {'password': ['exc_msg with %']} |
| 2904 |
assert serializer.errors['password'][0].code == 'exc_code' |
| 2905 |
|
| 2906 |
@pytest.mark.parametrize('code', (None, 'exc_code',)) |
| 2907 |
@pytest.mark.parametrize('use_list', (False, True)) |
| 2908 |
def test_validationerror_code_with_dict(self, use_list, code): |
| 2909 |
|
| 2910 |
class ExampleSerializer(serializers.Serializer): |
| 2911 |
|
| 2912 |
def validate(self, obj): |
| 2913 |
if code is None: |
| 2914 |
err = DjangoValidationError({ |
| 2915 |
'email': 'email error', |
| 2916 |
}) |
| 2917 |
else: |
| 2918 |
err = DjangoValidationError({ |
| 2919 |
'email': DjangoValidationError( |
| 2920 |
'email error', |
| 2921 |
code=code), |
| 2922 |
}) |
| 2923 |
if use_list: |
| 2924 |
err = DjangoValidationError([err]) |
| 2925 |
raise err |
| 2926 |
|
| 2927 |
serializer = ExampleSerializer(data={}) |
| 2928 |
serializer.is_valid() |
| 2929 |
expected_code = code if code else 'invalid' |
| 2930 |
if use_list: |
| 2931 |
assert serializer.errors == { |
| 2932 |
'non_field_errors': [ |
| 2933 |
exceptions.ErrorDetail( |
| 2934 |
string='email error', |
| 2935 |
code=expected_code |
| 2936 |
) |
| 2937 |
] |
| 2938 |
} |
| 2939 |
else: |
| 2940 |
assert serializer.errors == { |
| 2941 |
'email': ['email error'], |
| 2942 |
} |
| 2943 |
assert serializer.errors['email'][0].code == expected_code |
| 2944 |
|
| 2945 |
@pytest.mark.parametrize('code', (None, 'exc_code',)) |
| 2946 |
def test_validationerror_code_with_dict_list_same_code(self, code): |
| 2947 |
|
| 2948 |
class ExampleSerializer(serializers.Serializer): |
| 2949 |
|
| 2950 |
def validate(self, obj): |
| 2951 |
if code is None: |
| 2952 |
raise DjangoValidationError({'email': ['email error 1', |
| 2953 |
'email error 2']}) |
| 2954 |
raise DjangoValidationError({'email': [ |
| 2955 |
DjangoValidationError('email error 1', code=code), |
| 2956 |
DjangoValidationError('email error 2', code=code), |
| 2957 |
]}) |
| 2958 |
|
| 2959 |
serializer = ExampleSerializer(data={}) |
| 2960 |
serializer.is_valid() |
| 2961 |
expected_code = code if code else 'invalid' |
| 2962 |
assert serializer.errors == { |
| 2963 |
'email': [ |
| 2964 |
exceptions.ErrorDetail( |
| 2965 |
string='email error 1', |
| 2966 |
code=expected_code |
| 2967 |
), |
| 2968 |
exceptions.ErrorDetail( |
| 2969 |
string='email error 2', |
| 2970 |
code=expected_code |
| 2971 |
), |
| 2972 |
] |
| 2973 |
} |