Overload dump/dumps methods to increase type safety;

issue a warning, when using the `many` parameter in `__init__`
This commit is contained in:
2023-03-13 00:08:57 +01:00
parent 84fa2d2cd9
commit 712f7fca7b
2 changed files with 200 additions and 4 deletions

View File

@ -1,3 +1,4 @@
from typing import Any
from unittest import TestCase
from unittest.mock import MagicMock, patch
@ -5,6 +6,29 @@ from marshmallow_generic import _util, schema
class GenericSchemaTestCase(TestCase):
@patch("marshmallow.schema.Schema.__init__")
def test___init__(self, mock_super_init: MagicMock) -> None:
class Foo:
pass
kwargs: dict[str, Any] = {
"only": object(),
"exclude": object(),
"context": object(),
"load_only": object(),
"dump_only": object(),
"partial": object(),
"unknown": object(),
"many": None,
}
schema.GenericSchema[Foo](**kwargs)
mock_super_init.assert_called_once_with(**kwargs | {"many": False})
mock_super_init.reset_mock()
kwargs["many"] = True
with self.assertWarns(UserWarning):
schema.GenericSchema[Foo](**kwargs)
mock_super_init.assert_called_once_with(**kwargs)
@patch.object(_util.GenericInsightMixin, "_get_type_arg")
def test_instantiate(self, mock__get_type_arg: MagicMock) -> None:
mock__get_type_arg.return_value = mock_cls = MagicMock()
@ -20,6 +44,26 @@ class GenericSchemaTestCase(TestCase):
mock__get_type_arg.assert_called_once_with(0)
mock_cls.assert_called_once_with(**mock_data)
def test_dump_and_dumps(self) -> None:
"""Mainly for static type checking purposes."""
class Foo:
pass
class TestSchema(schema.GenericSchema[Foo]):
pass
foo = Foo()
single: dict[str, Any] = TestSchema().dump(foo)
self.assertDictEqual({}, single)
json_string: str = TestSchema().dumps(foo)
self.assertEqual("{}", json_string)
multiple: list[dict[str, Any]] = TestSchema().dump([foo], many=True)
self.assertListEqual([{}], multiple)
json_string = TestSchema().dumps([foo], many=True)
self.assertEqual("[{}]", json_string)
def test_load_and_loads(self) -> None:
"""Mainly for static type checking purposes."""