Skip to content

Commit

Permalink
Fixed/Extended context find_path function
Browse files Browse the repository at this point in the history
This patch enhances context find_path function to
allow using releative paths as well, by adding optional
root_node, from which the relative path is being evaluated
  • Loading branch information
steweg committed Jan 25, 2024
1 parent 097412c commit 08cdbdf
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 5 deletions.
14 changes: 12 additions & 2 deletions libyang/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,17 +175,27 @@ def get_module(self, name: str) -> Module:

return Module(self, mod)

def find_path(self, path: str, output: bool = False) -> Iterator[SNode]:
def find_path(
self,
path: str,
output: bool = False,
root_node: Optional["libyang.SNode"] = None,
) -> Iterator[SNode]:
if self.cdata is None:
raise RuntimeError("context already destroyed")

if root_node is not None:
ctx_node = root_node.cdata
else:
ctx_node = ffi.NULL

flags = 0
if output:
flags |= lib.LYS_FIND_XP_OUTPUT

node_set = ffi.new("struct ly_set **")
if (
lib.lys_find_xpath(self.cdata, ffi.NULL, str2c(path), 0, node_set)
lib.lys_find_xpath(self.cdata, ctx_node, str2c(path), 0, node_set)
!= lib.LY_SUCCESS
):
raise self.error("cannot find path")
Expand Down
8 changes: 5 additions & 3 deletions tests/test_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import os
import unittest

from libyang import Context, LibyangError, Module, SRpc
from libyang import Context, LibyangError, Module, SLeaf, SLeafList


YANG_DIR = os.path.join(os.path.dirname(__file__), "yang")
Expand Down Expand Up @@ -82,8 +82,10 @@ def test_ctx_load_invalid_module(self):
def test_ctx_find_path(self):
with Context(YANG_DIR) as ctx:
ctx.load_module("yolo-system")
node = next(ctx.find_path("/yolo-system:format-disk"))
self.assertIsInstance(node, SRpc)
node = next(ctx.find_path("/yolo-system:conf/offline"))
self.assertIsInstance(node, SLeaf)
node2 = next(ctx.find_path("../number", root_node=node))
self.assertIsInstance(node2, SLeafList)

def test_ctx_iter_modules(self):
with Context(YANG_DIR) as ctx:
Expand Down

0 comments on commit 08cdbdf

Please sign in to comment.