mydict.py
代码如下:
1 class Dict(dict): 2 3 def __init__(self, **kw): 4 super().__init__(**kw) 5 6 def __getattr__(self, key): 7 try: 8 return self[key] 9 except KeyError: 10 raise AttributeError( 11 r"'Dict' object has no attribute '%s'" % key) 12 13 def __setattr__(self, key, value): 14 self[key] = value
编写mydict_test.py
如下:
1 import unittest 2 3 from Dict import Dict 4 5 6 class TestDict(unittest.TestCase): 7 8 def setUp(self): 9 print('setUp...') 10 11 def tearDown(self): 12 print('tearDown...') 13 14 def test_init(self): 15 d = Dict(a=1, b='test') 16 self.assertEqual(d.a, 1) 17 self.assertEqual(d.b, 'test') 18 self.assertTrue(isinstance(d, dict)) 19 20 def test_key(self): 21 d = Dict() 22 d['key'] = 'value' 23 self.assertEqual(d.key, 'value') 24 25 def test_attr(self): 26 d = Dict() 27 d.key = 'value' 28 self.assertTrue('key' in d) 29 self.assertEqual(d['key'], 'value') 30 31 def test_keyerror(self): 32 d = Dict() 33 with self.assertRaises(KeyError): 34 value = d['empty'] 35 print(value) 36 37 def test_attrerror(self): 38 d = Dict() 39 with self.assertRaises(AttributeError): 40 value = d.empty 41 print(value) 42 43 44 if __name__ == '__main__': 45 unittest.main()