from pathlib import Path
import json,sys
from pattern_cases import *
from pattern_extensions import *
def adapter(c,out):
old=LegacyLog();LoggerAdapter(old).log("info","mbsky.com");c.eq("object adapter delegates",old.lines,["[INFO] mbsky.com"])
inherited=ClassLoggerAdapter();inherited.log("warn","check");c.eq("class adapter",inherited.lines,["[WARN] check"])
xml="<users><user><name>甲</name><age>21</age></user></users>"
c.eq("actual XML conversion",json.loads(xml_users_to_json(xml)),{"users":[{"name":"甲","age":21}]})
c.eq("changed source changes output",json.loads(xml_users_to_json(xml.replace("21","31")))["users"][0]["age"],31)
c.raises("malformed XML",ET.ParseError,lambda:xml_users_to_json("<users>"))
c.raises("missing field",ValueError,lambda:xml_users_to_json("<users><user/></users>"))
parsed=json.loads(csv_users_to_json('name,age,city\n"甲,乙",25,北京\n'))
c.eq("CSV quoted comma survives",parsed,[{"name":"甲,乙","age":25,"city":"北京"}])
c.raises("CSV bad schema",ValueError,lambda:csv_users_to_json("x,y\n1,2\n"))
rates={"CNY":Decimal("7"),"USD":Decimal("1")};recorded=[]
def pay(amount,currency):
if currency not in rates or not amount.is_finite() or amount<0: raise ValueError("invalid payment")
dollars=(amount/rates[currency]).quantize(Decimal("0.01"),rounding=ROUND_HALF_UP);recorded.append(dollars);return dollars
c.eq("injected fixed teaching exchange rate",str(pay(Decimal("700"),"CNY")),"100.00")
c.raises("unsupported currency not treated as USD",ValueError,lambda:pay(Decimal("2"),"EUR"))
c.eq("no external payment calls",len(recorded),1)
def extra_adapter(c,out):
class RecordedWeChat:
def call(self,amount,identity):return {"status":"success","transaction_id":"local-wx"}
class RecordedAli:
def call(self,amount,identity):return {"code":200,"trade_no":"local-ali"}
def adapt(service,amount,identity):
result=service.call(amount,identity)
if "status"in result:return {"ok":result["status"]=="success","reference":result.get("transaction_id")}
if "code"in result:return {"ok":result["code"]==200,"reference":result.get("trade_no")}
raise ValueError("unknown result schema")
c.eq("normalize local wechat result",adapt(RecordedWeChat(),100,"owned-user"),{"ok":True,"reference":"local-wx"});c.eq("normalize local ali result",adapt(RecordedAli(),100,"owned-user"),{"ok":True,"reference":"local-ali"})
calls=[];cached={}
def process(key):
if key not in cached:calls.append(key);cached[key]=key.upper()
return cached[key]
c.eq("adapter cached conversion",process("sky"),"SKY");process("sky");c.eq("cache exact key hit",calls,["sky"]);cached.clear();process("sky");c.eq("explicit cache invalidation",calls,["sky","sky"])
def run_case(out):
c=Checks()
adapter(c,out)
extra_adapter(c,out)
return {"chapter":'python-adapter',"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-adapter.py
预期结果与验证条件观察提示
- 当前固定输入命名检查符合明确实际结果及失败策略
- 每章输出、源码和预期分别对应;本地模型不冒充生产系统,未验能力继续单列
请结合实际环境逐项观察。
附件与关联工程包下载
课程关联工程包(登记关联24章) · 含当前章节或实例 · mbskycom202611a526.zip