File tree Expand file tree Collapse file tree 2 files changed +53
-0
lines changed
Expand file tree Collapse file tree 2 files changed +53
-0
lines changed Original file line number Diff line number Diff line change 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 (r"'Dict' object has no attribute '%s'" % key )
11+
12+ def __setattr__ (self , key , value ):
13+ self [key ] = value
14+
Original file line number Diff line number Diff line change 1+ #!/usr/bin/env python3
2+ # -*- coding: utf-8 -*-
3+
4+ import unittest
5+
6+ from mydict import Dict
7+
8+ class TestDict (unittest .TestCase ):
9+
10+ def test_init (self ):
11+ d = Dict (a = 1 , b = 'test' )
12+ self .assertEqual (d .a , 1 )
13+ self .assertEqual (d .b , 'test' )
14+ self .assertTrue (isinstance (d , dict ))
15+
16+ def test_key (self ):
17+ d = Dict ()
18+ d ['key' ] = 'value'
19+ self .assertEqual (d .key , 'value' )
20+
21+ def test_attr (self ):
22+ d = Dict ()
23+ d .key = 'value'
24+ self .assertTrue ('key' in d )
25+ self .assertEqual (d ['key' ], 'value' )
26+
27+ def test_keyerror (self ):
28+ d = Dict ()
29+ with self .assertRaises (KeyError ):
30+ value = d ['empty' ]
31+
32+ def test_attrerror (self ):
33+ d = Dict ()
34+ with self .assertRaises (AttributeError ):
35+ value = d .empty
36+
37+ if __name__ == '__main__' :
38+ unittest .main ()
39+
You can’t perform that action at this time.
0 commit comments