def test_key(self): print("test_key执行!!!!") d=Dict() d["key"]="value" self.assertEqual(d.key,"value")
def test_key(self): d = Dict() d['key'] = 'value' self.assertEqual(d.key, 'value')
def test_keyerror(self): d = Dict() with self.assertRaises(KeyError): value = d['empty']
def test_key(self): d = Dict() d['key'] = 'value' # 断言函数返回的结果与1相等 self.assertEqual(d.key, 'value')
def test_attrerror(self): d = Dict() with self.assertRaises(AttributeError): # 通过d.empty访问不存在的key时,我们期待抛出AttributeError value = d.empty
def test_init(self): d = Dict(a=1, b='test') self.assertEqual(d.a, 1) # d.a == 1 ? self.assertEqual(d.b, 'test') # d.b == 'test' ? self.assertTrue(isinstance(d, dict)) # d == dict ?
def test_key(self): d = Dict() d["key"] = "value" self.assertEqual(d.key, "value")
def test_init(self): # 初始化检测 d = Dict(a=1, b='test') self.assertEqual(d.a, 1) # 相当于判断 d.a == 1 self.assertEqual(d.b, 'test') self.assertTrue(isinstance(d, dict)) # 相当于判断 d的类型是dict
def test_attr(self): d = Dict() d['key'] = 'value' self.assertEqual(d['key'], 'value')
def test_init(self): #检查init方法 d = Dict(a=1, b='test') self.assertEqual(d.a, 1) #d.a应该等于1 self.assertEqual(d.b, 'test') #d.b应该等于2 self.assertTrue(isinstance(d, dict)) #d应该是一个字典
def test_key(self): # 测试key值赋值value d = Dict() d['key'] = 'value' # 为什么加单引号????? self.assertEqual(d['key'], 'value')
def test_attrerror(self): print("test_attrerror执行!!!!") d = Dict() with self.assertRaises(AttributeError): #点访问属性,会调用__getattr__的方法 print("问题出现:self.assertRaise(AttributeError)") value = d.empty
def test_keyError(self): print("test_keyError执行!!!!") d=Dict() with self.assertRaises(KeyError): #另一种重要的断言就是期待抛出指定类型的Error, print("问题出现:self.assertRaises(KeyError)") #比如通过d['empty']访问不存在的key时,断言会抛出KeyError value=d["empty"] #这里的意思是在冒号的后面的语句中期待会出现KeyError异常
def test_attr(self): print("test_attr执行!!!!") d=Dict() d.key="value" self.assertTrue("key" in d) self.assertEqual(d["key"],"value")
def test_init(self): # 以test开头的方法就是测试方法,不以test开头的方法不被认为是测试方法,测试的时候不会被执行。 d = Dict( a=1, b='test') self.assertEqual(d.a, 1) self.assertEqual(d.b, 'test') self.assertTrue(isinstance(d, dict))
def test_keyerror(self): d = Dict() #另一种重要的断言就是期待抛出指定类型的Error,比如通过d['empty']访问不存在的key时,断言会抛出KeyError: with self.assertRaises(KeyError): value = d['empty']
输入0,期待返回0; 输入非数值类型,比如None、[]、{},期待抛出TypeError。 把上面的测试用例放到一个测试模块里,就是一个完整的单元测试。 如果单元测试通过,说明我们测试的这个函数能够正常工作。如果单元测试不通过,要么函数有bug,要么测试条件输入不正确,总之,需要修复使单元测试能够通过。 单元测试通过后有什么意义呢?如果我们对abs()函数代码做了修改,只需要再跑一遍单元测试,如果通过,说明我们的修改不会对abs()函数原有的行为造成影响,如果测试不通过,说明我们的修改与原有行为不一致,要么修改代码,要么修改测试。 这种以测试为驱动的开发模式最大的好处就是确保一个程序模块的行为符合我们设计的测试用例。在将来修改的时候,可以极大程度地保证该模块行为仍然是正确的。 我们来编写一个Dict类,这个类的行为和dict一致,但是可以通过属性来访问,用起来就像下面这样: >>> d = Dict(a=1, b=2) >>> d['a'] 1 >>> d.a 1 mydict.py代码如下: class Dict(dict): def __init__(self, **kw): super().__init__(**kw) def __getattr__(self, key): try: return self[key]
def test_init(self): d = Dict(a=1, b='test') self.assertEqual(d.a, 2, msg='...')
def test_init(self): d = Dict(a=1, b="test") self.assertEqual(d.a, 1) self.assertEqual(d.b, "test") self.assertTrue(isinstance(d, Dict))
def __init__(self): super().__init__() d = Dict(a=1, b='test') self.assertEqual(d.a, 1) self.assertEqual(d.b, 'test') self.assertEqual(isinstance(d, dict))
def test_attr(self): d = Dict() d.key = "value" self.assertTrue("key" in d) self.assertEqual(d["key"], "value")
class CanvasSettings(Dict): """A collection of settings for an OpenGL Canvas. The canvas settings are a collection of settings and default values affecting the rendering in an individual viewport. There are two type of settings: - mode settings are set during the initialization of the canvas and can/should not be changed during the drawing of actors and decorations; - default settings can be used as default values but may be changed during the drawing of actors/decorations: they are reset before each individual draw instruction. Currently the following mode settings are defined: - bgmode: the viewport background color mode - bgcolor: the viewport background color: a single color or a list of colors (max. 4 are used). - bgimage: background image filename - slcolor: the highlight color - alphablend: boolean (transparency on/off) The list of default settings includes: - fgcolor: the default drawing color - bkcolor: the default backface color - colormap: the default color map to be used if color is an index - bklormap: the default color map to be used if bkcolor is an index - smooth: boolean (smooth/flat shading) - lighting: boolean (lights on/off) - culling: boolean - transparency: float (0.0..1.0) - avgnormals: boolean - edges: 'none', 'feature' or 'all' - pointsize: the default size for drawing points - marksize: the default size for drawing markers - linewidth: the default width for drawing lines Any of these values can be set in the constructor using a keyword argument. All items that are not set, will get their value from the configuration file(s). """ # A collection of default rendering profiles. # These contain the values different from the overall defaults RenderProfiles = { 'wireframe': Dict({ 'smooth': False, 'fill': False, 'lighting': False, # 'alphablend': False, 'transparency': 1.0, 'edges': 'none', 'avgnormals': False, }), 'smooth': Dict({ 'smooth': True, 'fill': True, 'lighting': True, # 'alphablend': False, 'transparency': 0.5, 'edges': 'none', 'avgnormals': False, }), 'smooth_avg': Dict({ 'smooth': True, 'fill': True, 'lighting': True, 'alphablend': False, 'transparency': 0.5, 'edges': 'none', 'avgnormals': True, }), 'smoothwire': Dict({ 'smooth': True, 'fill': True, 'lighting': True, # 'alphablend': False, 'transparency': 0.5, 'edges': 'all', 'avgnormals': False, }), 'flat': Dict({ 'smooth': False, 'fill': True, 'lighting': False, 'alphablend': False, 'transparency': 0.5, 'edges': 'none', 'avgnormals': False, }), 'flatwire': Dict({ 'smooth': False, 'fill': True, 'lighting': False, # 'alphablend': False, 'transparency': 0.5, 'edges': 'all', 'avgnormals': False, }), } bgcolormodes = ['solid', 'vertical', 'horizontal', 'full'] edge_options = ['none', 'feature', 'all'] def __init__(self, **kargs): """Create a new set of CanvasSettings.""" Dict.__init__(self) self.reset(kargs) def reset(self, d={}): """Reset the CanvasSettings to its defaults. The default values are taken from the configuration files. An optional dictionary may be specified to override (some of) these defaults. """ self.update(pf.refcfg['canvas']) self.update(self.RenderProfiles[pf.prefcfg['draw/rendermode']]) self.update(pf.prefcfg['canvas']) self.update(pf.cfg['canvas']) if d: self.update(d) def update(self, d, strict=True): """Update current values with the specified settings Returns the sanitized update values. """ ok = self.checkDict(d, strict) Dict.update(self, ok) @classmethod def checkDict(clas, dict, strict=True): """Transform a dict to acceptable settings.""" ok = {} for k, v in dict.items(): try: if k in [ 'bgcolor', 'fgcolor', 'bkcolor', 'slcolor', 'colormap', 'bkcolormap' ]: if v is not None: v = saneColor(v) elif k in ['bgimage']: v = str(v) elif k in [ 'smooth', 'fill', 'lighting', 'culling', 'alphablend', 'avgnormals', ]: v = bool(v) elif k in ['linewidth', 'pointsize', 'marksize']: v = float(v) elif k == 'linestipple': v = map(int, v) elif k == 'transparency': v = max(min(float(v), 1.0), 0.0) elif k == 'bgmode': v = str(v).lower() if not v in clas.bgcolormodes: raise elif k == 'edges': v = str(v).lower() if not v in clas.edge_options: raise elif k == 'marktype': pass else: raise ok[k] = v except: if strict: raise ValueError, "Invalid key/value for CanvasSettings: %s = %s" % ( k, v) return ok def __str__(self): return utils.formatDict(self) def setMode(self): """Activate the mode canvas settings in the GL machine.""" GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT) if self.bgcolor.ndim > 1: color = self.bgcolor[0] else: color = self.bgcolor GL.glClearColor(*colors.RGBA(color)) def activate(self): """Activate the default canvas settings in the GL machine.""" self.glOverride(self, self) @staticmethod def glOverride(settings, default): #if settings != default: #print("OVERRIDE CANVAS SETINGS %s" % settings['fill']) for k in settings: if k in ['fgcolor', 'transparency']: c = settings.get('fgcolor', default.fgcolor) t = settings.get('transparency', default.transparency) glColor(c, t) elif k == 'linestipple': glLineStipple(*settings[k]) elif k in ['smooth', 'fill', 'lighting', 'linewidth', 'pointsize']: func = globals()['gl' + k.capitalize()] func(settings[k])
def test_keyerror(self): d = Dict() with self.assertRaises(KeyError): # 通过d['empty']访问不存在的key时,断言会抛出keyerror value = d['empty']
def test_keyerror(self): d = Dict() with self.assertRaises(KeyError): #期待抛出指定类型的错误 value = d['empty'] print('test_keyerror...')
def test_init(self): d = Dict(a=1, b='test') self.assertEqual(d.a, 1) self.assertEqual(d.b, 'test') self.assertTrue(isinstance(d, dict))
def test_init(self): d = Dict(a=1, b='test') self.assertEqual(d.a, 1) #断言d.a与1相等 self.assertEqual(d.b, 'test') self.assertTrue(isinstance(d, dict)) print('test_init...')
def test_attr(self): d = Dict() d.key = 'value' self.assertTrue('key' in d) self.assertEqual(d['key'], 'value')
def test_init(self): d = Dict(a=1, b='test') self.assertEqual(d.a, 1) # 断言 函数返回的结果 d.a 与1相等 self.assertEqual(d.b, 'test') # 断言 函数返回的结果 d.b 与test相等 self.assertTrue(isinstance(d, dict))
def test_attrerror(self): d = Dict() with self.assertRaises(AttributeError): value = d.empty
def test_init(self): print("test_init执行!!!!") d=Dict(a=1,b="test") self.assertEqual(d.a,1) #单元测试常用的断言就是assertEqual(),判断相等 self.assertEqual(d.b,"test") self.assertTrue(isinstance(d,dict)) #判断返回True