utils.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. """Testing utils for jupyter_client tests
  2. """
  3. import os
  4. pjoin = os.path.join
  5. import sys
  6. try:
  7. from unittest.mock import patch
  8. except ImportError:
  9. from mock import patch
  10. import pytest
  11. from ipython_genutils.tempdir import TemporaryDirectory
  12. skip_win32 = pytest.mark.skipif(sys.platform.startswith('win'), reason="Windows")
  13. class test_env(object):
  14. """Set Jupyter path variables to a temporary directory
  15. Useful as a context manager or with explicit start/stop
  16. """
  17. def start(self):
  18. self.test_dir = td = TemporaryDirectory()
  19. self.env_patch = patch.dict(os.environ, {
  20. 'JUPYTER_CONFIG_DIR': pjoin(td.name, 'jupyter'),
  21. 'JUPYTER_DATA_DIR': pjoin(td.name, 'jupyter_data'),
  22. 'JUPYTER_RUNTIME_DIR': pjoin(td.name, 'jupyter_runtime'),
  23. 'IPYTHONDIR': pjoin(td.name, 'ipython'),
  24. })
  25. self.env_patch.start()
  26. def stop(self):
  27. self.env_patch.stop()
  28. self.test_dir.cleanup()
  29. def __enter__(self):
  30. self.start()
  31. return self.test_dir.name
  32. def __exit__(self, *exc_info):
  33. self.stop()
  34. def execute(code='', kc=None, **kwargs):
  35. """wrapper for doing common steps for validating an execution request"""
  36. from .test_message_spec import validate_message
  37. if kc is None:
  38. kc = KC
  39. msg_id = kc.execute(code=code, **kwargs)
  40. reply = kc.get_shell_msg(timeout=TIMEOUT)
  41. validate_message(reply, 'execute_reply', msg_id)
  42. busy = kc.get_iopub_msg(timeout=TIMEOUT)
  43. validate_message(busy, 'status', msg_id)
  44. assert busy['content']['execution_state'] == 'busy'
  45. if not kwargs.get('silent'):
  46. execute_input = kc.get_iopub_msg(timeout=TIMEOUT)
  47. validate_message(execute_input, 'execute_input', msg_id)
  48. assert execute_input['content']['code'] == code
  49. return msg_id, reply['content']