class XYGraph(Schema): """Class that defines the x/y graph value schema.""" values = fields.List(fields.Tuple((fields.Number(), fields.Number())), required=True) unit = fields.Tuple((fields.Str(), fields.Str()), required=False) class Meta: include = {"type": fields.Constant("xy", required=True)}
class MySchema(Schema): foo = fields.List(fields.DateTime()) bar = fields.Tuple((fields.DateTime(),)) baz = fields.List(fields.Date()) qux = fields.Tuple((fields.Date(),)) class Meta: datetimeformat = "iso8601" dateformat = "iso8601"
def test_bad_tuple_field(self): class ASchema(Schema): id = fields.Int() with pytest.raises(ValueError): fields.Tuple(["string"]) with pytest.raises(ValueError): fields.Tuple(fields.String) expected_msg = ('Elements of "tuple_fields" must be subclasses or ' "instances of marshmallow.base.FieldABC.") with pytest.raises(ValueError, match=expected_msg): fields.Tuple([ASchema])
def test_bad_tuple_field(self): class ASchema(Schema): id = fields.Int() with pytest.raises(ValueError): fields.Tuple(['string']) with pytest.raises(ValueError): fields.Tuple(fields.String) with pytest.raises(ValueError) as excinfo: fields.Tuple([ASchema]) expected_msg = ('Elements of "tuple_fields" must be subclasses or ' 'instances of marshmallow.base.FieldABC.') assert expected_msg in str(excinfo)
class LinearSchema(Schema): position = fields.Tuple((fields.Float(), fields.Float(), fields.Float()), missing=None) velocity = fields.Tuple((fields.Float(), fields.Float(), fields.Float()), missing=None) acceleration = fields.Tuple( (fields.Float(), fields.Float(), fields.Float()), missing=None) __model__ = _linear.Linear @post_load def make_object(self, data, **kwargs): return self.__model__(**data)
class PulleySchema(Schema): radius = fields.Float(required=True) inertia = fields.Nested(_inertia.InertiaSchema, missing=None) dcm = fields.Tuple( (fields.Tuple((fields.Float(), fields.Float(), fields.Float())), fields.Tuple((fields.Float(), fields.Float(), fields.Float())), fields.Tuple((fields.Float(), fields.Float(), fields.Float()))), missing=None) __model__ = _pulley.Pulley @post_load def make_object(self, data, **kwargs): return self.__model__(**data)
class PolyhedronSchema(_geometry.PrimitiveSchema): vertices = fields.List( fields.Tuple((fields.Float(required=True), fields.Float(required=True), fields.Float(required=True))), required=True, ) faces = fields.List( fields.Tuple( (fields.Integer(required=True), fields.Integer(required=True), fields.Integer(required=True))), required=True, ) __model__ = _polyhedron.Polyhedron
class ContentEntry(Schema): class Meta: ordered = True content_id = fields.Integer(data_key="content-id") unique_id = fields.Raw(data_key="unique-id", validate=validate.Length(min=4, max=4)) content_type = EnumField(ContentType, data_key="content-type", by_value=True) filesize = fields.Integer() # Most of these limits are limitations in the OpenTTD client. name = fields.String(validate=validate.Length(max=31)) version = fields.String(validate=validate.Length(max=15)) url = fields.String(validate=validate.Length(max=95)) description = fields.String(validate=validate.Length(max=511)) tags = fields.List(fields.String(validate=validate.Length(max=31))) md5sum = fields.Raw(validate=validate.Length(min=16, max=16)) min_version = fields.List(fields.Integer(), data_key="min-version", missing=None) max_version = fields.List(fields.Integer(), data_key="max-version", missing=None) raw_dependencies = fields.List( fields.Tuple(( EnumField(ContentType, by_value=True), fields.Raw(validate=validate.Length(min=4, max=4)), fields.Raw(validate=validate.Length(min=16, max=16)), )), data_key="raw-dependencies", )
class DirectedGraphSchema(Schema): """ Schema for :class:`DirectedGraph`. Validates graph somewhat rigorously. """ edge = fields.Dict( keys=fields.Int(), values=fields.Dict(keys=fields.Int, values=fields.Nested(EdgeDataSchema)), ) node = fields.List(fields.Nested(NodeDataSchema)) edge_list = fields.List(fields.Tuple((fields.Int(), fields.Int()))) class Meta: fields = ("node", "edge", "edge_list") @post_load def make_graph(self, data, **kwargs): # Modification below alters original settings, so use a deepcopy. _data = copy.deepcopy(data) return DirectedGraph(**_data) @pre_dump(pass_many=True) def sort_edge_list(self, data, many, **kwargs): """Sort edge list to make dumps consistent.""" data.edge_list = sorted(data.edge_list) return data
class PotholeSchema(Schema): id = fields.UUID(required=True) device_name = fields.String(required=True) timestamp = fields.DateTime(required=True) confidence = fields.Float(required=True) coordinates = fields.Tuple((fields.Float(), fields.Float()), required=True) photo_url = fields.String(required=True)
class ChangeSchema(ma.SQLAlchemyAutoSchema): class Meta: model = Change fields = ('category', 'page', 'data', 'created_at', 'author', '_links') dump_only = fields include_fk = True data = fields.List( fields.Tuple( (fields.Int(validate=validate.Range(-1, 1)), fields.String))) author = fields.UUID() _links = ma.Hyperlinks({ 'collection': ma.URLFor('changes', values={ 'category_id': '<category>', 'page_id': '<page>' }), 'page': ma.URLFor('page', values={ 'category_id': '<category>', 'page_id': '<page>' }), 'author': ma.URLFor('user', values={'user_id': '<author>'}) })
class ConfigSchema(Schema): """Snow config schema Attributes: address (str): Instance address, e.g. https://my_instance.service-now.com basic_auth (tuple): (<username>, <password>), mutually exclusive with other authentication methods """ class InternalConfig: """Internal Application config""" def __init__(self, **config): for k, v in config.items(): setattr(self, k, v) address = fields.Url(required=True) basic_auth = fields.Tuple(tuple_fields=(fields.String(), fields.String()), required=False) verify_ssl = fields.Boolean(missing=True) def __init__(self, *args, **kwargs): super(ConfigSchema, self).__init__(*args, **kwargs) @post_load def make_object(self, data, **_): if {"basic_auth", "oauth"} <= set(data): raise ValidationError("Cannot use multiple authentication methods") elif "basic_auth" in data: pass else: raise ValidationError( "No supported authentication method provided") return ConfigSchema.InternalConfig(**data)
class ArtpieceSchema(Schema): title = fields.Str(missing=None) email = fields.Email(required=True, load_only=True) art = fields.Dict(missing=None, keys=fields.Str(), values=fields.List( fields.Tuple((fields.Int(), fields.Int())))) def __init__(self, valid_color_keys): Schema.__init__(self) self._valid_color_keys = valid_color_keys @validates('title') def _validate_title_field(self, title): validate_title(title) @validates('art') def _validate_art_field(self, art): validate_art_content_length(art) validate_color_keys(art, self._valid_color_keys) validate_pixels(art) @pre_load def strip_title(self, in_data, **kwargs): title = in_data['title'] if in_data else None if title is not None: in_data['title'] = title.strip() return in_data class meta: strict = True
class AssetExportSchema(Schema): ''' Asset Export API Schema ''' # Temporal fields created_at = fields.Int() deleted_at = fields.Int() first_scan_time = fields.Int() last_assessed = fields.Int() last_authenticated_scan_time = fields.Int() terminated_at = fields.Int() updated_at = fields.Int() # Boolean flags has_plugin_results = fields.Bool() is_deleted = fields.Bool() is_licensed = fields.Bool() is_terminated = fields.Bool() servicenow_sysid = fields.Bool() # Other params chunk_size = fields.Int(dump_default=1000) network_id = fields.UUID() sources = fields.List(fields.Str()) tags = fields.List(fields.Tuple((fields.Str(), fields.Str()))) @post_dump def post_serialization(self, data, **kwargs): # noqa PLR0201 PLW0613 data = serialize_tags(data) data = envelope(data, 'filters', excludes=['chunk_size']) return data
class DashboardPermalinkPostSchema(Schema): dataMask = fields.Dict( required=False, allow_none=True, description="Data mask used for native filter state", ) activeTabs = fields.List( fields.String(), required=False, allow_none=True, description="Current active dashboard tabs", ) urlParams = fields.List( fields.Tuple( ( fields.String( required=True, allow_none=True, description="Key"), fields.String( required=True, allow_none=True, description="Value"), ), required=False, allow_none=True, description="URL Parameter key-value pair", ), required=False, allow_none=True, description="URL Parameters", ) anchor = fields.String( required=False, allow_none=True, description="Optional anchor link added to url hash", )
class DashboardPermalinkPostSchema(Schema): filterState = fields.Dict( required=False, allow_none=True, description="Native filter state", ) urlParams = fields.List( fields.Tuple( ( fields.String( required=True, allow_none=True, description="Key"), fields.String( required=True, allow_none=True, description="Value"), ), required=False, allow_none=True, description="URL Parameter key-value pair", ), required=False, allow_none=True, description="URL Parameters", ) hash = fields.String(required=False, allow_none=True, description="Optional anchor link")
class ClientConfig(BaseConfigSchema): """Client config schema Attributes: address (str): Instance address, e.g. my_instance.service-now.com basic_auth (tuple): (<username>, <password>), mutually exclusive with other authentication methods use_ssl (bool): Whether to use SSL, defaults to True verify_ssl (bool): Whether to validate SSL certificates, defaults to True """ def __init__(self, *args: Any, **kwargs: Any): super(ClientConfig, self).__init__(*args, **kwargs) basic_auth = fields.Tuple( tuple_fields=(fields.String(), fields.String()), required=False, allow_none=True ) oauth = fields.Dict(required=False, allow_none=True) use_ssl = fields.Boolean(missing=True) verify_ssl = fields.Boolean(missing=True) @post_load def make_object(self, data: dict, **_: Any) -> Any: if {"basic_auth", "oauth"} <= set(data): raise AmbiguousClientAuthentication( "Cannot use multiple authentication methods" ) elif data.get("basic_auth"): pass else: raise MissingClientAuthentication( "No supported authentication method provided" ) return super().make_object(data)
class FunctionSchema(Schema): name = fields.String() lines = fields.Tuple((fields.Integer(), fields.Integer())) @post_load def make_function(self, data, **kwargs): return Function(**data)
class DirectionalMacroConfigSchema(FactorySchema[DirectionalMacroConfig]): ctor = DirectionalMacroConfig spell_key_rotation = fields.List(fields.Str(), required=True) rotation_threshold_secs = fields.Int(default=3600) direction_pairs = fields.List(fields.Tuple((fields.Str(required=True), fields.Str(required=False, allow_none=True, default=None))), required=True)
class ConfigSchema(Schema): log_level = EnumField(LogLevel, load_default=LogLevel.WARNING) listen_addr = fields.IP(required=True) log_port_range = fields.Tuple((fields.Integer(), fields.Integer()), required=True) @post_load def make_config(self, data, **kwargs): return Config(**data)
class AnchorSchema(Schema): position = fields.Tuple( (fields.Float(), fields.Float(), fields.Float()), required=True, ) dcm = fields.Tuple( (fields.Tuple((fields.Float(), fields.Float(), fields.Float())), fields.Tuple((fields.Float(), fields.Float(), fields.Float())), fields.Tuple((fields.Float(), fields.Float(), fields.Float()))), missing=None) @post_load(pass_many=True) def make_object(self, data, many, **kwargs): if many: return _anchor.AnchorList( (self.make_object(each, False, **kwargs) for each in data)) else: return self.__model__(**data)
class NocturnalEventsSchema(Schema): query_kind = fields.String(validate=OneOf(["nocturnal_events"])) start = fields.Date(required=True) stop = fields.Date(required=True) hours = fields.Tuple((fields.Integer(), fields.Integer())) subscriber_subset = SubscriberSubset() @post_load def make_query_object(self, params, **kwargs): return NocturnalEventsExposed(**params)
class BarGraph(Schema): """Class that defines the bar graph value schema.""" values = fields.List(fields.Tuple([fields.Str(), fields.Number()]), required=True) unit = fields.String(required=False) class Meta: include = {"type": fields.Constant("bar", required=True)}
class QuerySchema(Schema): bounds = fields.Tuple(( fields.Float(), fields.Float(), fields.Float(), fields.Float(), ), required=True) limit = fields.Integer(required=False)
class CylinderSchema(_geometry.PrimitiveSchema): height = fields.Float( required=True ) radius = fields.Tuple( (fields.Float(), fields.Float()), required=True ) __model__ = _cylinder.Cylinder
class HistoricalAssetsPriceSchema(Schema): assets_timestamp = fields.List( fields.Tuple( # type: ignore # Tuple is not annotated (AssetField(required=True), TimestampField(required=True)), required=True, ), required=True, validate=webargs.validate.Length(min=1), ) target_asset = AssetField(required=True) async_query = fields.Boolean(missing=False)
class InertiaSchema(Schema): angular = fields.Tuple( ( fields.Tuple(( fields.Float(allow_nan=True), fields.Float(allow_nan=True), fields.Float(allow_nan=True) )), fields.Tuple(( fields.Float(allow_nan=True), fields.Float(allow_nan=True), fields.Float(allow_nan=True) )), fields.Tuple(( fields.Float(allow_nan=True), fields.Float(allow_nan=True), fields.Float(allow_nan=True) )) ), required=False, default=[[np.inf, 0, 0], [0, np.inf, 0], [0, 0, np.inf]], missing=None ) linear = fields.Tuple( ( fields.Tuple(( fields.Float(allow_nan=True), fields.Float(allow_nan=True), fields.Float(allow_nan=True) )), fields.Tuple(( fields.Float(allow_nan=True), fields.Float(allow_nan=True), fields.Float(allow_nan=True) )), fields.Tuple(( fields.Float(allow_nan=True), fields.Float(allow_nan=True), fields.Float(allow_nan=True) )) ), required=False, default=[[np.inf, 0, 0], [0, np.inf, 0], [0, 0, np.inf]], missing=None, ) __model__ = _inertia.Inertia @post_load def make_object(self, data, **kwargs): return self.__model__(**data)
class PlatformSchema(Schema): name = fields.String( required=False, missing='default', ) anchors = fields.Nested( PlatformAnchorSchema(many=True, ), required=True, ) pose = fields.Nested(_pose.PoseSchema, missing=None) motion_pattern = fields.Nested( _pattern.PatternSchema, required=True, ) center_of_gravity = fields.Tuple( (fields.Float(), fields.Float(), fields.Float()), required=False, missing=(0.0, 0.0, 0.0), ) center_of_linkage = fields.Tuple( (fields.Float(), fields.Float(), fields.Float()), required=False, missing=(0.0, 0.0, 0.0), ) inertia = fields.Nested( _inertia.InertiaSchema, required=False, missing=None, ) __model__ = _platform.Platform @post_load(pass_many=True) def make_object(self, data, many, **kwargs): if many: return _platform.PlatformList( (self.make_object(each, False) for each in data)) else: return self.__model__(**data)
class ProjectOptimizationModifierPruningNodeSchema( ProjectOptimizationModifierPruningNodeMetadataSchema, ProjectOptimizationModifierEstimationsSchema, ): """ Schema for a pruning node containing metadata and estimated values """ overridden = fields.Bool(required=True, allow_none=False) perf_sensitivities = fields.List( fields.Tuple( [fields.Float(allow_none=True), fields.Float(allow_none=True)]), required=True, allow_none=False, ) loss_sensitivities = fields.List( fields.Tuple( [fields.Float(allow_none=True), fields.Float(allow_none=True)]), required=True, allow_none=False, )
class ExplorePermalinkPostSchema(Schema): formData = fields.Dict( required=True, allow_none=False, description="Chart form data", ) urlParams = fields.List( fields.Tuple( ( fields.String( required=True, allow_none=True, description="Key"), fields.String( required=True, allow_none=True, description="Value"), ), required=False, allow_none=True, description="URL Parameter key-value pair", ), required=False, allow_none=True, description="URL Parameters", )