run-test.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. # Copyright (c) Jupyter Development Team.
  2. # Distributed under the terms of the Modified BSD License.
  3. from __future__ import print_function, absolute_import
  4. import atexit
  5. import json
  6. import os
  7. import sys
  8. import shutil
  9. import tempfile
  10. from tornado.ioloop import IOLoop
  11. from tornado.process import Subprocess
  12. from notebook.notebookapp import NotebookApp
  13. from traitlets import Bool, Unicode
  14. HERE = os.path.dirname(__file__)
  15. def create_notebook_dir():
  16. """Create a temporary directory with some file structure."""
  17. root_dir = tempfile.mkdtemp(prefix='mock_contents')
  18. os.mkdir(os.path.join(root_dir, 'src'))
  19. with open(os.path.join(root_dir, 'src', 'temp.txt'), 'w') as fid:
  20. fid.write('hello')
  21. atexit.register(lambda: shutil.rmtree(root_dir, True))
  22. return root_dir
  23. def run_command(cmd):
  24. """Run a task in a thread and exit with the return code."""
  25. shell = os.name == 'nt'
  26. p = Subprocess(cmd, shell=shell)
  27. print('\n\nRunning command: "%s"\n\n' % ' '.join(cmd))
  28. p.set_exit_callback(sys.exit)
  29. def get_command(nbapp):
  30. """Get the command to run."""
  31. terminalsAvailable = nbapp.web_app.settings['terminals_available']
  32. # Compatibility with Notebook 4.2.
  33. token = getattr(nbapp, 'token', '')
  34. config = dict(baseUrl=nbapp.connection_url, token=token,
  35. terminalsAvailable=str(terminalsAvailable))
  36. print('\n\nNotebook config:')
  37. print(json.dumps(config))
  38. with open(os.path.join(HERE, 'build', 'injector.js'), 'w') as fid:
  39. fid.write("""
  40. var node = document.createElement('script');
  41. node.id = 'jupyter-config-data';
  42. node.type = 'application/json';
  43. node.textContent = '%s';
  44. document.body.appendChild(node);
  45. """ % json.dumps(config))
  46. return ['karma', 'start'] + ARGS
  47. class TestApp(NotebookApp):
  48. """A notebook app that runs a karma test."""
  49. open_browser = Bool(False)
  50. notebook_dir = Unicode(create_notebook_dir())
  51. allow_origin = Unicode('*')
  52. def start(self):
  53. # Cannot run against Notebook 4.3.0 due to auth incompatibilities.
  54. if self.version == '4.3.0':
  55. msg = ('Cannot run unit tests against Notebook 4.3.0. '
  56. 'Please upgrade to Notebook 4.3.1+')
  57. self.log.error(msg)
  58. sys.exit(1)
  59. # Run the command after the ioloop starts.
  60. IOLoop.current().add_callback(run_command, get_command(self))
  61. super(TestApp, self).start()
  62. if __name__ == '__main__':
  63. # Reserve the command line arguments for karma.
  64. ARGS = sys.argv[1:]
  65. sys.argv = sys.argv[:1]
  66. try:
  67. nbapp = TestApp.launch_instance()
  68. except KeyboardInterrupt:
  69. nbapp.stop()