예제 #1
0
    def test_dataflow_unsub(self):
        """
        Check the dataflow is automatically unsubscribed when the subscriber
        disappears.
        """
        comp = model.createInNewContainer("testscont", MyComponent, 
                                          {"name":"MyComp"})
        comp2 = model.createInNewContainer("testscont2", MyComponent, 
                                           {"name":"MyComp2"})
        
        self.count = 0
        self.data_arrays_sent = 0
        comp.data.reset()
        # special hidden function that will directly ask the original DF
        nlisteners = comp.data._count_listeners()
        self.assertEqual(nlisteners, 0)
        
        comp2.sub(comp.data)
        time.sleep(0.5)
#         comp2.unsub()
        count_arrays = comp2.get_data_count()
        logging.info("received %d arrays", count_arrays)
        nlisteners = comp.data._count_listeners()
        logging.info("orig has %d listeners", nlisteners)
        comp2.terminate()
        model.getContainer("testscont2").terminate()
        logging.info("comp2 should now be disappeared")
        
        time.sleep(0.4)
        nlisteners = comp.data._count_listeners()
        self.assertEqual(nlisteners, 0)

        comp.terminate()
        model.getContainer("testscont").terminate()
        time.sleep(0.1) # give it some time to terminate
예제 #2
0
    def test_component(self):
        cont, comp = model.createInNewContainer("testscont", model.HwComponent,
                                          {"name":"MyHwComp", "role":"affected"})
        self.assertEqual(comp.name, "MyHwComp")

        cont2, comp2 = model.createInNewContainer("testscont2", model.HwComponent,
                                           {"name":"MyHwComp2", "role":"affecter"})
        self.assertEqual(comp2.name, "MyHwComp2")

        comp2.affects.value.append(comp)
        self.assertEqual(len(comp2.affects.value), 1)
        for c in comp2.affects.value:
            self.assertTrue(isinstance(c, model.ComponentBase))
            self.assertEqual(c.name, "MyHwComp")
            self.assertEqual(c.role, "affected")

        comp2_new = model.getObject("testscont2", "MyHwComp2")
        self.assertEqual(comp2_new.name, "MyHwComp2")
        self.assertEqual(len(comp2_new.affects.value), 1)

        comp.terminate()
        comp2.terminate()
        cont.terminate()
        cont2.terminate()
        time.sleep(0.1) # give it some time to terminate
예제 #3
0
    def test_dataflow(self):
        comp = model.createInNewContainer("testscont", MyComponent, 
                                          {"name":"MyComp"})
        self.assertEqual(comp.name, "MyComp")
        
        comp2 = model.createInNewContainer("testscont2", model.HwComponent, 
                                           {"name":"MyHwComp2", "role":"affecter"})
        self.assertEqual(comp2.name, "MyHwComp2")
        
        comp2._set_affects(set([comp]))
        self.assertEqual(len(comp2.affects), 1)
        comp_indir = list(comp2.affects)[0]

        self.count = 0
        self.data_arrays_sent = 0
        comp_indir.data.reset()
        
        comp_indir.data.subscribe(self.receive_data)
        time.sleep(0.5)
        comp_indir.data.unsubscribe(self.receive_data)
        count_end = self.count
        print "received %d arrays over %d" % (self.count, self.data_arrays_sent)
        
        time.sleep(0.1)
        self.assertEqual(count_end, self.count)

        comp.terminate()
        comp2.terminate()
        model.getContainer("testscont").terminate()
        model.getContainer("testscont2").terminate()
        time.sleep(0.1) # give it some time to terminate
예제 #4
0
 def test_component(self):
     comp = model.createInNewContainer("testscont", model.HwComponent, 
                                       {"name":"MyHwComp", "role":"affected"})
     self.assertEqual(comp.name, "MyHwComp")
         
     comp2 = model.createInNewContainer("testscont2", model.HwComponent, 
                                        {"name":"MyHwComp2", "role":"affecter"})
     self.assertEqual(comp2.name, "MyHwComp2")
     
     comp2._set_affects(set([comp]))
     self.assertEqual(len(comp2.affects), 1)
     for c in comp2.affects:
         self.assertTrue(isinstance(c, model.ComponentBase))
         self.assertEqual(c.name, "MyHwComp")
         self.assertEqual(c.role, "affected")
         
     comp2_new = model.getObject("testscont2", "MyHwComp2")
     self.assertEqual(comp2_new.name, "MyHwComp2")
     self.assertEqual(len(comp2_new.affects), 1)
         
     comp.terminate()
     comp2.terminate()
     model.getContainer("testscont").terminate()
     model.getContainer("testscont2").terminate()
     time.sleep(0.1) # give it some time to terminate
예제 #5
0
    def test_dataflow(self):
        cont, comp = model.createInNewContainer("testscont", MyComponent,
                                          {"name":"MyComp"})
        self.assertEqual(comp.name, "MyComp")

        cont2, comp2 = model.createInNewContainer("testscont2", model.HwComponent,
                                           {"name":"MyHwComp2", "role":"affecter"})
        self.assertEqual(comp2.name, "MyHwComp2")

        comp2.affects.value.append(comp)
        self.assertEqual(len(comp2.affects.value), 1)
        comp_indir = list(comp2.affects.value)[0]

        self.count = 0
        self.data_arrays_sent = 0
        comp_indir.data.reset()

        comp_indir.data.subscribe(self.receive_data)
        time.sleep(0.5)
        comp_indir.data.unsubscribe(self.receive_data)
        count_end = self.count
        print("received %d arrays over %d" % (self.count, self.data_arrays_sent))

        time.sleep(0.1)
        self.assertEqual(count_end, self.count)

        comp.terminate()
        comp2.terminate()
        cont.terminate()
        cont2.terminate()
        time.sleep(0.1) # give it some time to terminate
예제 #6
0
    def test_dataflow_unsub(self):
        """
        Check the dataflow is automatically unsubscribed when the subscriber
        disappears.
        """
        cont, comp = model.createInNewContainer("testscont", MyComponent,
                                                {"name": "MyComp"})
        cont2, comp2 = model.createInNewContainer("testscont2", MyComponent,
                                                  {"name": "MyComp2"})

        self.count = 0
        self.data_arrays_sent = 0
        comp.data.reset()
        # special hidden function that will directly ask the original DF
        nlisteners = comp.data._count_listeners()
        self.assertEqual(nlisteners, 0)

        comp2.sub(comp.data)
        time.sleep(0.5)
#         comp2.unsub()
        count_arrays = comp2.get_data_count()
        logging.info("received %d arrays", count_arrays)
        nlisteners = comp.data._count_listeners()
        logging.info("orig has %d listeners", nlisteners)
        comp2.terminate()
        cont2.terminate()
        logging.info("comp2 should now be disappeared")

        time.sleep(0.4)
        nlisteners = comp.data._count_listeners()
        self.assertEqual(nlisteners, 0)

        comp.terminate()
        cont.terminate()
        time.sleep(0.1) # give it some time to terminate
예제 #7
0
def scan():
    """
    Scan for connected devices and list them
    Output like:
    Classname: 'Name of Device' init={arg: value, arg2: value2}
    """
    # only here, to avoid importing everything for other commands
    from odemis import driver
    num = 0
    # we scan by using every HwComponent class which has a .scan() method
    for module_name in driver.__all__:
        module = importlib.import_module("." + module_name, "odemis.driver")
        for cls_name, cls in inspect.getmembers(module, inspect.isclass):
            if issubclass(cls, model.HwComponent) and hasattr(cls, "scan"):
                logging.info("Scanning for %s.%s components", module_name,
                             cls_name)
                # do it in a separate container so that we don't have to load
                # all drivers in the same process (andor cams don't like it)
                container_name = "scanner%d" % num
                num += 1
                scanner = model.createInNewContainer(container_name, Scanner,
                                                     {"cls": cls})
                devices = scanner.scan()
                scanner.terminate()
                model.getContainer(container_name).terminate()
                for name, args in devices:
                    print "%s.%s: '%s' init=%s" % (module_name, cls_name, name,
                                                   str(args))
    return 0
예제 #8
0
def scan():
    """
    Scan for connected devices and list them
    Output like:
    Classname: 'Name of Device' init={arg: value, arg2: value2}
    """
    # only here, to avoid importing everything for other commands
    from odemis import driver
    num = 0
    # we scan by using every HwComponent class which has a .scan() method
    for module_name in driver.__all__:
        module = importlib.import_module("." + module_name, "odemis.driver")
        for cls_name, cls in inspect.getmembers(module, inspect.isclass):
            if issubclass(cls, model.HwComponent) and hasattr(cls, "scan"):
                logging.info("Scanning for %s.%s components", module_name, cls_name)
                # do it in a separate container so that we don't have to load
                # all drivers in the same process (andor cams don't like it)
                container_name = "scanner%d" % num
                num += 1
                scanner = model.createInNewContainer(container_name, Scanner, {"cls": cls})
                devices = scanner.scan()
                scanner.terminate()
                model.getContainer(container_name).terminate()
                for name, args in devices:
                    print "%s.%s: '%s' init=%s" % (module_name, cls_name, name, str(args))
    return 0
예제 #9
0
def scan(cls=None):
    """
    Scan for connected devices and list them
    cls (str or None): the class name to scan (as written in the microscope file)
    Output like:
    Classname: 'Name of Device' init={arg: value, arg2: value2}
    """
    # FIXME: need to work when /var/run/odemisd is not available:
    # => fail to create the container.

    # only here, to avoid importing everything for other commands
    from odemis import driver
    num = 0
    cls_found = False
    # we scan by using every HwComponent class which has a .scan() method
    for module_name in driver.__all__:
        try:
            module = importlib.import_module("." + module_name,
                                             "odemis.driver")
        except ImportError:
            logging.warning("Cannot try module %s, failed to load." %
                            module_name)
        except Exception:
            logging.exception("Failed to load module %s" % module_name)
        for cls_name, clso in inspect.getmembers(module, inspect.isclass):
            if issubclass(clso, model.HwComponent) and hasattr(clso, "scan"):
                if cls:
                    full_name = "%s.%s" % (module_name, cls_name)
                    if cls != full_name:
                        logging.debug("Skipping %s", full_name)
                        continue
                    else:
                        cls_found = True

                logging.info("Scanning for %s.%s components", module_name,
                             cls_name)
                # do it in a separate container so that we don't have to load
                # all drivers in the same process (andor cams don't like it)
                container_name = "scanner%d" % num
                num += 1
                try:
                    cont, scanner = model.createInNewContainer(
                        container_name, Scanner, {"cls": clso})
                    devices = scanner.scan()
                    scanner.terminate()
                    cont.terminate()
                except Exception:
                    logging.exception("Failed to scan %s.%s components",
                                      module_name, cls_name)
                else:
                    if not devices:
                        logging.info("No device found")
                    for name, args in devices:
                        print "%s.%s: '%s' init=%s" % (module_name, cls_name,
                                                       name, str(args))

    if cls and not cls_found:
        raise ValueError("Failed to find class %s" % cls)
예제 #10
0
    def test_instantiate_simple_component(self):
        container, comp = model.createInNewContainer("testscont", FamilyValueComponent, {"name":"MyComp"})
        self.assertEqual(comp.name, "MyComp")

        comp_prime = model.getObject("testscont", "MyComp")
        self.assertEqual(comp_prime.name, "MyComp")

        comp.terminate()
        container.terminate()
예제 #11
0
    def test_instantiate_simple_component(self):
        container, comp = model.createInNewContainer("testscont", FamilyValueComponent, {"name":"MyComp"})
        self.assertEqual(comp.name, "MyComp")

        comp_prime = model.getObject("testscont", "MyComp")
        self.assertEqual(comp_prime.name, "MyComp")

        comp.terminate()
        container.terminate()
예제 #12
0
    def _instantiate_comp(self, name):
        """
        Instantiate a component
        name (str): name that will be given to the component instance
        returns (HwComponent): an instance of the component
        Raises:
            SemanticError in case an error in the model is detected.
        """
        attr = self.ast[name]
        class_name = attr["class"]
        class_comp = get_class(class_name)

        # create the arguments:
        # name (str)
        # role (str)
        # children:
        #  * explicit creation: (dict str -> HwComponent) internal name -> comp
        #  * delegation: (dict str -> dict) internal name -> init arguments
        # anything else is passed as is
        args = self._make_args(name)

        logging.debug("Going to instantiate %s (%s) with args %s",
                      name, class_name, args)

        # if the component is connected to a PowerSupplier we first need to turn
        # it on before we instantiate it
        if "power_supplier" in args:
            f = args["power_supplier"].supply({name: True})
            f.result()

        if self.dry_run and not class_name == "Microscope":
            # mock class for everything but Microscope (because it is safe)
            args["_realcls"] = class_comp
            class_comp = mock.MockComponent

        try:
            cont = self._get_container(name)
            if cont is None:
                # new container has the same name as the component
                cont, comp = model.createInNewContainer(name, class_comp, args)
                self.sub_containers[name] = cont
            else:
                logging.debug("Creating %s in container %s", name, cont)
                comp = model.createInContainer(cont, class_comp, args)
            self._comp_container[name] = cont
        except Exception:
            logging.error("Error while instantiating component %s.", name)
            raise

        self.components.add(comp)
        # Add all the children, which were created by delegation, to our list of components.
        self.components |= comp.children.value
        for child in comp.children.value:
            self._comp_container[child.name] = cont

        return comp
예제 #13
0
    def test_va(self):
        cont, comp = model.createInNewContainer("testscont", SimpleHwComponent,
                                                {
                                                    "name": "MyHwComp",
                                                    "role": "affected"
                                                })
        self.assertEqual(comp.name, "MyHwComp")

        cont2, comp2 = model.createInNewContainer("testscont2",
                                                  model.HwComponent, {
                                                      "name": "MyHwComp2",
                                                      "role": "affecter"
                                                  })
        self.assertEqual(comp2.name, "MyHwComp2")

        comp2.affects.value.append(comp)
        self.assertEqual(len(comp2.affects.value), 1)
        comp_indir = comp2.affects.value[0]
        self.assertIsInstance(comp_indir.prop, VigilantAttributeBase)
        self.assertIsInstance(comp_indir.cont, VigilantAttributeBase)
        self.assertIsInstance(comp_indir.enum, VigilantAttributeBase)

        prop = comp_indir.prop
        self.assertEqual(prop.value, 42)
        prop.value += 1
        self.assertEqual(prop.value, 43)
        self.assertEqual(comp.prop.value, 43)

        self.assertEqual(comp_indir.cont.value, 2.0)
        self.assertIsInstance(comp_indir.cont.range, tuple)
        try:
            # there is no such thing, it should fail
            c = len(comp_indir.cont.choices)
            self.fail("Accessing choices should fail")
        except:
            pass

        self.assertEqual(comp_indir.enum.value, "a")

        comp.terminate()
        comp2.terminate()
        cont.terminate()
        cont2.terminate()
예제 #14
0
파일: modelgen.py 프로젝트: delmic/odemis
    def _instantiate_comp(self, name):
        """
        Instantiate a component
        name (str): name that will be given to the component instance
        returns (HwComponent): an instance of the component
        Raises:
            SemanticError in case an error in the model is detected.
        """
        attr = self.ast[name]
        class_name = attr["class"]
        class_comp = get_class(class_name)

        # create the arguments:
        # name (str)
        # role (str)
        # children:
        #  * explicit creation: (dict str -> HwComponent) internal name -> comp
        #  * delegation: (dict str -> dict) internal name -> init arguments
        # anything else is passed as is
        args = self._make_args(name)

        logging.debug("Going to instantiate %s (%s) with args %s",
                      name, class_name, args)

        # if the component is connected to a PowerSupplier we first need to turn
        # it on before we instantiate it
        if "power_supplier" in args:
            f = args["power_supplier"].supply({name: True})
            f.result()

        if self.dry_run and not class_name == "Microscope":
            # mock class for everything but Microscope (because it is safe)
            args["_realcls"] = class_comp
            class_comp = mock.MockComponent

        try:
            cont = self._get_container(name)
            if cont is None:
                # new container has the same name as the component
                cont, comp = model.createInNewContainer(name, class_comp, args)
                self.sub_containers[name] = cont
            else:
                logging.debug("Creating %s in container %s", name, cont)
                comp = model.createInContainer(cont, class_comp, args)
            self._comp_container[name] = cont
        except Exception:
            logging.error("Error while instantiating component %s.", name)
            raise

        self.components.add(comp)
        # Add all the children to our list of components. Useful only if child
        # created by delegation, but can't hurt to add them all.
        self.components |= comp.children.value

        return comp
예제 #15
0
    def test_roattributes(self):
        cont, comp = model.createInNewContainer("testscont", MyComponent,
                                                {"name": "MyComp"})
        self.assertEqual(comp.name, "MyComp")

        cont2, comp2 = model.createInNewContainer("testscont2", model.HwComponent,
                                                  {"name": "MyHwComp2", "role": "affecter"})
        self.assertEqual(comp2.name, "MyHwComp2")

        comp2.affects.value.append(comp)
        self.assertEqual(len(comp2.affects.value), 1)
        for c in comp2.affects.value:
            self.assertTrue(isinstance(c, model.ComponentBase))
            self.assertEqual(c.name, "MyComp")
            val = comp.my_value
            self.assertEqual(val, "ro", "Reading attribute failed")

        comp.terminate()
        comp2.terminate()
        cont.terminate()
        cont2.terminate()
예제 #16
0
 def test_roattributes(self):
     comp = model.createInNewContainer("testscont", MyComponent, 
                                       {"name":"MyComp"})
     self.assertEqual(comp.name, "MyComp")
     
     comp2 = model.createInNewContainer("testscont2", model.HwComponent, 
                                        {"name":"MyHwComp2", "role":"affecter"})
     self.assertEqual(comp2.name, "MyHwComp2")
     
     comp2._set_affects(set([comp]))
     self.assertEqual(len(comp2.affects), 1)
     for c in comp2.affects:
         self.assertTrue(isinstance(c, model.ComponentBase))
         self.assertEqual(c.name, "MyComp")
         val = comp.my_value
         self.assertEqual(val, "ro", "Reading attribute failed")
     
     comp.terminate()
     comp2.terminate()
     model.getContainer("testscont").terminate()
     model.getContainer("testscont2").terminate()
예제 #17
0
파일: main.py 프로젝트: ktsitsikas/odemis
def scan(cls=None):
    """
    Scan for connected devices and list them
    cls (str or None): the class name to scan (as written in the microscope file)
    Output like:
    Classname: 'Name of Device' init={arg: value, arg2: value2}
    """
    # FIXME: need to work when /var/run/odemisd is not available:
    # => fail to create the container.

    # only here, to avoid importing everything for other commands
    from odemis import driver
    num = 0
    cls_found = False
    # we scan by using every HwComponent class which has a .scan() method
    for module_name in driver.__all__:
        try:
            module = importlib.import_module("." + module_name, "odemis.driver")
        except ImportError:
            logging.warning("Cannot try module %s, failed to load." % module_name)
        except Exception:
            logging.exception("Failed to load module %s" % module_name)
        for cls_name, clso in inspect.getmembers(module, inspect.isclass):
            if issubclass(clso, model.HwComponent) and hasattr(clso, "scan"):
                if cls:
                    full_name = "%s.%s" % (module_name, cls_name)
                    if cls != full_name:
                        logging.debug("Skipping %s", full_name)
                        continue
                    else:
                        cls_found = True

                logging.info("Scanning for %s.%s components", module_name, cls_name)
                # do it in a separate container so that we don't have to load
                # all drivers in the same process (andor cams don't like it)
                container_name = "scanner%d" % num
                num += 1
                try:
                    cont, scanner = model.createInNewContainer(container_name, Scanner, {"cls": clso})
                    devices = scanner.scan()
                    scanner.terminate()
                    cont.terminate()
                except Exception:
                    logging.exception("Failed to scan %s.%s components", module_name, cls_name)
                else:
                    if not devices:
                        logging.info("No device found")
                    for name, args in devices:
                        print "%s.%s: '%s' init=%s" % (module_name, cls_name, name, str(args))

    if cls and not cls_found:
        raise ValueError("Failed to find class %s" % cls)
예제 #18
0
 def test_instantiate_component(self):
     comp = model.createInNewContainer("testcont", MyComponent, {"name":"MyComp"})
     self.assertEqual(comp.name, "MyComp")
     val = comp.my_value
     self.assertEqual(val, "ro", "Reading attribute failed")
     
     comp_prime = model.getObject("testcont", "MyComp")
     self.assertEqual(comp_prime.name, "MyComp")
     
     container = model.getContainer("testcont")
     container.ping()
     comp.terminate()
     container.terminate()
예제 #19
0
파일: modelgen.py 프로젝트: arijitxx/odemis
    def _instantiate_comp(self, name):
        """
        Instantiate a component
        name (str): name that will be given to the component instance
        returns (HwComponent): an instance of the component
        Raises:
            SemanticError in case an error in the model is detected. 
        """
        attr = self.ast[name]
        class_name = attr["class"]
        class_comp = get_class(class_name)

        # create the arguments:
        # name (str)
        # role (str)
        # children:
        #  * explicit creation: (dict str -> HwComponent) internal name -> comp
        #  * delegation: (dict str -> dict) internal name -> init arguments
        # anything else is passed as is
        args = self._make_args(name)

        logging.debug("Going to instantiate %s (%s) with args %s", name,
                      class_name, args)

        if self.dry_run and not class_name == "Microscope":
            # mock class for everything but Microscope (because it is safe)
            args["_realcls"] = class_comp
            class_comp = mock.MockComponent

        try:
            # If it's not a leaf, it's probably a wrapper (eg, MultiplexActuator),
            # which is simple Python code and so doesn't need to run in a
            # separate container.
            if self.create_sub_containers and self.is_leaf(name):
                # new container has the same name as the component
                cont, comp = model.createInNewContainer(name, class_comp, args)
                self.sub_containers.add(cont)
            else:
                logging.debug("Creating %s in root container", name)
                comp = self.root_container.instantiate(class_comp, args)
        except Exception:
            logging.error("Error while instantiating component %s.", name)
            raise

        self.components.add(comp)
        # Add all the children to our list of components. Useful only if child
        # created by delegation, but can't hurt to add them all.
        self.components |= comp.children.value

        return comp
예제 #20
0
    def test_multi_components(self):
        container, comp = model.createInNewContainer("testmulti", FatherComponent, {"name":"Father", "children_num":3})
        self.assertEqual(comp.name, "Father")
        self.assertEqual(len(comp.children.value), 3, "Component should have 3 children")

        for child in comp.children.value:
            self.assertLess(child.value, 3)
            comp_direct = model.getObject("testmulti", child.name)
            self.assertEqual(comp_direct.name, child.name)
#            child.terminate()

        comp.terminate()
        # we are not terminating the children, but this should be caught by the container
        container.terminate()
예제 #21
0
파일: modelgen.py 프로젝트: arijitxx/odemis
    def _instantiate_comp(self, name):
        """
        Instantiate a component
        name (str): name that will be given to the component instance
        returns (HwComponent): an instance of the component
        Raises:
            SemanticError in case an error in the model is detected. 
        """
        attr = self.ast[name]
        class_name = attr["class"]
        class_comp = get_class(class_name)

        # create the arguments:
        # name (str)
        # role (str)
        # children:
        #  * explicit creation: (dict str -> HwComponent) internal name -> comp
        #  * delegation: (dict str -> dict) internal name -> init arguments
        # anything else is passed as is
        args = self._make_args(name)

        logging.debug("Going to instantiate %s (%s) with args %s",
                      name, class_name, args)

        if self.dry_run and not class_name == "Microscope":
            # mock class for everything but Microscope (because it is safe)
            args["_realcls"] = class_comp
            class_comp = mock.MockComponent

        try:
            # If it's not a leaf, it's probably a wrapper (eg, MultiplexActuator),
            # which is simple Python code and so doesn't need to run in a
            # separate container.
            if self.create_sub_containers and self.is_leaf(name):
                # new container has the same name as the component
                cont, comp = model.createInNewContainer(name, class_comp, args)
                self.sub_containers.add(cont)
            else:
                logging.debug("Creating %s in root container", name)
                comp = self.root_container.instantiate(class_comp, args)
        except Exception:
            logging.error("Error while instantiating component %s.", name)
            raise

        self.components.add(comp)
        # Add all the children to our list of components. Useful only if child 
        # created by delegation, but can't hurt to add them all.
        self.components |= comp.children.value

        return comp
예제 #22
0
    def test_instantiate_component(self):
        comp = model.createInNewContainer("testcont", MyComponent,
                                          {"name": "MyComp"})
        self.assertEqual(comp.name, "MyComp")
        val = comp.my_value
        self.assertEqual(val, "ro", "Reading attribute failed")

        comp_prime = model.getObject("testcont", "MyComp")
        self.assertEqual(comp_prime.name, "MyComp")

        container = model.getContainer("testcont")
        container.ping()
        comp.terminate()
        container.terminate()
예제 #23
0
    def test_multi_components(self):
        comp = model.createInNewContainer("testmulti", FatherComponent, {"name":"Father", "children_num":3})
        self.assertEqual(comp.name, "Father")
        self.assertEqual(len(comp.children), 3, "Component should have 3 children")
        
        for child in comp.children:
            self.assertLess(child.value, 3)
            comp_direct = model.getObject("testmulti", child.name)
            self.assertEqual(comp_direct.name, child.name)
#            child.terminate()
        
        comp.terminate()
        # we are not terminating the children, but this should be caught by the container
        model.getContainer("testmulti").terminate()
예제 #24
0
 def test_va(self):
     comp = model.createInNewContainer("testscont", SimpleHwComponent, 
                                       {"name":"MyHwComp", "role":"affected"})
     self.assertEqual(comp.name, "MyHwComp")
     
     comp2 = model.createInNewContainer("testscont2", model.HwComponent, 
                                        {"name":"MyHwComp2", "role":"affecter"})
     self.assertEqual(comp2.name, "MyHwComp2")
     
     comp2._set_affects(set([comp]))
     self.assertEqual(len(comp2.affects), 1)
     comp_indir = list(comp2.affects)[0]
     self.assertIsInstance(comp_indir.prop, VigilantAttributeBase)
     self.assertIsInstance(comp_indir.cont, VigilantAttributeBase)
     self.assertIsInstance(comp_indir.enum, VigilantAttributeBase)
             
     prop = comp_indir.prop
     self.assertEqual(prop.value, 42)
     prop.value += 1
     self.assertEqual(prop.value, 43)
     self.assertEqual(comp.prop.value, 43)
     
     self.assertEqual(comp_indir.cont.value, 2.0)
     self.assertIsInstance(comp_indir.cont.range, tuple)
     try:
         # there is no such thing, it should fail
         c = len(comp_indir.cont.choices)
         self.fail("Accessing choices should fail")
     except:
         pass
     
     self.assertEqual(comp_indir.enum.value, "a")
     
     comp.terminate()
     comp2.terminate()
     model.getContainer("testscont").terminate()
     model.getContainer("testscont2").terminate()
예제 #25
0
    def instantiate_comp(self, name):
        """
        Instantiate a component
        name (str): name that will be given to the component instance
        returns (HwComponent): an instance of the component
        Raises:
            SemanticError in case an error in the model is detected. 
        """
        attr = self.ast[name]
        class_name = attr["class"]
        class_comp = get_class(class_name)

        # create the arguments:
        # name (str)
        # role (str)
        # children:
        #  * explicit creation: (dict str -> HwComponent) internal name -> comp
        #  * delegation: (dict str -> dict) internal name -> init arguments
        # anything else is passed as is
        args = self.make_args(name)

        if self.dry_run and not class_name == "Microscope":
            # mock class for everything but Microscope (because it is safe)
            args["_realcls"] = class_comp
            class_comp = model.MockComponent

        try:
            if self.create_sub_containers and self.is_leaf(name):
                # new container has the same name as the component
                comp = model.createInNewContainer(name, class_comp, args)
                self.sub_containers.add(model.getContainer(name))
            elif self.root_container:
                comp = self.root_container.instantiate(class_comp, args)
            else:
                comp = class_comp(**args)
        except Exception:
            logging.error("Error while instantiating component %s.", name)
            raise

        # Add all the children to our list of components. Useful only if child
        # created by delegation, but can't hurt to add them all.
        self.components |= getattr(comp, "children", set())

        return comp