# -*- coding: utf-8 -*-

from __future__ import print_function

import os
from threading import Event, Thread

import jupyter_core
import jupyter_core.paths
import requests
from ipython_genutils.tempdir import TemporaryDirectory
from notebook.notebookapp import NotebookApp
from notebook.tests.launchnotebook import NotebookTestBase
from notebook.utils import url_path_join
from tornado.ioloop import IOLoop

pjoin = os.path.join

try:
    from unittest.mock import patch
except ImportError:
    from mock import patch  # py2


class ConfiguratorTest(NotebookTestBase):

    nbapp_kwargs = dict(
        log_level=0,
        open_browser=False,
        port_retries=0,
    )
    if hasattr(NotebookApp, 'nbserver_extensions'):
        nbapp_kwargs['nbserver_extensions'] = {
            'themysto.nbextensions_configurator': True,
        }
    else:
        nbapp_kwargs['server_extensions'] = [
            'themysto.nbextensions_configurator',
        ]

    @classmethod
    def setup_class(cls):
        """
        Similar to jupyter version, but uses our kwargs.
        It seems that, at least for notebook < 4.2.0b1, setting
        server_extensions in the config kwarg isn't sufficient to get them
        loaded, so we have to actually pass the value as a separate kwarg
        """

        cls.home_dir = TemporaryDirectory()
        data_dir = TemporaryDirectory()
        cls.env_patch = patch.dict('os.environ', {
            'HOME': cls.home_dir.name,
            'IPYTHONDIR': pjoin(cls.home_dir.name, '.ipython'),
            'JUPYTER_DATA_DIR': data_dir.name
        })
        cls.env_patch.start()
        cls.path_patch = patch.object(
            jupyter_core.paths, 'SYSTEM_JUPYTER_PATH', [])
        cls.path_patch.start()
        cls.config_dir = TemporaryDirectory()
        cls.data_dir = data_dir
        cls.runtime_dir = TemporaryDirectory()
        cls.notebook_dir = TemporaryDirectory()

        # setup keyword arguments
        cls.nbapp_kwargs.setdefault('port', cls.port)
        cls.nbapp_kwargs.setdefault('config_dir', cls.config_dir.name)
        cls.nbapp_kwargs.setdefault('data_dir', cls.data_dir.name)
        cls.nbapp_kwargs.setdefault('runtime_dir', cls.runtime_dir.name)
        cls.nbapp_kwargs.setdefault('notebook_dir', cls.notebook_dir.name)
        cls.nbapp_kwargs.setdefault(
            'base_url', getattr(cls, 'url_prefix', ''))
        cls.nbapp_kwargs.setdefault('config', cls.config)

        started = Event()

        def start_thread():
            app = cls.notebook = NotebookApp(**cls.nbapp_kwargs)

            # don't register signal handler during tests
            app.init_signal = lambda: None
            # clear log handlers and propagate to root for nose to capture it
            # needs to be redone after initialize, which reconfigures logging
            app.log.propagate = True
            app.log.handlers = []
            app.initialize(argv=[])
            app.log.propagate = True
            app.log.handlers = []
            loop = IOLoop.current()
            loop.add_callback(started.set)
            try:
                app.start()
            finally:
                # set the event, so failure to start doesn't cause a hang
                started.set()
                # themysto multi-version:
                # app.session_manager.close only exists for notebook>4.0
                if hasattr(app.session_manager, 'close'):
                    app.session_manager.close()
        cls.notebook_thread = Thread(target=start_thread)
        cls.notebook_thread.start()
        started.wait()
        cls.wait_until_alive()

    def test_load_nbextensions_page(self):
        """check that /nbextensions url loads"""
        response = requests.request(
            'GET', url_path_join(self.base_url(), 'nbextensions'),
        )
        response.raise_for_status()

@@ -68,611 +68,302 @@
 ort 
-os%0Afrom threading import Event, Thread%0A%0Aimport jupyter_core%0Aimport jupyter_core.paths%0Aimport requests%0Afrom ipython_genutils.tempdir import TemporaryDirectory%0Afrom notebook.notebookapp import NotebookApp%0Afrom notebook.tests.launchnotebook import NotebookTestBase%0Afrom notebook.utils import url_path_join%0Afrom tornado.ioloop import IOLoop%0A%0Apjoin = os.path.join%0A%0Atry:%0A    from unittest.mock import patch%0Aexcept ImportError:%0A    from mock import patch  # py2%0A%0A%0Aclass ConfiguratorTest(NotebookTestBase):%0A%0A    nbapp_kwargs = dict(%0A        log_level=0,%0A        open_browser=False,%0A        port_retries=0,%0A    )
+requests%0Afrom notebook.notebookapp import NotebookApp%0Afrom notebook.tests.launchnotebook import NotebookTestBase%0Afrom notebook.utils import url_path_join%0Afrom traitlets.config import Config%0A%0A%0Aclass ConfiguratorTest(NotebookTestBase):%0A%0A    config = Config()%0A    config.NotebookApp.log_level = 0%0A
 %0A   
@@ -419,30 +419,35 @@
         
-nbapp_kwargs%5B'
+config.NotebookApp.
 nbserver
@@ -457,18 +457,16 @@
 tensions
-'%5D
  = %7B%0A   
@@ -550,22 +550,27 @@
     
-nbapp_kwargs%5B'
+config.NotebookApp.
 serv
@@ -586,10 +586,8 @@
 ions
-'%5D
  = %5B
@@ -652,2674 +652,8 @@
  %5D%0A%0A
-    @classmethod%0A    def setup_class(cls):%0A        %22%22%22%0A        Similar to jupyter version, but uses our kwargs.%0A        It seems that, at least for notebook %3C 4.2.0b1, setting%0A        server_extensions in the config kwarg isn't sufficient to get them%0A        loaded, so we have to actually pass the value as a separate kwarg%0A        %22%22%22%0A%0A        cls.home_dir = TemporaryDirectory()%0A        data_dir = TemporaryDirectory()%0A        cls.env_patch = patch.dict('os.environ', %7B%0A            'HOME': cls.home_dir.name,%0A            'IPYTHONDIR': pjoin(cls.home_dir.name, '.ipython'),%0A            'JUPYTER_DATA_DIR': data_dir.name%0A        %7D)%0A        cls.env_patch.start()%0A        cls.path_patch = patch.object(%0A            jupyter_core.paths, 'SYSTEM_JUPYTER_PATH', %5B%5D)%0A        cls.path_patch.start()%0A        cls.config_dir = TemporaryDirectory()%0A        cls.data_dir = data_dir%0A        cls.runtime_dir = TemporaryDirectory()%0A        cls.notebook_dir = TemporaryDirectory()%0A%0A        # setup keyword arguments%0A        cls.nbapp_kwargs.setdefault('port', cls.port)%0A        cls.nbapp_kwargs.setdefault('config_dir', cls.config_dir.name)%0A        cls.nbapp_kwargs.setdefault('data_dir', cls.data_dir.name)%0A        cls.nbapp_kwargs.setdefault('runtime_dir', cls.runtime_dir.name)%0A        cls.nbapp_kwargs.setdefault('notebook_dir', cls.notebook_dir.name)%0A        cls.nbapp_kwargs.setdefault(%0A            'base_url', getattr(cls, 'url_prefix', ''))%0A        cls.nbapp_kwargs.setdefault('config', cls.config)%0A%0A        started = Event()%0A%0A        def start_thread():%0A            app = cls.notebook = NotebookApp(**cls.nbapp_kwargs)%0A%0A            # don't register signal handler during tests%0A            app.init_signal = lambda: None%0A            # clear log handlers and propagate to root for nose to capture it%0A            # needs to be redone after initialize, which reconfigures logging%0A            app.log.propagate = True%0A            app.log.handlers = %5B%5D%0A            app.initialize(argv=%5B%5D)%0A            app.log.propagate = True%0A            app.log.handlers = %5B%5D%0A            loop = IOLoop.current()%0A            loop.add_callback(started.set)%0A            try:%0A                app.start()%0A            finally:%0A                # set the event, so failure to start doesn't cause a hang%0A                started.set()%0A                # themysto multi-version:%0A                # app.session_manager.close only exists for notebook%3E4.0%0A                if hasattr(app.session_manager, 'close'):%0A                    app.session_manager.close()%0A        cls.notebook_thread = Thread(target=start_thread)%0A        cls.notebook_thread.start()%0A        started.wait()%0A        cls.wait_until_alive()%0A%0A
     

simplify test_nbextensions_configurator now that I've figure out how to set config values