test_kernel.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. # Copyright (c) IPython Development Team.
  2. # Distributed under the terms of the Modified BSD License.
  3. from __future__ import print_function
  4. import sys
  5. import unittest
  6. from ipykernel.inprocess.blocking import BlockingInProcessKernelClient
  7. from ipykernel.inprocess.manager import InProcessKernelManager
  8. from ipykernel.inprocess.ipkernel import InProcessKernel
  9. from ipykernel.tests.utils import assemble_output
  10. from IPython.testing.decorators import skipif_not_matplotlib
  11. from IPython.utils.io import capture_output
  12. from ipython_genutils import py3compat
  13. if py3compat.PY3:
  14. from io import StringIO
  15. else:
  16. from StringIO import StringIO
  17. class InProcessKernelTestCase(unittest.TestCase):
  18. def setUp(self):
  19. self.km = InProcessKernelManager()
  20. self.km.start_kernel()
  21. self.kc = self.km.client()
  22. self.kc.start_channels()
  23. self.kc.wait_for_ready()
  24. @skipif_not_matplotlib
  25. def test_pylab(self):
  26. """Does %pylab work in the in-process kernel?"""
  27. kc = self.kc
  28. kc.execute('%pylab')
  29. out, err = assemble_output(kc.iopub_channel)
  30. self.assertIn('matplotlib', out)
  31. def test_raw_input(self):
  32. """ Does the in-process kernel handle raw_input correctly?
  33. """
  34. io = StringIO('foobar\n')
  35. sys_stdin = sys.stdin
  36. sys.stdin = io
  37. try:
  38. if py3compat.PY3:
  39. self.kc.execute('x = input()')
  40. else:
  41. self.kc.execute('x = raw_input()')
  42. finally:
  43. sys.stdin = sys_stdin
  44. assert self.km.kernel.shell.user_ns.get('x') == 'foobar'
  45. def test_stdout(self):
  46. """ Does the in-process kernel correctly capture IO?
  47. """
  48. kernel = InProcessKernel()
  49. with capture_output() as io:
  50. kernel.shell.run_cell('print("foo")')
  51. assert io.stdout == 'foo\n'
  52. kc = BlockingInProcessKernelClient(kernel=kernel, session=kernel.session)
  53. kernel.frontends.append(kc)
  54. kc.execute('print("bar")')
  55. out, err = assemble_output(kc.iopub_channel)
  56. assert out == 'bar\n'
  57. def test_getpass_stream(self):
  58. "Tests that kernel getpass accept the stream parameter"
  59. kernel = InProcessKernel()
  60. kernel._allow_stdin = True
  61. kernel._input_request = lambda *args, **kwargs : None
  62. kernel.getpass(stream='non empty')