def test_constructor_links_next_node_when_passed_in_constructor(self): # Assemble c2 = Command() c1 = Command(next=c2) # Assert self.assertEqual(c1.get_next(), c2) self.assertEqual(c2.get_previous(), c1)
def extract_command(message_text) -> Command: logging.info("Message Text:: {}".format(message_text)) if len(message_text.split('me')) == 1: logging.info('Command Not Found ' + message_text) return Command(None, None) else: return Command( message_text.split('me')[0], message_text.split('me')[1])
def test_child_command_rolls_back_self_on_exception(self): # Assemble command chain with mocked __do__ functions # Initial command triggered will throw exception c1 = Command() c2 = Command(previous=c1) c2.__do__ = Mock(side_effect=Exception('Oh No!')) c2.__undo__ = Mock() # Action c1.run() # Assert command 2 was rolled back c2.__undo__.assert_called_once()
def test_all_execute_when_no_errors_are_thrown(self): # Setup command chain with mocked __do__ functions c2 = Command() c1 = Command(next=c2) c1.__do__ = Mock() c2.__do__ = Mock() # Action c1.run() # Assert all functions called c1.__do__.assert_called_once() c2.__do__.assert_called_once()
def test_set_previous_sets_node_correctly(self): # Assemble c1 = Command() c2 = Command() # Action c2.set_previous(c1) # Assert self.assertEqual(c1.get_next(), c2) self.assertEqual(c1.get_previous(), None) self.assertEqual(c2.get_next(), None) self.assertEqual(c2.get_previous(), c1)
def test_constructor_links_previous_and_next_node_when_passed_in_constructor(self): # Assemble c1 = Command() c3 = Command() c2 = Command(previous=c1, next=c3) # Assert self.assertEqual(c1.get_previous(), None) self.assertEqual(c1.get_next(), c2) self.assertEqual(c2.get_previous(), c1) self.assertEqual(c2.get_next(), c3) self.assertEqual(c3.get_previous(), c2) self.assertEqual(c3.get_next(), None)
def test_chained_command_does_not_execute_if_parent_throws_exception(self): # Assemble command chain with mocked __do__ functions # Initial command triggered will throw exception c1 = Command() c2 = Command(previous=c1) c1.__do__ = Mock(side_effect=Exception('Oh No!')) c2.__do__ = Mock() # Action c1.run() # Assert command one was called (Threw an exception) and c2 was not called c1.__do__.assert_called_once() c2.__do__.assert_not_called()
class Client(Updater): COMMANDS = [ Command('hello', funs.hello), Command('start', funs.start), Command('morning', funs.morning), Command('weather', funs.weather), Command('help', funs.help), Command('income', funs.income), Command('outflow', funs.outflow), Command('balance', funs.balance) ] def __init__(self, **kwargs): super().__init__(token=os.environ.get('TELEGRAM_KEY', 'XXX'), **kwargs) self.__init_client() def __init_client(self): for command in self.COMMANDS: self.__add_command(command()) def __add_command(self, command): self.dispatcher.add_handler(command) def run(self): self.start_polling() self.idle()
def test_given_next_command_when_executing_then_pass_handled_data(mocker): on_handle_stub = mocker.stub(name='on_handle_stub') on_unregister_stub = mocker.stub(name='on_unregister_stub') commands = [ Command([StubHandler(on_handle_stub, on_unregister_stub)]), Command([StubHandler(on_handle_stub, on_unregister_stub)]) ] handled_data = HANDLED_DATA for command in commands: handled_data = command.execute(handled_data) on_handle_stub.assert_has_calls([call(None), call(ONCE_HANDLED_DATA)]) assert on_unregister_stub.call_count == 2
def test_set_action_overrides_with_lambda(self): # Assemble c1 = Command() # Action c1.set_action(lambda x, y: x + y) # Assert self.assertEqual(3, c1.__do__(1, 2))
def test_set_action_overrides_with_function(self): c1 = Command() def my_action(): return 1 c1.set_action(my_action) self.assertEqual(1, c1.__do__())
def test_dispatches_to_hardware(self): with MockHardware() as hardware_service: dispatcher = Dispatcher(hardware_service) current_state = State(color=Color(100, 100, 100), buzzer_pattern=BuzzerPattern.NONE) command = Command(color=Color(110, 110, 110), duration=100, buzzer_pattern=BuzzerPattern.NONE) now = 0 next_state = dispatcher.dispatch(current_state, command, now) self.assertEqual(next_state.color.r, 100) self.assertEqual(next_state.color.g, 100) self.assertEqual(next_state.color.b, 100) self.assertEqual(hardware_service.color_last_called_with.r, 100) self.assertEqual(hardware_service.color_last_called_with.g, 100) self.assertEqual(hardware_service.color_last_called_with.b, 100) self.assertEqual(hardware_service.color_called_count, 1) now = 10 next_state = dispatcher.dispatch(next_state, command, now) self.assertEqual(next_state.color.r, 101) self.assertEqual(next_state.color.g, 101) self.assertEqual(next_state.color.b, 101) self.assertEqual(hardware_service.color_last_called_with.r, 101) self.assertEqual(hardware_service.color_last_called_with.g, 101) self.assertEqual(hardware_service.color_last_called_with.b, 101) self.assertEqual(hardware_service.color_called_count, 2) now = 90 next_state = dispatcher.dispatch(next_state, command, now) self.assertEqual(next_state.color.r, 109) self.assertEqual(next_state.color.g, 109) self.assertEqual(next_state.color.b, 109) self.assertEqual(hardware_service.color_last_called_with.r, 109) self.assertEqual(hardware_service.color_last_called_with.g, 109) self.assertEqual(hardware_service.color_last_called_with.b, 109) self.assertEqual(hardware_service.color_called_count, 3) now = 100 next_state = dispatcher.dispatch(next_state, command, now) self.assertEqual(next_state.color.r, 110) self.assertEqual(next_state.color.g, 110) self.assertEqual(next_state.color.b, 110) self.assertEqual(hardware_service.color_last_called_with.r, 110) self.assertEqual(hardware_service.color_last_called_with.g, 110) self.assertEqual(hardware_service.color_last_called_with.b, 110) self.assertEqual(hardware_service.color_called_count, 4)
def test_when_executing_then_handle(mocker): on_handle_stub = mocker.stub(name='on_handle_stub') on_unregister_stub = mocker.stub(name='on_unregister_stub') command = Command([StubHandler(on_handle_stub, on_unregister_stub)]) command.execute(HANDLED_DATA) on_handle_stub.assert_called_once_with(None) on_unregister_stub.assert_called_once()
def command(self, coro: Callable ) -> Callable[[fortnitepy.FriendMessage], Any]: if not asyncio.iscoroutinefunction(coro): raise TypeError("Function must be a coroutine") self.register_command(coro.__name__, Command(coro, self.command_prefix) ) def inner(*args, **kwargs): return coro(*args, **kwargs) return inner
def test_set_action_overrides_with_function_and_allows_params(self): # Assemble c1 = Command() def my_action(x, y): return x + y # Action c1.set_action(my_action) # Assert self.assertEqual(3, c1.__do__(1, 2))
def test_given_multiple_handlers_when_executing_then_handle(mocker): on_handle_stub = mocker.stub(name='on_handle_stub') on_unregister_stub = mocker.stub(name='on_unregister_stub') command = Command([ StubHandler(on_handle_stub, on_unregister_stub), StubHandler(on_handle_stub, on_unregister_stub) ]) command.execute(HANDLED_DATA) on_handle_stub.assert_has_calls([call(None), call(ONCE_HANDLED_DATA)]) assert on_unregister_stub.call_count == 2
def main(): admin = os.getenv('ADMIN_USER') telegram_token = os.getenv('TELEGRAM_TOKEN') with open('version', 'r') as v: version = v.read().rstrip() with open('handlers/greeters.yml') as f: gs = f.read() handlers = [] for g in yaml.full_load_all(gs): handlers.append(g) handlers.append( Command('versio', 'La meva versió és {}', [version], Filters.chat(username=admin))) handlers.append(Roller('roll', '', '', None)) r = Rostollador(admin, telegram_token, handlers) r.start()
def test_dispatches_to_hardware_with_buzzer(self): with MockHardware() as hardware_service: dispatcher = Dispatcher(hardware_service) current_state = State(color=Color(100, 100, 100), buzzer_pattern=BuzzerPattern.NONE) command = Command(color=Color.no_change(), duration=100, buzzer_pattern=BuzzerPattern(duration=10, strength=1)) now = 0 next_state = dispatcher.dispatch(current_state, command, now) self.assertEqual(next_state.color.r, 100) self.assertEqual(next_state.color.g, 100) self.assertEqual(next_state.color.b, 100) self.assertEqual(next_state.buzzer_pattern.strength, 1) self.assertEqual(hardware_service.motor_called_count, 1) self.assertEqual(hardware_service.motor_state, 1) now = 10 next_state = dispatcher.dispatch(next_state, command, now) self.assertEqual(next_state.color.r, 100) self.assertEqual(next_state.color.g, 100) self.assertEqual(next_state.color.b, 100) self.assertEqual(next_state.buzzer_pattern.strength, 1) self.assertEqual(hardware_service.motor_called_count, 2) self.assertEqual(hardware_service.motor_state, 1) now = 90 next_state = dispatcher.dispatch(next_state, command, now) self.assertEqual(next_state.color.r, 100) self.assertEqual(next_state.color.g, 100) self.assertEqual(next_state.color.b, 100) self.assertEqual(next_state.buzzer_pattern.strength, 0) self.assertEqual(hardware_service.motor_stop_called_count, 1) self.assertEqual(hardware_service.motor_state, 0)
def main(): # Init SMTP smtp_server = None smtp_user = None smtp_password = None smtp_recipients = None smtp_service = None use_smtp = input('Use SMTP? (y/n) ') if use_smtp == 'y': smtp_server = input('\t / SMTP Server: ') smtp_user = input('\t / User: '******'\t / Password: '******'\t / Recipients: ').split(',') ] smtp_service = SMTP_Service(smtp_user, smtp_password, smtp_server) print() # Init projector details IP_class = input('IP class (leave blank if different among projectors): ') default_port = input( 'Default port (leave blank if different among projectors): ') print() if IP_class: IP_class += '.' if default_port: default_port = int(default_port) projectors = {} projector_names = [] while not projectors: number_of_projectors = int(input('Number of projectors: ')) for i in range(1, number_of_projectors + 1): print() name = input('Name of projector {}: '.format(i)) projector_names.append(name) IP = IP_class + input('IP of projector {}: {}'.format(i, IP_class)) if not default_port: PORT = int(input('Port of projector {}: '.format(i))) else: PORT = default_port # Init projector projectors[name] = ChristieProjector(name, IP, PORT) if not projectors[name].connect(): del projectors[name] projector_names.remove(name) continue if not projectors: print() # Init argument parser parser = argparse.ArgumentParser() parser.add_argument('-v', '--videoprojector', nargs='*', help='videoprojector name / identifier') parser.add_argument('-c', '--command', help='serial command to be sent to videoprojector') parser.add_argument( '-p', '--predefined', nargs='*', help= 'predefined command, such as \'temp\', \'conf\', \'sys\', \'lamp\', \'cool\', \'seri\', \'sign\', \'health\', \'vers\', or \'update_loop_email <seconds>\'' ) # Init background action manager action_manager = ActionManager() action_manager.start() # Main loop args = {} destination_projectors = [] while True: # Parse arguments astr = input('\n$: ') if astr == 'exit': break try: args = vars(parser.parse_args(shlex.split(astr))) except SystemExit: # Trap argparse error message continue if args['videoprojector'] is None or args['videoprojector'] == []: destination_projectors = projector_names else: if set(args['videoprojector']).issubset(projector_names): destination_projectors = args['videoprojector'] else: print('\'{}\' not a videoprojector'.format( list(set(args['videoprojector']) - set(projector_names)))) continue for projector_name in destination_projectors: action = None if args['predefined']: command_code = args['predefined'][0] if 'terminate' in args[ 'predefined']: # if the action needs to be terminated for act in action_manager.actions: # parse current actions if act.code == command_code and act.projector.name in destination_projectors: action_manager.remove_action(act) else: if command_code == 'temp': action = TemperatureRequest(projectors[projector_name]) elif command_code == 'conf': action = ConfigurationRequest( projectors[projector_name]) elif command_code == 'sys': action = SystemRequest(projectors[projector_name]) elif command_code == 'vers': action = VersionRequest(projectors[projector_name]) elif command_code == 'sign': action = SignalRequest(projectors[projector_name]) elif command_code == 'cool': action = CoolingRequest(projectors[projector_name]) elif command_code == 'health': action = HealthRequest(projectors[projector_name]) elif command_code == 'serial': action = SerialRequest(projectors[projector_name]) elif command_code == 'lamp': action = LampRequest(projectors[projector_name]) elif command_code == 'update_loop_email': if use_smtp == 'n': use_smtp = input( '\n\t# SMTP was not enabled! Use SMTP? (y/n) ') smtp_server = input('\t\t / SMTP Server: ') smtp_user = input('\t\t / User: '******'\t\t / Password: '******'\t\t / Recipients: ').split(',') ] smtp_service = SMTP_Service( smtp_user, smtp_password, smtp_server) update_interval = float(args['predefined'][1]) action = UpdateLoopEmail( projectors[projector_name], update_interval, smtp_recipients, smtp_service) else: update_interval = float(args['predefined'][1]) action = UpdateLoopEmail( projectors[projector_name], update_interval, smtp_recipients, smtp_service) elif args['command']: is_request = '?' in args['command'] action = Command(projectors[projector_name], args['command'], is_request) # Add action if action != None: action_manager.add_action(action) # Print actions that require printing, such as requests - this blocks I/O if action.needs_printing: while True: if action in action_manager.responses: if not action_manager.responses[action]: print( '\n\t# Projector \'{}\' (IP: {}) did not respond' .format( projector_name, projectors[projector_name]. last_IP_digits)) else: print( '\n\t# Projector \'{}\' (IP: {}) sent the following response:' .format( projector_name, projectors[projector_name]. last_IP_digits)) action.print_response() action_manager.clear_reponse(action) break action_manager.exit()
def test_find_head_returns_head_in_chain(self): c1 = Command() c2 = Command(previous=c1) c3 = Command(previous=c2) self.assertEqual(c3.find_head(), c1)
from time import time from networks.inetwork import INetwork from dispatcher.dispatcher import Dispatcher from commands.command import Command from state.state import State from colors.color import Color from buzzer.buzzer_pattern import BuzzerPattern DefaultCommand = Command(duration=1, color=Color.no_change(), buzzer_pattern=BuzzerPattern.NONE) class Scheduler: def __init__(self, dispatcher_service: Dispatcher, network_service: INetwork): self.dispatcher_service = dispatcher_service self.network_service = network_service self.commands = [] self.commands.append(DefaultCommand) self.current_command = DefaultCommand self.state = State(Color(255, 255, 255), BuzzerPattern.NONE) self.last_run = time() self.last_poll = 0 def update_commands(self, commands, now): # For now, we will just replace the current commands if commands != None:
def build_command(self): # init response = self.speaker.prompt("Would you like to build a command from scratch or start from an old one?\n> ") old_command = None if response == "old": response = self.speaker.prompt("Which command?\n> ") try: old_command = self.commands[response] self.speaker.speak("Success!") except Exception as e: self.speaker.speak("Sorry, {} is not a current command. Building one from scratch instead.".format(response)) new_command = Command(old_command) # choose name name_not_chosen = True while name_not_chosen: command_name = self.speaker.prompt("Would you like to name the new command?\n> ") if command_name in self.commands: confirmation = self.speaker.prompt("That name is taken. Overwrite old command?\n> ") if confirmation == "yes": self.speaker.speak("Ok! Overwriting {} with new command.".format(command_name)) name_not_chosen = False else: self.speaker.speak("{} was not chosen as new name.".format(command_name)) else: self.speaker.speak("Ok! {} is the name of the new command.".format(command_name)) name_not_chosen = False # build command self.speaker.speak("We are going to start building the command. Say finished when you want to stop.") not_finished = True while not_finished: response = self.speaker.prompt("Next line:\n> ") if response == "pass": new_command.add_pass() elif response == "turn on": new_command.add_turn_on() elif response == "turn off": new_command.add_turn_off() elif response == "sleep": how_long = self.speaker.prompt("For how long?\n> ") new_command.add_sleep(how_long) elif response == "start repeat": how_long = self.speaker.prompt("For how long?\n> ") new_command.start_repeat(how_long) elif response == "end repeat": new_command.end_repeat() elif response == "finished": not_finished = False else: try: defined_command = self.commands[response] new_command.add_command(defined_command) except Exception as e: self.speaker.speak("Sorry, not a valid command... try again!") # save command self.speaker.speak("Done building command!") self.speaker.speak("Here is your command!\n---------------------------") self.speaker.speak(new_command.export_code("18")) self.commands[command_name] = new_command
else: # restrict non-members to general commands for com in general_commands: if m.words[0] == com.title or m.words[0] in com.aliases: result = com.execute(message=m) await message.channel.send(result) return for com in registered_commands: if m.words[0] == com.title or m.words[0] in com.aliases: to_send = "must be registered to use command: **{}**, please register with command **-reg**".format( com.title) await message.channel.send(to_send) return general_commands = [ Command("<@!654176688577445898>", ["-howdy"], greet), Command("-commands", ["-c", "-com"], pretty_print_commands), Command("-help", ["-h", "-halp"], help_dialog), Command("-register", ["-reg"], player_list.register_player) ] registered_commands = [ Command("-shop", ["-s", "-buy"], shop.buy, [player_list]), Command("-give", ["-gift"], gift, [player_list]), Command("-players", ["-p"], player_list.to_string), Command("-dev-gift", [], dev_gift, [player_list]), Command("-inventory", ["-i", "-status", "-s", "-profile"], player_list.get_status), Command("-casino", ["-gamble"], casinos.handle_message, [player_list]), Command("-description", ["-descr", "-desc"], get_description) ]
from commands.command import Command from linker.linker import Linker action1 = Command() action1.set_action(lambda: print("Hello from Action 1!")) action2 = Command() action2.set_action(lambda: print("Hello from Action 2!")) action1.run() linker = Linker() linker.load('./flow.yml') linker.validate() linker.link()
def _with_step(self, step): if step == Step.WAIT_FOR_ROBOT_READY_STATE: self._commands.append( Command([WaitForRobotReadyStateHandler()], step)) elif step == Step.WAIT_FOR_FRONTEND_CYCLE_START: self._commands.append( Command([WaitForFrontendCycleStartHandler()], step)) elif step == Step.MOVE_ROBOT_TO_RESISTANCE_STATION: self._commands.append( Command([MoveRobotToResistanceStationHandler()], step)) elif step == Step.READ_RESISTANCE: self._commands.append(Command([ReadResistanceHandler()], step)) elif step == Step.MOVE_ROBOT_TO_COMMAND_PANEL: self._commands.append( Command([MoveRobotToCommandPanelHandler()], step)) elif step == Step.READ_LETTERS: self._commands.append(Command([ReadLettersHandler()], step)) elif step in (Step.TO_FIRST_PUCK_AND_GRAB_FIRST_PUCK, Step.TO_SECOND_PUCK_AND_GRAB_SECOND_PUCK, Step.TO_THIRD_PUCK_AND_GRAB_THIRD_PUCK): self._commands.append(Command([MoveRobotToNextPuckHandler()], step)) elif step == Step.GRIP_PUCK: self._commands.append(Command([GripPuckHandler()])) elif step in (Step.TO_FIRST_CORNER_AND_RELEASE_FIRST_PUCK, Step.TO_SECOND_CORNER_AND_RELEASE_SECOND_PUCK, Step.TO_THIRD_CORNER_AND_RELEASE_THIRD_PUCK): self._commands.append( Command([MoveRobotToNextCornerHandler()], step)) elif step == Step.RELEASE_PUCK: self._commands.append(Command([ReleasePuckHandler()])) elif step == Step.MOVE_ROBOT_TO_SQUARE_CENTER: self._commands.append( Command([MoveRobotToSquareCenterHandler()], step)) elif step == Step.END_CYCLE: self._commands.append(Command([EndCycleHandler()], step))