Exemple #1
0
def test_show(unittest):
    from dtale.app import show
    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.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.logger', mock.Mock()))
        stack.enter_context(mock.patch('dtale.views.in_ipython_frontend', mock.Mock(return_value=True)))

        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))
        instance = show(data=test_data, subprocess=False, name='foo')
        assert instance.__repr__() == ''
        assert instance.__str__() == ''
        instance.adjust_cell_dimensions(height=600)

    # cleanup
    global_state.cleanup()
Exemple #2
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)
Exemple #3
0
def test_build_data_id():
    import dtale.global_state as global_state

    global_state.cleanup()
    assert global_state.build_data_id() == 1

    df = pd.DataFrame([1, 2, 3, 4, 5])
    data = {str(idx + 1): df for idx in range(10)}
    for k, v in data.items():
        global_state.set_data(k, v)
    assert global_state.build_data_id() == 11
Exemple #4
0
def initialize_store(test_data):
    """Helper function that sets up a default store with some data in it"""
    global_state.cleanup()
    global_state.use_default_store()
    for data_id in ["1", "2"]:
        global_state.set_data(data_id, test_data)
        global_state.set_dtypes(data_id, build_dtypes_state(test_data))
        global_state.set_settings(data_id, dict(locked=[]))
        global_state.set_name(data_id, "test_name" + data_id)
        global_state.set_context_variables(
            data_id, dict(favorite_words=["foo", "bar", "baz"]))
        global_state.set_history(data_id, ["foo", "bar", "baz"])
Exemple #5
0
def initialize_store(test_data):
    """Helper function that sets up a default store with some data in it"""
    global_state.cleanup()
    global_state.use_default_store()
    for data_id in ['1', '2']:
        global_state.set_data(data_id, test_data)
        global_state.set_dtypes(data_id, build_dtypes_state(test_data))
        global_state.set_settings(data_id, dict(locked=[]))
        global_state.set_metadata(data_id, dict(name='test_name'))
        global_state.set_context_variables(
            data_id, dict(favorite_words=['foo', 'bar', 'baz']))
        global_state.set_history(data_id, ['foo', 'bar', 'baz'])
Exemple #6
0
 def shutdown_server():
     global ACTIVE_HOST, ACTIVE_PORT
     """
     This function that checks if flask.request.environ['werkzeug.server.shutdown'] exists and
     if so, executes that function
     """
     logger.info("Executing shutdown...")
     func = request.environ.get("werkzeug.server.shutdown")
     if func is None:
         raise RuntimeError("Not running with the Werkzeug Server")
     func()
     global_state.cleanup()
     ACTIVE_PORT = None
     ACTIVE_HOST = None
Exemple #7
0
def test_use_shelve_store(unittest, tmpdir, test_data):
    initialize_store(test_data)
    contents_before = get_store_contents()
    type_before = get_store_type()

    directory = tmpdir.mkdir("test_use_shelve_store").dirname
    global_state.use_shelve_store(directory)
    contents_after = get_store_contents()
    type_after = get_store_type()

    unittest.assertEqual(contents_before, contents_after)
    unittest.assertNotEqual(type_before, type_after)

    global_state.cleanup(data_id="1")
    unittest.assertNotEqual(contents_after, get_store_contents())
Exemple #8
0
def test_cleanup_data_id():
    import dtale.global_state as global_state

    for prop in [
            'data', 'dtypes', 'settings', 'metadata', 'context_variables',
            'history'
    ]:
        getattr(global_state, 'set_{}'.format(prop))('1', 'test')

    global_state.cleanup('1')

    for prop in [
            'data', 'dtypes', 'settings', 'metadata', 'context_variables',
            'history'
    ]:
        assert getattr(global_state, 'get_{}'.format(prop))('1') is None
Exemple #9
0
def offline_chart(df, chart_type=None, query=None, x=None, y=None, z=None, group=None, agg=None, window=None,
                  rolling_comp=None, barmode=None, barsort=None, yaxis=None, filepath=None, **kwargs):
    """
    Builds the HTML for a plotly chart figure to saved to a file or output to a jupyter notebook

    :param df: integer string identifier for a D-Tale process's data
    :type df: :class:`pandas:pandas.DataFrame`
    :param chart_type: type of chart, possible options are line|bar|pie|scatter|3d_scatter|surface|heatmap
    :type chart_type: str
    :param query: pandas dataframe query string
    :type query: str, optional
    :param x: column to use for the X-Axis
    :type x: str
    :param y: columns to use for the Y-Axes
    :type y: list of str
    :param z: column to use for the Z-Axis
    :type z: str, optional
    :param group: column(s) to use for grouping
    :type group: list of str or str, optional
    :param agg: specific aggregation that can be applied to y or z axes.  Possible values are: count, first, last mean,
                median, min, max, std, var, mad, prod, sum.  This is included in label of axis it is being applied to.
    :type agg: str, optional
    :param window: number of days to include in rolling aggregations
    :type window: int, optional
    :param rolling_comp: computation to use in rolling aggregations
    :type rolling_comp: str, optional
    :param barmode: mode to use for bar chart display. possible values are stack|group(default)|overlay|relative
    :type barmode: str, optional
    :param barsort: axis name to sort the bars in a bar chart by (default is the 'x', but other options are any of
                    columns names used in the 'y' parameter
    :type barsort: str, optional
    :param filepath: location to save HTML output
    :type filepath: str, optional
    :param kwargs: optional keyword arguments, here in case invalid arguments are passed to this function
    :type kwargs: dict
    :return: possible outcomes are:
             - if run within a jupyter notebook and no 'filepath' is specified it will print the resulting HTML
               within a cell in your notebook
             - if 'filepath' is specified it will save the chart to the path specified
             - otherwise it will return the HTML output as a string
    """
    instance = startup(url=None, data=df, data_id=999)
    output = instance.offline_chart(chart_type=chart_type, query=query, x=x, y=y, z=z, group=group, agg=agg,
                                    window=window, rolling_comp=rolling_comp, barmode=barmode, barsort=barsort,
                                    yaxis=yaxis, filepath=filepath, **kwargs)
    global_state.cleanup()
    return output
Exemple #10
0
def test_use_redis_store(unittest, tmpdir, test_data):
    pytest.importorskip('redislite')

    initialize_store(test_data)
    contents_before = get_store_contents()
    type_before = get_store_type()

    directory = tmpdir.mkdir('test_use_redis_store').dirname
    global_state.use_redis_store(directory)
    contents_after = get_store_contents()
    type_after = get_store_type()

    unittest.assertEqual(contents_before, contents_after)
    unittest.assertNotEqual(type_before, type_after)

    global_state.cleanup(data_id='1')
    unittest.assertNotEqual(contents_after, get_store_contents())
Exemple #11
0
def test_cleanup(unittest, test_data):
    initialize_store(test_data)
    base_contents = get_store_contents()

    # should just remove 1 entry, leaving one still in there
    global_state.cleanup(data_id="2")
    without_one = get_store_contents()

    # should remove ALL entries
    initialize_store(test_data)
    global_state.cleanup()
    without_any = get_store_contents()

    unittest.assertNotEqual(base_contents, without_one, "should have removed one")
    unittest.assertNotEqual(base_contents, without_any, "should have removed all")
    unittest.assertNotEqual(
        without_one, without_any, "first should still have some data"
    )
Exemple #12
0
def test_show(unittest):
    from dtale.app import show
    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.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.logger", mock.Mock()))
        stack.enter_context(
            mock.patch("dtale.views.in_ipython_frontend",
                       mock.Mock(return_value=True)))

        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))
        instance = show(data=test_data, subprocess=False, name="foo")
        assert instance.__repr__() == ""
        assert instance.__str__() == ""
        instance.adjust_cell_dimensions(height=600)

    # cleanup
    global_state.cleanup()
Exemple #13
0
def teardown_module(module):
    global_state.cleanup()
    global_state.use_default_store()
Exemple #14
0
def setup_function(function):
    global_state.cleanup()
    global_state.use_default_store()
Exemple #15
0
def setup_function(function):
    global_state.cleanup()
    predefined_filters.set_filters([])
Exemple #16
0
def teardown_function(function):
    global_state.cleanup()
    global_state.use_default_store()
Exemple #17
0
def setup_module(module):
    global_state.cleanup()
    global_state.use_default_store()
Exemple #18
0
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()
Exemple #19
0
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, *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)
        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(
            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://localhost:9999/shutdown'
        assert global_state.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,
                        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

    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,
                        ignore_duplicate=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', 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/5'

        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, *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(
            {'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()
Exemple #20
0
def kill_instance(data_id: str) -> None:
    data_id = _format_data_id(data_id)
    global_state.cleanup(data_id)
Exemple #21
0
def teardown_function(function):
    global_state.cleanup()
    predefined_filters.set_filters([])
Exemple #22
0
def test_open_browser():
    from dtale.app import show
    import dtale.global_state as global_state

    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()))
        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_browser_proc = stack.enter_context(mock.patch("subprocess.Popen"))
        mock_webbrowser = stack.enter_context(mock.patch("webbrowser.open"))
        stack.enter_context(
            mock.patch("distutils.spawn.find_executable",
                       mock.Mock(return_value=None)))
        stack.enter_context(mock.patch("dtale.env_util.IS_WINDOWS", False))
        stack.enter_context(mock.patch("dtale.env_util.IS_LINUX_OR_BSD", True))
        stack.enter_context(mock.patch("dtale.env_util.IS_DARWIN", False))
        instance = show(
            data_loader=mock_data_loader,
            subprocess=False,
            port=9999,
            open_browser=True,
            ignore_duplicate=True,
        )
        mock_run.assert_not_called()
        mock_webbrowser.assert_called()
        assert mock_webbrowser.mock_calls[0].args[
            0] == "http://localhost:9999/dtale/main/{}".format(
                instance._data_id)
        mock_browser_proc.reset_mock()
        mock_webbrowser.reset_mock()

        stack.enter_context(
            mock.patch("distutils.spawn.find_executable",
                       mock.Mock(return_value="exists")))
        instance.open_browser()
        mock_browser_proc.assert_called()
        assert mock_browser_proc.mock_calls[0].args[0][
            1] == "http://localhost:9999/dtale/main/{}".format(
                instance._data_id)
        mock_browser_proc.reset_mock()
        mock_webbrowser.reset_mock()

        stack.enter_context(mock.patch("dtale.env_util.IS_WINDOWS", False))
        stack.enter_context(mock.patch("dtale.env_util.IS_LINUX_OR_BSD",
                                       False))
        stack.enter_context(mock.patch("dtale.env_util.IS_DARWIN", True))

        instance.open_browser()
        mock_browser_proc.assert_called()
        assert mock_browser_proc.mock_calls[0].args[0][
            1] == "http://localhost:9999/dtale/main/{}".format(
                instance._data_id)
        mock_browser_proc.reset_mock()
        mock_webbrowser.reset_mock()

        stack.enter_context(mock.patch("dtale.env_util.IS_WINDOWS", True))
        stack.enter_context(mock.patch("dtale.env_util.IS_LINUX_OR_BSD",
                                       False))
        stack.enter_context(mock.patch("dtale.env_util.IS_DARWIN", False))

        instance.open_browser()
        mock_webbrowser.assert_called()
        assert mock_webbrowser.mock_calls[0].args[
            0] == "http://localhost:9999/dtale/main/{}".format(
                instance._data_id)

    global_state.cleanup()
Exemple #23
0
def kill_instance(data_id: str) -> None:
    global_state.cleanup(data_id)