def test__given_command_processor__when_command_processor_invoked_with_new_peer_join__then_invoke_add_peer_and_data_upload( self, mock_websocket): calls_for_get_peer = [ mock.call('peer_id_1'), mock.call('peer_id_2'), mock.call('peer_id_3'), mock.call('SAMPLE_PEER_ID') ] calls_for_send_data_to_peer = [ mock.call('peer_id_1'), mock.call('peer_id_2'), mock.call('peer_id_3'), mock.call('SAMPLE_PEER_ID') ] mock_websocket.return_value = self.mock_websocket_instance command_processor = CommandProcessor(self.mock_chain_instance) actual_output = command_processor.command_processor( TestCommandProcessor.NEW_PEER_JOIN) expected_output = 'ACK' self.assertEqual(mock_websocket.call_count, 1) self.assertEqual(expected_output, actual_output) self.mock_chain_instance.add_new_peer.assert_called_once_with( 'SAMPLE_PEER_ID', { 'host': '0.0.0.0', 'port': '1234' }) self.mock_chain_instance.get_peer_id_list.assert_called_once() self.mock_chain_instance.get_peer.assert_has_calls(calls_for_get_peer) self.mock_chain_instance.get_block_data.assert_called_once() self.mock_websocket_instance.send.assert_called_once_with( json.dumps(TestCommandProcessor.UPLOAD_DICT))
class IntergrationTestProcessMethod(TestCase): def setUp(self): self.command_processor = CommandProcessor() def test_init_command(self): command = "Create_parking_lot 6" output = self.command_processor.process(command) self.assertEqual(output, "Created parking of 6 slots") def test_init_with_non_positive_int_size(self): command = "Create_parking_lot -6" with self.assertRaises(MalformedCommandError) as e: output = self.command_processor.process(command) self.assertEqual(e.msg, "Lot size should be positive integer") command = "Create_parking_lot 6.3" with self.assertRaises(MalformedCommandError) as e: output = self.command_processor.process(command) self.assertEqual(e.msg, "Lot size should be positive integer") command = "Create_parking_lot 0" with self.assertRaises(MalformedCommandError) as e: output = self.command_processor.process(command) self.assertEqual(e.msg, "Lot size should be positive integer") def test_park_with_valid_data(self): command = "Create_parking_lot 3" output = self.command_processor.process(command) self.assertEqual(output, "Created parking of 3 slots") command = "Park KA-01-HH-1234 driver_age 21" output = self.command_processor.process(command) self.assertEqual( output, 'Car with vehicle registration number "KA-01-HH-1234" has been parked at slot number 1', ) command = "Park KA-01-HH-1234 driver_age 21" output = self.command_processor.process(command) self.assertEqual( output, "Vehicle with this registration number is already parked.") command = "Park KA-01-HH-1235 driver_age 21" output = self.command_processor.process(command) self.assertEqual( output, 'Car with vehicle registration number "KA-01-HH-1235" has been parked at slot number 2', ) command = "Park KA-01-HH-1236 driver_age 21" output = self.command_processor.process(command) self.assertEqual( output, 'Car with vehicle registration number "KA-01-HH-1236" has been parked at slot number 3', ) command = "Park KA-01-HH-1237 driver_age 21" output = self.command_processor.process(command) self.assertEqual(output, "Cannot park more vehicles because parking is full.")
def processRequest(): try: form_data_dict = request.form logger.info("request team_id : %s" % form_data_dict['team_id']) cmdProcessor = CommandProcessor() response = cmdProcessor.processCommand(form_data_dict['text'], form_data_dict) return response except: return "Oops, could not process request."
def test__given_command_processor__when_command_processor_invoked_with_ping__then_return_pong_as_message( self): command_processor = CommandProcessor(self.mock_chain_instance) actual_output = command_processor.command_processor( TestCommandProcessor.PING_COMMAND) expected_output = {'CMD': 'PONG'} self.assertEqual(expected_output, actual_output) self.assertIsInstance(actual_output, dict)
def test__given_command_processor__when_command_processor_invoked_with_add_block_comand__then_add_block( self): command_processor = CommandProcessor(self.mock_chain_instance) actual_output = command_processor.command_processor( TestCommandProcessor.ADD_BLOCK_COMMAND) expected_output = 'ACK' self.assertEqual(expected_output, actual_output) self.mock_chain_instance.add_block.assert_called_once_with('TEST_DATA')
def test__given_command_processor__when_command_processor_invoked_with_validate_block_comand__then_validate_block( self): command_processor = CommandProcessor(self.mock_chain_instance) actual_output = command_processor.command_processor( TestCommandProcessor.VALIDATE_COMMAND_BLOCK) expected_output = 'ACK' self.assertEqual(expected_output, actual_output) self.mock_chain_instance.validate_block.assert_called_once_with( {'data': 'Test Data'})
def test__given_command_processor__when_command_processor_invoked_with_add_peer__then_invoke_add_peer_on_chain_instance( self): command_processor = CommandProcessor(self.mock_chain_instance) actual_output = command_processor.command_processor( TestCommandProcessor.ADD_PEER_COMMAND) expected_output = 'ACK' self.mock_chain_instance.add_new_peer.assert_called_once_with( 'SAMPLE_PEER_ID', { 'host': '0.0.0.0', 'port': '1234' }) self.assertEqual(expected_output, actual_output)
def setUp(self): self.command_processor = CommandProcessor() command = "Create_parking_lot 5" self.command_processor.process(command) command = "Park KA-01 driver_age 21" output = self.command_processor.process(command) command = "Park KA-02 driver_age 18" output = self.command_processor.process(command) command = "Park KA-03 driver_age 18" output = self.command_processor.process(command) command = "Park KA-04 driver_age 21" output = self.command_processor.process(command)
def __init__(self, websocket_port, *args, **kwargs): """ Function for intializing the block chain server. Initializes the BlockChain as well as the HTTP server for interacting with the blockchain """ bc_logger('Setting up naive chain server') self.peer_id = str(uuid.uuid4()) self.age = datetime.datetime.now() self.websocket_port = websocket_port bc_logger('Intializing websocket RPC') self.initialize_blockhain_rpc() bc_logger('Intializing websocket RPC') bc_logger('Intializing protocol processing') self.protocol_processor = CommandProcessor(self) self.peer_list = [] self.peer_connect_dict = {} self.block_data = [] # replace with a thread safe implementation # will run this in the background as a future that never returns!! self.rpc_server.start_websocket() bc_logger('Node {} live on {}:{}'.format(self.peer_id, '0.0.0.0', self.websocket_port)) if kwargs.get('existing_peer'): bc_logger('Peer Discovered') epeer_id = kwargs.get('peer_id') epeer_host = kwargs.get('peer_host') epeer_port = kwargs.get('peer_port') self.join_existing_peer_on_startup(epeer_id, epeer_host, epeer_port) else: bc_logger( 'No Peer Specified. Intializing genesis block for standalone operation' ) self.configure_genesis() # will block on this self.intialize_http_server() self.http_server.start_server()
def __init__(self, config): """ Initialize :param config: configuration :type config: Config """ self.command_processor = CommandProcessor( self._command_handlers(config.command_handlers)) self.robot = Robot(config.apiai.client_access_token, config.apiai.language, self.command_processor.commands) self.speech_to_text = SpeechToText( config.speechkit.key, "", config.speechkit.recognition.language) self.text_to_speech = TextToSpeech( config.speechkit.synthesis.cache_size, config.speechkit.key, config.speechkit.synthesis.language, config.speechkit.synthesis.speaker, config.speechkit.synthesis.emotion, config.speechkit.synthesis.speed) self.record = SpeechCapture(config.record.silence_calculation_chunks, config.record.speech_level_coefficient, config.record.start_wait_chunks, config.record.finish_wait_chunks)
def test__given_command_processor__when_command_processor_invoked_with_new_peer_join_then_raise_websocket_exception__then_remove_added_from_block_chain( self, mock_websocket): calls_for_get_peer = [ mock.call('peer_id_1'), mock.call('peer_id_2'), mock.call('peer_id_3'), mock.call('SAMPLE_PEER_ID') ] calls_for_send_data_to_peer = [ mock.call('peer_id_1'), mock.call('peer_id_2'), mock.call('peer_id_3'), mock.call('SAMPLE_PEER_ID') ] mock_websocket.return_value = self.mock_websocket_instance mock_websocket.side_effect = websocket_client.WebSocketTimeoutException command_processor = CommandProcessor(self.mock_chain_instance) actual_output = command_processor.command_processor( TestCommandProcessor.NEW_PEER_JOIN) expected_output = 'ACK' self.assertEqual(expected_output, actual_output) self.mock_chain_instance.add_new_peer.assert_called_once_with( 'SAMPLE_PEER_ID', { 'host': '0.0.0.0', 'port': '1234' }) self.assertEqual(mock_websocket.call_count, 1) self.mock_chain_instance.get_peer_id_list.assert_called_once() self.mock_chain_instance.get_peer.assert_has_calls(calls_for_get_peer) self.mock_chain_instance.get_block_data.assert_called_once() self.mock_chain_instance.remove_peer.assert_called_once_with( 'SAMPLE_PEER_ID')
def __init__(self, client): self.manually_overriden = False self.configuration_manager = ConfigurationManager(self.CONFIGURATION_FILENAME) self.repost_manager = RepostManager(self.HASHES_FILENAME) self.command_processor = CommandProcessor(self) self.configuration_manager.load_configuration() self.TOKEN = self.configuration_manager.configuration['token'] self.MASTER_ADMIN_ID = self.configuration_manager.configuration['admin'] self.ABOUT_MESSAGE = self.configuration_manager.configuration['about'] self.client = client
def test_file_reading(self, mockPrint): command_processor = CommandProcessor() input_consumer = FileInputConsumer(command_processor) file_name = os.path.join(os.path.dirname(__file__), "./data/test1.txt") input_consumer.consume(file_name) mockPrint.write.assert_has_calls( [ call("Created parking of 6 slots"), call("\n"), call( 'Car with vehicle registration number "KA-01-HH-1234" has been parked at slot number 1' ), call("\n"), call( 'Car with vehicle registration number "PB-01-HH-1234" has been parked at slot number 2' ), call("\n"), call("1,2"), call("\n"), call( 'Car with vehicle registration number "PB-01-TG-2341" has been parked at slot number 3' ), call("\n"), call("2"), call("\n"), call( 'Slot number 2 vacated, the car with vehicle registration number "PB-01-HH-1234" left the space, the driver of the car was of age 21' ), call("\n"), call( 'Car with vehicle registration number "HR-29-TG-3098" has been parked at slot number 2' ), call("\n"), call(""), call("\n"), ] )
def main(stdscr): holdstdout = StdOutWrapper() sys.stdout = holdstdout sys.stderr = holdstdout #stdscr = curses.initscr() screen_size = stdscr.getmaxyx() height = screen_size[0] width = screen_size[1] hincrement = int(height / 3) wincrement = int(width / 3) upper_left = (0, 0) upper_middle = (0, wincrement) upper_right = (0, 2 * wincrement) middle_left = (hincrement, 0) middle_middle = (hincrement, wincrement) middle_right = (hincrement, 2 * wincrement) lower_left = (2 * hincrement, 0) lower_middle = (2 * hincrement, wincrement) #lower_right= (2 * hincrement, 2 * wincrement) # Skills | Spells | Loadout # HUD | Map | Inventory # Terminal | Status | Inventory # Terminal green curses.init_pair(1, 46, curses.COLOR_BLACK) # Dull red curses.init_pair(2, 196, curses.COLOR_BLACK) # Dull Teal curses.init_pair(3, curses.COLOR_CYAN, curses.COLOR_BLACK) # Black on Grey curses.init_pair(4, curses.COLOR_BLACK, 244) # bronze curses.init_pair(5, 208, curses.COLOR_BLACK) curses.init_pair(6, 208, 130) # steel curses.init_pair(7, 252, curses.COLOR_BLACK) curses.init_pair(8, 253, 247) # mithril curses.init_pair(9, 117, curses.COLOR_BLACK) curses.init_pair(10, 117, 33) # adamant curses.init_pair(11, 99, curses.COLOR_BLACK) curses.init_pair(12, 52, 99) # demon curses.init_pair(13, 92, curses.COLOR_BLACK) curses.init_pair(14, 52, 99) # spark curses.init_pair(15, 92, curses.COLOR_BLACK) curses.init_pair(16, 52, 99) # night curses.init_pair(17, 92, curses.COLOR_BLACK) curses.init_pair(18, 52, 99) # cooked meat curses.init_pair(19, 124, curses.COLOR_BLACK) # leather curses.init_pair(20, 130, curses.COLOR_BLACK) # oak curses.init_pair(21, 172, curses.COLOR_BLACK) # maple curses.init_pair(22, 167, curses.COLOR_BLACK) # willow curses.init_pair(23, 137, curses.COLOR_BLACK) # flax curses.init_pair(100, 100, curses.COLOR_BLACK) # gold curses.init_pair(253, 220, curses.COLOR_BLACK) # white curses.init_pair(254, 252, curses.COLOR_BLACK) # box color, dull grey curses.init_pair(255, 240, curses.COLOR_BLACK) terwin = curses.newwin(hincrement, wincrement, lower_left[0], lower_left[1]) terwin.attron(curses.color_pair(255)) terwin.box() ter_panel = curses.panel.new_panel(terwin) ter_panel.top() hudwin = curses.newwin(hincrement, wincrement, middle_left[0], middle_left[1]) hudwin.attron(curses.color_pair(255)) hudwin.box() hud_panel = curses.panel.new_panel(hudwin) hud_panel.top() invwin = curses.newwin(hincrement * 2, wincrement, middle_right[0], middle_right[1]) invwin.attron(curses.color_pair(255)) invwin.box() inv_panel = curses.panel.new_panel(invwin) inv_panel.top() stswin = curses.newwin(hincrement, wincrement, lower_middle[0], lower_middle[1]) stswin.attron(curses.color_pair(255)) stswin.box() sts_panel = curses.panel.new_panel(stswin) sts_panel.top() sklwin = curses.newwin(hincrement, wincrement, upper_left[0], upper_left[1]) sklwin.attron(curses.color_pair(255)) sklwin.box() skl_panel = curses.panel.new_panel(sklwin) skl_panel.top() eqpwin = curses.newwin(hincrement, wincrement, upper_right[0], upper_right[1]) eqpwin.attron(curses.color_pair(255)) eqpwin.box() eqp_panel = curses.panel.new_panel(eqpwin) eqp_panel.top() mapwin = curses.newwin(hincrement, wincrement, middle_middle[0], middle_middle[1]) mapwin.attron(curses.color_pair(255)) mapwin.box() map_panel = curses.panel.new_panel(mapwin) map_panel.top() splwin = curses.newwin(hincrement, wincrement, upper_middle[0], upper_middle[1]) splwin.attron(curses.color_pair(255)) splwin.box() spl_panel = curses.panel.new_panel(splwin) spl_panel.top() curses.start_color() curses.cbreak() curses.noecho() terwin.keypad(1) terwin.idcok(False) try: var_handler = VarHandler() command_processor = CommandProcessor(var_handler) var_handler.bind('command_processor', command_processor) io_handler = IOHandler(terwin, var_handler) var_handler.bind('io_handler', io_handler) hud_handler = HUDHandler(hudwin, var_handler) var_handler.bind('hud_handler', hud_handler) status_handler = StatusHandler(stswin) var_handler.bind('status_handler', status_handler) player = Player(sklwin, var_handler) var_handler.bind('player', player) inventory_handler = InventoryHandler(invwin, eqpwin, var_handler) var_handler.bind('inventory_handler', inventory_handler) location_handler = LocationHandler(mapwin, var_handler) var_handler.bind('location_handler', location_handler) time_handler = TimeHandler() var_handler.bind('time_handler', time_handler) spell_handler = SpellHander(splwin, var_handler) var_handler.bind('spell_handler', spell_handler) combat_handler = CombatHandler(var_handler) var_handler.bind('combat_handler', combat_handler) start = location_handler.spawn_location('entervale') location_handler.spawn_location('forest') start.move("mine") io_handler.output("Welcome to pyscape", curses.color_pair(3), curses.A_BOLD) hud_handler.text_update() hud_panel.top() inventory_handler.update_inv_window() curses.panel.update_panels() while True: curses.curs_set(1) input = io_handler.get_input("~~~~~~~:", curses.color_pair(1)) output = command_processor.receive_command(input) io_handler.output(output[0], output[1]) hud_handler.text_update() hud_panel.top() #inventory_handler.draw_bank() curses.panel.update_panels() except KeyboardInterrupt: terwin.addstr("exiting") exit(0) finally: terwin.keypad(0) curses.nocbreak() curses.echo() curses.endwin() sys.stdout = sys.__stdout__ sys.stderr = sys.__stderr__ sys.stdout.write(holdstdout.get_text())
def setUp(self, daoMock, serviceMock): self.command_processor = CommandProcessor() self.parking_lot_service_mock = serviceMock.return_value
class Application: """ Application main class """ def __init__(self, config): """ Initialize :param config: configuration :type config: Config """ self.command_processor = CommandProcessor( self._command_handlers(config.command_handlers)) self.robot = Robot(config.apiai.client_access_token, config.apiai.language, self.command_processor.commands) self.speech_to_text = SpeechToText( config.speechkit.key, "", config.speechkit.recognition.language) self.text_to_speech = TextToSpeech( config.speechkit.synthesis.cache_size, config.speechkit.key, config.speechkit.synthesis.language, config.speechkit.synthesis.speaker, config.speechkit.synthesis.emotion, config.speechkit.synthesis.speed) self.record = SpeechCapture(config.record.silence_calculation_chunks, config.record.speech_level_coefficient, config.record.start_wait_chunks, config.record.finish_wait_chunks) def _handler(self, real_handler): return lambda args: real_handler(self, args) def _command_handlers(self, command_handlers): result = {} for command, handler in stdhandlers.items(): result[command] = self._handler(handler) for command, handler in command_handlers.items(): result[command] = self._handler(handler) return result def _process_answer(self, commands): finish, results = self.command_processor.process_commands(commands) if not finish: noempty_results = [ result for result in results if result is not None ] play_list(noempty_results) def welcome(self): """ Run robot welcome event """ success, session_id, answer_commands = self.robot.welcome() if success: self.speech_to_text.uuid = session_id self._process_answer(answer_commands) def query(self): """ Run speech request (if we'lll have it) """ print("Listening") silent, record = self.record.record_mp3() if silent: print("Silent") return success, text = self.speech_to_text.convert(record) if not success: print("Not recognized") return print("User : "******"Robot commands : " + json.dumps(commands)) if not success: return self._process_answer(commands) def main(self): self.welcome() while True: self.query()
def main(stdscr): holdstdout = StdOutWrapper() sys.stdout = holdstdout sys.stderr = holdstdout #stdscr = curses.initscr() screen_size = stdscr.getmaxyx() height = screen_size[0] width = screen_size[1] hincrement = int(height / 3) wincrement = int(width / 3) upper_left = (0, 0) upper_middle = (0, wincrement) upper_right = (0, 2 * wincrement) middle_left = (hincrement, 0) middle_middle = (hincrement, wincrement) middle_right = (hincrement, 2 * wincrement) lower_left = (2 * hincrement, 0) lower_middle = (2 * hincrement, wincrement) #lower_right= (2 * hincrement, 2 * wincrement) # Skills | Spells | Loadout # HUD | Map | Inventory # Terminal | Status | Inventory # Terminal green curses.init_pair(1, 46, curses.COLOR_BLACK) # Dull red curses.init_pair(2, 196, curses.COLOR_BLACK) # Dull Teal curses.init_pair(3, curses.COLOR_CYAN, curses.COLOR_BLACK) # Black on Grey curses.init_pair(4, curses.COLOR_BLACK, 244) # bronze curses.init_pair(5, 208, curses.COLOR_BLACK) curses.init_pair(6, 208, 130) # steel curses.init_pair(7, 252, curses.COLOR_BLACK) curses.init_pair(8, 253, 247) # mithril curses.init_pair(9, 117, curses.COLOR_BLACK) curses.init_pair(10, 117, 33) # adamant curses.init_pair(11, 99, curses.COLOR_BLACK) curses.init_pair(12, 52, 99) # demon curses.init_pair(13, 92, curses.COLOR_BLACK) curses.init_pair(14, 52, 99) # spark curses.init_pair(15, 92, curses.COLOR_BLACK) curses.init_pair(16, 52, 99) # night curses.init_pair(17, 92, curses.COLOR_BLACK) curses.init_pair(18, 52, 99) # cooked meat curses.init_pair(19, 124, curses.COLOR_BLACK) # leather curses.init_pair(20, 130, curses.COLOR_BLACK) # oak curses.init_pair(21, 172, curses.COLOR_BLACK) # maple curses.init_pair(22, 167, curses.COLOR_BLACK) # willow curses.init_pair(23, 137, curses.COLOR_BLACK) # flax curses.init_pair(100, 100, curses.COLOR_BLACK) # gold curses.init_pair(253, 220, curses.COLOR_BLACK) # white curses.init_pair(254, 252, curses.COLOR_BLACK) # box color, dull grey curses.init_pair(255, 240, curses.COLOR_BLACK) terwin = curses.newwin(hincrement, wincrement, lower_left[0], lower_left[1]) terwin.attron(curses.color_pair(255)) terwin.box() ter_panel = curses.panel.new_panel(terwin) ter_panel.top() hudwin = curses.newwin(hincrement, wincrement, middle_left[0], middle_left[1]) hudwin.attron(curses.color_pair(255)) hudwin.box() hud_panel = curses.panel.new_panel(hudwin) hud_panel.top() invwin = curses.newwin(hincrement * 2, wincrement, middle_right[0], middle_right[1]) invwin.attron(curses.color_pair(255)) invwin.box() inv_panel = curses.panel.new_panel(invwin) inv_panel.top() stswin = curses.newwin(hincrement, wincrement, lower_middle[0], lower_middle[1]) stswin.attron(curses.color_pair(255)) stswin.box() sts_panel = curses.panel.new_panel(stswin) sts_panel.top() sklwin = curses.newwin(hincrement, wincrement, upper_left[0], upper_left[1]) sklwin.attron(curses.color_pair(255)) sklwin.box() skl_panel = curses.panel.new_panel(sklwin) skl_panel.top() eqpwin = curses.newwin(hincrement, wincrement, upper_right[0], upper_right[1]) eqpwin.attron(curses.color_pair(255)) eqpwin.box() eqp_panel = curses.panel.new_panel(eqpwin) eqp_panel.top() mapwin = curses.newwin(hincrement, wincrement, middle_middle[0], middle_middle[1]) mapwin.attron(curses.color_pair(255)) mapwin.box() map_panel = curses.panel.new_panel(mapwin) map_panel.top() splwin = curses.newwin(hincrement, wincrement, upper_middle[0], upper_middle[1]) splwin.attron(curses.color_pair(255)) splwin.box() spl_panel = curses.panel.new_panel(splwin) spl_panel.top() curses.start_color() curses.cbreak() curses.noecho() terwin.keypad(1) terwin.idcok(False) try: var_handler = VarHandler() command_processor = CommandProcessor(var_handler) var_handler.bind('command_processor', command_processor) io_handler = IOHandler(terwin, var_handler) var_handler.bind('io_handler', io_handler) hud_handler = HUDHandler(hudwin, var_handler) var_handler.bind('hud_handler', hud_handler) status_handler = StatusHandler(stswin) var_handler.bind('status_handler', status_handler) player = Player(sklwin, var_handler) var_handler.bind('player', player) inventory_handler = InventoryHandler(invwin, eqpwin, var_handler) var_handler.bind('inventory_handler', inventory_handler) location_handler = LocationHandler(mapwin, var_handler) var_handler.bind('location_handler', location_handler) time_handler = TimeHandler() var_handler.bind('time_handler', time_handler) spell_handler = SpellHander(splwin, var_handler) var_handler.bind('spell_handler', spell_handler) combat_handler = CombatHandler(var_handler) var_handler.bind('combat_handler', combat_handler) start = location_handler.spawn_location('entervale') location_handler.spawn_location('forest') start.move("mine") io_handler.output("Welcome to pyscape", curses.color_pair(3), curses.A_BOLD) hud_handler.text_update() hud_panel.top() inventory_handler.update_inv_window() curses.panel.update_panels() while True: curses.curs_set(1) input = io_handler.get_input("~~~~~~~:", curses.color_pair(1)) output = command_processor.receive_command(input) io_handler.output(output[0], output[1]) hud_handler.text_update() hud_panel.top() #inventory_handler.draw_bank() curses.panel.update_panels() except KeyboardInterrupt: terwin.addstr("exiting") exit(0) finally: terwin.keypad(0) curses.nocbreak() curses.echo() curses.endwin() sys.stdout = sys.__stdout__ sys.stderr = sys.__stderr__ sys.stdout.write(holdstdout.get_text())
def setUp(self): self.command_processor = CommandProcessor()
class UnitTestProcessMethod(TestCase): @patch("command_processor.ParkingLotService") @patch("command_processor.ParkingLotDao") def setUp(self, daoMock, serviceMock): self.command_processor = CommandProcessor() self.parking_lot_service_mock = serviceMock.return_value def test_init_command(self): command = "Create_parking_lot 7" self.parking_lot_service_mock.create_parking_lot_of_size = MagicMock( return_value=7) output = self.command_processor.process(command) self.parking_lot_service_mock.create_parking_lot_of_size.assert_called_once_with( 7) self.assertEqual(output, "Created parking of 7 slots") @patch("command_processor.Vehicle") @patch("command_processor.Driver") def test_park_command(self, driverMock, vehicleMock): command = "Park KA-01-HH-1234 driver_age 21" parked_slot_mock = MagicMock() parked_slot_mock.return_value.parked_vehicle.number = "KA-01-HH-1234" type(parked_slot_mock.return_value).number = PropertyMock( return_value=1) self.parking_lot_service_mock.park_vehicle = parked_slot_mock output = self.command_processor.process(command) driverMock.assert_called_once_with(21) vehicleMock.assert_called_once_with("KA-01-HH-1234", driverMock.return_value) self.parking_lot_service_mock.park_vehicle.assert_called_once_with( vehicleMock.return_value) self.assertEqual( output, 'Car with vehicle registration number "KA-01-HH-1234" has been parked at slot number 1', ) def helper_to_test_missing_command_args_error(self, command): with self.assertRaises(MalformedCommandError) as e: output = self.command_processor.process(command) self.assertEqual(e.msg, "Missing command arguments.") def helper_to_test_missing_operation_in_command_error(self, command): with self.assertRaises(MalformedCommandError) as e: output = self.command_processor.process(command) self.assertEqual(e.msg, command + " missing valid operation.") def test_error_thrown_on_invalid_command(self): command = "Create_parking_lot" self.helper_to_test_missing_command_args_error(command) command = "Create_parking_lot " self.helper_to_test_missing_command_args_error(command) command = "Park " self.helper_to_test_missing_command_args_error(command) command = "Park VIP-001 driver_age " self.helper_to_test_missing_command_args_error(command) command = "Park driver_age 21" self.helper_to_test_missing_command_args_error(command) command = "Invalidop 6" self.helper_to_test_missing_operation_in_command_error(command) command = "Create_parking_lot invalid_size" with self.assertRaises(MalformedCommandError) as e: output = self.command_processor.process(command) self.assertEqual( e.msg, "invalid_size is not int. Slot size should be int.") command = "Park number_plate_sample driver_age -21" with self.assertRaises(MalformedCommandError) as e: output = self.command_processor.process(command) self.assertEqual(e.msg, "-100 is negative. Age should be positive.")
def main(): input_file = args[1] file_input_consumer = FileInputConsumer(CommandProcessor()) file_input_consumer.consume(input_file)
class IntergrationTestUnparkParkProcessMethod(TestCase): def setUp(self): self.command_processor = CommandProcessor() command = "Create_parking_lot 5" self.command_processor.process(command) command = "Park KA-01 driver_age 21" output = self.command_processor.process(command) command = "Park KA-02 driver_age 18" output = self.command_processor.process(command) command = "Park KA-03 driver_age 18" output = self.command_processor.process(command) command = "Park KA-04 driver_age 21" output = self.command_processor.process(command) def test_invalid_query(self): command = "Leave " with self.assertRaises(MalformedCommandError) as e: output = self.command_processor.process(command) self.assertEqual(e.msg, "Missing command arguments.") command = "Leave string" with self.assertRaises(MalformedCommandError) as e: output = self.command_processor.process(command) self.assertEqual(e.msg, "string is not int. Slot number should be int.") command = "Leave -2" with self.assertRaises(MalformedCommandError) as e: output = self.command_processor.process(command) self.assertEqual( e.msg, "-5 is negative. Slot Number should be positive.") def test_valid_commands(self): command = "Leave 2" output = self.command_processor.process(command) self.assertEqual( output, 'Slot number 2 vacated, the car with vehicle registration number "KA-02" left the space, the driver of the car was of age 18', ) command = "Leave 3" output = self.command_processor.process(command) self.assertEqual( output, 'Slot number 3 vacated, the car with vehicle registration number "KA-03" left the space, the driver of the car was of age 18', ) command = "Leave 3" output = self.command_processor.process(command) self.assertEqual(output, "Slot already vacant") command = "Leave 6" output = self.command_processor.process(command) self.assertEqual(output, "Slot number not present.") command = "Park KA-05 driver_age 21" output = self.command_processor.process(command) self.assertEqual( output, 'Car with vehicle registration number "KA-05" has been parked at slot number 2', )
class IntergrationTestQueryCommandsProcessMethod(TestCase): def setUp(self): self.command_processor = CommandProcessor() command = "Create_parking_lot 5" self.command_processor.process(command) command = "Park KA-01 driver_age 21" output = self.command_processor.process(command) command = "Park KA-02 driver_age 18" output = self.command_processor.process(command) command = "Park KA-03 driver_age 18" output = self.command_processor.process(command) command = "Park KA-04 driver_age 21" output = self.command_processor.process(command) def test_invalid_query(self): command = "Slot_number_for_car_with_number " with self.assertRaises(MalformedCommandError) as e: output = self.command_processor.process(command) self.assertEqual(e.msg, "Missing command arguments.") command = "Slot_numbers_for_driver_of_age " with self.assertRaises(MalformedCommandError) as e: output = self.command_processor.process(command) self.assertEqual(e.msg, "Missing command arguments.") command = "Vehicle_registration_number_for_driver_of_age " with self.assertRaises(MalformedCommandError) as e: output = self.command_processor.process(command) self.assertEqual(e.msg, "Missing command arguments.") command = "Slot_numbers_for_driver_of_age csd" with self.assertRaises(MalformedCommandError) as e: output = self.command_processor.process(command) self.assertEqual(e.msg, "csd is not int. Age should be int.") command = "Vehicle_registration_number_for_driver_of_age sdc" with self.assertRaises(MalformedCommandError) as e: output = self.command_processor.process(command) self.assertEqual(e.msg, "sdc is not int. Age should be int.") def test_valid_commands(self): command = "Slot_number_for_car_with_number KA-01" output = self.command_processor.process(command) self.assertEqual(output, "1") command = "Slot_number_for_car_with_number KA-02" output = self.command_processor.process(command) self.assertEqual(output, "2") command = "Slot_number_for_car_with_number KA-03" output = self.command_processor.process(command) self.assertEqual(output, "3") command = "Slot_number_for_car_with_number KA-04" output = self.command_processor.process(command) self.assertEqual(output, "4") command = "Slot_number_for_car_with_number KA-05" output = self.command_processor.process(command) self.assertEqual(output, "") command = "Slot_numbers_for_driver_of_age 18" output = self.command_processor.process(command) self.assertEqual(output, "2,3") command = "Slot_numbers_for_driver_of_age 21" output = self.command_processor.process(command) self.assertEqual(output, "1,4") command = "Slot_numbers_for_driver_of_age 14" output = self.command_processor.process(command) self.assertEqual(output, "") command = "Vehicle_registration_number_for_driver_of_age 14" output = self.command_processor.process(command) self.assertEqual(output, "") command = "Vehicle_registration_number_for_driver_of_age 21" output = self.command_processor.process(command) self.assertEqual(output, "KA-01,KA-04") command = "Vehicle_registration_number_for_driver_of_age 18" output = self.command_processor.process(command) self.assertEqual(output, "KA-02,KA-03")
class BlockChain(object): """ Blockchain server object using which will be responsible for starting the HTTP server as well adding more information to the blockchain """ def __init__(self, websocket_port, *args, **kwargs): """ Function for intializing the block chain server. Initializes the BlockChain as well as the HTTP server for interacting with the blockchain """ bc_logger('Setting up naive chain server') self.peer_id = str(uuid.uuid4()) self.age = datetime.datetime.now() self.websocket_port = websocket_port bc_logger('Intializing websocket RPC') self.initialize_blockhain_rpc() bc_logger('Intializing websocket RPC') bc_logger('Intializing protocol processing') self.protocol_processor = CommandProcessor(self) self.peer_list = [] self.peer_connect_dict = {} self.block_data = [] # replace with a thread safe implementation # will run this in the background as a future that never returns!! self.rpc_server.start_websocket() bc_logger('Node {} live on {}:{}'.format(self.peer_id, '0.0.0.0', self.websocket_port)) if kwargs.get('existing_peer'): bc_logger('Peer Discovered') epeer_id = kwargs.get('peer_id') epeer_host = kwargs.get('peer_host') epeer_port = kwargs.get('peer_port') self.join_existing_peer_on_startup(epeer_id, epeer_host, epeer_port) else: bc_logger( 'No Peer Specified. Intializing genesis block for standalone operation' ) self.configure_genesis() # will block on this self.intialize_http_server() self.http_server.start_server() def validate_blockchain(self): import hashlib for i in range(len(self.block_data)): hasher = hashlib.sha256() if i == 0: # genesis block, continue as # is continue prev_hash = self.block_data[i - 1].curr_hash current_block = self.block_data[i].data hasher.update(prev_hash.encode() + current_block.encode()) current_hash = hasher.hexdigest() if current_hash != self.block_data[i].curr_hash: return False return True def join_existing_peer_on_startup(self, peer_id, host, port): """ Send intialization request for data upload and connecting to other peers """ bc_logger('Joining remote peer') self.protocol_processor.add_new_peer(peer_id, host, port) command_dict = {} command_dict['CMD'] = 'NEW_PEER_JOIN' command_dict['peer_id'] = self.peer_id command_dict['peer_host'] = '0.0.0.0' command_dict['peer_port'] = self.websocket_port bc_logger('Intializing data sync peer') self.protocol_processor.write_to_peers([peer_id], json.dumps(command_dict)) def configure_genesis(self): """ Class function for configuring gensis """ genesis_block = Block(0, 'ioiiiuasyi891qbduquiuqwiqwiupwe', 'random') self.block_data.append(genesis_block) def create_sample_block_data(self, data): latest_block = self.block_data[-1] last_block = Block(latest_block.index + 1, latest_block.curr_hash, data) return last_block def add_block(self, data): latest_block = self.block_data[-1] last_block = Block(latest_block.index + 1, latest_block.curr_hash, data) self.block_data.append(last_block) return last_block def validate_block(self, block_data): block_data['data'] = json.loads(block_data.get('data')) latest_block = self.block_data[-1] compiled_block_data = Block(latest_block.index + 1, latest_block.curr_hash, block_data.get('data')) return block_data.get('curr_hash') == compiled_block_data.curr_hash def add_data(self, data): block = self.create_sample_block_data(data) consensus_result = self.protocol_processor.get_peer_agreement(({ 'CMD': 'VALIDATE_BLOCK', 'block_data': block.serialize() })) if not consensus_result: return False self.add_block(data) self.protocol_processor.write_to_peers( self.peer_connect_dict.keys(), json.dumps({ 'CMD': 'ADD_BLOCK', 'data': data })) return self.protocol_processor.get_peer_agreement(block.serialize()) def intialize_http_server(self): """ Initialize the HTTP server for handling incoming requests from the user """ self.http_server = NaiveChainHTTPServer(self, '0.0.0.0', int(self.websocket_port) + 1) def initialize_blockhain_rpc(self): """ Intialize block chain using web sockets """ # remote server for handling incoming requests self.rpc_server = WebSocketServer(self.websocket_port, self) def process_command(self, command): """ Class function for processing any incoming commands from other peers or nodes """ # get the command dict current_command = json.loads(command) return self.protocol_processor.command_processor(current_command) def process_data_upload(self, data): """ Class function for replicating and pre-processing data before adding it to the nodes master records """ #derp!!! return data