Test that mutable dicts are tracked correctly. Args: mutable_state: A test state.
(mutable_state)
| 1987 | |
| 1988 | |
| 1989 | def test_mutable_dict(mutable_state): |
| 1990 | """Test that mutable dicts are tracked correctly. |
| 1991 | |
| 1992 | Args: |
| 1993 | mutable_state: A test state. |
| 1994 | """ |
| 1995 | assert not mutable_state.dirty_vars |
| 1996 | |
| 1997 | def assert_hashmap_dirty(): |
| 1998 | assert mutable_state.dirty_vars == {"hashmap"} |
| 1999 | mutable_state._clean() |
| 2000 | assert not mutable_state.dirty_vars |
| 2001 | |
| 2002 | # Test all dict operations |
| 2003 | mutable_state.hashmap.update({"new_key": 43}) |
| 2004 | assert_hashmap_dirty() |
| 2005 | assert mutable_state.hashmap.setdefault("another_key", 66) == "another_value" |
| 2006 | assert_hashmap_dirty() |
| 2007 | assert mutable_state.hashmap.setdefault("setdefault_key", 67) == 67 |
| 2008 | assert_hashmap_dirty() |
| 2009 | assert mutable_state.hashmap.setdefault("setdefault_key", 68) == 67 |
| 2010 | assert_hashmap_dirty() |
| 2011 | assert mutable_state.hashmap.pop("new_key") == 43 |
| 2012 | assert_hashmap_dirty() |
| 2013 | mutable_state.hashmap.popitem() |
| 2014 | assert_hashmap_dirty() |
| 2015 | mutable_state.hashmap.clear() |
| 2016 | assert_hashmap_dirty() |
| 2017 | mutable_state.hashmap["new_key"] = 42 |
| 2018 | assert_hashmap_dirty() |
| 2019 | del mutable_state.hashmap["new_key"] |
| 2020 | assert_hashmap_dirty() |
| 2021 | if sys.version_info >= (3, 9): |
| 2022 | mutable_state.hashmap |= {"new_key": 44} |
| 2023 | assert_hashmap_dirty() |
| 2024 | |
| 2025 | # Test nested dict operations |
| 2026 | mutable_state.hashmap["array"] = [] |
| 2027 | assert_hashmap_dirty() |
| 2028 | mutable_state.hashmap["array"].append(1) |
| 2029 | assert_hashmap_dirty() |
| 2030 | mutable_state.hashmap["dict"] = {} |
| 2031 | assert_hashmap_dirty() |
| 2032 | mutable_state.hashmap["dict"]["key"] = 42 |
| 2033 | assert_hashmap_dirty() |
| 2034 | mutable_state.hashmap["dict"]["dict"] = {} |
| 2035 | assert_hashmap_dirty() |
| 2036 | mutable_state.hashmap["dict"]["dict"]["key"] = 43 |
| 2037 | assert_hashmap_dirty() |
| 2038 | |
| 2039 | # Test proxy returned from `setdefault` and `get` |
| 2040 | mutable_value = mutable_state.hashmap.setdefault("setdefault_mutable_key", []) |
| 2041 | assert_hashmap_dirty() |
| 2042 | assert mutable_value == [] |
| 2043 | assert isinstance(mutable_value, MutableProxy) |
| 2044 | mutable_value.append("foo") |
| 2045 | assert_hashmap_dirty() |
| 2046 | mutable_value_other_ref = mutable_state.hashmap.get("setdefault_mutable_key") |