Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
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)
dt = field.to_native(1446991200.7777)
assert dt == datetime(2015, 11, 8, 14, 00, microsecond=777700)
# -*- coding: utf-8 -*-
from datetime import datetime, timedelta
import sys
from dateutil.tz import gettz, tzutc
import pytest
from schematics.exceptions import ConversionError, ValidationError
from schematics.types import DateTimeType, UTCDateTimeType, TimestampType
UTC = DateTimeType.UTC
NYC = gettz('US/Eastern')
EPOCH = datetime(1970, 1, 1, 0, 0, tzinfo=UTC)
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)
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_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_model_validators():
now = datetime.datetime(2012, 1, 1, 0, 0)
future = now + datetime.timedelta(1)
assert future > now
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
TestDoc({'publish': now}).validate()
with pytest.raises(DataError):
TestDoc({'publish': future}).validate()
from schematics.types.compound import ListType, ModelType, DictType
from schematics.exceptions import BaseError, ConversionError
from schematics.transforms import get_import_context
from ..exceptions import SerializationException
from decimal import Decimal
from ..compat import all_string_types
JSON_SCHEMA_MAP = OrderedDict(
[
(BooleanType, {"type": "boolean"}),
(IntType, {"type": "integer"}),
(NumberType, {"type": "number"}),
(UUIDType, {"type": "string", "format": "uuid"}),
(URLType, {"type": "string", "format": "url"}),
(StringType, {"type": "string"}),
(DateTimeType, {"type": "string", "format": "date-time"}),
(BaseType, {"type": "object"}),
]
)
class SchematicsSerializer(ObjectSerializer):
"""
An ObjectSerializer which allows the serialization of
basic types and schematics models.
The valid types that SchematicsSerializer supports are:
- int
- float
- bool
- decimal
""" Describes one search result"""
project_id = IntType(required=True, serialized_name="projectId")
locale = StringType(required=True)
name = StringType(default="")
short_description = StringType(serialized_name="shortDescription", default="")
mapper_level = StringType(required=True, serialized_name="mapperLevel")
priority = StringType(required=True)
organisation_name = StringType(serialized_name="organisationName")
organisation_logo = StringType(serialized_name="organisationLogo")
campaign = StringType()
percent_mapped = IntType(serialized_name="percentMapped")
percent_validated = IntType(serialized_name="percentValidated")
status = StringType(serialized_name="status")
active_mappers = IntType(serialized_name="activeMappers")
last_updated = DateTimeType(serialized_name="lastUpdated")
due_date = DateTimeType(serialized_name="dueDate")
total_contributors = IntType(serialized_name="totalContributors")
country = StringType(serialize_when_none=False)
class ProjectSearchResultsDTO(Model):
""" Contains all results for the search criteria """
def __init__(self):
""" DTO constructor initialise all arrays to empty"""
super().__init__()
self.results = []
self.map_results = []
map_results = BaseType(serialized_name="mapResults")
results = ListType(ModelType(ListSearchResultDTO))
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 MLModelVersionDTO(Model):
""" Describes JSON of a ML model version """
version_id = IntType(serialized_name='versionId')
created = DateTimeType()
model_id = IntType(serialized_name='modelId', required=True)
version_major = IntType(serialized_name='versionMajor', required=True)
version_minor = IntType(serialized_name='versionMinor', required=True)
version_patch = IntType(serialized_name='versionPatch', required=True)
PROCESSING = "processing"
FAILED = "failed"
DONE = "done"
class JobStatusModel(Model, ExamplesMixin):
"""
Status information for a job.
"""
status: JobStatus = StringType(required=True, choices=[*map(
lambda m: getattr(JobStatus, m),
filter(str.isupper, dir(JobStatus)))
])
error_details: ErrorModel = ModelType(ErrorModel, required=False, default=None)
model: ModelModel = ModelType(ModelModel, required=True)
enqueued_at: datetime = DateTimeType(required=False)
processing_started_at: datetime = DateTimeType(required=False)
finished_at: datetime = DateTimeType(required=False)
def copy(self) -> 'JobStatusModel':
"""
Make a deep copy of this object.
:return: a deep copy of this object
"""
return JobStatusModel(deepcopy(self.to_primitive()))
@classmethod
def get_examples(cls):
return [
ModelExample("finished", cls({
"status": "done",
def conversion2():
print("=== conversion2 ===")
dt_t = DateTimeType()
dt = dt_t.to_native('2013-08-31T02:21:21.486072')
print("type: {}, value: {}".format(type(dt), dt))
print("type: {}, value: {}".format(type(dt_t.to_primitive(dt)), dt_t.to_primitive(dt)))