def test_parse_convert_drop_tzinfo(): field = DateTimeType(tzd='require', convert_tz=True, drop_tzinfo=True) dt = field.to_native('2015-11-08T12:34:56.0369-0730') assert dt == datetime(2015, 11, 8, 20, 4, 56, 36900) dt = field.to_native('2015-11-08 12:34:56.00Z') assert dt == datetime(2015, 11, 8, 12, 34, 56, 0)
def test_datetime_primitive(): output = '2013.03.07 15:31' dt = datetime.datetime(2013, 3, 7, 15, 31) dt_type = DateTimeType(serialized_format='%Y.%m.%d %H:%M') assert dt_type(dt.isoformat()) == dt assert dt_type.to_primitive(dt) == output obj = DateTimeType(serialized_format=str) assert obj.to_primitive(123) == '123'
def test_parse_require_tz(): field = DateTimeType(tzd='require') with pytest.raises(ConversionError): dt = field.to_native('2015-11-08 12:34:56.00') dt = field.to_native('2015-11-08 12:34:56.00Z') assert dt == datetime(2015, 11, 8, 12, 34, 56, tzinfo=UTC)
def test_parse_from_timestamp(): field = DateTimeType() dt = field.to_native('1446991200.7777') assert dt == datetime(2015, 11, 8, 14, 00, microsecond=777700, tzinfo=UTC) field = DateTimeType(convert_tz=True, drop_tzinfo=True) dt = field.to_native('1446991200.7777') assert dt == datetime(2015, 11, 8, 14, 00, microsecond=777700)
def test_parse_convert(): field = DateTimeType(convert_tz=True) dt = field.to_native('2015-11-08T12:34') assert dt == datetime(2015, 11, 8, 12, 34) dt = field.to_native('2015-11-08T12:34:56.0369-0730') assert dt == datetime(2015, 11, 8, 20, 4, 56, 36900, tzinfo=UTC) dt = field.to_native('2015-11-08 12:34:56,00Z') assert dt == datetime(2015, 11, 8, 12, 34, 56, 0, tzinfo=UTC)
def test_parse_using_formats(): formats = ('%Y-%m-%dT%H:%M:%S.%fZ', '%Y-%m-%dT%H:%M:%S.%f%z') field = DateTimeType(formats=formats) dt = field.to_native('2015-11-08T12:34:56.99Z') assert dt == datetime(2015, 11, 8, 12, 34, 56, 990000) if sys.version_info[0] >= 3: # strptime() supports the '%z' directive starting with Python 3.2. dt = field.to_native('2015-11-08T12:34:56.099-0700') assert dt.utcoffset() == timedelta(hours=-7) assert dt.replace(tzinfo=None) == datetime(2015, 11, 8, 12, 34, 56, 99000)
def test_to_primitive(): dt = datetime(2015, 11, 8, 12, 34, 56, 36900, tzinfo=DateTimeType.offset_timezone(-7, -30)) assert DateTimeType().to_primitive(dt) == '2015-11-08T12:34:56.036900-0730' assert DateTimeType(serialized_format='%Y-%m-%d %H:%M:%S').to_primitive(dt) \ == '2015-11-08 12:34:56'
class Message(NewMessage): """Existing message parameter.""" user_id = UUIDType() message_id = UUIDType(required=True) date_insert = DateTimeType(required=True) text = StringType() class Options: roles = {'default': blacklist('user_id')}
class RedisNode(Model): node_name = StringType() status = StringType() current_role = StringType(serialize_when_none=False) port = IntType() endpoint = StringType() arn = StringType() parameter_group_status = StringType() zone = StringType() created_on = DateTimeType()
class Discussion(Model): """Existing discussion.""" user_id = UUIDType() discussion_id = UUIDType(required=True) date_insert = DateTimeType(serialized_format=helpers.RFC3339Milli, tzd=u'utc') date_update = DateTimeType(serialized_format=helpers.RFC3339Milli, tzd=u'utc') excerpt = StringType(required=True) importance_level = IntType(required=True, default=0) participants = ListType(ModelType(Participant), default=lambda: []) total_count = IntType(required=True, default=0) unread_count = IntType(required=True, default=0) attachment_count = IntType(default=0) class Options: roles = {'default': blacklist('user_id')} serialize_when_none = False
class TargetTCPProxy(Model): id = StringType() name = StringType() description = StringType(default='') self_link = StringType(deserialize_from='selfLink', serialize_when_none=False) region = StringType(default='global') service = StringType() proxy_header = StringType(choices=['NONE', 'PROXY_V1'], deserialize_from='proxyHeader', serialize_when_none=False) creation_timestamp = DateTimeType(deserialize_from='creationTimestamp', serialize_when_none=False) kind = StringType()
class CityHallBidItem(BaseModel): category = StringType() month = IntType(min_value=1, max_value=12) year = IntType(min_value=1873) # quando Feira virou cidade :) description = StringType() history = ListType(DictType(StringType)) modality = StringType() date = DateTimeType(formats=("%d/%m/%Y %Hh%M")) file_urls = ListType(StringType) file_content = StringType()
class CityHallBidItem(BaseModel): public_agency = StringType() month = IntType(min_value=1, max_value=12) year = IntType(min_value=1873) # quando Feira virou cidade :) description = StringType() history = ListType(DictType(StringType)) codes = StringType() modality = StringType() session_at = DateTimeType() files = ListType(StringType)
class LaunchConfiguration(Model): launch_configuration_name = StringType( deserialize_from="LaunchConfigurationName", serialize_when_none=False) launch_configuration_arn = StringType( deserialize_from="LaunchConfigurationARN", serialize_when_none=False) image_id = StringType(deserialize_from="ImageId", serialize_when_none=False) key_name = StringType(deserialize_from="KeyName", serialize_when_none=False) security_groups = ListType(StringType, deserialize_from="SecurityGroups", serialize_when_none=False) classic_link_vpc_id = StringType(deserialize_from="ClassicLinkVPCId", serialize_when_none=False) classic_link_vpc_security_groups = ListType( StringType, deserialize_from="ClassicLinkVPCSecurityGroups", serialize_when_none=False) user_data = StringType(deserialize_from="UserData", serialize_when_none=False) instance_type = StringType(deserialize_from="InstanceType", serialize_when_none=False) kernel_id = StringType(deserialize_from="KernelId", serialize_when_none=False) ramdisk_id = StringType(deserialize_from="RamdiskId", serialize_when_none=False) block_device_mappings = ListType( ModelType(AutoScalingLaunchConfigurationBlockDeviceMappings), deserialize_from="BlockDeviceMappings", serialize_when_none=False) instance_monitoring = ModelType(InstanceMonitoring, deserialize_from="InstanceMonitoring", serialize_when_none=False) spot_price = StringType(deserialize_from="SpotPrice", serialize_when_none=False) iam_instance_profile = StringType(deserialize_from="IamInstanceProfile", serialize_when_none=False) created_time = DateTimeType(deserialize_from="CreatedTime", serialize_when_none=False) ebs_optimized = BooleanType(deserialize_from="EbsOptimized", serialize_when_none=False) associate_public_ip_address = BooleanType( deserialize_from="AssociatePublicIpAddress", serialize_when_none=False) placement_tenancy = StringType(deserialize_from="PlacementTenancy", serialize_when_none=False) region_name = StringType(serialize_when_none=False) account_id = StringType(serialize_when_none=False) def reference(self, region_code): return { "resource_id": self.launch_configuration_arn, "external_link": f"https://console.aws.amazon.com/ec2/autoscaling/home?region={region_code}#LaunchConfigurations:id={self.launch_configuration_name}" }
class NATGateway(Model): arn = StringType(default="") name = StringType(default="") create_time = DateTimeType(deserialize_from="CreateTime") delete_time = DateTimeType(deserialize_from="DeleteTime") failure_code = StringType(deserialize_from="FailureCode") failure_message = StringType(deserialize_from="FailureMessage") nat_gateway_addresses = ListType(ModelType(NATGatewayNatGatewayAddresses), deserialize_from="NatGatewayAddresses") nat_gateway_id = StringType(deserialize_from="NatGatewayId") provisioned_bandwidth = ModelType(ProvisionedBandwidth, deserialize_from="ProvisionedBandwidth") state = StringType(deserialize_from="State", choices=("pending", "failed", "available", "deleting", "deleted")) subnet_id = StringType(deserialize_from="SubnetId") vpc_id = StringType(deserialize_from="VpcId") tags = ListType(ModelType(Tags), deserialize_from="Tags", default=[]) account_id = StringType(default="") cloudwatch = ModelType(CloudWatchModel, serialize_when_none=False) def reference(self, region_code): return { "resource_id": self.arn, "external_link": f"https://console.aws.amazon.com/vpc/home?region={region_code}#NatGateways:natGatewayId={self.nat_gateway_id}" } def set_cloudwatch(self, region_code): return { "namespace": "AWS/NATGateway", "dimensions": [ CloudWatchDimensionModel({ 'Name': 'NatGatewayId', 'Value': self.nat_gateway_id }) ], "region_name": region_code }
class Disk(Model): project = StringType() id = StringType() name = StringType() zone = StringType() disk_type = StringType(choices=('local-ssd', 'pd-balanced', 'pd-ssd', 'pd-standard'), serialize_when_none=False) read_iops = FloatType(serialize_when_none=False) write_iops = FloatType(serialize_when_none=False) read_throughput = FloatType(serialize_when_none=False) write_throughput = FloatType(serialize_when_none=False) in_used_by = ListType(StringType(), default=[]) source_image_display = StringType(serialize_when_none=False) source_image_id = StringType(deserialize_from='sourceImageId', serialize_when_none=False) source_image = StringType(deserialize_from='sourceImage', serialize_when_none=False) status = StringType(choices=('INVALID', 'CREATING', 'machine_image_conn', 'DELETING', 'UPLOADING')) encryption = StringType(choices=('Google managed', 'Customer managed, Customer supplied')) size = FloatType() region = StringType() fingerprint = StringType(deserialize_from='labelFingerprint') snapshot_schedule_display = ListType(StringType(), default=[]) snapshot_schedule = ListType(ModelType(SnapShotSchedule), default=[]) self_link = StringType(deserialize_from='selfLink') labels = ListType(ModelType(Labels), default=[]) creation_timestamp = DateTimeType(deserialize_from='creationTimestamp') last_attach_timestamp = DateTimeType( deserialize_from='lastAttachTimestamp', serialize_when_none=False) last_detach_timestamp = DateTimeType( deserialize_from='lastDetachTimestamp', serialize_when_none=False) def reference(self): return { "resource_id": self.self_link, "external_link": f"https://console.cloud.google.com/compute/disksDetail/zones/{self.zone}/disks/{self.name}?project={self.project}" }
class LoadBalancer(Model): load_balancer_arn = StringType(deserialize_from="LoadBalancerArn") dns_name = StringType(deserialize_from="DNSName") canonical_hosted_zone_id = StringType( deserialize_from="CanonicalHostedZoneId") created_time = DateTimeType(deserialize_from="CreatedTime") load_balancer_name = StringType(deserialize_from="LoadBalancerName") scheme = StringType(deserialize_from="Scheme", choices=("internet-facing", "internal")) vpc_id = StringType(deserialize_from="VpcId") state = ModelType(State, deserialize_from="State") type = StringType(deserialize_from="Type", choices=("application", "network")) availability_zones = ListType(ModelType(LoadBalancerAvailabilityZones), deserialize_from="AvailabilityZones") security_groups = ListType(StringType, deserialize_from="SecurityGroups", default=[]) ip_address_type = StringType(deserialize_from="IpAddressType", choices=("ipv4", "dualstack")) account_id = StringType(default="") tags = ListType(ModelType(Tags), default=[]) listeners = ListType(ModelType(Listener)) attributes = ModelType(LoadBalancerAttributes) cloudwatch = ModelType(CloudWatchModel, serialize_when_none=False) def reference(self, region_code): return { "resource_id": self.load_balancer_arn, "external_link": f"https://console.aws.amazon.com/ec2/v2/home?region={region_code}#LoadBalancers:search={self.load_balancer_arn};sort=loadBalancerName" } def set_cloudwatch(self, region_code): namespace = '' _arn = arnparse(self.load_balancer_arn) dimensions = [ CloudWatchDimensionModel({ 'Name': 'LoadBalancer', 'Value': _arn.resource }) ] if self.type == 'application': namespace = 'AWS/ApplicationELB' elif self.type == 'network': namespace = 'AWS/NetworkELB' return { "namespace": namespace, "dimensions": dimensions, "region_name": region_code }
class TestDoc(Model): can_future = BooleanType() publish = DateTimeType() foo = StringType() def validate_publish(self, data, dt, context): if dt > datetime.datetime(2012, 1, 1, 0, 0) and not data['can_future']: raise ValidationError(future_error_msg) def validate_foo(self, data, dt): # without context param pass
class ContributorInsight(Model): table_name = StringType(deserialize_from="TableName") index_name = StringType(deserialize_from="IndexName") contributor_insights_rule_list = ListType( StringType, deserialize_from="ContributorInsightsRuleList") contributor_insights_status = StringType( deserialize_from="ContributorInsightsStatus", choices=("ENABLING", "ENABLED", "DISABLING", "DISABLED", "FAILED")) last_update_date_time = DateTimeType(deserialize_from="LastUpdateDateTime") failure_exception = ModelType(FailureException, deserialize_from="FailureException")
class TargetHttpProxy(Model): id = StringType() name = StringType() description = StringType(default='') self_link = StringType(deserialize_from='selfLink', serialize_when_none=False) url_map = StringType(deserialize_from='urlMap', serialize_when_none=False) region = StringType(default='global') kind = StringType() proxy_bind = BooleanType(deserialize_from='proxyBind', serialize_when_none=False) finger_print = StringType(deserialize_from='fingerprint', serialize_when_none=False) creation_timestamp = DateTimeType(deserialize_from='creationTimestamp', serialize_when_none=False)
class Patient(Model): """ A model class for patients """ name = NameType() age = AgeType() gender = GenderType() condition = ConditionType() doctor = NameType() blood_group = BloodGroupType() insured = BooleanType(default=True) last_visit = DateTimeType(default='2000-01-01T13:30:30')
class CortxUser(BaseModel): _id = "user_id" user_id = StringType() user_type = StringType() user_role = StringType() password_hash = StringType() email = StringType() alert_notification = BooleanType() updated_time = DateTimeType() created_time = DateTimeType() def update(self, new_values: dict): if 'password' in new_values: self.password_hash = 'dummyhash' new_values.pop('password') for key in new_values: setattr(self, key, new_values[key]) self.updated_time = datetime.now(timezone.utc)
class PredictionDTO(Model): """ Describes JSON of a set of predictions from a model """ prediction_id = IntType(serialized_name='predictionsId') created = DateTimeType() model_id = IntType(serialized_name='modelId', required=True) version_id = IntType(serialized_name='versionId', required=True) version_string = StringType(serialized_name='versionString') dockerhub_hash = StringType(serialized_name='dockerhubHash') bbox = ListType(FloatType, required=True) tile_zoom = IntType(serialized_name='tileZoom', required=True)
class Update(Model): id = StringType(deserialize_from="id") status = StringType(deserialize_from="status", choices=("InProgress", "Failed", "Cancelled", "Successful")) type = StringType(deserialize_from="type", choices=("VersionUpdate", "EndpointAccessUpdate", "LoggingUpdate", "ConfigUpdate")) params = ListType(ModelType(UpdateParams), deserialize_from="params") created_at = DateTimeType(deserialize_from="createdAt") errors = ListType(ModelType(UpdateErrors), deserialize_from="errors")
class Processed(Model): _name = 'processed' id = IntType(required=False) city, country = StringType(required=True) c_min = IntType(required=False) c_max = IntType(required=False) c_current = IntType(required=False) status = IntType(required=False) wind = IntType(required=False) time = DateTimeType(required=True, default=datetime.now()) user = StringType(required=False)
class ClusterCacheNodes(Model): cache_node_id = StringType(deserialize_from="CacheNodeId") cache_node_status = StringType(deserialize_from="CacheNodeStatus") cache_node_create_time = DateTimeType( deserialize_from="CacheNodeCreateTime") endpoint = ModelType(Endpoint, deserialize_from="Endpoint") parameter_group_status = StringType( deserialize_from="ParameterGroupStatus") source_cache_node_id = StringType(deserialize_from="SourceCacheNodeId") customer_availability_zone = StringType( deserialize_from="CustomerAvailabilityZone")
class Consumers(Model): consumers_num = IntType() consumer_name = StringType(deserialize_from="ConsumerName") consumer_arn = StringType(deserialize_from="ConsumerARN") consumer_status = StringType( deserialize_from="ConsumerStatus", choices=("CREATING", "DELETING", "ACTIVE") ) consumer_status_display = StringType(choices=("Creating", "Deleting", "Active")) consumer_creation_timestamp = DateTimeType( deserialize_from="ConsumerCreationTimestamp" )
class WorkflowModel(BaseModel): _id = UUIDType(required=True) name = StringType() created_at = DateTimeType(default=datetime.datetime.now()) processing_started_at = DateTimeType() processing_ended_at = DateTimeType() training_data = DictType(BaseType, {}) preprocessing = ListType(StringType, default=list()) model_processing = DictType(BaseType, default={'type': 'supervised'}) validation = DictType(BaseType, default={'type': 'fold', 'value': 3}) trained_models = DictType(BaseType, {}) fi_booster = StringType() validation_details = DictType(BaseType, default={}) state = StringType(default='new') MONGO_COLLECTION = 'workflows'
class AffectedResource(Model): entity_arn = StringType(deserialize_from='entityArn') event_arn = StringType(deserialize_from='eventArn') entity_value = StringType() entity_type = StringType(choices=('account', 'resource')) entity_url = StringType(deserialize_from='entityUrl', serialize_when_none=False) aws_account_id = StringType(deserialize_from='awsAccountId') last_update_time = DateTimeType(deserialize_from='lastUpdatedTime') status_code = StringType(deserialize_from='statusCode', choices=('IMPAIRED', 'UNIMPAIRED', 'UNKNOWN')) tags = ListType(ModelType(Tags), default=[])
class Contact(NewContact): """Existing contact.""" addresses = ListType(ModelType(PostalAddress), default=lambda: []) avatar = StringType(default='avatar.png') contact_id = UUIDType() date_insert = DateTimeType(serialized_format=helpers.RFC3339Milli, tzd=u'utc') date_update = DateTimeType(serialized_format=helpers.RFC3339Milli, tzd=u'utc') deleted = DateTimeType(serialized_format=helpers.RFC3339Milli, tzd=u'utc') emails = ListType(ModelType(Email), default=lambda: []) identities = ListType(ModelType(SocialIdentity), default=lambda: []) ims = ListType(ModelType(IM), default=lambda: []) organizations = ListType(ModelType(Organization), default=lambda: []) phones = ListType(ModelType(Phone), default=lambda: []) pi = ModelType(PIParameter) user_id = UUIDType() class Options: serialize_when_none = False
class NodeGroup(Model): nodegroup_name = StringType(deserialize_from="nodegroupName") nodegroup_arn = StringType(deserialize_from="nodegroupArn") cluster_name = StringType(deserialize_from="clusterName") version = StringType(deserialize_from="version") release_version = StringType(deserialize_from="releaseVersion") created_at = DateTimeType(deserialize_from="createdAt") modified_at = DateTimeType(deserialize_from="modifiedAt") status = StringType(deserialize_from="status", choices=("CREATING", "ACTIVE", "UPDATING", "DELETING", "CREATE_FAILED", "DELETE_FAILED", "DEGRADED")) scaling_config = ModelType(scalingConfig, deserialize_from="scalingConfig") instance_types = ListType(StringType, deserialize_from="instanceTypes") subnets = ListType(StringType, deserialize_from="subnets") remote_access = ModelType(remoteAccess, deserialize_from="remoteAccess") ami_type = StringType(deserialize_from="amiType", choices=("AL2_x86_64", "AL2_x86_64_GPU")) node_role = StringType(deserialize_from="nodeRole") labels = ModelType(labels, deserialize_from="labels") resources = ModelType(resources, deserialize_from="resources") disk_size = IntType(deserialize_from="diskSize") health = ModelType(health, deserialize_from="health") tags = ModelType(Tags, deserialize_from="tags")
class RelationDatabase(ResourceBase): relation_database_blueprint_id = StringType( deserialize_from="relationalDatabaseBlueprintId", serialize_when_none=False) relation_database_bundle_id = StringType( deserialize_from="relationalDatabaseBundleId", serialize_when_none=False) master_database_name = StringType(deserialize_from="masterDatabaseName", serialize_when_none=False) hardware = ModelType(RelationDatabaseHardware, serialize_when_none=False) state = StringType(serialize_when_none=False) secondary_availability_zone = StringType( deserialize_from="secondaryAvailabilityZone", serialize_when_none=False) backup_retention_enabled = BooleanType( deserialize_from="backupRetentionEnabled", serialize_when_none=False) pending_modified_values = ModelType( PendingModifiedValues, deserialize_from="pendingModifiedValues", serialize_when_none=False) engine = StringType(serialize_when_none=False) engine_version = StringType(deserialize_from="engineVersion", serialize_when_none=False) latest_restorable_time = DateTimeType( deserialize_from="latestRestorableTime", serialize_when_none=False) master_user_name = StringType(deserialize_from="masterUsername", serialize_when_none=False) parameter_apply_status = StringType( deserialize_from="parameterApplyStatus", serialize_when_none=False) preferred_backup_window = StringType( deserialize_from="preferredBackupWindow", serialize_when_none=False) preferred_maintenance_window = StringType( deserialize_from="preferredMaintenanceWindow", serialize_when_none=False) publicly_accessible = BooleanType(deserialize_from="publiclyAccessible", serialize_when_none=False) master_endpoint = ModelType(MasterEndpoint, deserialize_from="masterEndpoint", serialize_when_none=False) pending_maintenance_actions = ListType( ModelType(PendingMaintenanceActions), deserialize_from="pendingMaintenanceActions", serialize_when_none=False) ca_certificate_identifier = StringType( deserialize_from="caCertificateIdentifier", serialize_when_none=False) def reference(self, region_code): return { "resource_id": self.arn, "external_link": f"https://lightsail.aws.amazon.com/ls/webapp/{region_code}/databases/{self.name}/connect" }
class Compute(Model): keypair = StringType() az = StringType() instance_state = StringType(choices=('STARTING', 'RUNNING', 'STOPPING', 'STOPPED', 'DEALLOCATING', 'DEALLOCATED')) instance_type = StringType() launched_at = DateTimeType() instance_id = StringType(default='') instance_name = StringType(default='') security_groups = ListType(ModelType(SecurityGroups)) image = StringType() account = StringType(default='') tags = ModelType(ComputeTags, default={})
class TransitGatewayRouteTables(Model): transit_gateway_route_table_id = StringType( deserialize_from="TransitGatewayRouteTableId") transit_gateway_id = StringType(deserialize_from="TransitGatewayId") state = StringType(deserialize_from="State", choices=("pending", "available", "deleting", "deleted")) default_association_route_table = BooleanType( deserialize_from="DefaultAssociationRouteTable") default_propagation_route_table = BooleanType( deserialize_from="DefaultPropagationRouteTable") creation_time = DateTimeType(deserialize_from="CreationTime") tags = ListType(ModelType(Tags), deserialize_from="Tags", default=[])
class TCMBADocumentItem(Model): crawled_at = DateTimeType(required=True) category = StringType() filename = StringType(required=True) original_filename = StringType(required=True) filepath = StringType(required=True) inserted_by = StringType() inserted_at = DateType(formats=("%d/%m/%Y", "%d/%m/%y")) unit = StringType(required=True) month = StringType() year = StringType() period = StringType()
class User(NewUser): """Existing user.""" user_id = UUIDType(required=True) password = StringType() # not outpout by default, not required date_insert = DateTimeType() given_name = StringType() family_name = StringType() contact = ModelType(Contact) class Options: roles = {'default': blacklist('contact', 'password')}
class Compute(Model): keypair = StringType() ad = StringType() instance_state = StringType() launched_at = DateTimeType() instance_id = StringType(default='') instance_name = StringType(default='') account = StringType() image = StringType() instance_type = StringType() security_groups = ListType(DictType(StringType())) tags = ModelType(ComputeTags, default={})
def test_parse_reject_tzd(): field = DateTimeType(tzd='reject') with pytest.raises(ConversionError): field.to_native('2015-11-08T12:34+0200') with pytest.raises(ConversionError): field.to_native('2015-11-08T12:34Z') dt = field.to_native('2015-11-08T12:34') assert dt == datetime(2015, 11, 8, 12, 34)
def test_timestamp(): field = TimestampType() field_no_tz = TimestampType(drop_tzinfo=True) ts = field.to_primitive(datetime(2015, 11, 8, 14, 00)) assert ts == 1446991200.0 assert type(ts) == float ts = field_no_tz.to_primitive(datetime(2015, 11, 8, 14, 00)) assert ts == 1446991200.0 assert type(ts) == float ts = field.to_primitive(datetime(2014, 5, 8, 22, 40, 40, tzinfo=gettz('PST8PDT'))) assert ts == 1399614040.0 ts = field_no_tz.to_primitive(datetime(2014, 5, 8, 22, 40, 40, tzinfo=gettz('PST8PDT'))) assert ts == 1399614040.0 dt_with_tz = datetime(2015, 11, 8, 16, 00, tzinfo=DateTimeType.offset_timezone(2)) dt_no_tz = datetime(2015, 11, 8, 14, 00) dt_no_tz_usec = datetime(2015, 11, 8, 14, 00, microsecond=777700) assert field.to_primitive(dt_with_tz) == 1446991200.0 assert field_no_tz.to_primitive(dt_with_tz) == 1446991200.0 assert field.to_native(dt_with_tz) == dt_no_tz.replace(tzinfo=UTC) assert field_no_tz.to_native(dt_with_tz) == dt_no_tz assert field.to_native(1446991200.7777) == dt_no_tz_usec.replace(tzinfo=UTC) assert field_no_tz.to_native(1446991200.7777) == dt_no_tz_usec with pytest.raises(ConversionError): field.to_native(dt_no_tz) ts = field.to_primitive(dt_no_tz_usec) assert ts == 1446991200.7777 assert type(ts) == float ts = field.to_primitive(datetime(2014, 5, 8, 22, 40, 40, tzinfo=UTC)) assert ts == 1399588840.0 assert field.to_primitive(EPOCH) == 0 assert field.to_native(0) == EPOCH
def test_validate_tz(): dt_naive = lambda: datetime(2015, 6, 1, 14, 00) dt_utc = lambda: datetime(2015, 6, 1, 14, 00, tzinfo=UTC) dt_plustwo = lambda: datetime(2015, 6, 1, 16, 00, tzinfo=DateTimeType.offset_timezone(2)) dt_nyc = lambda: datetime(2015, 6, 1, 10, 00, tzinfo=NYC) all_values = [dt_naive, dt_utc, dt_plustwo, dt_nyc] def test_field(field, valid): for value in all_values: if value in valid: field.validate_tz(value()) else: with pytest.raises(ValidationError): field.validate_tz(value()) test_field(DateTimeType(tzd='allow'), [dt_naive, dt_utc, dt_plustwo, dt_nyc]) test_field(DateTimeType(convert_tz=True), [dt_naive, dt_utc]) test_field(DateTimeType(tzd='utc'), [dt_utc, dt_plustwo, dt_nyc]) test_field(DateTimeType(tzd='utc', convert_tz=True), [dt_utc]) test_field(DateTimeType(tzd='reject'), [dt_naive]) test_field(DateTimeType(tzd='require'), [dt_utc, dt_plustwo, dt_nyc]) test_field(DateTimeType(drop_tzinfo=True), [dt_naive])
def test_parse_with_defaults(): field = DateTimeType() dt = field.to_native('2015-11-08T12:34') assert dt == datetime(2015, 11, 8, 12, 34) dt = field.to_native('2015-11-08T12:34:00.1') assert dt == datetime(2015, 11, 8, 12, 34, 0, 100000) dt = field.to_native('2015-11-08T12:34:56,0369-0730') assert dt.utcoffset() == timedelta(hours=-7, minutes=-30) assert dt.replace(tzinfo=None) == datetime(2015, 11, 8, 12, 34, 56, 36900) assert dt == field.to_native(u'2015-11-08T12:34:56,0369−0730') # minus U+2212 dt = field.to_native('2015-11-08 12:34:56.00200+02:00') assert dt.utcoffset() == timedelta(hours=2) assert dt.replace(tzinfo=None) == datetime(2015, 11, 8, 12, 34, 56, 2000) dt = field.to_native('2015-11-08 12:34:56.00Z') assert dt.utcoffset() == timedelta(0) assert dt.replace(tzinfo=None) == datetime(2015, 11, 8, 12, 34, 56, 0)
def coercion(): dt_t = DateTimeType() dt = dt_t.to_native('2013-08-31T02:21:21.486072') print(dt, '\n', dt_t.to_primitive(dt))
def test_datetime_accepts_datetime(self): output = '2013.03.07 15:31' dt = datetime.datetime(2013, 3, 7, 15, 31) dt_type = DateTimeType(serialized_format='%Y.%m.%d %H:%M') self.assertEqual(dt_type(dt), dt) self.assertEqual(dt_type.to_primitive(dt), output)
def test_parse_utc(): field = DateTimeType(tzd='utc') dt = field.to_native('2015-11-08 12:34:56.00') assert dt == datetime(2015, 11, 8, 12, 34, 56, tzinfo=UTC)
def test_parse_reject_invalid_type(): field = DateTimeType() with pytest.raises(ConversionError): field.to_native(['2017-04-30'])
def test_mock(tzd, convert_tz, drop_tzinfo): field = DateTimeType(tzd=tzd, convert_tz=convert_tz, drop_tzinfo=drop_tzinfo) for _ in range(20): field.validate(field._mock())
def test_datetime_accepts_datetime(): output = '2013.03.07 15:31' dt = datetime.datetime(2013, 3, 7, 15, 31) dt_type = DateTimeType(serialized_format='%Y.%m.%d %H:%M') assert dt_type(dt) == dt assert dt_type.to_primitive(dt) == output
def test_to_native_from_datetime(): dt_naive_utc = datetime(2015, 6, 1, 14, 00) dt_utc = datetime(2015, 6, 1, 14, 00, tzinfo=UTC) dt_plustwo = datetime(2015, 6, 1, 16, 00, tzinfo=DateTimeType.offset_timezone(2)) dt_nyc = datetime(2015, 6, 1, 10, 00, tzinfo=NYC) field = DateTimeType(tzd='allow') assert field.to_native(dt_naive_utc) == dt_naive_utc assert field.to_native(dt_utc) == dt_utc assert field.to_native(dt_plustwo) == dt_plustwo assert field.to_native(dt_nyc) == dt_nyc field = DateTimeType(tzd='utc') assert field.to_native(dt_naive_utc) == dt_utc field = DateTimeType(tzd='reject') assert field.to_native(dt_naive_utc) == dt_naive_utc with pytest.raises(ConversionError): field.to_native(dt_utc) field = DateTimeType(tzd='require') assert field.to_native(dt_utc) == dt_utc with pytest.raises(ConversionError): field.to_native(dt_naive_utc) field = DateTimeType(tzd='require', convert_tz=True, drop_tzinfo=True) assert field.to_native(dt_naive_utc) == dt_naive_utc field = DateTimeType(convert_tz=True) assert field.to_native(dt_naive_utc) == dt_naive_utc assert field.to_native(dt_utc) == dt_utc assert field.to_native(dt_plustwo) == dt_utc assert field.to_native(dt_nyc) == dt_utc field = DateTimeType(convert_tz=True, drop_tzinfo=True) assert field.to_native(dt_naive_utc) == dt_naive_utc assert field.to_native(dt_utc) == dt_naive_utc assert field.to_native(dt_plustwo) == dt_naive_utc assert field.to_native(dt_nyc) == dt_naive_utc