Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
# pylint: disable=arguments-differ
from datetime import datetime
import pytest
from datafiles import Missing, converters, datafile
class MyDateTime(converters.Converter, datetime):
"""A custom class modified to support serialization."""
@classmethod
def to_preserialization_data(cls, python_value, **_kwargs):
return python_value.isoformat()
@classmethod
def to_python_value(cls, deserialized_data, **_kwargs):
return MyDateTime.fromisoformat(deserialized_data)
class DateTimeConverter(converters.Converter):
"""A converter to serialize a custom class."""
@classmethod
def to_preserialization_data(cls, python_value, **_kwargs):
def sample():
@dataclass
class Sample(datafiles.Model):
key: int
name: str
score: float = 1 / 16
class Meta:
datafile_attrs = {'name': datafiles.converters.String}
datafile_pattern = '../tmp/{self.key}.yml'
return Sample(4, "d")
def test_registration(expect):
converters.register(datetime, DateTimeConverter)
@datafile("../tmp/sample.yml")
class Timestamp:
dt: datetime
ts = Timestamp(datetime(2019, 1, 29))
expect(ts.datafile.text) == "dt: '2019-01-29T00:00:00'\n"
ts = Timestamp(Missing)
expect(ts.dt) == datetime(2019, 1, 29)
ts.datafile.text = "dt: '2019-01-22T00:00:00'\n"
expect(ts.dt.day) == 22
from datafiles import Missing, converters, datafile
class MyDateTime(converters.Converter, datetime):
"""A custom class modified to support serialization."""
@classmethod
def to_preserialization_data(cls, python_value, **_kwargs):
return python_value.isoformat()
@classmethod
def to_python_value(cls, deserialized_data, **_kwargs):
return MyDateTime.fromisoformat(deserialized_data)
class DateTimeConverter(converters.Converter):
"""A converter to serialize a custom class."""
@classmethod
def to_preserialization_data(cls, python_value, **_kwargs):
return python_value.isoformat()
@classmethod
def to_python_value(cls, deserialized_data, **_kwargs):
return datetime.fromisoformat(deserialized_data)
@pytest.mark.flaky
def test_extension(expect):
@datafile("../tmp/sample.yml")
class Timestamp:
dt: MyDateTime
def it_inferrs_attrs(expect, sample):
expect(sample.datafile.attrs) == {
'name': datafiles.converters.String,
'score': datafiles.converters.Float,
}
def it_inferrs_attrs(expect, sample):
expect(sample.datafile.attrs) == {
'key': datafiles.converters.Integer,
'name': datafiles.converters.String,
'score': datafiles.converters.Float,
}