from pathlib import Path
import json,sys
from pattern_cases import *
from pattern_extensions import *
def state(c,out):
lift=LiftModel();lift.act("open");c.raises("open door rejects movement",RuntimeError,lambda:lift.act("move"));c.eq("failed movement unchanged",lift.current is LIFT_OPEN,True)
lift.select(4);lift.act("close");lift.act("move");c.raises("moving rejects open",RuntimeError,lambda:lift.act("open"));c.raises("moving rejects floor selection",RuntimeError,lambda:lift.select(2))
lift.arrive();c.eq("arrival updates floor and stops",[lift.floor,lift.current is LIFT_CLOSED,lift.target],[4,True,None])
c.raises("invalid floor",ValueError,lambda:lift.select(0));lift.current=LIFT_MAINTENANCE
for action in ("open","close","move","stop"):c.raises("maintenance "+action,RuntimeError,lambda:lift.act(action))
other=LiftModel();c.eq("stateless state instance shared",other.current is LIFT_CLOSED,True);c.eq("context isolated",other.floor,1)
class BadMeta(type):pass
c.raises("type/ABCMeta conflict demonstrated",TypeError,lambda:BadMeta("BadShared",(LiftState,),{}))
machine=VendModel();c.raises("select before credit",RuntimeError,lambda:machine.select("lesson"));c.raises("negative coin",ValueError,lambda:machine.insert(-1))
machine.insert(100);c.raises("insufficient funds",RuntimeError,lambda:machine.select("lesson"));c.eq("insufficient leaves balance",machine.balance,100)
c.raises("missing product",KeyError,lambda:machine.select("missing"));c.raises("sold out",RuntimeError,lambda:machine.select("empty"))
machine.insert(400);machine.select("lesson");c.raises("selection locks coin",RuntimeError,lambda:machine.insert(1));c.eq("actual dispense and change",machine.dispense(),{"product":"lesson","change":200})
c.eq("stock decremented",machine.products["lesson"],(300,0));c.eq("after sale reset",[machine.balance,machine.selected,machine.current is VEND_WAITING],[0,None,True]);c.raises("no duplicate dispense",RuntimeError,machine.dispense)
machine.insert(300);c.eq("refund actual model balance",machine.refund(),300);c.eq("empty refund",machine.refund(),0)
lights=[("red",30),("green",25),("yellow",5)];index=0;elapsed=0
def advance(seconds):
nonlocal index,elapsed
if type(seconds)is not int or not 0<=seconds<=1000:raise ValueError("bounded virtual seconds")
elapsed+=seconds
while elapsed>=lights[index][1]:elapsed-=lights[index][1];index=(index+1)%3
return lights[index][0]
c.eq("traffic before30",advance(29),"red");c.eq("traffic exact30",advance(1),"green");c.eq("traffic exact25",advance(25),"yellow");c.eq("traffic exact5",advance(5),"red")
def character(mode,hp,damage):
if mode not in {"normal","poisoned","stunned","invincible"}:raise ValueError("mode")
return {"hp":max(0,hp-(0 if mode=="invincible"else damage)-(2 if mode=="poisoned"else 0)),"speed":0 if mode=="stunned"else 0.5 if mode=="poisoned"else 1,"attack":mode!="stunned"}
c.eq("poison tick and speed",character("poisoned",10,0),{"hp":8,"speed":0.5,"attack":True});c.eq("stun attack blocked",character("stunned",10,1)["attack"],False);c.eq("invincible damage ignored",character("invincible",10,99)["hp"],10)
def run_case(out):
c=Checks()
state(c,out)
return {"chapter":'python-state',"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-state.py
预期结果与验证条件观察提示
- 当前固定输入命名检查符合明确实际结果及失败策略
- 每章输出、源码和预期分别对应;本地模型不冒充生产系统,未验能力继续单列
请结合实际环境逐项观察。
附件与关联工程包下载
课程关联工程包(登记关联24章) · 含当前章节或实例 · mbskycom202611a526.zip