@@ -18,14 +18,20 @@ class CAPITest(unittest.TestCase):
1818
1919 maxDiff = None
2020
21+ def check_sys_getattr_common (self , sys_getattr , use_bytes = True ):
22+ self .assertIs (sys_getattr ('stdout' ), sys .stdout )
23+
24+ name = '\U0001f40d '
25+ with support .swap_attr (sys , name , 42 ):
26+ key = (name .encode () if use_bytes else name )
27+ self .assertEqual (sys_getattr (key ), 42 )
28+
2129 @support .cpython_only
2230 def test_sys_getobject (self ):
2331 # Test PySys_GetObject()
2432 getobject = _testlimitedcapi .sys_getobject
2533
26- self .assertIs (getobject (b'stdout' ), sys .stdout )
27- with support .swap_attr (sys , '\U0001f40d ' , 42 ):
28- self .assertEqual (getobject ('\U0001f40d ' .encode ()), 42 )
34+ self .check_sys_getattr_common (getobject )
2935
3036 self .assertIs (getobject (b'nonexisting' ), AttributeError )
3137 with support .catch_unraisable_exception () as cm :
@@ -35,21 +41,36 @@ def test_sys_getobject(self):
3541 "'utf-8' codec can't decode" )
3642 # CRASHES getobject(NULL)
3743
44+ def check_sys_getattr (self , sys_getattr ):
45+ self .check_sys_getattr_common (sys_getattr , use_bytes = False )
46+
47+ with self .assertRaises (AttributeError ):
48+ sys_getattr (b'nonexisting' )
49+
3850 def test_sys_getattr (self ):
3951 # Test PySys_GetAttr()
4052 sys_getattr = _testcapi .PySys_GetAttr
4153
42- self .assertIs (sys_getattr ('stdout' ), sys .stdout )
43- with support .swap_attr (sys , '\U0001f40d ' , 42 ):
44- self .assertEqual (sys_getattr ('\U0001f40d ' .encode ()), 42 )
54+ self .check_sys_getattr (sys_getattr )
4555
46- with self .assertRaises (AttributeError ):
47- sys_getattr ( b'nonexisting' )
48- with self .assertRaises (UnicodeDecodeError ):
49- self . assertIs ( sys_getattr (b' \xff ' ), AttributeError )
56+ with self .assertRaises (TypeError ):
57+ for invalid_name in ( 123 , [], object ()):
58+ with self .assertRaises (AttributeError ):
59+ sys_getattr (invalid_name )
5060
5161 # CRASHES sys_getattr(NULL)
5262
63+ def test_sys_getattrstring (self ):
64+ # Test PySys_GetAttr()
65+ sys_getattrstring = _testcapi .PySys_GetAttrString
66+
67+ self .check_sys_getattr (sys_getattrstring )
68+
69+ with self .assertRaises (UnicodeDecodeError ):
70+ self .assertIs (sys_getattrstring (b'\xff ' ), AttributeError )
71+
72+ # CRASHES sys_getattrstring(NULL)
73+
5374 @support .cpython_only
5475 def test_sys_setobject (self ):
5576 # Test PySys_SetObject()
0 commit comments