Skip to content

Commit

Permalink
Merge pull request #60 from pourhouse/bugfix-decimal
Browse files Browse the repository at this point in the history
Bug fix: add handling of decimal.Decimal value to jsonclass.py
  • Loading branch information
tcalmant authored Jun 14, 2024
2 parents 3422768 + 34abc58 commit 756dd93
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 0 deletions.
3 changes: 3 additions & 0 deletions jsonrpclib/jsonclass.py
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,9 @@ def dump(
params, attrs = serialize()
return_obj["__jsonclass__"].append(params)
return_obj.update(attrs)
elif utils.is_decimal(obj):
# Add parameter for Decimal that works with JSON
return_obj["__jsonclass__"].append([str(obj)])
elif utils.is_enum(obj):
# Add parameters for enumerations
return_obj["__jsonclass__"].append([obj.value])
Expand Down
28 changes: 28 additions & 0 deletions jsonrpclib/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,34 @@ def is_enum(obj): # pylint: disable=unused-argument
return False


# ------------------------------------------------------------------------------
# Decimal

try:
import decimal

def is_decimal(obj):
"""
Checks if an object is a decimal.Decimal
:param obj: Object to test
:return: True if the object is a Decimal
"""
return isinstance(obj, decimal.Decimal)


except ImportError:
# Decimal introduced in Python 2.4
def is_decimal(obj): # pylint: disable=unused-argument
"""
Before Python 2.4, Decimal did not exist.
:param obj: Object to test
:return: Always False
"""
return False


# ------------------------------------------------------------------------------
# Common

Expand Down
20 changes: 20 additions & 0 deletions tests/test_jsonclass.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,12 @@ class Color(enum.Enum):
except ImportError:
enum = None # type: ignore

try:
from decimal import Decimal
except ImportError:
Decimal = None


# JSON-RPC library
from jsonrpclib.jsonclass import dump, load
import jsonrpclib.config
Expand Down Expand Up @@ -365,3 +371,17 @@ def test_enum(self):
serialized = dump(data)
result = load(serialized)
self.assertListEqual(data, result)

def test_decimal(self):
"""
Tests the serialization of decimal.Decimal
"""
if Decimal is None:
self.skipTest("decimal package not available.")

for d in (1.1, "3.2"):
d_dec = Decimal(d)
serialized = dump(d_dec)
result = load(serialized)
self.assertIsInstance(result, Decimal)
self.assertEqual(result, d_dec)

0 comments on commit 756dd93

Please sign in to comment.