1 # encoding: utf-8 2 """Tests for io.py""" 3 4 # Copyright (c) IPython Development Team. 5 # Distributed under the terms of the Modified BSD License. 6 7 8 import sys 9 from io import StringIO 10 11 import unittest 12 13 from IPython.utils.io import Tee, capture_output 14 15 16 def test_tee_simple(): 17 "Very simple check with stdout only" 18 chan = StringIO() 19 text = 'Hello' 20 tee = Tee(chan, channel='stdout') 21 print(text, file=chan) 22 assert chan.getvalue() == text + "\n" 23 tee.close() 24 25 26 class TeeTestCase(unittest.TestCase): 27 28 def tchan(self, channel): 29 trap = StringIO() 30 chan = StringIO() 31 text = 'Hello' 32 33 std_ori = getattr(sys, channel) 34 setattr(sys, channel, trap) 35 36 tee = Tee(chan, channel=channel) 37 38 print(text, end='', file=chan) 39 trap_val = trap.getvalue() 40 self.assertEqual(chan.getvalue(), text) 41 42 tee.close() 43 44 setattr(sys, channel, std_ori) 45 assert getattr(sys, channel) == std_ori 46 47 def test(self): 48 for chan in ['stdout', 'stderr']: 49 self.tchan(chan) 50 51 class TestIOStream(unittest.TestCase): 52 53 def test_capture_output(self): 54 """capture_output() context works""" 55 56 with capture_output() as io: 57 print("hi, stdout") 58 print("hi, stderr", file=sys.stderr) 59 60 self.assertEqual(io.stdout, "hi, stdout\n") 61 self.assertEqual(io.stderr, "hi, stderr\n") 62