Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions AUTHORS.rst
Original file line number Diff line number Diff line change
Expand Up @@ -129,3 +129,4 @@ Suggestions and bug reporting:
- HocVoNgThai

- Mrunmayee Daware (Mrun25)
- Peter Olkhovets (peterolkhov)
1 change: 1 addition & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ Changelog
Version 8.0.1
-------------

* Apply configured value recasting, key conversion and duplicate checks to update and union insertions
* Preserve BoxList item comments when in-place repetition uses an object with __index__, without raising after changing the list

* Clear removed BoxList item comments after in-place repetition by zero or a negative count, so new items do not inherit stale YAML comments (thanks to Mrunmayee Daware)
Expand Down
8 changes: 1 addition & 7 deletions box/box.py
Original file line number Diff line number Diff line change
Expand Up @@ -1146,13 +1146,7 @@ def update(self, *args, **kwargs):
self._update_store(k, kwargs[k])

def _update_store(self, key, value):
# In box_dots mode a dotted key is a path, the same as in
# __setitem__ and merge_update; storing it literally would create
# a parallel key that dots lookups cannot reach consistently.
if self.__process_dotted_key(key):
self.__setitem__(key, value)
else:
self.__convert_and_store(key, value)
self.__setitem__(key, value)

def merge_update(self, *args, **kwargs):
"""
Expand Down
3 changes: 2 additions & 1 deletion test/test_box.py
Original file line number Diff line number Diff line change
Expand Up @@ -730,7 +730,8 @@ def test_camel_killer_box_dotted_lookup_disabled(self, camel_killer_box, box_dot

def test_camel_killer_box_dotted_lookup_exact_key(self):
bx = Box({"someKey": {"innerKey": "converted"}}, camel_killer_box=True, box_dots=True)
bx.update({"someKey": {"innerKey": "exact"}})
# Deliberately retain an unnormalized key to test exact-key lookup precedence.
dict.__setitem__(bx, "someKey", Box({"innerKey": "exact"}, camel_killer_box=True, box_dots=True))

assert bx["someKey.innerKey"] == "exact"
assert bx["some_key.innerKey"] == "converted"
Expand Down
88 changes: 88 additions & 0 deletions test/test_update_insertion.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import pytest

from box import Box, BoxError, ConfigBox
from box.exceptions import BoxWarning


@pytest.mark.parametrize("box_class", [Box, ConfigBox])
@pytest.mark.parametrize("source_type", [dict, list, iter])
def test_update_recasts_each_incoming_value_once(box_class, source_type):
calls = []

def cast(value):
calls.append(value)
return int(value)

bx = box_class(box_recast={"batch_size": cast})
pairs = [("batch_size", "12")]
assert bx.update(source_type(pairs), batch_size="13") is None
assert bx.batch_size == 13
assert calls == ["12", "13"]
assert pairs == [("batch_size", "12")]


@pytest.mark.parametrize("method", ["__or__", "__ior__"])
def test_union_uses_configured_insertions(method):
bx = Box({"TimeOut": 10}, camel_killer_box=True, box_recast={"batch_size": int})
source = {"TimeOut": 30, "batch_size": "12"}
result = getattr(bx, method)(source)
assert result.to_dict() == {"time_out": 30, "batch_size": 12}
assert result.batch_size * 2 == 24
assert source == {"TimeOut": 30, "batch_size": "12"}


def test_update_rejects_invalid_recast_without_replacing_value():
bx = Box(batch_size=10, box_recast={"batch_size": int})
with pytest.raises(ValueError, match="Cannot convert"):
bx.update(batch_size="invalid")
assert bx.batch_size == 10


@pytest.mark.parametrize("keep_keys", [False, True])
def test_update_respects_camel_key_policy(keep_keys):
bx = Box({"TimeOut": 10}, camel_killer_box=True, camel_killer_box_keep_keys=keep_keys)
bx.update({"TimeOut": 30})
key = "TimeOut" if keep_keys else "time_out"
assert bx.to_dict() == {key: 30}
assert bx.time_out == 30


@pytest.mark.parametrize("policy", ["error", "warn", "ignore"])
def test_update_respects_duplicate_policy(policy):
bx = Box({"a b": 1}, box_duplicates=policy)
bx.update({"a b": 2})
if policy == "error":
with pytest.raises(BoxError, match="Duplicate"):
bx.update({"a-b": 3})
assert bx.to_dict() == {"a b": 2}
elif policy == "warn":
with pytest.warns(BoxWarning, match="Duplicate"):
bx.update({"a-b": 3})
assert bx.to_dict() == {"a b": 2, "a-b": 3}
else:
bx.update({"a-b": 3})
assert bx.to_dict() == {"a b": 2, "a-b": 3}


def test_update_dispatches_subclass_assignment_and_replaces_nested_values():
calls = []

class RecordingBox(Box):
def __setitem__(self, key, value):
calls.append(key)
super().__setitem__(key, value)

bx = RecordingBox(service={"keep": 1}, box_dots=True)
calls.clear()
source = {"service": {"replace": 2}}
bx.update(source)
assert calls == ["service", "replace"]
assert bx.to_dict() == source
assert bx.service.to_dict() == {"replace": 2}


def test_config_box_update_keeps_latest_case_spelling_and_recasts():
bx = ConfigBox({"batch_size": 10}, box_recast={"BATCH_SIZE": int})
bx.update({"BATCH_SIZE": "12"})
assert bx.to_dict() == {"BATCH_SIZE": 12}
assert bx.batch_size == 12