• Index

### 关于作者

#### 单元测试

1. 输入正数，比如`1``1.2``0.99`，期待返回值与输入相同；

2. 输入负数，比如`-1``-1.2``-0.99`，期待返回值与输入相反；

3. 输入`0`，期待返回`0`

4. 输入非数值类型，比如`None``[]``{}`，期待抛出`TypeError`

``````>>> 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]
except KeyError:
raise AttributeError(r"'Dict' object has no attribute '%s'" % key)

def __setattr__(self, key, value):
self[key] = value
``````

``````import unittest

from mydict import Dict

class TestDict(unittest.TestCase):

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_key(self):
d = Dict()
d['key'] = 'value'
self.assertEqual(d.key, 'value')

def test_attr(self):
d = Dict()
d.key = 'value'
self.assertTrue('key' in d)
self.assertEqual(d['key'], 'value')

def test_keyerror(self):
d = Dict()
with self.assertRaises(KeyError):
value = d['empty']

def test_attrerror(self):
d = Dict()
with self.assertRaises(AttributeError):
value = d.empty
``````

`test`开头的方法就是测试方法，不以`test`开头的方法不被认为是测试方法，测试的时候不会被执行。

``````self.assertEqual(abs(-1), 1) # 断言函数返回的结果与1相等
``````

``````with self.assertRaises(KeyError):
value = d['empty']
``````

``````with self.assertRaises(AttributeError):
value = d.empty
``````

### 运行单元测试

``````if __name__ == '__main__':
unittest.main()
``````

``````\$ python3 mydict_test.py
``````

``````\$ python3 -m unittest mydict_test
.....
----------------------------------------------------------------------
Ran 5 tests in 0.000s

OK
``````

### setUp与tearDown

`setUp()``tearDown()`方法有什么用呢？设想你的测试需要启动一个数据库，这时，就可以在`setUp()`方法中连接数据库，在`tearDown()`方法中关闭数据库，这样，不必在每个测试方法中重复相同的代码：

``````class TestDict(unittest.TestCase):

def setUp(self):
print('setUp...')

def tearDown(self):
print('tearDown...')
``````

mydict.py

mydict_test.py