Skip to content

Commit

Permalink
tests for jq
Browse files Browse the repository at this point in the history
  • Loading branch information
amyasnikov committed Mar 6, 2024
1 parent 57dff0b commit 79d7a6d
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 3 deletions.
17 changes: 16 additions & 1 deletion validity/tests/test_utils/test_json.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
from validity.utils.json import transform_json
import pytest

from validity.utils.json import jq, transform_json


class TestTransformJson:
Expand Down Expand Up @@ -31,3 +33,16 @@ def test_change_key(self):
)
assert result["groups"]["admin2"] == self.JSON["groups"]["admin"]
assert "admin" not in result["groups"]


@pytest.mark.parametrize(
"data, expression, result",
[
({"a": {"b": "one", "c": "two"}}, ". | mkarr(.a.b)", {"a": {"b": ["one"], "c": "two"}}),
({"a": {"b": ["one"], "c": "two"}}, ". | mkarr(.a.b)", {"a": {"b": ["one"], "c": "two"}}),
({"a": "10.2", "b": {"c": "20"}}, ". | mknum(.b)", {"a": "10.2", "b": {"c": 20}}),
({"a": "10.2", "b": {"c": "20"}}, ". | mknum", {"a": 10.2, "b": {"c": 20}}),
],
)
def test_jq(data, expression, result):
assert jq.first(expression, data) == result
4 changes: 2 additions & 2 deletions validity/utils/json.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,8 @@ class jq:
# ensures that expression at "pth" is an array
'def mkarr(pth): . | pth as $tgt | . | pth = if $tgt | type != "array" then [$tgt] else $tgt end',
# recursively converts all number-like strings to numbers
'def mknum(pth):. | pth as $tgt | . | pth = '
'($tgt | walk(if type == "string" and test("[+-]?([0-9]*[.])?[0-9]+") then . | tonumber else . end))',
"def mknum(pth):. | pth as $tgt | . | pth = "
'($tgt | walk(if type == "string" and test("[+-]?([0-9]*[.])?[0-9]+") then . | tonumber else . end))',
'def mknum: walk(if type == "string" and test("[+-]?([0-9]*[.])?[0-9]+") then . | tonumber else . end)',
]

Expand Down

0 comments on commit 79d7a6d

Please sign in to comment.