模板方法:受控流程、可变步骤和异常清理
父类安排步骤,子类提供实现,实际资源仍按异常路径关闭。
本页展示最近一次实际本地Python命名测试结果,不是在线Python解释器。外部服务、真实硬件及完整来源语义仍分别验收。
| 检查项 | 实际结果 | 预期结果 |
|---|---|---|
| recursive transform actual JSON | {"n": 2, "name": "SKY", "nested": ["WEB", {"label": "LEARN"}]} | {"name": "SKY", "nested": ["WEB", {"label": "LEARN"}], "n": 2} |
| ordered template flow | ["validate", "read", "transform", "format", "save", "post", "cleanup"] | ["validate", "read", "transform", "format", "save", "post", "cleanup"] |
| CSV actual parse plus injected clock | [{"age": "25", "name": "甲,乙", "processed_at": "2026-11-03T00:00:00+00:00"}] | [{"name": "甲,乙", "age": "25", "processed_at": "2026-11-03T00:00:00+00:00"}] |
| read failure propagated | "JSONDecodeError" | "JSONDecodeError" |
| cleanup after failed read | ["validate", "read", "cleanup"] | ["validate", "read", "cleanup"] |
| no invented output | false | false |
| transform failure propagated | "ValueError" | "ValueError" |
| cleanup after transform | ["validate", "read", "transform", "cleanup"] | ["validate", "read", "transform", "cleanup"] |
| existing destination not overwritten | "FileExistsError" | "FileExistsError" |
| cleanup after save failure | "cleanup" | "cleanup" |
| original output still intact | {"n": 2, "name": "SKY", "nested": ["WEB", {"label": "LEARN"}]} | {"name": "SKY", "nested": ["WEB", {"label": "LEARN"}], "n": 2} |
| validate before IO | "ValueError" | "ValueError" |
| cleanup tolerates partial setup | ["validate", "cleanup"] | ["validate", "cleanup"] |
| coffee no condiment hook | ["boil", "coffee", "pour", "serve"] | ["boil", "coffee", "pour", "serve"] |
| tea default condiment hook | ["boil", "tea", "pour", "lemon", "serve"] | ["boil", "tea", "pour", "lemon", "serve"] |
| txt actual file | "<script>alert(\"only text\")</script> & 蓝色天空网" | "<script>alert(\"only text\")</script> & 蓝色天空网" |
| json actual file | "{\"text\": \"<script>alert(\\\"only text\\\")</script> & 蓝色天空网\"}" | "{\"text\": \"<script>alert(\\\"only text\\\")</script> & 蓝色天空网\"}" |
| html actual file | "<!doctype html><meta charset=utf-8><title>蓝色天空网</title><pre><script>alert("only text")</script> & 蓝色天空网</pre>" | "<!doctype html><meta charset=utf-8><title>蓝色天空网</title><pre><script>alert("only text")</script> & 蓝色天空网</pre>" |
| HTML data escaped | false | false |
| json exporter common flow | ["validate", "read", "transform", "format", "save", "post", "cleanup"] | ["validate", "read", "transform", "format", "save", "post", "cleanup"] |
| json exporter actual bytes | true | true |
| txt exporter common flow | ["validate", "read", "transform", "format", "save", "post", "cleanup"] | ["validate", "read", "transform", "format", "save", "post", "cleanup"] |
| txt exporter actual bytes | true | true |
| html exporter common flow | ["validate", "read", "transform", "format", "save", "post", "cleanup"] | ["validate", "read", "transform", "format", "save", "post", "cleanup"] |
| html exporter actual bytes | true | true |
| HTML subclass really escapes data | false | false |
| drink size condiment price | {"size": "medium", "extras": ["milk", "sugar"], "cents": 1700} | {"size": "medium", "extras": ["milk", "sugar"], "cents": 1700} |
| invalid drink option | "ValueError" | "ValueError" |
本章源码与生成文件
查看当前核心代码
from pathlib import Path
import json,sys
from pattern_cases import *
from pattern_extensions import *
def template_method(c,out):
source=out/"input.json";source.write_text(json.dumps({"name":"sky","nested":["web",{"label":"learn"}],"n":2}),encoding="utf8")
processor=JsonUpperProcessor();dest=out/"result.json";result=processor.run(source,dest)
c.eq("recursive transform actual JSON",json.loads(dest.read_text(encoding="utf8")),{"name":"SKY","nested":["WEB",{"label":"LEARN"}],"n":2})
c.eq("ordered template flow",processor.trace,["validate","read","transform","format","save","post","cleanup"])
csvfile=out/"input.csv";csvfile.write_text('name,age\n"甲,乙",25\n',encoding="utf8")
fixed="2026-11-03T00:00:00+00:00";csvproc=CsvTimeProcessor(lambda:fixed);csvdest=out/"csv-result.json";csvproc.run(csvfile,csvdest)
c.eq("CSV actual parse plus injected clock",json.loads(csvdest.read_text(encoding="utf8")),[{"name":"甲,乙","age":"25","processed_at":fixed}])
bad=out/"bad.json";bad.write_text("{",encoding="utf8");failed=JsonUpperProcessor();target=out/"must-not-exist.json"
c.raises("read failure propagated",json.JSONDecodeError,lambda:failed.run(bad,target))
c.eq("cleanup after failed read",failed.trace,["validate","read","cleanup"]);c.eq("no invented output",target.exists(),False)
class FailedTransform(JsonUpperProcessor):
def transform(self,data):raise ValueError("controlled transform failure")
failed=FailedTransform();c.raises("transform failure propagated",ValueError,lambda:failed.run(source,target));c.eq("cleanup after transform",failed.trace,["validate","read","transform","cleanup"])
failed=JsonUpperProcessor();c.raises("existing destination not overwritten",FileExistsError,lambda:failed.run(source,dest));c.eq("cleanup after save failure",failed.trace[-1],"cleanup")
c.eq("original output still intact",json.loads(dest.read_text(encoding="utf8")),result)
invalid=JsonUpperProcessor();c.raises("validate before IO",ValueError,lambda:invalid.run(source,target,{"encoding":"other"}));c.eq("cleanup tolerates partial setup",invalid.trace,["validate","cleanup"])
c.eq("coffee no condiment hook",BeverageTemplate("coffee","milk",False).make(),["boil","coffee","pour","serve"])
c.eq("tea default condiment hook",BeverageTemplate("tea","lemon").make(),["boil","tea","pour","lemon","serve"])
import html
text='<script>alert("only text")</script> & 蓝色天空网'
for extension,formatted in (("txt",text),("json",json.dumps({"text":text},ensure_ascii=False)),("html","<!doctype html><meta charset=utf-8><title>蓝色天空网</title><pre>"+html.escape(text)+"</pre>")):
path=out/("export."+extension);path.write_text(formatted,encoding="utf8");c.eq(extension+" actual file",path.read_text(encoding="utf8"),formatted)
c.eq("HTML data escaped",'<script>'in (out/"export.html").read_text(encoding="utf8"),False)
def extra_template(c,out):
class Exporter(ProcessingTemplate):
def read(self,source):return json.loads(source.read_text(encoding="utf8"))
def transform(self,data):return data
class JsonExporter(Exporter):pass
class TxtExporter(Exporter):
def format(self,data):return data["text"]
class HtmlExporter(Exporter):
def format(self,data):
import html
return '<!doctype html><meta charset="utf-8"><title>蓝色天空网</title><pre>'+html.escape(data["text"])+"</pre>"
source=out/"export-template-input.json";source.write_text(json.dumps({"text":"<literal> & mbsky.com"}),encoding="utf8")
for name,cls in (("json",JsonExporter),("txt",TxtExporter),("html",HtmlExporter)):
exporter=cls();dest=out/("template-output."+name);exporter.run(source,dest);c.eq(name+" exporter common flow",exporter.trace,["validate","read","transform","format","save","post","cleanup"]);c.eq(name+" exporter actual bytes",dest.stat().st_size>0,True)
c.eq("HTML subclass really escapes data",'<literal>'in (out/'template-output.html').read_text(encoding='utf8'),False)
def drink(size,extras):
if size not in {"small","medium","large"}or any(x not in {"milk","lemon","sugar"}for x in extras):raise ValueError("drink options")
return {"size":size,"extras":tuple(extras),"cents":{"small":1000,"medium":1500,"large":2000}[size]+100*len(extras)}
c.eq("drink size condiment price",drink("medium",["milk","sugar"]),{"size":"medium","extras":("milk","sugar"),"cents":1700});c.raises("invalid drink option",ValueError,lambda:drink("huge",[]))
def run_case(out):
c=Checks()
template_method(c,out)
extra_template(c,out)
return {"chapter":'python-template-method',"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))