diff --git a/credentials/tests/test_utils.py b/credentials/tests/test_utils.py new file mode 100644 index 000000000..82136ef42 --- /dev/null +++ b/credentials/tests/test_utils.py @@ -0,0 +1,44 @@ +import unittest + +from credentials.utils import keypath + +class TestKeypath(unittest.TestCase): + def test_keypath_exists(self): + payload = { + "course": { + "key": "105-3332", + } + } + result = keypath(payload, "course.key") + self.assertEqual(result, "105-3332") + + def test_keypath_not_exists(self): + payload = { + "course": { + "id": "105-3332", + } + } + result = keypath(payload, "course.key") + self.assertIsNone(result) + + def test_keypath_deep(self): + payload = { + "course": { + "data": { + "identification": { + "id": 25 + } + } + } + } + result = keypath(payload, "course.data.identification.id") + self.assertEqual(result, 25) + + def test_keypath_invalid_path(self): + payload = { + "course": { + "key": "105-3332", + } + } + result = keypath(payload, "course.id") + self.assertIsNone(result) \ No newline at end of file diff --git a/credentials/utils.py b/credentials/utils.py new file mode 100644 index 000000000..b43cf633e --- /dev/null +++ b/credentials/utils.py @@ -0,0 +1,14 @@ +def keypath(payload, keys_path): + keys = keys_path.split('.') + current = payload + + def traverse(current, keys): + if not keys: + return current + key = keys[0] + if isinstance(current, dict) and key in current: + return traverse(current[key], keys[1:]) + else: + return None + + return traverse(current, keys) \ No newline at end of file