Skip to content

Commit

Permalink
updated TestModel
Browse files Browse the repository at this point in the history
  • Loading branch information
davidvlaminck committed Jun 11, 2024
1 parent d8d69b9 commit 1fd48fa
Show file tree
Hide file tree
Showing 49 changed files with 2,661 additions and 0 deletions.
60 changes: 60 additions & 0 deletions UnitTests/TestModel/OtlmowModel/BaseClasses/BooleanField.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import random
import warnings
from typing import Optional, Any

from otlmow_model.OtlmowModel.BaseClasses.OTLField import OTLField
from otlmow_model.OtlmowModel.Exceptions.CouldNotConvertToCorrectTypeError import CouldNotConvertToCorrectTypeError
from otlmow_model.OtlmowModel.warnings.IncorrectTypeWarning import IncorrectTypeWarning


class BooleanField(OTLField):
"""Beschrijft een tekstregel volgens http://www.w3.org/2001/XMLSchema#string."""
naam = 'Boolean'
objectUri = 'http://www.w3.org/2001/XMLSchema#boolean'
definition = 'Beschrijft een boolean volgens http://www.w3.org/2001/XMLSchema#boolean.'
label = 'Boolean'
usagenote = 'https://www.w3.org/TR/xmlschema-2/#boolean'

@classmethod
def convert_to_correct_type(cls, value: Any, log_warnings: bool = True) -> Optional[bool]:
if value is None:
return None
if isinstance(value, bool):
return value
if isinstance(value, str):
if value.lower() == 'false':
if log_warnings:
warnings.warn(category=IncorrectTypeWarning,
message='Assigned a string to a boolean datatype. '
'Automatically converted to the correct type. Please change the type')
return False
elif value.lower() == 'true':
if log_warnings:
warnings.warn(category=IncorrectTypeWarning,
message='Assigned a string to a boolean datatype. '
'Automatically converted to the correct type. Please change the type')
return True
else:
raise CouldNotConvertToCorrectTypeError(
f'{value} could not be converted to correct type (implied by {cls.__name__})')
elif isinstance(value, int):
if log_warnings:
warnings.warn(category=IncorrectTypeWarning,
message='Assigned an integer to a boolean datatype. '
'Automatically converted to the correct type. Please change the type')
return value != 0
raise CouldNotConvertToCorrectTypeError(
f'{value} could not be converted to correct type (implied by {cls.__name__})')

@classmethod
def validate(cls, value: Any, attribuut) -> bool:
if value is not None and not isinstance(value, bool):
raise TypeError(f'expecting bool in {attribuut.naam}')
return True

def __str__(self) -> str:
return OTLField.__str__(self)

@classmethod
def create_dummy_data(cls) -> bool:
return random.choice([True, False])
42 changes: 42 additions & 0 deletions UnitTests/TestModel/OtlmowModel/BaseClasses/CachedProperty.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
_missing = object()


class cached_property(object):
"""A decorator that converts a function into a lazy property. The
function wrapped is called the first time to retrieve the result
and then that calculated result is used the next time you access
the value::
class Foo(object):
@cached_property
def foo(self):
# calculate something important here
return 42
The class has to have a `__dict__` in order for this property to
work.
"""

# implementation detail: this property is implemented as non-data
# descriptor. non-data descriptors are only invoked if there is
# no entry with the same name in the instance's __dict__.
# this allows us to completely get rid of the access function call
# overhead. If one choses to invoke __get__ by hand the property
# will still work as expected because the lookup logic is replicated
# in __get__ for manual invocation.

def __init__(self, func, name=None, doc=None):
self.__name__ = name or func.__name__
self.__module__ = func.__module__
self.__doc__ = doc or func.__doc__
self.func = func

def __get__(self, obj, type=None):
if obj is None:
return self
value = obj.__dict__.get(self.__name__, _missing)
if value is _missing:
value = self.func(obj)
obj.__dict__[self.__name__] = value
return value
9 changes: 9 additions & 0 deletions UnitTests/TestModel/OtlmowModel/BaseClasses/ComplexField.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
from abc import ABC
from otlmow_model.OtlmowModel.BaseClasses.OTLField import OTLField


class ComplexField(OTLField, ABC):
def __str__(self) -> str:
return OTLField.__str__(self)

waarde_shortcut_applicable = False
89 changes: 89 additions & 0 deletions UnitTests/TestModel/OtlmowModel/BaseClasses/DateField.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
import warnings
from datetime import date, datetime, timedelta, timezone
from random import randrange
from typing import Optional, Any

from otlmow_model.OtlmowModel.BaseClasses.OTLField import OTLField
from otlmow_model.OtlmowModel.Exceptions.CouldNotConvertToCorrectTypeError import CouldNotConvertToCorrectTypeError
from otlmow_model.OtlmowModel.warnings.IncorrectTypeWarning import IncorrectTypeWarning


class DateField(OTLField):
"""Beschrijft een datum volgens http://www.w3.org/2001/XMLSchema#date."""
naam = 'Date'
objectUri = 'http://www.w3.org/2001/XMLSchema#date'
definition = 'Beschrijft een datum volgens http://www.w3.org/2001/XMLSchema#date.'
label = 'Datum'
usagenote = 'https://www.w3.org/TR/xmlschema-2/#date'

@classmethod
def convert_to_correct_type(cls, value: Any, log_warnings: bool = True) -> Optional[date]:
if value is None:
return None
if isinstance(value, bool):
raise CouldNotConvertToCorrectTypeError(
f'{value} could not be converted to correct type (implied by {cls.__name__})')
if isinstance(value, datetime):
if log_warnings:
warnings.warn(category=IncorrectTypeWarning,
message='Assigned a datetime to a date datatype. '
'Automatically converted to the correct type. Please change the type')
return date(value.year, value.month, value.day)
if isinstance(value, date):
return value
if isinstance(value, int):
if log_warnings:
warnings.warn(category=IncorrectTypeWarning,
message='Assigned a int to a date datatype. '
'Automatically converted to the correct type. Please change the type')
timestamp = datetime.fromtimestamp(value, timezone.utc)

return date(timestamp.year, timestamp.month, timestamp.day)

if isinstance(value, str):
try:
dt = datetime.strptime(value, "%Y-%m-%d")
if log_warnings:
warnings.warn(category=IncorrectTypeWarning,
message='Assigned a string to a date datatype. '
'Automatically converted to the correct type. Please change the type')
return date(dt.year, dt.month, dt.day)
except ValueError:
try:
dt = datetime.strptime(value, "%d/%m/%Y")
if log_warnings:
warnings.warn(category=IncorrectTypeWarning,
message='Assigned a string to a date datatype. '
'Automatically converted to the correct type. Please change the type')
return date(dt.year, dt.month, dt.day)
except ValueError as e:
raise CouldNotConvertToCorrectTypeError(
f'{value} could not be converted to correct type (implied by {cls.__name__})'
) from e
raise CouldNotConvertToCorrectTypeError(
f'{value} could not be converted to correct type (implied by {cls.__name__})')

@classmethod
def validate(cls, value: Any, attribuut) -> bool:
if value is not None and not isinstance(value, date):
raise TypeError(f'expecting date in {attribuut.naam}')
return True

@classmethod
def value_default(cls, value: date) -> str:
return value.strftime("%Y-%m-%d")

def __str__(self) -> str:
return OTLField.__str__(self)

@classmethod
def random_date(cls, start: date, end: date) -> date:
delta = end - start
int_delta = delta.days
random_days = randrange(int_delta)
return start + timedelta(days=random_days)

@classmethod
def create_dummy_data(cls) -> date:
return DateField.random_date(start=date(2000, 1, 1),
end=date(2020, 1, 1))
100 changes: 100 additions & 0 deletions UnitTests/TestModel/OtlmowModel/BaseClasses/DateTimeField.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
import datetime
import logging
import warnings
from datetime import timedelta
from random import randrange
from typing import Optional, Any

from otlmow_model.OtlmowModel.Exceptions.CouldNotConvertToCorrectTypeError import CouldNotConvertToCorrectTypeError
from otlmow_model.OtlmowModel.BaseClasses.OTLField import OTLField
from otlmow_model.OtlmowModel.warnings.IncorrectTypeWarning import IncorrectTypeWarning


class DateTimeField(OTLField):
"""Beschrijft een datum volgens http://www.w3.org/2001/XMLSchema#dateTime."""
naam = 'DateTime'
objectUri = 'http://www.w3.org/2001/XMLSchema#dateTime'
definition = 'Beschrijft een datum volgens http://www.w3.org/2001/XMLSchema#dateTime.'
label = 'Datumtijd'
usagenote = 'https://www.w3.org/TR/xmlschema-2/#dateTime'

@classmethod
def validate(cls, value: Any, attribuut) -> bool:
if value is not None and not isinstance(value, datetime.datetime):
raise TypeError(f'expecting datetime in {attribuut.naam}')
return True

@classmethod
def convert_to_correct_type(cls, value: Any, log_warnings: bool = True) -> Optional[datetime.datetime]:
if value is None:
return None
if isinstance(value, bool):
raise CouldNotConvertToCorrectTypeError(
f'{value} could not be converted to correct type (implied by {cls.__name__})')
if isinstance(value, datetime.datetime):
return value
if isinstance(value, datetime.date):
if log_warnings:
warnings.warn(category=IncorrectTypeWarning,
message='Assigned a date to a datetime datatype. '
'Automatically converted to the correct type. Please change the type')
return datetime.datetime(year=value.year, month=value.month, day=value.day)
if isinstance(value, int):
if log_warnings:
warnings.warn(category=IncorrectTypeWarning,
message='Assigned a int to a datetime datatype. '
'Automatically converted to the correct type. Please change the type')
timestamp = datetime.datetime.fromtimestamp(value, datetime.timezone.utc)
return datetime.datetime(timestamp.year, timestamp.month, timestamp.day, timestamp.hour, timestamp.minute,
timestamp.second)
if isinstance(value, str):
try:
if 'T' in value:
dt = datetime.datetime.strptime(value, "%Y-%m-%dT%H:%M:%S")
else:
dt = datetime.datetime.strptime(value, "%Y-%m-%d %H:%M:%S")
if log_warnings:
warnings.warn(category=IncorrectTypeWarning,
message='Assigned a string to a datetime datatype. '
'Automatically converted to the correct type. Please change the type')
return dt
except ValueError:
try:
if 'T' in value:
dt = datetime.datetime.strptime(value, "%d/%m/%YT%H:%M:%S")
else:
dt = datetime.datetime.strptime(value, "%d/%m/%Y %H:%M:%S")
if log_warnings:
warnings.warn(category=IncorrectTypeWarning,
message='Assigned a string to a datetime datatype. '
'Automatically converted to the correct type. Please change the type')
return dt
except Exception as e:
raise CouldNotConvertToCorrectTypeError(
f'{value} could not be converted to correct type (implied by {cls.__name__})'
) from e
try:
return datetime.datetime(value)
except Exception as exc:
raise CouldNotConvertToCorrectTypeError(
f'{value} could not be converted to correct type (implied by {cls.__name__})'
) from exc

@classmethod
def value_default(cls, value: datetime.datetime) -> str:
return value.strftime("%Y-%m-%d %H:%M:%S")

def __str__(self) -> str:
return OTLField.__str__(self)

@staticmethod
def random_date(start: datetime.datetime, end: datetime.datetime) -> datetime.datetime:
delta = end - start
int_delta = (delta.days * 24 * 60 * 60) + delta.seconds
random_second = randrange(int_delta)
return start + timedelta(seconds=random_second)

@classmethod
def create_dummy_data(cls) -> datetime.datetime:
return DateTimeField.random_date(start=datetime.datetime(2000, 1, 1),
end=datetime.datetime(2020, 1, 1))
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# coding=utf-8
from abc import abstractmethod

from otlmow_model.OtlmowModel.BaseClasses.DteAssetType import DteAssetType
from otlmow_model.OtlmowModel.BaseClasses.OTLObject import OTLAttribuut


class DavieRelatieAttributes:
@abstractmethod
def __init__(self):
self._bron = OTLAttribuut(field=DteAssetType,
naam='bron',
label='bron',
objectUri='https://wegenenverkeer.data.vlaanderen.be/ns/implementatieelement#DavieRelatieAttributes.bron',
definition='De bron van een relatie, geformatteerd voor de Davie applicatie',
owner=self)

self._doel = OTLAttribuut(field=DteAssetType,
naam='doel',
label='doel',
objectUri='https://wegenenverkeer.data.vlaanderen.be/ns/implementatieelement#DavieRelatieAttributes.doel',
definition='Het doel van een relatie, geformatteerd voor de Davie applicatie',
owner=self)

@property
def bron(self):
"""De bron van een relatie, geformatteerd voor de Davie applicatie"""
return self._bron.get_waarde()

@bron.setter
def bron(self, value):
self._bron.set_waarde(value, owner=self)

@property
def doel(self):
"""Het doel van een relatie, geformatteerd voor de Davie applicatie"""
return self._doel.get_waarde()

@doel.setter
def doel(self, value):
self._doel.set_waarde(value, owner=self)


38 changes: 38 additions & 0 deletions UnitTests/TestModel/OtlmowModel/BaseClasses/DteAssetType.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# coding=utf-8
from otlmow_model.OtlmowModel.BaseClasses.ComplexField import ComplexField
from otlmow_model.OtlmowModel.BaseClasses.WaardenObject import WaardenObject
from otlmow_model.OtlmowModel.BaseClasses.OTLObject import OTLAttribuut
from otlmow_model.OtlmowModel.BaseClasses.StringField import StringField


class DteAssetTypeWaarden(WaardenObject):
def __init__(self):
WaardenObject.__init__(self)
self._typeURI = OTLAttribuut(
field=StringField,
naam='typeURI',
label='typeURI',
objectUri='https://wegenenverkeer.data.vlaanderen.be/ns/implementatieelement#AIMObject.typeURI',
definition='De uri van het assettype.',
owner=self)

@property
def typeURI(self):
"""De uri van het assettype."""
return self._typeURI.get_waarde()

@typeURI.setter
def typeURI(self, value):
self._typeURI.set_waarde(value, owner=self._parent)


class DteAssetType(ComplexField):
"""Complex datatype om het assettype te benoemen"""
naam = 'DteAssetType'
label = 'AssetType'
objectUri = 'https://wegenenverkeer.data.vlaanderen.be/ns/implementatieelement#DteAssetType'
definition = 'Complex datatype om het assettype te benoemen.'
waardeObject = DteAssetTypeWaarden

def __str__(self) -> str:
return ComplexField.__str__(self)
Loading

0 comments on commit 1fd48fa

Please sign in to comment.