Skip to content

Commit

Permalink
Fix/parse raw plutus data (Python-Cardano#220)
Browse files Browse the repository at this point in the history
* Add test that fails for Datum type

* Fix deserialization to make type annotation datum work

* Fix deserialization test, add iterable case
  • Loading branch information
nielstron authored Apr 22, 2023
1 parent 3c76964 commit b1cda02
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 2 deletions.
2 changes: 1 addition & 1 deletion pycardano/plutus.py
Original file line number Diff line number Diff line change
Expand Up @@ -693,7 +693,7 @@ def from_primitive(cls: Type[RawPlutusData], value: CBORTag) -> RawPlutusData:
return cls(value)


Datum = Union[PlutusData, dict, IndefiniteList, int, bytes, RawCBOR, RawPlutusData]
Datum = Union[PlutusData, dict, int, bytes, IndefiniteList, RawCBOR, RawPlutusData]
"""Plutus Datum type. A Union type that contains all valid datum types."""


Expand Down
5 changes: 4 additions & 1 deletion pycardano/serialization.py
Original file line number Diff line number Diff line change
Expand Up @@ -496,7 +496,10 @@ def _restore_typed_primitive(
raise DeserializeException(f"Expected type list but got {type(v)}")
return IndefiniteList([_restore_typed_primitive(t, w) for w in v])
elif isclass(t) and issubclass(t, IndefiniteList):
return IndefiniteList(v)
try:
return IndefiniteList(v)
except TypeError:
raise DeserializeException(f"Can not initialize IndefiniteList from {v}")
elif hasattr(t, "__origin__") and (t.__origin__ is dict):
t_args = t.__args__
if len(t_args) != 2:
Expand Down
19 changes: 19 additions & 0 deletions test/pycardano/test_serialization.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import cbor2
from dataclasses import dataclass, field

from pycardano import Datum, RawPlutusData
from test.pycardano.util import check_two_way_cbor
from typing import Any, Dict, List, Optional, Set, Tuple, Union

Expand Down Expand Up @@ -174,6 +177,22 @@ class Test1(MapCBORSerializable):
check_two_way_cbor(t)


def test_datum_type():
@dataclass
class Test1(MapCBORSerializable):
b: Datum

# make sure that no "not iterable" error is thrown
t = Test1(b=RawPlutusData(cbor2.CBORTag(125, [])))

check_two_way_cbor(t)

# Make sure that iterable objects are not deserialized to the wrong object
t = Test1(b=b"hello!")

check_two_way_cbor(t)


def test_wrong_primitive_type():
@dataclass
class Test1(MapCBORSerializable):
Expand Down

0 comments on commit b1cda02

Please sign in to comment.