Skip to content
Snippets Groups Projects
Commit 680884e2 authored by Ladislav Lhotka's avatar Ladislav Lhotka
Browse files

Implement XPath function sum().

parent 23f78188
No related branches found
No related tags found
No related merge requests found
......@@ -7,7 +7,7 @@ from yangson.datatype import YangTypeError
from yangson.instance import MinElements, NonexistentInstance
from yangson.instvalue import ArrayValue
from yangson.context import Context, BadPath, BadPrefName
from yangson.xpath import InvalidXPath, NotSupported, XPathParser
from yangson.xpath import InvalidXPath, NotSupported, XPathParser, XPathTypeError
tree = """+--rw test:contA
| +--rw leafA?
......@@ -387,6 +387,11 @@ def test_xpath(instance):
xptest("string(number('foo'))", "NaN")
xptest("number(true()) = 1")
xptest("number(false()) = 0")
xptest("sum(leafA | leafB)", 77, conta)
xptest("string(sum(//leafE))", "NaN")
xptest("sum(//leafF)", 2)
with pytest.raises(XPathTypeError):
xptest("sum(42)")
def test_instance_paths(data_model, instance):
rid1 = data_model.parse_resource_id("/test:contA/testb:leafN")
......
......@@ -578,6 +578,17 @@ class FuncSubstringBefore(BinaryExpr):
ind = lres.find(rres)
return lres[:ind] if ind >= 0 else ""
class FuncSum(UnaryExpr):
def _eval(self, xctx: XPathContext) -> float:
ns = self.expr._eval(xctx)
if not isinstance(ns, NodeSet):
raise XPathTypeError(ns)
try:
return float(sum([n.value for n in ns]))
except TypeError:
return float('nan')
class FuncTranslate(BinaryExpr):
def __init__(self, s1: Expr, s2: Expr, s3: Expr) -> None:
......@@ -933,6 +944,9 @@ class XPathParser(Parser):
def _func_substring_before(self) -> FuncSubstringBefore:
return FuncSubstringBefore(*self._two_args())
def _func_sum(self) -> FuncSum:
return FuncSum(self.parse())
def _func_translate(self) -> FuncTranslate:
s1, s2 = self._two_args()
self.char(",")
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment