55from test import test_support
66
77import sys
8- import io
8+ try :
9+ # 3.x
10+ from io import StringIO
11+ except ImportError :
12+ # 2.x
13+ from StringIO import StringIO
14+
915from contextlib import contextmanager
1016
1117NotDefined = object ()
@@ -51,7 +57,7 @@ def __str__(self):
5157 return self .x
5258
5359class TestPrint (unittest .TestCase ):
54- def check (self , expected , args , * ,
60+ def check (self , expected , args ,
5561 sep = NotDefined , end = NotDefined , file = NotDefined ):
5662 # Capture sys.stdout in a StringIO. Call print with args,
5763 # and with sep, end, and file, if they're defined. Result
@@ -63,21 +69,21 @@ def check(self, expected, args, *,
6369 end is not NotDefined ,
6470 file is not NotDefined )]
6571
66- t = io . StringIO ()
72+ t = StringIO ()
6773 with stdout_redirected (t ):
6874 fn (args , sep , end , file )
6975
7076 self .assertEqual (t .getvalue (), expected )
7177
7278 def test_print (self ):
73- def x (expected , args , * , sep = NotDefined , end = NotDefined ):
79+ def x (expected , args , sep = NotDefined , end = NotDefined ):
7480 # Run the test 2 ways: not using file, and using
7581 # file directed to a StringIO
7682
7783 self .check (expected , args , sep = sep , end = end )
7884
7985 # When writing to a file, stdout is expected to be empty
80- o = io . StringIO ()
86+ o = StringIO ()
8187 self .check ('' , args , sep = sep , end = end , file = o )
8288
8389 # And o will contain the expected output
@@ -87,13 +93,27 @@ def x(expected, args, *, sep=NotDefined, end=NotDefined):
8793 x ('a\n ' , ('a' ,))
8894 x ('None\n ' , (None ,))
8995 x ('1 2\n ' , (1 , 2 ))
96+ x ('1 2\n ' , (1 , ' ' , 2 ))
9097 x ('1*2\n ' , (1 , 2 ), sep = '*' )
9198 x ('1 s' , (1 , 's' ), end = '' )
9299 x ('a\n b\n ' , ('a' , 'b' ), sep = '\n ' )
93100 x ('1.01' , (1.0 , 1 ), sep = '' , end = '' )
94101 x ('1*a*1.3+' , (1 , 'a' , 1.3 ), sep = '*' , end = '+' )
102+ x ('a\n \n b\n ' , ('a\n ' , 'b' ), sep = '\n ' )
103+ x ('\0 + +\0 \n ' , ('\0 ' , ' ' , '\0 ' ), sep = '+' )
104+
105+ x ('a\n b\n ' , ('a\n ' , 'b' ))
106+ x ('a\n b\n ' , ('a\n ' , 'b' ), sep = None )
107+ x ('a\n b\n ' , ('a\n ' , 'b' ), end = None )
108+ x ('a\n b\n ' , ('a\n ' , 'b' ), sep = None , end = None )
95109
96110 x ('*\n ' , (ClassWith__str__ ('*' ),))
111+ x ('abc 1\n ' , (ClassWith__str__ ('abc' ), 1 ))
112+
113+ # errors
114+ self .assertRaises (TypeError , print , '' , sep = 3 )
115+ self .assertRaises (TypeError , print , '' , end = 3 )
116+ self .assertRaises (AttributeError , print , '' , file = '' )
97117
98118def test_main ():
99119 test_support .run_unittest (TestPrint )
0 commit comments