Ejemplo n.º 1
0
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        machine_args = {
            arg: getattr(self.StateMachine, arg)
            for arg in dir(self.StateMachine) if not arg.startswith("_")
        }

        transitions = [
            self.find_additional_args_for_transitions(trans_kwargs)
            for trans_kwargs in machine_args["transitions"]
        ]
        machine_args.update({
            "transitions": transitions,
            "model": self,
            "initial": self.state
        })
        self.machine = Machine(**machine_args)
Ejemplo n.º 2
0
 def _init_states(self):
     self.transitions = Machine(states=Session.states, initial='new')
     self.transitions.add_transition(trigger='connect',
                                     source='new',
                                     dest='connected')
     self.transitions.add_transition(trigger='connect',
                                     source='disconnected',
                                     dest='connected')
     self.transitions.add_transition(trigger='disconnect',
                                     source='connected',
                                     dest='disconnected')
     self.transitions.add_transition(trigger='disconnect',
                                     source='new',
                                     dest='disconnected')
     self.transitions.add_transition(trigger='disconnect',
                                     source='disconnected',
                                     dest='disconnected')
Ejemplo n.º 3
0
 def test_send_event_data_conditions(self):
     states = ['A', 'B', 'C', 'D']
     s = Stuff()
     # First pass positional and keyword args directly to the condition
     m = Machine(model=s, states=states, initial='A', send_event=False)
     m.add_transition(
         trigger='advance', source='A', dest='B',
         conditions='this_fails_by_default')
     s.advance(boolean=True)
     self.assertEqual(s.state, 'B')
     # Now wrap arguments in an EventData instance
     m.send_event = True
     m.add_transition(
         trigger='advance', source='B', dest='C',
         conditions='extract_boolean')
     s.advance(boolean=False)
     self.assertEqual(s.state, 'B')
Ejemplo n.º 4
0
 def __init__(self, map_graph, node_descriptors):
     self.machine = Machine(
         model=self,
         states=[str(this_node['id']) for this_node in map_graph['nodes']],
         transitions=map_graph['transitions'],
         ignore_invalid_triggers=True,
         initial=map_graph['initial'])
     """
     Nodes is a list of dicts 
         {'base_type': 'indoor', 
          'type': 'v/veranda', 
          'target': False, 
          'instance': 'v/veranda/ADE_train_00019501.jpg', 
          'id': (2, 1)}
     """
     self.nodes = map_graph['nodes']
     self.node_descriptors = node_descriptors
Ejemplo n.º 5
0
    def __init__(
        self,
        symbol: str,
        hold_short_a: float = -0.5,
        hold_short_b: float = -0.8,
        hold_short_c: float = -1.0,
    ):
        """持仓对象

        :param symbol: 标的代码
        :param hold_short_a: 首次开空仓后的仓位
        :param hold_short_b: 第一次加空后的仓位
        :param hold_short_c: 第二次加空后的仓位
        """
        assert 0 >= hold_short_a >= hold_short_b >= hold_short_c >= -1.0

        self.symbol = symbol
        self.pos_map = {
            "hold_money": 0,
            "hold_short_a": hold_short_a,
            "hold_short_b": hold_short_b,
            "hold_short_c": hold_short_c
        }
        self.states = list(self.pos_map.keys())
        self.machine = Machine(model=self,
                               states=self.states,
                               initial='hold_money')

        self.machine.add_transition('short_open', 'hold_money', 'hold_short_a')
        self.machine.add_transition('short_add1', 'hold_short_a',
                                    'hold_short_b')
        self.machine.add_transition('short_add2', 'hold_short_b',
                                    'hold_short_c')
        self.machine.add_transition('short_reduce1', 'hold_short_c',
                                    'hold_short_b')
        self.machine.add_transition('short_reduce2',
                                    ['hold_short_b', 'hold_short_c'],
                                    'hold_short_a')
        self.machine.add_transition(
            'short_exit', ['hold_short_a', 'hold_short_b', 'hold_short_c'],
            'hold_money')

        self.operates = []
        self.short_low = -1  # 持空仓期间出现的最低价
        self.short_cost = -1  # 最近一次加空仓的成本
        self.short_bid = -1  # 最近一次加空仓的1分钟Bar ID
Ejemplo n.º 6
0
 def __init__(self):
     self.states = [
         'waiting4start', 'pullingBack', 'slackening', 'launching'
     ]
     self.transitions = [
         {
             'trigger': 'startOver',
             'source': '*',
             'dest': 'waiting4start',
             'after': 'do_waiting4start'
         },
         {
             'trigger': 'beginPull',
             'source': 'waiting4start',
             'dest': 'pullingBack',
             'after': 'do_pullingBack',
             'conditions': 'olfactometer_says_go'
         },
         {
             'trigger': 'slacken',
             'source': 'pullingBack',
             'dest': 'slackening',
             'after': 'do_slackening',
             'conditions': 'not_struggling_anymore'
         },
         {
             'trigger': 'catchorlaunch',
             'source': 'slackening',
             'dest': 'pullingBack',
             'after': 'do_pullingBack',
             'conditions': 'animal_escaped'
         },
         {
             'trigger': 'catchorlaunch',
             'source': 'slackening',
             'dest': 'launching',
             'after': 'do_launching',
             'conditions': 'ok_to_launch'
         },
     ]
     Machine(model=self,
             states=self.states,
             transitions=self.transitions,
             initial='waiting4start')
     self.startOver()
Ejemplo n.º 7
0
    def __init__(self, name):

        self.name = name
        self.machine = Machine(model=self,
                               states=Haley.states,
                               initial='init',
                               auto_transitions=False)

        self.machine.add_transition(trigger='startSetup',
                                    source='init',
                                    dest='setup')

        self.machine.add_transition(trigger='setupComplete',
                                    source='setup',
                                    dest='ready')

        self.machine.add_transition(trigger='startPressed',
                                    source='ready',
                                    dest='waitForGreen')

        self.machine.add_transition(trigger='greenlight',
                                    source='waitForGreen',
                                    dest='blindDrive')

        self.machine.add_transition(trigger='wallsDedected',
                                    source='blindDrive',
                                    dest='guidedDrive')

        self.machine.add_transition(trigger='wallsLost',
                                    source='guidedDrive',
                                    dest='turning',
                                    unless='hasTurned')

        self.machine.add_transition(trigger='wallsLost',
                                    source='guidedDrive',
                                    dest='buttonDrive',
                                    conditions='hasTurned')

        self.machine.add_transition(trigger='turnDone',
                                    source='turning',
                                    dest='blindDrive')

        self.machine.add_transition(trigger='buttonPressed',
                                    source='buttonDrive',
                                    dest='end')
Ejemplo n.º 8
0
    def __init__(self, timer):
        super().__init__()
        self.timer = timer

        self.prev_state = None
        self.machine = Machine(
            model=self, states=TimerStateMachine.states,
            initial='stopped', name='TimerFSM',
            after_state_change='on_after_state_change')
        self.machine.add_transition(
            trigger='on_stop', source='*', dest='stopped',
            before='save_prev_state')

        self.machine.add_transition(
            trigger='on_pause', source=['running', 'alarmed'],
            dest='paused', before='save_prev_state')

        self.machine.add_transition(
            trigger='on_overflow',
            source=['running', 'alarmed'],
            dest='overflowed', before='save_prev_state')

        self.machine.add_transition(
            trigger='on_alarm', source='running',
            dest='alarmed',
            before='save_prev_state')

        self.machine.add_transition(
            trigger='on_start', source='alarmed',
            dest='running', conditions='is_cycling',
            before='save_prev_state')

        self.machine.add_transition(
            trigger='on_start', source='paused',
            dest='alarmed', conditions='prev_is_alarmed',
            before='save_prev_state')

        self.machine.add_transition(
            trigger='on_start', source='paused',
            dest='running', conditions='prev_is_running',
            before='save_prev_state')

        self.machine.add_transition(
            trigger='on_start', source='stopped', dest='running',
            before='save_prev_state')
Ejemplo n.º 9
0
    def __init__(self, sic: BasicSICConnector):
        self.sic = sic
        self.action_runner = ActionRunner(self.sic)
        self.machine = Machine(model=self,
                               states=ExampleRobot.states,
                               initial='asleep')

        self.user_model = {}
        self.recognition_manager = {
            'attempt_success': False,
            'attempt_number': 0
        }

        # Define transitions
        self.machine.add_transition(trigger='start',
                                    source='asleep',
                                    dest='awake',
                                    before='wake_up',
                                    after='introduce')
        self.machine.add_transition(trigger='introduce',
                                    source='awake',
                                    dest='introduced',
                                    before='introduction',
                                    after='get_name')
        self.machine.add_transition(trigger='get_name',
                                    source='introduced',
                                    dest='asked_name',
                                    before='ask_name',
                                    after='get_acquainted')
        self.machine.add_transition(trigger='get_acquainted',
                                    source='asked_name',
                                    dest='got_acquainted',
                                    conditions='has_name',
                                    before='get_acquainted_with',
                                    after='rest')
        self.machine.add_transition(trigger='get_acquainted',
                                    source='asked_name',
                                    dest='got_acquainted',
                                    unless='has_name',
                                    before='get_acquainted_without',
                                    after='rest')
        self.machine.add_transition(trigger='rest',
                                    source='*',
                                    dest='asleep',
                                    before='saying_goodbye')
Ejemplo n.º 10
0
    def __init__(
        self,
        clock: Clock,
        transitions: List[List[object]],
        states: List[Enum],
        initial_state: Enum,
        object_id: str = None,
    ):
        """

        Parameters
        ----------

        clock : Clock
            Simulated clock

        transitions : list
            List of state transitions, e.g. "idling" to "moving_to"

        states : List[Enum]
            List of state names, e.g. "idling", "moving_to"

        initial_state : Enum
            Initial state

        object_id : str
            A unique id of an object
            
        """
        self.id = object_id
        if self.id is None:
            self.id = uuid4().hex
        self.clock = clock
        self.created_at = clock.now

        self._state_machine = Machine(
            model=self,
            states=states,
            transitions=transitions,
            initial=initial_state,
            send_event=True,
            after_state_change="on_state_changed",
        )

        self.logger = get_simobility_logger()
Ejemplo n.º 11
0
 def __init__(self, name):
     # No anonymous superheroes on my watch! Every narcoleptic superhero gets
     # a name. Any name at all. SleepyMan. SlumberGirl. You get the idea.
     self.name = name
     # What have we accomplished today?
     self.kittens_rescued = 0
     # Initialize the state machine
     self.machine = Machine(model=self,
                            states=NarcolepticSuperhero.states,
                            initial='asleep',
                            send_event=True)
     # Add some transitions. We could also define these using a static list of
     # dictionaries, as we did with states above, and then pass the list to
     # the Machine initializer as the transitions= argument.
     # At some point, every superhero must rise and shine.
     self.machine.add_transition(trigger='wake_up',
                                 source='asleep',
                                 dest='hanging out',
                                 after="waked")
     # Superheroes need to keep in shape.
     self.machine.add_transition('work_out', 'hanging out', 'hungry')
     # Those calories won't replenish themselves!
     self.machine.add_transition('eat', 'hungry', 'hanging out')
     # Superheroes are always on call. ALWAYS. But they're not always
     # dressed in work-appropriate clothing.
     self.machine.add_transition('distress_call',
                                 '*',
                                 'saving the world',
                                 before='change_into_super_secret_costume')
     # When they get off work, they're all sweaty and disgusting. But before
     # they do anything else, they have to meticulously log their latest
     # escapades. Because the legal department says so.
     self.machine.add_transition('complete_mission',
                                 'saving the world',
                                 'sweaty',
                                 after='update_journal')
     # Sweat is a disorder that can be remedied with water.
     # Unless you've had a particularly long day, in which case... bed time!
     self.machine.add_transition('clean_up',
                                 'sweaty',
                                 'asleep',
                                 conditions=['is_exhausted'])
     self.machine.add_transition('clean_up', 'sweaty', 'hanging out')
     # Our NarcolepticSuperhero can fall asleep at pretty much any time.
     self.machine.add_transition('nap', '*', 'asleep')
Ejemplo n.º 12
0
    def __init__(self):
        super(FSMDST, self).__init__()
        self.dialogue_state = default_state()
        self.dialogue_state["cur_domain"] = "餐馆"
        self.restaurant_states = list(
            self.dialogue_state["belief_state"]["餐馆"].keys())
        self.restaurant_states.append("Request")
        self.machine = Machine(model=self,
                               states=self.restaurant_states,
                               initial="greet")

        self.dest2trigger = {
            "推荐菜": {
                "trigger": "inform_restaurant_dish",
                "callback": "set_recommend_dish",
            },
            "评分": {
                "trigger": "inform_restaurant_rating",
                "callback": "set_rating"
            },
            "人均消费": {
                "trigger": "inform_restaurant_avg_cost",
                "callback": "set_avg_cost",
            },
            "周边酒店": {
                "trigger": "inform_restaurant_surrounding_hotel",
                "callback": "set_surrounding_hotel",
            },
            "周边景点": {
                "trigger": "inform_restaurant_surrounding_attraction",
                "callback": "set_surrounding_attraction",
            },
            "周边餐馆": {
                "trigger": "inform_restaurant_surrounding_restaurant",
                "callback": "set_surrounding_restaurant",
            },
        }

        for slot, trigger in self.dest2trigger.items():
            self.machine.add_transition(
                trigger=trigger["trigger"],
                source="*",
                dest=slot,
                before=trigger["callback"],
            )
Ejemplo n.º 13
0
    def __init__(self, terrain_data: TerrainData) -> None:
        self.machine = Machine(model=self,
                               states=Player.states,
                               initial='idle')
        self.machine.add_transition(trigger='walk',
                                    source='idle',
                                    dest='walking',
                                    after='on_start_walk')
        self.machine.add_transition(trigger='stop',
                                    source='walking',
                                    dest='idle',
                                    after='on_stop')

        position = Vector2(terrain_data.start_x, terrain_data.start_y)
        self.transform = Transform(position, Direction.DOWN)
        self.terrain_data = terrain_data
        self.char_ctrl = CharacterController(terrain_data, self.transform)
        self.animator = PlayerAnimator(self.state, self.transform.direction)
Ejemplo n.º 14
0
    def __check_machine(self, filename):
        """"""

        # multi-state-machine for one machine
        if filename in self.data_files:
            mts = self.data_files[filename]
        else:
            mts = MtsStateMachine(self.config)
            self.data_files[filename] = mts
            #mts = MTSState()
            # Initialize
            machine = Machine(mts,
                              states=mts.states,
                              send_event=True,
                              transitions=mts.transitions,
                              initial='init')

        return mts
Ejemplo n.º 15
0
    def test_machine_finalize_exception(self):

        exception = ZeroDivisionError()

        def always_raises(event):
            raise exception

        def finalize_callback(event):
            self.assertEqual(event.error, exception)

        m = Machine(states=['A', 'B'],
                    send_event=True,
                    initial='A',
                    before_state_change=always_raises,
                    finalize_event=finalize_callback)

        with self.assertRaises(ZeroDivisionError):
            m.to_B()
Ejemplo n.º 16
0
    def __init__(self, head, listener):
        self.machine = Machine(model=self,
                               states=PenteFSM.states,
                               transitions=PenteFSM.transitions,
                               initial='startup',
                               auto_transitions=True)
        self.command = self.nullCmd
        self.head = head

        last_seen = listener.getLatestCommonTime('handoff_point', 'base')
        self.originPoint = listener.getTransform('handoff_point', 'base',
                                                 last_seen)
        last_seen = listener.getLatestCommonTime(
            'dropoff_point',
            'base',
        )
        self.dropoffPoint = listener.getTransform('dropoff_point', 'base',
                                                  last_seen)
Ejemplo n.º 17
0
 def __init__(self,
              board: Board = None,
              verbose: bool = True,
              buffer: bool = True):
     # an agent maintains an up-to-date board,
     # the current state of the agent,
     # and the current turn.
     self.board: Board = Board() if not board else board
     self.machine = Machine(model=self,
                            states=AgentState,
                            transitions=Agent.TRANSITIONS,
                            initial=AgentState.INIT)
     self.side: Optional[Side] = None
     self.action: Optional[Action] = None
     self.verbose: bool = verbose
     self.buffer: bool = buffer
     self.action_buffer: List[Action] = list()
     self.reward_buffer: List[float] = list()
    def __init__(self, name):
        self.name = name
        self.node_situation = NodeSituation()
        self.machine = Machine(
            model=self,
            states=TaskSituationType,
            initial=TaskSituationType.Initial,
            after_state_change=self.change_node_situation_type,
        )

        self._current_cycle = {
            StatusChangeType.Submit: None,
            StatusChangeType.Initial: None,
            StatusChangeType.Complete: None,
            StatusChangeType.Abort: None,
        }

        self._initial_transitions()
Ejemplo n.º 19
0
    def test_ordered_transition_callback(self):
        class Model:
            def __init__(self):
                self.flag = False

            def make_true(self):
                self.flag = True

        model = Model()
        states = ['beginning', 'middle', 'end']
        transits = [None, None, 'make_true']
        m = Machine(model, states, initial='beginning')
        m.add_ordered_transitions(before=transits)
        model.next_state()
        self.assertFalse(model.flag)
        model.next_state()
        model.next_state()
        self.assertTrue(model.flag)
Ejemplo n.º 20
0
    def __init__(self, name='miner', capacity=5, qty=0):

        self.name = name
        self.capacity = capacity
        self.qty = qty
        self.count = 0
        self.runningTransitions = False

        self.machine = Machine(model=self,
                               states=Miner.states,
                               transitions=Miner.transitions,
                               initial=Miner.initial,
                               auto_transitions=False)

        for state in Miner.states:
            on_exit = getattr(self.machine, 'on_exit_' + state)
            on_exit('stopRunningTransitions')
            print('stopRunningTransitions() added to', state)
Ejemplo n.º 21
0
    def __init__(self, config_path, **kwargs):
        super(MarketServiceAgent, self).__init__(**kwargs)

        config = utils.load_config(config_path)
        self.agent_name = config.get('agent_name', 'MixMarketService')
        self.market_period = int(config.get('market_period', 300))
        self.reservation_delay = int(config.get('reservation_delay', 0))
        self.offer_delay = int(config.get('offer_delay', 120))
        self.verbose_logging = int(config.get('verbose_logging', True))
        self.director = None
        # This can be periodic or event_driven
        self.market_type = config.get("market_type", "event_driven")
        if self.market_type not in ["periodic", "event_driven"]:
            self.market_type = "event_driven"

        self.state_machine = Machine(model=self, states=MarketServiceAgent.states,
                                     transitions= MarketServiceAgent.transitions, initial=INITIAL_WAIT)
        self.market_list = MarketList(self.vip.pubsub.publish, self.verbose_logging)
Ejemplo n.º 22
0
    def test_dynamic_model_state_attribute(self):
        class Model:
            def __init__(self):
                self.status = None
                self.state = 'some_value'

        m = Machine(Model(),
                    states=['A', 'B'],
                    initial='A',
                    model_attribute='status')
        self.assertEqual(m.model.status, 'A')
        self.assertEqual(m.model.state, 'some_value')

        m.add_transition('move', 'A', 'B')
        m.model.move()

        self.assertEqual(m.model.status, 'B')
        self.assertEqual(m.model.state, 'some_value')
Ejemplo n.º 23
0
    def test_state_and_transition_with_underscore(self):
        m = Machine(Stuff(), states=['_A_', '_B_', '_C_'], initial='_A_')
        m.add_transition('_move_', '_A_', '_B_', prepare='increase_level')
        m.add_transition('_after_', '_B_', '_C_', prepare='increase_level')
        m.add_transition('_on_exit_', '_C_', '_A_', prepare='increase_level', conditions='this_fails')

        m.model._move_()
        self.assertEquals(m.model.state, '_B_')
        self.assertEquals(m.model.level, 2)

        m.model._after_()
        self.assertEquals(m.model.state, '_C_')
        self.assertEquals(m.model.level, 3)

        # State does not advance, but increase_level still runs
        m.model._on_exit_()
        self.assertEquals(m.model.state, '_C_')
        self.assertEquals(m.model.level, 4)
Ejemplo n.º 24
0
    def test_string_trigger(self):
        def return_value(value):
            return value

        class Model:
            def trigger(self, value):
                return value

        self.stuff.machine.add_transition('do', '*', 'C')
        self.stuff.trigger('do')
        self.assertTrue(self.stuff.is_C())
        self.stuff.machine.add_transition('maybe',
                                          'C',
                                          'A',
                                          conditions=return_value)
        self.assertFalse(self.stuff.trigger('maybe', value=False))
        self.assertTrue(self.stuff.trigger('maybe', value=True))
        self.assertTrue(self.stuff.is_A())
        with self.assertRaises(AttributeError):
            self.stuff.trigger('not_available')
        with self.assertRaises(MachineError):
            self.stuff.trigger('maybe')

        model = Model()
        m = Machine(model=model)
        self.assertEqual(model.trigger(5), 5)

        def raise_key_error():
            raise KeyError

        self.stuff.machine.add_transition('do_raise_keyerror',
                                          '*',
                                          'C',
                                          before=raise_key_error)
        with self.assertRaises(KeyError):
            self.stuff.trigger('do_raise_keyerror')

        self.stuff.machine.get_model_state(
            self.stuff).ignore_invalid_triggers = True
        self.stuff.trigger('should_not_raise_anything')
        self.stuff.trigger('to_A')
        self.assertTrue(self.stuff.is_A())
        self.stuff.machine.ignore_invalid_triggers = True
        self.stuff.trigger('should_not_raise_anything')
Ejemplo n.º 25
0
    def __init__(self, api: Api):
        super().__init__()

        # Messenger api instance
        self.api = api

        # Transition machine instance
        self.machine = Machine(
            model=self,
            states=Pizza.states,
            initial='start',
            transitions=Pizza.transitions,
            before_state_change=lambda event: self.logger.info(f'Change state to: \"{event.state.value}\"'),
            send_event=True     # Encapsulate all callback arguments in Event object
        )

        # Simple order info
        self.order = {
            'size': 'большую',      # Default
            'payment': 'наличкой',  # Default
        }

        # Simple pizza sizes validation rules
        self.pizza_size = {
            'большую': r'больш[уюаяой]{2,}',
            'маленькую': r'маленьк[уюаяой]{2,}'
        }

        # Simple payment method validation rules
        self.payment_methods = {
            'наличкой': r'наличк[уаойе]{1,2}',
            'картой': r'карт[ыуаойе]{1,2}'
        }

        # Simple confirmation words validation rules
        self.confirmation_words = {
            'yes': ['Да', 'Подтверждаю', 'Согласен'],
            'no': ['Нет', 'Не', 'Отказываюсь', 'Не согласен']
        }

        # Signal words for intent exit
        self.cancel_words = [
            'Выход', 'Конец', 'Отстань'
        ]
Ejemplo n.º 26
0
    def __init__(self,
                 market_name,
                 participant,
                 publish,
                 verbose_logging=True):
        self.reservations = ReservationManager()
        self.offers = OfferManager()
        self.market_name = market_name
        self.publish = publish
        self.verbose_logging = verbose_logging
        self.price = None

        _log.debug("Initializing Market: {} {} verbose logging is {}.".format(
            self.market_name, participant.buyer_seller, self.verbose_logging))
        self.state_machine = Machine(model=self,
                                     states=Market.states,
                                     transitions=Market.transitions,
                                     initial=ACCEPT_RESERVATIONS)
        self.make_reservation(participant)
Ejemplo n.º 27
0
 def test_init_machine_with_hella_arguments(self):
     states = [
         State('State1'), 'State2', {
             'name': 'State3',
             'on_enter': 'hello_world'
         }
     ]
     transitions = [{
         'trigger': 'advance',
         'source': 'State2',
         'dest': 'State3'
     }]
     s = Stuff()
     m = Machine(model=s,
                 states=states,
                 transitions=transitions,
                 initial='State2')
     s.advance()
     self.assertEqual(s.message, 'Hello World!')
Ejemplo n.º 28
0
 def __init__(self, s):
     # ':' ---> __
     # '=' ---> ___
     self.machine = Machine(model=self,
                            states=Scanner.states,
                            initial='START')
     self.machine.add_transition('digit', 'START', 'INNUM')
     self.machine.add_transition('letter', 'START', 'INID')
     self.machine.add_transition('__', 'START', 'INASSIGN')
     self.machine.add_transition('other', 'START', 'DONE')
     self.machine.add_transition('digit', 'INNUM', 'INNUM')
     self.machine.add_transition('other', 'INNUM', 'DONE')
     self.machine.add_transition('letter', 'INID', 'INID')
     self.machine.add_transition('other', 'INID', 'DONE')
     self.machine.add_transition('___', 'INASSIGN', 'DONE')
     self.machine.add_transition('other', 'INASSIGN', 'DONE')
     self.input_string = s
     self.tokens = {}  # final output dictionary.
     self.previous_state = None  # previous state in state machine.
Ejemplo n.º 29
0
 def test_send_event_data(self):
     states = ['A', 'B', 'C', 'D']
     s = Stuff()
     # First pass positional and keyword args directly to the callback
     m = Machine(model=s, states=states, initial='A', send_event=False)
     m.add_transition(trigger='advance',
                      source='A',
                      dest='B',
                      before='set_message')
     s.advance(message='Hallo. My name is Inigo Montoya.')
     self.assertTrue(s.message.startswith('Hallo.'))
     # Now wrap arguments in an EventData instance
     m.send_event = True
     m.add_transition(trigger='advance',
                      source='B',
                      dest='C',
                      before='extract_message')
     s.advance(message='You killed my father. Prepare to die.')
     self.assertTrue(s.message.startswith('You'))
Ejemplo n.º 30
0
    def test_callback_identification(self):
        m = Machine(Stuff(), states=['A', 'B', 'C', 'D', 'E', 'F'], initial='A')
        m.add_transition('transition', 'A', 'B', before='increase_level')
        m.add_transition('after', 'B', 'C', before='increase_level')
        m.add_transition('on_exit_A', 'C', 'D', before='increase_level', conditions='this_fails')
        m.add_transition('check', 'C', 'E', before='increase_level')
        m.add_transition('prepare', 'E', 'F', before='increase_level')
        m.add_transition('before', 'F', 'A', before='increase_level')

        m.before_transition('increase_level')
        m.before_after('increase_level')
        m.before_on_exit_A('increase_level')
        m.after_check('increase_level')
        m.before_prepare('increase_level')
        m.before_before('increase_level')

        m.model.transition()
        self.assertEquals(m.model.state, 'B')
        self.assertEquals(m.model.level, 3)

        m.model.after()
        self.assertEquals(m.model.state, 'C')
        self.assertEquals(m.model.level, 5)

        m.model.on_exit_A()
        self.assertEquals(m.model.state, 'C')
        self.assertEquals(m.model.level, 5)

        m.model.check()
        self.assertEquals(m.model.state, 'E')
        self.assertEquals(m.model.level, 7)

        m.model.prepare()
        self.assertEquals(m.model.state, 'F')
        self.assertEquals(m.model.level, 9)

        m.model.before()
        self.assertEquals(m.model.state, 'A')
        self.assertEquals(m.model.level, 11)

        # An invalid transition shouldn't execute the callback
        with self.assertRaises(MachineError):
                m.model.on_exit_A()