From 87c76d71581a2cba13bbb7797991bf58e8417558 Mon Sep 17 00:00:00 2001 From: "Devin A. Conley" Date: Fri, 23 Dec 2022 09:13:33 -0500 Subject: [PATCH 1/4] remove deprecated default field --- objectfactory/field.py | 6 ------ 1 file changed, 6 deletions(-) diff --git a/objectfactory/field.py b/objectfactory/field.py index b223734..c066f87 100644 --- a/objectfactory/field.py +++ b/objectfactory/field.py @@ -36,7 +36,6 @@ def __set__( self, instance, value ): def marshmallow( self ): return marshmallow.fields.Field( data_key=self._key, - default=self._default, required=self._required, allow_none=self._allow_none ) @@ -50,7 +49,6 @@ class Integer( Field ): def marshmallow( self ): return marshmallow.fields.Integer( data_key=self._key, - default=self._default, required=self._required, allow_none=self._allow_none ) @@ -64,7 +62,6 @@ class String( Field ): def marshmallow( self ): return marshmallow.fields.String( data_key=self._key, - default=self._default, required=self._required, allow_none=self._allow_none ) @@ -78,7 +75,6 @@ class Boolean( Field ): def marshmallow( self ): return marshmallow.fields.Boolean( data_key=self._key, - default=self._default, required=self._required, allow_none=self._allow_none ) @@ -92,7 +88,6 @@ class Float( Field ): def marshmallow( self ): return marshmallow.fields.Float( data_key=self._key, - default=self._default, required=self._required, allow_none=self._allow_none ) @@ -125,7 +120,6 @@ def marshmallow( self ): return NestedFactoryField( field_type=self._field_type, data_key=self._key, - default=self._default, required=self._required, allow_none=self._allow_none ) From 957ed46163fc0fad6fb0b184627c0aae0b1b80fa Mon Sep 17 00:00:00 2001 From: "Devin A. Conley" Date: Tue, 24 Jan 2023 09:05:52 -0500 Subject: [PATCH 2/4] fix style --- README.md | 12 +-- examples/custom_schema.py | 30 +++---- examples/product_orders.py | 50 +++++------ examples/shapes.py | 12 +-- objectfactory/base.py | 16 ++-- objectfactory/factory.py | 30 +++---- objectfactory/field.py | 54 ++++++------ objectfactory/nested.py | 24 ++--- objectfactory/serializable.py | 36 ++++---- setup.py | 2 +- test/test_boolean.py | 72 +++++++-------- test/test_custom_schema.py | 84 +++++++++--------- test/test_factory.py | 38 ++++---- test/test_fields.py | 72 +++++++-------- test/test_float.py | 50 +++++------ test/test_integer.py | 48 +++++----- test/test_list.py | 156 ++++++++++++++++----------------- test/test_nested.py | 68 +++++++------- test/test_serializable.py | 70 +++++++-------- test/test_string.py | 40 ++++----- test/testmodule/testclasses.py | 8 +- 21 files changed, 486 insertions(+), 486 deletions(-) diff --git a/README.md b/README.md index a96d646..b338b9d 100644 --- a/README.md +++ b/README.md @@ -19,18 +19,18 @@ Simple **shapes** example: import objectfactory @objectfactory.register -class Square( objectfactory.Serializable ): +class Square(objectfactory.Serializable): side = objectfactory.Field() - def get_area( self ): + def get_area(self): return self.side * self.side @objectfactory.register -class Triangle( objectfactory.Serializable ): +class Triangle(objectfactory.Serializable): base = objectfactory.Field() height = objectfactory.Field() - def get_area( self ): + def get_area(self): return 0.5 * self.base * self.height serialized_data = [ @@ -40,8 +40,8 @@ serialized_data = [ ] for data in serialized_data: - shape = objectfactory.create( data ) - print( 'class type: {}, shape area: {}'.format( type( shape ), shape.get_area() ) ) + shape = objectfactory.create(data) + print('class type: {}, shape area: {}'.format(type(shape), shape.get_area())) ``` Output: diff --git a/examples/custom_schema.py b/examples/custom_schema.py index b5b2d6f..9283ce2 100644 --- a/examples/custom_schema.py +++ b/examples/custom_schema.py @@ -36,7 +36,7 @@ def main(): # load and validate each contact for c in contacts: try: - contact = objectfactory.create( c, object_type=Contact ) + contact = objectfactory.create(c, object_type=Contact) print( 'Loaded contact for: {} {}, number: {}, email: {}'.format( contact.first_name, @@ -46,29 +46,29 @@ def main(): ) ) except marshmallow.ValidationError as e: - print( 'Validation error: {}'.format( e ) ) + print('Validation error: {}'.format(e)) -class PhoneNumber( marshmallow.fields.Field ): +class PhoneNumber(marshmallow.fields.Field): """Custom marshmallow field to validate phone number""" - def _deserialize( self, value, *args, **kwargs ): + def _deserialize(self, value, *args, **kwargs): try: - x = value.split( '-' ) - assert len( x ) == 3 - assert len( x[0] ) == 3 - assert len( x[1] ) == 3 - assert len( x[2] ) == 4 - return str( value ) + x = value.split('-') + assert len(x) == 3 + assert len(x[0]) == 3 + assert len(x[1]) == 3 + assert len(x[2]) == 4 + return str(value) except AssertionError as e: - raise marshmallow.ValidationError( 'Invalid phone number' ) + raise marshmallow.ValidationError('Invalid phone number') - def _serialize( self, value, *args, **kwargs ): - return str( value ) + def _serialize(self, value, *args, **kwargs): + return str(value) -class ContactSchema( marshmallow.Schema ): +class ContactSchema(marshmallow.Schema): """Custom marshmallow schema for contact info""" first_name = marshmallow.fields.Str() @@ -78,7 +78,7 @@ class ContactSchema( marshmallow.Schema ): @objectfactory.register -class Contact( objectfactory.Serializable, schema=ContactSchema ): +class Contact(objectfactory.Serializable, schema=ContactSchema): """ product order from a dollar store vendor """ diff --git a/examples/product_orders.py b/examples/product_orders.py index bea94dc..8205392 100644 --- a/examples/product_orders.py +++ b/examples/product_orders.py @@ -26,60 +26,60 @@ def main(): ] # deserialize raw product order - products = [objectfactory.create( order, object_type=Product ) for order in raw_orders] + products = [objectfactory.create(order, object_type=Product) for order in raw_orders] # calculate overall price - price = sum( [prod.get_price() * prod.quantity for prod in products] ) - print( 'Overall order price: ${}'.format( price ) ) + price = sum([prod.get_price() * prod.quantity for prod in products]) + print('Overall order price: ${}'.format(price)) # estimate delivery - days = max( [prod.get_delivery_time() for prod in products] ) - print( 'Estimated delivery time is: {} days'.format( days ) ) + days = max([prod.get_delivery_time() for prod in products]) + print('Estimated delivery time is: {} days'.format(days)) # validate stocking - in_stock = all( [prod.quantity < prod.get_quantity_in_stock() for prod in products] ) - print( 'Products are {}stocked'.format( '' if in_stock else 'not ' ) ) + in_stock = all([prod.quantity < prod.get_quantity_in_stock() for prod in products]) + print('Products are {}stocked'.format('' if in_stock else 'not ')) -class Product( objectfactory.Serializable ): +class Product(objectfactory.Serializable): """ base abstract class for our products """ product_id = objectfactory.String() # all products will have an id - quantity = objectfactory.Integer( default=1 ) # all products will have a quantity + quantity = objectfactory.Integer(default=1) # all products will have a quantity - def get_price( self ) -> float: + def get_price(self) -> float: """ abstract method to calculate price and return :return: float """ - raise NotImplementedError( 'get_price method is required' ) + raise NotImplementedError('get_price method is required') - def get_delivery_time( self ) -> int: + def get_delivery_time(self) -> int: """ abstract method to get required delivery time :return: """ - raise NotImplementedError( 'get_delivery_time method is required' ) + raise NotImplementedError('get_delivery_time method is required') - def get_quantity_in_stock( self ) -> int: + def get_quantity_in_stock(self) -> int: """ abstract method to get quantity in stock :return: """ - raise NotImplementedError( 'get_quantity_in_stock method is required' ) + raise NotImplementedError('get_quantity_in_stock method is required') @objectfactory.register -class DollarStoreProduct( Product ): +class DollarStoreProduct(Product): """ product order from a dollar store vendor """ - def get_price( self ) -> float: + def get_price(self) -> float: """ everything is a dollar!!!! @@ -87,7 +87,7 @@ def get_price( self ) -> float: """ return 1.00 - def get_delivery_time( self ) -> int: + def get_delivery_time(self) -> int: """ everything takes about a week to ship @@ -95,7 +95,7 @@ def get_delivery_time( self ) -> int: """ return 7 - def get_quantity_in_stock( self ) -> int: + def get_quantity_in_stock(self) -> int: """ mock connection to this vendor's supply data @@ -105,16 +105,16 @@ def get_quantity_in_stock( self ) -> int: 'greeting_card': 300, 'candle': 15, 'glass_vase': 10 - }.get( self.product_id, 0 ) + }.get(self.product_id, 0) @objectfactory.register -class EcommerceGiantProduct( Product ): +class EcommerceGiantProduct(Product): """ product order from an e-commerce giant """ - def get_price( self ) -> float: + def get_price(self) -> float: """ mock connection to this vendor's pricing data @@ -125,9 +125,9 @@ def get_price( self ) -> float: 'tv': 450, 'digital_clock': 10, 'virtual_assistant': 50 - }.get( self.product_id, None ) + }.get(self.product_id, None) - def get_delivery_time( self ) -> int: + def get_delivery_time(self) -> int: """ guaranteed 2-day delivery @@ -135,7 +135,7 @@ def get_delivery_time( self ) -> int: """ return 2 - def get_quantity_in_stock( self ) -> int: + def get_quantity_in_stock(self) -> int: """ infinite supplies diff --git a/examples/shapes.py b/examples/shapes.py index 126630a..e98167b 100644 --- a/examples/shapes.py +++ b/examples/shapes.py @@ -16,18 +16,18 @@ def main(): # load each shape, printing object type and area for data in serialized_data: - shape = objectfactory.create( data ) - print( 'class type: {}, shape area: {}'.format( type( shape ), shape.get_area() ) ) + shape = objectfactory.create(data) + print('class type: {}, shape area: {}'.format(type(shape), shape.get_area())) @objectfactory.register -class Square( objectfactory.Serializable ): +class Square(objectfactory.Serializable): """ serializable square class """ side = objectfactory.Float() - def get_area( self ) -> float: + def get_area(self) -> float: """ calculate area of square @@ -37,14 +37,14 @@ def get_area( self ) -> float: @objectfactory.register -class Triangle( objectfactory.Serializable ): +class Triangle(objectfactory.Serializable): """ serializable triangle class """ base = objectfactory.Float() height = objectfactory.Float() - def get_area( self ) -> float: + def get_area(self) -> float: """ calculate area of triangle diff --git a/objectfactory/base.py b/objectfactory/base.py index ca60e7b..75aae75 100644 --- a/objectfactory/base.py +++ b/objectfactory/base.py @@ -7,12 +7,12 @@ from abc import ABC, abstractmethod -class FieldABC( ABC ): +class FieldABC(ABC): """ abstract base class for serializable field """ - def __init__( self, default=None, key=None, required=False, allow_none=True ): + def __init__(self, default=None, key=None, required=False, allow_none=True): """ :param default: default value for field if unset :param key: dictionary key to use for field serialization @@ -26,15 +26,15 @@ def __init__( self, default=None, key=None, required=False, allow_none=True ): self._allow_none = allow_none @abstractmethod - def __get__( self, instance, owner ): + def __get__(self, instance, owner): pass @abstractmethod - def __set__( self, instance, value ): + def __set__(self, instance, value): pass @abstractmethod - def marshmallow( self ): + def marshmallow(self): """ create generic marshmallow field to do actual serialization @@ -43,13 +43,13 @@ def marshmallow( self ): pass -class SerializableABC( ABC ): +class SerializableABC(ABC): """ abstract base class for serializable object """ @abstractmethod - def serialize( self, include_type: bool = True, use_full_type: bool = True ) -> dict: + def serialize(self, include_type: bool = True, use_full_type: bool = True) -> dict: """ serialize model to dictionary @@ -60,7 +60,7 @@ def serialize( self, include_type: bool = True, use_full_type: bool = True ) -> pass @abstractmethod - def deserialize( self, body: dict ): + def deserialize(self, body: dict): """ deserialize model from dictionary diff --git a/objectfactory/factory.py b/objectfactory/factory.py index 04140ef..9ee07be 100644 --- a/objectfactory/factory.py +++ b/objectfactory/factory.py @@ -10,19 +10,19 @@ from .serializable import Serializable # type var for hinting from generic function -T = TypeVar( 'T', bound=Serializable ) +T = TypeVar('T', bound=Serializable) -class Factory( object ): +class Factory(object): """ factory class for registering and creating serializable objects """ - def __init__( self, name ): + def __init__(self, name): self.name = name self.registry = {} - def register( self, serializable: Serializable ): + def register(self, serializable: Serializable): """ decorator to register class with factory @@ -33,7 +33,7 @@ def register( self, serializable: Serializable ): self.registry[serializable.__name__] = serializable return serializable - def create( self, body: dict, object_type: Type[T] = Serializable ) -> T: + def create(self, body: dict, object_type: Type[T] = Serializable) -> T: """ create object from dictionary @@ -49,31 +49,31 @@ def create( self, body: dict, object_type: Type[T] = Serializable ) -> T: pass if obj is None: try: - obj = self.registry[body['_type'].split( '.' )[-1]]() + obj = self.registry[body['_type'].split('.')[-1]]() except KeyError: pass if obj is None: raise ValueError( - 'Object type {} not found in factory registry'.format( body['_type'] ) + 'Object type {} not found in factory registry'.format(body['_type']) ) - if not isinstance( obj, object_type ): + if not isinstance(obj, object_type): raise TypeError( 'Object type {} is not a {}'.format( - type( obj ).__name__, + type(obj).__name__, object_type.__name__ ) ) - obj.deserialize( body ) + obj.deserialize(body) return obj # global registry -_global_factory = Factory( 'global' ) +_global_factory = Factory('global') -def create( body: dict, object_type: Type[T] = Serializable ) -> T: +def create(body: dict, object_type: Type[T] = Serializable) -> T: """ create object from dictionary with the global factory @@ -82,14 +82,14 @@ def create( body: dict, object_type: Type[T] = Serializable ) -> T: :raises TypeError: if the object is not an instance of the specified type :return: deserialized object of specified type """ - return _global_factory.create( body, object_type=object_type ) + return _global_factory.create(body, object_type=object_type) -def register( serializable: Serializable ): +def register(serializable: Serializable): """ decorator to register class with the global factory :param serializable: serializable object class :return: registered class """ - return _global_factory.register( serializable ) + return _global_factory.register(serializable) diff --git a/objectfactory/field.py b/objectfactory/field.py index c066f87..1fea824 100644 --- a/objectfactory/field.py +++ b/objectfactory/field.py @@ -14,7 +14,7 @@ from .nested import NestedFactoryField -class Field( FieldABC ): +class Field(FieldABC): """ base class for serializable field @@ -22,18 +22,18 @@ class Field( FieldABC ): serializable objects """ - def __get__( self, instance, owner ): + def __get__(self, instance, owner): try: - return getattr( instance, self._attr_key ) + return getattr(instance, self._attr_key) except AttributeError: # lazily create copy of default - setattr( instance, self._attr_key, deepcopy( self._default ) ) - return getattr( instance, self._attr_key ) + setattr(instance, self._attr_key, deepcopy(self._default)) + return getattr(instance, self._attr_key) - def __set__( self, instance, value ): - setattr( instance, self._attr_key, value ) + def __set__(self, instance, value): + setattr(instance, self._attr_key, value) - def marshmallow( self ): + def marshmallow(self): return marshmallow.fields.Field( data_key=self._key, required=self._required, @@ -41,12 +41,12 @@ def marshmallow( self ): ) -class Integer( Field ): +class Integer(Field): """ serializable field for integer data """ - def marshmallow( self ): + def marshmallow(self): return marshmallow.fields.Integer( data_key=self._key, required=self._required, @@ -54,12 +54,12 @@ def marshmallow( self ): ) -class String( Field ): +class String(Field): """ serializable field for string data """ - def marshmallow( self ): + def marshmallow(self): return marshmallow.fields.String( data_key=self._key, required=self._required, @@ -67,12 +67,12 @@ def marshmallow( self ): ) -class Boolean( Field ): +class Boolean(Field): """ serializable field for boolean data """ - def marshmallow( self ): + def marshmallow(self): return marshmallow.fields.Boolean( data_key=self._key, required=self._required, @@ -80,12 +80,12 @@ def marshmallow( self ): ) -class Float( Field ): +class Float(Field): """ serializable field for float data """ - def marshmallow( self ): + def marshmallow(self): return marshmallow.fields.Float( data_key=self._key, required=self._required, @@ -93,7 +93,7 @@ def marshmallow( self ): ) -class Nested( Field ): +class Nested(Field): """ field type for nested serializable object """ @@ -113,10 +113,10 @@ def __init__( :param required: whether this field is required to deserialize an object :param allow_none: whether null should be considered a valid value """ - super().__init__( default=default, key=key, required=required, allow_none=allow_none ) + super().__init__(default=default, key=key, required=required, allow_none=allow_none) self._field_type = field_type - def marshmallow( self ): + def marshmallow(self): return NestedFactoryField( field_type=self._field_type, data_key=self._key, @@ -125,7 +125,7 @@ def marshmallow( self ): ) -class List( Field ): +class List(Field): """ field type for list of serializable objects """ @@ -147,18 +147,18 @@ def __init__( """ if default is None: default = [] - super().__init__( default=default, key=key, required=required, allow_none=allow_none ) + super().__init__(default=default, key=key, required=required, allow_none=allow_none) self._field_type = field_type - def marshmallow( self ): - if self._field_type is None or issubclass( self._field_type, SerializableABC ): - cls = NestedFactoryField( field_type=self._field_type ) - elif issubclass( self._field_type, FieldABC ): + def marshmallow(self): + if self._field_type is None or issubclass(self._field_type, SerializableABC): + cls = NestedFactoryField(field_type=self._field_type) + elif issubclass(self._field_type, FieldABC): cls = self._field_type().marshmallow() - elif issubclass( self._field_type, marshmallow.fields.FieldABC ): + elif issubclass(self._field_type, marshmallow.fields.FieldABC): cls = self._field_type else: - raise ValueError( 'Invalid field type in List: {}'.format( self._field_type ) ) + raise ValueError('Invalid field type in List: {}'.format(self._field_type)) return marshmallow.fields.List( cls, diff --git a/objectfactory/nested.py b/objectfactory/nested.py index 736815f..9289bb9 100644 --- a/objectfactory/nested.py +++ b/objectfactory/nested.py @@ -12,13 +12,13 @@ from .factory import create -class NestedFactoryField( marshmallow.fields.Field ): +class NestedFactoryField(marshmallow.fields.Field): - def __init__( self, field_type=None, **kwargs ): - super().__init__( **kwargs ) + def __init__(self, field_type=None, **kwargs): + super().__init__(**kwargs) self._field_type = field_type - def _serialize( self, value, attr, obj, **kwargs ): + def _serialize(self, value, attr, obj, **kwargs): """ dump serializable object within the interface of marshmallow field @@ -28,11 +28,11 @@ def _serialize( self, value, attr, obj, **kwargs ): :param kwargs: :return: """ - if not isinstance( value, Serializable ): + if not isinstance(value, Serializable): return {} - return value.serialize( **obj._serialize_kwargs ) + return value.serialize(**obj._serialize_kwargs) - def _deserialize( self, value, attr, data, **kwargs ): + def _deserialize(self, value, attr, data, **kwargs): """ create serializable object with factory through interface of marshmallow field @@ -46,16 +46,16 @@ def _deserialize( self, value, attr, data, **kwargs ): return if '_type' in value: - obj = create( value ) - if self._field_type and not isinstance( obj, self._field_type ): + obj = create(value) + if self._field_type and not isinstance(obj, self._field_type): raise ValueError( '{} is not an instance of type: {}'.format( - type( obj ).__name__, self._field_type.__name__ ) + type(obj).__name__, self._field_type.__name__) ) elif self._field_type: obj = self._field_type() - obj.deserialize( value ) + obj.deserialize(value) else: - raise ValueError( 'Cannot infer type information' ) + raise ValueError('Cannot infer type information') return obj diff --git a/objectfactory/serializable.py b/objectfactory/serializable.py index 1f79598..45334a8 100644 --- a/objectfactory/serializable.py +++ b/objectfactory/serializable.py @@ -12,7 +12,7 @@ from .base import FieldABC, SerializableABC -class Meta( ABCMeta ): +class Meta(ABCMeta): """ metaclass for serializable classes @@ -20,7 +20,7 @@ class Meta( ABCMeta ): defining a new serializable class """ - def __new__( mcs, name, bases, attributes, schema=None ): + def __new__(mcs, name, bases, attributes, schema=None): """ define a new serializable object class, collect and register all field descriptors, construct marshmallow schema @@ -31,16 +31,16 @@ def __new__( mcs, name, bases, attributes, schema=None ): :param schema: (optional) predefined marshmallow schema :return: newly defined class """ - obj = ABCMeta.__new__( mcs, name, bases, attributes ) + obj = ABCMeta.__new__(mcs, name, bases, attributes) # init and collect serializable fields of parents fields = {} for base in bases: - fields.update( getattr( base, '_fields', {} ) ) + fields.update(getattr(base, '_fields', {})) # populate with all serializable class descriptors for attr_name, attr in attributes.items(): - if isinstance( attr, FieldABC ): + if isinstance(attr, FieldABC): if attr._key is None: attr._key = attr_name attr._attr_key = '_' + attr_name # define key that descriptor will use to access data @@ -54,16 +54,16 @@ def __new__( mcs, name, bases, attributes, schema=None ): } schema = marshmallow.Schema.from_dict( marsh_fields, - name='_{}Schema'.format( name ) + name='_{}Schema'.format(name) ) # set fields and schema - setattr( obj, '_fields', fields ) - setattr( obj, '_schema', schema ) + setattr(obj, '_fields', fields) + setattr(obj, '_schema', schema) return obj -class Serializable( SerializableABC, metaclass=Meta, schema=None ): +class Serializable(SerializableABC, metaclass=Meta, schema=None): """ base class for serializable objects """ @@ -71,7 +71,7 @@ class Serializable( SerializableABC, metaclass=Meta, schema=None ): _schema = None @classmethod - def from_kwargs( cls, **kwargs ): + def from_kwargs(cls, **kwargs): """ constructor to set field data by keyword args @@ -81,12 +81,12 @@ def from_kwargs( cls, **kwargs ): obj = cls() for key, val in kwargs.items(): if key in obj._fields: - obj._fields[key].__set__( obj, val ) + obj._fields[key].__set__(obj, val) return obj @classmethod - def from_dict( cls, body: dict ): + def from_dict(cls, body: dict): """ constructor to set data with dictionary @@ -94,17 +94,17 @@ def from_dict( cls, body: dict ): :return: new instance of serializable object """ obj = cls() - obj.deserialize( body ) + obj.deserialize(body) return obj - def serialize( self, include_type: bool = True, use_full_type: bool = True ) -> dict: + def serialize(self, include_type: bool = True, use_full_type: bool = True) -> dict: self._serialize_kwargs = { 'include_type': include_type, 'use_full_type': use_full_type } - body = self._schema().dump( self ) + body = self._schema().dump(self) if include_type: if use_full_type: body['_type'] = self.__class__.__module__ + '.' + self.__class__.__name__ @@ -112,11 +112,11 @@ def serialize( self, include_type: bool = True, use_full_type: bool = True ) -> body['_type'] = self.__class__.__name__ return body - def deserialize( self, body: dict ): - data = self._schema().load( body, unknown=marshmallow.EXCLUDE ) + def deserialize(self, body: dict): + data = self._schema().load(body, unknown=marshmallow.EXCLUDE) for name, attr in self._fields.items(): if attr._key not in body: continue if name not in data: continue - setattr( self, name, data[name] ) + setattr(self, name, data[name]) diff --git a/setup.py b/setup.py index 3b3cb84..b3f98c0 100644 --- a/setup.py +++ b/setup.py @@ -1,6 +1,6 @@ import setuptools -with open( 'README.md', 'r' ) as fh: +with open('README.md', 'r') as fh: long_description = fh.read() setuptools.setup( diff --git a/test/test_boolean.py b/test/test_boolean.py index aa6caba..9bf222f 100644 --- a/test/test_boolean.py +++ b/test/test_boolean.py @@ -10,12 +10,12 @@ from objectfactory import Serializable, Boolean -class TestBoolean( object ): +class TestBoolean(object): """ test case for boolean field type """ - def test_definition( self ): + def test_definition(self): """ test definition of class with boolean field @@ -23,30 +23,30 @@ def test_definition( self ): in schema creation """ - class MyTestClass( Serializable ): + class MyTestClass(Serializable): bool_prop = Boolean() - assert isinstance( MyTestClass._fields, dict ) - assert len( MyTestClass._fields ) == 1 + assert isinstance(MyTestClass._fields, dict) + assert len(MyTestClass._fields) == 1 assert 'bool_prop' in MyTestClass._fields - assert isinstance( MyTestClass._fields['bool_prop'], Boolean ) + assert isinstance(MyTestClass._fields['bool_prop'], Boolean) schema = MyTestClass._schema - assert issubclass( schema, marshmallow.Schema ) - assert len( schema._declared_fields ) == 1 + assert issubclass(schema, marshmallow.Schema) + assert len(schema._declared_fields) == 1 assert 'bool_prop' in schema._declared_fields prop = schema._declared_fields['bool_prop'] - assert isinstance( prop, marshmallow.fields.Boolean ) + assert isinstance(prop, marshmallow.fields.Boolean) - def test_serialize( self ): + def test_serialize(self): """ test serialize expect boolean data to be dumped to json body """ - class MyTestClass( Serializable ): + class MyTestClass(Serializable): bool_prop = Boolean() obj = MyTestClass() @@ -57,14 +57,14 @@ class MyTestClass( Serializable ): assert body['_type'] == 'test.test_boolean.MyTestClass' assert body['bool_prop'] == True - def test_deserialize( self ): + def test_deserialize(self): """ test deserialization expect boolean data to be loaded into class """ - class MyTestClass( Serializable ): + class MyTestClass(Serializable): bool_prop = Boolean() body = { @@ -73,20 +73,20 @@ class MyTestClass( Serializable ): } obj = MyTestClass() - obj.deserialize( body ) + obj.deserialize(body) - assert isinstance( obj, MyTestClass ) - assert type( obj.bool_prop ) == bool + assert isinstance(obj, MyTestClass) + assert type(obj.bool_prop) == bool assert obj.bool_prop == True - def test_deserialize_cast( self ): + def test_deserialize_cast(self): """ test deserialization casting expect int data to be cast to boolean """ - class MyTestClass( Serializable ): + class MyTestClass(Serializable): bool_prop = Boolean() body = { @@ -95,10 +95,10 @@ class MyTestClass( Serializable ): } obj = MyTestClass() - obj.deserialize( body ) + obj.deserialize(body) - assert isinstance( obj, MyTestClass ) - assert type( obj.bool_prop ) == bool + assert isinstance(obj, MyTestClass) + assert type(obj.bool_prop) == bool assert obj.bool_prop == True body = { @@ -107,13 +107,13 @@ class MyTestClass( Serializable ): } obj = MyTestClass() - obj.deserialize( body ) + obj.deserialize(body) - assert isinstance( obj, MyTestClass ) - assert type( obj.bool_prop ) == bool + assert isinstance(obj, MyTestClass) + assert type(obj.bool_prop) == bool assert obj.bool_prop == False - def test_deserialize_invalid_int( self ): + def test_deserialize_invalid_int(self): """ test deserialization validation @@ -121,7 +121,7 @@ def test_deserialize_invalid_int( self ): int not in [0, 1] """ - class MyTestClass( Serializable ): + class MyTestClass(Serializable): bool_prop = Boolean() body = { @@ -130,17 +130,17 @@ class MyTestClass( Serializable ): } obj = MyTestClass() - with pytest.raises( marshmallow.ValidationError ): - obj.deserialize( body ) + with pytest.raises(marshmallow.ValidationError): + obj.deserialize(body) - def test_deserialize_invalid_float( self ): + def test_deserialize_invalid_float(self): """ test deserialization validation expect validation error to be raised on invalid boolean data from float """ - class MyTestClass( Serializable ): + class MyTestClass(Serializable): bool_prop = Boolean() body = { @@ -149,17 +149,17 @@ class MyTestClass( Serializable ): } obj = MyTestClass() - with pytest.raises( marshmallow.ValidationError ): - obj.deserialize( body ) + with pytest.raises(marshmallow.ValidationError): + obj.deserialize(body) - def test_deserialize_invalid_string( self ): + def test_deserialize_invalid_string(self): """ test deserialization validation expect validation error to be raised on invalid boolean data from string """ - class MyTestClass( Serializable ): + class MyTestClass(Serializable): bool_prop = Boolean() body = { @@ -168,5 +168,5 @@ class MyTestClass( Serializable ): } obj = MyTestClass() - with pytest.raises( marshmallow.ValidationError ): - obj.deserialize( body ) + with pytest.raises(marshmallow.ValidationError): + obj.deserialize(body) diff --git a/test/test_custom_schema.py b/test/test_custom_schema.py index 8414fce..2932108 100644 --- a/test/test_custom_schema.py +++ b/test/test_custom_schema.py @@ -11,43 +11,43 @@ from objectfactory import Serializable, Field -class TestCustomSchema( object ): +class TestCustomSchema(object): """ test group for custom marshmallow serialization schema """ - def test_serialize( self ): + def test_serialize(self): """ test serialize expect date field to be serialized to a string (YYYY-MM-DD) """ - class CustomSchema( marshmallow.Schema ): + class CustomSchema(marshmallow.Schema): date = marshmallow.fields.Date() - class MyTestClass( Serializable, schema=CustomSchema ): + class MyTestClass(Serializable, schema=CustomSchema): date = Field() obj = MyTestClass() - obj.date = datetime.date( 2012, 3, 4 ) + obj.date = datetime.date(2012, 3, 4) body = obj.serialize() assert body['_type'] == 'test.test_custom_schema.MyTestClass' assert body['date'] == '2012-03-04' - def test_deserialize( self ): + def test_deserialize(self): """ test deserialize expect date field to be loaded from date string encoding (YYYY-MM-DD) """ - class CustomSchema( marshmallow.Schema ): + class CustomSchema(marshmallow.Schema): date = marshmallow.fields.Date() - class MyTestClass( Serializable, schema=CustomSchema ): + class MyTestClass(Serializable, schema=CustomSchema): date = Field() body = { @@ -56,24 +56,24 @@ class MyTestClass( Serializable, schema=CustomSchema ): } obj = MyTestClass() - obj.deserialize( body ) + obj.deserialize(body) - assert isinstance( obj, MyTestClass ) + assert isinstance(obj, MyTestClass) assert obj.date.year == 2012 assert obj.date.month == 3 assert obj.date.day == 4 - def test_deserialize_invalid( self ): + def test_deserialize_invalid(self): """ test deserialize expect exception to be thrown on invalid date string """ - class CustomSchema( marshmallow.Schema ): + class CustomSchema(marshmallow.Schema): date = marshmallow.fields.Date() - class MyTestClass( Serializable, schema=CustomSchema ): + class MyTestClass(Serializable, schema=CustomSchema): date = Field() body = { @@ -82,30 +82,30 @@ class MyTestClass( Serializable, schema=CustomSchema ): } obj = MyTestClass() - with pytest.raises( marshmallow.exceptions.ValidationError ): - obj.deserialize( body ) + with pytest.raises(marshmallow.exceptions.ValidationError): + obj.deserialize(body) -class TestCustomField( object ): +class TestCustomField(object): """ test group for custom marshmallow field """ - def test_serialize( self ): + def test_serialize(self): """ test serialize expect property to be serialized to a lowercase string """ - class CustomField( marshmallow.fields.Field ): - def _serialize( self, value, *args, **kwargs ): - return str( value ).lower() + class CustomField(marshmallow.fields.Field): + def _serialize(self, value, *args, **kwargs): + return str(value).lower() - class CustomSchema( marshmallow.Schema ): + class CustomSchema(marshmallow.Schema): str_prop = CustomField() - class MyTestClass( Serializable, schema=CustomSchema ): + class MyTestClass(Serializable, schema=CustomSchema): str_prop = Field() obj = MyTestClass() @@ -116,23 +116,23 @@ class MyTestClass( Serializable, schema=CustomSchema ): assert body['_type'] == 'test.test_custom_schema.MyTestClass' assert body['str_prop'] == 'hello' - def test_deserialize( self ): + def test_deserialize(self): """ test deserialize expect string to be loaded and formatted as all uppercase """ - class CustomField( marshmallow.fields.Field ): - def _deserialize( self, value, *args, **kwargs ): - if len( value ) > 8: - raise marshmallow.ValidationError( 'Field too long' ) - return str( value ).upper() + class CustomField(marshmallow.fields.Field): + def _deserialize(self, value, *args, **kwargs): + if len(value) > 8: + raise marshmallow.ValidationError('Field too long') + return str(value).upper() - class CustomSchema( marshmallow.Schema ): + class CustomSchema(marshmallow.Schema): str_prop = CustomField() - class MyTestClass( Serializable, schema=CustomSchema ): + class MyTestClass(Serializable, schema=CustomSchema): str_prop = Field() body = { @@ -141,28 +141,28 @@ class MyTestClass( Serializable, schema=CustomSchema ): } obj = MyTestClass() - obj.deserialize( body ) + obj.deserialize(body) - assert isinstance( obj, MyTestClass ) + assert isinstance(obj, MyTestClass) assert obj.str_prop == 'HELLO' - def test_deserialize_invalid( self ): + def test_deserialize_invalid(self): """ test deserialize expect exception to be thrown on too long of a string """ - class CustomField( marshmallow.fields.Field ): - def _deserialize( self, value, *args, **kwargs ): - if len( value ) > 8: - raise marshmallow.ValidationError( 'Field too long' ) - return str( value ).upper() + class CustomField(marshmallow.fields.Field): + def _deserialize(self, value, *args, **kwargs): + if len(value) > 8: + raise marshmallow.ValidationError('Field too long') + return str(value).upper() - class CustomSchema( marshmallow.Schema ): + class CustomSchema(marshmallow.Schema): str_prop = CustomField() - class MyTestClass( Serializable, schema=CustomSchema ): + class MyTestClass(Serializable, schema=CustomSchema): str_prop = Field() body = { @@ -171,5 +171,5 @@ class MyTestClass( Serializable, schema=CustomSchema ): } obj = MyTestClass() - with pytest.raises( marshmallow.exceptions.ValidationError ): - obj.deserialize( body ) + with pytest.raises(marshmallow.exceptions.ValidationError): + obj.deserialize(body) diff --git a/test/test_factory.py b/test/test_factory.py index 24549bd..1d72967 100644 --- a/test/test_factory.py +++ b/test/test_factory.py @@ -11,12 +11,12 @@ from .testmodule.testclasses import MyBasicClass, MyComplexClass -class TestFactory( object ): +class TestFactory(object): """ test case for serializable factory """ - def test_register_class( self ): + def test_register_class(self): """ validate register_class method @@ -25,7 +25,7 @@ def test_register_class( self ): assert 'MyBasicClass' in _global_factory.registry assert 'test.testmodule.testclasses.MyBasicClass' in _global_factory.registry - def test_create_object( self ): + def test_create_object(self): """ validate create object method @@ -36,13 +36,13 @@ def test_create_object( self ): 'str_prop': 'somestring', 'int_prop': 42, } - obj = objectfactory.create( body ) + obj = objectfactory.create(body) - assert isinstance( obj, MyBasicClass ) + assert isinstance(obj, MyBasicClass) assert obj.str_prop == 'somestring' assert obj.int_prop == 42 - def test_create_object_short_type( self ): + def test_create_object_short_type(self): """ validate create object method without fully qualified path @@ -53,13 +53,13 @@ def test_create_object_short_type( self ): 'str_prop': 'somestring', 'int_prop': 42, } - obj = objectfactory.create( body ) + obj = objectfactory.create(body) - assert isinstance( obj, MyBasicClass ) + assert isinstance(obj, MyBasicClass) assert obj.str_prop == 'somestring' assert obj.int_prop == 42 - def test_create_object_other_full_path( self ): + def test_create_object_other_full_path(self): """ validate create object method when full path is altered @@ -70,13 +70,13 @@ def test_create_object_other_full_path( self ): 'str_prop': 'somestring', 'int_prop': 42, } - obj = objectfactory.create( body ) + obj = objectfactory.create(body) - assert isinstance( obj, MyBasicClass ) + assert isinstance(obj, MyBasicClass) assert obj.str_prop == 'somestring' assert obj.int_prop == 42 - def test_create_object_unregistered( self ): + def test_create_object_unregistered(self): """ validate create object method throws when unregistered @@ -87,10 +87,10 @@ def test_create_object_unregistered( self ): 'str_prop': 'somestring', 'int_prop': 42, } - with pytest.raises( ValueError, match=r'.*type MyClassThatDoesNotExist not found.*' ): - _ = objectfactory.create( body ) + with pytest.raises(ValueError, match=r'.*type MyClassThatDoesNotExist not found.*'): + _ = objectfactory.create(body) - def test_create_object_typed( self ): + def test_create_object_typed(self): """ validate create object method when enforcing type @@ -101,13 +101,13 @@ def test_create_object_typed( self ): 'str_prop': 'somestring', 'int_prop': 42, } - obj = objectfactory.create( body, object_type=MyBasicClass ) + obj = objectfactory.create(body, object_type=MyBasicClass) - assert isinstance( obj, MyBasicClass ) + assert isinstance(obj, MyBasicClass) assert obj.str_prop == 'somestring' assert obj.int_prop == 42 - def test_create_object_typed_invalid( self ): + def test_create_object_typed_invalid(self): """ validate create object method throws when type mismatch @@ -122,4 +122,4 @@ def test_create_object_typed_invalid( self ): TypeError, match=r'.*Object type MyBasicClass is not a MyComplexClass.*' ): - _ = objectfactory.create( body, object_type=MyComplexClass ) + _ = objectfactory.create(body, object_type=MyComplexClass) diff --git a/test/test_fields.py b/test/test_fields.py index 62c9f89..2833c2b 100644 --- a/test/test_fields.py +++ b/test/test_fields.py @@ -10,20 +10,20 @@ from objectfactory import Serializable, Field -class TestFieldOptionals( object ): +class TestFieldOptionals(object): """ test case for optional params to field arguments """ - def test_serialize_default( self ): + def test_serialize_default(self): """ test serialization expect default value to be serialized for unset str_prop """ - class MyTestClass( Serializable ): - str_prop = Field( default='default_val' ) + class MyTestClass(Serializable): + str_prop = Field(default='default_val') obj = MyTestClass() @@ -34,7 +34,7 @@ class MyTestClass( Serializable ): assert body['_type'] == 'test.test_fields.MyTestClass' assert body['str_prop'] == 'default_val' - def test_deserialize_default( self ): + def test_deserialize_default(self): """ test deserialization @@ -42,28 +42,28 @@ def test_deserialize_default( self ): int_prop_named to be deserialized into int_prop """ - class MyTestClass( Serializable ): - str_prop = Field( default='default_val' ) + class MyTestClass(Serializable): + str_prop = Field(default='default_val') body = { '_type': 'MyTestClass' } obj = MyTestClass() - obj.deserialize( body ) + obj.deserialize(body) - assert isinstance( obj, MyTestClass ) + assert isinstance(obj, MyTestClass) assert obj.str_prop == 'default_val' - def test_serialize_keyed( self ): + def test_serialize_keyed(self): """ test serialization expect int_prop to be serialized under key int_prop_named """ - class MyTestClass( Serializable ): - int_prop = Field( key='int_prop_named' ) + class MyTestClass(Serializable): + int_prop = Field(key='int_prop_named') obj = MyTestClass() obj.int_prop = 99 @@ -73,15 +73,15 @@ class MyTestClass( Serializable ): assert body['_type'] == 'test.test_fields.MyTestClass' assert body['int_prop_named'] == 99 - def test_deserialize_keyed( self ): + def test_deserialize_keyed(self): """ test deserialization expect int_prop_named to be deserialized into int_prop """ - class MyTestClass( Serializable ): - int_prop = Field( key='int_prop_named' ) + class MyTestClass(Serializable): + int_prop = Field(key='int_prop_named') body = { '_type': 'MyTestClass', @@ -89,20 +89,20 @@ class MyTestClass( Serializable ): } obj = MyTestClass() - obj.deserialize( body ) + obj.deserialize(body) - assert isinstance( obj, MyTestClass ) + assert isinstance(obj, MyTestClass) assert obj.int_prop == 99 - def test_deserialize_required( self ): + def test_deserialize_required(self): """ test deserialization of required field expect required property to be deserialized into prop """ - class MyTestClass( Serializable ): - prop = Field( required=True ) + class MyTestClass(Serializable): + prop = Field(required=True) body = { '_type': 'MyTestClass', @@ -110,37 +110,37 @@ class MyTestClass( Serializable ): } obj = MyTestClass() - obj.deserialize( body ) + obj.deserialize(body) - assert isinstance( obj, MyTestClass ) + assert isinstance(obj, MyTestClass) assert obj.prop == 42 - def test_deserialize_required_missing( self ): + def test_deserialize_required_missing(self): """ test deserialization of required field expect exception to be thrown on missing prop field """ - class MyTestClass( Serializable ): - prop = Field( required=True ) + class MyTestClass(Serializable): + prop = Field(required=True) body = { '_type': 'MyTestClass' } obj = MyTestClass() - with pytest.raises( marshmallow.exceptions.ValidationError ): - obj.deserialize( body ) + with pytest.raises(marshmallow.exceptions.ValidationError): + obj.deserialize(body) - def test_deserialize_null( self ): + def test_deserialize_null(self): """ test deserialization validation expect null to be deserialized to None """ - class MyTestClass( Serializable ): + class MyTestClass(Serializable): prop = Field() body = { @@ -149,20 +149,20 @@ class MyTestClass( Serializable ): } obj = MyTestClass() - obj.deserialize( body ) + obj.deserialize(body) - assert isinstance( obj, MyTestClass ) + assert isinstance(obj, MyTestClass) assert obj.prop is None - def test_deserialize_null_disallowed( self ): + def test_deserialize_null_disallowed(self): """ test deserialization validation expect exception to be thrown when null value is not allowed """ - class MyTestClass( Serializable ): - prop = Field( allow_none=False ) + class MyTestClass(Serializable): + prop = Field(allow_none=False) body = { '_type': 'MyTestClass', @@ -170,5 +170,5 @@ class MyTestClass( Serializable ): } obj = MyTestClass() - with pytest.raises( marshmallow.exceptions.ValidationError ): - obj.deserialize( body ) + with pytest.raises(marshmallow.exceptions.ValidationError): + obj.deserialize(body) diff --git a/test/test_float.py b/test/test_float.py index 447b49c..9653bcb 100644 --- a/test/test_float.py +++ b/test/test_float.py @@ -10,12 +10,12 @@ from objectfactory import Serializable, Float -class TestFloat( object ): +class TestFloat(object): """ test case for float field type """ - def test_definition( self ): + def test_definition(self): """ test definition of class with float field @@ -23,30 +23,30 @@ def test_definition( self ): in schema creation """ - class MyTestClass( Serializable ): + class MyTestClass(Serializable): float_prop = Float() - assert isinstance( MyTestClass._fields, dict ) - assert len( MyTestClass._fields ) == 1 + assert isinstance(MyTestClass._fields, dict) + assert len(MyTestClass._fields) == 1 assert 'float_prop' in MyTestClass._fields - assert isinstance( MyTestClass._fields['float_prop'], Float ) + assert isinstance(MyTestClass._fields['float_prop'], Float) schema = MyTestClass._schema - assert issubclass( schema, marshmallow.Schema ) - assert len( schema._declared_fields ) == 1 + assert issubclass(schema, marshmallow.Schema) + assert len(schema._declared_fields) == 1 assert 'float_prop' in schema._declared_fields prop = schema._declared_fields['float_prop'] - assert isinstance( prop, marshmallow.fields.Float ) + assert isinstance(prop, marshmallow.fields.Float) - def test_serialize( self ): + def test_serialize(self): """ test serialize expect float data to be dumped to json body """ - class MyTestClass( Serializable ): + class MyTestClass(Serializable): float_prop = Float() obj = MyTestClass() @@ -57,14 +57,14 @@ class MyTestClass( Serializable ): assert body['_type'] == 'test.test_float.MyTestClass' assert body['float_prop'] == 99.99 - def test_deserialize( self ): + def test_deserialize(self): """ test deserialization expect float data to be loaded into class """ - class MyTestClass( Serializable ): + class MyTestClass(Serializable): float_prop = Float() body = { @@ -73,20 +73,20 @@ class MyTestClass( Serializable ): } obj = MyTestClass() - obj.deserialize( body ) + obj.deserialize(body) - assert isinstance( obj, MyTestClass ) - assert type( obj.float_prop ) == float + assert isinstance(obj, MyTestClass) + assert type(obj.float_prop) == float assert obj.float_prop == 99.99 - def test_deserialize_cast( self ): + def test_deserialize_cast(self): """ test deserialization casting expect int data to be cast to float """ - class MyTestClass( Serializable ): + class MyTestClass(Serializable): float_prop = Float() body = { @@ -95,20 +95,20 @@ class MyTestClass( Serializable ): } obj = MyTestClass() - obj.deserialize( body ) + obj.deserialize(body) - assert isinstance( obj, MyTestClass ) - assert type( obj.float_prop ) == float + assert isinstance(obj, MyTestClass) + assert type(obj.float_prop) == float assert obj.float_prop == 99.0 - def test_deserialize_invalid( self ): + def test_deserialize_invalid(self): """ test deserialization validation expect validation error to be raised on invalid float data """ - class MyTestClass( Serializable ): + class MyTestClass(Serializable): float_prop = Float() body = { @@ -117,5 +117,5 @@ class MyTestClass( Serializable ): } obj = MyTestClass() - with pytest.raises( marshmallow.ValidationError ): - obj.deserialize( body ) + with pytest.raises(marshmallow.ValidationError): + obj.deserialize(body) diff --git a/test/test_integer.py b/test/test_integer.py index 2c8b72f..f9b119c 100644 --- a/test/test_integer.py +++ b/test/test_integer.py @@ -10,12 +10,12 @@ from objectfactory import Serializable, Integer -class TestInteger( object ): +class TestInteger(object): """ test case for integer field type """ - def test_definition( self ): + def test_definition(self): """ test definition of class with integer field @@ -23,30 +23,30 @@ def test_definition( self ): in schema creation """ - class MyTestClass( Serializable ): + class MyTestClass(Serializable): int_prop = Integer() - assert isinstance( MyTestClass._fields, dict ) - assert len( MyTestClass._fields ) == 1 + assert isinstance(MyTestClass._fields, dict) + assert len(MyTestClass._fields) == 1 assert 'int_prop' in MyTestClass._fields - assert isinstance( MyTestClass._fields['int_prop'], Integer ) + assert isinstance(MyTestClass._fields['int_prop'], Integer) schema = MyTestClass._schema - assert issubclass( schema, marshmallow.Schema ) - assert len( schema._declared_fields ) == 1 + assert issubclass(schema, marshmallow.Schema) + assert len(schema._declared_fields) == 1 assert 'int_prop' in schema._declared_fields prop = schema._declared_fields['int_prop'] - assert isinstance( prop, marshmallow.fields.Integer ) + assert isinstance(prop, marshmallow.fields.Integer) - def test_serialize( self ): + def test_serialize(self): """ test serialize expect integer data to be dumped to json body """ - class MyTestClass( Serializable ): + class MyTestClass(Serializable): int_prop = Integer() obj = MyTestClass() @@ -57,14 +57,14 @@ class MyTestClass( Serializable ): assert body['_type'] == 'test.test_integer.MyTestClass' assert body['int_prop'] == 99 - def test_deserialize( self ): + def test_deserialize(self): """ test deserialization expect integer data to be loaded into class """ - class MyTestClass( Serializable ): + class MyTestClass(Serializable): int_prop = Integer() body = { @@ -73,19 +73,19 @@ class MyTestClass( Serializable ): } obj = MyTestClass() - obj.deserialize( body ) + obj.deserialize(body) - assert isinstance( obj, MyTestClass ) + assert isinstance(obj, MyTestClass) assert obj.int_prop == 99 - def test_deserialize_cast( self ): + def test_deserialize_cast(self): """ test deserialization casting expect float data to be cast to integer """ - class MyTestClass( Serializable ): + class MyTestClass(Serializable): int_prop = Integer() body = { @@ -94,20 +94,20 @@ class MyTestClass( Serializable ): } obj = MyTestClass() - obj.deserialize( body ) + obj.deserialize(body) - assert isinstance( obj, MyTestClass ) - assert type( obj.int_prop ) == int + assert isinstance(obj, MyTestClass) + assert type(obj.int_prop) == int assert obj.int_prop == 99 - def test_deserialize_invalid( self ): + def test_deserialize_invalid(self): """ test deserialization validation expect validation error to be raised on invalid integer data """ - class MyTestClass( Serializable ): + class MyTestClass(Serializable): int_prop = Integer() body = { @@ -116,5 +116,5 @@ class MyTestClass( Serializable ): } obj = MyTestClass() - with pytest.raises( marshmallow.ValidationError ): - obj.deserialize( body ) + with pytest.raises(marshmallow.ValidationError): + obj.deserialize(body) diff --git a/test/test_list.py b/test/test_list.py index 4db7607..f3e117a 100644 --- a/test/test_list.py +++ b/test/test_list.py @@ -11,12 +11,12 @@ from objectfactory import Serializable, List, String, Integer, register -class TestPrimitiveList( object ): +class TestPrimitiveList(object): """ test case for serialization of basic lists of primitive strings and integers """ - def test_serialize( self ): + def test_serialize(self): """ test serialization @@ -24,22 +24,22 @@ def test_serialize( self ): and to dump up-to-date list of all primitive values """ - class MyTestClass( Serializable ): - str_list_prop = List( field_type=String ) - int_list_prop = List( field_type=Integer ) + class MyTestClass(Serializable): + str_list_prop = List(field_type=String) + int_list_prop = List(field_type=Integer) obj = MyTestClass() obj.str_list_prop = ['hello', 'world'] obj.int_list_prop = [0, 1, 2, 3, 4] - obj.str_list_prop.append( '!' ) - obj.int_list_prop.append( 5 ) + obj.str_list_prop.append('!') + obj.int_list_prop.append(5) body = obj.serialize() assert body['_type'] == 'test.test_list.MyTestClass' assert body['str_list_prop'] == ['hello', 'world', '!'] assert body['int_list_prop'] == [0, 1, 2, 3, 4, 5] - def test_deserialize( self ): + def test_deserialize(self): """ test deserialization @@ -47,9 +47,9 @@ def test_deserialize( self ): serializable object """ - class MyTestClass( Serializable ): - str_list_prop = List( field_type=String ) - int_list_prop = List( field_type=Integer ) + class MyTestClass(Serializable): + str_list_prop = List(field_type=String) + int_list_prop = List(field_type=Integer) body = { '_type': 'MyTestClass', @@ -58,22 +58,22 @@ class MyTestClass( Serializable ): } obj = MyTestClass() - obj.deserialize( body ) + obj.deserialize(body) - assert isinstance( obj, MyTestClass ) + assert isinstance(obj, MyTestClass) assert obj.str_list_prop == ['my', 'awesome', 'list', 'of', 'strings'] assert obj.int_list_prop == [9001, 9002, 9003] - def test_deserialize_invalid( self ): + def test_deserialize_invalid(self): """ test deserialization validation expect validation error to be raised on invalid integer data """ - class MyTestClass( Serializable ): - str_list_prop = List( field_type=String ) - int_list_prop = List( field_type=Integer ) + class MyTestClass(Serializable): + str_list_prop = List(field_type=String) + int_list_prop = List(field_type=Integer) body = { '_type': 'MyTestClass', @@ -83,10 +83,10 @@ class MyTestClass( Serializable ): obj = MyTestClass() - with pytest.raises( marshmallow.ValidationError ): - obj.deserialize( body ) + with pytest.raises(marshmallow.ValidationError): + obj.deserialize(body) - def test_serialize_deep_copy( self ): + def test_serialize_deep_copy(self): """ test serialization @@ -94,23 +94,23 @@ def test_serialize_deep_copy( self ): serialized json body """ - class MyTestClass( Serializable ): - str_list_prop = List( field_type=String ) - int_list_prop = List( field_type=Integer ) + class MyTestClass(Serializable): + str_list_prop = List(field_type=String) + int_list_prop = List(field_type=Integer) obj = MyTestClass() obj.str_list_prop = ['hello', 'world'] obj.int_list_prop = [0, 1, 2, 3, 4] body = obj.serialize() - obj.str_list_prop.append( '!' ) - obj.int_list_prop.append( 5 ) + obj.str_list_prop.append('!') + obj.int_list_prop.append(5) assert body['_type'] == 'test.test_list.MyTestClass' assert body['str_list_prop'] == ['hello', 'world'] assert body['int_list_prop'] == [0, 1, 2, 3, 4] - def test_deserialize_deep_copy( self ): + def test_deserialize_deep_copy(self): """ test deserialization @@ -118,9 +118,9 @@ def test_deserialize_deep_copy( self ): have not effect on loaded serializable object """ - class MyTestClass( Serializable ): - str_list_prop = List( field_type=String ) - int_list_prop = List( field_type=Integer ) + class MyTestClass(Serializable): + str_list_prop = List(field_type=String) + int_list_prop = List(field_type=Integer) body = { '_type': 'MyTestClass', @@ -129,28 +129,28 @@ class MyTestClass( Serializable ): } obj = MyTestClass() - obj.deserialize( body ) + obj.deserialize(body) body['str_list_prop'].pop() body['int_list_prop'].pop() - assert isinstance( obj, MyTestClass ) + assert isinstance(obj, MyTestClass) assert obj.str_list_prop == ['my', 'awesome', 'list', 'of', 'strings'] assert obj.int_list_prop == [9001, 9002, 9003] -class TestNestedList( object ): +class TestNestedList(object): """ test case for model containing a list of nested serializable objects """ - def setup_method( self, _ ): + def setup_method(self, _): """ prepare for each test """ objectfactory.factory._global_factory.registry.clear() - def test_serializable( self ): + def test_serializable(self): """ test serialization @@ -159,11 +159,11 @@ def test_serializable( self ): """ @register - class MyNestedClass( Serializable ): + class MyNestedClass(Serializable): str_prop = String() int_prop = Integer() - class MyTestClass( Serializable ): + class MyTestClass(Serializable): str_prop = String() nested_list_prop = List() @@ -174,23 +174,23 @@ class MyTestClass( Serializable ): nested_strings = ['some string', 'another string', 'one more string'] nested_ints = [101, 102, 103] - for s, n in zip( nested_strings, nested_ints ): + for s, n in zip(nested_strings, nested_ints): temp = MyNestedClass() temp.str_prop = s temp.int_prop = n - obj.nested_list_prop.append( temp ) + obj.nested_list_prop.append(temp) body = obj.serialize() assert body['_type'] == 'test.test_list.MyTestClass' assert body['str_prop'] == 'object name' - assert len( body['nested_list_prop'] ) == 3 - for i, nested_body in enumerate( body['nested_list_prop'] ): + assert len(body['nested_list_prop']) == 3 + for i, nested_body in enumerate(body['nested_list_prop']): assert nested_body['_type'] == 'test.test_list.MyNestedClass' assert nested_body['str_prop'] == nested_strings[i] assert nested_body['int_prop'] == nested_ints[i] - def test_deserialize( self ): + def test_deserialize(self): """ test deserialization @@ -199,11 +199,11 @@ def test_deserialize( self ): """ @register - class MyNestedClass( Serializable ): + class MyNestedClass(Serializable): str_prop = String() int_prop = Integer() - class MyTestClass( Serializable ): + class MyTestClass(Serializable): str_prop = String() nested_list_prop = List() @@ -215,7 +215,7 @@ class MyTestClass( Serializable ): nested_strings = ['some string', 'another string', 'one more string'] nested_ints = [101, 102, 103] - for s, n in zip( nested_strings, nested_ints ): + for s, n in zip(nested_strings, nested_ints): body['nested_list_prop'].append( { '_type': 'MyNestedClass', @@ -225,17 +225,17 @@ class MyTestClass( Serializable ): ) obj = MyTestClass() - obj.deserialize( body ) + obj.deserialize(body) - assert isinstance( obj, MyTestClass ) + assert isinstance(obj, MyTestClass) assert obj.str_prop == 'really great string property' - assert len( obj.nested_list_prop ) == 3 - for i, nested_obj in enumerate( obj.nested_list_prop ): - assert isinstance( nested_obj, MyNestedClass ) + assert len(obj.nested_list_prop) == 3 + for i, nested_obj in enumerate(obj.nested_list_prop): + assert isinstance(nested_obj, MyNestedClass) assert nested_obj.str_prop == nested_strings[i] assert nested_obj.int_prop == nested_ints[i] - def test_deserialize_typed( self ): + def test_deserialize_typed(self): """ test deserialization without _type field @@ -245,13 +245,13 @@ def test_deserialize_typed( self ): """ @register - class MyNestedClass( Serializable ): + class MyNestedClass(Serializable): str_prop = String() int_prop = Integer() - class MyTestClass( Serializable ): + class MyTestClass(Serializable): str_prop = String() - nested_list_prop = List( field_type=MyNestedClass ) + nested_list_prop = List(field_type=MyNestedClass) body = { '_type': 'MyTestClass', @@ -261,7 +261,7 @@ class MyTestClass( Serializable ): nested_strings = ['some string', 'another string', 'one more string'] nested_ints = [101, 102, 103] - for s, n in zip( nested_strings, nested_ints ): + for s, n in zip(nested_strings, nested_ints): body['nested_list_prop'].append( { 'str_prop': s, @@ -270,17 +270,17 @@ class MyTestClass( Serializable ): ) obj = MyTestClass() - obj.deserialize( body ) + obj.deserialize(body) - assert isinstance( obj, MyTestClass ) + assert isinstance(obj, MyTestClass) assert obj.str_prop == 'really great string property' - assert len( obj.nested_list_prop ) == 3 - for i, nested_obj in enumerate( obj.nested_list_prop ): - assert isinstance( nested_obj, MyNestedClass ) + assert len(obj.nested_list_prop) == 3 + for i, nested_obj in enumerate(obj.nested_list_prop): + assert isinstance(nested_obj, MyNestedClass) assert nested_obj.str_prop == nested_strings[i] assert nested_obj.int_prop == nested_ints[i] - def test_deserialize_typed_invalid( self ): + def test_deserialize_typed_invalid(self): """ test deserialization validation @@ -288,16 +288,16 @@ def test_deserialize_typed_invalid( self ): """ @register - class MyNestedClass( Serializable ): + class MyNestedClass(Serializable): str_prop = String() @register - class OtherClass( Serializable ): + class OtherClass(Serializable): str_prop = String() - class MyTestClass( Serializable ): + class MyTestClass(Serializable): str_prop = String() - nested_list_prop = List( field_type=MyNestedClass ) + nested_list_prop = List(field_type=MyNestedClass) body = { '_type': 'MyTestClass', @@ -311,10 +311,10 @@ class MyTestClass( Serializable ): obj = MyTestClass() - with pytest.raises( ValueError ): - obj.deserialize( body ) + with pytest.raises(ValueError): + obj.deserialize(body) - def test_default_unique( self ): + def test_default_unique(self): """ test default nested list field is unique between instances @@ -323,31 +323,31 @@ def test_default_unique( self ): """ @register - class MyNestedClass( Serializable ): + class MyNestedClass(Serializable): str_prop = String() int_prop = Integer() - class MyTestClass( Serializable ): + class MyTestClass(Serializable): str_prop = Integer() nested_list_prop = List() obj_a = MyTestClass() obj_b = MyTestClass() - assert len( obj_a.nested_list_prop ) == 0 - assert len( obj_b.nested_list_prop ) == 0 + assert len(obj_a.nested_list_prop) == 0 + assert len(obj_b.nested_list_prop) == 0 - obj_a.nested_list_prop.append( MyNestedClass.from_kwargs( str_prop='x' ) ) + obj_a.nested_list_prop.append(MyNestedClass.from_kwargs(str_prop='x')) - assert len( obj_a.nested_list_prop ) == 1 + assert len(obj_a.nested_list_prop) == 1 assert obj_a.nested_list_prop[0].str_prop == 'x' - assert len( obj_b.nested_list_prop ) == 0 + assert len(obj_b.nested_list_prop) == 0 - obj_a.nested_list_prop.append( MyNestedClass.from_kwargs( str_prop='y' ) ) - obj_b.nested_list_prop.append( MyNestedClass.from_kwargs( str_prop='z' ) ) + obj_a.nested_list_prop.append(MyNestedClass.from_kwargs(str_prop='y')) + obj_b.nested_list_prop.append(MyNestedClass.from_kwargs(str_prop='z')) - assert len( obj_a.nested_list_prop ) == 2 + assert len(obj_a.nested_list_prop) == 2 assert obj_a.nested_list_prop[0].str_prop == 'x' assert obj_a.nested_list_prop[1].str_prop == 'y' - assert len( obj_b.nested_list_prop ) == 1 + assert len(obj_b.nested_list_prop) == 1 assert obj_b.nested_list_prop[0].str_prop == 'z' diff --git a/test/test_nested.py b/test/test_nested.py index 76df863..9b135a4 100644 --- a/test/test_nested.py +++ b/test/test_nested.py @@ -12,18 +12,18 @@ from objectfactory.nested import NestedFactoryField -class TestNested( object ): +class TestNested(object): """ test case for nested object field type """ - def setup_method( self, _ ): + def setup_method(self, _): """ prepare for each test """ objectfactory.factory._global_factory.registry.clear() - def test_definition( self ): + def test_definition(self): """ test definition of class with nested field @@ -31,33 +31,33 @@ def test_definition( self ): in schema creation """ - class MyTestClass( Serializable ): + class MyTestClass(Serializable): nested = Nested() - assert isinstance( MyTestClass._fields, dict ) - assert len( MyTestClass._fields ) == 1 + assert isinstance(MyTestClass._fields, dict) + assert len(MyTestClass._fields) == 1 assert 'nested' in MyTestClass._fields - assert isinstance( MyTestClass._fields['nested'], Nested ) + assert isinstance(MyTestClass._fields['nested'], Nested) schema = MyTestClass._schema - assert issubclass( schema, marshmallow.Schema ) - assert len( schema._declared_fields ) == 1 + assert issubclass(schema, marshmallow.Schema) + assert len(schema._declared_fields) == 1 assert 'nested' in schema._declared_fields prop = schema._declared_fields['nested'] - assert isinstance( prop, NestedFactoryField ) + assert isinstance(prop, NestedFactoryField) - def test_serialize( self ): + def test_serialize(self): """ test serialize expect nested object to be dumped to nested dict in json body """ - class MyNestedClass( Serializable ): + class MyNestedClass(Serializable): str_prop = String() - class MyTestClass( Serializable ): + class MyTestClass(Serializable): nested = Nested() obj = MyTestClass() @@ -67,11 +67,11 @@ class MyTestClass( Serializable ): body = obj.serialize() assert body['_type'] == 'test.test_nested.MyTestClass' - assert isinstance( body['nested'], dict ) + assert isinstance(body['nested'], dict) assert body['nested']['_type'] == 'test.test_nested.MyNestedClass' assert body['nested']['str_prop'] == 'some string' - def test_deserialize( self ): + def test_deserialize(self): """ test deserialization @@ -79,10 +79,10 @@ def test_deserialize( self ): """ @register - class MyNestedClass( Serializable ): + class MyNestedClass(Serializable): str_prop = String() - class MyTestClass( Serializable ): + class MyTestClass(Serializable): nested = Nested() body = { @@ -94,13 +94,13 @@ class MyTestClass( Serializable ): } obj = MyTestClass() - obj.deserialize( body ) + obj.deserialize(body) - assert isinstance( obj, MyTestClass ) - assert isinstance( obj.nested, MyNestedClass ) + assert isinstance(obj, MyTestClass) + assert isinstance(obj.nested, MyNestedClass) assert obj.nested.str_prop == 'some string' - def test_deserialize_typed( self ): + def test_deserialize_typed(self): """ test deserialization with typed nested field @@ -108,11 +108,11 @@ def test_deserialize_typed( self ): on specified field type, despite lack of type info or registration """ - class MyNestedClass( Serializable ): + class MyNestedClass(Serializable): str_prop = String() - class MyTestClass( Serializable ): - nested = Nested( field_type=MyNestedClass ) + class MyTestClass(Serializable): + nested = Nested(field_type=MyNestedClass) body = { '_type': 'MyTestClass', @@ -122,13 +122,13 @@ class MyTestClass( Serializable ): } obj = MyTestClass() - obj.deserialize( body ) + obj.deserialize(body) - assert isinstance( obj, MyTestClass ) - assert isinstance( obj.nested, MyNestedClass ) + assert isinstance(obj, MyTestClass) + assert isinstance(obj.nested, MyNestedClass) assert obj.nested.str_prop == 'some string' - def test_deserialize_enforce_typed( self ): + def test_deserialize_enforce_typed(self): """ test deserialization enforcing field type @@ -137,15 +137,15 @@ def test_deserialize_enforce_typed( self ): """ @register - class MyNestedClass( Serializable ): + class MyNestedClass(Serializable): str_prop = String() @register - class OtherClass( Serializable ): + class OtherClass(Serializable): str_prop = String() - class MyTestClass( Serializable ): - nested = Nested( field_type=MyNestedClass ) + class MyTestClass(Serializable): + nested = Nested(field_type=MyNestedClass) body = { '_type': 'MyTestClass', @@ -156,5 +156,5 @@ class MyTestClass( Serializable ): } obj = MyTestClass() - with pytest.raises( ValueError ): - obj.deserialize( body ) + with pytest.raises(ValueError): + obj.deserialize(body) diff --git a/test/test_serializable.py b/test/test_serializable.py index 428092c..74df8f5 100644 --- a/test/test_serializable.py +++ b/test/test_serializable.py @@ -10,12 +10,12 @@ from .testmodule.testclasses import MyBasicClass, MySubClass -class TestClassDefinition( object ): +class TestClassDefinition(object): """ test group for definition of serializable object """ - def test_fields_collected( self ): + def test_fields_collected(self): """ test collection of field descriptors @@ -23,45 +23,45 @@ def test_fields_collected( self ): and indexed under the _fields parameter """ - class MyClass( Serializable ): + class MyClass(Serializable): some_field = Field() another_field = Field() not_a_field = 'some class attribute' - assert isinstance( MyClass._fields, dict ) - assert len( MyClass._fields ) == 2 + assert isinstance(MyClass._fields, dict) + assert len(MyClass._fields) == 2 assert 'some_field' in MyClass._fields - assert isinstance( MyClass._fields['some_field'], Field ) + assert isinstance(MyClass._fields['some_field'], Field) assert 'another_field' in MyClass._fields - assert isinstance( MyClass._fields['another_field'], Field ) + assert isinstance(MyClass._fields['another_field'], Field) assert 'not_a_field' not in MyClass._fields - def test_schema_creation( self ): + def test_schema_creation(self): """ test creation of marshmallow schema expect schema to contain each field defined in serializable class """ - class MyClass( Serializable ): + class MyClass(Serializable): some_field = Field() another_field = Field() schema = MyClass._schema - assert issubclass( schema, marshmallow.Schema ) - assert len( schema._declared_fields ) == 2 + assert issubclass(schema, marshmallow.Schema) + assert len(schema._declared_fields) == 2 assert 'some_field' in schema._declared_fields - assert isinstance( schema._declared_fields['some_field'], marshmallow.fields.Field ) + assert isinstance(schema._declared_fields['some_field'], marshmallow.fields.Field) assert 'another_field' in schema._declared_fields - assert isinstance( schema._declared_fields['another_field'], marshmallow.fields.Field ) + assert isinstance(schema._declared_fields['another_field'], marshmallow.fields.Field) -class TestSerializableObject( object ): +class TestSerializableObject(object): """ test group for normal python usage of serializable object """ - def test_init_keywords( self ): + def test_init_keywords(self): """ test initializing class with keywords based on fields @@ -75,7 +75,7 @@ def test_init_keywords( self ): assert obj.str_prop == 'some string' assert obj.int_prop == 12 - def test_init_dictionary( self ): + def test_init_dictionary(self): """ test initializing class with dictionary @@ -92,12 +92,12 @@ def test_init_dictionary( self ): assert obj.int_prop == 12 -class TestSerialization( object ): +class TestSerialization(object): """ test group for serialization of basic object with primitive fields """ - def test_serialize( self ): + def test_serialize(self): """ test serialization """ @@ -110,7 +110,7 @@ def test_serialize( self ): assert body['str_prop'] == 'my awesome string' assert body['int_prop'] == 1234 - def test_deserialize( self ): + def test_deserialize(self): """ test deserialization """ @@ -121,13 +121,13 @@ def test_deserialize( self ): } obj = MyBasicClass() - obj.deserialize( body ) + obj.deserialize(body) - assert isinstance( obj, MyBasicClass ) + assert isinstance(obj, MyBasicClass) assert obj.str_prop == 'another great string' assert obj.int_prop == 9001 - def test_multiple( self ): + def test_multiple(self): """ test deserializing multiple objects of same class @@ -144,19 +144,19 @@ def test_multiple( self ): 'int_prop': 9002 } obj1 = MyBasicClass() - obj1.deserialize( body1 ) + obj1.deserialize(body1) obj2 = MyBasicClass() - obj2.deserialize( body2 ) + obj2.deserialize(body2) - assert isinstance( obj1, MyBasicClass ) + assert isinstance(obj1, MyBasicClass) assert obj1.str_prop == 'string1' assert obj1.int_prop == 9001 - assert isinstance( obj2, MyBasicClass ) + assert isinstance(obj2, MyBasicClass) assert obj2.str_prop == 'string2' assert obj2.int_prop == 9002 - def test_serialize_short_type( self ): + def test_serialize_short_type(self): """ test serialization without fully qualified path @@ -165,13 +165,13 @@ def test_serialize_short_type( self ): obj = MyBasicClass() obj.str_prop = 'my awesome string' obj.int_prop = 1234 - body = obj.serialize( use_full_type=False ) + body = obj.serialize(use_full_type=False) assert body['_type'] == 'MyBasicClass' assert body['str_prop'] == 'my awesome string' assert body['int_prop'] == 1234 - def test_serialize_no_type( self ): + def test_serialize_no_type(self): """ test serialization without type info @@ -180,19 +180,19 @@ def test_serialize_no_type( self ): obj = MyBasicClass() obj.str_prop = 'my awesome string' obj.int_prop = 1234 - body = obj.serialize( include_type=False ) + body = obj.serialize(include_type=False) assert '_type' not in body assert body['str_prop'] == 'my awesome string' assert body['int_prop'] == 1234 -class TestSubClass( object ): +class TestSubClass(object): """ test group for sub-classing another serializable model """ - def test_serialize( self ): + def test_serialize(self): """ test serialization @@ -211,7 +211,7 @@ def test_serialize( self ): assert body['int_prop'] == 99 assert body['str_prop_sub'] == 'sub_class_string' - def test_deserialize( self ): + def test_deserialize(self): """ test deserialization @@ -226,9 +226,9 @@ def test_deserialize( self ): } obj = MySubClass() - obj.deserialize( body ) + obj.deserialize(body) - assert isinstance( obj, MySubClass ) + assert isinstance(obj, MySubClass) assert obj.str_prop == 'parent_class_string' assert obj.int_prop == 99 assert obj.str_prop_sub == 'sub_class_string' diff --git a/test/test_string.py b/test/test_string.py index 9b987dd..24a554e 100644 --- a/test/test_string.py +++ b/test/test_string.py @@ -10,12 +10,12 @@ from objectfactory import Serializable, String -class TestString( object ): +class TestString(object): """ test case for string field type """ - def test_definition( self ): + def test_definition(self): """ test definition of class with string field @@ -23,30 +23,30 @@ def test_definition( self ): in schema creation """ - class MyTestClass( Serializable ): + class MyTestClass(Serializable): str_prop = String() - assert isinstance( MyTestClass._fields, dict ) - assert len( MyTestClass._fields ) == 1 + assert isinstance(MyTestClass._fields, dict) + assert len(MyTestClass._fields) == 1 assert 'str_prop' in MyTestClass._fields - assert isinstance( MyTestClass._fields['str_prop'], String ) + assert isinstance(MyTestClass._fields['str_prop'], String) schema = MyTestClass._schema - assert issubclass( schema, marshmallow.Schema ) - assert len( schema._declared_fields ) == 1 + assert issubclass(schema, marshmallow.Schema) + assert len(schema._declared_fields) == 1 assert 'str_prop' in schema._declared_fields prop = schema._declared_fields['str_prop'] - assert isinstance( prop, marshmallow.fields.String ) + assert isinstance(prop, marshmallow.fields.String) - def test_serialize( self ): + def test_serialize(self): """ test serialize expect string data to be dumped to json body """ - class MyTestClass( Serializable ): + class MyTestClass(Serializable): str_prop = String() obj = MyTestClass() @@ -57,14 +57,14 @@ class MyTestClass( Serializable ): assert body['_type'] == 'test.test_string.MyTestClass' assert body['str_prop'] == 'some string' - def test_deserialize( self ): + def test_deserialize(self): """ test deserialization expect string data to be loaded into class """ - class MyTestClass( Serializable ): + class MyTestClass(Serializable): str_prop = String() body = { @@ -73,20 +73,20 @@ class MyTestClass( Serializable ): } obj = MyTestClass() - obj.deserialize( body ) + obj.deserialize(body) - assert isinstance( obj, MyTestClass ) - assert type( obj.str_prop ) == str + assert isinstance(obj, MyTestClass) + assert type(obj.str_prop) == str assert obj.str_prop == 'another string' - def test_deserialize_invalid( self ): + def test_deserialize_invalid(self): """ test deserialization validation expect validation error to be raised on invalid string data """ - class MyTestClass( Serializable ): + class MyTestClass(Serializable): str_prop = String() body = { @@ -95,5 +95,5 @@ class MyTestClass( Serializable ): } obj = MyTestClass() - with pytest.raises( marshmallow.ValidationError ): - obj.deserialize( body ) + with pytest.raises(marshmallow.ValidationError): + obj.deserialize(body) diff --git a/test/testmodule/testclasses.py b/test/testmodule/testclasses.py index 30f5cc9..68b5fd7 100644 --- a/test/testmodule/testclasses.py +++ b/test/testmodule/testclasses.py @@ -7,7 +7,7 @@ @register -class MyBasicClass( Serializable ): +class MyBasicClass(Serializable): """ basic class to be used for testing serialization """ @@ -16,7 +16,7 @@ class MyBasicClass( Serializable ): @register -class MySubClass( MyBasicClass ): +class MySubClass(MyBasicClass): """ sub class to be used for testing inheritance and serialization """ @@ -25,9 +25,9 @@ class MySubClass( MyBasicClass ): @register -class MyComplexClass( Serializable ): +class MyComplexClass(Serializable): """ complex class to test hierarchical serialization """ - nested = Nested( MyBasicClass ) + nested = Nested(MyBasicClass) prop = Field() From 5ab3b2abc9fe40e1ffff6df357a4d2c3655a063a Mon Sep 17 00:00:00 2001 From: "Devin A. Conley" Date: Thu, 17 Aug 2023 14:20:53 -0700 Subject: [PATCH 3/4] test nested optionals --- test/test_nested.py | 56 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/test/test_nested.py b/test/test_nested.py index 9b135a4..b5c4d3e 100644 --- a/test/test_nested.py +++ b/test/test_nested.py @@ -158,3 +158,59 @@ class MyTestClass(Serializable): obj = MyTestClass() with pytest.raises(ValueError): obj.deserialize(body) + + def test_serialize_nested_optional(self): + """ + test serialize with nested optional + + expect nested object to be dumped to nested dict under specified key + """ + + class MyNestedClass(Serializable): + str_prop = String(key='string_property') + + class MyTestClass(Serializable): + nested = Nested() + + obj = MyTestClass() + obj.nested = MyNestedClass() + obj.nested.str_prop = 'some string' + + body = obj.serialize() + + assert body['_type'] == 'test.test_nested.MyTestClass' + assert isinstance(body['nested'], dict) + assert body['nested']['_type'] == 'test.test_nested.MyNestedClass' + assert 'str_prop' not in body['nested'] + assert body['nested']['string_property'] == 'some string' + + def test_deserialize_nested_optional(self): + """ + test deserialization with nested optional + + expect nested object to be created and data to be loaded from specified key + """ + + @register + class MyNestedClass(Serializable): + str_prop = String(key='string_property') + + class MyTestClass(Serializable): + nested = Nested() + + body = { + '_type': 'MyTestClass', + 'nested': { + '_type': 'MyNestedClass', + 'string_property': 'some string' + } + } + + obj = MyTestClass() + obj.deserialize(body) + + obj = MyTestClass.from_dict(body) + + assert isinstance(obj, MyTestClass) + assert isinstance(obj.nested, MyNestedClass) + assert obj.nested.str_prop == 'some string' From 6667d6990e4e03a466e806c84a37d3d9f9949a8f Mon Sep 17 00:00:00 2001 From: "Devin A. Conley" Date: Thu, 17 Aug 2023 14:52:27 -0700 Subject: [PATCH 4/4] bump version --- LICENSE | 2 +- README.md | 2 +- docs/source/conf.py | 4 ++-- docs/source/index.rst | 1 - setup.py | 2 +- 5 files changed, 5 insertions(+), 6 deletions(-) diff --git a/LICENSE b/LICENSE index b4972ac..c6254af 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2018-2021 Devin A. Conley +Copyright (c) 2018-2023 Devin A. Conley Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/README.md b/README.md index b338b9d..1efb71c 100644 --- a/README.md +++ b/README.md @@ -52,7 +52,7 @@ class type: , shape area: 2.25 ``` ### More examples -See more advanced examples [here](examples) +See more advanced examples [here](https://github.com/devinaconley/py-object-factory/tree/develop/examples) ## Install Use [pip](https://pip.pypa.io/en/stable/installing/) for installation diff --git a/docs/source/conf.py b/docs/source/conf.py index 442b52c..6c6a5bf 100644 --- a/docs/source/conf.py +++ b/docs/source/conf.py @@ -7,9 +7,9 @@ # project info project = 'objectfactory' -copyright = '2018-2021, Devin A. Conley' +copyright = '2018-2023, Devin A. Conley' author = 'Devin A. Conley' -release = '0.1.0' +release = '0.1.1' # config extensions = [ diff --git a/docs/source/index.rst b/docs/source/index.rst index 3266e57..c375717 100644 --- a/docs/source/index.rst +++ b/docs/source/index.rst @@ -7,7 +7,6 @@ objectfactory .. toctree:: :maxdepth: 2 - :caption: Contents: quickstart objectfactory diff --git a/setup.py b/setup.py index b3f98c0..49542fa 100644 --- a/setup.py +++ b/setup.py @@ -5,7 +5,7 @@ setuptools.setup( name='objectfactory', - version='0.1.0', + version='0.1.1', author='Devin A. Conley', author_email='devinaconley@gmail.com', description='objectfactory is a python package to easily implement the factory design pattern for object creation, serialization, and polymorphism',