App Server 握手、双向事件与审批:练习答案
练习解答
先按正文生成schema并保存dispatcher.py,同目录保存answer_dispatch.py。运行 python answer_dispatch.py ./schema;导入正文模块先运行其基线测试,再使用全新Host状态检查变体。
python
from dispatcher import Host,approval
h=Host()
h.receive(approval(21,'int-item'))
h.receive(approval('21','string-item'))
assert h.resolve(21,'decline')=={'id':21,'result':{'decision':'decline'}}
assert ('str','21') in h.pending
assert h.resolve('21','cancel')=={'id':'21','result':{'decision':'cancel'}}
for unknown in (21,999):
try:h.resolve(unknown,'accept')
except ValueError:pass
else:raise AssertionError('unknown or repeated decision')
print('integer and string IDs stay distinct')JSON-RPC请求身份包含值的类型,整数21与字符串21不能被一个字符串键覆盖。回复保留原id,decline与cancel是安装版schema定义的两种真实决定;它们对turn是否继续的含义不同。