Skip to content

Commit

Permalink
deserialize with Monster() and Item() functions
Browse files Browse the repository at this point in the history
  • Loading branch information
tassaron committed Aug 8, 2023
1 parent fa1915e commit cad4ef8
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 5 deletions.
11 changes: 9 additions & 2 deletions dnd_character/equipment.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,5 +62,12 @@ def __iter__(self):
yield k, v


def Item(index: str) -> _Item:
return _Item(**SRD_equipment[index])
def Item(item: Union[str, dict]) -> _Item:
"""
Create new Item by calling with string (e.g., torch)
Deserialize item by calling with a dict
"""
if type(item) == str:
return _Item(**SRD_equipment[item])
else:
return _Item(**item)
15 changes: 12 additions & 3 deletions dnd_character/monsters.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@

@dataclass(kw_only=True)
class _Monster:
"""Dataclass for items. Deserialize item with `_Monster(**dict)` or Monster() function"""
"""Dataclass for monsters. Deserialize item with `_Monster(**dict)` or Monster() function"""

index: str
uid: str = uuid4().hex
Expand Down Expand Up @@ -57,5 +57,14 @@ def __iter__(self):
yield k, v


def Monster(index: str) -> _Monster:
return _Monster(**SRD_monsters[index])
def Monster(monster: Union[str, dict]) -> _Monster:
"""
Create new Monster by calling with string (e.g., zombie)
Deserialize monster by calling with a dict
"""
if type(monster) == str:
# new monster
return _Monster(**SRD_monsters[monster])
else:
# deserialized monster
return _Monster(**monster)
5 changes: 5 additions & 0 deletions tests/test_equipment.py
Original file line number Diff line number Diff line change
Expand Up @@ -346,3 +346,8 @@ def test_item_serialization(item_name: str, expected_value: dict):
item = Item(item_name)
serialized_item = literal_eval(str(dict(item)))
assert all([serialized_item[k] == v for k, v in expected_value.items()])


def test_item_function_deserializes_dict():
torch = Item("torch")
assert Item(dict(torch)) == torch
5 changes: 5 additions & 0 deletions tests/test_monsters.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,3 +79,8 @@ def test_zombie_serialization():
}
serialized_zombie = dict(zombie)
assert all([serialized_zombie[k] == v for k, v in expected_zombie.items()])


def test_monster_function_deserializes_dict():
roper = Monster("roper")
assert Monster(dict(roper)) == roper

0 comments on commit cad4ef8

Please sign in to comment.