Skip to content

Commit b74c5ea

Browse files
authored
feat(core/bridge): add decimal marshaling functions (#680)
1 parent ec876ee commit b74c5ea

File tree

3 files changed

+46
-0
lines changed

3 files changed

+46
-0
lines changed

scaleway-core/scaleway_core/bridge/__init__.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,9 @@
2222
from .timeseries import unmarshal_TimeSeriesPoint
2323
from .timeseries import marshal_TimeSeriesPoint
2424

25+
from .decimal import unmarshal_Decimal
26+
from .decimal import marshal_Decimal
27+
2528
__all__ = [
2629
"Money",
2730
"unmarshal_Money",
@@ -42,4 +45,6 @@
4245
"marshal_TimeSeries",
4346
"unmarshal_TimeSeriesPoint",
4447
"marshal_TimeSeriesPoint",
48+
"unmarshal_Decimal",
49+
"marshal_Decimal"
4550
]
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
from decimal import Decimal
2+
from typing import Any, Dict
3+
4+
def unmarshal_Decimal(data: Any) -> Decimal:
5+
"""
6+
Unmarshal an instance of Decimal from the given data.
7+
"""
8+
if not isinstance(data, dict):
9+
raise TypeError(
10+
"Unmarshalling the type 'Decimal' failed as data isn't a dictionary."
11+
)
12+
13+
if "value" not in data:
14+
raise TypeError(
15+
"Unmarshalling the type 'Decimal' failed as data does not contain a 'value' key."
16+
)
17+
18+
19+
return Decimal(data["value"])
20+
21+
22+
def marshal_Decimal(data: Decimal) -> Dict[str, Any]:
23+
"""
24+
Marshal an instance of Decimal into google.protobuf.Decimal JSON representation.
25+
"""
26+
return {
27+
"value": str(data),
28+
}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
import unittest
2+
from decimal import Decimal
3+
4+
from scaleway_core.bridge import unmarshal_Decimal, marshal_Decimal
5+
6+
class TestBridgeMarshal(unittest.TestCase):
7+
def test_decimal_marshal(self):
8+
decimal = Decimal('1.2')
9+
self.assertEqual(marshal_Decimal(decimal), {'value': '1.2'})
10+
11+
def test_decimal_unmarshal(self):
12+
decimal = Decimal('1.2')
13+
self.assertEqual(unmarshal_Decimal({'value': '1.2'}), decimal)

0 commit comments

Comments
 (0)