test_kernelapp.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. from __future__ import division
  2. import os
  3. import shutil
  4. from subprocess import Popen, PIPE
  5. import sys
  6. from tempfile import mkdtemp
  7. import time
  8. PY3 = sys.version_info[0] >= 3
  9. def _launch(extra_env):
  10. env = os.environ.copy()
  11. env.update(extra_env)
  12. return Popen([sys.executable, '-c',
  13. 'from jupyter_client.kernelapp import main; main()'],
  14. env=env, stderr=(PIPE if PY3 else None))
  15. WAIT_TIME = 10
  16. POLL_FREQ = 10
  17. def hacky_wait(p):
  18. """Python 2 subprocess doesn't have timeouts :-("""
  19. for _ in range(WAIT_TIME * POLL_FREQ):
  20. if p.poll() is not None:
  21. return p.returncode
  22. time.sleep(1 / POLL_FREQ)
  23. else:
  24. raise AssertionError("Process didn't exit in {} seconds"
  25. .format(WAIT_TIME))
  26. def test_kernelapp_lifecycle():
  27. # Check that 'jupyter kernel' starts and terminates OK.
  28. runtime_dir = mkdtemp()
  29. startup_dir = mkdtemp()
  30. started = os.path.join(startup_dir, 'started')
  31. try:
  32. p = _launch({'JUPYTER_RUNTIME_DIR': runtime_dir,
  33. 'JUPYTER_CLIENT_TEST_RECORD_STARTUP_PRIVATE': started,
  34. })
  35. # Wait for start
  36. for _ in range(WAIT_TIME * POLL_FREQ):
  37. if os.path.isfile(started):
  38. break
  39. time.sleep(1 / POLL_FREQ)
  40. else:
  41. raise AssertionError("No started file created in {} seconds"
  42. .format(WAIT_TIME))
  43. # Connection file should be there by now
  44. files = os.listdir(runtime_dir)
  45. assert len(files) == 1
  46. cf = files[0]
  47. assert cf.startswith('kernel')
  48. assert cf.endswith('.json')
  49. # Send SIGTERM to shut down
  50. p.terminate()
  51. if PY3:
  52. _, stderr = p.communicate(timeout=WAIT_TIME)
  53. assert cf in stderr.decode('utf-8', 'replace')
  54. else:
  55. hacky_wait(p)
  56. finally:
  57. shutil.rmtree(runtime_dir)
  58. shutil.rmtree(startup_dir)