test_notebookapp.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. """Test NotebookApp"""
  2. import getpass
  3. import logging
  4. import os
  5. import re
  6. import signal
  7. from subprocess import Popen, PIPE, STDOUT
  8. import sys
  9. from tempfile import NamedTemporaryFile
  10. try:
  11. from unittest.mock import patch
  12. except ImportError:
  13. from mock import patch # py2
  14. import nose.tools as nt
  15. from traitlets.tests.utils import check_help_all_output
  16. from jupyter_core.application import NoStart
  17. from ipython_genutils.tempdir import TemporaryDirectory
  18. from traitlets import TraitError
  19. from notebook import notebookapp, __version__
  20. from notebook.auth.security import passwd_check
  21. NotebookApp = notebookapp.NotebookApp
  22. from .launchnotebook import NotebookTestBase
  23. def test_help_output():
  24. """ipython notebook --help-all works"""
  25. check_help_all_output('notebook')
  26. def test_server_info_file():
  27. td = TemporaryDirectory()
  28. nbapp = NotebookApp(runtime_dir=td.name, log=logging.getLogger())
  29. def get_servers():
  30. return list(notebookapp.list_running_servers(nbapp.runtime_dir))
  31. nbapp.initialize(argv=[])
  32. nbapp.write_server_info_file()
  33. servers = get_servers()
  34. nt.assert_equal(len(servers), 1)
  35. nt.assert_equal(servers[0]['port'], nbapp.port)
  36. nt.assert_equal(servers[0]['url'], nbapp.connection_url)
  37. nbapp.remove_server_info_file()
  38. nt.assert_equal(get_servers(), [])
  39. # The ENOENT error should be silenced.
  40. nbapp.remove_server_info_file()
  41. def test_nb_dir():
  42. with TemporaryDirectory() as td:
  43. app = NotebookApp(notebook_dir=td)
  44. nt.assert_equal(app.notebook_dir, td)
  45. def test_no_create_nb_dir():
  46. with TemporaryDirectory() as td:
  47. nbdir = os.path.join(td, 'notebooks')
  48. app = NotebookApp()
  49. with nt.assert_raises(TraitError):
  50. app.notebook_dir = nbdir
  51. def test_missing_nb_dir():
  52. with TemporaryDirectory() as td:
  53. nbdir = os.path.join(td, 'notebook', 'dir', 'is', 'missing')
  54. app = NotebookApp()
  55. with nt.assert_raises(TraitError):
  56. app.notebook_dir = nbdir
  57. def test_invalid_nb_dir():
  58. with NamedTemporaryFile() as tf:
  59. app = NotebookApp()
  60. with nt.assert_raises(TraitError):
  61. app.notebook_dir = tf
  62. def test_nb_dir_with_slash():
  63. with TemporaryDirectory(suffix="_slash" + os.sep) as td:
  64. app = NotebookApp(notebook_dir=td)
  65. nt.assert_false(app.notebook_dir.endswith(os.sep))
  66. def test_nb_dir_root():
  67. root = os.path.abspath(os.sep) # gets the right value on Windows, Posix
  68. app = NotebookApp(notebook_dir=root)
  69. nt.assert_equal(app.notebook_dir, root)
  70. def test_generate_config():
  71. with TemporaryDirectory() as td:
  72. app = NotebookApp(config_dir=td)
  73. app.initialize(['--generate-config', '--allow-root'])
  74. with nt.assert_raises(NoStart):
  75. app.start()
  76. assert os.path.exists(os.path.join(td, 'jupyter_notebook_config.py'))
  77. #test if the version testin function works
  78. def test_pep440_version():
  79. for version in [
  80. '4.1.0.b1',
  81. '4.1.b1',
  82. '4.2',
  83. 'X.y.z',
  84. '1.2.3.dev1.post2',
  85. ]:
  86. def loc():
  87. with nt.assert_raises(ValueError):
  88. raise_on_bad_version(version)
  89. yield loc
  90. for version in [
  91. '4.1.1',
  92. '4.2.1b3',
  93. ]:
  94. yield (raise_on_bad_version, version)
  95. pep440re = re.compile('^(\d+)\.(\d+)\.(\d+((a|b|rc)\d+)?)(\.post\d+)?(\.dev\d*)?$')
  96. def raise_on_bad_version(version):
  97. if not pep440re.match(version):
  98. raise ValueError("Versions String does apparently not match Pep 440 specification, "
  99. "which might lead to sdist and wheel being seen as 2 different release. "
  100. "E.g: do not use dots for beta/alpha/rc markers.")
  101. def test_current_version():
  102. raise_on_bad_version(__version__)
  103. def test_notebook_password():
  104. password = 'secret'
  105. with TemporaryDirectory() as td:
  106. with patch.dict('os.environ', {
  107. 'JUPYTER_CONFIG_DIR': td,
  108. }), patch.object(getpass, 'getpass', return_value=password):
  109. app = notebookapp.NotebookPasswordApp(log_level=logging.ERROR)
  110. app.initialize([])
  111. app.start()
  112. nb = NotebookApp()
  113. nb.load_config_file()
  114. nt.assert_not_equal(nb.password, '')
  115. passwd_check(nb.password, password)
  116. class TestingStopApp(notebookapp.NbserverStopApp):
  117. """For testing the logic of NbserverStopApp."""
  118. def __init__(self, **kwargs):
  119. super(TestingStopApp, self).__init__(**kwargs)
  120. self.servers_shut_down = []
  121. def shutdown_server(self, server):
  122. self.servers_shut_down.append(server)
  123. return True
  124. def test_notebook_stop():
  125. def list_running_servers(runtime_dir):
  126. for port in range(100, 110):
  127. yield {
  128. 'pid': 1000 + port,
  129. 'port': port,
  130. 'base_url': '/',
  131. 'hostname': 'localhost',
  132. 'notebook_dir': '/',
  133. 'secure': False,
  134. 'token': '',
  135. 'password': False,
  136. 'url': 'http://localhost:%i' % port,
  137. }
  138. mock_servers = patch('notebook.notebookapp.list_running_servers', list_running_servers)
  139. # test stop with a match
  140. with mock_servers:
  141. app = TestingStopApp()
  142. app.initialize(['105'])
  143. app.start()
  144. nt.assert_equal(len(app.servers_shut_down), 1)
  145. nt.assert_equal(app.servers_shut_down[0]['port'], 105)
  146. # test no match
  147. with mock_servers, patch('os.kill') as os_kill:
  148. app = TestingStopApp()
  149. app.initialize(['999'])
  150. with nt.assert_raises(SystemExit) as exc:
  151. app.start()
  152. nt.assert_equal(exc.exception.code, 1)
  153. nt.assert_equal(len(app.servers_shut_down), 0)
  154. class NotebookAppTests(NotebookTestBase):
  155. def test_list_running_servers(self):
  156. servers = list(notebookapp.list_running_servers())
  157. assert len(servers) >= 1
  158. assert self.port in {info['port'] for info in servers}