test_io.py
61 lines
| 1.4 KiB
| text/x-python
|
PythonLexer
|
r2498 | # encoding: utf-8 | ||
"""Tests for io.py""" | ||||
|
r19932 | # Copyright (c) IPython Development Team. | ||
# Distributed under the terms of the Modified BSD License. | ||||
|
r2498 | |||
import sys | ||||
|
r23108 | from io import StringIO | ||
|
r2498 | |||
|
r12372 | import unittest | ||
|
r2498 | |||
|
r27208 | from IPython.utils.io import Tee, capture_output | ||
|
r13366 | |||
|
r2498 | |||
def test_tee_simple(): | ||||
"Very simple check with stdout only" | ||||
chan = StringIO() | ||||
text = 'Hello' | ||||
tee = Tee(chan, channel='stdout') | ||||
|
r7817 | print(text, file=chan) | ||
|
r26920 | assert chan.getvalue() == text + "\n" | ||
|
r28589 | tee.close() | ||
|
r2498 | |||
|
r12372 | class TeeTestCase(unittest.TestCase): | ||
|
r2498 | |||
|
r25056 | def tchan(self, channel): | ||
|
r2498 | trap = StringIO() | ||
chan = StringIO() | ||||
text = 'Hello' | ||||
std_ori = getattr(sys, channel) | ||||
setattr(sys, channel, trap) | ||||
tee = Tee(chan, channel=channel) | ||||
|
r25056 | |||
|
r7817 | print(text, end='', file=chan) | ||
|
r2498 | trap_val = trap.getvalue() | ||
|
r26920 | self.assertEqual(chan.getvalue(), text) | ||
|
r25056 | |||
tee.close() | ||||
setattr(sys, channel, std_ori) | ||||
assert getattr(sys, channel) == std_ori | ||||
|
r2498 | |||
def test(self): | ||||
for chan in ['stdout', 'stderr']: | ||||
|
r25056 | self.tchan(chan) | ||
|
r3800 | |||
|
r25109 | class TestIOStream(unittest.TestCase): | ||
def test_capture_output(self): | ||||
"""capture_output() context works""" | ||||
with capture_output() as io: | ||||
|
r26920 | print("hi, stdout") | ||
print("hi, stderr", file=sys.stderr) | ||||
self.assertEqual(io.stdout, "hi, stdout\n") | ||||
self.assertEqual(io.stderr, "hi, stderr\n") | ||||