browser_check.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. # -*- coding: utf-8 -*-
  2. """
  3. This module is meant to run JupyterLab in a headless browser, making sure
  4. the application launches and starts up without errors.
  5. """
  6. import asyncio
  7. import inspect
  8. import logging
  9. import os
  10. import shutil
  11. import subprocess
  12. import sys
  13. import time
  14. from concurrent.futures import ThreadPoolExecutor
  15. from os import path as osp
  16. from jupyter_server.serverapp import aliases, flags
  17. from jupyter_server.utils import pathname2url, urljoin
  18. from tornado.ioloop import IOLoop
  19. from tornado.iostream import StreamClosedError
  20. from tornado.websocket import WebSocketClosedError
  21. from traitlets import Bool
  22. from .labapp import LabApp, get_app_dir
  23. from .tests.test_app import TestEnv
  24. here = osp.abspath(osp.dirname(__file__))
  25. test_flags = dict(flags)
  26. test_flags["core-mode"] = ({"BrowserApp": {"core_mode": True}}, "Start the app in core mode.")
  27. test_flags["dev-mode"] = ({"BrowserApp": {"dev_mode": True}}, "Start the app in dev mode.")
  28. test_flags["watch"] = ({"BrowserApp": {"watch": True}}, "Start the app in watch mode.")
  29. test_aliases = dict(aliases)
  30. test_aliases["app-dir"] = "BrowserApp.app_dir"
  31. class LogErrorHandler(logging.Handler):
  32. """A handler that exits with 1 on a logged error."""
  33. def __init__(self):
  34. super().__init__(level=logging.ERROR)
  35. self.errored = False
  36. def filter(self, record):
  37. # Handle known StreamClosedError from Tornado
  38. # These occur when we forcibly close Websockets or
  39. # browser connections during the test.
  40. # https://github.com/tornadoweb/tornado/issues/2834
  41. if (
  42. hasattr(record, "exc_info")
  43. and not record.exc_info is None
  44. and isinstance(record.exc_info[1], (StreamClosedError, WebSocketClosedError))
  45. ):
  46. return
  47. return super().filter(record)
  48. def emit(self, record):
  49. print(record.msg, file=sys.stderr)
  50. self.errored = True
  51. def run_test(app, func):
  52. """Synchronous entry point to run a test function.
  53. func is a function that accepts an app url as a parameter and returns a result.
  54. func can be synchronous or asynchronous. If it is synchronous, it will be run
  55. in a thread, so asynchronous is preferred.
  56. """
  57. IOLoop.current().spawn_callback(run_test_async, app, func)
  58. async def run_test_async(app, func):
  59. """Run a test against the application.
  60. func is a function that accepts an app url as a parameter and returns a result.
  61. func can be synchronous or asynchronous. If it is synchronous, it will be run
  62. in a thread, so asynchronous is preferred.
  63. """
  64. handler = LogErrorHandler()
  65. app.log.addHandler(handler)
  66. env_patch = TestEnv()
  67. env_patch.start()
  68. app.log.info("Running async test")
  69. # The entry URL for browser tests is different in notebook >= 6.0,
  70. # since that uses a local HTML file to point the user at the app.
  71. if hasattr(app, "browser_open_file"):
  72. url = urljoin("file:", pathname2url(app.browser_open_file))
  73. else:
  74. url = app.display_url
  75. # Allow a synchronous function to be passed in.
  76. if inspect.iscoroutinefunction(func):
  77. test = func(url)
  78. else:
  79. app.log.info("Using thread pool executor to run test")
  80. loop = asyncio.get_event_loop()
  81. executor = ThreadPoolExecutor()
  82. task = loop.run_in_executor(executor, func, url)
  83. test = asyncio.wait([task])
  84. try:
  85. await test
  86. except Exception as e:
  87. app.log.critical("Caught exception during the test:")
  88. app.log.error(str(e))
  89. app.log.info("Test Complete")
  90. result = 0
  91. if handler.errored:
  92. result = 1
  93. app.log.critical("Exiting with 1 due to errors")
  94. else:
  95. app.log.info("Exiting normally")
  96. app.log.info("Stopping server...")
  97. try:
  98. app.http_server.stop()
  99. app.io_loop.stop()
  100. env_patch.stop()
  101. except Exception as e:
  102. app.log.error(str(e))
  103. result = 1
  104. finally:
  105. time.sleep(2)
  106. os._exit(result)
  107. async def run_async_process(cmd, **kwargs):
  108. """Run an asynchronous command"""
  109. proc = await asyncio.create_subprocess_exec(*cmd, **kwargs)
  110. stdout, stderr = await proc.communicate()
  111. if proc.returncode != 0:
  112. raise RuntimeError(str(cmd) + " exited with " + str(proc.returncode))
  113. return stdout, stderr
  114. async def run_browser(url):
  115. """Run the browser test and return an exit code."""
  116. target = osp.join(get_app_dir(), "browser_test")
  117. if not osp.exists(osp.join(target, "node_modules")):
  118. if not osp.exists(target):
  119. os.makedirs(osp.join(target))
  120. await run_async_process(["jlpm", "init", "-y"], cwd=target)
  121. await run_async_process(["jlpm", "add", "playwright@^1.9.2"], cwd=target)
  122. shutil.copy(osp.join(here, "browser-test.js"), osp.join(target, "browser-test.js"))
  123. await run_async_process(["node", "browser-test.js", url], cwd=target)
  124. def run_browser_sync(url):
  125. """Run the browser test and return an exit code."""
  126. target = osp.join(get_app_dir(), "browser_test")
  127. if not osp.exists(osp.join(target, "node_modules")):
  128. os.makedirs(target)
  129. subprocess.call(["jlpm", "init", "-y"], cwd=target)
  130. subprocess.call(["jlpm", "add", "playwright@^1.9.2"], cwd=target)
  131. shutil.copy(osp.join(here, "browser-test.js"), osp.join(target, "browser-test.js"))
  132. return subprocess.check_call(["node", "browser-test.js", url], cwd=target)
  133. class BrowserApp(LabApp):
  134. """An app the launches JupyterLab and waits for it to start up, checking for
  135. JS console errors, JS errors, and Python logged errors.
  136. """
  137. name = __name__
  138. open_browser = False
  139. serverapp_config = {"base_url": "/foo/"}
  140. default_url = "/lab?reset"
  141. ip = "127.0.0.1"
  142. flags = test_flags
  143. aliases = test_aliases
  144. test_browser = Bool(True)
  145. def initialize_settings(self):
  146. self.settings.setdefault("page_config_data", dict())
  147. self.settings["page_config_data"]["browserTest"] = True
  148. self.settings["page_config_data"]["buildAvailable"] = False
  149. self.settings["page_config_data"]["exposeAppInBrowser"] = True
  150. super().initialize_settings()
  151. def initialize_handlers(self):
  152. func = run_browser if self.test_browser else lambda url: 0
  153. if os.name == "nt" and func == run_browser:
  154. func = run_browser_sync
  155. run_test(self.serverapp, func)
  156. super().initialize_handlers()
  157. def _jupyter_server_extension_points():
  158. return [{"module": __name__, "app": BrowserApp}]
  159. # TODO: remove handling of --notebook arg and the following two
  160. # functions in JupyterLab 4.0
  161. def load_jupyter_server_extension(serverapp):
  162. extension = BrowserApp()
  163. extension.serverapp = serverapp
  164. extension.load_config_file()
  165. extension.update_config(serverapp.config)
  166. extension.parse_command_line(serverapp.extra_args)
  167. extension.initialize()
  168. def _jupyter_server_extension_paths():
  169. return [{"module": "jupyterlab.browser_check"}]
  170. if __name__ == "__main__":
  171. skip_options = ["--no-browser-test", "--no-chrome-test"]
  172. for option in skip_options:
  173. if option in sys.argv:
  174. BrowserApp.test_browser = False
  175. sys.argv.remove(option)
  176. if "--notebook" in sys.argv:
  177. from notebook.notebookapp import NotebookApp
  178. NotebookApp.default_url = "/lab"
  179. sys.argv.remove("--notebook")
  180. NotebookApp.nbserver_extensions = {"jupyterlab.browser_check": True}
  181. NotebookApp.open_browser = False
  182. NotebookApp.launch_instance()
  183. else:
  184. BrowserApp.launch_instance()