example_check.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. # -*- coding: utf-8 -*-
  2. """
  3. This file is mean to be called with a path to an example directory as
  4. its argument. We import the application entry point for the example
  5. and add instrument them with a puppeteer test that makes sure
  6. there are no console errors or uncaught errors prior to a sentinel
  7. string being printed.
  8. e.g. python example_check.py ./app
  9. """
  10. import importlib.util
  11. import logging
  12. from os import path as osp
  13. import os
  14. import shutil
  15. import sys
  16. import subprocess
  17. from tornado.ioloop import IOLoop
  18. from traitlets import Bool, Dict, Unicode
  19. from jupyter_server.serverapp import ServerApp
  20. from jupyterlab.labapp import get_app_dir
  21. from jupyterlab.browser_check import run_test, run_async_process
  22. from jupyter_server.serverapp import ServerApp
  23. here = osp.abspath(osp.dirname(__file__))
  24. def main():
  25. # Load the main file and grab the example class so we can subclass
  26. example_dir = sys.argv.pop()
  27. mod_path = osp.abspath(osp.join(example_dir, 'main.py'))
  28. spec = importlib.util.spec_from_file_location('example', mod_path)
  29. mod = importlib.util.module_from_spec(spec)
  30. spec.loader.exec_module(mod)
  31. sys.modules[__name__] = mod
  32. class App(mod.ExampleApp):
  33. """An app that launches an example and waits for it to start up, checking for
  34. JS console errors, JS errors, and Python logged errors.
  35. """
  36. name = __name__
  37. open_browser = False
  38. serverapp_config = {
  39. "base_url": "/foo/",
  40. "root_dir": osp.abspath(example_dir)
  41. }
  42. ip = '127.0.0.1'
  43. def initialize_settings(self):
  44. run_test(self.serverapp, run_browser)
  45. super().initialize_settings()
  46. def _jupyter_server_extension_points():
  47. return [
  48. {
  49. 'module': __name__,
  50. 'app': App
  51. }
  52. ]
  53. mod._jupyter_server_extension_points = _jupyter_server_extension_points
  54. App.__name__ = osp.basename(example_dir).capitalize() + 'Test'
  55. App.launch_instance()
  56. async def run_browser(url):
  57. """Run the browser test and return an exit code.
  58. """
  59. # Run the browser test and return an exit code.
  60. target = osp.join(get_app_dir(), 'example_test')
  61. if not osp.exists(osp.join(target, 'node_modules')):
  62. if not osp.exists(target):
  63. os.makedirs(osp.join(target))
  64. await run_async_process(["npm", "init", "-y"], cwd=target)
  65. await run_async_process(["npm", "install", "puppeteer@^4"], cwd=target)
  66. shutil.copy(osp.join(here, 'chrome-example-test.js'), osp.join(target, 'chrome-example-test.js'))
  67. await run_async_process(["node", "chrome-example-test.js", url], cwd=target)
  68. if __name__ == '__main__':
  69. main()