def __init__(self, config):
        """
        Instantiate a new emulator
        :param config: config to use
        :type config: configuration.config.EmulatorConfig
        """
        self.logger = init_logger(__name__)

        if not config.is_initialized():
            self.logger.error(
                'Config is not properly initialized, exiting emulator')
            raise Exception('Config is not properly initialized')

        self.config = config
        self.text_scenarios = config.get_text_scenarios()
        self.hex_scenarios = config.get_hex_scenarios()
        self.overwritten_text_scenarios = dict()
        self.overwritten_hex_scenarios = dict()
        self.input = config.get_input()
        self.output = config.get_output()
        self.keys = list(self.text_scenarios.keys())
        self.field_values = FieldValueList()
        self.paused = False
        self.stopped = False
        self.status = 'initialized'
        self.bit_error_random = Random(config.get_default_seed())
        self.observable = Observable()
        self.timed = self.config.get_timed()
        self.stop_condition = self.config.get_stop_condition()
        if self.timed:
            self.event_queue = EventQueue(self)
Ejemplo n.º 2
0
 def __init__(self, direction, puzzle, wordsToFind):
     self.observable = Observable()
     self.direction = direction
     self.puzzle = puzzle
     self.puzzleRows = len(puzzle)
     self.puzzleColumns = len(puzzle[0])
     self.wordsToFind = wordsToFind
Ejemplo n.º 3
0
 def subscribe(self, *args, **keys):
     Observable.subscribe( self, *args, **keys )
     if self.dirty:
         self._notifyDirty()
 #
 #def _getRecursiveDirty(self):
 #    if self.dirty:
 #        return True
 #    
 #    for name, value in vars(self).items():
 #        if hasattr(name, 'dirty'):
 #            if value.recursiveDirty:
 #                return True
 #    
 #    return False
 #
 #def _setRecursiveDirty(self, dirtyValue):
 #    for name in self.observer_attribs:
 #        value = getattr(self, name)
 #        try:
 #            value.recursiveDirty = dirtyValue
 #        except AttributeError:
 #            pass
 #        #value.dirty = False
 #        pass
 #            
 #    self.dirty = dirtyValue
 #
 #recursiveDirty = property( _getRecursiveDirty, _setRecursiveDirty )
Ejemplo n.º 4
0
 def __init__(self, environment):
     Observable.__init__(self)
     self.environment = environment
     self.debug = self.environment.getdebugmode()
     self.verbose = self.environment.getverbosemode()
     self.constsrequired = [localize.REPORTSERVER,
                            localize.STONIXDEVS,
                            localize.STONIXERR,
                            localize.MAILRELAYSERVER]
     reportfile = 'stonix-report.log'
     xmlfile = 'stonix-xmlreport.xml'
     self.logpath = self.environment.get_log_path()
     self.reportlog = os.path.join(self.logpath, reportfile)
     self.xmllog = os.path.join(self.logpath, xmlfile)
     if self.debug:
         print 'LOGDISPATCHER: xml log path: ' + self.xmllog
     if os.path.isfile(self.xmllog):
         try:
             if os.path.exists(self.xmllog + '.old'):
                 os.remove(self.xmllog + '.old')
             move(self.xmllog, self.xmllog + '.old')
         except (KeyboardInterrupt, SystemExit):
             # User initiated exit
             raise
         except Exception, err:
             print 'logdispatcher: '
             print traceback.format_exc()
             print err
Ejemplo n.º 5
0
    def __init__(self, config, environ, logger, statechglogger):
        Observable.__init__(self)
        self.config = config
        self.environ = environ
        self.statechglogger = statechglogger
        self.logdispatch = logger
        self.rulenumber = 0
        self.rulename = 'template class'
        self.mandatory = False
        self.helptext = """This is the default help text for the base rule
class. If you are seeing this text it is because the developer for one of the
rules forgot to assign the appropriate help text. Please file a bug against
LANL-stonix."""
        self.executionpriority = 50
        self.rootrequired = True
        self.configinsimple = False
        self.detailedresults = """This is the default detailed results text
        for the base rule class. If you are seeing this text it is because the
        developer for one of the rules forgot to assign the appropriate text.
        Please file a bug against stonix."""
        self.compliant = False
        self.rulesuccess = True
        self.databaserule = False
        self.applicable = {'default': 'default'}
        self.revertable = False
        self.confitems = []
        self.currstate = "notconfigured"
        self.targetstate = "configured"
        self.guidance = []
Ejemplo n.º 6
0
 def __init__(self):
     """
     Constructor for monster base class. Initiates observable 
     args:
     param(self)
     """
     Observable.__init__(self)
Ejemplo n.º 7
0
    def __init__(self,id_scan,nom_unique,type_scan,chemin_rapport,liste_adresses,nmap_options=None,nessus_policy_id=None):
        Observable.__init__(self)
        self.nmap={'enable':False,'options':None,'instance':None,'status':'disable','progress':0,'import':'disable'}
        self.nessus={'enable':False,'id':-1,'policy_id':None,'status':'disable','progress':0,'import':'disable'}
        self.erreurs=[]
        self.cibles=liste_adresses
        self.nom_unique=nom_unique
        self.chemin_rapport=chemin_rapport
        self.id_scan=id_scan
        self.tache_attente=[]
        self.compteur_erreur_nessus=0
        self.type_scan=type_scan

        if nmap_options!=None:
            self.nmap['enable']=True
            self.nmap['options']=nmap_options
            self.nmap['status']='ready'
            self.nmap['import']='ready'
            self.nmap['instance']=scanNmap(self.cibles,self.nmap['options'],CHEMIN_TEMP+'nmap/'+str(self.nom_unique)+'.xml')


        if nessus_policy_id!=None:
            self.nessus['enable']=True
            self.nessus['policy_id']=nessus_policy_id
            self.nessus['status']='ready'
            self.nessus['import']='ready'
Ejemplo n.º 8
0
    def __init__(self, config, environ, logger, statechglogger):
        Observable.__init__(self)
        self.config = config
        self.environ = environ
        self.statechglogger = statechglogger
        self.logdispatch = logger
        self.rulenumber = 0
        self.rulename = 'template class'
        self.mandatory = False
        self.helptext = """This is the default help text for the base rule
class. If you are seeing this text it is because the developer for one of the
rules forgot to assign the appropriate help text. Please file a bug against
LANL-stonix."""
        self.executionpriority = 50
        self.rootrequired = True
        self.configinsimple = False
        self.detailedresults = """This is the default detailed results text
        for the base rule class. If you are seeing this text it is because the
        developer for one of the rules forgot to assign the appropriate text.
        Please file a bug against stonix."""
        self.compliant = False
        self.rulesuccess = True
        self.databaserule = False
        self.applicable = {'default': 'default'}
        self.revertable = False
        self.confitems = []
        self.currstate = "notconfigured"
        self.targetstate = "configured"
        self.guidance = []
Ejemplo n.º 9
0
 def __init__(self, N, food_size):
     self.reaction_computed = Observable()
     self.step_computed = Observable()
     self.generation_computed = Observable()
     self.expressions = Multiset(N)
     self.tmp_removed_expressions = []
     self.food_size = food_size
Ejemplo n.º 10
0
    def __init__(self, app=None):
        Observable.__init__(self)
        self.app = None
        self.resources = {}

        if app is not None:
            self.init_app(app)
Ejemplo n.º 11
0
def test_off():
    """test obs.off method"""
    obs = Observable()
    nose.assert_false(obs.events)

    @obs.on("on_test")
    def on_test():
        pass

    nose.assert_equals(obs.events['on_test'], [on_test])
    nose.assert_true(obs.trigger("on_test"))
    obs.off("on_test", on_test)
    nose.assert_equals(obs.events['on_test'],[])

    obs.off()
    nose.assert_false(obs.events)

    @obs.on("more_than_one_event")
    def func1():
        pass

    @obs.on("more_than_one_event")
    def func2():
        pass

    @obs.on("more_than_one_event")
    def func3():
        pass

    nose.assert_equals(obs.events["more_than_one_event"], [func1, func2, func3])
    obs.off("more_than_one_event", func2)
    nose.assert_equals(obs.events["more_than_one_event"], [func1, func3])
    obs.off("more_than_one_event")
    nose.assert_equals(obs.events["more_than_one_event"], [])
Ejemplo n.º 12
0
    def __init__(self, tableau_adresse, options, fichier_sortie):
        Thread.__init__(self)
        Observable.__init__(self)
        self.adresse = ""
        self.progress = 0.0
        self.status = "ready"

        # On cree un string a partir de la liste des adresses
        # contenues dans le tableau
        for ip in tableau_adresse:
            try:
                ip = valideIP(ip)
                self.adresse += " " + str(ip)
            except:
                pass

        liste_arguments = [options, fichier_sortie]

        # Contrôle des arguments
        for arg in liste_arguments:
            error = re.search('[;|<>"`&{}]', str(arg))

            if error != None:
                raise Exception("Paramètres Nmap invalide")

        # Si pas de levé d'exception
        self.options = options
        self.fichier_sortie = fichier_sortie
Ejemplo n.º 13
0
def test_no_event_for_trigger():
    """test exception raising for not existing events"""
    obs = Observable()
    nose.assert_false(obs.events)

    nose.assert_false(obs.trigger("no_existing_event"))
    nose.assert_raises(EventNotFound, obs.off, "no_existing_event")
Ejemplo n.º 14
0
    def __init__(self):
        self.phrases = Observable({})
        self.db = MongoDbProxy("mongodb://localhost:27017/", "RepeatItDb",
                               "phrases")

        data = self.db.get_all()
        self.phrases.setData(data)
Ejemplo n.º 15
0
	def __init__(self, trig, echo):
		Thread.__init__(self)
		self.trig = trig
		self.echo = echo
		self.distance = UltraSonicSensor.DISTANCE_DEFAULT
		Observable.__init__(self)
                self.cont = True
Ejemplo n.º 16
0
    def __init__(self, app=None):
        Observable.__init__(self)
        self.app = None
        self.resources = {}

        if app is not None:
            self.init_app(app)
Ejemplo n.º 17
0
	def __init__(self, network_interface, src_ip, target_ip):
		Observable.__init__(self)
		Executable.__init__(self, self.ping_executable)
		self.network_interface = network_interface
		self.src_ip = src_ip
		self.target_ip = target_ip
		print "# Setting up loop for pinging " + target_ip + " (with " + src_ip + " on " + network_interface + ") "
Ejemplo n.º 18
0
    def __init__(self):
        # Create Home as an Observer object
        Observer.__init__(self)

        # Create Home as an Observable object
        Observable.__init__(self)

        # Monsters/NPCs within the house
        self.monsters = []

        # Populates the homes with random monsters
        for i in range(randint(0, 10)):
            randNum = randint(1, 5)
            if (randNum == 1):
                currMonster = Persons()
            elif (randNum == 2):
                currMonster = Zombies()
            elif (randNum == 3):
                currMonster = Ghouls()
            elif (randNum == 4):
                currMonster = Vampires()
            elif (randNum == 5):
                currMonster = Werewolves()

            # Has house observe each monster
            currMonster.add_observer(self)
            self.monsters.append(currMonster)
Ejemplo n.º 19
0
 def kill(self):
     if self.__strategy is not None:
         self.__is_dead = self.__strategy.kill(self)
     else:
         raise Exception(
             'Please choice strategy for kill in set_strategy_kill method')
     Observable.notify(self, 'kill')
Ejemplo n.º 20
0
    def __init__(self,
                 client,
                 key='',
                 secret='',
                 server='',
                 name='',
                 version='',
                 redirect_uri='',
                 known_prefixes=None):

        Observable.__init__(self)

        self._server = server
        self._key = key
        self._name = name if name else 'Unnamed'
        self._version = version if version else '0.0.0'
        self._redirect_uri = redirect_uri
        self._secret = secret
        self._client = client
        self._auth = Auth()
        self._account = ACCOUNT_ID
        self._known_prefixes = known_prefixes if known_prefixes else KNOWN_PREFIXES
        self._userAgent = ((self._name + ('/' + self._version if self._version else '') + ' ') if self._name else '') + \
                          sys.platform + '/VERSION' + ' ' + \
                          'PYTHON/VERSION ' + \
                          'RCPYTHONSDK/VERSION'
Ejemplo n.º 21
0
    def __init__(self, tableau_adresse, options, fichier_sortie):
        Thread.__init__(self)
        Observable.__init__(self)
        self.adresse = ''
        self.progress = 0.0
        self.status = 'ready'

        #On cree un string a partir de la liste des adresses
        #contenues dans le tableau
        for ip in tableau_adresse:
            try:
                ip = valideIP(ip)
                self.adresse += ' ' + str(ip)
            except:
                pass

        liste_arguments = [options, fichier_sortie]

        #Contrôle des arguments
        for arg in liste_arguments:
            error = re.search('[;|<>"`&{}]', str(arg))

            if error != None:
                raise Exception("Paramètres Nmap invalide")

        #Si pas de levé d'exception
        self.options = options
        self.fichier_sortie = fichier_sortie
Ejemplo n.º 22
0
class QuackCounter(Quackable):

    number_of_quacks = 0

    def __init__(self, quackable):
        self._quackable = quackable
        self._observable = Observable(self)

    def __repr__(self):
        return repr(self._quackable)

    def quack(self):
        self._quackable.quack()
        QuackCounter.number_of_quacks += 1
        self.notify_observers()

    def register_observer(self, observer):
        self._observable.register_observer(observer)

    def notify_observers(self):
        self._observable.notify_observers()

    @classmethod
    def get_quacks(cls):
        return cls.number_of_quacks
Ejemplo n.º 23
0
 def __init__(self):
     self.Name = Observable(None)
     self.FullPath = Observable(None)
     self.Magic = Observable(None)
     self.Format = Observable(None)
     self.Directory = Observable(None)
     self.Magic.addCallback(self,self.OnMagic)
Ejemplo n.º 24
0
 def __init__(self, config):
     self._config = config
     self._mame = None
     self._connection = None
     self._running = False
     Observable.__init__(self)
     threading.Thread.__init__(self)
Ejemplo n.º 25
0
	def __init__(self, network_interface, src_ip, target_ip):
		Observable.__init__(self)
		Executable.__init__(self, self.ping_executable)
		self.network_interface = network_interface
		self.src_ip = src_ip
		self.target_ip = target_ip
		print "# Setting up loop for pinging " + target_ip + " (with " + src_ip + " on " + network_interface + ") "
Ejemplo n.º 26
0
    def __init__(self, trigger, func, args, kwargs, misfire_grace_time,
                 coalesce, name=None, max_runs=None, max_instances=1, active=True):
        Observable.__init__(self)
        if not trigger:
            raise ValueError('The trigger must not be None')
        if not hasattr(func, '__call__'):
            raise TypeError('func must be callable')
        if not hasattr(args, '__getitem__'):
            raise TypeError('args must be a list-like object')
        if not hasattr(kwargs, '__getitem__'):
            raise TypeError('kwargs must be a dict-like object')
        if misfire_grace_time <= 0:
            raise ValueError('misfire_grace_time must be a positive value')
        if max_runs is not None and max_runs <= 0:
            raise ValueError('max_runs must be a positive value')
        if max_instances <= 0:
            raise ValueError('max_instances must be a positive value')


        self._lock = Lock()
        self.trigger = trigger
        self.func = func
        self.args = args
        self.kwargs = kwargs
        self.name = to_unicode(name or get_callable_name(func))
        self.misfire_grace_time = misfire_grace_time
        self.coalesce = coalesce
        self.max_runs = max_runs
        self.max_instances = max_instances
        self.runs = 0
        self.instances = 0
        self.active = active
Ejemplo n.º 27
0
class Conductor:
    def __init__(self):
        self.bpm = 90
        self.q = 1 / self.bpm * 60
        self.started = False
        self.lock = Lock()
        self.obs = Observable()
        self.interval = 0
        self.base_note = 0
        self.last_note = 0
        self.arpeggio_speed = 1
        self.arpeggio_length = 0
        self.arpeggio_step = 0
        self.arpeggio_repeat = True
        self.lastTick = time.time()

    def __start(self):
        if self.started:
            print("already started")
            return None
        self.started = True
        self.thread = Thread(target=self.update, args=())
        self.thread.start()
        return self

    def stop(self):
        # self.started = False
        self.thread.join()

    def update(self):
        while self.started:
            if self.arpeggio_length == 0:
                time.sleep(1)
                continue
            if time.time() - self.lastTick > self.q * self.arpeggio_speed:
                self.lastTick = time.time()
                # Go to the next arpeggio
                self.last_note += self.interval * 4
                self.arpeggio_step += 1
                if self.arpeggio_step > self.arpeggio_length:
                    self.last_note = self.base_note
                    if self.arpeggio_repeat:
                        self.arpeggio_step = 0
                    else:
                        continue
                self.obs.trigger('note', self.last_note)

    def play(self, tone):
        if not self.started:
            self.__start()
        self.lastTick = time.time()
        self.base_note = tone
        self.last_note = tone
        self.arpeggio_step = 0
        self.obs.trigger('note', self.last_note)

    def set_bpm(self, bpm):
        self.bpm = bpm
        self.q = 1 / self.bpm * 60
Ejemplo n.º 28
0
def test_no_event_for_trigger():
    """test exception raising for not existing events"""
    obs = Observable()

    assert not obs.trigger("no_existing_event")

    with pytest.raises(EventNotFound):
        obs.off("no_existing_event")
    def __init__(self, *args, **kwargs):
        self._children = []
        self.synchronize_on_event = {}

        Observable.__init__(self, *args, **kwargs)

        self.add_observer("any", self._replicate_event)
        self.synchronize_on_all_events()
Ejemplo n.º 30
0
 def __init__(self):
     SaveableType.__init__(self)
     Observable.__init__(self)
     self.values = []
     self.signal_add = Signal()
     self.signal_remove = Signal()
     self.array_type = array_type
     self.signal_changed = Signal()
Ejemplo n.º 31
0
def test_no_event_for_trigger():
    """test exception raising for not existing events"""
    obs = Observable()

    assert not obs.trigger("no_existing_event")

    with pytest.raises(EventNotFound):
        obs.off("no_existing_event")
Ejemplo n.º 32
0
 def refresh_play_status(self):
     logger.debug("refresh_playing_status")
     try:
         status = self.get_status()
         if 'state' in status:
             self.play_status = status['state']
         Observable.notify_toggle_observers(self, {'status': self.play_status})
     except mpd.ConnectionError:
         logger.error('Lost connection on get get_playing_status')
Ejemplo n.º 33
0
def test_trigger_arg():
    """test event triggering with arguments"""
    obs = Observable()

    @obs.on("some_test")
    def some_test(some_data):
        assert some_data == "some data"

    assert obs.trigger("some_test", "some data")
Ejemplo n.º 34
0
def test_trigger_arg():
    """test event triggering with arguments"""
    obs = Observable()

    @obs.on("some_test")
    def some_test(some_data):
        assert some_data == "some data"

    assert obs.trigger("some_test", "some data")
Ejemplo n.º 35
0
def test_on():
    """test event registering with the on method"""
    obs = Observable()

    def on_test():
        pass

    obs.on("on_test", on_test)
    assert on_test in obs._events["on_test"]
Ejemplo n.º 36
0
def test_on():
    """test event registering with the on method"""
    obs = Observable()

    def on_test():
        pass

    obs.on("on_test", on_test)
    assert on_test in obs._events["on_test"]
Ejemplo n.º 37
0
def test_on():
    """test event registering with the on method"""
    obs = Observable()
    nose.assert_false(obs.events)

    def on_test():
        pass

    obs.on("on_test", on_test)
    nose.assert_in(on_test, obs.events["on_test"])
Ejemplo n.º 38
0
 def __setattr__(self, attr, value):
     if attr in [
             "position", "label", "shape", "size", "color", "filled",
             "comment"
     ]:
         old_value = getattr(self, attr, None)
         object.__setattr__(self, attr, value)
         self.notify_observers(attr, old_value=old_value)
     else:
         Observable.__setattr__(self, attr, value)
Ejemplo n.º 39
0
def test_is_registered():
    """test is_registered() after registering an event"""
    obs = Observable()

    def some_test():
        pass

    assert not obs.is_registered("some_event", some_test)
    obs.on("some_event", some_test)
    assert obs.is_registered("some_event", some_test)
Ejemplo n.º 40
0
def test_trigger_kwargs():
    """test event triggering with keyword-arguments"""
    obs = Observable()

    @obs.on("some_test")
    def some_test(some_data=True, some_other_data=False):
        assert some_data is False
        assert some_other_data is True

    assert obs.trigger("some_test", some_other_data=True, some_data=False)
Ejemplo n.º 41
0
def test_trigger_args():
    """test event triggering with argument list"""
    obs = Observable()

    @obs.on("some_test")
    def some_test(some_data, some_other_data):
        assert some_data is True
        assert some_other_data is False

    assert obs.trigger("some_test", *[True, False])
Ejemplo n.º 42
0
def test_trigger_args():
    """test event triggering with argument list"""
    obs = Observable()

    @obs.on("some_test")
    def some_test(some_data, some_other_data):
        assert some_data is True
        assert some_other_data is False

    assert obs.trigger("some_test", *[True, False])
Ejemplo n.º 43
0
def test_trigger_arg():
    """test event triggering with arguments"""
    obs = Observable()
    nose.assert_false(obs.events)

    @obs.on("some_test")
    def some_test(some_data):
        nose.assert_equals(some_data, "some data")

    nose.assert_true(obs.trigger("some_test", "some data"))
Ejemplo n.º 44
0
def test_trigger_kwargs():
    """test event triggering with keyword-arguments"""
    obs = Observable()

    @obs.on("some_test")
    def some_test(some_data=True, some_other_data=False):
        assert some_data is False
        assert some_other_data is True

    assert obs.trigger("some_test", some_other_data=True, some_data=False)
Ejemplo n.º 45
0
def test_once_decorator():
    """test event registering with the once decorator"""
    obs = Observable()

    @obs.once("once_test")
    def once_test():
        pass

    assert once_test in obs._events["once_test"]
    assert obs.trigger("once_test")
    assert once_test not in obs._events["once_test"]
Ejemplo n.º 46
0
def test_trigger_args():
    """test event triggering with argument list"""
    obs = Observable()
    nose.assert_false(obs.events)

    @obs.on("some_test")
    def some_test(some_data, some_other_data):
        nose.assert_true(some_data)
        nose.assert_false(some_other_data)

    nose.assert_true(obs.trigger("some_test", *[True, False]))
Ejemplo n.º 47
0
def test_trigger_kwargs():
    """test event triggering with keyword-arguments"""
    obs = Observable()
    nose.assert_false(obs.events)

    @obs.on("some_test")
    def some_test(some_data=True, some_other_data=False):
        nose.assert_false(some_data)
        nose.assert_true(some_other_data)

    nose.assert_true(obs.trigger("some_test", some_other_data=True, some_data=False))
Ejemplo n.º 48
0
 def __init__(self):
     Observable.__init__(self)
     self.level = 0
     self.isPaused = True
     self.id = None
     self.currClip = None
     self.currClipIndex = None
     self.name = None
     self.md5 = None
     self.dDBook = None
     self.msg = "Welcome to Daisy Delight"
Ejemplo n.º 49
0
def test_once_decorator():
    """test event registering with the once decorator"""
    obs = Observable()

    @obs.once("once_test")
    def once_test():
        pass

    assert once_test in obs._events["once_test"]
    assert obs.trigger("once_test")
    assert once_test not in obs._events["once_test"]
Ejemplo n.º 50
0
 def __init__(self,connection,transparent):
     Observable.__init__(self)
     self.connection = connection
     self.transparent = transparent
     connection.addListeners(self)
     self.datas = HostsInfos()
     self.nas= Nas(connection, transparent, self.datas)
     self.L2=LearningSwitch(connection, transparent)
     self.add_observer(self.nas,'nac')
     self.dhcp_interceptor = DhcpIntercept(connection, transparent, self.datas)
     self.add_observer(self.dhcp_interceptor,'dhcp')
Ejemplo n.º 51
0
    def __init__(self, users):
        self.users = users  # Socket assigned to user object

        file = open("config/rooms.json", "r")
        self.rooms = json.loads(file.read())

        self.packet = PacketManager(self.rooms)
        self.obs = Observable()
        self.plugins = PluginManager(self)

        self.POLICY = "<cross-domain-policy><allow-access-from domain='*' to-ports='*' /></cross-domain-policy>"
Ejemplo n.º 52
0
def test_once():
    """test event registering with the once method"""
    obs = Observable()

    def once_test():
        pass

    obs.once("once_test", once_test)

    assert len(obs._events["once_test"]) == 1
    assert obs.trigger("once_test")
    assert obs._events["once_test"] == []
Ejemplo n.º 53
0
def test_once_decorator():
    """test event registering with the once decorator"""
    obs = Observable()
    nose.assert_false(obs.events)

    @obs.once("once_test")
    def once_test():
        pass

    nose.assert_in(once_test, obs.events["once_test"])
    nose.assert_true(obs.trigger("once_test"))
    nose.assert_not_in(once_test, obs.events["once_test"])
Ejemplo n.º 54
0
def test_once():
    """test event registering with the once method"""
    obs = Observable()

    def once_test():
        pass

    obs.once("once_test", once_test)

    assert len(obs._events["once_test"]) == 1
    assert obs.trigger("once_test")
    assert obs._events["once_test"] == []
Ejemplo n.º 55
0
def test_on_trigger():
    """test event triggering with event registered with on"""
    obs = Observable()
    nose.assert_equals(obs._events, {})

    @obs.on("on_test")
    def on_test():
        pass

    nose.assert_equals(obs._events, {"on_test": [on_test]})
    nose.assert_true(obs.trigger("on_test"))
    nose.assert_true(obs.trigger("on_test"))