Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion pageindex/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -300,7 +300,7 @@ def structure_to_list(structure):

def get_leaf_nodes(structure):
if isinstance(structure, dict):
if not structure['nodes']:
if not structure.get('nodes'):
structure_node = copy.deepcopy(structure)
structure_node.pop('nodes', None)
return [structure_node]
Expand Down
48 changes: 48 additions & 0 deletions tests/test_utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
from pageindex.utils import get_leaf_nodes


def test_get_leaf_nodes_handles_missing_nodes_key():
"""Tree cleanup (see `clean_node` in utils.py) deletes the `nodes` key
entirely from childless nodes rather than setting it to `[]`, so
`get_leaf_nodes` must not assume the key is always present (#330)."""
tree = {
"title": "Root",
"nodes": [
{"title": "Leaf A"}, # no 'nodes' key at all
{
"title": "Branch",
"nodes": [
{"title": "Leaf B"},
],
},
],
}

leaves = get_leaf_nodes(tree)

assert {leaf["title"] for leaf in leaves} == {"Leaf A", "Leaf B"}
assert all("nodes" not in leaf for leaf in leaves)


def test_get_leaf_nodes_still_handles_empty_nodes_list():
tree = {
"title": "Root",
"nodes": [
{"title": "Leaf A", "nodes": []},
],
}

leaves = get_leaf_nodes(tree)

assert [leaf["title"] for leaf in leaves] == ["Leaf A"]


def test_get_leaf_nodes_handles_list_of_trees():
trees = [
{"title": "Leaf A"},
{"title": "Root", "nodes": [{"title": "Leaf B"}]},
]

leaves = get_leaf_nodes(trees)

assert {leaf["title"] for leaf in leaves} == {"Leaf A", "Leaf B"}