Esempio n. 1
0
def test_expanded_signal(items, user, user2):
    items.append(user)
    items.append(user2, user)
    item_expanded = CheckCalled(items, 'item-expanded')
    items.expand_row(items._path_for(user), True)
    refresh_gui()
    assert item_expanded.called
Esempio n. 2
0
def test_delete_file(view, tmpdir, monkeypatch):
    monkeypatch.setattr(view.svc, 'yesno_dlg', lambda v:True)
    assert tmpdir.join('browse/test.py').check()
    view.file_list.selected_item = view.file_list[0]
    view.svc.actions.on_delete(None)
    refresh_gui()
    assert not tmpdir.join('browse/test.py').check()
Esempio n. 3
0
def test_expand_item(items, user, user2):
    items.append(user)
    items.append(user2, user)
    item_expanded = CheckCalled(items, 'item-expanded')
    items.expand_item(user)
    refresh_gui()
    assert item_expanded.called
Esempio n. 4
0
def test_delete_file(view, tmpdir, monkeypatch):
    monkeypatch.setattr(view.svc, 'yesno_dlg', lambda v: True)
    assert tmpdir.join('browse/test.py').check()
    view.file_list.selected_item = view.file_list[0]
    view.svc.actions.on_delete(None)
    refresh_gui()
    assert not tmpdir.join('browse/test.py').check()
Esempio n. 5
0
 def wait_for_gui_process(self, retry_count=20, retry_duration_s=1):
     '''
     .. versionchanged:: 2.7.2
         Do not execute `refresh_gui()` while waiting for response from
         `hub_execute()`.
     '''
     start = datetime.now()
     for i in xrange(retry_count):
         try:
             hub_execute(self.name, 'ping', timeout_s=5, silent=True)
         except Exception:
             logger.debug('[wait_for_gui_process] failed (%d of %d)',
                          i + 1,
                          retry_count,
                          exc_info=True)
         else:
             logger.info('[wait_for_gui_process] success (%d of %d)', i + 1,
                         retry_count)
             self.alive_timestamp = datetime.now()
             return
         for j in xrange(10):
             time.sleep(retry_duration_s / 10.)
             refresh_gui()
     raise IOError('Timed out after %ss waiting for GUI process to connect '
                   'to hub.' % si_format(
                       (datetime.now() - start).total_seconds()))
Esempio n. 6
0
def test_update_and_read(proxy, value):
    proxy.update(value)
    if isinstance(proxy.widget, gtk.FileChooserButton):
        refresh_gui(0.1, 0.1)
    else:
        refresh_gui()
    data = proxy.read()
    assert data == value
Esempio n. 7
0
def test_paste_view():
    mock = Mock(name='svc')
    mock.get_pastebin_types.return_value = pastebin_types
    view = PastebinEditorView(mock)

    view.paste_proxy.update(LodgeIt)
    #XXX: more
    refresh_gui()
Esempio n. 8
0
def test_add_proxy_for():
    m = ProxyGroup()
    e = gtk.Entry()
    m.add_proxy_for('foo', e)
    check = CheckCalled(m, 'changed')
    e.set_text('a')
    refresh_gui()
    assert check.called_count == 1
Esempio n. 9
0
def test_paste_view():
    mock = Mock(name='svc')
    mock.get_pastebin_types.return_value = pastebin_types
    view = PastebinEditorView(mock)

    view.paste_proxy.update(LodgeIt)
    #XXX: more
    refresh_gui()
Esempio n. 10
0
def test_select_single_fails_when_select_multiple_is_set(items, user):
    items.append(user)
    items.get_selection().set_mode(gtk.SELECTION_MULTIPLE)
    py.test.raises(AttributeError, 'items.selected_item = user')
    py.test.raises(AttributeError, 'items.selected_item')
    items.selected_items = [user]
    refresh_gui()
    assert items.selected_items == [user]
Esempio n. 11
0
def test_gcall():
    data = []

    def doit():
        gcall(data.append, 1)

    AsyncTask(doit).start()
    refresh_gui(.1)
    assert data == [1]
Esempio n. 12
0
def test_double_click_event(items, user):
    items.append(user, select=True)
    e = gtk.gdk.Event(gtk.gdk._2BUTTON_PRESS)
    e.button = 1
    item_clicked = CheckCalled(items, 'item-double-clicked')
    items._emit_for_path((0,), e)
    refresh_gui()
    assert item_clicked.called
    assert item_clicked.called_count == 1
Esempio n. 13
0
def test_list_collapse_item(items, user, user2):
    items.append(user)
    items.append(user2, user)
    item_collapsed = CheckCalled(items, 'item-collapsed')
    items.expand_item(user)
    refresh_gui()
    items.collapse_item(user)
    refresh_gui()
    assert item_collapsed.called
Esempio n. 14
0
def test_item_expanded(items, user, user2):
    items.append(user)
    items.append(user2, user)
    items.expand_item(user)
    refresh_gui()
    assert items.item_expanded(user)
    items.collapse_item(user)
    refresh_gui()
    assert not items.item_expanded(user)
    def get_ui_json_settings(self):
        '''
        Get current video settings from DMF device UI plugin.

        Returns
        -------

            (dict) : DMF device UI plugin settings in JSON-compatible format
                (i.e., only basic Python data types).
        '''
        video_settings = {}

        # Try to request video configuration.
        try:
            video_config = hub_execute(self.name, 'get_video_config',
                                       wait_func=lambda *args: refresh_gui(),
                                       timeout_s=2)
        except IOError:
            logger.warning('Timed out waiting for device window size and '
                           'position request.')
        else:
            if video_config is not None:
                video_settings['video_config'] = video_config.to_json()
            else:
                video_settings['video_config'] = ''

        # Try to request allocation to save in app options.
        try:
            data = hub_execute(self.name, 'get_corners', wait_func=lambda
                               *args: refresh_gui(), timeout_s=2)
        except IOError:
            logger.warning('Timed out waiting for device window size and '
                           'position request.')
        else:
            if data:
                # Get window allocation settings (i.e., width, height, x, y).

                # Replace `df_..._corners` with CSV string named `..._corners`
                # (no `df_` prefix).
                for k in ('df_canvas_corners', 'df_frame_corners'):
                    if k in data:
                        data['allocation'][k[3:]] = data.pop(k).to_csv()
                video_settings.update(data['allocation'])

        # Try to request surface alphas.
        try:
            surface_alphas = hub_execute(self.name, 'get_surface_alphas',
                                         wait_func=lambda *args: refresh_gui(),
                                         timeout_s=2)
        except IOError:
            logger.warning('Timed out waiting for surface alphas.')
        else:
            if surface_alphas is not None:
                video_settings['surface_alphas'] = surface_alphas.to_json()
            else:
                video_settings['surface_alphas'] = ''
        return video_settings
Esempio n. 16
0
def test_tree_collapse_item(items, user, user2):
    items.append(user)
    items.append(user2, user)
    item_collapsed = CheckCalled(items, 'item-collapsed')
    items.expand_item(user)
    refresh_gui()
    items.collapse_row(items._path_for(user))
    refresh_gui()
    assert item_collapsed.called
Esempio n. 17
0
def test_left_click_event(items, user):
    items.append(user, select=True)
    e = gtk.gdk.Event(gtk.gdk.BUTTON_PRESS)
    e.button = 1
    e.x, e.y = 10.0, 10.0
    item_clicked = CheckCalled(items, 'item-left-clicked')
    items._emit_for_path((0,), e)
    refresh_gui()
    assert item_clicked.called
    assert item_clicked.called_count == 1
Esempio n. 18
0
def test_invoke_in_mainloop():
    data = []

    def doit():
        invoke_in_mainloop(data.append, 1)
        assert invoke_in_mainloop(len, data) == 1

    AsyncTask(doit).start()
    # timeout needed for asynctask cleanup
    refresh_gui(.1)
    assert data == [1]
Esempio n. 19
0
def test_edit_name(items, user):
    items.append(user)
    item_changed = CheckCalled(items, 'item-changed')

    refresh_gui()
    assert not item_changed.called
    name_cell = items.get_columns()[0].get_cells()[0]
    text_path = items._path_for(user)
    name_cell.emit('edited', text_path, 'peter')
    refresh_gui()
    assert user.name=='peter'
    assert item_changed.called
Esempio n. 20
0
def test_add_proxy():
    m = ProxyGroup()
    e = gtk.Entry()
    p = GtkEntryProxy(e)
    m.add_proxy('foo', p)
    check = CheckCalled(m, 'changed')
    e.set_text('a')
    refresh_gui()
    assert check.called_count == 1
    p.update('b')
    refresh_gui()
    assert check.called_count == 2
Esempio n. 21
0
def test_async_task():

    data = []

    def do():
        data.append(1)
        return 2, 3

    def done(*k):
        data.extend(k)

    GeneratorTask(do, done).start()
    refresh_gui()
    assert data == [1, 2, 3]
    def on_frame_update(self, slave, np_frame):
        if self.widget.window is None:
            return
        if np_frame is None:
            cr_warped = cairo.ImageSurface(cairo.FORMAT_RGB24, *self.shape)
        else:
            cr_warped, np_warped_view = np_to_cairo(np_frame)
            if not self._enabled:
                logging.error('got frame when not enabled')
        refresh_gui(0, 0)

        combined_surface = composite_surface([cr_warped] + self.surfaces)
        refresh_gui(0, 0)
        self.draw_surface(combined_surface)
    def execute_transition(self):
        '''
        Execute a single transition (corresponding to the current transition
        index) in each route with a sufficient number of transitions.
        '''
        route_info = self.route_info

        # Trail follows transition corresponding to *transition counter* by
        # the specified *trail length*.
        start_i = route_info['transition_counter']
        end_i = (route_info['transition_counter'] + route_info['trail_length']
                 - 1)

        if start_i == end_i:
            logger.debug('[execute_transition] %s', start_i)
        else:
            logger.debug('[execute_transition] %s-%s', start_i, end_i)

        df_routes = route_info['df_routes']
        start_i_mod = start_i % df_routes.route_length
        end_i_mod = end_i % df_routes.route_length

        #  1. Within the specified trail length of the current transition
        #     counter of a single pass.
        single_pass_mask = ((df_routes.transition_i >= start_i) &
                            (df_routes.transition_i <= end_i))
        #  2. Within the specified trail length of the current transition
        #     counter in the second route pass.
        second_pass_mask = (max(end_i, start_i) < 2 * df_routes.route_length)
        #  3. Start marker is higher than end marker, i.e., end has wrapped
        #     around to the start of the route.
        wrap_around_mask = ((end_i_mod < start_i_mod) &
                            ((df_routes.transition_i >= start_i_mod) |
                             (df_routes.transition_i <= end_i_mod + 1)))

        # Find active transitions based on the transition counter.
        active_transition_mask = (single_pass_mask |
                                  # Only consider wrap-around transitions for
                                  # the second pass of cyclic routes.
                                  (df_routes.cyclic & second_pass_mask &
                                   wrap_around_mask))
                                   #(subsequent_pass_mask | wrap_around_mask)))

        df_routes['active'] = active_transition_mask.astype(int)
        active_electrode_mask = (df_routes.groupby('electrode_i')['active']
                                 .sum())

        # An electrode may appear twice in the list of modified electrode
        # states in cases where the same channel is mapped to multiple
        # electrodes.
        #
        # Sort electrode states with "on" electrodes listed first so the "on"
        # state will take precedence when the electrode controller plugin drops
        # duplicate states for the same electrode.
        modified_electrode_states = (active_electrode_mask.astype(bool)
                                     .sort_values(ascending=False))
        self.plugin.execute('wheelerlab.electrode_controller_plugin',
                            'set_electrode_states',
                            electrode_states=modified_electrode_states,
                            save=False, wait_func=lambda *args: refresh_gui())
Esempio n. 24
0
def test_generator_task():
    data = []

    def do():
        for i in range(10):
            yield i

    def work(val):
        data.append(val)

    def done():
        data.extend(data)

    GeneratorTask(do, work, done).start()
    refresh_gui()

    assert data == range(10)*2
 def wait_for_gui_process(self, retry_count=20, retry_duration_s=1):
     start = datetime.now()
     for i in xrange(retry_count):
         try:
             hub_execute(self.name, 'ping', wait_func=lambda *args:
                         refresh_gui(), timeout_s=5, silent=True)
         except:
             logger.debug('[wait_for_gui_process] failed (%d of %d)', i + 1,
                          retry_count, exc_info=True)
         else:
             logger.info('[wait_for_gui_process] success (%d of %d)', i + 1,
                         retry_count)
             self.alive_timestamp = datetime.now()
             return
         for j in xrange(10):
             time.sleep(retry_duration_s / 10.)
             refresh_gui()
     raise IOError('Timed out after %ss waiting for GUI process to connect '
                   'to hub.' % si_format((datetime.now() -
                                          start).total_seconds()))
    def on_step_run(self):
        '''
        Handler called whenever a step is executed.

        Plugins that handle this signal must emit the on_step_complete signal
        once they have completed the step. The protocol controller will wait
        until all plugins have completed the current step before proceeding.
        '''
        app = get_app()

        if (app.realtime_mode or app.running) and self.gui_process is not None:
            step_options = self.get_step_options()
            if not step_options['video_enabled']:
                hub_execute(self.name, 'disable_video',
                            wait_func=lambda *args: refresh_gui(), timeout_s=5,
                            silent=True)
            else:
                hub_execute(self.name, 'enable_video',
                            wait_func=lambda *args: refresh_gui(), timeout_s=5,
                            silent=True)
        emit_signal('on_step_complete', [self.name, None])
    def measure_channel_impedances(self, channels, voltage, frequency,
                                   n_sampling_windows, **kwargs):
        '''
        Parameters
        ----------
        channels : list
            List of channels to scan.
        voltage : float
            Voltage to apply during scan.
        frequency : float
            Frequency to apply during scan.
        n_sampling_windows : int
            Number of sampling windows to collect for each channel.

        Returns
        -------
        pandas.DataFrame
            Table containing one RMS measurement per row and the columns
            ``frequency``, ``voltage``, ``channel_i``, ``V_actuation``,
            ``capacitance``, and ``impedance``.
        '''
        channel_count = self.execute('wheelerlab.dmf_control_board_plugin',
                                     'channel_count', timeout_s=1.,
                                     wait_func=lambda *args: refresh_gui(0, 0))
        assert(all([c < channel_count for c in channels]))

        print '[measure_channel_impedances]', channels

        if 'wait_func' not in kwargs:
           kwargs['wait_func'] = lambda *args: refresh_gui(0, 0)
        channel_states = np.zeros(channel_count, dtype=int)
        channel_states[list(channels)] = 1
        df_result = self.execute('wheelerlab.dmf_control_board_plugin',
                                 'sweep_channels', voltage=voltage,
                                 frequency=frequency, state=channel_states,
                                 n_sampling_windows=n_sampling_windows,
                                 timeout_s=30., **kwargs).dropna()
        return df_result.loc[df_result.V_actuation > .9 * voltage]
Esempio n. 28
0
def test_deselect_multiple(items, user, user2):
    listing = [user, user2]
    items.extend(listing)
    items.get_selection().set_mode(gtk.SELECTION_MULTIPLE)
    items.selected_items = listing
    refresh_gui()
    assert items.selected_items == listing
    items.selected_items = []
    refresh_gui()
    assert items.selected_items == []

    items.selected_items = listing
    refresh_gui()
    assert items.selected_items == listing
    items.selected_items = None
    refresh_gui()
    assert items.selected_items == []
    def set_ui_settings(self, ui_settings, default_corners=False):
        '''
        Set DMF device UI settings from settings dictionary.

        Args
        ----

            ui_settings (dict) : DMF device UI plugin settings in format
                returned by `json_settings_as_python` method.
        '''
        if self.alive_timestamp is None or self.gui_process is None:
            # Repeat until GUI process has started.
            raise IOError('GUI process not ready.')

        if 'video_config' in ui_settings:
            hub_execute(self.name, 'set_video_config',
                        video_config=ui_settings['video_config'],
                        wait_func=lambda *args: refresh_gui(), timeout_s=5)

        if 'surface_alphas' in ui_settings:
            hub_execute(self.name, 'set_surface_alphas',
                        surface_alphas=ui_settings['surface_alphas'],
                        wait_func=lambda *args: refresh_gui(), timeout_s=5)

        if all((k in ui_settings) for k in ('df_canvas_corners',
                                            'df_frame_corners')):
            if default_corners:
                hub_execute(self.name, 'set_default_corners',
                            canvas=ui_settings['df_canvas_corners'],
                            frame=ui_settings['df_frame_corners'],
                            wait_func=lambda *args: refresh_gui(), timeout_s=5)
            else:
                hub_execute(self.name, 'set_corners',
                            df_canvas_corners=ui_settings['df_canvas_corners'],
                            df_frame_corners=ui_settings['df_frame_corners'],
                            wait_func=lambda *args: refresh_gui(), timeout_s=5)
Esempio n. 30
0
def test_empty_text_filler(etf):
    etf, e = etf
    etf.grab_focus()
    refresh_gui(0.1, 0.1)
    e.grab_focus()
    refresh_gui(0.2, 0.2)
    assert etf.get_buffer().props.text == 'enter something'
    assert etf.addons.empty_filler.empty
    etf.grab_focus()
    refresh_gui(0.2, 0.2)
    assert etf.get_buffer().props.text == ''
    def channel_impedance_structures(self, df_channel_impedances):
        hdf_impedance_path = 'channel_impedances'
        hdf_device = 'device'
        hdf_device_shapes = 'shapes'

        device = self.plugin.execute('wheelerlab.device_info_plugin',
                                     'get_device', timeout_s=5.,
                                     wait_func=lambda *args: refresh_gui(0, 0))

        result = {}
        result[hdf_impedance_path] = df_channel_impedances
        result[hdf_device_shapes] = device.df_shapes

        for series_name_i in ('electrodes_by_channel', 'electrode_areas',
                              'channels_by_electrode', 'channel_areas'):
            hdf_path_i = '/'.join([hdf_device, series_name_i])
            data = getattr(device, series_name_i).sort_index()
            result[hdf_path_i] = data
        return result
    def reset(self):
        '''
        Reset execution state.
        '''
        if 'timeout_id' in self.route_info:
            gobject.source_remove(self.route_info['timeout_id'])
            del self.route_info['timeout_id']

        if ('electrode_ids' in self.route_info and
            (self.route_info['electrode_ids'].shape[0] > 0)):
            # At least one route exists.
            # Deactivate all electrodes belonging to all routes.
            electrode_states = pd.Series(0, index=self.route_info
                                         ['electrode_ids'], dtype=int)
            self.plugin.execute('wheelerlab'
                                '.electrode_controller_plugin',
                                'set_electrode_states',
                                electrode_states=electrode_states,
                                save=False, wait_func=lambda *args:
                                refresh_gui())
        self.route_info = {'transition_counter': 0}
Esempio n. 33
0
def gtk_wait(wait_duration_s):
    refresh_gui()
Esempio n. 34
0
def test_column_width():
    col = Column('test', width=30)
    view_col = col.create_treecolumn(None)
    refresh_gui()
    assert view_col.get_sizing() == gtk.TREE_VIEW_COLUMN_FIXED
    assert view_col.get_fixed_width() == 30