Skip to content

Commit

Permalink
add test for filter_dicts_on_key
Browse files Browse the repository at this point in the history
  • Loading branch information
davidsmejia committed Sep 29, 2023
1 parent b54ed9e commit ccb5535
Showing 1 changed file with 39 additions and 2 deletions.
41 changes: 39 additions & 2 deletions foreman/tests/surveyor/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ def test_flatten_dict(self):
self.assertEqual(prefix_flattened_dict["test_third_fuzz_0"], "another_nested")
self.assertEqual(prefix_flattened_dict["test_third_fuzz_1_nested_object"], True)

def test_get_first_dict(self):
def test_find_first_dict(self):
"""
Tests that you can fetch the first dict from an iterable based on a key.
"""
Expand All @@ -50,6 +50,43 @@ def test_get_first_dict(self):
good_key_no_match = utils.find_first_dict("test_key", 5, iterable_of_dicts)
self.assertEqual(good_key_no_match, None)

# Test when key does not existing.
# Test when key does not exist.
no_dict = utils.find_first_dict("another_key", 1, iterable_of_dicts)
self.assertEqual(no_dict, None)

# Test when iterable is empty.
empty_iterable_dict = utils.find_first_dict("test_key", 1, [])
self.assertEqual(empty_iterable_dict, None)

def test_filter_dicts_on_key(self):
"""
Tests that you can filter an iterable of dicts based on key value.
"""

iterable_of_dicts = [
{"test_key": 1},
{"test_key": 1},
{"test_key": 2},
{"test_key": 3},
{"test_key": 4},
]

# Test for filter with results.
matches = utils.filter_dicts_on_key("test_key", 1, iterable_of_dicts)
values = [match["test_key"] for match in matches]
self.assertEqual(len(values), 2)

correct_values = [value == 1 for value in values]
self.assertTrue(all(correct_values))

# Test for no matches.
good_key_no_match = utils.filter_dicts_on_key("test_key", 5, iterable_of_dicts)
self.assertEqual(len(list(good_key_no_match)), 0)

# Test for no matches on different key that doesn't exist.
no_match = utils.filter_dicts_on_key("another_key", 1, iterable_of_dicts)
self.assertEqual(len(list(no_match)), 0)

# Test for no matches on empty iterable.
empty_list = utils.filter_dicts_on_key("test_key", 1, [])
self.assertEqual(len(list(empty_list)), 0)

0 comments on commit ccb5535

Please sign in to comment.