Skip to content

Commit

Permalink
feat: [ACI-779] implement data path-key lookup function (#78)
Browse files Browse the repository at this point in the history
Co-authored-by: Andrii <[email protected]>
  • Loading branch information
andrii-hantkovskyi and Andrii authored Mar 26, 2024
1 parent f435946 commit 9fd60e1
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 0 deletions.
44 changes: 44 additions & 0 deletions credentials/tests/test_utils.py
Original file line number Diff line number Diff line change
@@ -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)
14 changes: 14 additions & 0 deletions credentials/utils.py
Original file line number Diff line number Diff line change
@@ -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)

0 comments on commit 9fd60e1

Please sign in to comment.