单元测试
class Dict(dict):
def __init__(self, **kw):
super().__init__(self, **kw)
def __getattr__(self, key):
try:
return self[key]
except KeyError:
raise AttributeError(r"'Dict' object has no attribute '%s'" % key)
def __setattr__(self, key, value):
self[key] = value
dd = dict(a=1,b=2)
dd1 = Dict(a=1, b=2)
dd1.a
1
dd1.b=1
dd1.b
1
为了编写单元测试,我们需要引入unittest模块,编写mydict_test.py
以test开头的就是测试方法,测试的时候才会被执行
import unittest
class TestDict(unittest.TestCase):
def setUp(self):
print('setUp...')
def tearDown(self):
print('tearDown...')
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_attr(self):
d= Dict()
d.key = 'value'
self.assertEqual(d['key'], 'value')
self.assertTure('key' in d)
def test_key(self):
d = Dict()
d['key'] = 'value'
self.assertEqual(d.key, 'value')
def test_keyerror(self):
d = Dict()
with self.assertRaises(KeyError): #这一种断言是期待抛出指定类型的error,如果通过d['empty']访问不存在的key时,断言会抛出
value = d['empty']
def test_attrerror(self):
d = Dict()
with self.assertRaises(AttributeError):
value = d.empty
if __name__ == '__main__':
unittest.main()
E
======================================================================
ERROR: C:\Users\lovelyfrog\AppData\Roaming\jupyter\runtime\kernel-91a86608-8b96-4f69-a4ff-9857990ce019 (unittest.loader._FailedTest)
----------------------------------------------------------------------
AttributeError: module '__main__' has no attribute 'C:\Users\lovelyfrog\AppData\Roaming\jupyter\runtime\kernel-91a86608-8b96-4f69-a4ff-9857990ce019'
----------------------------------------------------------------------
Ran 1 test in 0.002s
FAILED (errors=1)
An exception has occurred, use %tb to see the full traceback.
SystemExit: True
C:\Users\lovelyfrog\AppData\Local\Programs\Python\Python35\lib\site-packages\IPython\core\interactiveshell.py:2870: UserWarning: To exit: use 'exit', 'quit', or Ctrl-D.
warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)