Python patch.dict 实战:临时覆盖如何恢复,为什么嵌套对象不会回滚
测试一段读取配置字典的代码时,直接执行 update 很方便,难点在收尾:原来的值要回来,新键要消失,测试体自己删除的旧键也要恢复。unittest.mock.patch.dict 可以管理这段临时作用域,但它保护的是映射层面的状态,不是整个对象图的事务。
本文用纯内存配置演示,不读取或修改真实 os.environ,不访问业务模块,不安装第三方依赖。实测环境为 CPython 3.12.14,普通模式和 -O 模式均通过完整的 35 条冻结判例,并分别识别出 8 个故意写错的封装。文档链接使用当前可访问的官方页面;滚动文档版本不等于本文实测解释器版本。

一、先分清三个动作:覆盖、清空、恢复
patch.dict 的主要参数是目标映射、values 和 clear。values 可以是字典,也可以是键值对序列;额外关键字参数同样用于提供临时值。clear=True 表示进入作用域时先清空原有键,再放入临时值。Python 3.8 起,with 后面的 as 变量拿到的是被修改的目标映射。参见官方 patch.dict 文档。
下面这一段可以单独保存为 example_restore.py 并直接执行。请注意:timeout 并未列入补丁参数,却在测试体里被删除;scratch 也不是补丁参数,而是测试体后来添加的键。
from unittest.mock import patch
settings = {"mode": "prod", "timeout": 30}
try:
with patch.dict(settings, {"mode": "test"}, retries=2) as active:
print("same:", active is settings)
settings["scratch"] = "temporary"
del settings["timeout"]
print("inside:", sorted(settings.items()))
raise ValueError("body failed")
except ValueError as exc:
print("caught:", str(exc))
print("after:", sorted(settings.items()))
with patch.dict(settings, {"mode": "test"}, clear=True):
print("clear:", sorted(settings.items()))
print("restored:", sorted(settings.items()))实际输出:
same: True
inside: [('mode', 'test'), ('retries', 2), ('scratch', 'temporary')]
caught: body failed
after: [('mode', 'prod'), ('timeout', 30)]
clear: [('mode', 'test')]
restored: [('mode', 'prod'), ('timeout', 30)]这里有四个值得单独核对的结果:
active is settings 为 True,目标字典没有被换成一份隔离副本。
退出时,不只恢复 mode;timeout 也回来了,retries 与 scratch 都被移除。
测试体抛出 ValueError 后,映射仍恢复,异常继续交给外层处理,并没有被吞掉。
clear=True 只决定进入时的视图,退出后仍回到进入前的键绑定。
对普通 dict,可以把本次实测行为理解为:先保存一份浅层快照,在同一个对象上应用临时值,退出时用快照重建它的内容。这个模型比“结束时把传进去的那几个键改回来”更准确。恢复的前提是正常离开上下文、目标映射的相关方法能够完成;它不承诺进程被强制结束后还能清理。
二、键绑定恢复,不等于对象内部状态回滚
最容易漏测的情况是配置值本身为列表或字典。浅拷贝保留内部对象的引用,不会递归复制所有对象;这一点可对照Python 官方浅拷贝与深拷贝说明。下面是本文针对 patch.dict 写出的独立实验:
from unittest.mock import patch
original = ["stable"]
config = {"items": original}
with patch.dict(config, {}):
config["items"].append("changed")
print("mutation persists:", config["items"])
print("same original:", config["items"] is original)
replacement = ["temporary"]
with patch.dict(config, {}):
config["items"] = replacement
replacement.append("outside-alias")
print("binding restored:", config["items"] is original)
print("replacement remains:", replacement)
with patch.dict(config, {}, clear=True):
original.append("via-alias")
print("clear cannot rewind:", config["items"])实际输出:
mutation persists: ['stable', 'changed'] same original: True binding restored: True replacement remains: ['temporary', 'outside-alias'] clear cannot rewind: ['stable', 'changed', 'via-alias']
第一段修改列表内容,退出后 changed 还在。第二段把 items 这个键改为指向 replacement,退出后它重新指向 original;但是 replacement 本身仍带着后来追加的内容。第三段即使使用 clear=True,只要外部还持有 original 的引用,仍可以改变那个对象,退出时恢复的也正是这个已经变化的对象。
所以不要把 patch.dict 当作数据库回滚或内存沙箱。测试若要每次得到干净的可变配置,通常应由 fixture 工厂重新创建对象,或者显式传入独立配置。是否需要深拷贝取决于对象模型;给所有值套一层 deepcopy 并不等同于 patch.dict 的语义,也可能破坏本来有意保留的共享引用。
三、自定义映射:把“像字典”落实到协议
下面的 TinyMap 没有 copy、update、clear 方法,只实现取值、赋值、删除和按键迭代。在本文的 CPython 3.12.14 环境中,它可以完成补丁与恢复。代码仍可单独运行:
from unittest.mock import patch
class TinyMap:
def __init__(self):
self.data = {"mode": "prod"}
def __getitem__(self, key):
return self.data[key]
def __setitem__(self, key, value):
self.data[key] = value
def __delitem__(self, key):
del self.data[key]
def __iter__(self):
return iter(self.data)
box = TinyMap()
with patch.dict(box, {"mode": "test"}, clear=True) as active:
box["scratch"] = 1
print("inside:", box.data)
print("same:", active is box)
print("after:", box.data)实际输出:
inside: {'mode': 'test', 'scratch': 1}
same: True
after: {'mode': 'prod'}有一个细节不能只看一句文档就下结论:官方页面前段要求能够迭代键,后段又写到“迭代或成员检测”两种接口。本文没有把后一段概括成“仅提供 __contains__ 就一定够用”。完整测试同时放入两种明确的对照:
ContainsOnly 显式令 __iter__ 为 None,没有 copy、clear、update,但有取值、赋值、删除和成员检测。在 CPython 3.12.14 中,进入补丁时得到 TypeError,测试体没有执行,原数据未变。
ContainsWithHelpers 在同样禁用迭代的基础上提供正常的 copy、clear、update,本次测试可以完成清空、补丁与恢复。
这是两种具体夹具在指定运行时下的观察,不是所有自定义映射的失败定理,也不是新漏洞。固定版本的CPython 3.12.14 mock.py 源码可以解释这一区别:复制、更新、清空都有调用现成方法和使用回退路径的分支;没有 copy 时,快照回退路径需要遍历键。自定义方法本身若有副作用、异常或特殊复制语义,也应单独测试。
四、嵌套、装饰器和字符串目标,分别验证
两个独立的 patch.dict 上下文嵌套时,内层退出应回到“内层进入时”的外层状态,最外层退出才回到原始状态。下面的完整测试分别覆盖正常退出和内层异常,不把同一个 patcher 对象重复进入当作前提。
函数装饰器用法不会像某些 patch 用法那样额外注入一个 Mock 参数。类装饰器默认只处理名称以 test 开头的方法,本例不更改 patch.TEST_PREFIX。对应案例会分别检查装饰后的函数和未被包装的 helper 方法。
官方也记录了字符串形式的字典目标,它会通过导入与名称查找取得映射。本文仅使用当前独立演示模块中的 STRING_BOX,目标写作 __name__ + ".STRING_BOX";不测试真实系统模块,也不改 sys.modules。这里验证的是名称能够解析到同一个映射,不对名称解析的具体时机作额外保证。相关接口见Python 3.12 分支官方文档。
五、可直接运行的 35 条判例与 8 个错误对照
先给预期,再看实现结果:35 条预期由语义手推,在北京时间 2026 年 10 月 22 日 06:27:20 冻结为 JSON;首次行为测试在 06:28:56 开始。冻结后的预期没有修改。其 SHA-256 为 82b1549a5ce457cea2bcbebd3611a0cd34e066f365e45bc92714a6de81718605。时间与哈希用于说明这次实验的过程,不是第三方公证。
这 35 条不是重复运行 35 次:18 条检查基本更新、键值对、关键字优先级、空值、clear 及测试体增删改;另外 17 条检查对象身份、别名、嵌套、浅引用、四种自定义映射情形、字符串目标、装饰器和异常对象。预期值没有用被测 patch.dict 的返回结果生成。
把下面整段保存为 patchdict_lab.py,不需要其他文件。EXPECTED 是冻结 JSON 的等价 Python 表示,程序按固定格式重新编码后校验哈希。每条结果按 JSON 表示比较,避免 Python 中 True 与 1、False 与 0 的宽松相等掩盖类型差异。判断使用显式抛出 AssertionError,不依赖会被 -O 移除的 assert 语句。
"""Self-contained patch.dict laboratory; tested on CPython 3.12.14."""
import hashlib
import json
import platform
import sys
from contextlib import contextmanager
from copy import deepcopy
from unittest.mock import patch
EXPECTED_SHA256 = '82b1549a5ce457cea2bcbebd3611a0cd34e066f365e45bc92714a6de81718605'
EXPECTED = {
'add': [{'a': 1, 'b': 2}, {'a': 1}, False],
'alias_visibility': [{'a': 2}, {'a': 1}, True],
'body_add': [{'a': 1, 'b': 2}, {'a': 1}, False],
'body_clear': [{}, {'a': 1}, False],
'body_delete_original': [{'a': 2}, {'a': 1, 'keep': 9}, False],
'body_delete_patched': [{'a': 1}, {'a': 1}, False],
'body_exception': [{'a': 1, 'b': 2, 'x': 3}, {'a': 1}, True],
'body_replace_patched': [{'a': 3}, {'a': 1}, False],
'body_replace_unpatched': [{'a': 2, 'keep': 0}, {'a': 1, 'keep': 9}, False],
'class_decorator': [2, 1, {'a': 1}],
'clear': [{'b': 2}, {'a': 1}, False],
'clear_empty': [{}, {'a': 1}, False],
'clear_external_reference': [{'items': [1, 2]}, True],
'clear_readd_original': [{'a': 7, 'b': 2}, {'a': 1}, False],
'contains_only_rejected': ['TypeError', {'a': 1}, False],
'contains_with_helpers': [{'b': 3}, {'a': 1}],
'custom_exception': [{'b': 3}, {'a': 1}, True],
'custom_iterable': [{'a': 2, 'b': 3}, {'a': 1}, True],
'duplicate_pairs': [{'a': 3}, {'a': 1}, False],
'falsey_values': [{'empty': '', 'flag': False, 'zero': 0}, {'a': 1}, False],
'function_decorator': [7, {'a': 1}],
'kwargs': [{'a': 2, 'c': 3}, {'a': 1}, False],
'kwargs_precedence': [{'a': 3}, {'a': 1}, False],
'nested_exception': [{'a': 2}, {'a': 1}, True],
'nested_normal': [{'a': 2}, {'z': 3}, {'a': 2}, {'a': 1}],
'none_value': [{'a': None}, {'a': 1}, False],
'overwrite': [{'a': 2, 'keep': 9}, {'a': 1, 'keep': 9}, False],
'pairs': [{'a': 1, 'b': 2, 'c': 3}, {'a': 1}, False],
'patch_value_reference': [{}, [1, 2], True],
'restore_original_reference': [{'items': [1]}, True, [9, 10]],
'return_identity': [True, {'a': 1}],
'same_exception': [True, {'a': 1}],
'shallow_dict': [{'node': {'x': 2}}, True],
'shallow_list': [{'items': [1, 2]}, True],
'string_target': [{'a': 2}, {'a': 1}, True],
}
# Each row: initial mapping, values, clear, keyword overrides, body actions.
BASIC = {
"overwrite": ({"a": 1, "keep": 9}, {"a": 2}, False, {}, []),
"add": ({"a": 1}, {"b": 2}, False, {}, []),
"clear": ({"a": 1}, {"b": 2}, True, {}, []),
"clear_empty": ({"a": 1}, {}, True, {}, []),
"body_add": ({"a": 1}, {}, False, {}, [("set", "b", 2)]),
"body_delete_original": ({"a": 1, "keep": 9}, {"a": 2}, False, {}, [("del", "keep")]),
"body_replace_unpatched": ({"a": 1, "keep": 9}, {"a": 2}, False, {}, [("set", "keep", 0)]),
"body_clear": ({"a": 1}, {"b": 2}, False, {}, [("clear",)]),
"body_delete_patched": ({"a": 1}, {"b": 2}, False, {}, [("del", "b")]),
"body_replace_patched": ({"a": 1}, {"a": 2}, False, {}, [("set", "a", 3)]),
"body_exception": ({"a": 1}, {"b": 2}, False, {}, [("set", "x", 3), ("raise",)]),
"kwargs": ({"a": 1}, {}, False, {"a": 2, "c": 3}, []),
"kwargs_precedence": ({"a": 1}, {"a": 2}, False, {"a": 3}, []),
"pairs": ({"a": 1}, [("b", 2), ("c", 3)], False, {}, []),
"duplicate_pairs": ({"a": 1}, [("a", 2), ("a", 3)], False, {}, []),
"none_value": ({"a": 1}, {"a": None}, False, {}, []),
"falsey_values": ({"a": 1}, {"flag": False, "zero": 0, "empty": ""}, True, {}, []),
"clear_readd_original": ({"a": 1}, {"b": 2}, True, {}, [("set", "a", 7)]),
}
def observe_basic(name, scope=patch.dict):
initial, values, clear, kwargs, actions = BASIC[name]
d = dict(initial)
caught = False
inside = None
try:
with scope(d, values, clear=clear, **kwargs):
for action in actions:
if action[0] == "set":
d[action[1]] = action[2]
elif action[0] == "del":
del d[action[1]]
elif action[0] == "clear":
d.clear()
elif action[0] == "raise":
inside = dict(d)
raise RuntimeError("synthetic body failure")
inside = dict(d)
except RuntimeError:
caught = True
return [inside, d, caught]
class TinyMap:
"""Deliberately has no copy(), update(), or clear()."""
def __init__(self):
self.data = {"a": 1}
def __getitem__(self, key):
return self.data[key]
def __setitem__(self, key, value):
self.data[key] = value
def __delitem__(self, key):
del self.data[key]
def __iter__(self):
return iter(self.data)
class ContainsOnly(TinyMap):
__iter__ = None
def __contains__(self, key):
return key in self.data
class ContainsWithHelpers(ContainsOnly):
def copy(self):
return self.data.copy()
def update(self, values):
self.data.update(values)
def clear(self):
self.data.clear()
# The string target belongs only to this isolated tutorial module.
STRING_BOX = {"a": 1}
def observe_special(name, scope=patch.dict):
d = {"a": 1}
if name == "return_identity":
with scope(d, a=2) as returned:
same = returned is d
return [same, d]
if name == "alias_visibility":
alias = d
with scope(d, a=2):
inside = dict(alias)
return [inside, dict(alias), alias is d]
if name == "nested_normal":
trace = []
with scope(d, a=2):
trace.append(dict(d))
with scope(d, {"z": 3}, clear=True):
trace.append(dict(d))
trace.append(dict(d))
return trace + [d]
if name == "nested_exception":
caught = False
with scope(d, a=2):
try:
with scope(d, a=3):
d["x"] = 9
raise RuntimeError("inner")
except RuntimeError:
caught = True
outer = dict(d)
return [outer, d, caught]
if name == "shallow_list":
items = [1]
d = {"items": items}
with scope(d, {}):
d["items"].append(2)
return [d, d["items"] is items]
if name == "shallow_dict":
node = {"x": 1}
d = {"node": node}
with scope(d, {}):
d["node"]["x"] = 2
return [d, d["node"] is node]
if name == "restore_original_reference":
items, replacement = [1], [9]
d = {"items": items}
with scope(d, {}):
d["items"] = replacement
replacement.append(10)
return [d, d["items"] is items, replacement]
if name == "patch_value_reference":
items, d = [1], {}
with scope(d, {"items": items}):
same = d["items"] is items
d["items"].append(2)
return [d, items, same]
if name == "clear_external_reference":
items = [1]
d = {"items": items}
with scope(d, {}, clear=True):
items.append(2)
return [d, d["items"] is items]
if name == "custom_iterable":
d = TinyMap()
with scope(d, a=2, b=3) as returned:
inside = dict(d.data)
same = returned is d
return [inside, d.data, same]
if name == "custom_exception":
d, caught = TinyMap(), False
try:
with scope(d, {"b": 3}, clear=True):
inside = dict(d.data)
del d["b"]
raise RuntimeError("custom")
except RuntimeError:
caught = True
return [inside, d.data, caught]
if name == "contains_only_rejected":
d, entered, error = ContainsOnly(), False, None
try:
with scope(d, a=2):
entered = True
except TypeError as exc:
error = type(exc).__name__
return [error, d.data, entered]
if name == "contains_with_helpers":
d = ContainsWithHelpers()
with scope(d, {"b": 3}, clear=True):
inside = dict(d.data)
return [inside, d.data]
if name == "string_target":
with scope(__name__ + ".STRING_BOX", a=2) as returned:
inside, same = dict(STRING_BOX), returned is STRING_BOX
return [inside, dict(STRING_BOX), same]
if name == "function_decorator":
@patch.dict(d, a=2)
def decorated(value):
return d["a"] + value
result = decorated(5)
return [result, d]
if name == "class_decorator":
@patch.dict(d, a=2)
class Example:
def test_value(self):
return d["a"]
def helper(self):
return d["a"]
obj = Example()
return [obj.test_value(), obj.helper(), d]
if name == "same_exception":
error, caught = RuntimeError("identity"), None
try:
with scope(d, a=2):
raise error
except RuntimeError as exc:
caught = exc
return [caught is error, d]
raise ValueError(name)
def observe(name, scope=patch.dict):
if name in BASIC:
return observe_basic(name, scope)
return observe_special(name, scope)
def wrong_scope(mode):
"""Deliberately wrong teaching fixtures, never production helpers."""
@contextmanager
def broken(d, values=(), clear=False, **kwargs):
old = deepcopy(d) if mode == "deep_restore" else d.copy()
target = d.copy() if mode == "copy_target" else d
incoming = dict(values)
incoming.update(kwargs)
if clear and mode != "ignore_clear":
target.clear()
target.update(incoming)
try:
yield target.copy() if mode == "return_copy" else target
except RuntimeError:
if mode != "swallow_body":
raise
finally:
if mode == "no_restore":
pass
elif mode == "update_restore":
target.update(old)
elif mode == "only_supplied":
for key in incoming:
if key in old:
target[key] = old[key]
else:
target.pop(key, None)
else:
target.clear()
target.update(old)
return broken
PROBES = {
"no_restore": "overwrite",
"update_restore": "add",
"only_supplied": "body_replace_unpatched",
"ignore_clear": "clear",
"copy_target": "overwrite",
"swallow_body": "body_exception",
"deep_restore": "shallow_list",
"return_copy": "return_identity",
}
def main():
raw = (json.dumps(EXPECTED, ensure_ascii=False, indent=2, sort_keys=True) + "\n").encode("utf-8")
digest = hashlib.sha256(raw).hexdigest()
if digest != EXPECTED_SHA256:
raise AssertionError("Frozen expectations changed")
expected = EXPECTED
actual = {name: observe(name) for name in expected}
for name, wanted in expected.items():
if json.dumps(actual[name], sort_keys=True) != json.dumps(wanted, sort_keys=True):
raise AssertionError(f"{name}: actual={actual[name]!r}, expected={wanted!r}")
rejected = []
for mode, case in PROBES.items():
result = observe(case, wrong_scope(mode))
if json.dumps(result, sort_keys=True) == json.dumps(expected[case], sort_keys=True):
raise AssertionError(f"Probe missed wrong wrapper: {mode}")
rejected.append(mode)
print("Runtime:", platform.python_implementation(), platform.python_version())
print("Optimization:", sys.flags.optimize)
print("Oracle SHA256:", digest)
print(f"PASS: {len(actual)} frozen cases")
print(f"REJECTED: {len(rejected)}/{len(PROBES)} wrong wrappers")
print("Wrong wrappers:", ", ".join(rejected))
if "--dump" in sys.argv:
print(json.dumps({"actual": actual, "rejected": rejected}, ensure_ascii=False, sort_keys=True))
if __name__ == "__main__":
main()运行 python patchdict_lab.py,实际输出如下。添加 --dump 会打印全部观测结果,方便逐项检查。
Runtime: CPython 3.12.14 Optimization: 0 Oracle SHA256: 82b1549a5ce457cea2bcbebd3611a0cd34e066f365e45bc92714a6de81718605 PASS: 35 frozen cases REJECTED: 8/8 wrong wrappers Wrong wrappers: no_restore, update_restore, only_supplied, ignore_clear, copy_target, swallow_body, deep_restore, return_copy
再运行 python -O patchdict_lab.py,实际输出如下:
Runtime: CPython 3.12.14 Optimization: 1 Oracle SHA256: 82b1549a5ce457cea2bcbebd3611a0cd34e066f365e45bc92714a6de81718605 PASS: 35 frozen cases REJECTED: 8/8 wrong wrappers Wrong wrappers: no_restore, update_restore, only_supplied, ignore_clear, copy_target, swallow_body, deep_restore, return_copy
wrong_scope 是故意写错的教学夹具,不应复制为工具函数。8 个探针分别抓住:不恢复、只 update 旧值而留下新键、只恢复补丁提供的键、忽略 clear、改了副本没改目标、吞掉异常、错误地做深度回滚,以及返回副本而非目标对象。
REJECTED: 8/8 说明这 8 种已知错误各有一个能够区分它们的判例,不表示达到了完整的 Python 一致性测试覆盖率,也不代表检查了所有第三方映射类型。三个讲解示例同样在普通和 -O 模式校验了实际输出;未执行跨版本或性能基准。
六、什么时候该换一种测试设计
如果被测代码和测试都持有同一个映射,它们都会看到作用域中的临时值。回调可能在补丁生效期间读取它,其他线程也不会自动得到隔离副本;退出时的恢复还可能覆盖别处在这段时间里写入的键。本文没有启动线程测试,不能从顺序案例推出并发安全。
更稳妥的边界是:把补丁范围收窄到一次顺序调用;每个测试使用独立夹具;需要隔离时优先通过参数传入配置,不把共享全局字典当作并发测试的控制开关。自定义映射若在写入或恢复阶段可能抛异常,要另外设计清理与错误检查,不能把“测试体抛错会恢复”扩大为“任何阶段失败都能原子回滚”。
最终要检查的不只是作用域内读到了什么,还包括退出后有哪些键、这些键指向哪个对象,以及对象内部有没有被修改。把这三层分开,patch.dict 才会成为可预测的测试工具。

