Debian Codegraph @

ansible_collections/community/dns/tests/unit/plugins/module_utils/utils.py

raw
1 # Copyright (c) 2025, Felix Fontein <[email protected]>
2 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
3 # SPDX-License-Identifier: GPL-3.0-or-later
4
5 from __future__ import annotations
6
7 import contextlib
8
9
10 @contextlib.contextmanager
11 def patch_dict(dictionary, key, value):
12 has_key = key in dictionary
13 old_value = dictionary.get(key)
14 try:
15 dictionary[key] = value
16 yield
17 finally:
18 if has_key:
19 dictionary[key] = old_value
20 else:
21 dictionary.pop(key, None)
22
23
24 @contextlib.contextmanager
25 def patch_dict_absent(dictionary, key):
26 has_key = key in dictionary
27 old_value = dictionary.get(key)
28 try:
29 dictionary.pop(key, None)
30 yield
31 finally:
32 if has_key:
33 dictionary[key] = old_value