test_io.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. # encoding: utf-8
  2. """Tests for io.py"""
  3. # Copyright (c) IPython Development Team.
  4. # Distributed under the terms of the Modified BSD License.
  5. from __future__ import print_function
  6. from __future__ import absolute_import
  7. import io as stdlib_io
  8. import os.path
  9. import stat
  10. import sys
  11. from subprocess import Popen, PIPE
  12. import unittest
  13. import nose.tools as nt
  14. from IPython.testing.decorators import skipif, skip_win32
  15. from IPython.utils.io import Tee, capture_output
  16. from IPython.utils.py3compat import doctest_refactor_print, PY3
  17. from IPython.utils.tempdir import TemporaryDirectory
  18. if PY3:
  19. from io import StringIO
  20. else:
  21. from StringIO import StringIO
  22. def test_tee_simple():
  23. "Very simple check with stdout only"
  24. chan = StringIO()
  25. text = 'Hello'
  26. tee = Tee(chan, channel='stdout')
  27. print(text, file=chan)
  28. nt.assert_equal(chan.getvalue(), text+"\n")
  29. class TeeTestCase(unittest.TestCase):
  30. def tchan(self, channel, check='close'):
  31. trap = StringIO()
  32. chan = StringIO()
  33. text = 'Hello'
  34. std_ori = getattr(sys, channel)
  35. setattr(sys, channel, trap)
  36. tee = Tee(chan, channel=channel)
  37. print(text, end='', file=chan)
  38. setattr(sys, channel, std_ori)
  39. trap_val = trap.getvalue()
  40. nt.assert_equal(chan.getvalue(), text)
  41. if check=='close':
  42. tee.close()
  43. else:
  44. del tee
  45. def test(self):
  46. for chan in ['stdout', 'stderr']:
  47. for check in ['close', 'del']:
  48. self.tchan(chan, check)
  49. def test_io_init():
  50. """Test that io.stdin/out/err exist at startup"""
  51. for name in ('stdin', 'stdout', 'stderr'):
  52. cmd = doctest_refactor_print("from IPython.utils import io;print io.%s.__class__"%name)
  53. p = Popen([sys.executable, '-c', cmd],
  54. stdout=PIPE)
  55. p.wait()
  56. classname = p.stdout.read().strip().decode('ascii')
  57. # __class__ is a reference to the class object in Python 3, so we can't
  58. # just test for string equality.
  59. assert 'IPython.utils.io.IOStream' in classname, classname
  60. def test_capture_output():
  61. """capture_output() context works"""
  62. with capture_output() as io:
  63. print('hi, stdout')
  64. print('hi, stderr', file=sys.stderr)
  65. nt.assert_equal(io.stdout, 'hi, stdout\n')
  66. nt.assert_equal(io.stderr, 'hi, stderr\n')