def create_factory(): return Factory(schemas={ datetime: DateSchema(), Station: StationSchema(), PolicyRuleCheck: Schema(pre_parse=type_checker("0", field="action")), PolicyRuleAction: Schema(pre_parse=type_checker("1", field="action")), }, default_schema=Schema(omit_default=True, ), debug_path=True)
def test_nothing(self): factory = Factory( schemas={ A: Schema(pre_parse=type_checker("A", field="x")), B: Schema(pre_parse=type_checker("B", field="x")), C: Schema(pre_parse=type_checker("C", field="x")), }) self.assertRaises((ValueError, KeyError, TypeError, AttributeError), factory.load, {"some": { "a": "hello", "x": "XXX" }}, Container) self.assertRaises((ValueError, KeyError, TypeError, AttributeError), factory.load, {"some": { "a": "hello" }}, Container)
def test_pre_parse(self): factory = Factory( schemas={ A: Schema(pre_parse=type_checker( "A", field="x", pre_parse=pre_parse)), B: Schema(pre_parse=type_checker( "B", field="x", pre_parse=pre_parse)), C: Schema(pre_parse=type_checker( "C", field="x", pre_parse=pre_parse)), }) self.assertEqual( factory.load({"some": { "a": "hello", "x": "B" }}, Container), Container(B("hello*")))
from typing import Union from dataclasses import dataclass from dataclass_factory import Factory, Schema from dataclass_factory.schema_helpers import type_checker @dataclass class Item: name: str type: str = "item" @dataclass class Group: name: str type: str = "group" Something = Union[Item, Group] # Available types factory = Factory(schemas={ Item: Schema(pre_parse=type_checker("item", field="type")), Group: Schema(pre_parse=type_checker("group")), # `type` is default name for checked field }) assert factory.load({"name": "some name", "type": "group"}, Something) == Group("some name")