|
1 | | -import pytest |
2 | 1 | import schemars |
3 | 2 |
|
4 | 3 |
|
@@ -187,22 +186,53 @@ def __init__(self, name): |
187 | 186 |
|
188 | 187 | class ProductSchema(schemars.Schema): |
189 | 188 | name = schemars.Str() |
| 189 | + method = schemars.Method() |
190 | 190 |
|
191 | | - def serialize(self, instance, many=None): |
192 | | - context_suffix = self.context.get("suffix") if self.context else "" |
193 | | - result = super().serialize(instance, many) |
194 | | - if not many: |
195 | | - result["name"] += context_suffix |
196 | | - else: |
197 | | - for item in result: |
198 | | - item["name"] += context_suffix |
199 | | - return result |
200 | | - |
201 | | - schema = ProductSchema(context={"suffix": " - Context"}) |
| 191 | + def get_method(self, obj): |
| 192 | + return self.context.get("suffix") |
| 193 | + |
| 194 | + schema = ProductSchema(context={"suffix": "test"}) |
202 | 195 | product = Product("Product 1") |
203 | 196 | result = schema.serialize(product) |
204 | | - assert result == {"name": "Product 1 - Context"} |
| 197 | + assert result == {"name": "Product 1", "method": "test"} |
205 | 198 |
|
206 | | - products = [Product("Product 1"), Product("Product 2")] |
207 | | - result = schema.serialize(products, many=True) |
208 | | - assert result == [{"name": "Product 1 - Context"}, {"name": "Product 2 - Context"}] |
| 199 | + |
| 200 | +def test_serialize_with_inheritance(): |
| 201 | + class Product: |
| 202 | + def __init__(self, name, display_name, related_products): |
| 203 | + self.name = name |
| 204 | + self.display_name = display_name |
| 205 | + self.related_products = related_products |
| 206 | + |
| 207 | + class BaseProductSchema(schemars.Schema): |
| 208 | + name = schemars.Str() |
| 209 | + display_name = schemars.Str() |
| 210 | + |
| 211 | + class ProductSchema(BaseProductSchema): |
| 212 | + related_products = BaseProductSchema(many=True) |
| 213 | + |
| 214 | + schema = ProductSchema() |
| 215 | + product = Product("Product 1", "Product 1", [Product("Product 2", "Product 2", [])]) |
| 216 | + result = schema.serialize(product) |
| 217 | + assert result == { |
| 218 | + "name": "Product 1", |
| 219 | + "display_name": "Product 1", |
| 220 | + "related_products": [{"name": "Product 2", "display_name": "Product 2"}], |
| 221 | + } |
| 222 | + |
| 223 | + |
| 224 | +def test_serialize_with_custom_attributes(): |
| 225 | + class Product: |
| 226 | + pass |
| 227 | + |
| 228 | + class ProductSchema(schemars.Schema): |
| 229 | + method = schemars.Method() |
| 230 | + |
| 231 | + def get_method(self, obj): |
| 232 | + self.test = "test" |
| 233 | + return self.test |
| 234 | + |
| 235 | + schema = ProductSchema() |
| 236 | + product = Product() |
| 237 | + result = schema.serialize(product) |
| 238 | + assert result == {"method": "test"} |
0 commit comments