├── .gitignore ├── LICENSE.txt ├── README.md ├── declarative-fsm.png ├── fsm.py ├── setup.cfg ├── setup.py └── tests.py /.gitignore: -------------------------------------------------------------------------------- 1 | *.py[cod] 2 | 3 | # C extensions 4 | *.so 5 | 6 | # Packages 7 | *.egg 8 | *.egg-info 9 | dist 10 | build 11 | eggs 12 | parts 13 | bin 14 | var 15 | sdist 16 | develop-eggs 17 | .installed.cfg 18 | lib 19 | lib64 20 | __pycache__ 21 | 22 | # Installer logs 23 | pip-log.txt 24 | 25 | # Unit test / coverage reports 26 | .coverage 27 | .tox 28 | nosetests.xml 29 | 30 | # Translations 31 | *.mo 32 | 33 | # Mr Developer 34 | .mr.developer.cfg 35 | .project 36 | .pydevproject 37 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ### Introduction 2 | The purpose of this project is to use the expressive power of the Python language to declaratively implement finite state machines. 3 | 4 | ### Concepts 5 | A few concepts are important to understand in order to properly use this project. As an aid, an image has been provided below to help convey the ideas covered in this section. 6 | 7 | ![Finite State Machine](https://raw.github.com/thomasquintana/declarative-fsm/master/declarative-fsm.png "Finite State Machine") 8 | 9 | **Actions** 10 | An action is executed upon entering or exiting a state. Actions are the mechanism by which a finite state machine (FSM) gets work done. 11 | 12 | **Guards** 13 | A guard constrains transitions by allowing transitions to occur only under specific circumstances. A good example of how guards are useful can be found in the security domain. In this domain a guard can be implemented that only allows a transition to occur if the user has previously authenticated with the system. 14 | 15 | **States** 16 | A state is considered to be the value of all the variables in an FSM at some point in time. All the states of interest as well as the initial state must be declared while initializing the FSM in order for it to build it's internal transition table. 17 | 18 | **Transitions** 19 | A transition is the action of moving an FSM from an initial state to a desired state. All the possible transitions must be declared while initializing the FSM in order to constrain how states are traversed. 20 | 21 | ### Code Example 22 | ```python 23 | class LightSwitch(FiniteStateMachine): 24 | # Initial state. 25 | initial_state = 'off' 26 | 27 | # Possible transitions. 28 | transitions = [ 29 | ('off', 'on'), 30 | ('on', 'off'), 31 | ('off', 'broken'), 32 | ('on', 'broken') 33 | ] 34 | 35 | # Initialize the FSM. 36 | def __init__(self, *args, **kwargs): 37 | super(LightSwitch, self).__init__(*args, **kwargs) 38 | self.electricity = True 39 | 40 | # Handle incoming events. 41 | def on_message(self, message): 42 | if message == 'turn on': 43 | self.transition(to = 'on', event = message) 44 | elif message == 'turn off': 45 | self.transition(to = 'off', event = message) 46 | elif message == 'break': 47 | self.transition(to = 'broken', event = message) 48 | 49 | # Attach a guard to the FSM that protects transitions into 50 | # the on state. The guard is a predicate that returns True 51 | # or False based on the availability of electricity to the 52 | # socket. 53 | @Guard(state = 'on') 54 | def check_electricity(self): 55 | return self.electricity 56 | 57 | # Attach an action to the FSM that will execute anytime 58 | # the off state is entered. 59 | @Action(state = 'off') 60 | def turn_off(self, message): 61 | self.indicator = 'dim' 62 | 63 | # Attach an action to the FSM that will execute anytime 64 | # the on state is entered. 65 | @Action(state = 'on') 66 | def turn_on(self, message): 67 | self.indicator = 'lit' 68 | 69 | # Attach an action to the FSM that will execute anytime 70 | # the broken state is entered. 71 | @Action(state = 'broken') 72 | def smash(self, message): 73 | self.indicator = 'broken' 74 | 75 | # Instantiate an FSM and send it events to process. 76 | light_switch = LightSwitch() 77 | light_switch.on_message('turn on') 78 | light_switch.on_message('turn off') 79 | light_switch.on_message('break') 80 | ``` 81 | -------------------------------------------------------------------------------- /declarative-fsm.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thomasquintana/declarative-fsm/d4f7f1d9cee49ecee4a267a6c7881774e189bd5e/declarative-fsm.png -------------------------------------------------------------------------------- /fsm.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, 12 | # software distributed under the License is distributed on an 13 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | # KIND, either express or implied. See the License for the 15 | # specific language governing permissions and limitations 16 | # under the License. 17 | # 18 | # Thomas Quintana 19 | 20 | ''' 21 | In this module we implement a declarative finite state machine using method decorators. 22 | ''' 23 | __version__ = '0.0.1' 24 | 25 | def is_string(string): 26 | try: 27 | return isinstance(string, basestring) 28 | except NameError: 29 | return isinstance(string, str) 30 | 31 | 32 | class FiniteStateMachineError(Exception): 33 | ''' 34 | A finite state machine exception. 35 | ''' 36 | 37 | def __init__(self, message): 38 | self.message = message 39 | 40 | def __str__(self): 41 | return self.message 42 | 43 | class Action(object): 44 | ''' 45 | The Action decorator adds metadata to methods so they can be used by the finite 46 | state machine as actions that are executed upon entering or exiting a state. 47 | 48 | Arguments: state - The state upon which the action will be executed. 49 | on_enter - If True the action is executed when entering the state. 50 | on_exit - If True the action is executed when exiting the state. 51 | ''' 52 | 53 | def __init__(self, *args, **kwargs): 54 | self.args = args 55 | self.kwargs = kwargs 56 | 57 | def __call__(self, function): 58 | # Append metadata to the function that is necessary 59 | # to build a transition lookup table by the finite 60 | # state machine. 61 | state = self.kwargs.get('state') 62 | if not state \ 63 | or not is_string(state) \ 64 | or len(state) == 0: 65 | raise FiniteStateMachineError('Please specify a valid action \ 66 | state attribute.\n Possible values are strings.') 67 | else: 68 | function.__fsm_action_state__ = state 69 | if 'on_enter' in self.kwargs: 70 | on_enter = self.kwargs.get('on_enter') 71 | if isinstance(on_enter, bool): 72 | function.__fsm_action_on_enter__ = on_enter 73 | else: 74 | raise TypeError('Please specify a valid action on_enter \ 75 | attribute.\n Possible values are True or False.') 76 | else: 77 | function.__fsm_action_on_enter__ = True 78 | if 'on_exit' in self.kwargs: 79 | on_exit = self.kwargs.get('on_exit') 80 | if isinstance(on_exit, bool): 81 | function.__fsm_action_on_exit__ = on_exit 82 | else: 83 | raise TypeError('Please specify a valid action on_exit \ 84 | attribute.\n Possible values are True or False.') 85 | else: 86 | function.__fsm_action_on_exit__ = False 87 | function.__fsm_action__ = True 88 | return function 89 | 90 | class Guard(object): 91 | ''' 92 | The Guard decorator adds metadata to predicate methods so they can be used by 93 | the finite state machine as guards protecting transitions into states. 94 | 95 | Arguments: state - The state upon which the guard will be executed. 96 | ''' 97 | 98 | def __init__(self, *args, **kwargs): 99 | self.args = args 100 | self.kwargs = kwargs 101 | 102 | def __call__(self, function): 103 | # Append metadata to the function that is necessary 104 | # to build a transition lookup table by the finite 105 | # state machine. 106 | state = self.kwargs.get('state') 107 | if not state \ 108 | or not is_string(state) \ 109 | or len(state) == 0: 110 | raise TypeError('Please specify a valid guard state attribute.\n\ 111 | Possible values are strings.') 112 | else: 113 | function.__fsm_guard_state__ = state 114 | function.__fsm_guard__ = True 115 | return function 116 | 117 | class FiniteStateMachine(object): 118 | ''' 119 | A finite state machine. 120 | ''' 121 | def __init__(self, *args, **kwargs): 122 | super(FiniteStateMachine, self).__init__(*args, **kwargs) 123 | self.__fsm_transition_table__ = self.__create_lookup_table__() 124 | self.__state__ = self.initial_state 125 | 126 | def __create_lookup_table__(self): 127 | ''' 128 | Creates a transition lookup table based on the possible transitions. 129 | ''' 130 | actions = self.__get_actions__() 131 | guards = self.__get_guards__() 132 | states = self.__get_states__() 133 | state_map = self.__create_state_map__(actions, guards, states) 134 | # Create the lookup table. 135 | lookup_table = dict() 136 | for begin, end in self.transitions: 137 | transitions = lookup_table.get(begin) 138 | if not transitions: 139 | transitions = dict() 140 | lookup_table.update({ begin: transitions }) 141 | transition = transitions.get(end) 142 | if not transition: 143 | transition = dict() 144 | transitions.update({ end: transition }) 145 | if 'beginning_state' not in transition: 146 | transition.update({ 'beginning_state': state_map.get(begin) }) 147 | if 'end_state' not in transition: 148 | transition.update({ 'end_state': state_map.get(end) }) 149 | return lookup_table 150 | 151 | def __create_state_map__(self, actions, guards, states): 152 | ''' 153 | Creates a map from states to actions and guards. 154 | 155 | Arguments: actions - The actions declared for this finite state machine. 156 | guards - The guards declared for this finite state machine. 157 | state - The possible states for this finite state machine. 158 | ''' 159 | state_map = dict() 160 | # Make sure every state has an entry. 161 | for state in states: 162 | state_map.update({ state: dict() }) 163 | # Attach actions to their states. 164 | for action in actions: 165 | state_name = action.__fsm_action_state__ 166 | if state_name not in states: 167 | raise FiniteStateMachineError('A state named %s is not declared \ 168 | in the transitions list.\n Please add %s to the list of possible \ 169 | transitions or modify the @Action decorator on %s.' % (state_name, 170 | state_name, action.__name__)) 171 | state = state_map.get(state_name) 172 | on_enter = action.__fsm_action_on_enter__ 173 | if 'on_enter' not in state: 174 | if on_enter: 175 | state.update({ 'on_enter': action }) 176 | else: 177 | raise FiniteStateMachineError('The %s state can only have one \ 178 | action declared for on_enter.' % (state_name)) 179 | on_exit = action.__fsm_action_on_exit__ 180 | if 'on_exit' not in state: 181 | if on_exit: 182 | state.update({ 'on_exit': action }) 183 | else: 184 | raise FiniteStateMachineError('The %s state can only have one \ 185 | action declared for on_exit.' % (state_name)) 186 | # Attach guards to their states. 187 | for guard in guards: 188 | state_name = guard.__fsm_guard_state__ 189 | if state_name not in states: 190 | raise FiniteStateMachineError('A state named %s is not declared \ 191 | in the transitions list.\n Please add %s to the list of possible \ 192 | transitions or modify the @Guard decorator on %s.' % (state_name, 193 | state_name, guard.__name__)) 194 | state = state_map.get(state_name) 195 | if 'guard' not in state: 196 | state.update({ 'guard': guard }) 197 | else: 198 | raise FiniteStateMachineError('The %s state can only have one guard \ 199 | declared' % (state_name)) 200 | return state_map 201 | 202 | def __get_actions__(self): 203 | ''' 204 | Returns: All the actions declared for this finite state machine. 205 | ''' 206 | return filter( 207 | lambda callable: hasattr(callable, '__fsm_action__'), 208 | self.__get_callables__() 209 | ) 210 | 211 | def __get_callables__(self): 212 | ''' 213 | Returns: All the methods for this object. 214 | ''' 215 | actions = list() 216 | results = dir(self) 217 | for result in results: 218 | attr = getattr(self, result) 219 | if hasattr(attr, '__call__'): 220 | actions.append(attr) 221 | return actions 222 | 223 | def __get_guards__(self): 224 | ''' 225 | Returns: All the guards declared for this finite state machine. 226 | ''' 227 | return filter( 228 | lambda callable: hasattr(callable, '__fsm_guard__'), 229 | self.__get_callables__() 230 | ) 231 | 232 | def __get_states__(self): 233 | ''' 234 | Returns: The possible states based on the declared transitions. 235 | ''' 236 | # Make sure the user declared a set of possible transitions. 237 | if not self.transitions: 238 | raise FiniteStateMachineError('Please specify a list of possible \ 239 | transitions.\n Each entry in the list is a two-tuple where the \ 240 | first value is the beginning state and the second value is the \ 241 | end state.') 242 | states = list() 243 | for begin, end in self.transitions: 244 | if begin not in states: 245 | states.append(begin) 246 | if end not in states: 247 | states.append(end) 248 | return states 249 | 250 | def state(self): 251 | return self.__state__ 252 | 253 | def transition(self, to = None, event = None): 254 | ''' 255 | Transitions the finite state machine to a new state. 256 | 257 | Arguments: to - The desired end state. 258 | event - The event that caused the state change. 259 | ''' 260 | # Make sure we are in a good state. 261 | transitions = self.__fsm_transition_table__.get(self.__state__) 262 | if not transitions: 263 | raise FiniteStateMachineError('The %s state is invalid, or we \ 264 | have entered a terminal state.' % (self.__state__)) 265 | # Try to find the desired transition. 266 | transition = transitions.get(to) 267 | if not transition: 268 | raise FiniteStateMachineError('The transition from %s to %s is \ 269 | invalid.' % (self.__state__, to)) 270 | # If there are any guards lets execute those now. 271 | if 'guard' in transition.get('end_state'): 272 | allowed = transition.get('end_state').get('guard')() 273 | if not isinstance(allowed, bool): 274 | raise FiniteStateMachineError('A guard must only return True \ 275 | or False values.') 276 | if not allowed: 277 | raise FiniteStateMachineError('A guard declined the transition \ 278 | from %s to %s.' % (self.__state__, to)) 279 | # Try to execute the action associated with leaving the current state. 280 | if 'on_exit'in transition.get('beginning_state'): 281 | transition.get('beginning_state').get('on_exit')(event) 282 | # Try to execute the action associated with entering the new state. 283 | if 'on_enter'in transition.get('end_state'): 284 | transition.get('end_state').get('on_enter')(event) 285 | # Enter the new state and we're done. 286 | self.__state__ = to -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [metadata] 2 | description-file = README.md -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | from setuptools import setup 4 | import fsm 5 | 6 | setup( 7 | name="declarative-fsm", 8 | version=fsm.__version__, 9 | py_modules=["fsm"], 10 | author="Thomas Quintana", 11 | author_email="quintana.thomas@gmail.com", 12 | description='A Python declarative finite state machine.', 13 | license="PROPRIETARY", 14 | url="https://github.com/thomasquintana/declarative-fsm", 15 | ) 16 | -------------------------------------------------------------------------------- /tests.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | 11 | # Unless required by applicable law or agreed to in writing, 12 | # software distributed under the License is distributed on an 13 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | # KIND, either express or implied. See the License for the 15 | # specific language governing permissions and limitations 16 | # under the License. 17 | # 18 | # Thomas Quintana 19 | 20 | from fsm import * 21 | from unittest import TestCase, expectedFailure, main 22 | 23 | class AbstractLightBulb(FiniteStateMachine): 24 | # Initial state. 25 | initial_state = 'off' 26 | 27 | # Possible transitions. 28 | transitions = [ 29 | ('off', 'on'), 30 | ('on', 'off'), 31 | ('off', 'broken'), 32 | ('on', 'broken') 33 | ] 34 | 35 | class LightBulb(AbstractLightBulb): 36 | # Handle incoming events. 37 | def on_message(self, message): 38 | if message == 'turn on': 39 | self.transition(to = 'on', event = message) 40 | elif message == 'turn off': 41 | self.transition(to = 'off', event = message) 42 | elif message == 'break': 43 | self.transition(to = 'broken', event = message) 44 | 45 | @Guard(state = 'on') 46 | def check_electricity(self): 47 | if hasattr(self, 'electricity'): 48 | return self.electricity 49 | return False 50 | 51 | @Action(state = 'off') 52 | def turn_off(self, message): 53 | self.indicator = 'dim' 54 | 55 | @Action(state = 'on') 56 | def turn_on(self, message): 57 | self.indicator = 'lit' 58 | 59 | @Action(state = 'broken') 60 | def smash(self, message): 61 | self.indicator = 'broken' 62 | 63 | class LightBulbWithMultipleGuards(AbstractLightBulb): 64 | @Guard(state = 'on') 65 | def check_electricity(self): 66 | pass 67 | 68 | @Guard(state = 'on') 69 | def check_socket(self): 70 | pass 71 | 72 | class LightBulbWithMultipleOnEnterActions(AbstractLightBulb): 73 | @Action(state = 'on') 74 | def turn_on(self, message): 75 | pass 76 | 77 | @Action(state = 'on') 78 | def turn_on_again(self, message): 79 | pass 80 | 81 | class LightBulbWithMultipleOnExitActions(AbstractLightBulb): 82 | @Action(state = 'on', on_enter = False, on_exit = True) 83 | def turn_on(self, message): 84 | pass 85 | 86 | @Action(state = 'on', on_enter = False, on_exit = True) 87 | def turn_on_again(self, message): 88 | pass 89 | 90 | class LightBulbWithBadActionState(AbstractLightBulb): 91 | @Action(state = 'bogus') 92 | def foobar(self, message): 93 | pass 94 | 95 | class LightBulbWithBadGuardState(AbstractLightBulb): 96 | @Guard(state = 'bogus') 97 | def foobar(self): 98 | pass 99 | 100 | class LightBulbTests(TestCase): 101 | def test_success_scenario(self): 102 | light_bulb = LightBulb() 103 | light_bulb.electricity = True 104 | self.assertTrue(light_bulb.state() == 'off') 105 | light_bulb.on_message('turn on') 106 | self.assertTrue(light_bulb.state() == 'on') 107 | self.assertTrue(light_bulb.indicator == 'lit') 108 | light_bulb.on_message('turn off') 109 | self.assertTrue(light_bulb.state() == 'off') 110 | self.assertTrue(light_bulb.indicator == 'dim') 111 | 112 | def test_invalid_transition(self): 113 | light_bulb = LightBulb() 114 | light_bulb.electricity = True 115 | self.assertTrue(light_bulb.state() == 'off') 116 | self.assertRaises(FiniteStateMachineError, light_bulb.on_message, 'turn off') 117 | self.assertFalse(hasattr(light_bulb, 'indicator')) 118 | 119 | def test_terminal_state(self): 120 | light_bulb = LightBulb() 121 | light_bulb.electricity = True 122 | self.assertTrue(light_bulb.state() == 'off') 123 | light_bulb.on_message('turn on') 124 | self.assertTrue(light_bulb.state() == 'on') 125 | self.assertTrue(light_bulb.indicator == 'lit') 126 | light_bulb.on_message('turn off') 127 | self.assertTrue(light_bulb.state() == 'off') 128 | self.assertTrue(light_bulb.indicator == 'dim') 129 | light_bulb.on_message('break') 130 | self.assertTrue(light_bulb.state() == 'broken') 131 | self.assertTrue(light_bulb.indicator == 'broken') 132 | self.assertRaises(FiniteStateMachineError, light_bulb.on_message, 'turn on') 133 | self.assertTrue(light_bulb.state() == 'broken') 134 | self.assertTrue(light_bulb.indicator == 'broken') 135 | 136 | def test_guard_denial(self): 137 | light_bulb = LightBulb() 138 | self.assertTrue(light_bulb.state() == 'off') 139 | self.assertRaises(FiniteStateMachineError, light_bulb.on_message, 'turn on') 140 | self.assertTrue(light_bulb.state() == 'off') 141 | self.assertFalse(hasattr(light_bulb, 'indicator')) 142 | 143 | def test_multiple_guards(self): 144 | light_bulb = None 145 | self.assertRaises(FiniteStateMachineError, LightBulbWithMultipleGuards) 146 | self.assertTrue(light_bulb == None) 147 | 148 | def test_multiple_on_enter_actions(self): 149 | light_bulb = None 150 | self.assertRaises(FiniteStateMachineError, LightBulbWithMultipleOnEnterActions) 151 | self.assertTrue(light_bulb == None) 152 | 153 | def test_multiple_on_exit_actions(self): 154 | light_bulb = None 155 | self.assertRaises(FiniteStateMachineError, LightBulbWithMultipleOnExitActions) 156 | self.assertTrue(light_bulb == None) 157 | 158 | def test_bad_action_state(self): 159 | light_bulb = None 160 | self.assertRaises(FiniteStateMachineError, LightBulbWithBadActionState) 161 | self.assertTrue(light_bulb == None) 162 | 163 | def test_bad_guard_state(self): 164 | light_bulb = None 165 | self.assertRaises(FiniteStateMachineError, LightBulbWithBadGuardState) 166 | self.assertTrue(light_bulb == None) 167 | 168 | if __name__ == '__main__': 169 | main() --------------------------------------------------------------------------------