from pathlib import Path
import json,sys
from pattern_cases import *
from pattern_extensions import *
def strategy(c,out):
cart=CartContext();c.raises("missing strategy",ValueError,cart.total)
for amount in (8900,12900,39900):cart.add(amount)
c.eq("raw amount before selection",cart.raw_total(),Decimal("617"))
for policy,expected in [(Discount("none"),"617.00"),(Discount("percent",Decimal(20)),"493.60"),(Discount("fixed",Decimal(50)),"567.00"),(Discount("seasonal",Decimal(30),Decimal("1.5")),"572.00")]:
cart.strategy=policy;c.eq("actual "+policy.kind,cart.total(),Decimal(expected))
c.eq("fixed is not threshold promotion",Discount("fixed",Decimal(50))(Decimal(20)),Decimal("0.00"))
for user,total,expected in [("vip","500","375.00"),("vip","499","424.15"),("normal","300","270.00"),("normal","299","299.00"),("unknown","1000","1000.00")]:
amount=Decimal(total);c.eq(user+" threshold "+total,select_discount(user,amount)(amount),Decimal(expected))
c.raises("invalid percent",ValueError,lambda:Discount("percent",Decimal(101)))
c.raises("negative seasonal multiplier",ValueError,lambda:Discount("seasonal",Decimal(30),Decimal(-1)))
c.raises("NaN total",ValueError,lambda:Discount("none")(Decimal("NaN")))
c.raises("unknown factory key",ValueError,lambda:Discount("mystery"))
c.raises("negative item",ValueError,lambda:cart.add(-1))
c.eq("failed input preserves total",cart.raw_total(),Decimal(617))
context=SortContext();c.raises("missing sorting strategy",ValueError,lambda:context.sort([1]))
from itertools import product
for algorithm in (bubble_sort,quick_sort,merge_sort):
context.algorithm=algorithm
for length in range(5):
for values in product((-1,0,1),repeat=length):
original=list(values);actual=context.sort(original)
c.eq(algorithm.__name__+" sorts "+repr(values),actual,sorted(values));c.eq(algorithm.__name__+" input unchanged "+repr(values),original,list(values))
body="蓝色天空网 · mbsky.com\n学习策略模式".encode("utf8");context_codec=ZipCodec()
for name,codec in (("zip",context_codec),("gz",GzipCodec())):
compressed=codec.compress(body);path=out/("lesson."+name);path.write_bytes(compressed)
c.eq(name+" actual roundtrip",codec.decompress(path.read_bytes()),body)
import zipfile
c.raises("bad ZIP raises not fake output",zipfile.BadZipFile,lambda:context_codec.decompress(b"not a zip"))
stream=io.BytesIO()
with zipfile.ZipFile(stream,"w")as archive:archive.writestr("../other.txt",body)
c.raises("ZIP path mismatch rejected without extraction",ValueError,lambda:context_codec.decompress(stream.getvalue()))
def run_case(out):
c=Checks()
strategy(c,out)
return {"chapter":'python-strategy',"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-strategy.py
预期结果与验证条件观察提示
- 当前固定输入命名检查符合明确实际结果及失败策略
- 每章输出、源码和预期分别对应;本地模型不冒充生产系统,未验能力继续单列
请结合实际环境逐项观察。
附件与关联工程包下载
课程关联工程包(登记关联24章) · 含当前章节或实例 · mbskycom202611a526.zip