예제 #1
0
def test_engine_status(execution_view, dialog_sleep):
    """Test te display of the engine status.

    """
    execution_view.show()
    process_app_events()
    sleep(dialog_sleep)

    item = execution_view.widget

    en_stat = item.dock_widget().widgets()[-1]
    assert not en_stat.visible

    pl = item.workspace.plugin
    pl.processor.engine = pl.create('engine', 'dummy')
    pl.processor.engine.status = 'Stopped'
    process_app_events()
    assert en_stat.visible

    assert en_stat.widgets()[1].text == 'Stopped'

    meas = item.workspace.plugin.enqueued_measures.measures[0]
    item.workspace.plugin.processor.running_measure = meas
    item.workspace.plugin.processor.active = True

    assert not en_stat.widgets()[2].enabled
    assert en_stat.widgets()[2].text == 'Shut down'
예제 #2
0
def test_text_monitor_item(text_monitor_workbench, monitor, dialog_sleep):
    """Test that the dock item of the text monitor does display the right
    entries.

    """
    # Check only displayed entries are indeed shown.
    monitor.handle_database_change(('added', 'root/test', 0))
    monitor.handle_database_change(('added', 'root/simp/test', 0))
    monitor.handle_database_change(('added', 'root/comp/index', 0))
    monitor.move_entries('displayed', 'undisplayed',
                         [monitor.displayed_entries[0]])
    w = DockItemTestingWindow(widget=TextMonitorItem(monitor=monitor))
    w.show()
    process_app_events()
    f = w.widget.dock_widget()
    assert (sorted([l.text for l in f.widgets()[::2]]) ==
            sorted([e.name for e in monitor.displayed_entries]))
    sleep(dialog_sleep)

    e = sorted(monitor.displayed_entries, key=attrgetter('path'))[0]
    e.name = 'new'
    e.value = '1'
    process_app_events()
    assert f.widgets()[0].text == 'new'
    assert f.widgets()[1].text == '1'
예제 #3
0
def test_show_monitors(execution_view, dialog_sleep):
    """Test restoring the monitor window.

    """
    execution_view.show()
    process_app_events()
    sleep(dialog_sleep)

    item = execution_view.widget

    mon_btn = item.dock_widget().widgets()[5]
    assert not mon_btn.enabled

    with enaml.imports():
        from ecpy.measure.workspace.monitors_window import MonitorsWindow

    meas = item.workspace.plugin.enqueued_measures.measures[0]
    mon_win = MonitorsWindow(item, measure=meas)
    item.workspace.plugin.processor.monitors_window = mon_win

    assert not mon_win.visible

    mon_btn.clicked = True
    process_app_events()
    assert mon_win.visible
예제 #4
0
def test_selecting_profile_from_scratch(prof_plugin, process_and_sleep):
    """Test selecting a profile.

    """
    d = ProfileSelectionDialog(plugin=prof_plugin)
    d.show()
    process_and_sleep()

    d.profile = 'fp2'
    assert not d.connection
    assert not d.settings
    process_and_sleep()

    d.connection = 'false_connection1'
    d.settings = 'false_settings1'
    d.driver = 'tests.test.FalseDriver%s' % ('' if d.driver.endswith('2')
                                             else 2)
    assert not d.connection
    assert not d.settings
    process_and_sleep()

    d.connection = 'false_connection'
    d.settings = 'false_settings'
    process_and_sleep()

    d.central_widget().widgets()[-1].clicked = True
    process_app_events()
    assert d.result
예제 #5
0
def test_save_action(workspace, measure, windows):
    """Test that save action calls the proper commands.

    """
    act = SaveAction(workspace=workspace,
                     action_context={'data': (None, None,
                                              measure.root_task, None)})

    with handle_dialog('reject'):
        act.triggered = True

    class CmdException(Exception):

        def __init__(self, cmd, opts):
            self.cmd = cmd

    def invoke(self, cmd, opts, caller=None):
        raise CmdException(cmd, opts)

    from enaml.workbench.core.core_plugin import CorePlugin
    old = CorePlugin.invoke_command
    CorePlugin.invoke_command = invoke

    try:
        with pytest.raises(CmdException) as ex:
            act.triggered = True
            process_app_events()
        assert ex.value.cmd == 'ecpy.app.errors.signal'
    finally:
        CorePlugin.invoke_command = old
예제 #6
0
 def answer_dialog(dial):
     selector = dial.selector
     selector.selected_filter = 'Logic'
     selector.selected_task = 'ecpy.WhileTask'
     dial.config.task_name = 'Test'
     process_app_events()
     assert dial.config.ready
예제 #7
0
def test_stopping_measure_while_preprocessing(mode, processor,
                                              measure_with_tools):
    """Test asking the processor to stop while is is running the pre-hooks.

    The post-hooks should not be run.

    """
    measure = measure_with_tools
    if mode == 'between hooks':
        # Will see the difference only in coverage
        measure.move_tool('pre-hook', 0, 1)
    processor.start_measure(measure)

    pre_hook = measure.pre_hooks['dummy']
    assert pre_hook.waiting.wait(5)
    process_app_events()
    processor.stop_measure(no_post_exec=True)
    assert pre_hook.stop_called

    pre_hook.go_on.set()

    processor._thread.join()
    process_app_events()
    assert measure.status == 'INTERRUPTED'
    m = processor.plugin.workbench.get_manifest('test.measure')
    assert not m.find('runtime_dummy1').collected
    assert not m.find('runtime_dummy2').collected
예제 #8
0
def test_collecting_registering_and_stopping(monkeypatch, workbench, windows):
    """Test basic behavior of PackaggesPlugin.

    """
    patch_pkg(
        monkeypatch,
        [FalseEntryPoint(name="test", manifests=[Manifest1, Manifest2]), FalseEntryPoint(name="test2", manifests=[])],
    )

    app = workbench.get_plugin(APP_ID)
    app.run_app_startup(object())
    process_app_events()

    plugin = workbench.get_plugin(PACKAGES_ID)

    assert "test" in plugin.packages
    assert "test2" in plugin.packages
    assert "ecpy.test1" in plugin.packages["test"]
    assert "ecpy.test2" in plugin.packages["test"]
    assert (100, 0, "ecpy.test1") in plugin._registered
    assert (0, 1, "ecpy.test2") in plugin._registered
    assert workbench.get_plugin("ecpy.test1")
    assert workbench.get_plugin("ecpy.test2")

    workbench.unregister(PACKAGES_ID)

    with pytest.raises(ValueError):
        workbench.get_plugin("ecpy.test1")
    with pytest.raises(ValueError):
        workbench.get_plugin("ecpy.test2")
예제 #9
0
def test_running_forced_enqueued_measure(processor, measure_with_tools):
    """Test running a measure about which we know that checks are failing.

    """
    measure = measure_with_tools
    measure.forced_enqueued = True
    measure.pre_hooks['dummy'].fail_check = True
    processor.start_measure(measure_with_tools)
    pre_hook = measure.pre_hooks['dummy']
    assert pre_hook.waiting.wait(5)
    process_app_events()

    pre_hook.go_on.set()

    wait_and_process(processor.engine.waiting.wait)
    assert processor.engine.measure_force_enqueued
    processor.engine.go_on.set()

    post_hook = measure.post_hooks['dummy']
    wait_and_process(post_hook.waiting.wait)

    post_hook.go_on.set()

    processor._thread.join()
    process_app_events()
예제 #10
0
def test_stopping_processing_in_hook(processor, measure_with_tools):
    """Test stopping processing while running the main task..

    """
    plugin = processor.plugin.workbench.get_plugin('ecpy.measure')
    measure2 = Measure(plugin=plugin, root_task=RootTask(),
                       name='Dummy', id='002')
    processor.plugin.enqueued_measures.add(measure2)

    measure = measure_with_tools
    processor.start_measure(measure)

    pre_hook = measure.pre_hooks['dummy']
    assert pre_hook.waiting.wait(5)
    process_app_events()

    processor.stop_processing(no_post_exec=True)
    pre_hook.go_on.set()

    def wait(timeout):
        processor._thread.join(timeout)
        return not processor._thread.is_alive()

    wait_and_process(wait)
    assert measure.status == 'INTERRUPTED'
    m = processor.plugin.workbench.get_manifest('test.measure')
    assert not m.find('runtime_dummy1').collected
    assert not m.find('runtime_dummy2').collected

    assert measure2.status == 'READY'
예제 #11
0
def test_stopping_measure_while_postprocessing(processor, measure_with_tools):
    """Test asking the processor to stop while is is running the post hooks.

    """
    measure = measure_with_tools
    measure.add_tool('post-hook', 'dummy2')
    measure.post_hooks['dummy2'].fail_run = True
    processor.start_measure(measure)

    pre_hook = measure.pre_hooks['dummy']
    assert pre_hook.waiting.wait(5)
    process_app_events()

    pre_hook.go_on.set()

    wait_and_process(processor.engine.waiting.wait)

    processor.engine.go_on.set()

    post_hook = measure.post_hooks['dummy']
    wait_and_process(post_hook.waiting.wait)

    processor.stop_measure(force=True)
    assert post_hook.stop_called
    post_hook.go_on.set()

    processor._thread.join()
    process_app_events()
    assert measure.status == 'INTERRUPTED'
    m = processor.plugin.workbench.get_manifest('test.measure')
    assert not m.find('runtime_dummy1').collected
    assert not m.find('runtime_dummy2').collected
예제 #12
0
def test_profile_edition_dialog_cancel(prof_plugin, process_and_sleep,
                                       profile_infos):
    """Test the dialog used to edit a profile.

    """
    ed = ProfileEditionDialog(plugin=prof_plugin, profile_infos=profile_infos)
    ed.show()
    process_and_sleep()

    ed_widgets = ed.central_widget().widgets()
    ed_widget = ed_widgets[0]

    nb = ed_widget.widgets()[5]
    c_page, s_page = nb.pages()

    # Delete a connection and open valiadtion window
    c_page.page_widget().widgets()[3].clicked = True
    c_page.page_widget().widgets()[4].clicked = True

    # Delete a settings
    s_page.page_widget().widgets()[4].clicked = True

    process_and_sleep()
    w = ed_widget._validator

    assert len(ed_widget.connections) == 2
    assert len(ed_widget.settings) == 2

    ed_widgets[-2].clicked = True
    process_app_events()
    assert not ed.visible and not w.visible

    assert len(profile_infos.connections) == 3
    assert len(profile_infos.settings) == 3
예제 #13
0
def test_saving_as_template(windows, tmpdir, task_workbench, task,
                            monkeypatch):
    """Test saving a task as a template.

    """
    from ecpy.tasks.utils import saving

    monkeypatch.setattr(saving.TemplateViewer, 'exec_',
                        saving.TemplateViewer.show)

    plugin = task_workbench.get_plugin('ecpy.tasks')
    plugin.templates = {'test': ''}

    def answer_dialog(dialog):
        model = dialog._model
        model.folder = str(tmpdir)
        model.filename = 'test'
        model.doc = 'This is a test'
        dialog.show_result = True

        assert model.accept_template_info(dialog)

    core = task_workbench.get_plugin('enaml.workbench.core')
    with handle_dialog('accept', answer_dialog):
        core.invoke_command(CMD, dict(task=task, mode='template'))

    get_window(Dialog).accept()
    process_app_events()

    path = str(tmpdir.join('test.task.ini'))
    assert os.path.isfile(path)
    config = ConfigObj(path)
    assert config.initial_comment == ['# This is a test']
예제 #14
0
def test_logger_thread(app, logger):
    """Test the logger thread.

    """
    queue = Queue()
    handler = QueueHandler(queue)
    logger.addHandler(handler)
    logger.info('test')
    logger.removeHandler(handler)

    model = LogModel()
    handler = GuiHandler(model)
    logger.addHandler(handler)

    thread = QueueLoggerThread(queue)
    thread.start()
    sleep(1)
    queue.put(None)
    thread.join(2)
    process_app_events()

    if thread.is_alive():
        raise

    assert model.text == 'test\n'
예제 #15
0
    def test_pause2(self, app):
        """Test pausing and stopping the execution.

        """
        def pause_and_stop(task, value):
            """Post a method stopping execution on event loop and pause.

            """
            deferred_call(lambda t: t.root.should_stop.set(), task)
            task.root.should_pause.set()

        root = self.root
        par = CheckTask(name='test', custom=pause_and_stop)
        comp = ComplexTask(name='comp', stoppable=False,
                           parallel={'activated': True, 'pool': 'test'})
        par2 = CheckTask(name='test2')
        comp.add_child_task(0, par2)
        par3 = CheckTask(name='test3')
        for i, c in enumerate([par, comp, par3]):
            root.add_child_task(i, c)
        root.check()

        t = threading.Thread(target=root.perform)
        t.start()
        sleep(0.1)
        process_app_events()
        t.join()

        assert root.should_pause.is_set()
        assert root.should_stop.is_set()
        assert par.perform_called
        assert not par2.perform_called
        assert not par3.perform_called
예제 #16
0
def test_clear(execution_view, dialog_sleep):
    """Test clearing the enqueued measures.

    """
    execution_view.show()
    process_app_events()
    sleep(dialog_sleep)

    item = execution_view.widget

    cl_btn = item.dock_widget().widgets()[4]
    assert cl_btn.enabled

    # Check disabled when running
    meas = item.workspace.plugin.enqueued_measures.measures[0]
    item.workspace.plugin.processor.running_measure = meas
    item.workspace.plugin.processor.active = True
    assert not cl_btn.enabled

    item.workspace.plugin.processor.active = False
    assert cl_btn.enabled

    measures = item.workspace.plugin.enqueued_measures.measures
    measures[0].status = 'COMPLETED'
    measures[1].status = 'FAILED'

    cl_btn.clicked = True
    process_app_events()
    assert not item.workspace.plugin.enqueued_measures.measures
    assert not cl_btn.enabled
예제 #17
0
def test_browing_dialog_profiles_add(prof_plugin, process_and_sleep):
    """Test the browsing dialog page dedicated to explore the profiles.

    """
    d = BrowsingDialog(plugin=prof_plugin)
    nb = d.central_widget().widgets()[0]
    nb.selected_tab = "profiles"
    d.show()
    process_and_sleep()

    btn = nb.pages()[1].page_widget().widgets()[-2]

    origin = prof_plugin.profiles[:]
    with handle_dialog("reject", cls=ProfileEditionDialog):
        btn.clicked = True

    assert prof_plugin.profiles == origin

    def handle(dial):
        assert dial.creation
        dial.profile_infos.id = "test"
        dial.profile_infos.model = prof_plugin._profiles["fp1"].model

    with handle_dialog("accept", handle, cls=ProfileEditionDialog):
        btn.clicked = True

    # Wait for file notification to be treated
    sleep(1.0)
    process_app_events()

    assert "test" in prof_plugin.profiles
    assert os.path.isfile(os.path.join(prof_plugin._profiles_folders[0], "test.instr.ini"))
예제 #18
0
    def add_tool_1(dial):
        widgets = dial.central_widget().widgets()
        widgets[0].selected_item = 'Dummy'
        process_app_events()
        sleep(dialog_sleep)

        widgets[-2].clicked = True
예제 #19
0
def test_stopping_measure_while_running_main(processor, measure_with_tools):
    """Test asking the processor to stop while is is running the main task.

    The post-hooks should be run.

    """
    measure = measure_with_tools
    processor.start_measure(measure)

    pre_hook = measure.pre_hooks['dummy']
    assert pre_hook.waiting.wait(5)
    process_app_events()

    pre_hook.go_on.set()

    wait_and_process(processor.engine.waiting.wait)

    processor.stop_measure()
    processor.engine.go_on.set()

    post_hook = measure.post_hooks['dummy']
    wait_and_process(post_hook.waiting.wait)

    post_hook.go_on.set()

    processor._thread.join()
    process_app_events()
    assert measure.status == 'INTERRUPTED'
    m = processor.plugin.workbench.get_manifest('test.measure')
    assert not m.find('runtime_dummy1').collected
    assert not m.find('runtime_dummy2').collected
예제 #20
0
def test_running_measure_failing_post_hooks(processor, measure_with_tools):
    """Test running a measure whose post-hooks fail to execute.

    """
    measure = measure_with_tools
    measure_with_tools.post_hooks['dummy'].fail_run = True
    processor.start_measure(measure_with_tools)
    pre_hook = measure.pre_hooks['dummy']
    assert pre_hook.waiting.wait(5)
    process_app_events()

    pre_hook.go_on.set()

    wait_and_process(processor.engine.waiting.wait)

    processor.engine.go_on.set()

    post_hook = measure.post_hooks['dummy']
    wait_and_process(post_hook.waiting.wait)

    post_hook.go_on.set()

    processor._thread.join()
    process_app_events()
    assert measure_with_tools.status == 'FAILED'
    assert 'post-execution' in measure_with_tools.infos
    m = processor.plugin.workbench.get_manifest('test.measure')
    assert not m.find('runtime_dummy1').collected
    assert not m.find('runtime_dummy2').collected
예제 #21
0
 def run(measure):
     t = Thread(target=processor._start_monitors, args=(measure,))
     t.start()
     while t.is_alive():
         process_app_events()
         sleep(0.001)
     process_app_events()
     sleep(dialog_sleep)
예제 #22
0
def test_sequence_config_view(windows):
    """Test the view of the base config.

    """
    w = SequenceConfigView(model=SequenceConfig(sequence_doc='test',))
    show_widget(w)
    w.widgets()[1].text = 'test'
    process_app_events()
    assert w.model.ready
예제 #23
0
def test_starting_measure_no_measure_enqueued(processor):
    """Test starting next measure in the queue when no measures are enqueued.

    """
    processor.start_measure(None)
    assert processor.active
    processor._thread.join()
    process_app_events()
    assert not processor.active
예제 #24
0
def test_entry_formatting():
    """Test that we can correctly format an entry.

    """
    e = MonitoredEntry(name='test', formatting='{a} = {b}',
                       depend_on=['a', 'b'])

    e.update(dict(a=1, b=2, c=3))
    process_app_events()
    assert e.value == '1 = 2'
예제 #25
0
def test_running_measure_whose_runtime_are_unavailable(processor, monkeypatch,
                                                       measure_with_tools):
    """Test running whose runtime dependencies are unavailable.

    """
    monkeypatch.setattr(Flags, 'RUNTIME2_UNAVAILABLE', True)
    processor.start_measure(measure_with_tools)

    processor._thread.join()
    process_app_events()
    assert measure_with_tools.status == 'SKIPPED'
예제 #26
0
def wait_and_process(waiting_function):
    """Call a function which can timeout and process app events.

    """
    i = 0
    while not waiting_function(timeout=0.02):
        process_app_events()
        i += 1
        if i > 5000:
            assert False
    process_app_events()
예제 #27
0
    def test_pause1(self, app):
        """Test pausing and resuming the execution. (add instrs)

        Tricky as only the main thread is allowed to resume.

        """
        class Dummy(object):
            """False instrument checking that restarting does its job.

            """
            owner = 'test'
            called = 0

            def finalize(self):
                pass

            def clear_cache(self):
                self.called += 1

        def pause(task, value):
            """Post a method restarting execution on event loop and pause.

            """
            deferred_call(lambda t: t.root.should_pause.clear(), task)
            task.root.should_pause.set()

        root = self.root
        dummy = Dummy()
        root.resources['instrs']['test'] = dummy
        par = CheckTask(name='test', custom=pause)
        comp = ComplexTask(name='comp', stoppable=False,
                           parallel={'activated': True, 'pool': 'test'})
        par2 = CheckTask(name='test2')
        comp.add_child_task(0, par2)
        par3 = CheckTask(name='test3')
        for i, c in enumerate([par, comp, par3]):
            root.add_child_task(i, c)
        root.check()

        t = threading.Thread(target=root.perform)
        t.start()
        sleep(0.1)
        process_app_events()
        t.join()

        assert not root.should_pause.is_set()
        assert not root.should_stop.is_set()
        assert par.perform_called == 1
        assert par2.perform_called == 1
        assert par3.perform_called == 1
        assert root.resumed.is_set()
        assert dummy.called == 1
        assert dummy.owner == ''
예제 #28
0
def test_plugin_lifecycle(instr_workbench):
    """Test the plugin lifecycle (initial registration and later on).

    """
    instr_workbench.register(InstrContributor1())

    # Test starting
    p = instr_workbench.get_plugin("ecpy.instruments")

    assert "tests" in p.users
    assert "false_starter" in p.starters
    assert "false_connection" in p.connections
    assert "false_settings" in p.settings
    assert "tests.test.FalseDriver" in p._drivers.contributions
    for d in p._drivers.contributions.values():
        assert d.valid
    assert p.get_aliases("Dummy")

    # Test later registration (incomplete as dynamic loading of driver is not
    # fully implemented).
    c2 = InstrContributor2()
    instr_workbench.register(c2)

    assert "tests_" in p.users
    assert "false_starter_bis" in p.starters
    assert "false_connection_bis" in p.connections
    assert "false_settings_bis" in p.settings

    # Test observation of profiles folders
    shutil.copy(PROFILE_PATH, p._profiles_folders[0])
    sleep(1.0)
    process_app_events()

    assert "fp" in p.profiles

    os.remove(os.path.join(p._profiles_folders[0], "fp.instr.ini"))
    sleep(1.0)
    process_app_events()

    assert "fp" not in p.profiles

    # Test dynamic unregsitrations (same remark as above)
    instr_workbench.unregister(c2.id)

    assert "tests_" not in p.users
    assert "false_starter_bis" not in p.starters
    assert "false_connection_bis" not in p.connections
    assert "false_settings_bis" not in p.settings

    assert "Dummy" in p._manufacturers._manufacturers  # dummy is an alias

    # Stop
    p.stop()
예제 #29
0
    def answer_dialog(dial):
        selector = dial.selector
        qlist = selector.widgets()[-1]
        qlist.selected_item = qlist.items[-1]
        process_app_events()
        sleep(dialog_sleep)
        assert dial.config
        selector.selected_task = '_dummy_'

        process_app_events()
        assert not dial.config
        sleep(dialog_sleep)
예제 #30
0
    def test_formatter2(self, logger, app):
        """Test setting the formatter of a non existing handler.

        """
        core = self.workbench.get_plugin(u'enaml.workbench.core')

        formatter = logging.Formatter('test : %(message)s')
        core.invoke_command('ecpy.app.logging.set_formatter',
                            {'formatter': formatter,
                             'handler_id': 'non-existing'},
                            self)

        process_app_events()
예제 #31
0
def test_running_measure_failing_pre_hooks(processor, measure_with_tools):
    """Test running a measure whose pre-hooks fail to execute.

    """
    measure_with_tools.pre_hooks['dummy'].fail_run = True
    processor.start_measure(measure_with_tools)

    process_and_assert(getattr, (processor, 'active'))

    pre_hook = measure_with_tools.pre_hooks['dummy']
    process_and_assert(pre_hook.waiting.wait, (5, ))
    process_app_events()
    pre_hook.go_on.set()

    process_and_join_thread(processor._thread)
    assert measure_with_tools.status == 'FAILED'
    assert 'pre-execution' in measure_with_tools.infos
    m = processor.plugin.workbench.get_manifest('test.measure')
    assert not m.find('runtime_dummy1').collected
    assert not m.find('runtime_dummy2').collected
예제 #32
0
def test_rule_selection_for_loading(text_monitor_workbench, dialog_sleep):
    """Test using the dialog to select an existing config to load a task.

    """
    p = text_monitor_workbench.get_plugin(PLUGIN_ID)

    d = CreateRuleDialog(plugin=p)
    d.show()
    process_app_events()
    sleep(dialog_sleep)

    page = d.central_widget().widgets()[0].pages()[0]
    page_content = page.page_widget().widgets()

    # Select rule config
    qlist = page_content[0]
    qlist.selected_item = qlist.items[-1]
    process_app_events()
    assert page.rule == d.rule
    sleep(dialog_sleep)
예제 #33
0
def test_stopping_processing_while_in_pause(processor, measure_with_tools):
    """Test stopping processing while in pause before starting main.

    """
    plugin = processor.plugin.workbench.get_plugin('ecpy.measure')
    measure2 = Measure(plugin=plugin,
                       root_task=RootTask(),
                       name='Dummy',
                       id='002')
    processor.plugin.enqueued_measures.add(measure2)

    def wait_on_state_paused(timeout):
        return processor._state.wait(timeout, 'paused')

    measure = measure_with_tools
    processor.start_measure(measure)

    pre_hook = measure.pre_hooks['dummy']
    assert pre_hook.waiting.wait(5)
    process_app_events()

    processor.pause_measure()
    pre_hook.accept_pause = False
    pre_hook.go_on.set()

    wait_and_process(wait_on_state_paused)

    processor.stop_processing(no_post_exec=True)
    sleep(0.2)

    def wait(timeout):
        processor._thread.join(timeout)
        return not processor._thread.is_alive()

    wait_and_process(wait)
    assert measure.status == 'INTERRUPTED'
    m = processor.plugin.workbench.get_manifest('test.measure')
    assert not m.find('runtime_dummy1').collected
    assert not m.find('runtime_dummy2').collected

    assert measure2.status == 'READY'
예제 #34
0
def test_closing_measure(edition_view, monkeypatch, dialog_sleep):
    """Test closing the measure dock item.

    """
    edition_view.show()
    process_app_events()
    sleep(dialog_sleep)

    # Open the tools edition panel to check that we will properly close the
    # it later
    ed = edition_view.widget.dock_widget().widgets()[0]
    btn = ed.widgets()[4]

    btn.clicked = True
    process_app_events()

    # Monkeypatch question (handle_dialog does not work on it on windows)
    with enaml.imports():
        from ecpy.measure.workspace import measure_edition

    monkeypatch.setattr(measure_edition, 'question', lambda *args: None)
    edition_view.widget.proxy.on_closed()
    edition_view.widget.measure.name = 'First'
    process_app_events()
    assert len(edition_view.area.dock_items()) == 2
    sleep(dialog_sleep)

    false_btn = namedtuple('FalseBtn', ['action'])
    monkeypatch.setattr(measure_edition, 'question',
                        lambda *args: false_btn('reject'))
    edition_view.widget.proxy.on_closed()
    edition_view.widget.measure.name = 'Second'
    process_app_events()
    assert len(edition_view.area.dock_items()) == 2
    sleep(dialog_sleep)

    monkeypatch.setattr(measure_edition, 'question',
                        lambda *args: false_btn('accept'))
    edition_view.widget.proxy.on_closed()
    process_app_events()
    assert len(edition_view.area.dock_items()) == 0
예제 #35
0
def test_visa_tcpip_socket(windows, process_and_sleep):
    """Test the visa tcpip connection.

    """
    c = VisaTCPIP()
    show_widget(c)
    c.resource_class = 'SOCKET'
    process_and_sleep()
    c.widgets()[-4].text = '192.168.0.10'
    c.widgets()[-2].text = '10000'
    process_app_events()
    c.widgets()[-1].checked = True
    process_app_events()
    assert c.gather_infos() == {
        'interface_type': 'TCPIP',
        'resource_class': 'SOCKET',
        'host_address': '192.168.0.10',
        'port': '10000',
        'board': '0'
    }
    assemble_canonical_name(**c.gather_infos())
예제 #36
0
def test_profiles_observation(instr_workbench):
    """Test observing the profiles in the profile folders.

    """
    instr_workbench.register(InstrContributor1())

    # Test starting
    p = instr_workbench.get_plugin('ecpy.instruments')

    # Test observation of profiles folders
    shutil.copy(PROFILE_PATH, p._profiles_folders[0])
    sleep(1.0)
    process_app_events()

    assert 'fp' in p.profiles

    os.remove(os.path.join(p._profiles_folders[0], 'fp.instr.ini'))
    sleep(1.0)
    process_app_events()

    assert 'fp' not in p.profiles
예제 #37
0
def test_ending_with_no_tools(measure, windows, dialog_sleep):
    """Test adding/moving/removing tools.

    """
    for m in list(measure.monitors):
        measure.remove_tool('monitor', m)
    item = ToolsEditorDockItem(measure=measure)
    window = DockItemTestingWindow(widget=item)

    window.show()
    window.maximize()
    process_app_events()
    sleep(dialog_sleep)

    nb = item.dock_widget().widgets()[0]
    mon_ed = nb.pages()[1].page_widget().widgets()[0]

    # Add a tool
    def add_tool_1(dial):
        widgets = dial.central_widget().widgets()
        widgets[0].selected_item = 'Dummy'
        process_app_events()
        sleep(dialog_sleep)

    with handle_dialog('accept', custom=add_tool_1):
        mon_ed.widgets()[-4].clicked = True

    assert 'dummy' in measure.monitors

    # Move up and then down
    mon_ed.selected_id = 'dummy'
    assert not mon_ed.widgets()[-2].enabled

    assert not mon_ed.widgets()[-1].enabled

    # Remove dummy
    mon_ed.widgets()[-3].clicked = True
    process_app_events()
    sleep(dialog_sleep)
    assert 'dummy' not in measure.monitors
예제 #38
0
def test_gui_handler(app, logger, monkeypatch):
    """Test the gui handler.

    """
    model = LogModel()
    handler = GuiHandler(model)
    logger.addHandler(handler)

    logger.info('test')
    process_app_events()
    assert model.text == 'test\n'
    model.clean_text()

    logger.debug('test')
    process_app_events()
    assert model.text == 'DEBUG: test\n'
    model.clean_text()

    logger.warn('test')
    process_app_events()
    assert model.text == 'WARNING: test\n'
    model.clean_text()

    logger.error('test')
    process_app_events()
    assert model.text == 'ERROR: test\n'
    model.clean_text()

    logger.critical('test')
    process_app_events()
    answer = 'An error occured please check the log file for more details.\n'
    assert model.text == answer
    model.clean_text()

    def err(record):
        raise Exception

    monkeypatch.setattr(handler, 'format', err)
    logger.info('raise')
예제 #39
0
def test_profile_edition_dialog_ok(prof_plugin, process_and_sleep,
                                   profile_infos):
    """Test the dialog used to edit a profile.

    """
    # XXX need to test model selection
    profile_infos.connections.clear()
    profile_infos.settings.clear()

    ed = ProfileEditionDialog(plugin=prof_plugin, profile_infos=profile_infos)
    ed.show()
    process_and_sleep()

    ed_widgets = ed.central_widget().widgets()
    ed_widget = ed_widgets[0]

    nb = ed_widget.widgets()[5]
    c_page, s_page = nb.pages()

    # Add a connection
    with handle_dialog(cls=ConnectionCreationDialog):
        c_page.page_widget().widgets()[2].clicked = True

    process_and_sleep()

    # Add a settings
    with handle_dialog(cls=SettingsCreationDialog):
        s_page.page_widget().widgets()[2].clicked = True

    process_and_sleep()

    assert len(ed_widget.connections) == 1
    assert len(ed_widget.settings) == 1

    ed_widgets[-1].clicked = True
    process_app_events()

    assert len(profile_infos.connections) == 1
    assert len(profile_infos.settings) == 1
예제 #40
0
def test_checks_display_warning(windows, dialog_sleep):
    """Test displaying checks that allow enqueuing.

    """
    dial = ChecksDisplay(errors={
        'test': 'dummy',
        'internal': {
            'rr': 'tt'
        }
    },
                         is_warning=True)

    dial.show()
    process_app_events()
    sleep(dialog_sleep)

    assert dial.central_widget().widgets()[-1].text == 'Enqueue'

    dial.central_widget().widgets()[-1].clicked = True
    process_app_events()

    assert dial.result
예제 #41
0
def test_visa_usb(windows):
    """ Test the visa usb connection.

    """
    c = VisaUSB()
    show_widget(c)
    c.widgets()[-6].text = '0x00'
    c.widgets()[-4].text = '0x01'
    c.widgets()[-2].text = '0x02'
    process_app_events()
    c.widgets()[-1].checked = True
    process_app_events()
    assert c.gather_infos() == {
        'interface_type': 'USB',
        'resource_class': 'INSTR',
        'manufacturer_id': '0x00',
        'model_code': '0x01',
        'serial_number': '0x02',
        'usb_interface_number': '0',
        'board': '0'
    }
    assemble_canonical_name(**c.gather_infos())
예제 #42
0
def test_stopping_processing(processor, measure_with_tools):
    """Test stopping processing while running the main task..

    """
    plugin = processor.plugin.workbench.get_plugin('ecpy.measure')
    measure2 = Measure(plugin=plugin,
                       root_task=RootTask(),
                       name='Dummy',
                       id='002')
    processor.plugin.enqueued_measures.add(measure2)

    measure = measure_with_tools
    processor.start_measure(measure)

    process_and_assert(getattr, (processor, 'active'))

    pre_hook = measure.pre_hooks['dummy']
    process_and_assert(pre_hook.waiting.wait, (5, ))
    process_app_events()

    pre_hook.go_on.set()

    wait_and_process(processor.engine.waiting.wait)

    processor.stop_processing(no_post_exec=True)
    processor.engine.go_on.set()

    def wait(timeout):
        processor._thread.join(timeout)
        return not processor._thread.is_alive()

    wait_and_process(wait)
    assert measure.status == 'INTERRUPTED'
    m = processor.plugin.workbench.get_manifest('test.measure')
    assert not m.find('runtime_dummy1').collected
    assert not m.find('runtime_dummy2').collected

    assert measure2.status == 'READY'
예제 #43
0
def test_process_news(monitor, database):
    """ Test processing news coming from a database.

    """
    rule = FormatRule(id='Test',
                      suffixes=['loop', 'index'],
                      new_entry_suffix='progress',
                      new_entry_formatting='{index}/{loop}',
                      hide_entries=False)
    monitor.rules.append(rule)
    database.observe('notifier', monitor.handle_database_entries_change)
    database.set_value('root', 'test_loop', 10)
    database.set_value('root', 'test_index', 1)

    monitor.process_news(('root/test_index', 2))
    process_app_events()
    assert monitor.displayed_entries[0].value == '10'
    assert monitor.displayed_entries[1].value == '2'
    assert monitor.displayed_entries[2].value == '2/10'

    monitor.updaters = {}
    monitor.process_news(('root/test_index', 2))
    process_app_events()
예제 #44
0
def test_measure_edition_dialog(workspace, measure, windows, monkeypatch,
                                dialog_sleep):
    """Test creating a measure edition dialog.

    """
    dialog = MeasureEditorDialog(workspace=workspace, measure=measure)
    dialog.show()
    process_app_events()
    sleep(dialog_sleep)

    from ecpy.measure.workspace.workspace import MeasureSpace

    def false_save(self, meas, *args, **kwargs):
        false_save.called = 1

    monkeypatch.setattr(MeasureSpace, 'save_measure', false_save)

    btn = dialog.central_widget().widgets()[-1]
    btn.clicked = True
    process_app_events()
    assert false_save.called

    dialog.close()
예제 #45
0
def test_starting_measure_thread_not_dying(processor, measure):
    """Test starting but failing to stop the backgground thread.

    """
    class FalseThread(object):
        def __init__(self, processor):
            self.state = processor._state

        def is_alive(self):
            return True

        def join(self, timeout):
            if not self.state.test('stop_processing'):
                raise Exception()

    processor._thread = FalseThread(processor)
    core = processor.plugin.workbench.get_plugin('enaml.workbench.core')
    core.invoke_command('ecpy.app.errors.enter_error_gathering')
    processor.start_measure(None)
    sleep(0.1)
    process_app_events()
    with pytest.raises(ErrorDialogException):
        core.invoke_command('ecpy.app.errors.exit_error_gathering')
예제 #46
0
def test_workspace_lifecycle(workspace):
    """Test the workspace life cycle.

    """
    process_app_events()

    workbench = workspace.plugin.workbench
    log = workbench.get_plugin('ecpy.app.logging')
    # Check UI creation
    assert workspace.content
    assert workspace.dock_area
    assert workbench.get_manifest('ecpy.measure.workspace.menus')

    # Check log handling
    assert 'ecpy.measure.workspace' in log.handler_ids

    # Check engine handling
    engine = workbench.get_manifest('test.measure').find('dummy_engine')
    assert engine.workspace_contributing

    # Check measure creation
    assert len(workspace.plugin.edited_measures.measures) == 1
    assert workspace.plugin.edited_measures.measures[0].monitors

    # Check observance of engine selection.
    workspace.plugin.selected_engine = ''
    assert not engine.workspace_contributing
    workspace.plugin.selected_engine = 'dummy'
    assert engine.workspace_contributing

    # Test stopping the workspace
    core = workbench.get_plugin('enaml.workbench.core')
    cmd = 'enaml.workbench.ui.close_workspace'
    core.invoke_command(cmd, {'workspace': 'ecpy.measure.workspace'})

    assert workspace.plugin.workspace is None
    assert not engine.workspace_contributing
    assert workbench.get_manifest('ecpy.measure.workspace.menus') is None
    assert 'ecpy.measure.workspace' not in log.handler_ids

    # Test restarting now that we have one edited measure.
    cmd = 'enaml.workbench.ui.select_workspace'
    core.invoke_command(cmd, {'workspace': 'ecpy.measure.workspace'})
    assert len(workspace.plugin.edited_measures.measures) == 1

    # Create a false monitors_window
    workspace.plugin.processor.monitors_window = Window()
    workspace.plugin.processor.monitors_window.show()
    process_app_events()

    # Stop again
    core = workbench.get_plugin('enaml.workbench.core')
    cmd = 'enaml.workbench.ui.close_workspace'
    core.invoke_command(cmd, {'workspace': 'ecpy.measure.workspace'})
    process_app_events()

    assert not workspace.plugin.processor.monitors_window.visible
예제 #47
0
    def test_pause2(self, app):
        """Test pausing and stopping the execution.

        """
        def pause_and_stop(task, value):
            """Post a method stopping execution on event loop and pause.

            """
            deferred_call(lambda t: t.root.should_stop.set(), task)
            task.root.should_pause.set()

        root = self.root
        par = CheckTask(name='test', custom=pause_and_stop)
        comp = ComplexTask(name='comp',
                           stoppable=False,
                           parallel={
                               'activated': True,
                               'pool': 'test'
                           })
        par2 = CheckTask(name='test2')
        comp.add_child_task(0, par2)
        par3 = CheckTask(name='test3')
        for i, c in enumerate([par, comp, par3]):
            root.add_child_task(i, c)
        root.check()

        t = threading.Thread(target=root.perform)
        t.start()
        sleep(0.1)
        process_app_events()
        t.join()

        assert root.should_pause.is_set()
        assert root.should_stop.is_set()
        assert par.perform_called
        assert not par2.perform_called
        assert not par3.perform_called
예제 #48
0
def test_connection_validation_window(prof_plugin, process_and_sleep,
                                      profile_infos):
    """Test the window used to check that connection infos allows to open a
    connection.

    """
    ed = ProfileEditionDialog(plugin=prof_plugin, profile_infos=profile_infos)
    ed.show()
    process_and_sleep()
    w = ConnectionValidationWindow(editor=ed.central_widget().widgets()[0])
    w.show()
    process_and_sleep()

    # XXX need to select a driver

    widgets = w.central_widget().widgets()
    p = widgets[-3]
    p.clicked = True
    assert 'The connection was successfully established' in widgets[-2].text

    # XXX add a test for failed connection test

    widgets[-1].clicked = True
    process_app_events()
예제 #49
0
    def test_formatter(self, logger, app):
        """Test setting the formatter of a handler.

        """
        core = self.workbench.get_plugin(u'enaml.workbench.core')
        model = LogModel()
        handler = GuiHandler(model=model)
        core.invoke_command('ecpy.app.logging.add_handler', {
            'id': 'ui',
            'handler': handler,
            'logger': 'test'
        }, self)

        formatter = logging.Formatter('test : %(message)s')
        core.invoke_command('ecpy.app.logging.set_formatter', {
            'formatter': formatter,
            'handler_id': 'ui'
        }, self)

        logger.info('test')

        process_app_events()

        assert model.text == 'test : test\n'
예제 #50
0
def test_loop_config_with_subtask(task_workbench, windows, dialog_sleep,
                                  monkeypatch):
    """Test the loop config.

    """
    plugin = task_workbench.get_plugin('ecpy.tasks')

    config = LoopTaskConfig(manager=plugin,
                            task_class=plugin.get_task('ecpy.LoopTask'),
                            task_name='Test')

    show_widget(LoopConfigView(config=config))
    assert config.ready
    sleep(dialog_sleep)

    config.use_subtask = True
    assert not config.ready
    process_app_events()
    sleep(dialog_sleep)

    config.subtask = 'ecpy.BreakTask'
    assert config.ready
    process_app_events()
    sleep(dialog_sleep)

    def dummy(self):
        self.ready = False

    monkeypatch.setattr(type(config.subconfig), 'check_parameters', dummy)
    config.task_name = 'Bis'
    assert config.subconfig.task_name == 'Bis'  # Check sync
    assert not config.ready  # Result from the monkeypatch
    process_app_events()
    sleep(dialog_sleep)

    config.use_subtask = False
    assert config.ready
    process_app_events()
    sleep(dialog_sleep)

    config.use_subtask = True
    config.subtask = 'ecpy.ContinueTask'
    task = config.build_task()
    assert task.name == 'Bis'
    assert type(task.task).__name__ == 'ContinueTask'
예제 #51
0
def process_and_assert(test_func, args=(), kwargs={}, time=0.01, count=1000):
    """Process events and check test_func value.

    """
    process_app_events()
    counter = 0
    while not test_func(*args, **kwargs):
        sleep(time)
        process_app_events()
        if counter > count:
            assert False
        counter += 1
    process_app_events()
예제 #52
0
def test_loop_config_with_subtask(task_workbench, windows, dialog_sleep):
    """Test the loop config.

    """
    plugin = task_workbench.get_plugin('ecpy.tasks')

    config = LoopTaskConfig(manager=plugin,
                            task_class=plugin.get_task('ecpy.LoopTask'),
                            task_name='Test')

    show_widget(LoopConfigView(config=config))
    assert config.ready
    sleep(dialog_sleep)

    config.use_subtask = True
    assert not config.ready
    process_app_events()
    sleep(dialog_sleep)

    config.subtask = 'ecpy.BreakTask'
    assert config.ready
    process_app_events()
    sleep(dialog_sleep)

    config.subconfig.task_name = ''
    assert not config.ready
    process_app_events()
    sleep(dialog_sleep)

    config.use_subtask = False
    assert config.ready
    process_app_events()
    sleep(dialog_sleep)

    config.use_subtask = True
    config.subtask = 'ecpy.ContinueTask'
    task = config.build_task()
    assert task.name == 'Test'
    assert type(task.task).__name__ == 'ContinueTask'
def test_measure_manipulations(execution_view, dialog_sleep):
    """Test moving/removing measure using editor

    """
    execution_view.show()
    process_app_events()
    sleep(dialog_sleep)

    item = execution_view.widget

    ed = item.dock_widget().widgets()[0]
    meas = item.workspace.plugin.enqueued_measures.measures
    ed.operations['move'](0, 1)
    process_app_events()
    assert meas[0].name == 'dummy_test'

    ed.operations['move'](0, 1)
    process_app_events()
    assert meas[1].name == 'dummy_test'

    ed.operations['remove'](0)
    process_app_events()
    assert meas[0].name == 'dummy_test'
    assert len(meas) == 1
예제 #54
0
def test_sync_name(edition_view, dialog_sleep):
    """Test the synchronisation between the measure name and widget.

    """
    edition_view.show()
    process_app_events()
    sleep(dialog_sleep)

    ed = edition_view.widget.dock_widget().widgets()[0]
    meas = ed.measure
    field = ed.widgets()[1]

    meas.name = '__dummy'
    process_app_events()
    assert meas.name == field.text

    field.text = 'dummy__'
    process_app_events()
    assert meas.name == field.text
예제 #55
0
def test_sync_id(edition_view, dialog_sleep):
    """Test the synchronisation between the measure id and widget.

    """
    edition_view.show()
    process_app_events()
    sleep(dialog_sleep)

    ed = edition_view.widget.dock_widget().widgets()[0]
    meas = ed.measure
    field = ed.widgets()[3]

    meas.id = '101'
    process_app_events()
    assert meas.id == field.text

    field.text = '202'
    process_app_events()
    assert meas.id == field.text
예제 #56
0
def test_tool_selector(windows, measure, dialog_sleep):
    """Selecting a new tool to add to a measure using the dedicated dialog.

    """
    dial = ToolSelector(measure=measure, kind='pre-hook')
    dial.show()
    process_app_events()
    widgets = dial.central_widget().widgets()

    assert len(widgets[0].items) == (len(dial.measure.plugin.pre_hooks) -
                                     len(dial.measure.pre_hooks))
    widgets[0].selected_item = 'Dummy'
    process_app_events()
    sleep(dialog_sleep)
    assert dial.selected_decl
    assert widgets[-2].enabled
    assert widgets[1].text

    widgets[-1].clicked = True
    process_app_events()
def test_continuous_processing(execution_view, dialog_sleep):
    """Test that the checkbox does reflect the underlying setting.

    """
    execution_view.show()
    process_app_events()
    sleep(dialog_sleep)

    item = execution_view.widget
    ch_box = item.dock_widget().widgets()[3]
    proc = item.workspace.plugin.processor

    assert ch_box.checked == proc.continuous_processing
    ch_box.checked = not proc.continuous_processing
    process_app_events()

    assert ch_box.checked == proc.continuous_processing
    proc.continuous_processing = not ch_box.checked
    process_app_events()

    assert ch_box.checked == proc.continuous_processing
예제 #58
0
def test_content(content_workbench, windows, dialog_sleep):
    """Test creating the content of the workspace.

    """
    w = content_workbench
    ui = w.get_plugin('enaml.workbench.ui')
    ui.show_window()
    process_app_events()
    sleep(dialog_sleep)

    core = content_workbench.get_plugin('enaml.workbench.core')
    cmd = 'enaml.workbench.ui.select_workspace'
    core.invoke_command(cmd, {'workspace': 'ecpy.measure.workspace'})
    process_app_events()
    sleep(dialog_sleep)

    pl = content_workbench.get_plugin('ecpy.measure')
    pl.workspace.new_measure()
    process_app_events()
    sleep(dialog_sleep)

    ui.close_window()
예제 #59
0
def test_app_window(workbench_and_tools):
    """Test that closing and closed handlers are called when trying to close
    the app window.

    """
    w, closing, closed = workbench_and_tools

    ui = w.get_plugin('enaml.workbench.ui')
    ui.show_window()
    process_app_events()

    ui.close_window()
    process_app_events()

    assert closing.called
    assert ui.window.visible

    closing.accept = True
    ui.close_window()
    process_app_events()

    assert not ui.window.visible
    assert closed.called
예제 #60
0
def test_swapping(windows, task_workbench, dialog_sleep):
    """Test moving a view between containers.

    """
    task = RootTask()
    view = RootTaskView(task=task,
                        core=task_workbench.get_plugin('enaml.workbench.core'))

    subtask = ComplexTask(name='Test')
    subview = view.view_for(subtask)

    task.add_child_task(0, subtask)

    cont = Container()

    show_widget(cont)
    view.set_parent(cont)
    view.refresh()
    process_app_events()
    assert cont.children == [view]
    sleep(dialog_sleep)

    view.set_parent(None)
    subview.set_parent(cont)
    subview.refresh()
    process_app_events()
    assert cont.children == [subview]
    sleep(dialog_sleep)

    subview.set_parent(None)
    view.set_parent(cont)
    view.refresh()
    process_app_events()
    assert cont.children == [view]
    assert subview.visible
    sleep(dialog_sleep)