Skip to content

Commit 14e2d8b

Browse files
committed
Add a test for post_dump
see #125
1 parent 098cf96 commit 14e2d8b

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

tests/test_postdump.py

+57
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
import typing as T
2+
from dataclasses import field
3+
4+
import marshmallow as mm
5+
import marshmallow_dataclass as mmdc
6+
import collections.abc
7+
import unittest
8+
9+
10+
# Test from https://github.com/lovasoa/marshmallow_dataclass/issues/125
11+
class TestPostDump(unittest.TestCase):
12+
def setUp(self) -> None:
13+
class BaseSchema(mm.Schema):
14+
SKIP_VALUES = {None}
15+
16+
@mm.post_dump
17+
def remove_skip_values(self, data, many):
18+
return {
19+
key: value
20+
for key, value in data.items()
21+
if not isinstance(value, collections.abc.Hashable)
22+
or value not in self.SKIP_VALUES
23+
}
24+
25+
@mmdc.add_schema(base_schema=BaseSchema)
26+
@mmdc.dataclass
27+
class Item:
28+
key: str
29+
val: str
30+
Schema: T.ClassVar[T.Type[mm.Schema]] = mm.Schema
31+
32+
@mmdc.add_schema(base_schema=BaseSchema)
33+
@mmdc.dataclass
34+
class Items:
35+
other: T.Optional[str]
36+
items: T.List[Item] = field(default_factory=list)
37+
Schema: T.ClassVar[T.Type[mm.Schema]] = mm.Schema
38+
39+
self.BaseSchema = BaseSchema
40+
self.Item = Item
41+
self.Items = Items
42+
self.data = {"items": [{"key": "any key", "val": "any value"}]}
43+
44+
def test_class_schema(self):
45+
items_schema = mmdc.class_schema(self.Items, base_schema=self.BaseSchema)()
46+
items = items_schema.load(self.data)
47+
self.assertEqual(
48+
{"items": [{"key": "any key", "val": "any value"}]},
49+
items_schema.dump(items),
50+
)
51+
52+
def test_inside_schema(self):
53+
items = self.Items.Schema().load(self.data)
54+
self.assertEqual(
55+
{"items": [{"key": "any key", "val": "any value"}]},
56+
self.Items.Schema().dump(items),
57+
)

0 commit comments

Comments
 (0)