example_check.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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. import os
  13. import shutil
  14. import subprocess
  15. import sys
  16. from os import path as osp
  17. from jupyter_server.serverapp import ServerApp
  18. from tornado.ioloop import IOLoop
  19. from traitlets import Bool, Dict, Unicode
  20. from jupyterlab.browser_check import run_async_process, run_test
  21. from jupyterlab.labapp import get_app_dir
  22. here = osp.abspath(osp.dirname(__file__))
  23. def main():
  24. # Load the main file and grab the example class so we can subclass
  25. example_dir = sys.argv.pop()
  26. mod_path = osp.abspath(osp.join(example_dir, "main.py"))
  27. spec = importlib.util.spec_from_file_location("example", mod_path)
  28. mod = importlib.util.module_from_spec(spec)
  29. spec.loader.exec_module(mod)
  30. sys.modules[__name__] = mod
  31. class App(mod.ExampleApp):
  32. """An app that launches an example and waits for it to start up, checking for
  33. JS console errors, JS errors, and Python logged errors.
  34. """
  35. name = __name__
  36. open_browser = False
  37. serverapp_config = {"base_url": "/foo/", "root_dir": osp.abspath(example_dir)}
  38. ip = "127.0.0.1"
  39. def initialize_settings(self):
  40. run_test(self.serverapp, run_browser)
  41. super().initialize_settings()
  42. def _jupyter_server_extension_points():
  43. return [{"module": __name__, "app": App}]
  44. mod._jupyter_server_extension_points = _jupyter_server_extension_points
  45. App.__name__ = osp.basename(example_dir).capitalize() + "Test"
  46. App.launch_instance()
  47. async def run_browser(url):
  48. """Run the browser test and return an exit code."""
  49. # Run the browser test and return an exit code.
  50. target = osp.join(get_app_dir(), "example_test")
  51. if not osp.exists(osp.join(target, "node_modules")):
  52. if not osp.exists(target):
  53. os.makedirs(osp.join(target))
  54. await run_async_process(["npm", "init", "-y"], cwd=target)
  55. await run_async_process(["npm", "install", "puppeteer@^4"], cwd=target)
  56. shutil.copy(
  57. osp.join(here, "chrome-example-test.js"), osp.join(target, "chrome-example-test.js")
  58. )
  59. await run_async_process(["node", "chrome-example-test.js", url], cwd=target)
  60. if __name__ == "__main__":
  61. main()