LibBotUniversal/tests/test_nested_set.py

82 lines
1.8 KiB
Python
Raw Permalink Normal View History

2023-08-06 22:22:24 +03:00
from typing import Any, Dict, List
2023-08-06 13:51:32 +03:00
import pytest
2024-05-26 16:40:29 +03:00
from libbot.sync._nested import nested_delete, nested_set
2023-08-06 13:51:32 +03:00
@pytest.mark.parametrize(
"target, value, path, create_missing, expected",
[
({"foo": "bar"}, "rab", ["foo"], True, {"foo": "rab"}),
({"foo": "bar"}, {"123": 456}, ["foo"], True, {"foo": {"123": 456}}),
(
{"foo": {"bar": {}}},
True,
["foo", "bar", "test"],
True,
{"foo": {"bar": {"test": True}}},
),
(
{"foo": {"bar": {}}},
True,
["foo", "bar", "test"],
False,
{"foo": {"bar": {}}},
),
],
)
def test_nested_set_valid(
2023-08-06 22:22:24 +03:00
target: Dict[str, Any],
2023-08-06 13:51:32 +03:00
value: Any,
path: List[str],
create_missing: bool,
expected: Any,
):
2024-05-26 16:40:29 +03:00
assert (nested_set(target, value, *path, create_missing=create_missing)) == expected
2023-08-06 13:51:32 +03:00
@pytest.mark.parametrize(
"target, value, path, create_missing, expected",
[
(
{"foo": {"bar": {}}},
True,
["foo", "bar", "test1", "test2"],
False,
KeyError,
),
],
)
def test_nested_set_invalid(
2023-08-06 22:22:24 +03:00
target: Dict[str, Any],
2023-08-06 13:51:32 +03:00
value: Any,
path: List[str],
create_missing: bool,
expected: Any,
):
with pytest.raises(expected):
assert (
2024-05-26 16:40:29 +03:00
nested_set(target, value, *path, create_missing=create_missing)
2023-08-06 13:51:32 +03:00
) == expected
2024-05-26 16:40:29 +03:00
@pytest.mark.parametrize(
"target, path, expected",
[
({"foo": "bar"}, ["foo"], {}),
({"foo": "bar", "bar": "foo"}, ["bar"], {"foo": "bar"}),
(
{"foo": {"bar": {}}},
["foo", "bar"],
{"foo": {}},
),
],
)
def test_nested_delete(
target: Dict[str, Any],
path: List[str],
expected: Any,
):
assert (nested_delete(target, *path)) == expected