class TestEnumFieldByName(object): def setup(self): self.field = EnumField(EnumTester) def test_serialize_enum(self): assert self.field._serialize(EnumTester.one, None, object()) == 'one' def test_deserialize_enum(self): assert self.field._deserialize('one', None, {}) == EnumTester.one def test_deserialize_nonexistent_member(self): with pytest.raises(ValidationError): self.field._deserialize('fred', None, {})
class UserRegisterRequestSchema(Schema): """Request register user schema.""" name = fields.Str(description='name', required=True) country = fields.Str(description='country', required=True) city = fields.Str(description='city', required=True) balance = fields.Decimal( description='balance', required=False, validate=[ Range(min=0, error='Negative balance.'), ], ) currency = EnumField(Currency, description='currency_type', required=True)
class TradingCodeSchema(BaseSchema): """ TradingCode 모델의 Schema입니다. Schema of Trading Code model. """ class Meta: model = models.TradingCode id = ma.auto_field( validate=validate.Range(min=1, error="Id must be bigger than 1") ) code = ma.auto_field(validate=validate.Length(min=4, max=10)) trading_type = EnumField(models.TradingType, data_key="tradingType")
class TitleSchema(Schema): '''Title object schema''' title = fields.String(required=True) # WARNING: This field has been superseded by 'titleType' type = fields.String() # TitleTypeEnum titleType = EnumField(TitleTypeEnum) lang = fields.String() @post_load def make_title(self, data): '''Return Title object after loading''' return Title(**data)
class RHMatchingEvents(RHRoomBookingBase): """Get events suitable for booking linking.""" @use_kwargs( { 'start_dt': fields.DateTime(), 'end_dt': fields.DateTime(), 'repeat_frequency': EnumField(RepeatFrequency, missing='NEVER'), 'repeat_interval': fields.Int(missing=1), }, location='query') def _process(self, start_dt, end_dt, repeat_frequency, repeat_interval): events = get_matching_events(start_dt, end_dt, repeat_frequency, repeat_interval) return jsonify(reservation_user_event_schema.dump(events))
class SubmissionVersionSchema(ma.ModelSchema): class Meta: fields = ( "submissionVersionId", # "submission", "createdBy", "createdAt") model = SubmissionVersion.Model # optionally attach a Session # to use for deserialization sqla_session = db.session submission = EnumField(SubmissionSchema)
class UserSchema(ma.Schema): id=fields.Integer() username = fields.Str( required=True, validate=ValidationHelper.must_not_be_blank ) # print(".........Username", username) password = fields.Str( required=True, # load_only=True, validate=ValidationHelper.must_not_be_blank) role = EnumField(RolesAvailable, by_value=True)
class RoomUpdateSchema(RoomSchema): owner = Principal() acl_entries = PrincipalPermissionList(RoomPrincipal) protection_mode = EnumField(ProtectionMode) class Meta(RoomSchema.Meta): fields = RoomSchema.Meta.fields + ( 'notification_before_days', 'notification_before_days_weekly', 'owner', 'notification_before_days_monthly', 'notifications_enabled', 'end_notification_daily', 'end_notification_weekly', 'end_notification_monthly', 'end_notifications_enabled', 'verbose_name', 'site', 'notification_emails', 'booking_limit_days', 'acl_entries', 'protection_mode')
class UserIdSchema(Schema): id = fields.String(required=True) type = EnumField(PlayerType, by_value=True) client_id = fields.String(required=True, allow_none=True) @post_load def make_user_id(self, data, **kwargs): return UserId(**data) def on_bind_field(self, field_name, field_obj): field_obj.data_key = camelcase(field_obj.data_key or field_name) class Meta: unknown = EXCLUDE
class LocationSchema(Schema): __model__ = LocationEntity uuid = fields.Str(missing=lambda: str(uuid4())) label = fields.Str(required=True) slug = fields.Str(dump_only=True) external_id = fields.Str(dump_only=True) search_label = fields.Str(dump_only=True) type = EnumField(LocationType, validate=validate.OneOf([e.value for e in LocationType])) @post_load def make_location(self, data: dict, **kwargs): current_app.logger.info(f"data {data}") return LocationEntity.from_dict(data)
class AttendanceSchema(TrackableSchema): id = fields.Integer() attendance_sheet_id = fields.Integer(load_only=True) student = fields.Nested(StudentSchema, dump_only=True) student_id = fields.Integer(load_only=True, required=True) status = EnumField(AttendanceStatus) @post_load def get_obj(self, data, **kwargs): return Attendance(**data) def to_int(self, value, **kwargs): if isinstance(value, (datetime, date)): return value.timestamp()
class AttachmentResultSchema(ResultSchemaBase): #: The record type type: SearchTarget = EnumField(SearchTarget, validate=require_search_target(SearchTarget.attachment)) #: The attachment id attachment_id = fields.Int(required=True) #: The attachment folder id folder_id = fields.Int(required=True) #: The attachment event id event_id = fields.Int(required=True) #: The attachment contribution id contribution_id = fields.Int(missing=None) #: The attachment sub-contribution id subcontribution_id = fields.Int(missing=None) #: The attachment title title = fields.String(required=True) #: The attachment filename filename = fields.String(missing=None) #: The attachment author user: PersonSchema = fields.Nested(PersonSchema, missing=None) #: The attachment type attachment_type: AttachmentType = EnumField(AttachmentType, required=True) #: The attachment last modified date time modified_dt = fields.DateTime(required=True) # extra fields that are not taken from the data returned by the search engine url = fields.Method('_get_url') event_path = fields.Method('_get_event_path', dump_only=True) def _get_url(self, data): return url_for('attachments.download', event_id=data['event_id'], contrib_id=data['contribution_id'], subcontrib_id=data['subcontribution_id'], folder_id=data['folder_id'], attachment_id=data['attachment_id'], filename=(data['filename'] or 'go')) def _get_event_path(self, data): if not (folder := AttachmentFolder.get(data['folder_id'])): return [] return _get_event_path(folder)
class AgencySchema(mm.Schema): agency_id = mm.fields.Int(required=True) agency_name = mm.fields.Str(required=True) agency_url = mm.fields.Url(required=True) agency_timezone = EnumField(mbta_models.TimeZone, required=True) agency_lang = EnumField(mbta_models.LangCode) agency_phone = mm.fields.Str() @mm.pre_load def convert_input(self, in_data: typing.Dict, **kwargs) -> typing.Dict: in_data["agency_timezone"] = schema_utils.timezone_enum_key( in_data["agency_timezone"]) in_data["agency_lang"] = in_data.get("agency_lang", "").lower() return {k: v for k, v in in_data.items() if v} @mm.post_load def make_agency(self, data: typing.Dict, **kwargs) -> mbta_models.Agency: return mbta_models.Agency( data.pop("agency_id"), data.pop("agency_name"), data.pop("agency_url"), data.pop("agency_timezone"), **data, )
class TaskSchema(ma.Schema): class Meta: fields = ["id", "name", "title", "type", "state", "lane", "form", "documentation", "data", "multi_instance_type", "multi_instance_count", "multi_instance_index", "process_name", "properties"] multi_instance_type = EnumField(MultiInstanceType) documentation = marshmallow.fields.String(required=False, allow_none=True) form = marshmallow.fields.Nested(FormSchema, required=False, allow_none=True) title = marshmallow.fields.String(required=False, allow_none=True) process_name = marshmallow.fields.String(required=False, allow_none=True) lane = marshmallow.fields.String(required=False, allow_none=True) @marshmallow.post_load def make_task(self, data, **kwargs): return Task(**data)
class SectionSessionSchema(Schema): id = fields.Integer() start = fields.Time() end = fields.Time() day_of_week = EnumField(WeekDay, required=True) section = fields.Nested(SectionSchema) @validates_schema def validate_session(self, data, **kwargs): if data['start'] >= data['end']: raise ValidationError('start must be less than end') @post_load def get_obj(self, data, **kwargs): return SectionSession(**data)
class ExperienceSchema(Schema): id = fields.Integer(dump_only=True) description = fields.String(allow_none=True) host = fields.String(required=True) title = fields.String(required=True) degree = fields.String(allow_none=True) degree_other = fields.String(allow_none=True) link = fields.String(allow_none=True) link_name = fields.String(allow_none=True) is_current = fields.Boolean(dump_only=True) start_month = EnumField(Month, by_value=True, required=True) start_year = fields.Integer(required=True) end_month = EnumField(Month, by_value=True, required=True) end_year = fields.Integer(required=True) length_year = fields.Integer(dump_only=True) length_month = fields.Integer(dump_only=True) type = EnumField(Type, by_value=True) contact_id = fields.Integer(required=True) location = fields.String(allow_none=True) achievements = fields.Nested(AchievementSchema, many=True) skills = fields.Nested(SkillSchema, many=True) class Meta: unknown = EXCLUDE
class StationaryItem_Schema(ma.ModelSchema): stationaryItemType = EnumField(StationaryItemTypeEnum) class Meta: fields = ( "stationaryItemId", "stationaryItemType", "electionId", "available" ) model = StationaryItem.Model # optionally attach a Session # to use for deserialization sqla_session = db.session
class StopTimeSchema(mm.Schema): trip_id = fk.StringForeignKey(mbta_models.Trip, required=True) arrival_time = mm.fields.Int(required=True) departure_time = mm.fields.Int(required=True) stop_id = fk.StringForeignKey(mbta_models.Stop, required=True) stop_sequence = mm.fields.Int(required=True) stop_headsign = mm.fields.Str() pickup_type = EnumField(mbta_models.PickupDropOffType) drop_off_type = EnumField(mbta_models.PickupDropOffType) shape_dist_traveled = mm.fields.Float() timepoint = bv.BinaryValue() checkpoint_id = fk.StringForeignKey(mbta_models.Checkpoint) @mm.pre_load def convert_input(self, in_data: typing.Dict, **kwargs) -> typing.Dict: in_data["arrival_time"] = schema_utils.time_as_seconds( in_data["arrival_time"]) in_data["departure_time"] = schema_utils.time_as_seconds( in_data["departure_time"]) in_data["pickup_type"] = schema_utils.numbered_type_enum_key( in_data["pickup_type"], default_0=True) in_data["drop_off_type"] = schema_utils.numbered_type_enum_key( in_data["drop_off_type"], default_0=True) return {k: v for k, v in in_data.items() if v} @mm.post_load def make_stop_time(self, data: typing.Dict, **kwargs) -> mbta_models.StopTime: return mbta_models.StopTime( trip_id=data.pop("trip_id"), arrival_time=data.pop("arrival_time"), departure_time=data.pop("departure_time"), stop_id=data.pop("stop_id"), stop_sequence=data.pop("stop_sequence"), **data, )
class TransactionSchema(Schema): transaction_date = fields.Function( lambda obj: obj.transaction_date) # Keep datetime format transaction_type = EnumField(TransactionType, dump_by=EnumField.VALUE) order = fields.Str() isin = fields.Str() mic = fields.Str() name = fields.Str() quantity = fields.Float() price = fields.Float() gross_amount = fields.Float() fee = fields.Float() transaction_tax = fields.Float() net_cashflow = fields.Float() notes = fields.Str()
class _EnvironmentStepExecutionSchema(BaseSchema): environment_id = fields.UUID(data_key="environmentId", required=True) environment_step_id = fields.UUID(data_key="environmentStepId", required=True) environment_name = fields.String(data_key="environmentName", required=True) command = fields.String(required=True) state = EnumField(EnvironmentStepExecutionState, by_value=True, required=True) started_at = fields.DateTime(data_key="startedAt", missing=None) ended_at = fields.DateTime(data_key="endedAt", missing=None) @post_load def make_environment_step_execution(self, data, **kwargs): return EnvironmentStepExecution(**data)
class StudySchema(ModelSchema): class Meta(ModelSchema.Meta): model = Study fields = ('id', 'title', 'short_title', 'short_description', 'image_url', 'last_updated', 'description', 'participant_description', 'benefit_description', 'coordinator_email', 'organization_name', 'location', 'status', 'study_categories', 'study_investigators', 'eligibility_url', 'survey_url', 'results_url', 'ages', 'languages', 'num_visits', '_links') status = EnumField(Status) study_categories = ma.Nested(CategoriesOnStudySchema(), many=True, dump_only=True) study_investigators = ma.Nested(InvestigatorsOnStudySchema(), many=True, dump_only=True) _links = ma.Hyperlinks({ 'self': ma.URLFor('api.studyendpoint', id='<id>'), 'collection': ma.URLFor('api.studylistendpoint'), 'categories': ma.UrlFor('api.categorybystudyendpoint', study_id='<id>') })
class UserExportSchema(ModelSchema): """ Used exclusively for data export, removes identifying information""" class Meta: model = User fields = ('id', 'last_updated', 'role', 'email_verified', 'email', '_links') ordered = True include_fk = True role = EnumField(Role) email = fields.Method("obfuscate_email") _links = ma.Hyperlinks({ 'self': ma.URLFor('api.userendpoint', id='<id>'), }) def obfuscate_email(self, obj): return obj.id
class DateSchema(Schema): '''Date object schema''' # YYYY,YYYY-MM-DD, YYYY-MM-DDThh:mm:ssTZD or any other format or level of granularity described in W3CDTF. # Use RKMS-ISO8601 standard for depicting date ranges. date = fields.Date() # DateTypeEnum dateType = EnumField(DateTypeEnum, required=True) # Specific information about the date dateInformation = fields.String() @post_load def make_date(self, data): '''Return Date object after loading''' return Date(**data)
class NodeSchema(Schema): command_line = fields.Str() compute_id = fields.Str() console = fields.Int() console_host = fields.Str() console_type = EnumField(ConsoleType, by_value=True) first_port_name = fields.Str() height = fields.Int() label = fields.Nested(Label) name = fields.Str() node_directory = fields.Str() node_id = fields.UUID() node_type = EnumField(NodeType, by_value=True) port_name_format = fields.Str() port_segment_size = fields.Str() ports = fields.Nested(Port, many=True) project_id = fields.UUID() properties = fields.Nested(NodeProperties) status = EnumField(NodeStatus, by_value=True) symbol = fields.Str() width = fields.Int() x = fields.Int() y = fields.Int() z = fields.Int()
class CommentSchema(ma.ModelSchema): user = fields.Nested(simple_user_schema) status = EnumField(CommentStatus) @pre_dump def deleted_comment(self, data): if data.is_deleted: data.content = '삭제된 댓글입니다.' return data class Meta: strict = True model = Comment sqla_session = db.session
class UserProfileSchema(DistributeIdSchema): email = fields.Email() role_id = fields.Integer(dump_only=True) avatar = fields.String() birthday = fields.DateTime() city = fields.String() gender = EnumField(Gender, by_value=True) facebook_id = fields.String() google_id = fields.String() full_name = fields.String() phone_number = fields.String() role = fields.Nested(RoleSchema, dump_only=True)
class DatasetVersionLightSchema(ma.ModelSchema): class Meta: additional = ( "id", "name", "dataset_id", "creation_date", "creator", "description", "version", "reason_state", ) creator = ma.Nested(UserNamedIdSchema) state = EnumField(DatasetVersion.DatasetVersionState)
class SecurityInfoResponse(CommandResponse): HardwareEncryptionCaps = EnumField(HardwareEncryptionCaps) PasscodePresent = fields.Boolean() PasscodeCompliant = fields.Boolean() PasscodeCompliantWithProfiles = fields.Boolean() PasscodeLockGracePeriodEnforced = fields.Integer() FDE_Enabled = fields.Boolean() FDE_HasPersonalRecoveryKey = fields.Boolean() FDE_HasInstitutionalRecoveryKey = fields.Boolean() FDE_PersonalRecoveryKeyCMS = fields.String() FDE_PersonalRecoveryKeyDeviceKey = fields.String() FirewallSettings = fields.Nested(FirewallSettings) SystemIntegrityProtectionEnabled = fields.Boolean() FirmwarePasswordStatus = fields.Nested(FirmwarePasswordStatus) ManagementStatus = fields.Nested(ManagementStatus)
class CategorySchema(ma.Schema): tags = EnumField(Tags, by_value=True) class Meta: # Fields to expose # model = StoreModel fields = ('id', 'percentage', 'tags', 'total', 'remaining', 'user_id', 'links') # model = StoreModel # item = ma.Nested(ItemSchema) links = ma.Hyperlinks({ # 'self': ma.URLFor('item', store_id ='<id>', id='<id>'), 'collection': ma.URLFor('items', category_id='<id>') })
class BlockedRoomSchema(mm.ModelSchema): room = Nested(RoomSchema, only=('id', 'name', 'sprite_position', 'full_name')) state = EnumField(BlockedRoomState) class Meta: model = BlockedRoom fields = ('room', 'state', 'rejection_reason', 'rejected_by') @post_dump(pass_many=True) def sort_rooms(self, data, many): if many: data = sorted( data, key=lambda x: natural_sort_key(x['room']['full_name'])) return data
class OpportunitySchema(Schema): id = fields.String(required=True, dump_only=True) title = fields.String(required=True) short_description = fields.String(required=True) gdoc_link = fields.String(required=True) status = EnumField(OpportunityStage, dump_only=True) org_name = fields.String(required=True) program_name = fields.String(allow_none=True) program_id = fields.Integer(allow_none=True) is_active = fields.Boolean(dump_only=True) applications = fields.Nested(OpportunityAppSchema( exclude=('opportunity', 'resume'), many=True)) class Meta: unknown = EXCLUDE
def test_deserialize_enum(self): field = EnumField(EnumTester, by_value=True) assert field._deserialize(1, None, {}) == EnumTester.one
def setup(self): self.field = EnumField(EnumTester)
def test_serialize_enum(self): field = EnumField(EnumTester, by_value=True) assert field._serialize(EnumTester.one, None, object()) == 1
def test_serialize_none(self): field = EnumField(EnumTester, by_value=True) assert field._serialize(None, None, object()) is None
def test_deserialize_nonexistent_member(self): field = EnumField(EnumTester, by_value=True) with pytest.raises(ValidationError): field._deserialize(4, None, {})