from pathlib import Path
import json,sys
from pattern_cases import *
from pattern_extensions import *
def memento(c,out):
origin=OriginatorModel();history=SnapshotHistory(origin,2);saved=origin.save();origin.state["inventory"][0]["stats"]["power"]=9
c.eq("saved nested state isolated",json.loads(saved.payload)["inventory"][0]["stats"]["power"],1)
origin.restore(saved);origin.state["inventory"][0]["stats"]["power"]=7;origin.restore(saved);c.eq("restore does not contaminate saved inventory",origin.state["inventory"][0]["stats"]["power"],1)
c.raises("frozen snapshot field",AttributeError,lambda:setattr(saved,"payload","{}"));c.raises("another origin cannot load snapshot",ValueError,lambda:OriginatorModel().restore(saved))
history.edit(lambda state:state.update(content="一"));history.edit(lambda state:state.update(content="二"));history.edit(lambda state:state.update(content="三"))
c.eq("bounded history size",len(history.undo_stack),2);history.undo();c.eq("first undo",origin.state["content"],"二");history.undo();c.eq("second undo",origin.state["content"],"一");c.eq("oldest dropped no further undo",history.undo(),False)
history.redo();c.eq("redo restores content",origin.state["content"],"二");history.edit(lambda state:state.update(content="新分支"));c.eq("new edit clears redo",history.redo(),False)
before=origin.save()
def bad(state):state["content"]="bad";raise ValueError("controlled edit")
c.raises("failed edit restored",ValueError,lambda:history.edit(bad));c.eq("failed edit state",origin.save().payload,before.payload)
origin.cache["transient"]="cache";checkpoint=origin.save();origin.cache.clear();origin.restore(checkpoint);c.eq("selective snapshot excludes cache",origin.cache,{})
slots={"first":saved,"current":origin.save()};c.eq("named save identity",slots["first"]is saved,True);c.raises("missing named slot",KeyError,lambda:slots["absent"])
c.raises("invalid capacity",ValueError,lambda:SnapshotHistory(origin,0))
path=out/"owned-game-save.json";path.write_text(json.dumps({"version":1,"timestamp":saved.timestamp,"state":json.loads(saved.payload)},ensure_ascii=False),encoding="utf8")
loaded=json.loads(path.read_text(encoding="utf8"));c.eq("actual save file schema",loaded["version"],1);c.eq("save timestamp explicit",loaded["timestamp"],"2026-11-03T00:00:00+00:00");c.eq("disk nested data",loaded["state"]["inventory"][0]["stats"]["power"],1)
def extra_memento(c,out):
with closing(sqlite3.connect(':memory:'))as db:
db.execute('CREATE TABLE lesson(title TEXT)');db.execute('INSERT INTO lesson VALUES(?)',('base',));db.commit();db.execute('SAVEPOINT lesson_checkpoint');db.execute('INSERT INTO lesson VALUES(?)',('temporary',));db.execute('ROLLBACK TO lesson_checkpoint');db.execute('RELEASE lesson_checkpoint');c.eq("actual DB savepoint not connection-copy rollback",db.execute('SELECT title FROM lesson').fetchall(),[('base',)])
config={"settings":{"theme":"blue"},"preferences":{"font":16},"cache":{"transient":1}};backup=deepcopy({k:config[k]for k in ('settings','preferences')});config['settings']['theme']='dark';config.update(deepcopy(backup));c.eq("configuration selective backup",config['settings']['theme'],'blue');c.eq("configuration transient cache unchanged",config['cache'],{'transient':1})
def run_case(out):
c=Checks()
memento(c,out)
extra_memento(c,out)
return {"chapter":'python-memento',"checks":c.rows,"passed":True,"scope":"named owned all24chapter named cases only; full source coverage pending"}
if __name__ == "__main__":
output=Path(sys.argv[1]);output.mkdir(parents=True,exist_ok=False)
print(json.dumps(run_case(output),ensure_ascii=False,default=repr))
本例需在 Windows/Python3.12.14标准库;静态浏览器页面使用独立Edge会话,不在线执行Python 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows/Python3.12.14标准库;静态浏览器页面使用独立Edge会话,不在线执行Python
入口文件:projects/patterns-lab/python-memento.py
预期结果与验证条件观察提示
- 当前固定输入命名检查符合明确实际结果及失败策略
- 每章输出、源码和预期分别对应;本地模型不冒充生产系统,未验能力继续单列
请结合实际环境逐项观察。
附件与关联工程包下载
课程关联工程包(登记关联24章) · 含当前章节或实例 · mbskycom202611a526.zip