Files
slic/tests/test_utils_dictext.py
T
tligui_y 4517561ae6
Run CI Tests / test (push) Successful in 27s
Update tests/test_utils_dictext.py
2025-07-25 13:07:00 +02:00

108 lines
2.9 KiB
Python

import pytest
import sys
import os
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from slic.utils.dictext import *
# Class AttrDict
class MyDict(AttrDict):
pass
# (__getattr__)
@pytest.mark.parametrize(
"data, attr, expected",
[
({"x": 1, "y": 2}, "x", 1),
({"world": "ok"}, "world", "ok"),
({"outer": {"inner": 42}}, "outer", {"inner": 42}),
]
)
def test_attrdict_getattr(data, attr, expected):
d = MyDict(**data)
assert getattr(d, attr) == expected
# (__setattr__)
@pytest.mark.parametrize(
"initial, attr, value",
[
({}, "nouveau", 123),
({"a": 1}, "b", "valeur"),
]
)
def test_attrdict_setattr(initial, attr, value):
d = MyDict(**initial)
setattr(d, attr, value)
assert d[attr] == value
assert getattr(d, attr) == value
# (__delattr__)
@pytest.mark.parametrize(
"initial, to_del, expected_keys",
[
({"a": 1, "b": 2}, "a", ["b"]),
({"k": "v"}, "k", []),
]
)
def test_attrdict_delattr(initial, to_del, expected_keys):
d = MyDict(**initial)
delattr(d, to_del)
assert list(d.keys()) == expected_keys
with pytest.raises(AttributeError):
getattr(d, to_del)
# (__dir__)
@pytest.mark.parametrize(
"data, expected_keys",
[
({"alpha": 1, "beta": 2}, {"alpha", "beta"}),
({}, set()),
]
)
def test_attrdict_dir(data, expected_keys):
d = MyDict(**data)
res = set(dir(d))
for k in expected_keys:
assert k in res
# (_raise_missing_attribute)
@pytest.mark.parametrize(
"data, attr, expect_value, expect_error",
[
({"x": 1, "y": 2}, "x", 1, None),
({"number": 42}, "missing", None, "'MyDict' object has no attribute 'missing'"),
]
)
def test_attrdict_getattr_and_missing(data, attr, expect_value, expect_error):
d = MyDict(**data)
if expect_error is None:
assert getattr(d, attr) == expect_value
else:
with pytest.raises(AttributeError) as excinfo:
_ = getattr(d, attr)
assert str(excinfo.value) == expect_error
# Class DictUpdateMixin
class MyDict2(DictUpdateMixin, dict):
pass
@pytest.mark.parametrize(
"init_kwargs, other, kwargs, expected",
[
({'a': 1, 'b': 2}, None, {}, {'a': 1, 'b': 2}),
({}, {'x': 10, 'y': 20}, {}, {'x': 10, 'y': 20}),
({'world': 'ok'}, {'number': 42}, {'num2': 100}, {'world': 'ok', 'number': 42, 'num2': 100}),
({}, None, {'alpha': 'beta'}, {'alpha': 'beta'}),
({}, {'key': 'value'}, {'extra': 1}, {'key': 'value', 'extra': 1}),
({}, [('key', 'value'), ('list', [5, 6])], {'extra': {'subkey': 123}}, {'key': 'value', 'list': [5, 6], 'extra': {'subkey': 123}}),
]
)
def test_dictupdatemixin_init_and_update(init_kwargs, other, kwargs, expected):
d = MyDict2(**init_kwargs)
if other is not None:
d.update(other, **kwargs)
else:
d.update(**kwargs)
assert dict(d) == expected