示例#1
0
def test_show_ngrok(unittest, builtin_pkg):
    from dtale.app import show, get_instance, instances
    import dtale.views as views
    import dtale.global_state as global_state

    orig_import = __import__
    mock_flask_ngrok = mock.Mock()
    mock_flask_ngrok._run_ngrok = lambda: "ngrok_host"

    def import_mock(name, *args, **kwargs):
        if name == "flask_ngrok":
            return mock_flask_ngrok
        return orig_import(name, *args, **kwargs)

    test_data = pd.DataFrame([dict(a=1, b=2)])
    with ExitStack() as stack:
        stack.enter_context(
            mock.patch("{}.__import__".format(builtin_pkg), side_effect=import_mock)
        )
        stack.enter_context(mock.patch("dtale.app.USE_NGROK", True))
        stack.enter_context(mock.patch("dtale.app.PY3", True))
        mock_run = stack.enter_context(
            mock.patch("dtale.app.DtaleFlask.run", mock.Mock())
        )
        stack.enter_context(
            mock.patch("dtale.app.is_up", mock.Mock(return_value=False))
        )
        mock_requests = stack.enter_context(mock.patch("requests.get", mock.Mock()))
        instance = show(
            data=test_data, subprocess=False, name="foo", ignore_duplicate=True
        )
        assert "http://ngrok_host" == instance._url
        mock_run.assert_called_once()

        pdt.assert_frame_equal(instance.data, test_data)
        tmp = test_data.copy()
        tmp["biz"] = 2.5
        instance.data = tmp
        unittest.assertEqual(
            global_state.DTYPES[instance._data_id],
            views.build_dtypes_state(tmp),
            "should update app data/dtypes",
        )

        instance2 = get_instance(instance._data_id)
        assert instance2._url == instance._url
        instances()

        assert get_instance(20) is None  # should return None for invalid data ids

        instance.kill()
        mock_requests.assert_called_once()
        assert mock_requests.call_args[0][0] == "http://ngrok_host/shutdown"
        assert global_state.METADATA["1"]["name"] == "foo"

    with ExitStack() as stack:
        stack.enter_context(mock.patch("dtale.app.USE_NGROK", True))
        stack.enter_context(mock.patch("dtale.app.PY3", False))
        with pytest.raises(Exception):
            show(data=test_data)
示例#2
0
def test_show_colab(unittest, builtin_pkg):
    from dtale.app import show, get_instance, instances
    import dtale.views as views
    import dtale.global_state as global_state

    orig_import = __import__
    mock_eval_js = mock.Mock()
    mock_eval_js.eval_js = lambda _port: "http://colab_host"

    def import_mock(name, *args, **kwargs):
        if name == "google.colab.output":
            return mock_eval_js
        return orig_import(name, *args, **kwargs)

    test_data = pd.DataFrame([dict(a=1, b=2)])
    with ExitStack() as stack:
        stack.enter_context(
            mock.patch("{}.__import__".format(builtin_pkg),
                       side_effect=import_mock))
        stack.enter_context(mock.patch("dtale.app.USE_COLAB", True))
        stack.enter_context(mock.patch("dtale.app.ACTIVE_PORT", 40000))
        stack.enter_context(mock.patch("dtale.app.ACTIVE_HOST", "localhost"))
        mock_run = stack.enter_context(
            mock.patch("dtale.app.DtaleFlask.run", mock.Mock()))
        stack.enter_context(
            mock.patch("dtale.app.is_up", mock.Mock(return_value=False)))
        mock_requests = stack.enter_context(
            mock.patch("requests.get", mock.Mock()))
        instance = show(data=test_data,
                        subprocess=False,
                        name="foo",
                        ignore_duplicate=True)
        assert "http://colab_host" == instance._url
        mock_run.assert_called_once()

        pdt.assert_frame_equal(instance.data, test_data)
        tmp = test_data.copy()
        tmp["biz"] = 2.5
        instance.data = tmp
        unittest.assertEqual(
            global_state.get_dtypes(instance._data_id),
            views.build_dtypes_state(tmp),
            "should update app data/dtypes",
        )

        instance2 = get_instance(instance._data_id)
        assert instance2._url == instance._url
        instances()

        assert get_instance(
            20) is None  # should return None for invalid data ids

        instance.kill()
        mock_requests.assert_called_once()
        assert mock_requests.call_args[0][0] == "http://colab_host/shutdown"
示例#3
0
def update_dtale_data(player_data):
    curr_data = get_instance("1")
    if curr_data is not None:
        # append data to pre-existing data in D-Tale
        curr_data = curr_data.data
        curr_data = curr_data[~(curr_data["name"] == player_data["name"].values[0])]
        player_data = pd.concat([curr_data, player_data], ignore_index=True)
        cleanup("1")
    # load data to D-Tale
    startup(data_id="1", data=player_data)
示例#4
0
文件: app.py 项目: sts-sadr/dtale
def load_data_props():
    instance = get_instance("1")

    if instance is not None:
        names = instance.data["name"].unique()
        chart_url = build_chart_url(names)
        return dict(
            names=", ".join(instance.data["name"].unique()),
            data_exists=True,
            chart_url=chart_url,
        )
    return dict(data_exists=False)
示例#5
0
def load_iframes():
    instance = get_instance("1")

    if instance is not None:
        names = instance.data["name"].unique()
        chart_url = build_chart_url(names)
        name_str = ", ".join(names)

        # use uuid so that way streamlit reloads iframes
        grid = (
            '<h3 style="padding-top: 10px">Data For: {}</h3>'
            '<iframe class="grid" src="/dtale/main/1?_id={}"/>'
        ).format(name_str, uuid.uuid4().hex)
        charts = '<iframe class="chart" src="{}&_id={}" />'.format(chart_url, uuid.uuid4().hex)
        return grid, charts
    return "", ""
示例#6
0
文件: test_app.py 项目: rlcjj/dtale
def test_show_jupyter_server_proxy(unittest):
    from dtale.app import show, get_instance, instances
    import dtale.views as views
    import dtale.global_state as global_state

    test_data = pd.DataFrame([dict(a=1, b=2)])
    with ExitStack() as stack:
        stack.enter_context(mock.patch("dtale.app.JUPYTER_SERVER_PROXY", True))
        mock_run = stack.enter_context(
            mock.patch("dtale.app.DtaleFlask.run", mock.Mock()))
        stack.enter_context(
            mock.patch("dtale.app.is_up", mock.Mock(return_value=False)))
        stack.enter_context(mock.patch("dtale.app.ACTIVE_PORT", 40000))
        stack.enter_context(mock.patch("dtale.app.ACTIVE_HOST", "localhost"))
        mock_requests = stack.enter_context(
            mock.patch("requests.get", mock.Mock()))
        instance = show(data=test_data,
                        subprocess=False,
                        name="foo",
                        ignore_duplicate=True)
        assert "/user/{}/proxy/40000".format(
            getpass.getuser()) == instance._url
        mock_run.assert_called_once()

        pdt.assert_frame_equal(instance.data, test_data)
        tmp = test_data.copy()
        tmp["biz"] = 2.5
        instance.data = tmp
        unittest.assertEqual(
            global_state.DTYPES[instance._data_id],
            views.build_dtypes_state(tmp),
            "should update app data/dtypes",
        )

        instance2 = get_instance(instance._data_id)
        assert instance2._url == instance._url
        instances()

        assert get_instance(
            20) is None  # should return None for invalid data ids

        instance.kill()
        mock_requests.assert_called_once()
        assert mock_requests.call_args[0][
            0] == "/user/{}/proxy/40000/shutdown".format(getpass.getuser())
        assert global_state.METADATA["1"]["name"] == "foo"

    with ExitStack() as stack:
        stack.enter_context(mock.patch("dtale.app.JUPYTER_SERVER_PROXY", True))
        stack.enter_context(mock.patch("dtale.app.ACTIVE_PORT", 40000))
        stack.enter_context(mock.patch("dtale.app.ACTIVE_HOST", "localhost"))
        mock_run = stack.enter_context(
            mock.patch("dtale.app.DtaleFlask.run", mock.Mock()))
        stack.enter_context(
            mock.patch("dtale.app.is_up", mock.Mock(return_value=False)))
        mock_requests = stack.enter_context(
            mock.patch("requests.get", mock.Mock()))
        instance = show(
            data=test_data,
            subprocess=False,
            ignore_duplicate=True,
            app_root="/custom_root/",
        )
        assert "/custom_root/40000" == instance._url
        mock_run.assert_called_once()

        instance2 = get_instance(instance._data_id)
        # this is a known bug where get_instance will not work if you've specified an `app_root' in show()
        assert not instance2._url == instance._url
        instances()
        instance.kill()
        mock_requests.assert_called_once()
        assert mock_requests.call_args[0][0] == "/custom_root/40000/shutdown"
示例#7
0
文件: test_app.py 项目: rlcjj/dtale
def test_show(unittest, builtin_pkg):
    from dtale.app import show, get_instance, instances
    import dtale.views as views
    import dtale.global_state as global_state

    class MockDtaleFlask(Flask):
        def __init__(self,
                     import_name,
                     reaper_on=True,
                     url=None,
                     app_root=None,
                     *args,
                     **kwargs):
            kwargs.pop("instance_relative_config", None)
            kwargs.pop("static_url_path", None)
            super(MockDtaleFlask, self).__init__(import_name, *args, **kwargs)

        def run(self, *args, **kwargs):
            pass

    instances()
    test_data = pd.DataFrame([dict(a=1, b=2)])
    with ExitStack() as stack:
        mock_run = stack.enter_context(
            mock.patch("dtale.app.DtaleFlask.run", mock.Mock()))
        mock_find_free_port = stack.enter_context(
            mock.patch("dtale.app.find_free_port",
                       mock.Mock(return_value=9999)))
        stack.enter_context(
            mock.patch("socket.gethostname",
                       mock.Mock(return_value="localhost")))
        stack.enter_context(
            mock.patch("dtale.app.is_up", mock.Mock(return_value=False)))
        mock_requests = stack.enter_context(
            mock.patch("requests.get", mock.Mock()))
        instance = show(data=test_data,
                        subprocess=False,
                        name="foo",
                        ignore_duplicate=True)
        print(instance.main_url())
        assert "http://localhost:9999" == instance._url
        assert "http://localhost:9999/dtale/main/foo" == instance.main_url()
        mock_run.assert_called_once()
        mock_find_free_port.assert_called_once()

        pdt.assert_frame_equal(instance.data, test_data)
        tmp = test_data.copy()
        tmp["biz"] = 2.5
        instance.data = tmp
        unittest.assertEqual(
            global_state.DTYPES[instance._data_id],
            views.build_dtypes_state(tmp),
            "should update app data/dtypes",
        )

        instance2 = get_instance(instance._data_id)
        assert instance2._url == instance._url
        instance2 = get_instance("foo")
        assert instance2._url == instance._url
        pdt.assert_frame_equal(instance2.data, tmp)

        instances()

        assert get_instance(
            20) is None  # should return None for invalid data ids

        instance.kill()
        mock_requests.assert_called_once()
        assert mock_requests.call_args[0][
            0] == "http://localhost:9999/shutdown"
        assert global_state.METADATA["1"]["name"] == "foo"

        instance3 = show(data=test_data,
                         subprocess=False,
                         name="It's Here",
                         ignore_duplicate=True)
        assert instance3.main_url(
        ) == "http://localhost:9999/dtale/main/its_here"
        pdt.assert_frame_equal(instance3.data, test_data)

    with ExitStack() as stack:
        mock_run = stack.enter_context(
            mock.patch("dtale.app.DtaleFlask.run", mock.Mock()))
        mock_find_free_port = stack.enter_context(
            mock.patch("dtale.app.find_free_port",
                       mock.Mock(return_value=9999)))
        stack.enter_context(
            mock.patch("socket.gethostname",
                       mock.Mock(return_value="localhost")))
        stack.enter_context(
            mock.patch("dtale.app.is_up", mock.Mock(return_value=False)))
        mock_data_loader = mock.Mock(return_value=test_data)
        instance = show(
            data_loader=mock_data_loader,
            subprocess=False,
            port=9999,
            force=True,
            debug=True,
            ignore_duplicate=True,
        )
        assert "http://localhost:9999" == instance._url
        mock_run.assert_called_once()
        mock_find_free_port.assert_not_called()
        mock_data_loader.assert_called_once()
        _, kwargs = mock_run.call_args

        assert "9999" in instance._url

    # RangeIndex test
    test_data = pd.DataFrame([1, 2, 3])
    with ExitStack() as stack:
        stack.enter_context(mock.patch("dtale.app.DtaleFlask", MockDtaleFlask))
        stack.enter_context(
            mock.patch("dtale.app.find_free_port",
                       mock.Mock(return_value=9999)))
        stack.enter_context(
            mock.patch("socket.gethostname",
                       mock.Mock(return_value="localhost")))
        stack.enter_context(
            mock.patch("dtale.app.is_up", mock.Mock(return_value=False)))
        stack.enter_context(mock.patch("dtale.app.logger", mock.Mock()))
        instance = show(data=test_data,
                        subprocess=False,
                        name="foo",
                        ignore_duplicate=True)
        assert np.array_equal(instance.data["0"].values, test_data[0].values)

    with ExitStack() as stack:
        stack.enter_context(mock.patch("dtale.app.DtaleFlask", MockDtaleFlask))
        stack.enter_context(
            mock.patch("dtale.app.find_free_port",
                       mock.Mock(return_value=9999)))
        stack.enter_context(
            mock.patch("socket.gethostname",
                       mock.Mock(return_value="localhost")))
        stack.enter_context(
            mock.patch("dtale.app.is_up", mock.Mock(return_value=False)))
        stack.enter_context(mock.patch("dtale.app.logger", mock.Mock()))
        stack.enter_context(
            mock.patch("dtale.views.in_ipython_frontend",
                       mock.Mock(return_value=False)))

        get_calls = {"ct": 0}
        getter = namedtuple("get", "ok")

        def mock_requests_get(url, verify=True):
            if url.endswith("/health"):
                is_ok = get_calls["ct"] > 0
                get_calls["ct"] += 1
                return getter(is_ok)
            return getter(True)

        stack.enter_context(mock.patch("requests.get", mock_requests_get))
        mock_display = stack.enter_context(
            mock.patch("IPython.display.display", mock.Mock()))
        mock_iframe = stack.enter_context(
            mock.patch("IPython.display.IFrame", mock.Mock()))
        instance = show(
            data=test_data,
            subprocess=True,
            name="foo",
            notebook=True,
            ignore_duplicate=True,
        )
        mock_display.assert_called_once()
        mock_iframe.assert_called_once()
        assert mock_iframe.call_args[0][
            0] == "http://localhost:9999/dtale/iframe/{}".format(
                instance._data_id)

        assert type(instance.__str__()).__name__ == "str"
        assert type(instance.__repr__()).__name__ == "str"

    class MockDtaleFlaskRunTest(Flask):
        def __init__(self,
                     import_name,
                     reaper_on=True,
                     url=None,
                     app_root=None,
                     *args,
                     **kwargs):
            kwargs.pop("instance_relative_config", None)
            kwargs.pop("static_url_path", None)
            super(MockDtaleFlaskRunTest,
                  self).__init__(import_name, *args, **kwargs)

        def run(self, *args, **kwargs):
            assert self.jinja_env.auto_reload
            assert self.config["TEMPLATES_AUTO_RELOAD"]

    with mock.patch("dtale.app.DtaleFlask", MockDtaleFlaskRunTest):
        show(
            data=test_data,
            subprocess=False,
            port=9999,
            debug=True,
            ignore_duplicate=True,
        )

    with mock.patch("dtale.app._thread.start_new_thread",
                    mock.Mock()) as mock_thread:
        show(data=test_data, subprocess=True, ignore_duplicate=True)
        mock_thread.assert_called()

    test_data = pd.DataFrame([dict(a=1, b=2)])

    with ExitStack() as stack:
        mock_build_app = stack.enter_context(
            mock.patch("dtale.app.build_app", mock.Mock()))
        stack.enter_context(
            mock.patch("dtale.app.find_free_port",
                       mock.Mock(return_value=9999)))
        stack.enter_context(
            mock.patch("socket.gethostname",
                       mock.Mock(return_value="localhost")))
        stack.enter_context(
            mock.patch("dtale.app.is_up", mock.Mock(return_value=False)))
        stack.enter_context(mock.patch("requests.get", mock.Mock()))
        show(data=test_data,
             subprocess=False,
             name="foo",
             ignore_duplicate=True)

        _, kwargs = mock_build_app.call_args
        unittest.assertEqual(
            {
                "app_root": None,
                "host": "localhost",
                "reaper_on": True
            },
            kwargs,
            "build_app should be called with defaults",
        )

    # test adding duplicate column
    with ExitStack() as stack:
        stack.enter_context(mock.patch("dtale.app.DtaleFlask", MockDtaleFlask))
        stack.enter_context(
            mock.patch("dtale.app.find_free_port",
                       mock.Mock(return_value=9999)))
        stack.enter_context(
            mock.patch("socket.gethostname",
                       mock.Mock(return_value="localhost")))
        stack.enter_context(
            mock.patch("dtale.app.is_up", mock.Mock(return_value=False)))
        stack.enter_context(mock.patch("requests.get", mock.Mock()))
        instance = show(
            data=pd.DataFrame([dict(a=1, b=2)]),
            subprocess=False,
            name="foo",
            ignore_duplicate=True,
        )
        with pytest.raises(Exception):
            instance.data = instance.data.rename(columns={"b": "a"})

        curr_instance_ct = len(global_state.DATA)
        show(data=pd.DataFrame([dict(a=1, b=2)]), subprocess=False, name="foo")
        assert curr_instance_ct == len(global_state.DATA)

    # cleanup
    global_state.cleanup()
示例#8
0
def test_show(unittest, builtin_pkg):
    from dtale.app import show, get_instance, instances
    import dtale.views as views

    test_data = pd.DataFrame([dict(a=1, b=2)])
    with ExitStack() as stack:
        mock_run = stack.enter_context(
            mock.patch('dtale.app.DtaleFlask.run', mock.Mock()))
        mock_find_free_port = stack.enter_context(
            mock.patch('dtale.app.find_free_port',
                       mock.Mock(return_value=9999)))
        stack.enter_context(
            mock.patch('socket.gethostname',
                       mock.Mock(return_value='localhost')))
        stack.enter_context(
            mock.patch('dtale.app.is_up', mock.Mock(return_value=False)))
        mock_requests = stack.enter_context(
            mock.patch('requests.get', mock.Mock()))
        instance = show(data=test_data, subprocess=False, name='foo')
        assert 'http://localhost:9999' == instance._url
        mock_run.assert_called_once()
        mock_find_free_port.assert_called_once()

        pdt.assert_frame_equal(instance.data, test_data)
        tmp = test_data.copy()
        tmp['biz'] = 2.5
        instance.data = tmp
        unittest.assertEqual(views.DTYPES[instance._data_id],
                             views.build_dtypes_state(tmp),
                             'should update app data/dtypes')

        instance2 = get_instance(instance._data_id)
        assert instance2._url == instance._url
        assert instances()[instance._data_id]._url == instance._url

        assert get_instance(
            20) is None  # should return None for invalid data ids

        instance.kill()
        mock_requests.assert_called_once()
        mock_requests.call_args[0][0] == 'http://localhost:9999/shutdown'
        assert views.METADATA['1']['name'] == 'foo'

    with ExitStack() as stack:
        mock_run = stack.enter_context(
            mock.patch('dtale.app.DtaleFlask.run', mock.Mock()))
        mock_find_free_port = stack.enter_context(
            mock.patch('dtale.app.find_free_port',
                       mock.Mock(return_value=9999)))
        stack.enter_context(
            mock.patch('socket.gethostname',
                       mock.Mock(return_value='localhost')))
        stack.enter_context(
            mock.patch('dtale.app.is_up', mock.Mock(return_value=False)))
        mock_data_loader = mock.Mock(return_value=test_data)
        instance = show(data_loader=mock_data_loader,
                        subprocess=False,
                        port=9999,
                        force=True,
                        debug=True)
        assert 'http://localhost:9999' == instance._url
        mock_run.assert_called_once()
        mock_find_free_port.assert_not_called()
        mock_data_loader.assert_called_once()
        _, kwargs = mock_run.call_args

        assert '9999' in instance._url

    with ExitStack() as stack:
        mock_run = stack.enter_context(
            mock.patch('dtale.app.DtaleFlask.run', mock.Mock()))
        stack.enter_context(
            mock.patch('dtale.app.find_free_port',
                       mock.Mock(return_value=9999)))
        stack.enter_context(
            mock.patch('socket.gethostname',
                       mock.Mock(return_value='localhost')))
        stack.enter_context(
            mock.patch('dtale.app.is_up', mock.Mock(return_value=True)))
        mock_data_loader = mock.Mock(return_value=test_data)
        mock_webbrowser = stack.enter_context(mock.patch('webbrowser.get'))
        instance = show(data_loader=mock_data_loader,
                        subprocess=False,
                        port=9999,
                        open_browser=True)
        mock_run.assert_not_called()
        webbrowser_instance = mock_webbrowser.return_value
        assert 'http://localhost:9999/dtale/main/3' == webbrowser_instance.open.call_args[
            0][0]
        instance.open_browser()
        assert 'http://localhost:9999/dtale/main/3' == webbrowser_instance.open.mock_calls[
            1][1][0]

    # RangeIndex test
    test_data = pd.DataFrame([1, 2, 3])
    with ExitStack() as stack:
        stack.enter_context(mock.patch('dtale.app.DtaleFlask.run',
                                       mock.Mock()))
        stack.enter_context(
            mock.patch('dtale.app.find_free_port',
                       mock.Mock(return_value=9999)))
        stack.enter_context(
            mock.patch('socket.gethostname',
                       mock.Mock(return_value='localhost')))
        stack.enter_context(
            mock.patch('dtale.app.is_up', mock.Mock(return_value=False)))
        stack.enter_context(mock.patch('dtale.app.logger', mock.Mock()))
        instance = show(data=test_data, subprocess=False, name='foo')
        assert np.array_equal(instance.data['0'].values, test_data[0].values)

    with ExitStack() as stack:
        stack.enter_context(mock.patch('dtale.app.DtaleFlask.run',
                                       mock.Mock()))
        stack.enter_context(
            mock.patch('dtale.app.find_free_port',
                       mock.Mock(return_value=9999)))
        stack.enter_context(
            mock.patch('socket.gethostname',
                       mock.Mock(return_value='localhost')))
        stack.enter_context(
            mock.patch('dtale.app.is_up', mock.Mock(return_value=False)))
        stack.enter_context(mock.patch('dtale.app.logger', mock.Mock()))
        stack.enter_context(
            mock.patch('dtale.views.in_ipython_frontend',
                       mock.Mock(return_value=False)))

        get_calls = {'ct': 0}
        getter = namedtuple('get', 'ok')

        def mock_requests_get(url, verify=True):
            if url.endswith('/health'):
                is_ok = get_calls['ct'] > 0
                get_calls['ct'] += 1
                return getter(is_ok)
            return getter(True)

        stack.enter_context(mock.patch('requests.get', mock_requests_get))
        mock_display = stack.enter_context(
            mock.patch('IPython.display.display', mock.Mock()))
        mock_iframe = stack.enter_context(
            mock.patch('IPython.display.IFrame', mock.Mock()))
        instance = show(data=test_data,
                        subprocess=True,
                        name='foo',
                        notebook=True)
        mock_display.assert_called_once()
        mock_iframe.assert_called_once()
        assert mock_iframe.call_args[0][
            0] == 'http://localhost:9999/dtale/iframe/5'

        assert type(instance.__str__()).__name__ == 'str'
        assert type(instance.__repr__()).__name__ == 'str'

    def mock_run(self, *args, **kwargs):
        assert self.jinja_env.auto_reload
        assert self.config['TEMPLATES_AUTO_RELOAD']

    with mock.patch('dtale.app.DtaleFlask.run', mock_run):
        show(data=test_data, subprocess=False, port=9999, debug=True)

    with mock.patch('dtale.app._thread.start_new_thread',
                    mock.Mock()) as mock_thread:
        show(data=test_data, subprocess=True)
        mock_thread.assert_called()

    test_data = pd.DataFrame([dict(a=1, b=2)])

    with ExitStack() as stack:
        mock_build_app = stack.enter_context(
            mock.patch('dtale.app.build_app', mock.Mock()))
        stack.enter_context(
            mock.patch('dtale.app.find_free_port',
                       mock.Mock(return_value=9999)))
        stack.enter_context(
            mock.patch('socket.gethostname',
                       mock.Mock(return_value='localhost')))
        stack.enter_context(
            mock.patch('dtale.app.is_up', mock.Mock(return_value=False)))
        stack.enter_context(mock.patch('requests.get', mock.Mock()))
        show(data=test_data, subprocess=False, name='foo')

        _, kwargs = mock_build_app.call_args
        unittest.assertEqual({
            'host': 'localhost',
            'reaper_on': True
        }, kwargs, 'build_app should be called with defaults')

    # test adding duplicate column
    with ExitStack() as stack:
        stack.enter_context(mock.patch('dtale.app.DtaleFlask.run',
                                       mock.Mock()))
        stack.enter_context(
            mock.patch('dtale.app.find_free_port',
                       mock.Mock(return_value=9999)))
        stack.enter_context(
            mock.patch('socket.gethostname',
                       mock.Mock(return_value='localhost')))
        stack.enter_context(
            mock.patch('dtale.app.is_up', mock.Mock(return_value=False)))
        stack.enter_context(mock.patch('requests.get', mock.Mock()))
        instance = show(data=pd.DataFrame([dict(a=1, b=2)]),
                        subprocess=False,
                        name='foo')
        with pytest.raises(Exception):
            instance.data = instance.data.rename(columns={'b': 'a'})

    # cleanup
    views.DATA = {}
    views.DTYPES = {}
    views.SETTINGS = {}
    views.METADATA = {}
示例#9
0
    div.stBlock-horiz div.stBlock:first-child > div {
      margin-top: 1em;
    }
</style> 
"""
PREAMBLE = (
    "# DISCLAIMER: 'df' refers to the data you passed in when calling 'dtale.show'\n\n"
    "import pandas as pd\n\n"
    "if isinstance(df, (pd.DatetimeIndex, pd.MultiIndex)):\n"
    "\tdf = df.to_frame(index=False)\n\n"
    "# remove any pre-existing indices for ease of use in the D-Tale code, but this is not required\n"
    "df = df.reset_index().drop('index', axis=1, errors='ignore')\n"
    "df.columns = [str(c) for c in df.columns]  # update columns to strings in case they are numbers"
)

curr_instance = get_instance("1")
if curr_instance is None:
    df = pd.DataFrame(dict(a=list(range(1, 11))))
    startup(data_id="1", data=df)
    curr_instance = get_instance("1")

html = f"""
{CSS}
<iframe src="/dtale/main/1" style="height: 100%;width: 100%"/>
"""
st.markdown(html, unsafe_allow_html=True)

col1, col2 = st.beta_columns((1, 3))
reload_columns = col1.button("Reload")
columns = [c for c in curr_instance.data.columns]
if reload_columns:
示例#10
0
文件: test_app.py 项目: yg79/dtale
def test_show_jupyter_server_proxy(unittest):
    from dtale.app import show, get_instance, instances
    import dtale.app as dtale_app
    import dtale.views as views
    import dtale.global_state as global_state

    test_data = pd.DataFrame([dict(a=1, b=2)])
    with ExitStack() as stack:
        stack.enter_context(mock.patch('dtale.app.JUPYTER_SERVER_PROXY', True))
        mock_run = stack.enter_context(
            mock.patch('dtale.app.DtaleFlask.run', mock.Mock()))
        stack.enter_context(
            mock.patch('dtale.app.is_up', mock.Mock(return_value=False)))
        mock_requests = stack.enter_context(
            mock.patch('requests.get', mock.Mock()))
        instance = show(data=test_data,
                        subprocess=False,
                        name='foo',
                        ignore_duplicate=True)
        assert '/user/{}/proxy/{}'.format(
            getpass.getuser(), dtale_app.ACTIVE_PORT) == instance._url
        mock_run.assert_called_once()

        pdt.assert_frame_equal(instance.data, test_data)
        tmp = test_data.copy()
        tmp['biz'] = 2.5
        instance.data = tmp
        unittest.assertEqual(global_state.DTYPES[instance._data_id],
                             views.build_dtypes_state(tmp),
                             'should update app data/dtypes')

        instance2 = get_instance(instance._data_id)
        assert instance2._url == instance._url
        instances()

        assert get_instance(
            20) is None  # should return None for invalid data ids

        instance.kill()
        mock_requests.assert_called_once()
        assert mock_requests.call_args[0][
            0] == '/user/{}/proxy/{}/shutdown'.format(getpass.getuser(),
                                                      dtale_app.ACTIVE_PORT)
        assert global_state.METADATA['1']['name'] == 'foo'

    with ExitStack() as stack:
        stack.enter_context(mock.patch('dtale.app.JUPYTER_SERVER_PROXY', True))
        mock_run = stack.enter_context(
            mock.patch('dtale.app.DtaleFlask.run', mock.Mock()))
        stack.enter_context(
            mock.patch('dtale.app.is_up', mock.Mock(return_value=False)))
        mock_requests = stack.enter_context(
            mock.patch('requests.get', mock.Mock()))
        instance = show(data=test_data,
                        subprocess=False,
                        ignore_duplicate=True,
                        app_root='/custom_root/')
        assert '/custom_root/{}'.format(dtale_app.ACTIVE_PORT) == instance._url
        mock_run.assert_called_once()

        instance2 = get_instance(instance._data_id)
        # this is a known bug where get_instance will not work if you've specified an `app_root' in show()
        assert not instance2._url == instance._url
        instances()
        instance.kill()
        mock_requests.assert_called_once()
        assert mock_requests.call_args[0][
            0] == '/custom_root/{}/shutdown'.format(dtale_app.ACTIVE_PORT)
示例#11
0
def load_data_props():
    instance = get_instance("1")
    if instance is not None:
        return dict(names=", ".join(instance.data["name"].unique()),
                    data_exists=True)
    return dict(data_exists=False)