Skip to content

Commit cc0c343

Browse files
jeanseb6windrjarry
authored andcommitted
data: allow to customize free
When using sysrepo, we need to use sysrepo function to free dnode data. Currently, the free method can't be overridden without hack. This patch add the possibility to override the free method and will allow the utilization with sysrepo-python.
1 parent 367e2e5 commit cc0c343

File tree

2 files changed

+22
-2
lines changed

2 files changed

+22
-2
lines changed

libyang/data.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -205,7 +205,7 @@ class DNode:
205205
Data tree node.
206206
"""
207207

208-
__slots__ = ("context", "cdata")
208+
__slots__ = ("context", "cdata", "free_func")
209209

210210
def __init__(self, context: "libyang.Context", cdata):
211211
"""
@@ -216,6 +216,7 @@ def __init__(self, context: "libyang.Context", cdata):
216216
"""
217217
self.context = context
218218
self.cdata = cdata # C type: "struct lyd_node *"
219+
self.free_func = None # type: Callable[struct lyd_node *]
219220

220221
def meta(self):
221222
ret = {}
@@ -791,7 +792,9 @@ def merge_data_dict(
791792

792793
def free(self, with_siblings: bool = True) -> None:
793794
try:
794-
if with_siblings:
795+
if self.free_func:
796+
self.free_func(self.cdata) # pylint: disable=not-callable
797+
elif with_siblings:
795798
lib.lyd_free_all(self.cdata)
796799
else:
797800
lib.lyd_free_tree(self.cdata)

tests/test_data.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import json
55
import os
66
import unittest
7+
from unittest import mock
78
from unittest.mock import patch
89

910
from _libyang import lib
@@ -394,6 +395,22 @@ def test_data_from_dict_module(self):
394395
dnode.free()
395396
self.assertEqual(json.loads(j), json.loads(self.JSON_CONFIG))
396397

398+
def test_data_from_dict_module_free_func(self):
399+
module = self.ctx.get_module("yolo-system")
400+
401+
free_func = mock.Mock()
402+
dnode = module.parse_data_dict(
403+
self.DICT_CONFIG, strict=True, validate_present=True
404+
)
405+
dnode.free_func = free_func
406+
self.assertIsInstance(dnode, DContainer)
407+
try:
408+
j = dnode.print_mem("json")
409+
finally:
410+
dnode.free()
411+
self.assertEqual(json.loads(j), json.loads(self.JSON_CONFIG))
412+
free_func.assert_called()
413+
397414
DICT_CONFIG_WITH_PREFIX = {
398415
"yolo-system:conf": {
399416
"hostname": "foo",

0 commit comments

Comments
 (0)