Skip to content

Commit

Permalink
test: added unit tests for serialize function
Browse files Browse the repository at this point in the history
  • Loading branch information
muhammadadeeltajamul committed Sep 16, 2024
1 parent 471bf04 commit ded9b1d
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 6 deletions.
42 changes: 42 additions & 0 deletions edx_ace/tests/utils/test_signals.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
from django.test import TestCase
from edx_ace.utils.signals import make_serializable_object

class TestMakeSerializableObject(TestCase):
def test_primitive_types(self):
self.assertEqual(make_serializable_object(42), 42)
self.assertEqual(make_serializable_object(3.14), 3.14)
self.assertEqual(make_serializable_object("string"), "string")
self.assertEqual(make_serializable_object(True), True)
self.assertEqual(make_serializable_object(None), None)

def test_dict(self):
input_dict = {
"int": 1,
"float": 2.0,
"str": "test",
"bool": False,
"none": None,
"list": [1, 2, 3],
"nested_dict": {"key": "value"}
}
self.assertEqual(make_serializable_object(input_dict), input_dict)

def test_list(self):
input_list = [1, 2.0, "test", False, None, [1, 2, 3], {"key": "value"}]
self.assertEqual(make_serializable_object(input_list), input_list)

def test_non_serializable(self):
class NonSerializable:
pass

obj = NonSerializable()
self.assertEqual(make_serializable_object(obj), str(obj))

def test_non_serializable_list(self):
class NonSerializable:
pass

obj = NonSerializable()
obj2 = NonSerializable()
obj_list = [obj, obj2]
self.assertEqual(make_serializable_object(obj_list), [str(obj), str(obj2)])
15 changes: 9 additions & 6 deletions edx_ace/utils/signals.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,15 @@ def make_serializable_object(obj):
Takes a dictionary/list and returns a dictionary/list with all the values converted
to JSON serializable objects.
"""
if isinstance(obj, (int, float, str, bool)) or obj is None:
return obj
elif isinstance(obj, dict):
return {key: make_serializable_object(value) for key, value in obj.items()}
elif isinstance(obj, list):
return [make_serializable_object(element) for element in obj]
try:
if isinstance(obj, (int, float, str, bool)) or obj is None:
return obj
elif isinstance(obj, dict):
return {key: make_serializable_object(value) for key, value in obj.items()}
elif isinstance(obj, list):
return [make_serializable_object(element) for element in obj]
except: # pylint: disable=bare-except
pass

Check warning on line 20 in edx_ace/utils/signals.py

View check run for this annotation

Codecov / codecov/patch

edx_ace/utils/signals.py#L19-L20

Added lines #L19 - L20 were not covered by tests
return str(obj)


Expand Down

0 comments on commit ded9b1d

Please sign in to comment.