class TestEventManager(unittest.TestCase):
    """ Class for testing event.EventManager from cspy """

    def setUp(self):
        """ Prepare the test """
        self.e_mgr = EventManager()

    def test_singleton(self):
        """ Design pattern implemented correctly? """
        self.assertEqual(self.e_mgr._Singleton__instance, EventManager()._Singleton__instance)

    def test_subscription(self):
        """ Events are created correctly a recieved? """
        def function(**kwargs):
            """ Test function """
            self.assertEqual(1, kwargs['test'])
        self.e_mgr.register_event('test_event')
        self.e_mgr.subscribe('test_event', function)
        self.e_mgr.raise_event('test_event', test=1)
Exemple #2
0
class SolverVariable():
    """ Varible class for cspy Solver. Each Variable has a domain. When a variable
    is set an unique event is raised.
    """

    def __init__(self, id, domain):
        """ Init method """
        self.id = id
        self.instancied = False
        self.event_name = "%s_on_set_value" % id
        self.e_mgr = EventManager()
        self.e_mgr.register_event(self.event_name)
        if len(domain) == 0:
            raise BTException()
        self.domain = domain
        
        if len(domain) == 1:
            self.set(domain[0])
        else:
            self.value = None

    def _restore(self, domain):
        """ Restore domain to a previous domain """
        self.domain = domain
        if len(domain) > 1:
            self.instancied = False
            self.value = None

    def set(self, val):
        """ Set the value to val and raise a event """
        self.domain = [val]
        self.value = val
        self.instancied = True
        self.e_mgr.raise_event(self.event_name, id=self.id, value=val)

    def remove_from_domain(self, values):
        """ Remove values from domain. If domain had more than one value
        and after remove only have one the variable become set.
        """
        # len before removing
        domain_len = len(self.domain)
        for value in values:
            if self.in_domain(value):
                self.domain.remove(value)
        # No values is an invalid states
        if len(self.domain) == 0:
            raise BTException()
        # Now the variable is set
        elif len(self.domain) == 1 and domain_len > 1:
            self.set(self.domain[0])

    def subscribe(self, function):
        """ Subscribe to variable event """
        self.e_mgr.subscribe(self.event_name, function)

    def in_domain(self, value):
        """ Is the value in the domain?  """
        return value in self.domain

    def min(self):
        """ Min posible value of the variable"""
        return min(self.domain)

    def max(self):
        """ Max posible value of the variable"""
        return max(self.domain)

    def __str__(self):
        """ String representation of the variable """
        return str(self.domain)