def test_range_max(): assert validate.Range(1, 2)(2) == 2 assert validate.Range(None, 2)(2) == 2 assert validate.Range()(2) == 2 assert validate.Range(min_inclusive=False, max_inclusive=False)(2) == 2 assert validate.Range(2, 2)(2) == 2 with pytest.raises(ValidationError, match="less than or equal to 1"): validate.Range(0, 1)(2) with pytest.raises(ValidationError, match="less than or equal to 1"): validate.Range(None, 1)(2) with pytest.raises(ValidationError, match="less than 2"): validate.Range(1, 2, min_inclusive=True, max_inclusive=False, error=None)(2) with pytest.raises(ValidationError, match="greater than 2"): validate.Range(2, 2, min_inclusive=False, max_inclusive=True, error=None)(2)
class GetStateListForm(Schema): """ Get a list of states form. """ address = AccountAddressField(allow_none=True, required=False) start = AccountAddressField(allow_none=True, required=False) head = BlockIdentifierField(allow_none=True, required=False) limit = fields.Integer( allow_none=True, strict=True, required=False, validate=[ validate.Range(min=1, error='Limit must be greater than 0.'), ], ) reverse = fields.Boolean(required=False) node_url = NodeUrlField(required=True)
class IterativeSchema(BaseSchema): kind = fields.Str(allow_none=True, validate=validate.Equal("iterative")) n_iterations = RefOrObject(fields.Int(required=True, validate=validate.Range(min=1)), required=True) concurrency = fields.Int(allow_none=True) matrix = fields.Dict(keys=fields.Str(), values=fields.Nested(MatrixSchema), allow_none=True) seed = RefOrObject(fields.Int(allow_none=True)) container = fields.Nested(ContainerSchema, allow_none=True) early_stopping = fields.Nested(EarlyStoppingSchema, many=True, allow_none=True) @staticmethod def schema_config(): return IterativeConfig
class RandomSearchSchema(BaseCamelSchema): kind = fields.Str(allow_none=True, validate=validate.Equal(V1ParallelKind.RANDOM)) params = fields.Dict(keys=fields.Str(), values=fields.Nested(MatrixSchema), required=True) num_runs = RefOrObject(fields.Int(required=True, validate=validate.Range(min=1)), required=True) seed = RefOrObject(fields.Int(allow_none=True)) concurrency = fields.Int(allow_none=True) early_stopping = fields.Nested(EarlyStoppingSchema, many=True, allow_none=True) @staticmethod def schema_config(): return V1RandomSearch
class IterativeSchema(BaseCamelSchema): kind = fields.Str(allow_none=True, validate=validate.Equal(V1MatrixKind.ITERATIVE)) max_iterations = RefOrObject(fields.Int(required=True, validate=validate.Range(min=1)), required=True) concurrency = RefOrObject(fields.Int(allow_none=True)) params = fields.Dict(keys=fields.Str(), values=fields.Nested(HpParamSchema), allow_none=True) seed = RefOrObject(fields.Int(allow_none=True)) tuner = fields.Nested(TunerSchema, allow_none=True) early_stopping = fields.List(fields.Nested(EarlyStoppingSchema), allow_none=True) @staticmethod def schema_config(): return V1Iterative
class ObjectSchema(ma.Schema): # type: ignore """object field schema """ oid = fields.String(required=True) size = fields.Integer(required=True, validate=validate.Range(min=0)) extra = fields.Dict(required=False, missing=dict) @pre_load def set_extra_fields(self, data, **_): extra = {} rest = {} for k, v in data.items(): if k.startswith('x-'): extra[k[2:]] = v else: rest[k] = v return {'extra': extra, **rest}
class ProductSchema(Schema): """ Schema class for product details :ivar product_id: The ID of the product :vartype product_id: :class:`marshmallow.fields.Str` :ivar product_quantity: The quantity that is available :vartype product_quantity: :class:`marshmallow.fields.Int` """ product_id = fields.Str() product_quantity = fields.Int( validate=validate.Range(min=0), error_messages={"message": "Fill up the stock"}) @post_load def make_product(self, data, **kwargs): return Product(**data)
class BookSchema(Schema): """Schema abstraction layer for Book model using Marshmallow.""" id = fields.Int() title = fields.Str(required=True, validate=validate.Length( min=1, error="Field should not be empty.")) author = fields.Str(required=True, validate=validate.Length( min=1, error="Field should not be empty.")) publisher = fields.Str(required=True, validate=validate.Length( min=1, error="Field should not be empty.")) published_year = fields.Int( required=True, validate=validate.Range(min=1, max=2020, error="Futuristic books are not yet allowed."))
class ModifyLabelChangesSchema(Schema): context = fields.Str(required=True, validate=validate.OneOf(AXIS_NAME_TYPES)) index = fields.Int(required=True, validate=validate.Range(min=0)) label = fields.Str(required=True) @validates_schema def validate_label(self, data, **kwargs): context = data['context'] label = data['label'] if context == AXIS_NAME_TYPES.COLUMN: if label not in TABLE_COLUMN_TYPES: raise ValidationError('label {} unrecognized'.format(label)) elif context == AXIS_NAME_TYPES.ROW: if label not in TABLE_ROW_TYPES: raise ValidationError('label {} unrecognized'.format(label)) else: raise ValidationError('context {} unrecognized'.format(context))
class GetBlocksListForm(Schema): """ Get a list of blocks form. """ ids = BlockIdentifiersListField(allow_none=True, required=False) limit = fields.Integer( allow_none=True, strict=True, required=False, validate=[ validate.Range(min=1, error='Limit must be greater than 0.'), ], ) head = BlockIdentifierField(allow_none=True, required=False) reverse = fields.Boolean(required=False) ids_only = fields.Boolean(required=False) node_url = NodeUrlField(required=True)
class HyperoptSchema(BaseCamelSchema): kind = fields.Str(allow_none=True, validate=validate.Equal(V1MatrixKind.HYPEROPT)) algorithm = fields.Str( allow_none=True, validate=validate.OneOf(["tpe", "rand", "anneal"]) ) params = fields.Dict( keys=fields.Str(), values=fields.Nested(MatrixSchema), required=True ) num_runs = RefOrObject( fields.Int(required=True, validate=validate.Range(min=1)), required=True ) seed = RefOrObject(fields.Int(allow_none=True)) concurrency = fields.Int(allow_none=True) early_stopping = fields.Nested(EarlyStoppingSchema, many=True, allow_none=True) @staticmethod def schema_config(): return V1Hyperopt
class RandomSearchSchema(BaseSchema): kind = fields.Str(allow_none=True, validate=validate.Equal("random_search")) matrix = fields.Dict(keys=fields.Str(), values=fields.Nested(MatrixSchema), required=True) n_runs = RefOrObject(fields.Int(required=True, validate=validate.Range(min=1)), required=True) seed = RefOrObject(fields.Int(allow_none=True)) concurrency = fields.Int(allow_none=True) early_stopping = fields.Nested(EarlyStoppingSchema, many=True, allow_none=True) @staticmethod def schema_config(): return RandomSearchConfig
class PolicySchema(Schema): """ JSON schema for policy """ uid = fields.String(required=True) description = fields.String(default="", missing="") rules = fields.Nested(RulesSchema, required=True) targets = fields.Nested(TargetsSchema, required=True) effect = fields.String(required=True, validate=validate.OneOf([DENY_ACCESS, ALLOW_ACCESS])) priority = fields.Integer(default=0, missing=0, validate=validate.Range(min=0)) @post_load def post_load(self, data, **_): # pylint: disable=missing-docstring,no-self-use return Policy(**data)
class OrfCalling: min_protein_len: int = field( default=30, metadata={ "metadata": { "description": "minimum length of called proteins (in AAs). Default: 30 (90 nts)" }, "validate": validate.Range(min=0) }) execute: bool = field( default=True, metadata={ "metadata": { "description": "boolean flag. Default: true, ie execute the ORF calling." } })
class ImageSchema(Schema): scale = fields.Int( validate=validate.Range(min=1, max=100), required=False, ) width = fields.Int(required=False, ) height = fields.Int(required=False, ) @validates_schema def validates_schema(self, data, **kwargs): err_msg = 'Please select correct arguments combination: 1)scale 2)height 3)width 4)height and width' width = data.get("width") scale = data.get("scale") height = data.get("height") if not any([width, scale, height]): raise ValidationError(err_msg, field_name="error") if ((width and scale) or (height and scale)): raise ValidationError(err_msg, field_name="error")
class ServerSchema(Schema): """ redis server 记录序列化类 """ id = fields.Integer(dump_only=True) name = fields.String(required=True, validate=validate.Length(2, 64)) description = fields.String(validate=validate.Length(0, 512)) host = fields.String( required=True, validate=validate.Regexp(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$')) port = fields.Integer(validate=validate.Range(1024, 65536)) password = fields.String() updated_at = fields.DateTime(dump_only=True) created_at = fields.DateTime(dump_only=True) @validates_schema def validate_schema(self, data): """ verify if exist redis server which has same name """ if 'port' not in data: data['port'] = 6379 instance = self.context.get('instance', None) server = Server.query.filter_by(name=data['name']).first() if server is None: return if instance is not None and server != instance: raise ValidationError('Redis server already exist', 'name') if instance is None and server: raise ValidationError('Redis server already exist', 'name') @post_load def create_or_update(self, data): """ after data load successfully,auto create Server instance """ instance = self.context.get('instance', None) #create redis server if instance is None: return Server(**data) #update server for key in data: setattr(instance, key, data[key]) return instance
class CalculationRequestParameters(Schema): """ Defines the schema that the API expects to receive. This is compiled into the openAPI spec, and used for data validation """ birth_date = fields.Date( required=True, description= "Date of birth of the patient in `YYYY-MM-DD` format. Other formats such as the FHIR/ISO YYYY-MM-DDTHH:MM:SS and those that include milliseconds and timezones will be accepted but everything after the T will be discarded in processing. Time of day and time zone are not taken into account by the centile/SDS calculation" ) gestation_days = fields.Number( description= "The number of additional days _beyond the completed weeks of gestation_ at which the patient was born. This enables Gestational Age correction if the child was not born at term. See also the other parameter `gestation_weeks` - both are usually required." ) gestation_weeks = fields.Number( validate=validate.Range(min=MINIMUM_GESTATION_WEEKS, max=MAXIMUM_GESTATION_WEEKS), description= "The number of completed weeks of gestation at which the patient was born. This enables Gestational Age Correction if the child was not born at term. See also the other parameter `gestation_days` - both are usually required. If the child is term then any value between 37 and 42 will be handled the same, and a value must be provided. Values outside the validation range will return errors." ) measurement_method = fields.String( required=True, enum=["height", "weight", "bmi", "ofc"], validate=validate.OneOf(["height", "weight", "bmi", "ofc"]), description= "The type of measurement performed on the infant or child (`height`, `weight`, `bmi` or `ofc`). The value of this measurement is supplied as the `observation_value` parameter. The measurements represent height **in centimetres**, weight *in kilograms**, body mass index **in kilograms/metre²** and occipitofrontal circumference (head circumference, OFC) **in centimetres**." ) observation_date = fields.Date( required=True, description= "The date that the measurement was taken, in `YYYY-MM-DD` format. Other formats such as the FHIR/ISO YYYY-MM-DDTHH:MM:SS and those that include milliseconds and timezones will be accepted but everything after the T will be discarded in processing. Time of day and time zone are not taken into account by the centile/SDS calculation" ) observation_value = fields.Float( required=True, description= "The value of the measurement supplied. Used in conjunction with type of measurement performed(`height`, `weight`, `bmi` or `ofc`) on the infant or child." ) sex = fields.String( required=True, enum=['male', 'female'], validate=validate.OneOf(['male', 'female']), description= "The sex of the patient, as a string value which can either be `male` or `female`. Abbreviations or alternatives are not accepted" )
class NodeSchema(Schema): """Represent a node schema.""" node_id = NODE_ID_FIELD node_type = fields.Int(required=True) protocol_version = fields.Str(required=True) children = fields.Dict(keys=fields.Int(), values=fields.Nested(ChildSchema)) sketch_name = fields.Str() sketch_version = fields.Str() battery_level = fields.Int(validate=validate.Range(min=0, max=100)) heartbeat = fields.Int() sleeping = fields.Bool() @post_load def make_node(self, data: dict, **kwargs: Any) -> Node: """Make a node.""" # pylint: disable=no-self-use, unused-argument return Node(**data)
class HomeChainSchema(ChainSchema): max_reorg_depth = fields.Integer(missing=10, validate=validate_non_negative) event_poll_interval = fields.Float(missing=5, validate=validate_non_negative) gas_price = fields.Integer(missing=10 * denoms.gwei, validate=validate_non_negative) # disable type check as type hint in eth_utils is wrong, (see # https://github.com/ethereum/eth-utils/issues/168) minimum_validator_balance = fields.Integer( missing=to_wei(0.04, "ether"), validate=validate_non_negative # type: ignore ) balance_warn_poll_interval = fields.Float(missing=60, validate=validate_non_negative) # maximum number of pending transactions per reorg-unsafe block max_pending_transactions_per_block = fields.Integer( missing=16, validate=validate.Range(min=1, max=128))
class ConfigVariablesSchema(Schema): """Data Model for Application Configuration Environment Variables""" class Meta: unknown = EXCLUDE DEBUG = fields.Boolean(data_key='APPUSERS_DEBUG') ENV = fields.Str(data_key='APPUSERS_ENV') SERVER_NAME = fields.Str(data_key='APPUSERS_SERVER_NAME') APPLICATION_ROOT = fields.Str(data_key='APPUSERS_APPLICATION_ROOT') SQLALCHEMY_DATABASE_URI = fields.Str(data_key='APPUSERS_DATABASE_URI') API_KEY = fields.Str(data_key='APPUSERS_API_KEY') JWT_SECRET_KEY = fields.Str(data_key='APPUSERS_SECRET_KEY') JWT_ACCESS_TOKEN_EXPIRES = fields.TimeDelta(precision='seconds', data_key='APPUSERS_ACCESS_TOKEN_EXPIRES') MAX_FAILED_LOGIN_ATTEMPTS = fields.Integer( validate=validate.Range(min=1, error='Max failed login attempts must be greater or equal {min}, is {input}'), data_key='APPUSERS_MAX_FAILED_LOGIN_ATTEMPTS') LOCK_TIMEOUT = fields.TimeDelta(precision='seconds', data_key='APPUSERS_LOCK_TIMEOUT')
class StreamsAPIEventSchema(BaseSchema): """Base Streams API event schema.""" __model__ = StreamsAPIEvent api_version = fields.String(required=True, validate=validate.Equal('1.0')) event_type = fields.String(required=True) event_id = fields.String( required=True, validate=validate.Regexp( '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$')) time_created = fields.Integer(required=True, validate=validate.Range(min=1546300800000, max=99999999999999)) gateway_serial = fields.String(validate=validate.Length(min=1, max=128))
class EventSchema(Schema): category = fields.Nested(CategorySchema, required=False) name = fields.String(required=True) start_date = fields.DateTime(required=True) location = fields.Nested(EventLocationSchema, required=False) finish_date = fields.DateTime(required=True) result_score = fields.Nested(ScoreSchema, required=False) source_type = fields.Integer( required=True, validate=[validate.Range(min=-1, max=len(SOURCES) - 2)]) color = fields.String(required=False) def __init__(self, data=None, **kwargs): super(EventSchema, self).__init__(**kwargs) if data is not None: self.data, self.errors = self.load(data) def save(self, user, event=None): if self.errors and len(self.errors) > 0: raise InvalidDataException(message='Invalid event input fields', fields=self.errors) if event is None: event = Event() # TODO add check on correct category (it must exist and be either current_user's or default (created on server) event.category = self.data.get('category') event.name = self.data.get('name') event.start_date = self.data.get('start_date') # if not event.start_date.tzinfo: # event.start_date = UTC.localize(event.start_date) # else: # event.start_date = event.start_date.astimezone(UTC) event.finish_date = self.data.get('finish_date') # if not event.finish_date.tzinfo: # event.finish_date = UTC.localize(event.finish_date) # else: # event.finish_date = event.finish_date.astimezone(UTC) event.result_score = self.data.get('result_score') event.source_type = self.data.get('source_type') event.location = self.data.get('location') event.user = user.id event.color = self.data.get('color') event.save() return event
class CarBrandSchema(BaseSchema): """Complete car brand schema""" name = fields.Str( required=True, description="Name of the car brand", example="Mercedes-Benz", validate=validate.Length(min=1, max=16), ) established = fields.Int( required=True, description="Year when the car brand was established", example=1926, validate=validate.Range(min=1886, max=2100), ) created_at = fields.DateTime( required=False, description="The time at which the car brand was created in the database", )
class CreateParkParameters(Parameters): """ Helper parameters to create a park. """ latitude = base_fields.Float(validate=validate.Range( min=-90.0, max=90.0, error="Invalid latitude parameters. Must be between -90 and 90.")) longitude = base_fields.Float(validate=validate.Range( min=-180.0, max=180.0, error="Invalid longitude parameters. Must be between -180 and 180.")) name = base_fields.String(validate=validate.Range(min=0)) address = base_fields.String(validate=validate.Range(min=0)) operator = base_fields.String(validate=validate.Range(min=0)) sponsors = base_fields.List(cls_or_instance=base_fields.String()) opening_time = base_fields.String(validate=validate.Range(min=0)) closing_time = base_fields.String(validate=validate.Range(min=0)) admission_price = base_fields.Float(validate=validate.Range( min=0.0, error="Invalid price parameters. Must be greater than or equal to$0."))
class Model(Schema): id = fields.Integer(required=True) client_name = fields.Str(validate=validate.Length(max=255), required=True) sort_index = fields.Float(required=True) client_phone = fields.Str(validate=validate.Length(max=255), allow_none=True) location = fields.Nested(LocationSchema) contractor = fields.Integer(validate=validate.Range(min=0), allow_none=True) upstream_http_referrer = fields.Str(validate=validate.Length(max=1023), allow_none=True) grecaptcha_response = fields.Str(validate=validate.Length(min=20, max=1000), required=True) last_updated = fields.DateTime(allow_none=True) skills = fields.Nested(SkillSchema, many=True)
class ServiceInstanceValueSchema(Schema): ip = fields.String( required=True, error_messages={'required': 'ip must be provided in instance value'}) port = NestedDict( fields.Integer(validate=validate.Range(min=1, max=65535)), required=True, error_messages={ 'required': 'port must be provided in instance value', 'invalid': 'port must be a dict, eg: {{"port":{{"main": 8080}}' }) state = fields.String(validate=validate.OneOf( ['up', 'down'], error='state must be "up" or "down".')) meta = fields.Dict(required=False) # TODO: remove these fields below idc = fields.String(required=False) cluster = fields.String(required=False) name = fields.String(required=False) @validates('ip') def validate_ip(self, value): try: IPv4Address(unicode(value)) except ValueError: raise ValidationError('illegal IP address') @validates('port') def validate_port(self, value): if 'main' not in value: raise ValidationError('main port is required') @pre_load def ensure_meta_dict(self, data): data['meta'] = data.get('meta') or {} return data @post_load def coerce_meta_value(self, data): meta = data.setdefault('meta', {}) for key, value in meta.iteritems(): meta[key] = ensure_text_type(value or '') return data
class BouncingBallConfigSchema(Schema): bounciness = fields.Float(validate=validate.Range(min=0, max=1), missing=0.8) terminal_velocity = fields.Int(validate=validate.Range(min=0), missing=3) gravity = fields.Float(validate=validate.Range(min=0), missing=0.05) colour = fields.List( fields.Int(validate=validate.Range(min=0, max=255)), validate=validate.Length(equal=3), missing=[255, 255, 255], ) trail_length = fields.Int(validate=validate.Range(min=0), missing=3) max_height = fields.Int(validate=validate.Range(min=0), missing=None) starting_height = fields.Int(validate=validate.Range(min=0), missing=None) invert = fields.Bool(missing=False) @post_load def make_config(self, data, **kwargs): return BouncingBallConfig(**data)
class hostschema(Schema): hostname = fields.String() device_type = fields.String() host = fields.String() device_type = fields.Str(validate=validate.OneOf(["MM", "MD"])) #print(device_type) MM = fields.Nested(mm_config_schema, required=False) MD = fields.Nested(md_config_schema, required=False) AOS_Source = fields.Nested(aos_source_schema, required=True) Validate_Image_before_upgrade = fields.Boolean(required=True) Validate_controller_sync_before_upgrade = fields.Boolean(required=True) Validate_controller_up_before_upgrade = fields.Boolean(required=True) Authentication = fields.Nested(device_authentication, required=True) image_file_name = fields.Str(required=True) image_version = fields.Str(required=True) image_build = fields.Str(required=True) upgrade_disk = fields.Str(validate=validate.OneOf(["Auto", "0", "1"]), required=True) CheckList = fields.List(fields.Dict(), validate=validate.Length(min=1), required=True) Pre_image_AP = fields.Boolean(required=False) max_ap_image_load = fields.Int(validate=validate.Range(min=1, max=250), required=False) # If device type is MD then Pre_image_AP required @validates_schema def validate_max_ap_image_load(self, data, **kwargs): errors = {} if data.get("device_type") == "MD": if data.get("Pre_image_AP") == None: errors["Pre_image_AP"] = ["Missing field"] if data.get("Pre_image_AP") != True: if type(data.get("max_ap_image_load")) != int: errors["max_ap_image_load"] = ["Must intiger"] if errors: raise ValidationError(errors)
class EfsSettingsSchema(BaseSchema): """Represent the EFS schema.""" encrypted = fields.Bool( metadata={"update_policy": UpdatePolicy.UNSUPPORTED}) kms_key_id = fields.Str( metadata={"update_policy": UpdatePolicy.UNSUPPORTED}) performance_mode = fields.Str( validate=validate.OneOf(["generalPurpose", "maxIO"]), metadata={"update_policy": UpdatePolicy.UNSUPPORTED}) throughput_mode = fields.Str( validate=validate.OneOf(["provisioned", "bursting"]), metadata={"update_policy": UpdatePolicy.SUPPORTED}) provisioned_throughput = fields.Int( validate=validate.Range(min=1, max=1024), metadata={"update_policy": UpdatePolicy.SUPPORTED}) file_system_id = fields.Str( validate=validate.Regexp(r"^fs-[0-9a-z]{8}$|^fs-[0-9a-z]{17}$"), metadata={"update_policy": UpdatePolicy.UNSUPPORTED}, ) @validates_schema def validate_existence_of_mode_throughput(self, data, **kwargs): """Validate the conditional existence requirement between throughput_mode and provisioned_throughput.""" if kwargs.get("partial"): # If the schema is to be loaded partially, do not check existence constrain. return throughput_mode = data.get("throughput_mode") provisioned_throughput = data.get("provisioned_throughput") if throughput_mode != "provisioned" and provisioned_throughput: raise ValidationError( message= "When specifying provisioned throughput, the throughput mode must be set to provisioned", field_name="ThroughputMode", ) if throughput_mode == "provisioned" and not provisioned_throughput: raise ValidationError( message="When specifying throughput mode to provisioned," " the provisioned throughput option must be specified", field_name="ProvisionedThroughput", )
class IterativeSchema(BaseCamelSchema): kind = fields.Str(allow_none=True, validate=validate.Equal(V1MatrixKind.ITERATIVE)) num_iterations = RefOrObject( fields.Int(required=True, validate=validate.Range(min=1)), required=True ) concurrency = fields.Int(allow_none=True) params = fields.Dict( keys=fields.Str(), values=fields.Nested(MatrixSchema), allow_none=True ) seed = RefOrObject(fields.Int(allow_none=True)) container = SwaggerField( cls=k8s_schemas.V1Container, defaults={"name": MAIN_JOB_CONTAINER}, allow_none=True, ) early_stopping = fields.Nested(EarlyStoppingSchema, many=True, allow_none=True) @staticmethod def schema_config(): return V1Iterative