Debian Codegraph @

tests/test_io.py

raw
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 def tchan(self, channel):
28 trap = StringIO()
29 chan = StringIO()
30 text = "Hello"
31
32 std_ori = getattr(sys, channel)
33 setattr(sys, channel, trap)
34
35 tee = Tee(chan, channel=channel)
36
37 print(text, end="", file=chan)
38 trap_val = trap.getvalue()
39 self.assertEqual(chan.getvalue(), text)
40
41 tee.close()
42
43 setattr(sys, channel, std_ori)
44 assert getattr(sys, channel) == std_ori
45
46 def test(self):
47 for chan in ["stdout", "stderr"]:
48 self.tchan(chan)
49
50
51 class TestIOStream(unittest.TestCase):
52 def test_capture_output(self):
53 """capture_output() context works"""
54
55 with capture_output() as io:
56 print("hi, stdout")
57 print("hi, stderr", file=sys.stderr)
58
59 self.assertEqual(io.stdout, "hi, stdout\n")
60 self.assertEqual(io.stderr, "hi, stderr\n")