Ejemplo n.º 1
0
class TestSetDCVoltageTask(object):

    def setup(self):
        self.root = RootTask(should_stop=Event(), should_pause=Event())
        self.task = MeasDCVoltageTask(name='Test')
        self.root.add_child_task(0, self.task)

        self.root.run_time[DRIVERS] = {'Test': (InstrHelper,
                                                InstrHelperStarter())}
        self.root.run_time[PROFILES] =\
            {'Test1': {'connections': {'C': {'owner': []}},
                       'settings': {'S': {'check_connection': [True]}}
                       }
             }

        # This is set simply to make sure the test of InstrTask pass.
        self.task.selected_instrument = ('Test1', 'Test', 'C', 'S')

    def test_perform(self):
        self.task.wait_time = 1.0

        p = self.root.run_time[PROFILES]['Test1']
        p['settings']['S']['read_voltage_dc'] = [2.0]
        self.root.prepare()

        self.task.perform()
        assert self.root.get_from_database('Test_voltage') == 2.0
Ejemplo n.º 2
0
    def test_saving_building_from_config(self, iterable_interface):
        """Done here as the LoopTask is a viable case of a member tagged with
        child.

        """
        subtask1 = CheckTask(name='check', database_entries={'val': 1})
        self.task.task = subtask1

        self.root.update_preferences_from_members()

        deps = {'ecpy.task': {'ecpy.RootTask': RootTask,
                              'ecpy.LoopTask': LoopTask,
                              'ecpy.CheckTask': CheckTask}
                }
        new = RootTask.build_from_config(self.root.preferences, deps)

        assert new.children[0].task.name == 'check'

        self.task.interface = iterable_interface
        self.root.update_preferences_from_members()
        prefs = self.root.preferences
        del prefs['children_0']['task']
        deps = {'ecpy.task': {'ecpy.RootTask': RootTask,
                              'ecpy.LoopTask': LoopTask,
                              'ecpy.CheckTask': CheckTask},
                'ecpy.tasks.interface':
                    {('IterableLoopInterface', ('ecpy.LoopTask',)):
                        IterableLoopInterface}
                }
        new = RootTask.build_from_config(prefs, deps)

        assert not new.children[0].task
Ejemplo n.º 3
0
def exec_infos(measure_workbench, measure, tmpdir, process_engine,
               sync_server):

    tp = measure_workbench.get_plugin('ecpy.tasks')
    tp._tasks.contributions['tests.WaitingTask'] = TaskInfos(cls=WaitingTask)

    r = RootTask(default_path=text(tmpdir))
    r.add_child_task(0, WaitingTask(name='test1', sock_id='test1',
                                    sync_port=sync_server.port))
    r.add_child_task(1, WaitingTask(name='test2', sock_id='test2',
                                    sync_port=sync_server.port))

    measure.root_task = r
    deps = measure.dependencies
    res, msg, errors = deps.collect_runtimes()
    assert res

    return ExecutionInfos(
            id='test',
            task=r,
            build_deps=deps.get_build_dependencies().dependencies,
            runtime_deps=deps.get_runtime_dependencies('main'),
            observed_entries=['test'],
            checks=not measure.forced_enqueued,
            )
Ejemplo n.º 4
0
def load_array_task(tmpdir, fake_data):
    """Build a LoadArrayTask for testing purposes.

    """
    root = RootTask(should_stop=Event(), should_pause=Event())
    task = LoadArrayTask(name="Test")
    task.interface = CSVLoadInterface()
    task.folder = str(tmpdir)
    task.filename = "fake.dat"
    root.add_child_task(0, task)
    return task
Ejemplo n.º 5
0
class TestSleepTask(object):
    """Test SleepTask.

    """

    def setup(self):
        self.root = RootTask(should_stop=Event(), should_pause=Event())
        self.task = SleepTask(name="Test")
        self.root.add_child_task(0, self.task)

    def test_check1(self):
        """ Test handling a correct string in the 'time' field

        """
        self.task.time = "2.0"

        test, traceback = self.task.check()
        assert test
        assert not traceback
        assert self.task.get_from_database("Test_time") == 2

    def test_check2(self):
        """Test handling a wrong string in the 'time' field.

        """
        self.task.time = "a1.0"

        test, traceback = self.task.check()
        assert not test
        assert len(traceback) == 1
        assert "root/Test-time" in traceback

    def test_check3(self):
        """Test handling a negative value 'time' field.

        """
        self.task.time = "-1.0"

        test, traceback = self.task.check()
        assert not test
        assert len(traceback) == 1
        assert "root/Test" in traceback

    def test_perform1(self):
        """Test performing when 'time' is correctly formatted, and
        checking that the time value gets written to the database

        """
        self.task.time = "1.0+5.0"
        self.root.prepare()

        self.task.perform()
        assert self.task.get_from_database("Test_time") == 6.0
Ejemplo n.º 6
0
def task():
    r = RootTask()
    r.add_child_task(0, SimpleTask(name='simp1', database_entries={'t': 1}))
    c = ComplexTask(name='comp1', database_entries={'t1': 2, 't2': 'r'})
    c.add_child_task(0,
                     SimpleTask(name='simp2', database_entries={'t': 1}))
    c2 = ComplexTask(name='comp2', database_entries={'t1': 2, 't2': 'r'})
    c2.add_child_task(0,
                      SimpleTask(name='simp3', database_entries={'t': 1}))
    c.add_child_task(1, c2)
    r.add_child_task(1, c)
    return r
Ejemplo n.º 7
0
def task():
    """Create a basic task hierarchy for testing.

    """
    root = RootTask()
    root.add_child_task(0, SimpleTask(name="simp1"))

    comp = ComplexTask(name="comp1", wait={"activated": True, "no_wait": ["test"]})
    comp.add_child_task(0, SimpleTask(name="simp2", parallel={"activated": True, "pool": "test"}))

    root.add_child_task(1, comp)
    return root
Ejemplo n.º 8
0
class TestSleepTask(object):
    """Test SleepTask.

    """
    def setup(self):
        self.root = RootTask(should_stop=Event(), should_pause=Event())
        self.task = SleepTask(name='Test')
        self.root.add_child_task(0, self.task)

    def test_check1(self):
        """ Test handling a correct string in the 'time' field

        """
        self.task.time = '2.0'

        test, traceback = self.task.check()
        assert test
        assert not traceback
        assert self.task.get_from_database('Test_time') == 2

    def test_check2(self):
        """Test handling a wrong string in the 'time' field.

        """
        self.task.time = 'a1.0'

        test, traceback = self.task.check()
        assert not test
        assert len(traceback) == 1
        assert 'root/Test-time' in traceback

    def test_check3(self):
        """Test handling a negative value 'time' field.

        """
        self.task.time = '-1.0'

        test, traceback = self.task.check()
        assert not test
        assert len(traceback) == 1
        assert 'root/Test' in traceback

    def test_perform1(self):
        """Test performing when 'time' is correctly formatted, and
        checking that the time value gets written to the database

        """
        self.task.time = '1.0+5.0'
        self.root.prepare()

        self.task.perform()
        assert self.task.get_from_database('Test_time') == 6.0
Ejemplo n.º 9
0
def task():
    """Create a task to test the validators.

    """
    class Tester(CheckTask):
            """Class for testing feval validators.

            """
            feval = Unicode()

    root = RootTask(should_stop=Event(), should_pause=Event())
    task = Tester(name='test', database_entries={'val': 1})
    loop = LoopTask(name='Loop', task=task)
    root.add_child_task(0, loop)
    return task
Ejemplo n.º 10
0
def test_stopping_processing_in_hook(processor, measure_with_tools):
    """Test stopping processing while running a hook.

    """
    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()

    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'
Ejemplo n.º 11
0
class TestSetRFFrequencyTask(object):

    def setup(self):
        self.root = RootTask(should_stop=Event(), should_pause=Event())
        self.task = SetRFFrequencyTask(name='Test')
        self.task.unit = 'GHz'
        self.root.add_child_task(0, self.task)

        self.root.run_time[DRIVERS] = {'Test': (InstrHelper,
                                                InstrHelperStarter())}
        self.root.run_time[PROFILES] =\
            {'Test1': {'connections': {'C': {'owner': []}},
                       'settings': {'S': {'check_connection': [True]}}
                       }
             }

        # This is set simply to make sure the test of InstrTask pass.
        self.task.selected_instrument = ('Test1', 'Test', 'C', 'S')

    def test_check_base_interface1(self):
        """Simply test that everything is ok if voltage can be evaluated.

        """
        self.task.frequency = '1.0'

        test, traceback = self.task.check(test_instr=True)
        assert test
        assert not traceback

    def test_check_base_interface2(self):
        # Check handling a wrong frequency.
        self.task.frequency = '*1.0*'

        test, traceback = self.task.check(test_instr=True)
        assert not test
        assert len(traceback) == 1

    def test_perform_base_interface(self):
        self.task.frequency = '1.0'

        c = self.root.run_time[PROFILES]['Test1']['connections']
        c['C'] = {'frequency': [0.0], 'frequency_unit': ['GHz'],
                  'owner': [None]}
        self.root.prepare()

        self.task.perform()
        assert self.root.get_from_database('Test_frequency') == 1.0
Ejemplo n.º 12
0
    def setup(self):
        self.root = RootTask(should_stop=Event(), should_pause=Event())
        self.task = SaveTask(name='Test')
        self.root.add_child_task(0, self.task)

        self.root.write_in_database('int', 1)
        self.root.write_in_database('float', 2.0)
        self.root.write_in_database('str', 'a')
Ejemplo n.º 13
0
def task(sequence, tmpdir):
    """Transfer sequence task for testing.

    """
    root = RootTask()
    root.run_time = {d_id: {'d': (object, FalseStarter())},
                     p_id: {'p': {'connections': {'c': {}, 'c2': {}},
                                  'settings': {'s': {}}}}}
    path = os.path.join(str(tmpdir), 'test.pulse.ini')
    save_sequence_prefs(path, sequence.preferences_from_members())
    task = TransferPulseSequenceTask(sequence=sequence, sequence_path=path,
                                     sequence_timestamp=os.path.getmtime(path),
                                     sequence_vars=OrderedDict({'a': '1.5'}),
                                     name='Test',
                                     selected_instrument=('p', 'd', 'c', 's'))
    root.add_child_task(0, task)
    return task
Ejemplo n.º 14
0
 def setup(self):
     self.root = RootTask(should_stop=Event(), should_pause=Event())
     self.task = ArrayExtremaTask(name="Test")
     self.root.add_child_task(0, self.task)
     array = np.zeros((5,), dtype={"names": ["var1", "var2"], "formats": ["f8", "f8"]})
     array["var1"][1] = -1
     array["var1"][3] = 1
     self.root.write_in_database("array", array)
Ejemplo n.º 15
0
    def setup(self):
        self.root = RootTask(should_stop=Event(), should_pause=Event())
        self.task = SaveFileTask(name='Test')
        self.root.add_child_task(0, self.task)

        self.root.write_in_database('int', 1)
        self.root.write_in_database('float', 2.0)
        self.root.write_in_database('array', np.array(range(10)))
Ejemplo n.º 16
0
def instr_view(instr_task_workbench):
    """Initialize a instr view.

    """
    c = instr_task_workbench.get_plugin('enaml.workbench.core')
    task = RootTask()
    view = RootTaskView(task=task, core=c)
    i_view = InstrTaskView(task=InterInstrTask(root=task), root=view)
    i_view.set_parent(view)
    return i_view
Ejemplo n.º 17
0
def root_view(task_workbench):
    """Initialize a root view.

    """
    c = task_workbench.get_plugin('enaml.workbench.core')
    task = RootTask()
    view = RootTaskView(task=task, core=c)
    w = ContainerTestingWindow(workbench=task_workbench)
    view.set_parent(w)
    return view
Ejemplo n.º 18
0
def test_linspace_handling_of_rounding(monkeypatch, linspace_interface):
    """Test that we properly round the values.

    """
    monkeypatch.setattr(LoopTask, 'perform_loop', false_perform_loop)
    root = RootTask(should_stop=Event(), should_pause=Event())
    lt = LoopTask(name='Test')
    root.add_child_task(0, lt)

    # Step use more digit
    lt.interface = linspace_interface
    linspace_interface.start = '0.1'
    linspace_interface.stop = '0.11'
    linspace_interface.step = '0.001'
    linspace_interface.perform()
    expected = np.array([
        0.1, 0.101, 0.102, 0.103, 0.104, 0.105, 0.106, 0.107, 0.108, 0.109,
        0.11
    ])
    # Check that this does indeed cause a rounding issue
    with pytest.raises(AssertionError):
        np.testing.assert_array_equal(np.linspace(0.1, 0.11, 11), expected)
    np.testing.assert_array_equal(lt.database_entries['iterable'], expected)

    # Start use more digit
    lt.interface = linspace_interface
    linspace_interface.start = '1.01'
    linspace_interface.stop = '2.01'
    linspace_interface.step = '0.1'
    linspace_interface.perform()
    expected = np.array(
        [1.01, 1.11, 1.21, 1.31, 1.41, 1.51, 1.61, 1.71, 1.81, 1.91, 2.01])
    np.testing.assert_array_equal(lt.database_entries['iterable'], expected)

    # Start use more digit and stop does not round properly
    lt.interface = linspace_interface
    linspace_interface.start = '0.501'
    linspace_interface.stop = '1'
    linspace_interface.step = '0.2'
    linspace_interface.perform()
    expected = np.array([0.501, 0.701, 0.901])
    np.testing.assert_array_equal(lt.database_entries['iterable'], expected)
Ejemplo n.º 19
0
def test_linspace_handling_of_non_matching_stop(monkeypatch,
                                                linspace_interface):
    """Test that we respect the step even if stop does not match.

    """
    monkeypatch.setattr(LoopTask, 'perform_loop', false_perform_loop)
    root = RootTask(should_stop=Event(), should_pause=Event())
    lt = LoopTask(name='Test')
    root.add_child_task(0, lt)

    lt.interface = linspace_interface
    linspace_interface.start = '0.1'
    linspace_interface.stop = '0.1101'
    linspace_interface.step = '0.001'
    linspace_interface.perform()
    expected = np.array([
        0.1, 0.101, 0.102, 0.103, 0.104, 0.105, 0.106, 0.107, 0.108, 0.109,
        0.11
    ])
    np.testing.assert_array_equal(lt.database_entries['iterable'], expected)
Ejemplo n.º 20
0
def task(sequence, tmpdir):
    """Transfer sequence task for testing.

    """
    root = RootTask()
    root.run_time = {
        d_id: {"d": (object, FalseStarter())},
        p_id: {"p": {"connections": {"c": {}, "c2": {}}, "settings": {"s": {}}}},
    }
    path = os.path.join(str(tmpdir), "test.pulse.ini")
    save_sequence_prefs(path, sequence.preferences_from_members())
    task = TransferPulseSequenceTask(
        sequence=sequence,
        sequence_path=path,
        sequence_timestamp=os.path.getmtime(path),
        sequence_vars={"a": "1.5"},
        name="Test",
        selected_instrument=("p", "d", "c", "s"),
    )
    root.add_child_task(0, task)
    return task
Ejemplo n.º 21
0
def test_linspace_handling_of_step_sign(monkeypatch, linspace_interface):
    """Test that no matter the sign of step we generate the proper array.

    """
    monkeypatch.setattr(LoopTask, 'perform_loop', false_perform_loop)
    root = RootTask(should_stop=Event(), should_pause=Event())
    lt = LoopTask(name='Test')
    root.add_child_task(0, lt)

    lt.interface = linspace_interface
    linspace_interface.step = '-0.1'
    linspace_interface.perform()
    expected = np.array(
        [1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.0])
    np.testing.assert_array_equal(lt.database_entries['iterable'], expected)

    linspace_interface.start = '3.0'
    linspace_interface.perform()
    expected = np.array(
        [3.0, 2.9, 2.8, 2.7, 2.6, 2.5, 2.4, 2.3, 2.2, 2.1, 2.0])
    np.testing.assert_array_equal(lt.database_entries['iterable'], expected)
Ejemplo n.º 22
0
    def setup(self):
        self.root = RootTask(should_stop=Event(), should_pause=Event())
        self.task = LockInMeasureTask(name="Test")
        self.root.add_child_task(0, self.task)

        self.root.run_time[DRIVERS] = {"Test": (InstrHelper, InstrHelperStarter())}
        self.root.run_time[PROFILES] = {
            "Test1": {"connections": {"C": {"owner": []}}, "settings": {"S": {"check_connection": [True]}}}
        }

        # This is set simply to make sure the test of InstrTask pass.
        self.task.selected_instrument = ("Test1", "Test", "C", "S")
Ejemplo n.º 23
0
    def setup(self):
        self.root = RootTask(should_stop=Event(), should_pause=Event())
        self.task = SaveArrayTask(name='Test')
        self.root.add_child_task(0, self.task)

        array = np.empty(2, dtype={'names': ('a', 'b'),
                                   'formats': ('f8', 'f8')})
        array[0] = (0, 1)
        array[1] = (2, 3)
        self.root.write_in_database('array', array)
        self.root.write_in_database('float', 2.0)
        self.root.write_in_database('str', 'a')
Ejemplo n.º 24
0
def measure(measure_workbench):
    """Register the dummy testing tools and create an empty measure.

    """
    try:
        measure_workbench.register(MeasureTestManifest())
    except ValueError:
        pass
    plugin = measure_workbench.get_plugin('ecpy.measure')
    measure = Measure(plugin=plugin, root_task=RootTask(),
                      name='Dummy', id='001')
    return measure
Ejemplo n.º 25
0
    def test_saving_building_from_config(self, iterable_interface):
        """Done here as the LoopTask is a viable case of a member tagged with
        child.

        """
        subtask1 = CheckTask(name='check', database_entries={'val': 1})
        self.task.task = subtask1

        self.root.update_preferences_from_members()

        deps = {
            'ecpy.task': {
                'ecpy.RootTask': RootTask,
                'ecpy.LoopTask': LoopTask,
                'ecpy.CheckTask': CheckTask
            }
        }
        new = RootTask.build_from_config(self.root.preferences, deps)

        assert new.children[0].task.name == 'check'

        self.task.interface = iterable_interface
        self.root.update_preferences_from_members()
        prefs = self.root.preferences
        assert prefs['children_0'].sections[1] == 'task'
        del prefs['children_0']['task']
        deps = {
            'ecpy.task': {
                'ecpy.RootTask': RootTask,
                'ecpy.LoopTask': LoopTask,
                'ecpy.CheckTask': CheckTask
            },
            'ecpy.tasks.interface': {
                'ecpy.LoopTask:ecpy.IterableLoopInterface':
                IterableLoopInterface
            }
        }
        new = RootTask.build_from_config(prefs, deps)

        assert not new.children[0].task
Ejemplo n.º 26
0
class TestLoadArrayView(object):
    def setup(self):
        self.root = RootTask(should_stop=Event(), should_pause=Event())
        self.task = LoadArrayTask(name="Test")
        self.root.add_child_task(0, self.task)

    def test_view(self, windows, root_view, task_workbench, process_and_sleep):
        """Intantiate a view with no selected interface and select one after

        """
        view = LoadArrayView(task=self.task, root=root_view)
        win = show_widget(view)
        process_and_sleep()

        assert self.task.interface is None

        assert "CSV" in view.file_formats
        self.task.selected_format = "CSV"
        process_and_sleep()
        assert isinstance(self.task.interface, CSVLoadInterface)

        win.close()

    def test_view2(self, windows, root_view, task_workbench, process_and_sleep):
        """Intantiate a view with a selected interface.

        """
        interface = CSVLoadInterface()
        self.task.interface = interface
        self.task.selected_format = "CSV"

        interface = self.task.interface

        view = LoadArrayView(task=self.task, root=root_view)
        win = show_widget(view)

        process_and_sleep()

        assert self.task.interface is interface
        win.close()
Ejemplo n.º 27
0
def exec_infos(measure_workbench, measure, tmpdir, process_engine,
               sync_server):

    tp = measure_workbench.get_plugin('ecpy.tasks')
    tp._tasks.contributions['tests.WaitingTask'] = TaskInfos(cls=WaitingTask)

    r = RootTask(default_path=text(tmpdir))
    r.add_child_task(0, WaitingTask(name='test1', sock_id='test1',
                                    sync_port=sync_server.port))
    r.add_child_task(1, WaitingTask(name='test2', sock_id='test2',
                                    sync_port=sync_server.port))

    measure.root_task = r
    deps = measure.dependencies
    res, msg, errors = deps.collect_runtimes()
    assert res

    return ExecutionInfos(
            id='test',
            task=r,
            build_deps=deps.get_build_dependencies().dependencies,
            runtime_deps=deps.get_runtime_dependencies('main'),
            observed_entries=['test'],
            checks=not measure.forced_enqueued,
            )
Ejemplo n.º 28
0
def test_editor_changing_root(task):
    """Setting a new root.

    """
    ed = EditorModel(root=RootTask())
    assert len(ed.nodes) == 1

    ed.root = task
    assert len(ed.nodes) == 3
    assert ('root' in ed.nodes and 'root/comp1' in ed.nodes
            and 'root/comp1/comp2' in ed.nodes)
    assert ed.nodes['root/comp1'] in ed.nodes['root'].children
    assert ed.nodes['root/comp1/comp2'] in ed.nodes['root/comp1'].children
Ejemplo n.º 29
0
def test_running_full_measure(app, processor, measure_with_tools, windows,
                              dialog_sleep, tmpdir):
    """Test running a complete measure with pre/post-hooks and monitor.

    """
    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.continuous_processing = False
    processor.start_measure(measure)

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

    pre_hook = measure.pre_hooks['dummy']
    process_and_assert(pre_hook.waiting.wait, (5, ))
    assert measure is processor.running_measure
    assert measure.status == 'RUNNING'
    assert tmpdir.listdir()

    pre_hook.go_on.set()

    wait_and_process(processor.engine.waiting.wait)

    assert processor.monitors_window
    assert processor.monitors_window.measure is measure
    assert measure.monitors['dummy'].running
    sleep(dialog_sleep)
    processor.engine.go_on.set()

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

    assert measure.task_execution_result
    assert not measure.monitors['dummy'].running
    assert measure.monitors['dummy'].received_news

    post_hook.go_on.set()

    process_and_join_thread(processor._thread)
    assert measure.status == 'COMPLETED'
    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'
Ejemplo n.º 30
0
    def setup(self):
        self.root = RootTask(should_stop=Event(), should_pause=Event())
        self.task = PNASinglePointMeasureTask(name='Test')
        self.root.add_child_task(0, self.task)

        self.root.run_time[DRIVERS] = {'Test': (InstrHelper,
                                                InstrHelperStarter())}
        self.root.run_time[PROFILES] =\
            {'Test1': {'connections': {'C': {'owner': []}},
                       'settings': {'S': {'check_connection': [True]}}
                       }
             }

        # This is set simply to make sure the test of InstrTask pass.
        self.task.selected_instrument = ('Test1', 'Test', 'C', 'S')
Ejemplo n.º 31
0
def task():
    r = RootTask()
    r.add_child_task(0, SimpleTask(name='simp1', database_entries={'t': 1}))
    c = ComplexTask(name='comp1', database_entries={'t1': 2, 't2': 'r'})
    c.add_child_task(0, SimpleTask(name='simp2', database_entries={'t': 1}))
    c2 = ComplexTask(name='comp2', database_entries={'t1': 2, 't2': 'r'})
    c2.add_child_task(0, SimpleTask(name='simp3', database_entries={'t': 1}))
    c.add_child_task(1, c2)
    r.add_child_task(1, c)
    return r
Ejemplo n.º 32
0
class TestConditionTask(object):
    """Test ConditionalTask.

    """

    def setup(self):
        self.root = RootTask(should_stop=Event(), should_pause=Event())
        self.task = ConditionalTask(name='Test')
        self.root.add_child_task(0, self.task)
        self.check = CheckTask(name='check')
        self.task.add_child_task(0, self.check)

    def test_check1(self):
        """Test that everything is ok if condition is evaluable.

        """
        self.task.condition = 'True'

        test, traceback = self.task.check()
        assert test
        assert not traceback
        assert self.check.check_called

    def test_check2(self):
        """Test handling a wrong condition.

        """
        self.task.condition = '*True'

        test, traceback = self.task.check(test_instr=True)
        assert not test
        assert len(traceback) == 1
        assert 'root/Test-condition' in traceback

    def test_perform1(self):
        """Test performing when condition is True.

        """
        self.task.condition = 'True'
        self.root.prepare()

        self.task.perform()
        assert self.check.perform_called

    def test_perform2(self):
        """Test performing when condition is False.

        """
        self.task.condition = '1 < 0'
        self.root.prepare()

        self.task.perform()
        assert not self.check.perform_called
    def setup(self):
        self.root = RootTask(should_stop=Event(), should_pause=Event())
        self.task = ApplyMagFieldTask(name='Test',
                                      parallel={'activated': False})
        self.root.add_child_task(0, self.task)

        self.root.run_time[DRIVERS] = {'Test': (InstrHelper,
                                                InstrHelperStarter())}
        self.root.run_time[PROFILES] =\
            {'Test1': {'connections': {'C': {'owner': []}},
                       'settings': {'S': {'make_ready': [None],
                                          'go_to_field': [None],
                                          'check_connection': [True]}}
                       }
             }

        # This is set simply to make sure the test of InstrTask pass.
        self.task.selected_instrument = ('Test1', 'Test', 'C', 'S')
Ejemplo n.º 34
0
class TestConditionTask(object):
    """Test ConditionalTask.

    """
    def setup(self):
        self.root = RootTask(should_stop=Event(), should_pause=Event())
        self.task = ConditionalTask(name='Test')
        self.root.add_child_task(0, self.task)
        self.check = CheckTask(name='check')
        self.task.add_child_task(0, self.check)

    def test_check1(self):
        """Test that everything is ok if condition is evaluable.

        """
        self.task.condition = 'True'

        test, traceback = self.task.check()
        assert test
        assert not traceback
        assert self.check.check_called

    def test_check2(self):
        """Test handling a wrong condition.

        """
        self.task.condition = '*True'

        test, traceback = self.task.check(test_instr=True)
        assert not test
        assert len(traceback) == 1
        assert 'root/Test-condition' in traceback

    def test_perform1(self):
        """Test performing when condition is True.

        """
        self.task.condition = 'True'
        self.root.prepare()

        self.task.perform()
        assert self.check.perform_called

    def test_perform2(self):
        """Test performing when condition is False.

        """
        self.task.condition = '1 < 0'
        self.root.prepare()

        self.task.perform()
        assert not self.check.perform_called
Ejemplo n.º 35
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'
Ejemplo n.º 36
0
def task():
    """Create a basic task hierarchy for testing.

    """
    root = RootTask()
    root.add_child_task(0, SimpleTask(name='simp1'))

    comp = ComplexTask(name='comp1',
                       wait={
                           'activated': True,
                           'no_wait': ['test']
                       })
    comp.add_child_task(
        0,
        SimpleTask(name='simp2', parallel={
            'activated': True,
            'pool': 'test'
        }))

    root.add_child_task(1, comp)
    return root
Ejemplo n.º 37
0
class TestLoopTask(object):
    """Test Loop task with and without included child.

    """

    def setup(self):
        self.root = RootTask(should_stop=Event(), should_pause=Event())
        self.task = LoopTask(name='Test')
        self.root.add_child_task(0, self.task)

    def test_subtask_handling(self):
        """Test adding, changing, removing the subtask.

        """
        subtask1 = CheckTask(name='check', database_entries={'val': 1})
        self.task.task = subtask1

        assert subtask1.root is self.root
        assert subtask1.database is self.root.database
        assert subtask1.parent is self.task
        assert subtask1.path and subtask1.depth
        assert 'value' not in self.task.database_entries
        assert subtask1.get_from_database('check_val')
        assert self.task.preferences['task']['name'] == 'check'

        subtask2 = CheckTask(name='rep', database_entries={'new': 1})
        self.task.task = subtask2

        assert not subtask1.root
        assert not subtask1.parent
        with pytest.raises(KeyError):
            assert subtask1.get_from_database('check_val')

        assert subtask2.root is self.root
        assert subtask2.database is self.root.database
        assert subtask2.parent is self.task
        assert subtask2.path and subtask1.depth
        assert 'value' not in self.task.database_entries
        assert subtask2.get_from_database('rep_new')
        assert self.task.preferences['task']['name'] == 'rep'

        self.task.task = None

        assert not subtask2.root
        assert not subtask2.parent
        with pytest.raises(KeyError):
            assert subtask2.get_from_database('rep_new')
        assert 'value' in self.task.database_entries

    def test_traverse(self, linspace_interface):
        """Test traversing a with interfaces ComplexTask.

        """
        self.task.interface = linspace_interface
        self.task.add_child_task(0, CheckTask(name='check'))
        assert len(list(self.task.traverse())) == 3

    def test_saving_building_from_config(self, iterable_interface):
        """Done here as the LoopTask is a viable case of a member tagged with
        child.

        """
        subtask1 = CheckTask(name='check', database_entries={'val': 1})
        self.task.task = subtask1

        self.root.update_preferences_from_members()

        deps = {'ecpy.task': {'ecpy.RootTask': RootTask,
                              'ecpy.LoopTask': LoopTask,
                              'ecpy.CheckTask': CheckTask}
                }
        new = RootTask.build_from_config(self.root.preferences, deps)

        assert new.children[0].task.name == 'check'

        self.task.interface = iterable_interface
        self.root.update_preferences_from_members()
        prefs = self.root.preferences
        del prefs['children_0']['task']
        deps = {'ecpy.task': {'ecpy.RootTask': RootTask,
                              'ecpy.LoopTask': LoopTask,
                              'ecpy.CheckTask': CheckTask},
                'ecpy.tasks.interface':
                    {('IterableLoopInterface', ('ecpy.LoopTask',)):
                        IterableLoopInterface}
                }
        new = RootTask.build_from_config(prefs, deps)

        assert not new.children[0].task

    def test_timing_handling(self):
        """Test enabling/disabling the timing.

        """
        assert 'elapsed_time' not in self.task.database_entries

        self.task.timing = True

        assert 'elapsed_time' in self.task.database_entries

        self.task.timing = False

        assert 'elapsed_time' not in self.task.database_entries

    def test_check_missing(self):
        """Test handling a missing interface (check overridden so necessary).

        """
        res, tb = self.task.check()

        assert not res
        assert len(tb) == 1
        assert 'root/Test-interface' in tb

    def test_check_linspace_interface1(self, linspace_interface):
        """Test that everything is ok when all formulas are true.

        """
        self.task.interface = linspace_interface

        test, traceback = self.task.check()
        assert test
        assert not traceback
        assert self.task.get_from_database('Test_point_number') == 11

    def test_check_linspace_interface2(self, linspace_interface):
        """Test handling a wrong start.

        """
        linspace_interface.start = '1.0*'
        self.task.interface = linspace_interface

        test, traceback = self.task.check(test_instr=True)
        assert not test
        assert len(traceback) == 1
        assert 'root/Test-start' in traceback

    def test_check_linspace_interface3(self, linspace_interface):
        """Test handling a wrong stop.

        """
        linspace_interface.stop = '2.0*'
        self.task.interface = linspace_interface

        test, traceback = self.task.check(test_instr=True)
        assert not test
        assert len(traceback) == 1
        assert 'root/Test-stop' in traceback

    def test_check_linspace_interface4(self, linspace_interface):
        """Test handling a wrong step.

        """
        linspace_interface.step = '0.1*'
        self.task.interface = linspace_interface

        test, traceback = self.task.check(test_instr=True)
        assert not test
        assert len(traceback) == 1
        assert 'root/Test-step' in traceback

    def test_check_linspace_interface5(self, linspace_interface):
        """Test handling a wrong number of point.

        """
        linspace_interface.step = '0.0'
        self.task.interface = linspace_interface

        test, traceback = self.task.check(test_instr=True)
        assert not test
        assert len(traceback) == 1
        assert 'root/Test-points' in traceback

    def test_check_linspace_interface6(self, monkeypatch, linspace_interface):
        """Test handling an issue in linspace.

        """
        self.task.interface = linspace_interface
        import ecpy.tasks.tasks.logic.loop_linspace_interface as li
        monkeypatch.setattr(li, 'linspace', lambda x: x)

        test, traceback = self.task.check(test_instr=True)
        assert not test
        assert len(traceback) == 1
        assert 'root/Test-linspace' in traceback

    def test_check_iterable_interface1(self, iterable_interface):
        """Test that everything is ok when all formulas are true.

        """
        self.task.interface = iterable_interface

        test, traceback = self.task.check()
        assert test
        assert not traceback
        assert self.task.get_from_database('Test_point_number') == 11

        iterable_interface.iterable = 'dict(a=1)'
        test, traceback = self.task.check()
        assert test
        assert not traceback
        assert self.task.get_from_database('Test_point_number') == 1
        assert self.task.get_from_database('Test_value') == 'a'

    def test_check_iterable_interface2(self, iterable_interface):
        """Test handling a wrong iterable formula.

        """
        iterable_interface.iterable = '*range(11)'
        self.task.interface = iterable_interface

        test, traceback = self.task.check()
        assert not test
        assert len(traceback) == 1
        assert 'root/Test-iterable' in traceback

    def test_check_iterable_interface3(self, iterable_interface):
        """Test handling a wrong iterable type.

        """
        iterable_interface.iterable = '1.0'
        self.task.interface = iterable_interface

        test, traceback = self.task.check()
        assert not test
        assert len(traceback) == 1
        assert 'root/Test' in traceback

    def test_check_execution_order(self, iterable_interface):
        """Test that the interface checks are run before the children checks.

        """
        iterable_interface.iterable = '[(1, 0)]'
        self.task.interface = iterable_interface

        subiter = IterableLoopInterface(iterable='{Test_value}')
        self.task.add_child_task(0, LoopTask(interface=subiter))

        test, traceback = self.task.check()
        print(traceback)
        assert test

    def test_perform1(self, iterable_interface):
        """Test performing a simple loop no timing. Iterable interface.

        """
        self.task.interface = iterable_interface
        self.root.prepare()

        self.task.perform()
        assert self.root.get_from_database('Test_value') == 10

    def test_perform2(self, linspace_interface):
        """Test performing a simple loop no timing. Linspace interface.

        """
        self.task.interface = linspace_interface
        self.root.prepare()

        self.task.perform()
        assert self.root.get_from_database('Test_value') == 2.0

    def test_perform3(self, iterable_interface):
        """Test performing a simple loop no timing. Break.

        """
        self.task.interface = iterable_interface
        self.task.add_child_task(0, BreakTask(name='break',
                                              condition='{Test_value} == 5')
                                 )
        self.root.prepare()

        self.task.perform()
        assert self.root.get_from_database('Test_value') == 5

    def test_perform4(self, iterable_interface):
        """Test performing a simple loop no timing. Continue

        """
        self.task.interface = iterable_interface
        for i, t in enumerate([ContinueTask(name='break', condition='True'),
                               CheckTask(name='check')]):
            self.task.add_child_task(i, t)

        self.root.prepare()

        self.task.perform()
        assert not self.task.children[1].perform_called

    def test_perform_task1(self, iterable_interface):
        """Test performing a loop with an embedded task no timing.

        """
        self.task.interface = iterable_interface
        self.task.task = CheckTask(name='check')
        self.root.prepare()

        self.task.perform()
        assert self.root.get_from_database('Test_index') == 11
        assert self.task.task.perform_called
        assert self.task.task.perform_value == 10

    def test_perform_task2(self):
        """Test performing a loop with an embedded task no timing. Break.

        """
        interface = IterableLoopInterface()
        interface.iterable = 'range(11)'
        self.task.interface = interface
        self.task.task = CheckTask(name='check')
        self.task.add_child_task(0, BreakTask(name='Break',
                                              condition='{Test_index} == 6')
                                 )
        self.root.prepare()

        self.task.perform()
        assert self.root.get_from_database('Test_index') == 6
        assert self.task.task.perform_called
        assert self.task.task.perform_value == 5

    def test_perform_task3(self, iterable_interface):
        """Test performing a loop with an embedded task no timing. Continue.

        """
        self.task.interface = iterable_interface
        self.task.task = CheckTask(name='check')
        self.task.add_child_task(0, ContinueTask(name='Continue',
                                                 condition='True')
                                 )
        self.task.children.append(CheckTask(name='check'))
        self.root.prepare()

        self.task.perform()
        assert self.root.get_from_database('Test_index') == 11
        assert self.task.task.perform_called
        assert self.task.task.perform_value == 10
        assert not self.task.children[1].perform_called

    def test_perform_timing1(self, iterable_interface):
        """Test performing a simple loop timing.

        """
        self.task.interface = iterable_interface
        self.task.timing = True
        self.root.prepare()

        self.task.perform()
        assert self.root.get_from_database('Test_value') == 10
        assert self.root.get_from_database('Test_elapsed_time') != 1.0

    def test_perform_timing2(self, iterable_interface):
        """Test performing a simple loop timing. Break.

        """
        self.task.interface = iterable_interface
        self.task.timing = True
        self.task.add_child_task(0, BreakTask(name='break',
                                              condition='{Test_value} == 0')
                                 )

        self.root.prepare()

        self.task.perform()
        assert self.root.get_from_database('Test_value') == 0
        assert self.root.get_from_database('Test_elapsed_time') != 1.0

    def test_perform_timing3(self, iterable_interface):
        """Test performing a simple loop timing. Continue.

        """
        self.task.interface = iterable_interface
        self.task.timing = True
        self.task.add_child_task(0, ContinueTask(name='Continue',
                                                 condition='True')
                                 )
        self.task.add_child_task(1, CheckTask(name='check'))

        self.root.prepare()

        self.task.perform()
        assert not self.task.children[1].perform_called
        assert self.root.get_from_database('Test_elapsed_time') != 1.0

    def test_perform_timing_task1(self, iterable_interface):
        """Test performing a loop with an embedded task no timing.

        """
        self.task.interface = iterable_interface
        self.task.timing = True
        self.task.task = CheckTask(name='check')

        self.root.prepare()

        self.task.perform()
        assert self.root.get_from_database('Test_index') == 11
        assert self.task.task.perform_called
        assert self.task.task.perform_value == 10
        assert self.root.get_from_database('Test_elapsed_time') != 1.0

    def test_perform_timing_task2(self, iterable_interface):
        """Test performing a loop with an embedded task no timing. Break.

        """
        self.task.interface = iterable_interface
        self.task.timing = True
        self.task.task = CheckTask(name='check')
        self.task.add_child_task(0, BreakTask(name='break',
                                              condition='{Test_index} == 1')
                                 )

        self.root.prepare()

        self.task.perform()
        assert self.root.get_from_database('Test_index') == 1
        assert self.task.task.perform_called
        assert self.task.task.perform_value == 0
        assert self.root.get_from_database('Test_elapsed_time') != 1.0

    def test_perform_timing_task3(self, iterable_interface):
        """Test performing a loop with an embedded task no timing. Continue.

        """
        self.task.interface = iterable_interface
        self.task.timing = True
        self.task.task = CheckTask(name='check')
        self.task.add_child_task(0, ContinueTask(name='break',
                                                 condition='True')
                                 )
        self.task.add_child_task(1, CheckTask(name='check'))

        self.root.prepare()

        self.task.perform()
        assert self.root.get_from_database('Test_index') == 11
        assert self.task.task.perform_called
        assert self.task.task.perform_value == 10
        assert not self.task.children[1].perform_called
        assert self.root.get_from_database('Test_elapsed_time') != 1.0

    def test_performing_stop1(self, iterable_interface):
        """Test handling stop in the middle of an iteration.

        no child, no timing.

        """
        self.task.interface = iterable_interface
        stop = lambda t, v: t.root.should_stop.set()
        self.task.add_child_task(0, CheckTask(name='Stop', custom=stop,
                                              stoppable=False))
        self.task.prepare()

        self.task.perform()

        assert self.task.children[0].perform_called == 1

    def test_performing_stop2(self, iterable_interface):
        """Test handling stop in the middle of an iteration.

        No child, timing.

        """
        self.task.timing = True
        self.task.interface = iterable_interface
        stop = lambda t, v: t.root.should_stop.set()
        self.task.add_child_task(0, CheckTask(name='Stop', custom=stop,
                                              stoppable=False))
        self.task.prepare()

        self.task.perform()

        assert self.task.children[0].perform_called == 1

    def test_performing_stop3(self, iterable_interface):
        """Test handling stop in the middle of an iteration.

        Child, no timing

        """
        self.task.interface = iterable_interface
        self.task.task = CheckTask(name='check')
        stop = lambda t, v: t.root.should_stop.set()
        self.task.add_child_task(0, CheckTask(name='Stop', custom=stop,
                                              stoppable=False))
        self.task.prepare()

        self.task.perform()

        assert self.task.children[0].perform_called == 1

    def test_performing_stop4(self, iterable_interface):
        """Test handling stop in the middle of an iteration.

        Child, timing

        """
        self.task.timing = True
        self.task.interface = iterable_interface
        self.task.task = CheckTask(name='check')
        stop = lambda t, v: t.root.should_stop.set()
        self.task.add_child_task(0, CheckTask(name='Stop', custom=stop,
                                              stoppable=False))
        self.task.prepare()

        self.task.perform()

        assert self.task.children[0].perform_called == 1

    @pytest.mark.ui
    def test_view(self, windows, task_workbench):
        """Test the LoopTask view.

        """
        core = task_workbench.get_plugin('enaml.workbench.core')
        root = RootTaskView(core=core)
        show_and_close_widget(LoopView(task=self.task, root=root))

    @pytest.mark.ui
    def test_view_with_subtask(self, windows, task_workbench):
        """Test the LoopTask view.

        """
        core = task_workbench.get_plugin('enaml.workbench.core')
        root = RootTaskView(core=core)
        self.task.task = BreakTask(name='Aux')
        show_and_close_widget(LoopView(task=self.task, root=root))
Ejemplo n.º 38
0
 def setup(self):
     self.root = RootTask(should_stop=Event(), should_pause=Event())
Ejemplo n.º 39
0
class TestPNASetRFFrequencyTask(object):
    """Test of the PNA set frequency interface.

    """

    def setup(self):
        self.root = RootTask(should_stop=Event(), should_pause=Event())
        self.task = SetRFFrequencyTask(name='Test')
        self.task.unit = 'GHz'
        self.root.add_child_task(0, self.task)

        self.root.run_time[DRIVERS] = {'Test': (InstrHelper,
                                                InstrHelperStarter())}
        self.root.run_time[PROFILES] =\
            {'Test1': {'connections': {'C': {'owner': []}},
                       'settings': {'S': {'check_connection': [True]}}
                       }
             }

        # This is set simply to make sure the test of InstrTask pass.
        self.task.selected_instrument = ('Test1', 'Test', 'C', 'S')

    def test_check_pna_interface1(self):
        """Simply test that everything is ok if frequency can be evaluated.

        """
        self.task.interface = PNASetRFFrequencyInterface(task=self.task,
                                                         channel=1)
        self.task.frequency = '1.0'

        c = self.root.run_time[PROFILES]['Test1']['connections']
        c['C'] = {'defined_channels': [[1]]}

        test, traceback = self.task.check(test_instr=True)
        assert test
        assert not traceback

    def test_check_pna_interface2(self):
        """Check handling a wrong channel.

        """
        self.task.interface = PNASetRFFrequencyInterface(task=self.task,
                                                         channel=1)
        self.task.frequency = '1.0'

        c = self.root.run_time[PROFILES]['Test1']['connections']
        c['C'] = {'defined_channels': [[2]]}

        test, traceback = self.task.check(test_instr=True)
        assert not test
        assert len(traceback) == 1

    def test_perform_pna_interface(self):
        """Test setting the frequency through the interface.

        """
        self.task.interface = PNASetRFFrequencyInterface(task=self.task)
        self.task.frequency = '1.0'

        c = self.root.run_time[PROFILES]['Test1']['connections']
        c['C'] = {'frequency': [0.0], 'owner': [None]}
        s = self.root.run_time[PROFILES]['Test1']['settings']
        s['S'] = {'get_channel': lambda x, i: x}

        self.root.prepare()

        self.task.perform()
        assert self.root.get_from_database('Test_frequency') == 1.0e9
Ejemplo n.º 40
0
 def setup(self):
     self.root = RootTask(should_stop=Event(), should_pause=Event())
     self.task = WhileTask(name='Test')
     self.root.add_child_task(0, self.task)
     self.check = CheckTask(name='check')
     self.task.add_child_task(0, self.check)
Ejemplo n.º 41
0
class TestPNASinglePointMeasureTask(object):
    """Test PNASinglePointMeasureTask.

    """
    def setup(self):
        self.root = RootTask(should_stop=Event(), should_pause=Event())
        self.task = PNASinglePointMeasureTask(name='Test')
        self.root.add_child_task(0, self.task)

        self.root.run_time[DRIVERS] = {'Test': (InstrHelper,
                                                InstrHelperStarter())}
        self.root.run_time[PROFILES] =\
            {'Test1': {'connections': {'C': {'owner': []}},
                       'settings': {'S': {'check_connection': [True]}}
                       }
             }

        # This is set simply to make sure the test of InstrTask pass.
        self.task.selected_instrument = ('Test1', 'Test', 'C', 'S')

    def test_measure_observation(self):
        pass

    def test_check1(self):
        """Simply test that everything is ok.

        """
        self.task.measures = [('S21', ''), ('S33', 'MLIN')]

        c = self.root.run_time[PROFILES]['Test1']['connections']
        c['C'] = {'defined_channels': [[1]]}

        test, traceback = self.task.check(test_instr=True)
        assert test
        assert not traceback

    def test_check2(self):
        """Check handling a wrong channel.

        """
        self.task.measures = [('S21', ''), ('S33', 'MLIN')]

        c = self.root.run_time[PROFILES]['Test1']['connections']
        c['C'] = {'defined_channels': [[3]]}

        test, traceback = self.task.check(test_instr=True)
        assert not test
        assert len(traceback) == 1

    def test_check3(self):
        """Check handling a wrong S parameter.

        """
        self.task.measures = [('S21', ''), ('SF3', 'MLIN')]

        c = self.root.run_time[PROFILES]['Test1']['connections']
        c['C'] = {'defined_channels': [[1]]}

        test, traceback = self.task.check(test_instr=True)
        assert not test
        assert len(traceback) == 1
Ejemplo n.º 42
0
class TestExceptionTasks(object):
    """Test Break and Continue tasks checks, perform will be tested in each
    looping task

    """
    def setup(self):
        self.root = RootTask(should_stop=Event(), should_pause=Event())

    def test_check1(self, exception_task):
        """Test that everything is ok condition is evaluable and parent
        is a Loop.

        """
        loop = LoopTask()
        loop.add_child_task(0, exception_task)
        self.root.add_child_task(0, loop)
        exception_task.condition = 'True'

        test, traceback = exception_task.check()
        assert test
        assert not traceback

    def test_check2(self, exception_task):
        """Simply test that everything is ok condition is evaluable and parent
        is a While.

        """
        whil = WhileTask()
        whil.add_child_task(0, exception_task)
        exception_task.condition = 'True'
        self.root.add_child_task(0, whil)

        test, traceback = exception_task.check()
        assert test
        assert not traceback

    def test_check3(self, exception_task):
        """Test handling a wrong condition.

        """
        loop = LoopTask(name='Parent')
        loop.add_child_task(0, exception_task)
        exception_task.condition = '*True'
        self.root.add_child_task(0, loop)

        test, traceback = exception_task.check()
        assert not test
        assert len(traceback) == 1
        assert 'root/Parent/Test-condition' in traceback

    def test_check4(self, exception_task):
        """Test handling a wrong parent type.

        """
        self.root.add_child_task(0, exception_task)
        exception_task.condition = 'True'

        test, traceback = exception_task.check()
        assert not test
        assert len(traceback) == 1
        assert 'root/Test-parent' in traceback
Ejemplo n.º 43
0
class TestWhileTask(object):
    """The Whiletask behaviour.

    """
    def setup(self):
        self.root = RootTask(should_stop=Event(), should_pause=Event())
        self.task = WhileTask(name='Test')
        self.root.add_child_task(0, self.task)
        self.check = CheckTask(name='check')
        self.task.add_child_task(0, self.check)

    def test_check1(self):
        """Simply test that everything is ok if condition is evaluable.

        """
        self.task.condition = 'True'

        test, traceback = self.task.check()
        assert test
        assert not traceback
        assert self.check.check_called

    def test_check2(self):
        """Test handling a wrong condition.

        """
        self.task.condition = '*True'

        test, traceback = self.task.check(test_instr=True)
        assert not test
        assert len(traceback) == 1
        assert 'root/Test-condition' in traceback

    def test_perform1(self):
        """Test performing when condition is True.

        """
        self.task.condition = '{Test_index} < 5'

        self.root.prepare()

        self.task.perform()
        assert self.check.perform_called == 4

    def test_perform2(self):
        """Test performing when condition is False.

        """
        self.task.condition = '1 < 0'

        self.root.prepare()

        self.task.perform()
        assert not self.check.perform_called

    def test_perform3(self):
        """Test handling of BreakTask and ContinueTask.

        """
        self.task.condition = 'True'
        self.task.add_child_task(0, BreakTask(name='Break', condition='True'))
        self.task.add_child_task(
            0, ContinueTask(name='Continue', condition='{Test_index} < 5'))

        self.root.prepare()

        self.task.perform()
        assert not self.check.perform_called
        assert self.task.get_from_database('Test_index') == 5

    @pytest.mark.timeout(1)
    def test_perform4(self):
        """Test handling stopping while iterating.

        """
        self.task.condition = 'True'
        stop = lambda t, v: t.root.should_stop.set()
        self.task.add_child_task(
            0, CheckTask(name='Stop', custom=stop, stoppable=False))
        self.root.prepare()

        self.task.perform()

        assert self.task.children[0].perform_called == 1
Ejemplo n.º 44
0
 def setup(self):
     self.root = RootTask(should_stop=Event(), should_pause=Event())
Ejemplo n.º 45
0
def task():
    root = RootTask()
    root.add_child_task(0, ComplexTask(name='Dummy'))
    return root
Ejemplo n.º 46
0
class TestSaveFileTask(object):

    def setup(self):
        self.root = RootTask(should_stop=Event(), should_pause=Event())
        self.task = SaveFileTask(name='Test')
        self.root.add_child_task(0, self.task)

        self.root.write_in_database('int', 1)
        self.root.write_in_database('float', 2.0)
        self.root.write_in_database('array', np.array(range(10)))

    def test_check1(self, tmpdir):
        """Test everything ok in file mode (no array size).

        """
        task = self.task
        task.folder = str(tmpdir)
        task.filename = 'test{int}.txt'
        task.saved_values = OrderedDict([('toto', '{int}'),
                                         ('tata', '{float}')])
        file_path = os.path.join(str(tmpdir), 'test1.txt')

        test, traceback = task.check()
        assert test
        assert not os.path.isfile(file_path)
        assert not task.initialized

    def test_check4(self, tmpdir):
        """Test check issues in file mode : folder.

        """
        task = self.task
        task.folder = str(tmpdir) + '{tt}'

        test, traceback = task.check()
        assert not test
        assert len(traceback) == 1

    def test_check5(self, tmpdir):
        """Test check issues in file mode : file.

        """
        task = self.task
        task.folder = str(tmpdir)
        task.filename = 'test{tt}.txt'

        test, traceback = task.check()
        assert not test
        assert len(traceback) == 1

    def test_check6(self, tmpdir):
        """Test check issues in file mode : header formatting.

        """
        task = self.task
        task.folder = str(tmpdir)
        task.filename = 'test.txt'
        task.header = 'test {*}'

        test, traceback = task.check()
        assert not test
        assert len(traceback) == 1

    def test_check9(self, tmpdir):
        """Test check issues in entries.

        """
        task = self.task
        task.folder = str(tmpdir)
        self.root.write_in_database('int', 3)
        task.filename = 'test{int}.txt'
        task.saved_values = OrderedDict([('toto', '{int*}'),
                                         ('tata', '{float*}')])

        test, traceback = task.check()
        assert not test
        assert len(traceback) == 2

    def test_check10(self, tmpdir):
        """Test warning in case the file already exists in new mode.

        """
        task = self.task
        task.folder = str(tmpdir)
        task.filename = 'test_e.txt'
        task.header = 'test'
        task.saved_values = OrderedDict([('toto', '{int}'),
                                         ('tata', '{float}')])
        file_path = os.path.join(str(tmpdir), 'test_e.txt')
        with open(file_path, 'w'):
            pass

        assert os.path.isfile(file_path)
        test, traceback = task.check()
        assert test
        assert traceback
        assert os.path.isfile(file_path)

    def test_perform1(self, tmpdir):
        """Test performing with non rec array. (Call twice perform)

        """
        task = self.task
        task.folder = str(tmpdir)
        task.filename = 'test_perform{int}.txt'
        task.header = 'test {float}'
        task.saved_values = OrderedDict([('toto', '{float}'),
                                         ('tata', '{array}')])
        file_path = os.path.join(str(tmpdir), 'test_perform1.txt')

        with open(file_path, 'w') as f:
            f.write('test\n')

        try:
            task.perform()

            assert task.initialized
            assert task.file_object
            with open(file_path) as f:
                a = f.readlines()

            assert a[:2] == ['# test 2.0\n', 'toto\ttata\n']
            for i in range(10):
                assert float(a[2+i].split('\t')[0]) == 2.0
                assert float(a[2+i].split('\t')[1]) == float(i)

            task.perform()

            assert task.initialized
            with open(file_path) as f:
                a = f.readlines()
            assert float(a[12].split('\t')[0]) == 2.0
            assert float(a[12].split('\t')[1]) == 0.0

            task.perform()
        finally:
            task.file_object.close()

    def test_perform2(self, tmpdir):
        """Test performing with a rec array. (Call twice perform)

        """
        self.root.write_in_database('array',
                                    np.rec.fromarrays([range(10), range(10)],
                                                      names=['a', 'b']))
        task = self.task
        task.folder = str(tmpdir)
        task.filename = 'test_perform_rec.txt'
        task.header = 'test'
        task.saved_values = OrderedDict([('toto', '{float}'),
                                         ('tata', '{array}')])
        file_path = os.path.join(str(tmpdir), 'test_perform_rec.txt')

        with open(file_path, 'w') as f:
            f.write('test\n')

        try:
            task.perform()

            assert task.initialized
            assert task.file_object
            with open(file_path) as f:
                a = f.readlines()

            assert a[:2] == ['# test\n', 'toto\ttata_a\ttata_b\n']

            for i in range(10):
                assert float(a[2+i].split('\t')[0]) == 2.0
                assert float(a[2+i].split('\t')[1]) == float(i)

            task.perform()

            assert task.initialized
            with open(file_path) as f:
                a = f.readlines()

            assert float(a[12].split('\t')[0]) == 2.0
            assert float(a[12].split('\t')[1]) == 0.0

            task.perform()
        finally:
            task.file_object.close()
Ejemplo n.º 47
0
class TestSaveTask(object):

    def setup(self):
        self.root = RootTask(should_stop=Event(), should_pause=Event())
        self.task = SaveTask(name='Test')
        self.root.add_child_task(0, self.task)

        self.root.write_in_database('int', 1)
        self.root.write_in_database('float', 2.0)
        self.root.write_in_database('str', 'a')

    def test_saving_target_observer(self):
        """Test that changing the target does change the database content.

        """
        self.task.saving_target = 'Array'

        assert self.task.get_from_database('Test_array') == np.array([1.0])

        self.task.saving_target = 'File'

        aux = self.task.list_accessible_database_entries()
        assert 'Test_array' not in aux

        self.task.saving_target = 'File and array'

        assert self.task.get_from_database('Test_array') == np.array([1.0])

    def test_check1(self, tmpdir):
        """Test everything ok in file mode (no array size).

        """
        task = self.task
        task.saving_target = 'File'
        task.folder = str(tmpdir)
        task.filename = 'test{int}.txt'
        task.file_mode = 'New'
        task.header = 'test'
        task.saved_values = OrderedDict([('toto', '{str}'),
                                         ('tata', '{float}')])
        file_path = os.path.join(str(tmpdir), 'test1.txt')

        test, traceback = task.check()
        assert test and not traceback
        assert not os.path.isfile(file_path)
        assert not task.initialized

        task.file_mode = 'Add'

        test, traceback = task.check()
        assert test and not traceback
        assert os.path.isfile(file_path)

    def test_check2(self):
        """Test everything ok in array mode (assert database state).

        """
        task = self.task
        task.saving_target = 'Array'
        task.array_size = '1000*{float}'
        task.saved_values = OrderedDict([('toto', '{str}'),
                                         ('tata', '{float}')])

        test, traceback = task.check()
        assert test and not traceback
        array = task.get_from_database('Test_array')
        assert array.dtype.names == ('toto', 'tata')

    def test_check3(self, tmpdir):
        """Test everything is ok in file & array mode.

        """
        task = self.task
        task.saving_target = 'File and array'
        task.folder = str(tmpdir)
        task.filename = 'test_rr.txt'
        task.file_mode = 'New'
        task.header = 'test'
        task.array_size = '1000*{float}'
        task.saved_values = OrderedDict([('toto', '{str}'),
                                         ('tata', '{float}')])
        file_path = os.path.join(str(tmpdir), 'test_rr.txt')

        test, traceback = task.check()
        assert test and not traceback
        assert not os.path.isfile(file_path)
        array = task.get_from_database('Test_array')
        assert array.dtype.names == ('toto', 'tata')

    def test_check4(self, tmpdir):
        """Test check issues in file mode : folder.

        """
        task = self.task
        task.saving_target = 'File'
        task.folder = str(tmpdir) + '{tt}'

        test, traceback = task.check()
        assert not test
        assert len(traceback) == 1

    def test_check5(self, tmpdir):
        """Test check issues in file mode : file.

        """
        task = self.task
        task.saving_target = 'File'
        task.folder = str(tmpdir)
        task.filename = 'test{tt}.txt'

        test, traceback = task.check()
        assert not test
        assert len(traceback) == 1

    def test_check6(self, tmpdir):
        """Test check issues in file mode : array_size.

        """
        task = self.task
        task.saving_target = 'File'
        task.folder = str(tmpdir)
        task.filename = 'test.txt'
        task.file_mode = 'New'
        task.header = 'test'
        task.array_size = '1000*'
        task.saved_values = OrderedDict([('toto', '{str}'),
                                         ('tata', '{float}')])
        file_path = os.path.join(str(tmpdir), 'test.txt')

        test, traceback = task.check()
        assert not test
        assert len(traceback) == 1
        assert not os.path.isfile(file_path)

    def test_check6bis(self, tmpdir):
        """Test check issues in file mode : header formatting.

        """
        task = self.task
        task.saving_target = 'File'
        task.folder = str(tmpdir)
        task.filename = 'test.txt'
        task.file_mode = 'New'
        task.header = 'test {*}'
        task.array_size = '1000'
        task.saved_values = OrderedDict([('toto', '{str}'),
                                         ('tata', '{float}')])
        file_path = os.path.join(str(tmpdir), 'test.txt')

        test, traceback = task.check()
        assert not test
        assert len(traceback) == 1
        assert not os.path.isfile(file_path)

    def test_check7(self):
        """Test check issues in array mode  : wrong array_size.

        """
        task = self.task
        task.saving_target = 'Array'
        task.array_size = '1000*{float}*'
        task.saved_values = OrderedDict([('toto', '{str}'),
                                         ('tata', '{float}')])

        test, traceback = task.check()
        assert not test
        assert len(traceback) == 1
        assert self.task.get_from_database('Test_array') == np.array([1.0])

    def test_check8(self):
        """Test check issues in array mode : absent array_size.

        """
        task = self.task
        task.saving_target = 'Array'
        task.saved_values = OrderedDict([('toto', '{str}'),
                                         ('tata', '{float}')])

        test, traceback = task.check()
        assert not test
        assert len(traceback) == 1
        assert self.task.get_from_database('Test_array') == np.array([1.0])

    def test_check9(self):
        """Test check issues in entrie.

        """
        task = self.task
        task.saving_target = 'Array'
        task.array_size = '1000*{float}'
        task.saved_values = OrderedDict([('toto', '*{str}'),
                                         ('tat{str}', '{float}@')])

        test, traceback = task.check()
        assert not test
        assert len(traceback) == 2

    def test_check9bis(self):
        """Test check issues in label.

        """
        task = self.task
        task.saving_target = 'Array'
        task.array_size = '1000*{float}'
        task.saved_values = OrderedDict([('toto', '{str}'),
                                         ('tat{str*}', '{float}')])

        test, traceback = task.check()
        assert not test
        assert len(traceback) == 1

    def test_check10(self, tmpdir):
        """Test warning in case the file already exists in new mode.

        """
        task = self.task
        task.saving_target = 'File'
        task.folder = str(tmpdir)
        task.filename = 'test_e.txt'
        task.file_mode = 'New'
        task.header = 'test'
        task.saved_values = OrderedDict([('toto', '{str}'),
                                         ('tat{str}', '{float}')])

        file_path = os.path.join(str(tmpdir), 'test_e.txt')
        with open(file_path, 'w'):
            pass

        assert os.path.isfile(file_path)
        test, traceback = task.check()
        assert test and traceback
        assert os.path.isfile(file_path)

    def test_perform1(self, tmpdir):
        """Test performing in mode file. (Call three times perform)

        """
        task = self.task
        task.saving_target = 'File'
        task.folder = str(tmpdir)
        task.filename = 'test_perform{int}.txt'
        task.file_mode = 'Add'
        task.header = 'test {str}'
        task.array_size = '3'
        task.saved_values = OrderedDict([('toto', '{str}'),
                                         ('tat{str}', '{float}')])

        file_path = os.path.join(str(tmpdir), 'test_perform1.txt')

        with open(file_path, 'w') as f:
            f.write('test\n')

        task.perform()

        assert task.initialized
        assert task.file_object
        assert task.line_index == 1
        with open(file_path) as f:
            a = f.readlines()
            assert a == ['test\n', '# test a\n', 'toto\ttata\n', 'a\t2.0\n']

        task.perform()

        assert task.initialized
        assert task.line_index == 2
        with open(file_path) as f:
            a = f.readlines()
            assert (a == ['test\n', '# test a\n', 'toto\ttata\n', 'a\t2.0\n',
                          'a\t2.0\n'])

        task.perform()

        assert not task.initialized
        assert task.line_index == 3
        with open(file_path) as f:
            a = f.readlines()
            assert a == ['test\n', '# test a\n', 'toto\ttata\n',
                         'a\t2.0\n', 'a\t2.0\n', 'a\t2.0\n']

    def test_perform2(self):
        """Test performing in array mode. (Call three times perform)

        """
        task = self.task
        task.saving_target = 'Array'
        task.array_size = '3'
        task.saved_values = OrderedDict([('toto', '{int}'),
                                         ('tat{str}', '{float}')])

        task.perform()

        assert task.initialized
        assert task.line_index == 1

        task.perform()

        assert task.initialized
        assert task.line_index == 2

        task.perform()

        assert not task.initialized
        assert task.line_index == 3

        dtype = np.dtype({'names': [task.format_string(s)
                                    for s in task.saved_values],
                          'formats': ['f8']*len(task.saved_values)})
        array = np.empty((3),  dtype)
        array[0] = (1, 2.0)
        array[1] = (1, 2.0)
        array[2] = (1, 2.0)
        np.testing.assert_array_equal(task.array, array)
Ejemplo n.º 48
0
class TestLoopTask(object):
    """Test Loop task with and without included child.

    """
    def setup(self):
        self.root = RootTask(should_stop=Event(), should_pause=Event())
        self.task = LoopTask(name='Test')
        self.root.add_child_task(0, self.task)

    def test_subtask_handling(self):
        """Test adding, changing, removing the subtask.

        """
        subtask1 = CheckTask(name='check', database_entries={'val': 1})
        self.task.task = subtask1

        assert subtask1.root is self.root
        assert subtask1.database is self.root.database
        assert subtask1.parent is self.task
        assert subtask1.path and subtask1.depth
        assert 'value' not in self.task.database_entries
        assert subtask1.get_from_database('check_val')
        assert self.task.preferences['task']['name'] == 'check'

        subtask2 = CheckTask(name='rep', database_entries={'new': 1})
        self.task.task = subtask2

        assert not subtask1.root
        assert not subtask1.parent
        with pytest.raises(KeyError):
            assert subtask1.get_from_database('check_val')

        assert subtask2.root is self.root
        assert subtask2.database is self.root.database
        assert subtask2.parent is self.task
        assert subtask2.path and subtask1.depth
        assert 'value' not in self.task.database_entries
        assert subtask2.get_from_database('rep_new')
        assert self.task.preferences['task']['name'] == 'rep'

        self.task.task = None

        assert not subtask2.root
        assert not subtask2.parent
        with pytest.raises(KeyError):
            assert subtask2.get_from_database('rep_new')
        assert 'value' in self.task.database_entries

    def test_traverse(self, linspace_interface):
        """Test traversing a with interfaces ComplexTask.

        """
        self.task.interface = linspace_interface
        self.task.add_child_task(0, CheckTask(name='check'))
        assert len(list(self.task.traverse())) == 3

    def test_saving_building_from_config(self, iterable_interface):
        """Done here as the LoopTask is a viable case of a member tagged with
        child.

        """
        subtask1 = CheckTask(name='check', database_entries={'val': 1})
        self.task.task = subtask1

        self.root.update_preferences_from_members()

        deps = {
            'ecpy.task': {
                'ecpy.RootTask': RootTask,
                'ecpy.LoopTask': LoopTask,
                'ecpy.CheckTask': CheckTask
            }
        }
        new = RootTask.build_from_config(self.root.preferences, deps)

        assert new.children[0].task.name == 'check'

        self.task.interface = iterable_interface
        self.root.update_preferences_from_members()
        prefs = self.root.preferences
        assert prefs['children_0'].sections[1] == 'task'
        del prefs['children_0']['task']
        deps = {
            'ecpy.task': {
                'ecpy.RootTask': RootTask,
                'ecpy.LoopTask': LoopTask,
                'ecpy.CheckTask': CheckTask
            },
            'ecpy.tasks.interface': {
                'ecpy.LoopTask:ecpy.IterableLoopInterface':
                IterableLoopInterface
            }
        }
        new = RootTask.build_from_config(prefs, deps)

        assert not new.children[0].task

    def test_timing_handling(self):
        """Test enabling/disabling the timing.

        """
        assert 'elapsed_time' not in self.task.database_entries

        self.task.timing = True

        assert 'elapsed_time' in self.task.database_entries

        self.task.timing = False

        assert 'elapsed_time' not in self.task.database_entries

    def test_check_missing(self):
        """Test handling a missing interface (check overridden so necessary).

        """
        res, tb = self.task.check()

        assert not res
        assert len(tb) == 1
        assert 'root/Test-interface' in tb

    def test_check_linspace_interface1(self, linspace_interface):
        """Test that everything is ok when all formulas are true.

        """
        self.task.interface = linspace_interface

        test, traceback = self.task.check()
        assert test
        assert not traceback
        assert self.task.get_from_database('Test_point_number') == 11
        assert self.task.get_from_database('Test_value') == 1.0

    def test_check_linspace_interface2(self, linspace_interface):
        """Test handling a wrong start.

        """
        linspace_interface.start = '1.0*'
        self.task.interface = linspace_interface

        test, traceback = self.task.check(test_instr=True)
        assert not test
        assert len(traceback) == 1
        assert 'root/Test-start' in traceback

    def test_check_linspace_interface3(self, linspace_interface):
        """Test handling a wrong stop.

        """
        linspace_interface.stop = '2.0*'
        self.task.interface = linspace_interface

        test, traceback = self.task.check(test_instr=True)
        assert not test
        assert len(traceback) == 1
        assert 'root/Test-stop' in traceback

    def test_check_linspace_interface4(self, linspace_interface):
        """Test handling a wrong step.

        """
        linspace_interface.step = '0.1*'
        self.task.interface = linspace_interface

        test, traceback = self.task.check(test_instr=True)
        assert not test
        assert len(traceback) == 1
        assert 'root/Test-step' in traceback

    def test_check_linspace_interface5(self, linspace_interface):
        """Test handling a wrong number of point.

        """
        linspace_interface.step = '0.0'
        self.task.interface = linspace_interface

        test, traceback = self.task.check(test_instr=True)
        assert not test
        assert len(traceback) == 1
        assert 'root/Test-points' in traceback

    def test_check_linspace_interface6(self, monkeypatch, linspace_interface):
        """Test handling an issue in linspace.

        """
        self.task.interface = linspace_interface
        import ecpy.tasks.tasks.logic.loop_linspace_interface as li
        monkeypatch.setattr(li.np, 'arange', lambda x: x)

        test, traceback = self.task.check(test_instr=True)
        assert not test
        assert len(traceback) == 1
        assert 'root/Test-arange' in traceback

    def test_check_iterable_interface1(self, iterable_interface):
        """Test that everything is ok when all formulas are true.

        """
        self.task.interface = iterable_interface

        test, traceback = self.task.check()
        assert test
        assert not traceback
        assert self.task.get_from_database('Test_point_number') == 11

        iterable_interface.iterable = 'dict(a=1)'
        test, traceback = self.task.check()
        assert test
        assert not traceback
        assert self.task.get_from_database('Test_point_number') == 1
        assert self.task.get_from_database('Test_value') == 'a'

    def test_check_iterable_interface2(self, iterable_interface):
        """Test handling a wrong iterable formula.

        """
        iterable_interface.iterable = '*range(11)'
        self.task.interface = iterable_interface

        test, traceback = self.task.check()
        assert not test
        assert len(traceback) == 1
        assert 'root/Test-iterable' in traceback

    def test_check_iterable_interface3(self, iterable_interface):
        """Test handling a wrong iterable type.

        """
        iterable_interface.iterable = '1.0'
        self.task.interface = iterable_interface

        test, traceback = self.task.check()
        assert not test
        assert len(traceback) == 1
        assert 'root/Test-iterable' in traceback

    def test_check_execution_order(self, iterable_interface):
        """Test that the interface checks are run before the children checks.

        """
        iterable_interface.iterable = '[(1, 0)]'
        self.task.interface = iterable_interface

        subiter = IterableLoopInterface(iterable='{Test_value}')
        self.task.add_child_task(0, LoopTask(interface=subiter))

        test, traceback = self.task.check()
        print(traceback)
        assert test

    def test_perform1(self, iterable_interface):
        """Test performing a simple loop no timing. Iterable interface.

        """
        self.task.interface = iterable_interface
        self.root.prepare()

        self.task.perform()
        assert self.root.get_from_database('Test_value') == 10

    def test_perform2(self, linspace_interface):
        """Test performing a simple loop no timing. Linspace interface.

        """
        self.task.interface = linspace_interface
        self.root.prepare()

        self.task.perform()
        assert self.root.get_from_database('Test_value') == 2.0

    def test_perform3(self, iterable_interface):
        """Test performing a simple loop no timing. Break.

        """
        self.task.interface = iterable_interface
        self.task.add_child_task(
            0, BreakTask(name='break', condition='{Test_value} == 5'))
        self.root.prepare()

        self.task.perform()
        assert self.root.get_from_database('Test_value') == 5

    def test_perform4(self, iterable_interface):
        """Test performing a simple loop no timing. Continue

        """
        self.task.interface = iterable_interface
        for i, t in enumerate([
                ContinueTask(name='break', condition='True'),
                CheckTask(name='check')
        ]):
            self.task.add_child_task(i, t)

        self.root.prepare()

        self.task.perform()
        assert not self.task.children[1].perform_called

    def test_perform_task1(self, iterable_interface):
        """Test performing a loop with an embedded task no timing.

        """
        self.task.interface = iterable_interface
        self.task.task = CheckTask(name='check')
        self.root.prepare()

        self.task.perform()
        assert self.root.get_from_database('Test_index') == 11
        assert self.task.task.perform_called
        assert self.task.task.perform_value == 10

    def test_perform_task2(self):
        """Test performing a loop with an embedded task no timing. Break.

        """
        interface = IterableLoopInterface()
        interface.iterable = 'range(11)'
        self.task.interface = interface
        self.task.task = CheckTask(name='check')
        self.task.add_child_task(
            0, BreakTask(name='Break', condition='{Test_index} == 6'))
        self.root.prepare()

        self.task.perform()
        assert self.root.get_from_database('Test_index') == 6
        assert self.task.task.perform_called
        assert self.task.task.perform_value == 5

    def test_perform_task3(self, iterable_interface):
        """Test performing a loop with an embedded task no timing. Continue.

        """
        self.task.interface = iterable_interface
        self.task.task = CheckTask(name='check')
        self.task.add_child_task(
            0, ContinueTask(name='Continue', condition='True'))
        self.task.children.append(CheckTask(name='check'))
        self.root.prepare()

        self.task.perform()
        assert self.root.get_from_database('Test_index') == 11
        assert self.task.task.perform_called
        assert self.task.task.perform_value == 10
        assert not self.task.children[1].perform_called

    def test_perform_timing1(self, iterable_interface):
        """Test performing a simple loop timing.

        """
        self.task.interface = iterable_interface
        self.task.timing = True
        self.root.prepare()

        self.task.perform()
        assert self.root.get_from_database('Test_value') == 10
        assert self.root.get_from_database('Test_elapsed_time') != 1.0

    def test_perform_timing2(self, iterable_interface):
        """Test performing a simple loop timing. Break.

        """
        self.task.interface = iterable_interface
        self.task.timing = True
        self.task.add_child_task(
            0, BreakTask(name='break', condition='{Test_value} == 0'))

        self.root.prepare()

        self.task.perform()
        assert self.root.get_from_database('Test_value') == 0
        assert self.root.get_from_database('Test_elapsed_time') != 1.0

    def test_perform_timing3(self, iterable_interface):
        """Test performing a simple loop timing. Continue.

        """
        self.task.interface = iterable_interface
        self.task.timing = True
        self.task.add_child_task(
            0, ContinueTask(name='Continue', condition='True'))
        self.task.add_child_task(1, CheckTask(name='check'))

        self.root.prepare()

        self.task.perform()
        assert not self.task.children[1].perform_called
        assert self.root.get_from_database('Test_elapsed_time') != 1.0

    def test_perform_timing_task1(self, iterable_interface):
        """Test performing a loop with an embedded task no timing.

        """
        self.task.interface = iterable_interface
        self.task.timing = True
        self.task.task = CheckTask(name='check')

        self.root.prepare()

        self.task.perform()
        assert self.root.get_from_database('Test_index') == 11
        assert self.task.task.perform_called
        assert self.task.task.perform_value == 10
        assert self.root.get_from_database('Test_elapsed_time') != 1.0

    def test_perform_timing_task2(self, iterable_interface):
        """Test performing a loop with an embedded task no timing. Break.

        """
        self.task.interface = iterable_interface
        self.task.timing = True
        self.task.task = CheckTask(name='check')
        self.task.add_child_task(
            0, BreakTask(name='break', condition='{Test_index} == 1'))

        self.root.prepare()

        self.task.perform()
        assert self.root.get_from_database('Test_index') == 1
        assert self.task.task.perform_called
        assert self.task.task.perform_value == 0
        assert self.root.get_from_database('Test_elapsed_time') != 1.0

    def test_perform_timing_task3(self, iterable_interface):
        """Test performing a loop with an embedded task no timing. Continue.

        """
        self.task.interface = iterable_interface
        self.task.timing = True
        self.task.task = CheckTask(name='check')
        self.task.add_child_task(0, ContinueTask(name='break',
                                                 condition='True'))
        self.task.add_child_task(1, CheckTask(name='check'))

        self.root.prepare()

        self.task.perform()
        assert self.root.get_from_database('Test_index') == 11
        assert self.task.task.perform_called
        assert self.task.task.perform_value == 10
        assert not self.task.children[1].perform_called
        assert self.root.get_from_database('Test_elapsed_time') != 1.0

    def test_performing_stop1(self, iterable_interface):
        """Test handling stop in the middle of an iteration.

        no child, no timing.

        """
        self.task.interface = iterable_interface
        stop = lambda t, v: t.root.should_stop.set()
        self.task.add_child_task(
            0, CheckTask(name='Stop', custom=stop, stoppable=False))
        self.task.prepare()

        self.task.perform()

        assert self.task.children[0].perform_called == 1

    def test_performing_stop2(self, iterable_interface):
        """Test handling stop in the middle of an iteration.

        No child, timing.

        """
        self.task.timing = True
        self.task.interface = iterable_interface
        stop = lambda t, v: t.root.should_stop.set()
        self.task.add_child_task(
            0, CheckTask(name='Stop', custom=stop, stoppable=False))
        self.task.prepare()

        self.task.perform()

        assert self.task.children[0].perform_called == 1

    def test_performing_stop3(self, iterable_interface):
        """Test handling stop in the middle of an iteration.

        Child, no timing

        """
        self.task.interface = iterable_interface
        self.task.task = CheckTask(name='check')
        stop = lambda t, v: t.root.should_stop.set()
        self.task.add_child_task(
            0, CheckTask(name='Stop', custom=stop, stoppable=False))
        self.task.prepare()

        self.task.perform()

        assert self.task.children[0].perform_called == 1

    def test_performing_stop4(self, iterable_interface):
        """Test handling stop in the middle of an iteration.

        Child, timing

        """
        self.task.timing = True
        self.task.interface = iterable_interface
        self.task.task = CheckTask(name='check')
        stop = lambda t, v: t.root.should_stop.set()
        self.task.add_child_task(
            0, CheckTask(name='Stop', custom=stop, stoppable=False))
        self.task.prepare()

        self.task.perform()

        assert self.task.children[0].perform_called == 1

    @pytest.mark.ui
    def test_view(self, windows, task_workbench):
        """Test the LoopTask view.

        """
        core = task_workbench.get_plugin('enaml.workbench.core')
        root = RootTaskView(core=core)
        show_and_close_widget(LoopView(task=self.task, root=root))

    @pytest.mark.ui
    def test_view_interface_not_inline(self, windows, task_workbench,
                                       linspace_interface):
        """Test the LoopTask view.

        """
        core = task_workbench.get_plugin('enaml.workbench.core')
        root = RootTaskView(core=core)
        self.task.interface = linspace_interface
        show_and_close_widget(LoopView(task=self.task, root=root))

    @pytest.mark.ui
    def test_view_with_subtask(self, windows, task_workbench):
        """Test the LoopTask view.

        """
        core = task_workbench.get_plugin('enaml.workbench.core')
        root = RootTaskView(core=core)
        self.task.task = BreakTask(name='Aux')
        show_and_close_widget(LoopView(task=self.task, root=root))

    @pytest.mark.ui
    def test_view_changing_interface(self, windows, task_workbench):
        """Test the LoopTask view.

        """
        core = task_workbench.get_plugin('enaml.workbench.core')
        root = RootTaskView(core=core)
        view = LoopView(task=self.task, root=root)
        show_widget(view)
        selector = view.widgets()[2]
        selector.selected = selector.items[1]
        process_app_events()
        selector.selected = selector.items[0]
        process_app_events()
Ejemplo n.º 49
0
 def setup(self):
     self.root = RootTask(should_stop=Event(), should_pause=Event())
     self.task = ConditionalTask(name='Test')
     self.root.add_child_task(0, self.task)
     self.check = CheckTask(name='check')
     self.task.add_child_task(0, self.check)
Ejemplo n.º 50
0
class TestSaveArrayTask(object):

    def setup(self):
        self.root = RootTask(should_stop=Event(), should_pause=Event())
        self.task = SaveArrayTask(name='Test')
        self.root.add_child_task(0, self.task)

        array = np.empty(2, dtype={'names': ('a', 'b'),
                                   'formats': ('f8', 'f8')})
        array[0] = (0, 1)
        array[1] = (2, 3)
        self.root.write_in_database('array', array)
        self.root.write_in_database('float', 2.0)
        self.root.write_in_database('str', 'a')

    def test_check1(self, tmpdir):
        """Check everything ok in Text mode.

        """
        array = np.empty(2, dtype={'names': ('a', 'b'),
                                   'formats': ('f8', 'f8')})
        self.root.write_in_database('arrays', {'a': array})
        task = self.task
        task.folder = str(tmpdir)
        task.filename = 'test_perform{str}.txt'
        task.mode = 'Text file'
        task.header = 'teststs'
        task.target_array = '{arrays}["a"]'

        test, traceback = task.check()

        assert test
        assert not os.path.isfile(os.path.join(str(tmpdir),
                                               'test_performa.txt'))

    def test_check2(self, tmpdir):
        """Check everything ok in Binary mode (wrong file extension, and
        header)

        """
        task = self.task
        task.folder = str(tmpdir)
        task.filename = 'test_perform{str}.txt'
        task.mode = 'Binary file'
        task.header = 'teststs'
        task.target_array = '{array}'

        test, traceback = task.check()

        assert test
        assert len(traceback) == 2
        assert 'root/Test-header' in traceback
        assert 'root/Test-file_ext' in traceback
        assert not os.path.isfile(os.path.join(str(tmpdir),
                                               'test_performa.npy'))

    def test_check3(self, tmpdir):
        """Check handling a wrong folder.

        """
        task = self.task
        task.folder = str(tmpdir) + '{eee}'
        task.target_array = '{array}'

        test, traceback = task.check()

        assert not test
        assert len(traceback) == 1

    def test_check4(self, tmpdir):
        """Check handling a wrong filename.

        """
        task = self.task
        task.folder = str(tmpdir)
        task.filename = '{rr}'
        task.target_array = '{array}'

        test, traceback = task.check()

        assert not test
        assert len(traceback) == 1

    def test_check5(self, tmpdir):
        """Check handling a wrong database address.

        """
        task = self.task
        task.folder = str(tmpdir)
        task.filename = 'test_perform{str}.txt'
        task.mode = 'Text file'
        task.header = 'teststs'
        task.target_array = '**{array}'

        test, traceback = task.check()

        assert not test
        assert len(traceback) == 1

    def test_check6(self, tmpdir):
        """Check handling a wrong type.

        """
        self.root.write_in_database('array', 1.0)
        task = self.task
        task.folder = str(tmpdir)
        task.filename = 'test_perform{str}.txt'
        task.mode = 'Text file'
        task.header = 'teststs'
        task.target_array = '{array}'

        test, traceback = task.check()

        assert not test
        assert len(traceback) == 1

    def test_perform1(self, tmpdir):
        """Test performing in text mode.

        """
        task = self.task
        task.folder = str(tmpdir)
        task.filename = 'test_perform{str}.txt'
        task.mode = 'Text file'
        task.header = 'tests'
        task.target_array = '{array}'

        task.perform()

        path = os.path.join(str(tmpdir), 'test_performa.txt')
        assert os.path.isfile(path)
        with open(path) as f:
            lines = f.readlines()
            assert lines[0:2] == ['# tests\n', 'a\tb\n']
            assert [float(x) for x in lines[2][:-1].split('\t')] == [0.0, 1.0]
            assert [float(x) for x in lines[3][:-1].split('\t')] == [2.0, 3.0]

    def test_perform1bis(self, tmpdir):
        # Test performing in text mode wrong type.
        self.root.write_in_database('array', 1.0)
        task = self.task
        task.folder = str(tmpdir)
        task.filename = 'test_perform{str}.txt'
        task.mode = 'Text file'
        task.header = 'tests'
        task.target_array = '{array}'

        with pytest.raises(AssertionError):
            task.perform()

    def test_perform2(self, tmpdir):
        """Test performing in binary mode.

        """
        task = self.task
        task.folder = str(tmpdir)
        task.filename = 'test_perform{str}.npy'
        task.mode = 'Binary file'
        task.target_array = '{array}'

        task.perform()

        path = os.path.join(str(tmpdir), 'test_performa.npy')
        assert os.path.isfile(path)
Ejemplo n.º 51
0
 def setup(self):
     self.root = RootTask(should_stop=Event(), should_pause=Event())
     self.task = SleepTask(name='Test')
     self.root.add_child_task(0, self.task)
Ejemplo n.º 52
0
 def setup(self):
     self.root = RootTask(should_stop=Event(), should_pause=Event())
     self.task = LoopTask(name='Test')
     self.root.add_child_task(0, self.task)
Ejemplo n.º 53
0
 def setup(self):
     self.root = RootTask(should_stop=Event(), should_pause=Event())
     self.task = SleepTask(name="Test")
     self.root.add_child_task(0, self.task)
Ejemplo n.º 54
0
class TestWhileTask(object):
    """The Whiletask behaviour.

    """

    def setup(self):
        self.root = RootTask(should_stop=Event(), should_pause=Event())
        self.task = WhileTask(name='Test')
        self.root.add_child_task(0, self.task)
        self.check = CheckTask(name='check')
        self.task.add_child_task(0, self.check)

    def test_check1(self):
        """Simply test that everything is ok if condition is evaluable.

        """
        self.task.condition = 'True'

        test, traceback = self.task.check()
        assert test
        assert not traceback
        assert self.check.check_called

    def test_check2(self):
        """Test handling a wrong condition.

        """
        self.task.condition = '*True'

        test, traceback = self.task.check(test_instr=True)
        assert not test
        assert len(traceback) == 1
        assert 'root/Test-condition' in traceback

    def test_perform1(self):
        """Test performing when condition is True.

        """
        self.task.condition = '{Test_index} < 5'

        self.root.prepare()

        self.task.perform()
        assert self.check.perform_called == 4

    def test_perform2(self):
        """Test performing when condition is False.

        """
        self.task.condition = '1 < 0'

        self.root.prepare()

        self.task.perform()
        assert not self.check.perform_called

    def test_perform3(self):
        """Test handling of BreakTask and ContinueTask.

        """
        self.task.condition = 'True'
        self.task.add_child_task(0, BreakTask(name='Break',
                                              condition='True'))
        self.task.add_child_task(0, ContinueTask(name='Continue',
                                                 condition='{Test_index} < 5'))

        self.root.prepare()

        self.task.perform()
        assert not self.check.perform_called
        assert self.task.get_from_database('Test_index') == 5

    @pytest.mark.timeout(1)
    def test_perform4(self):
        """Test handling stopping while iterating.

        """
        self.task.condition = 'True'
        stop = lambda t, v: t.root.should_stop.set()
        self.task.add_child_task(0, CheckTask(name='Stop', custom=stop,
                                              stoppable=False))
        self.root.prepare()

        self.task.perform()

        assert self.task.children[0].perform_called == 1