forked from openedx/credentials
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: [ACI-779] implement data path-key lookup function (#78)
Co-authored-by: Andrii <[email protected]>
- Loading branch information
1 parent
f435946
commit 9fd60e1
Showing
2 changed files
with
58 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |