"""蓝色天空网 mbsky.com: typed immutable observations for owned, bounded examples."""
import json,copy,math
class Checks:
def __init__(self):self.records=[]
def snapshot(self,value):
if isinstance(value,complex):return dict(type='complex',real=value.real,imag=value.imag)
if isinstance(value,(bytes,bytearray)):return dict(type=type(value).__name__,hex=value.hex())
if isinstance(value,float)and not math.isfinite(value):return dict(type='float',value=repr(value))
if isinstance(value,dict):return dict(type='dict',items=[[self.snapshot(k),self.snapshot(v)]for k,v in value.items()])
if isinstance(value,(set,frozenset)):return dict(type=type(value).__name__,members=sorted([self.snapshot(v)for v in value],key=repr))
if isinstance(value,(tuple,list)):return dict(type=type(value).__name__,items=[self.snapshot(v)for v in value])
if isinstance(value,(str,bool,int,float)):return dict(type=type(value).__name__,value=copy.deepcopy(value))
return copy.deepcopy(value)
def eq(self,name,actual,expected):
a=self.snapshot(actual);e=self.snapshot(expected)
if a!=e or type(actual)is not type(expected):raise AssertionError((name,a,e))
self.records.append(dict(name=name,actual=a,expected=e,passed=True))
return actual
def raises(self,name,error,function):
try:function()
except Exception as exc:
if type(exc)is not error:raise
self.records.append(dict(name=name,actual_error=type(exc).__name__,message=str(exc),expected_error=error.__name__,passed=True))
else:raise AssertionError(name+' did not raise '+error.__name__)
def finish(self,chapter,**observations):
print(json.dumps(dict(brand='蓝色天空网',domain='mbsky.com',chapter=chapter,checks=self.records,observations=observations,source_scripts_executed=False,full_source_semantic_review='pending'),ensure_ascii=False))
本例需在 本地 Python 3 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:本地 Python 3
入口文件:projects/python-lab/mbsky_pychecks.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
mbsky_pychecks.py,或下载右侧课程工程包。 - 确认本地已准备 本地 Python 3。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联82章) · 含当前章节或实例 · mbskycom202611a463.zip
课程关联工程包(登记关联82章) · 含当前章节或实例 · mbskycom202612a292.zip