蓝色天空网 · mbsky.com 全部实例

状态:合法转换、上下文与共享行为

把状态相关行为委托给当前状态对象,并验证非法操作保持原状。

本页展示最近一次实际本地Python命名测试结果,不是在线Python解释器。外部服务、真实硬件及完整来源语义仍分别验收。

Python 3.12.14 · 33 项实际检查 · 当前入口SHA256 f55bbe6a01a9b9e3a94b04872818403381f6d2eeb09136ede1f70380973d0bcc

检查项实际结果预期结果
open door rejects movement"RuntimeError""RuntimeError"
failed movement unchangedtruetrue
moving rejects open"RuntimeError""RuntimeError"
moving rejects floor selection"RuntimeError""RuntimeError"
arrival updates floor and stops[4, true, null][4, true, null]
invalid floor"ValueError""ValueError"
maintenance open"RuntimeError""RuntimeError"
maintenance close"RuntimeError""RuntimeError"
maintenance move"RuntimeError""RuntimeError"
maintenance stop"RuntimeError""RuntimeError"
stateless state instance sharedtruetrue
context isolated11
type/ABCMeta conflict demonstrated"TypeError""TypeError"
select before credit"RuntimeError""RuntimeError"
negative coin"ValueError""ValueError"
insufficient funds"RuntimeError""RuntimeError"
insufficient leaves balance100100
missing product"KeyError""KeyError"
sold out"RuntimeError""RuntimeError"
selection locks coin"RuntimeError""RuntimeError"
actual dispense and change{"product": "lesson", "change": 200}{"product": "lesson", "change": 200}
stock decremented[300, 0][300, 0]
after sale reset[0, null, true][0, null, true]
no duplicate dispense"RuntimeError""RuntimeError"
refund actual model balance300300
empty refund00
traffic before30"red""red"
traffic exact30"green""green"
traffic exact25"yellow""yellow"
traffic exact5"red""red"
poison tick and speed{"hp": 8, "speed": 0.5, "attack": true}{"hp": 8, "speed": 0.5, "attack": true}
stun attack blockedfalsefalse
invincible damage ignored1010

本章源码与生成文件

下载独立入口 共享实现 补充实例实现 本章结果JSON

查看当前核心代码
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))

上图是本站运行生成文件,不能当作来源原图已采集。