1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463
|
from dataclasses import dataclass, field
from typing import Optional, Union
import pytest
from typing_extensions import Literal
from mashumaro import DataClassDictMixin
from mashumaro.config import TO_DICT_ADD_OMIT_NONE_FLAG, BaseConfig
from mashumaro.exceptions import ExtraKeysError, InvalidFieldValue
from mashumaro.types import Discriminator, SerializationStrategy
from .entities import (
MyDataClassWithOptional,
MyDataClassWithOptionalAndOmitNoneFlag,
MyNamedTuple,
MyNamedTupleWithDefaults,
MyUntypedNamedTuple,
MyUntypedNamedTupleWithDefaults,
TypedDictRequiredKeys,
)
@dataclass
class LazyCompilationDataClass(DataClassDictMixin):
x: int
class Config(BaseConfig):
lazy_compilation = True
def test_debug_true_option(mocker):
mocked_print = mocker.patch("builtins.print")
@dataclass
class _(DataClassDictMixin):
union: Union[int, str, MyNamedTuple]
typed_dict: TypedDictRequiredKeys
named_tuple: MyNamedTupleWithDefaults
literal: Literal[1, 2, 3]
class Config(BaseConfig):
debug = True
mocked_print.assert_called()
def test_config_without_base_config_base(mocker):
mocked_print = mocker.patch("builtins.print")
@dataclass
class _(DataClassDictMixin):
x: Union[int, str]
class Config:
debug = True
mocked_print.assert_called()
def test_debug_false_option(mocker):
mocked_print = mocker.patch("builtins.print")
@dataclass
class _(DataClassDictMixin):
x: Union[int, str]
class Config(BaseConfig):
debug = False
mocked_print.assert_not_called()
def test_omit_none_code_generation_flag():
@dataclass
class DataClass(DataClassDictMixin):
x: Optional[int] = None
class Config(BaseConfig):
code_generation_options = [TO_DICT_ADD_OMIT_NONE_FLAG]
assert DataClass().to_dict() == {"x": None}
assert DataClass().to_dict(omit_none=True) == {}
def test_no_omit_none_code_generation_flag():
@dataclass
class DataClass(DataClassDictMixin):
x: Optional[int] = None
assert DataClass().to_dict() == {"x": None}
with pytest.raises(TypeError):
DataClass().to_dict(omit_none=True)
def test_omit_none_flag_for_inner_class_without_it():
@dataclass
class DataClass(DataClassDictMixin):
x: Optional[MyDataClassWithOptional] = None
class Config(BaseConfig):
code_generation_options = [TO_DICT_ADD_OMIT_NONE_FLAG]
assert DataClass().to_dict() == {"x": None}
assert DataClass().to_dict(omit_none=True) == {}
empty_x = MyDataClassWithOptional()
assert DataClass(empty_x).to_dict() == {"x": {"a": None, "b": None}}
assert DataClass(empty_x).to_dict(omit_none=True) == {
"x": {"a": None, "b": None}
}
def test_omit_none_flag_for_inner_class_with_it():
@dataclass
class DataClass(DataClassDictMixin):
x: Optional[MyDataClassWithOptionalAndOmitNoneFlag] = None
class Config(BaseConfig):
code_generation_options = [TO_DICT_ADD_OMIT_NONE_FLAG]
assert DataClass().to_dict() == {"x": None}
assert DataClass().to_dict(omit_none=True) == {}
empty_x = MyDataClassWithOptionalAndOmitNoneFlag()
assert DataClass(empty_x).to_dict() == {"x": {"a": None, "b": None}}
assert DataClass(empty_x).to_dict(omit_none=True) == {"x": {}}
def test_passing_omit_none_into_union():
@dataclass
class DataClass(DataClassDictMixin):
a: Optional[int] = None
b: Optional[Union[int, MyDataClassWithOptionalAndOmitNoneFlag]] = None
class Config(BaseConfig):
code_generation_options = [TO_DICT_ADD_OMIT_NONE_FLAG]
instance = DataClass(b=MyDataClassWithOptionalAndOmitNoneFlag(a=1))
assert instance.to_dict(omit_none=True) == {"b": {"a": 1}}
def test_serialization_strategy():
class TestSerializationStrategy(SerializationStrategy):
def serialize(self, value):
return [value]
def deserialize(self, value):
return value[0]
@dataclass
class DataClass(DataClassDictMixin):
a: int
b: str
c: int
class Config(BaseConfig):
serialization_strategy = {
int: TestSerializationStrategy(),
str: {
"serialize": lambda v: [v],
"deserialize": lambda v: v[0],
},
}
obj = DataClass(a=123, b="abc", c=123)
assert DataClass.from_dict({"a": [123], "b": ["abc"], "c": [123]}) == obj
assert obj.to_dict() == {"a": [123], "b": ["abc"], "c": [123]}
def test_named_tuple_as_dict():
@dataclass
class DataClass(DataClassDictMixin):
mnp: MyNamedTuple
mnpwd: MyNamedTupleWithDefaults
munp: MyUntypedNamedTuple
class Config(BaseConfig):
namedtuple_as_dict = True
obj = DataClass(
mnp=MyNamedTuple(i=1, f=2.0),
mnpwd=MyNamedTupleWithDefaults(i=1, f=2.0),
munp=MyUntypedNamedTuple(i=1, f=2.0),
)
obj_dict = {
"mnp": {"i": 1, "f": 2.0},
"mnpwd": {"i": 1, "f": 2.0},
"munp": {"i": 1, "f": 2.0},
}
assert obj.to_dict() == obj_dict
assert DataClass.from_dict(obj_dict) == obj
def test_untyped_named_tuple_with_defaults_as_dict():
@dataclass
class DataClass(DataClassDictMixin):
munpwd: MyUntypedNamedTupleWithDefaults
class Config(BaseConfig):
namedtuple_as_dict = True
obj = DataClass(munpwd=MyUntypedNamedTupleWithDefaults(i=1, f=2.0))
assert obj.to_dict() == {"munpwd": {"i": 1, "f": 2.0}}
assert DataClass.from_dict({"munpwd": {"i": 1, "f": 2.0}}) == obj
def test_named_tuple_as_dict_and_as_list_engine():
@dataclass
class DataClass(DataClassDictMixin):
as_dict: MyNamedTuple
as_list: MyNamedTuple = field(
metadata={"serialize": "as_list", "deserialize": "as_list"}
)
class Config(BaseConfig):
namedtuple_as_dict = True
obj = DataClass(
as_dict=MyNamedTuple(i=1, f=2.0),
as_list=MyNamedTuple(i=1, f=2.0),
)
obj_dict = {
"as_dict": {"i": 1, "f": 2.0},
"as_list": [1, 2.0],
}
assert obj.to_dict() == obj_dict
assert DataClass.from_dict(obj_dict) == obj
def test_omit_none_code_generation_flag_with_omit_none_by_default():
@dataclass
class DataClass(DataClassDictMixin):
x: Optional[int] = None
class Config(BaseConfig):
code_generation_options = [TO_DICT_ADD_OMIT_NONE_FLAG]
omit_none = True
assert DataClass().to_dict() == {}
assert DataClass().to_dict(omit_none=True) == {}
assert DataClass().to_dict(omit_none=False) == {"x": None}
def test_lazy_compilation():
obj = LazyCompilationDataClass(42)
assert LazyCompilationDataClass.from_dict({"x": "42"}) == obj
assert obj.to_dict() == {"x": 42}
def test_sort_keys_with_mixin():
@dataclass
class SortedDataClass(DataClassDictMixin):
foo: int
bar: int
class Config(BaseConfig):
sort_keys = True
@dataclass
class UnSortedDataClass(DataClassDictMixin):
foo: int
bar: int
class Config(BaseConfig):
sort_keys = False
t = SortedDataClass(1, 2)
assert str(t.to_dict()) == "{'bar': 2, 'foo': 1}"
t = UnSortedDataClass(1, 2)
assert str(t.to_dict()) == "{'foo': 1, 'bar': 2}"
@dataclass
class SortedDataClass:
foo: int
bar: int
class Config(BaseConfig):
sort_keys = True
@dataclass
class UnSortedDataClass:
foo: int
bar: int
class Config(BaseConfig):
sort_keys = False
def test_sort_keys_plain_dataclass():
@dataclass
class RootSortedModel(DataClassDictMixin):
unsorted_sub: UnSortedDataClass
sorted_sub: SortedDataClass
class Config(BaseConfig):
sort_keys = True
@dataclass
class RootUnSortedModel(DataClassDictMixin):
unsorted_sub: UnSortedDataClass
sorted_sub: SortedDataClass
class Config(BaseConfig):
sort_keys = False
t = RootSortedModel(
unsorted_sub=UnSortedDataClass(1, 2),
sorted_sub=SortedDataClass(1, 2),
)
assert str(t.to_dict()) == (
"{'sorted_sub': {'bar': 2, 'foo': 1}, "
"'unsorted_sub': {'foo': 1, 'bar': 2}}"
)
t = RootUnSortedModel(
unsorted_sub=UnSortedDataClass(1, 2),
sorted_sub=SortedDataClass(1, 2),
)
assert str(t.to_dict()) == (
"{'unsorted_sub': {'foo': 1, 'bar': 2}, "
"'sorted_sub': {'bar': 2, 'foo': 1}}"
)
def test_forbid_extra_keys():
@dataclass
class ForbidKeysModel(DataClassDictMixin):
foo: int
class Config(BaseConfig):
forbid_extra_keys = True
# Test unpacking works
assert ForbidKeysModel.from_dict({"foo": 1}) == ForbidKeysModel(1)
# Test extra keys are forbidden
with pytest.raises(ExtraKeysError) as exc_info:
ForbidKeysModel.from_dict({"foo": 1, "bar": 2, "baz": 3})
assert exc_info.value.extra_keys == {"bar", "baz"}
assert exc_info.value.target_type == ForbidKeysModel
# Now with alias, but not allow_deserialization_not_by_alias
@dataclass
class ForbidKeysModel(DataClassDictMixin):
foo: int = field(metadata={"alias": "f"})
bar: int
class Config(BaseConfig):
forbid_extra_keys = True
aliases = {"bar": "b"}
# Test unpacking works
assert ForbidKeysModel.from_dict({"f": 1, "b": 2}) == ForbidKeysModel(1, 2)
# Test extra keys are forbidden
with pytest.raises(ExtraKeysError) as exc_info:
ForbidKeysModel.from_dict({"foo": 1, "bar": 2})
assert exc_info.value.extra_keys == {"foo", "bar"}
assert exc_info.value.target_type == ForbidKeysModel
# Now with alias, but allow_deserialization_not_by_alias
@dataclass
class ForbidKeysModel(DataClassDictMixin):
foo: int = field(metadata={"alias": "f"})
bar: int
class Config(BaseConfig):
forbid_extra_keys = True
aliases = {"bar": "b"}
allow_deserialization_not_by_alias = True
# Test unpacking works
assert ForbidKeysModel.from_dict({"f": 1, "bar": 2}) == ForbidKeysModel(
1, 2
)
# Test extra keys are forbidden
with pytest.raises(ExtraKeysError) as exc_info:
ForbidKeysModel.from_dict({"foo": 1, "b": 2, "baz": 3})
assert exc_info.value.extra_keys == {"baz"}
assert exc_info.value.target_type == ForbidKeysModel
@dataclass
class _VariantByBase(DataClassDictMixin):
class Config(BaseConfig):
discriminator = Discriminator(
field="__type",
include_subtypes=True,
variant_tagger_fn=lambda clz: clz.__name__,
)
forbid_extra_keys = True
@dataclass
class _VariantByField1(_VariantByBase):
x: Optional[str] = None
@dataclass
class _VariantByField2(_VariantByBase):
x: Optional[str] = None
@dataclass
class _VariantByField3(_VariantByBase):
x: Optional[str] = None
class Config(BaseConfig):
# add intermediate config to check if we're looking for the
# discriminator in the base class _VariantByBase to add the
# discriminator field to the list of allowed keys for _VariantByField4
# deserializable via _VariantByBase.from_dict
omit_none = True
@dataclass
class _VariantByField4(_VariantByField3):
class Config(BaseConfig):
forbid_extra_keys = True
@dataclass
class ForbidKeysModelWithDiscriminator(DataClassDictMixin):
inner: _VariantByBase
class Config(BaseConfig):
forbid_extra_keys = True
def test_forbid_extra_keys_with_discriminator():
# Test unpacking works
assert ForbidKeysModelWithDiscriminator.from_dict(
{"inner": {"x": "foo", "__type": "_VariantByField2"}}
) == ForbidKeysModelWithDiscriminator(_VariantByField2(x="foo"))
# Test extra keys are forbidden
with pytest.raises(InvalidFieldValue) as exc_info:
ForbidKeysModelWithDiscriminator.from_dict(
{"inner": {"x": "foo", "__type": "_VariantByField2", "bar": "baz"}}
)
root_exc = exc_info.value.__context__
assert isinstance(root_exc, ExtraKeysError)
assert root_exc.extra_keys == {"bar"}
assert root_exc.target_type == _VariantByField2
def test_forbid_extra_keys_with_discriminator_for_subclass():
assert _VariantByBase.from_dict(
{"x": "foo", "__type": "_VariantByField4"}
) == _VariantByField4("foo")
with pytest.raises(ExtraKeysError) as exc_info:
_VariantByBase.from_dict(
{"x": "foo", "__type": "_VariantByField4", "y": "bar"}
)
assert exc_info.value.extra_keys == {"y"}
|