Skip to content

Commit

Permalink
tests/test_mapping.py: add tests, bug fix nested dataclasses
Browse files Browse the repository at this point in the history
  • Loading branch information
suvayu committed Jul 9, 2024
1 parent 418c4c8 commit 69136f1
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 8 deletions.
6 changes: 3 additions & 3 deletions src/esdl4tulipa/mapping.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,9 @@ def fields(cls) -> list[str]:
def __post_init__(self): # noqa: D105
for key, field_t in self.__annotations__.items():
value = getattr(self, key)
if not unguarded_is_dataclass(field_t) or isinstance(value, dict):
continue
setattr(self, key, field_t(**value))
print(key, field_t, unguarded_is_dataclass(field_t), value)
if unguarded_is_dataclass(field_t) and isinstance(value, dict):
setattr(self, key, field_t(**value))


@dataclass(unsafe_hash=True)
Expand Down
59 changes: 54 additions & 5 deletions tests/test_mapping.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,59 @@
"""Test all asset dataclasses."""

from dataclasses import dataclass
from esdl4tulipa.mapping import AssetData
from esdl4tulipa.mapping import asset_types
from esdl4tulipa.mapping import ESDL2TULIPA
from esdl4tulipa.mapping import _producer_t
import pytest
import re


def test_asset_types():
"""Test attribute names and types match."""
for kind, fields in ESDL2TULIPA.items():
assert asset_types[kind].__annotations__ == dict(fields.values())
@dataclass(unsafe_hash=True)
class Leaf(AssetData):
random: int = 42


@dataclass(unsafe_hash=True)
class Nested(AssetData):
flag: bool = True
seed: Leaf = Leaf()


def test_nesting_asset_types():
nest = Nested()
assert isinstance(nest.seed, Leaf)
assert nest.seed.random == 42

data = {"flag": False, "seed": {"random": 5}}
nest = Nested(**data)
assert not nest.flag
assert isinstance(nest.seed, Leaf)
assert nest.seed.random == 5


@pytest.mark.parametrize("kind", list(asset_types))
def test_asset_types(kind: str):
"""Test asset types are default constructable, and hashable."""
assert hash(asset_types[kind]())


@pytest.mark.parametrize("kind", list(asset_types))
def test_esdl_key(kind):
asset = asset_types[kind]()

# test examples
key_re = re.compile(r"cost|lifetime")
esdl_re = re.compile(r"costInformation\..+\.value|technicalLifetime")

for fld in asset.fields():
try:
assert asset.esdl_key(fld)
except AssertionError:
if fld in ("from_asset", "to_asset"):
# from & to nodes have no ESDL equivalent
pass
else:
raise

if isinstance(asset, _producer_t) and key_re.match(fld):
assert esdl_re.match(asset.esdl_key(fld))

0 comments on commit 69136f1

Please sign in to comment.