Skip to content

Commit

Permalink
Add some test and fix default value bug
Browse files Browse the repository at this point in the history
  • Loading branch information
n1nj4t4nuk1 committed Dec 27, 2021
1 parent b8a98b5 commit a0cbd01
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 17 deletions.
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,5 @@ deps:

# Run tests
.PHONY = test
test: build
test:
python -m unittest discover -s ./tests -p '*_test.py'
23 changes: 7 additions & 16 deletions deepfinder/deep_find.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,30 +3,19 @@ def deep_find(
path: str,
token: str = '.',
default_return: any = None,
default_if_err: any = None,
raise_err: bool = False,
) -> any:
"""
Description
:param raise_err:
:param default_if_err:
:param default_return: default return if function raise an error or param is None.
:param token: token to separate attributes.
:param obj: obj in which find.
:param path: path to wanted attribute.
:return: found attribute.
"""
result: any = None
try:
path = path.split(token)
if path == ['']:
path = None
result = __rec_helper(obj, path)
except Exception as e:
if raise_err:
raise e
if default_if_err is not None:
return default_if_err
path = path.split(token)
if path == ['']:
path = None
result = __rec_helper(obj, path)

if result is not None:
return result
Expand All @@ -45,7 +34,9 @@ def __rec_helper(obj: any, path: [str]):

if isinstance(obj, list):
if current_path == '*':
return [__rec_helper(sub_obj, path.copy()) for sub_obj in obj]
with_nones_results = [__rec_helper(sub_obj, path.copy()) for sub_obj in obj]
clear_results = [obj for obj in with_nones_results if obj is not None]
return clear_results
if current_path == '?':
for sub_obj in obj:
result = __rec_helper(sub_obj, path.copy())
Expand Down
33 changes: 33 additions & 0 deletions tests/unit/deep_find_defaults_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import unittest

from deepfinder import deep_find


class TestFindDefault(unittest.TestCase):
def test_with_basic_dict(self):
"""
Return default if attribute is not present
"""
data: dict = {'any': 'any'}
result = deep_find(data, 'some', default_return='default')
self.assertEqual(result, 'default')

def test_with_list_and_find_all(self):
"""
Return empty list if does not match
"""
data: list = [{'any': 'any'}]
result = deep_find(data, '*.some', default_return='default')
self.assertEqual(result, [])

def test_with_list_and_find_some(self):
"""
Return default if attribute is not present
"""
data: list = [{'any': 'any'}]
result = deep_find(data, '?.some', default_return='default')
self.assertEqual(result, 'default')


if __name__ == '__main__':
unittest.main()

0 comments on commit a0cbd01

Please sign in to comment.