@@ -68,33 +68,20 @@ def testcommon(formatstr, args, output=None, limit=None, overflowok=False):
6868 testformat (b_format , args , b_output , limit , overflowok )
6969 testformat (ba_format , args , ba_output , limit , overflowok )
7070
71- def test_exc (formatstr , args , exception , excmsg ):
72- try :
73- testformat (formatstr , args )
74- except exception as exc :
75- if str (exc ) == excmsg :
76- if verbose :
77- print ("yes" )
78- else :
79- if verbose : print ('no' )
80- print ('Unexpected ' , exception , ':' , repr (str (exc )))
81- raise
82- except :
83- if verbose : print ('no' )
84- print ('Unexpected exception' )
85- raise
86- else :
87- raise TestFailed ('did not get expected exception: %s' % excmsg )
88-
89- def test_exc_common (formatstr , args , exception , excmsg ):
90- # test str and bytes
91- test_exc (formatstr , args , exception , excmsg )
92- if isinstance (args , dict ):
93- args = {k .encode ('ascii' ): v for k , v in args .items ()}
94- test_exc (formatstr .encode ('ascii' ), args , exception , excmsg )
9571
9672class FormatTest (unittest .TestCase ):
9773
74+ def check_exc (self , formatstr , args , exception , excmsg ):
75+ with self .assertRaisesRegex (exception , re .escape (excmsg )):
76+ testformat (formatstr , args )
77+
78+ def check_exc_common (self , formatstr , args , exception , excmsg ):
79+ # test str and bytes
80+ self .check_exc (formatstr , args , exception , excmsg )
81+ if isinstance (args , dict ):
82+ args = {k .encode ('ascii' ): v for k , v in args .items ()}
83+ self .check_exc (formatstr .encode ('ascii' ), args , exception , excmsg )
84+
9885 def test_common_format (self ):
9986 # test the format identifiers that work the same across
10087 # str, bytes, and bytearrays (integer, float, oct, hex)
@@ -271,6 +258,7 @@ def test_common_format(self):
271258
272259 if verbose :
273260 print ('Testing exceptions' )
261+ test_exc_common = self .check_exc_common
274262 test_exc_common ('abc %' , (), ValueError , "stray % at position 4" )
275263 test_exc_common ('abc % %s' , 1 , ValueError ,
276264 "stray % at position 4 or unexpected format character '%' at position 6" )
@@ -365,6 +353,7 @@ def test_str_format(self):
365353 # Test exception for unknown format characters, etc.
366354 if verbose :
367355 print ('Testing exceptions' )
356+ test_exc = self .check_exc
368357 test_exc ('abc %b' , 1 , ValueError ,
369358 "unsupported format %b at position 4" )
370359 test_exc ("abc %\n d" , 1 , ValueError ,
@@ -468,6 +457,7 @@ def __bytes__(self):
468457 # Test exception for unknown format characters, etc.
469458 if verbose :
470459 print ('Testing exceptions' )
460+ test_exc = self .check_exc
471461 test_exc (b"abc %\n d" , 1 , ValueError ,
472462 "stray % at position 4 or unexpected format character with code 0x0a at position 5" )
473463 test_exc (b"abc %'d" , 1 , ValueError ,
0 commit comments