def ClientThread(self, clientSocket): """ Handles network I/O with the client. Parameters ---------- clientSocket : socket The socket object that is connected to the remote client's socket. Returns ------ Doesn't return anything. Stops when client issues stop command. """ commandParser = CommandParser() while True: try: command = clientSocket.recv(4096) command = command.decode() response = commandParser.parseCommand(command) if response == "Stop": clientSocket.sendall( "\nThank you for using our telnet server. Bye.\n". encode()) clientSocket.close() break clientSocket.sendall((str(response) + "\n").encode()) except: clientSocket.sendall( "\nOops! something went wrong with the connection.\n". encode())
def testCommandParser(self): running = [True] command_parser = CommandParser(running, self.firebase, self.db) with mock.patch( 'Posts.ViewPost.QueryPostsByUser', return_value=[{ 'content': "Anakin, you're going down a path i cannot follow.", 'post_id': '-MWIr7MbPHHpcrl-5ca0', 'time': '03/21/2021' }, { 'content': 'Execute Order 66', 'post_id': '-MWIrOezXVoDC--zkVBq', 'time': '03/21/2021' }]), mock.patch('sys.stdout', new=StringIO()) as fake_out: command_parser.parseCommand("post view dummy") self.assertTrue( '''|-----------------------------------------------------| | @dummy | | | | Anakin, you're going down a path i cannot follow. | | | | 03/21/2021 -MWIr7MbPHHpcrl-5ca0 | |-----------------------------------------------------| |-----------------------------------------------------| | @dummy | | | | Execute Order 66 | | | | 03/21/2021 -MWIrOezXVoDC--zkVBq | |-----------------------------------------------------|''' in fake_out.getvalue().strip())
def main(): # Parse the command line arguments to determine what to tweet parser = OptionParser() imgController = ImgurController() twController = TwitterController() cmdParser = CommandParser(imgController, twController) parser.add_option("-e", "--exec-direct-messages", dest="exec_direct_messages", default=False, action="store_true", help="Check direct messages for commands") parser.add_option("-n", "--number", dest="number", default=1, help="Specify the number of images to post") parser.add_option("-g", "--gallery", dest="gallery", default="random", help="Specify a gallery to get images from") (options, args) = parser.parse_args() if options.exec_direct_messages: # Parse direct messages and execute their commands cmdParser.parse_commands() elif options.gallery != "random": # Print images from specific gallery messages = imgController.get_formatted_gallery_messages(options.gallery, numImages=int(options.number)) twController.tweet_messages(messages) else: # just post random images for i in range(int(options.number)): message = imgController.get_formatted_random_image_message() twController.tweet_message(message)
def __init__(self, root: Node): from CommandParser import CommandParser from CommandInterpreter import CommandInterpreter self._root = root self.interpreter = CommandInterpreter(self._root) self.parser = CommandParser() self.current_path = NodePath() self.current_path.is_absolute = True
def testCommandParser(self): running = [True] command_parser = CommandParser(running, self.firebase, self.db) with mock.patch('sys.stdout', new=StringIO()) as fake_out: command_parser.parseCommand("profile edit_location ontario") self.assertEqual(fake_out.getvalue().strip(), "Location has been set to ontario")
def testCommandParser(self): running = [True] command_parser = CommandParser(running, self.firebase, self.db) with mock.patch('sys.stdout', new=StringIO()) as fake_out: command_parser.parseCommand("post add test post") self.assertEqual(fake_out.getvalue().strip(), 'Post "test post" added')
def testCommandParser(self): running = [True] command_parser = CommandParser(running, self.firebase, self.db) with mock.patch('sys.stdout', new=StringIO()) as fake_out: command_parser.parseCommand("радость") self.assertEqual( fake_out.getvalue().strip(), "Sorry, your command is invalid. Please type 'help' if you need to view the list of commands!" )
def testCommandParser(self): running = [True] command_parser = CommandParser(running, self.firebase, self.db) with mock.patch('Profile.AddFollowers.QueryFollowing', return_value={""}), mock.patch( 'Profile.AddFollowers.QueryFollowers', return_value={""}), mock.patch( 'sys.stdout', new=StringIO()) as fake_out: command_parser.parseCommand("profile followings_add graeme") self.assertEqual( fake_out.getvalue().strip(), "graeme was successfully added to your followings list!")
def testCommandParser(self): running = [True] command_parser = CommandParser(running, self.firebase, self.db) with mock.patch('sys.stdout', new=StringIO()) as fake_out: try: command_parser.parseCommand("post view dummy") # if there was no error, command connected to the database properly so assert True self.assertTrue(True) except: self.assertTrue(False)
class Shell: """Makes interaction with user painless""" def __init__(self, root: Node): from CommandParser import CommandParser from CommandInterpreter import CommandInterpreter self._root = root self.interpreter = CommandInterpreter(self._root) self.parser = CommandParser() self.current_path = NodePath() self.current_path.is_absolute = True def execute(self, command_line: str): command = self.parser.parse(command_line) if command is None: return None return self.interpreter.execute(command) @staticmethod def pretty_print(result): if isinstance(result, list): for r in result: if isinstance(r, Node): print("[{}] {}\t = {}".format(r['@index'], r["@name"], r)) else: print("[{}] {}".format(r['@index'], r)) else: print(result)
class DriftController: """ Handle Commands, Manage Encounters """ def __init__(self, debughook, ViewManager, ModelManager): self.vm = ViewManager self.mm = ModelManager self.dh = debughook self.cp = CommandParser(debughook, ModelManager) def _get_input(self): return self.vm.get_input_string() def process_command(self): input = self._get_input() self.dh(input) (success, error_code, message) = self.cp.parse_commands(input) if not success: self.vm.provide_command_feedback(message) def process_encounter(self): self.dh("PROCESS ENCOUNTER")
class SlackHook: LISTENING = True @profiler_logging def __init__(self): self._token = os.environ.get("BOT_SLACK_TOKEN") self._slack_client = SlackClient(self._token) self._getBotId() self._at_bot = "<@" + self._bot_id + ">" self._command_parser = CommandParser() @profiler_logging def _getBotId(self): response = self._slack_client.api_call('users.list') if response.get('ok'): _members = response.get('members') for _m in _members: if _m['name'] == self._bot_name: self._bot_id = _m.get('id') @profiler_logging def get_slack_client(self): return self._slack_client @profiler_logging def listen(self): _websocket_delay = 1 if self._slack_client.rtm_connect(): logger.info("pdbot connected, and running!") while SlackHook.LISTENING: command, channel, user = self._parse_slack_output(self._slack_client.rtm_read()) if command and channel: self._handle_command(command, channel, user) time.sleep(_websocket_delay) else: logger.error("Connection failed. Token and bot ID okay?") @profiler_logging def _parse_slack_output(self, rtm_output): if len(rtm_output) != 0: logger.debug(rtm_output) if rtm_output and len(rtm_output) > 0: for output in rtm_output: if "user" in output.keys(): if output['type'] == "message" and output['user'] != self._bot_id: return output['text'], output['channel'], output['user'] return None, None, None @profiler_logging def _handle_command(self, command, channel, user): logger.info("command was {0}, channel was {1}".format(command, channel)) command_output = self._command_parser.parse_command(command) if command_output: response = ("<@{0}> ".format(user)) + command_output self._slack_client.api_call("chat.postMessage", channel=channel, text=response, as_user=True) @profiler_logging def shutdown(self): SlackHook.LISTENING = False
def activate(self): """ Connects to the C&C an infinitely waits for incoming commands. Calls parseCommand and runCommand methods sequentially for every command.""" self.__client.connect() while True: cmd = self.__client.waitForCommand() print cmd self.runCommand(CommandParser.parseCommand(cmd))
class Command: def __init__(self, coms, backup_path="data/backup.pcl"): DEBUG("Command __init__.") self._lock = threading.Lock() self._parse_lock = threading.Lock() self._local = threading.local() self._thread_lock = threading.Lock() self.threads = {} self._registered_callbacks = {} self._fsm = CommandParser(coms) self.setDEBUG(False) self._fsm.finish_callback = self._finish_callback self._fsm.stop_callback = self._stop_callback self._keep_running = True self.backup_path = backup_path self._cmd_hook = Command.CommandHook() def init_tasklist(self): backup_path = self.backup_path self._tasklist_path = backup_path self._tasklist = [] tasklist = self._load_tasklist() # don't self._tasklist if not tasklist is None: for command in tasklist: INFO("exec backup task:%s" % (command, )) self._fsm.put_cmd_into_parse_stream(command) def _load_tasklist(self): with self._lock: try: with io.open(self._tasklist_path, "r", encoding="utf-8") as f: res = f.read().split() DEBUG("_load_tasklist: %d" % len(res)) return res # return Decoder().decode(f) # return json.load(f) # not loads() except Exception, e: ERROR(e) INFO("no unfinished task list.") return []
def __init__(self, coms, backup_path="data/backup.pcl"): DEBUG("Command __init__.") self._lock = threading.Lock() self._parse_lock = threading.Lock() self._local = threading.local() self._thread_lock = threading.Lock() self.threads = {} self._registered_callbacks = {} self._fsm = CommandParser(coms) self.setDEBUG(False) self._fsm.finish_callback = self._finish_callback self._fsm.stop_callback = self._stop_callback self._keep_running = True self.backup_path = backup_path self._cmd_hook = Command.CommandHook()
class CommandParserTests(unittest.TestCase): def setUp(self): self.parser = CommandParser() def parse(self, text) -> Command: cmd = self.parser.parse(text) if cmd is not None: # Check if parsed command can be rebuild: self.assertEqual(text, str(cmd)) return cmd def test_empty(self): cmd = self.parse("") self.assertIsNone(cmd) def test_spaces(self): cmd = self.parse(" ") self.assertIsNone(cmd) def test_comments(self): cmd = self.parse("# rabarbar") self.assertIsNone(cmd) cmd = self.parse(" # indented") self.assertIsNone(cmd) def test_just_name(self): cmd = self.parse("action") self.assertEqual("action", cmd.name) def test_arguments(self): cmd = self.parse("action arg1 arg2") self.assertListEqual(['arg1', 'arg2'], cmd.arguments) def test_target(self): cmd = self.parse("target: action") self.assertEqual("target", cmd.target) self.assertEqual("action", cmd.name) def test_nested_target(self): cmd = self.parse("{target}: action") self.assertEqual("target", cmd.target.name) self.assertEqual("action", cmd.name) def test_nested_name(self): cmd = self.parse("{action}") self.assertEqual("action", cmd.name.name) def test_nested_arguments(self): cmd = self.parse("action {foo} bar {spam: rabarbar}") self.assertEqual("action", cmd.name) self.assertEqual("foo", cmd.arguments[0].name) self.assertEqual("bar", cmd.arguments[1]) self.assertEqual("spam", cmd.arguments[2].target) self.assertEqual("rabarbar", cmd.arguments[2].name)
def testCommandParser(self): running = [True] command_parser = CommandParser(running, self.firebase, self.db) with mock.patch('Profile.ViewProfile.QueryProfile', return_value={ 'following': { 'followers_list': '', 'following_list': 'graeme' }, 'location': 'toronto', 'name': 'dummy', 'posts': '' }), mock.patch('sys.stdout', new=StringIO()) as fake_out: command_parser.parseCommand("profile view dummy") self.assertEqual( fake_out.getvalue().strip(), '''----dummy----\nLocation: toronto\nFollowers List: \ndummy has no followers.\nFollowing List: \n- graeme''' )
def testCommandParser(self): running = [True] command_parser = CommandParser(running, self.firebase, self.db) command_parser.parseCommand("profile followings_add yuvi") command_parser.parseCommand("profile followings_delete yuvi") followingList = self.db.child('profile').child('username').child('dummy').child('following').child("following_list").get(self.user_token).val() self.assertEqual(followingList,'')
def testCommandParser(self): running = [True] command_parser = CommandParser(running, self.firebase, self.db) # check if post added succussfully # store the printed console items in the fake_out variable for assertions later with mock.patch('sys.stdout', new=StringIO()) as fake_out: command_parser.parseCommand( "post add Hello there! My name is Dummy and this is a test post!!" ) # delete the post that was just added posts = QueryPostsByUser(self.db, "dummy", self.user_token) for post in posts: if post["content"] == "Hello there! My name is Dummy and this is a test post!!": DeletePost(self.db, self.firebase.get_username(), self.user_token, post["post_id"]) # check if post succuss message was printed to console self.assertTrue( 'Post "Hello there! My name is Dummy and this is a test post!!" added' in fake_out.getvalue().strip())
def testCommandParser(self): running = [True] command_parser = CommandParser(running, self.firebase, self.db) command_parser.parseCommand("profile edit_name NotDummy") name = self.db.child('profile').child('username').child('dummy').child( 'name').get(self.user_token).val() self.assertEqual(name, "notdummy") command_parser.parseCommand("profile edit_name dummy")
def init_game(): # TODO Take this out of a main file for production. # Setup essential game parts. player = Player(player_name="Demo") room = Room(room_name="Log_Cabin", player_name=player.player_name) command_parser = CommandParser(player=player, room=room) # Continue to take commands till the player dies or the player achieves win conditions. while player.alive and not player.win: user_command = input() user_command = user_command.lower() command_parser.parse_command(user_command) # TODO Make dynamic win/loss statements. if not player.alive: if player.win: print("\n\nYou have won, but have died in the process.") else: print("\n\nYou have died.\nGame Over.") elif player.win: print("Congratulations, You've Won!")
def main(): # Parse the command line arguments to determine what to tweet parser = OptionParser() imgController = ImgurController() twController = TwitterController() cmdParser = CommandParser(imgController, twController) parser.add_option( "-e", "--exec-direct-messages", dest="exec_direct_messages", default=False, action="store_true", help="Check direct messages for commands", ) parser.add_option("-n", "--number", dest="number", default=1, help="Specify the number of images to post") parser.add_option("-g", "--gallery", dest="gallery", default="random", help="Specify a gallery to get images from") (options, args) = parser.parse_args() if options.exec_direct_messages: # Parse direct messages and execute their commands cmdParser.parse_commands() elif options.gallery != "random": # Print images from specific gallery messages = imgController.get_formatted_gallery_messages(options.gallery, numImages=int(options.number)) twController.tweet_messages(messages) else: # just post random images for i in range(int(options.number)): message = imgController.get_formatted_random_image_message() twController.tweet_message(message)
def testCommandParser(self): # test help running = [True] command_parser = CommandParser(running, self.firebase, self.db) help_output = '''********************************* --------Command Reference-------- ********************************* post add [post_content]\t\t\t: Create a new post post edit [post_id]\t\t\t: Edit post with specified ID post delete [post_id]\t\t\t: Delete post with specified ID post view followings\t\t\t: View posts of users you follow post view\t\t\t\t: View your own posts post view [username]\t\t\t: View specified user's posts post view all\t\t\t\t: View all posts from all users profile followings_view [username]\t: View list of users you follow profile followers_view [username]\t: View list of users that follow you profile followings_add [username]\t: Follow a user profile followings_delete [username]\t: Unfollow a user profile view\t\t\t\t: View your own profile profile view [username]\t\t\t: View profile info of specified user profile edit_location [new_location]\t: Change your profile location profile edit_name [new_name]\t\t: Change your profile name profile delete account\t\t\t: Delete your account exit\t\t\t\t\t: Exit app help\t\t\t\t\t: Show this reference screen clear\t\t\t\t\t: Clear the terminal screen''' with mock.patch('sys.stdout', new=StringIO()) as fake_out: command_parser.parseCommand("help") self.assertEqual(fake_out.getvalue().strip(), help_output)
def __init__(self): self.scenario = None #message to display to screen self.message = None #global command parser #it takes in the engine so then it can handle scenario specific commands self.parser = CommandParser(self) #player object for the user #stores their inventory, score, and other things for them self.player = Player() global _instance _instance = self self.startGame()
def launch(command): (result, parameterStack, functionStack) = CommandParser.parseCommand(command) missingData = FunctionDataManager.checkMissingData( functionStack, parameterStack) if (len(missingData) > 0): print('ERROR:') # function not found if (type(missingData) == tuple): print("Function Not Found: " + missingData[1]) else: for param in missingData: if (param == DataType.DIRECTION.name): print("Which Way ? Direction missing !") elif (param == str(DataType.MAGNITUDE.name)): print("How much ? Magnitude missing !") Planner.returnToUnity(result)
def Initialize(port, functionMap={}, asyncHandler = None): global __executors, __connMan, __parser, __p, __initialized, __ready __executors = { 'busy' : (lambda x: Response('busy'), False), 'ready' : (__isReady, False), 'alive' : (lambda x: Response('alive', True), False) } for m in functionMap: if isinstance(functionMap[m], types.FunctionType): __executors[m] = (functionMap[m], False) elif isinstance(functionMap[m], tuple): __executors[m] = functionMap[m] else: print 'Element in function map is not a function nor a tuple: ' + repr(functionMap[m]) __connMan = ConnectionManager(port) __parser = CommandParser(asyncHandler) __p = threading.Thread(target=__MainThread) __p.daemon = True __initialized = True
def test_add_command_foo(self): parser = CommandParser() try: parser.add_command("foo", helpers.bar) except Exceptions.CommandAlreadyExists: self.fail()
def test_add_data_twice(self): parser = CommandParser() parser.add_data("foo_data") self.assertRaises(Exceptions.DataAlreadyExists, parser.add_data, "foo_data")
def test_add_data(self): parser = CommandParser() try: parser.add_data("foo_data") except Exceptions.DataAlreadyExists: self.fail("Data foo_data should not exist")
def test_add_command_foo_twice(self): parser = CommandParser() parser.add_command("foo", helpers.bar) self.assertRaises(Exceptions.CommandAlreadyExists, parser.add_command, "foo", helpers.bar)
def processReceivedCommand(self, command): commandParser = CommandParser(self.setupWindowManager, command) if(commandParser.getCookie() != self.getCookie()): raise Exception("Bad cookie!") else: return commandParser.executeCommand()
def processReceivedCommand(self, command): commandParser = CommandParser(self.setupWindowManager, command) if (commandParser.getCookie() != self.getCookie()): raise Exception("Bad cookie!") else: return commandParser.executeCommand()
def __init__(self, debughook, ViewManager, ModelManager): self.vm = ViewManager self.mm = ModelManager self.dh = debughook self.cp = CommandParser(debughook, ModelManager)
- `/roll` - reply with a random integer between 1 and 6, like rolling a dice. - `/time` - reply with the current time, like a clock. """ def handle(msg): chat_id = msg['chat']['id'] command = msg['text'] print 'Got command: %s' % command if command == '/roll': bot.sendMessage(chat_id, random.randint(1, 6)) elif command == '/time': bot.sendMessage(chat_id, str(datetime.datetime.now())) elif command == '/info': bot.sendMessage(chat_id, 'I am a bot. My name is DemuthBot') elif command == '/uptime': bot.sendMessage(chat_id, cp.runAndReturn(cp.getCommand("load"))) elif command == '/ip': bot.sendMessage(chat_id, cp.runAndReturn(cp.getCommand("publicIP"))) cp = CommandParser() bot = telepot.Bot('<<your Telegram Bot token>>') bot.message_loop(handle) print 'I am listening ...' while 1: time.sleep(10)
Authenticate = Authentication(firebase, db) # Registration if input_.strip() == 'su': Authenticate.register() # Login ''' Sample account credentials: [email protected] 123456789 [email protected] 123456789 [email protected] 123456789 ''' if input_.strip() == 'si': Authenticate.login() if input_.strip() == 'reset': Authenticate.password_reset() ''' Post-Authentication stage: Interaction with the application''' print("\nWelcome back, " + firebase.get_username() + "!") print( "Type 'help' if you would like to find out about the various commands!\nYou can also type 'exit' to quit." ) command = "" running = [True] command_parser = CommandParser(running, firebase, db) while running[0]: sys.stdout.write(">") command = input() command_parser.parseCommand(command)
class Engine: #initializes the engine to starting game position def __init__(self): self.scenario = None #message to display to screen self.message = None #global command parser #it takes in the engine so then it can handle scenario specific commands self.parser = CommandParser(self) #player object for the user #stores their inventory, score, and other things for them self.player = Player() global _instance _instance = self self.startGame() def startGame(self): self.setScenario(_initial_scenario) #loads data to a previously saved point # @param number the save id that wants to be loaded def loadGame(self, number): pass #saves data to the disk for quick recovery in the future #save files will contain the time taken so far, when the data was # last saved, a point count, inventory, and the current position # scenario # @param number the save id that you want to save into def saveGame(self, number): pass #sets the current scenario to a new scenario # if the scenario ID (file path to the scenario) is the same then # it ignores the setting # @return true if a new scenario is set # false if the sceneraio does not change def setScenario(self, s): if self.scenario is None or str(self.scenario) != s: self.scenario = getRoom(s) print self.scenario #after loading a new room, tell the parser to look at the room self.parser.addLetter("look") self.parser.execute() return True return False #gets the current scenario from the engine # used for rendering the current scene def getScenario(self): return self.scenario def getTyped(self): return self.parser.getCurrentTypedMessage() #displaysprint string a message to the screen def show(self, string): self.message = string #checks to see if there is currently a message being rendered #if there is then typing input is usually disabled def isShowingMessage(self): if self.message is not None: return True return False #gets the message to be printed to the display def getMessage(self): return self.message #gets the engine's current player instance def getPlayer(self): return self.player
class Test(unittest.TestCase): """ This class runs unit tests for the commandParser class. ... Attributes ---------- None Methods ------- test_isValidVarName() Tests the isValidVarName method of the commandParser class. test_isValidNumber() Tests the isValidNumnber method of the commandParser class. test_isValidAssignmentExpression() Tests the isValidAssignmentExpression method of the commandParser class. test_parseCommand() Tests the parseCommand method of the commandParser class. """ commandParser = CommandParser() def test_isValidVarName(self): """ Tests the isValidVarName method of the commandParser class. :return: None """ print("\nStart isValidVarName test.") self.assertEqual(self.commandParser.isValidVarName("x"), True) self.assertEqual(self.commandParser.isValidVarName("x1"), True) self.assertEqual(self.commandParser.isValidVarName("x1-12["), False) self.assertEqual(self.commandParser.isValidVarName("x_1"), True) self.assertEqual(self.commandParser.isValidVarName("x x y z"), False) self.assertEqual(self.commandParser.isValidVarName("xxyz"), True) self.assertEqual(self.commandParser.isValidVarName("x@z"), False) self.assertEqual(self.commandParser.isValidVarName("z1.1"), False) print("Finished isValidVarName test. All tests passed.\n") def test_isValidNumber(self): """ Tests the isValidNumber method of the commandParser class. :return: None """ print("\nStart isValidNumber test.") self.assertEqual(self.commandParser.isValidNumber("10"), True) self.assertEqual(self.commandParser.isValidNumber("-10"), True) self.assertEqual(self.commandParser.isValidNumber("1.2432"), True) self.assertEqual(self.commandParser.isValidNumber("-0.000121"), True) self.assertEqual(self.commandParser.isValidNumber("-121212341"), True) self.assertEqual(self.commandParser.isValidNumber("1.2.2.3.4"), False) self.assertEqual(self.commandParser.isValidNumber("112abcd"), False) self.assertEqual(self.commandParser.isValidNumber("1()1"), False) self.assertEqual(self.commandParser.isValidNumber("-+*2"), False) self.assertEqual(self.commandParser.isValidNumber("-----554.12"), False) print("Finished isValidNumber test. All tests passed.\n") def test_isValidAssignmentExpression(self): """ Tests the isValidAssignmentExpression method of the commandParser class. :return: None """ print("\nStart isValidAssignmentExp test.") self.assertEqual(self.commandParser.isValidAssignmentExp("x = 1"), True) self.assertEqual(self.commandParser.isValidAssignmentExp("x1 = 1"), True) self.assertEqual(self.commandParser.isValidAssignmentExp("x = = 1"), False) self.assertEqual(self.commandParser.isValidAssignmentExp("x"), False) self.assertEqual(self.commandParser.isValidAssignmentExp("x y z = 12"), False) self.assertEqual( self.commandParser.isValidAssignmentExp("x = y = z = 12"), False) self.assertEqual(self.commandParser.isValidAssignmentExp("x = y"), False) print("Finished isValidAssignmentExp test. All tests passed.\n") def test_parseCommand(self): """ Tests the parseCommand method of the commandParser class. :return: None """ print("\nStart parseCommand test.") self.assertEqual(self.commandParser.parseCommand("x = 5"), "x has been set to 5") # simplest assignment test self.assertEqual(self.commandParser.parseCommand("y = 10"), "y has been set to 10") # simplest assignment test self.assertEqual( self.commandParser.parseCommand("y1 = 6"), "y1 has been set to 6") # alphanumeric variable name test self.assertEqual(self.commandParser.parseCommand("z = 3.14"), "z has been set to 3.14") # float assignment test self.assertEqual( self.commandParser.parseCommand("p = -0.9112"), "p has been set to -0.9112") # negative float assignment test self.assertEqual(self.commandParser.parseCommand("p = x = -0.9112"), Messages.incorrectCommand) # double assignment test self.assertEqual(self.commandParser.parseCommand("x"), 5) # fetch variable test self.assertEqual(self.commandParser.parseCommand("x + y1"), 11) # operation on stored variables self.assertEqual(self.commandParser.parseCommand("z ** p"), 0.35253131799965065) # operation on stored variables self.assertEqual(self.commandParser.parseCommand("12 ** 3"), 1728) # exponent operation test self.assertEqual(self.commandParser.parseCommand("(x+y)*2/6"), 5) # operation on stored variables with # parentheses self.assertEqual(self.commandParser.parseCommand("k = -----2"), Messages.incorrectCommand) # incorrect # variable value. There can only be 0 or 1 prefix negative signs. self.assertEqual(self.commandParser.parseCommand("k(12 = 2"), Messages.incorrectCommand) # incorrect variable # name self.assertEqual(self.commandParser.parseCommand("k 12 34 abc = 2"), Messages.incorrectCommand) # incorrect # assignment expression. self.assertEqual(self.commandParser.parseCommand("1/ 0"), Messages.incorrectCommand) # division by zero error print("Finished parseCommand test. All tests passed.")
def testCommandParser(self): running = [True] with mock.patch('Posts.ViewPost.QueryPostsAll', return_value=[{'username': "******", 'post_id': '-MWIpcZlD7vuC4oybA4G', 'time': '03/21/2021', "content": "Hey! I am Anando Zaman"}, {'username': "******", 'post_id': '-MWIpnMbZaY0_gv7vZAN', 'time': '03/21/2021', "content": "anakin my allegiance is to the republic to democracy!"}, {'username': "******", 'post_id': '-MWIqFLWUCDvujKJ_26G', 'time': '03/21/2021', "content": "I have brought peace, freedom, justice, and security to my new empire."}, {'username': "******", 'post_id': '-MWIqRbZAAa5HKFC4_qj', 'time': '03/21/2021', "content": "Star Wars: Episode III - Revenge of the Sith"}, {'username': "******", 'post_id': '-MWIrOezXVoDC--zkVBq', 'time': '03/21/2021', "content": "Execute Order 66"} ]), mock.patch('sys.stdout', new=StringIO()) as fake_out: command_parser = CommandParser(running, self.firebase, self.db) command_parser.parseCommand("post view all") self.assertTrue('''|-----------------------------------------------------| | @anando | | | | Hey! I am Anando Zaman | | | | 03/21/2021 -MWIpcZlD7vuC4oybA4G | |-----------------------------------------------------| |-----------------------------------------------------| | @anando | | | | anakin my allegiance is to the republic to | | democracy! | | | | 03/21/2021 -MWIpnMbZaY0_gv7vZAN | |-----------------------------------------------------| |-----------------------------------------------------| | @graeme | | | | I have brought peace, freedom, justice, and | | security to my new empire. | | | | 03/21/2021 -MWIqFLWUCDvujKJ_26G | |-----------------------------------------------------| |-----------------------------------------------------| | @graeme | | | | Star Wars: Episode III - Revenge of the Sith | | | | 03/21/2021 -MWIqRbZAAa5HKFC4_qj | |-----------------------------------------------------| |-----------------------------------------------------| | @yuvi | | | | Execute Order 66 | | | | 03/21/2021 -MWIrOezXVoDC--zkVBq | |-----------------------------------------------------|''' in fake_out.getvalue().strip())
# -*- coding: utf-8 -*- """Execute commands for paintg app.""" # Imports from ConcreteCommandFactory import CommandFactory from PenCommand import SelectPenCommand, DownPenCommand, UpPenCommand from MoveCommand import MoveNorth, MoveEast, MoveSouth, MoveWest from CommandParser import CommandParser from ConcreteReader import FileReader if __name__ == '__main__': defined_commands = [SelectPenCommand(), DownPenCommand(), UpPenCommand(), MoveNorth(), MoveEast(), MoveSouth(), MoveWest()] factory = CommandFactory(defined_commands) parser = CommandParser(factory) reader = FileReader("./data/commands.cmd") command_lines = reader.read() commands = [parser.parse(line) for line in command_lines] for command in commands: command.print()