def getProperties(command): ''' Function to return a list containing the properties of the filter query :param command: a list containing the user command, split by whitespaces :return: another list containing the arguments of the filter command which can be of two types: greater/less than X - all transactions greater/less than X (given amount of money) greater/less than X before Y - all transactions greater/less than X (given amount of money) before given day(Y) :raises exception whenever there is a syntax error, a value error or an invalid parameter error. ''' if len(command) < 3: raise CommandError("Filter command - Syntax error!") if len(command) == 4: raise CommandError("Filter command - Syntax error!") if command[1] != 'than': raise CommandError("Filter command - Syntax error!") if len(command) > 3 and command[3] != 'before': raise CommandError("Filter command - Syntax error!") if not representsInt(command[2]): raise InvalidParameters("Filter command - amount is not an integer!") if int(command[2]) <= 0: raise InvalidParameters( "Filter command - amount should be strictly positive!") if len(command) > 3 and not representsInt(command[4]): raise InvalidParameters("Filter command - day is not an integer!") if len(command) > 3 and int(command[4]) <= 0: raise InvalidParameters( "Filter command - day should be strictly positive!") arguments = [command[0], int(command[2])] if len(command) > 3: arguments.append(int(command[4])) return arguments
def getReplaceTransaction(command): ''' A function to handle the Replace Transaction Feature :param command: the command the user has inputted the transaction the user wants to insert ''' if len(command) < 4: raise CommandError("Replace command - Syntax error!") if command[-2] != 'with': raise CommandError("Replace command - Syntax error!") if not representsInt(command[-1]): raise InvalidParameters("Replace command - Amount not an integer!") if int(command[-1]) <= 0: raise InvalidParameters( 'Replace command - Amount cannot be negative or null!') argsList = command[1].split(',') if len(argsList) < 3: raise CommandError("Replace command - Not enough parameters!") if not representsInt(argsList[0]): raise InvalidParameters("Replace command - Date not an integer!") if int(argsList[0]) <= 0: raise InvalidParameters( "Replace command - Date should be strictly positive!") if argsList[1] not in ['in', 'out']: raise InvalidParameters( 'Replace command - Transaction type unknown, should be only in or out' ) newAmount = int(command[-1]) day = int(argsList[0]) description = ','.join(argsList[2:]) if len(command) > 4: description = description + ' ' + ' '.join(command[2:-2]) return (day, argsList[1], newAmount, description)
def __validate_response(self, response): if response.status / 100 == 2: return if response.status == 400: # Bad Request json_response = json.loads(response.read()) raise CommandError( 1, "Bad Request: {0}".format( json_response["badRequest"]["message"])) if response.status / 100 == 4: raise CommandError(1, response.reason) raise CommandError( 1, "Unhandled response code: %s (%s)" % (response.status, response.reason))
def getSortArguments(command): ''' Function to get the arguments of Sort command :param command: a list containing the whitespace-split command from the user :return: a tuple ('asc'/'desc', 'day'/'in'/'out') representing the arguments the the sort function :raises exception whenever there is a syntax error, a value error or an invalid parameter error. ''' if len(command) < 3: raise CommandError("Sort command - Syntax Error!") if command[1] != 'sort': raise CommandError("Sort command - Syntax Error!") if command[2] != 'day' and command[2] != 'in' and command[2] != 'out': raise CommandError("Sort command - Syntax Error!") return (command[0], command[2])
def getMaxArguments(command): ''' Function to get the arguments of Max command :param command: a list containing the whitespace-split command from the user :return: an string from the set {"in", "out"} which is the argument of the max command :raises exception whenever there is a syntax error, a value error or an invalid parameter error. ''' if len(command) < 3: raise CommandError("Max command - Syntax error!") if command[1] != 'in' and command[1] != 'out': raise InvalidParameters("Max command - Unknown type of transaction") if command[2] != 'day': raise CommandError("Max command - Syntax error!") return command[1]
def auth_keystone(self): token = self.options.token password = self.options.password username = self.options.username tenant_id = self.options.tenant_id tenant_name = self.options.tenant_name if token: params = {"auth": {"token": {"id": token}}} elif username and password: params = { "auth": { "passwordCredentials": { "username": username, "password": password } } } else: raise CommandError(1, "A username and password or token is required") if tenant_id: params['auth']['tenantId'] = tenant_id elif tenant_name: params['auth']['tenantName'] = tenant_name _, access = self.request(self.options.auth_url + "/tokens", "POST", body=params, headers={"Content-Type": "application/json"}) if access is None: raise CommandError(1, "You are not authenticated") self.token_info = TokenInfo(access) if not self.management_url and self.service_type: self.set_service_type(self.service_type) self.auth_headers = {"X-Auth-Token": self.token_info.get_token()} if not tenant_id: try: tenant_id = access['access']['token']['tenant']['id'] except Exception: raise CommandError( 1, "Response json object doesn't contain chain 'access->token->tenant->id'" ) self.options.tenant_id = tenant_id self.auth_headers["X-Tenant"] = tenant_id if tenant_name: self.auth_headers["X-Tenant-Name"] = tenant_name
def getAddTransaction(command): ''' A function to handle the Add Transaction Feature :param command: the command the user has inputted :return a tuple (day, amount, in/out, description) which describes the transaction the user wants to add or None if there is a command syntax error ''' if len(command) < 2: raise CommandError("Add command - Syntax Error!") argsList = command[1].split(',') if len(argsList) < 3: raise InvalidParameters("Add command - Not enough parameters!") if not representsInt(argsList[0]): raise InvalidParameters( "Add command - The amount of money not an integer!") if int(argsList[0]) <= 0: raise InvalidParameters( "Add command - The amount of money should be strictly positive!") if argsList[1].lower() not in ["in", "out"]: raise InvalidParameters( "Add command - The only known types are in and out!") description = ','.join(argsList[2:]) if len(command) > 2: description = description + ' ' + ' '.join(command[2:]) transaction = (datetime.datetime.now().day, int(argsList[0]), argsList[1], description) return transaction
def getInsertTransaction(command): ''' A function to handle the Insert Transaction Feature :param command: the command the user has inputted :return a tuple (day, amount, in/out, description) which describes the transaction the user wants to insert or None if there is a command syntax error ''' if len(command) < 2: raise CommandError("Insert Command - Syntax Error!") argsList = command[1].split(',') if len(argsList) < 4: raise InvalidParameters("Insert Command - Not enough parameters!") if not representsInt(argsList[0]): raise InvalidParameters("Insert Command - Day not an integer!") if int(argsList[0]) <= 0: raise InvalidParameters( "Insert Command - Day should be strictly positive!") if not representsInt(argsList[1]): raise InvalidParameters("Insert Command - Amount not an integer!") if int(argsList[1]) <= 0: raise InvalidParameters( "Insert Command - Amount cannot be negative or nul!") if argsList[2].lower() not in ["in", "out"]: raise InvalidParameters( "Insert Command - The only known transaction types are in and out") description = ','.join(argsList[3:]) if len(command) > 2: description = description + ' ' + ' '.join(command[2:]) transaction = (int(argsList[0]), int(argsList[1]), argsList[2], description) return transaction
def url_for(self, service_type, endpoint_type='publicURL'): try: return self.token_info.url_for(service_type=service_type, endpoint_type=endpoint_type) except EndpointNotFound: raise CommandError( 1, "Could not find `%s' in service catalog" % service_type)
def getCommand(self): #gets the command from the user and calls the validation functions cmd = input("Please choose an option from above: ") print() if cmd == "": raise CommandError("Enter is not an option.") self._validateinteger.validate_integer(cmd) return str(cmd)
def auth(self): if self.options.token: self.__token = self.options.token self.management_url = self.options.endpoint if not (self.options.token and self.options.endpoint): if not self.options.auth_url: raise CommandError(1, "Authentication URL is required") if self.options.use_keystone is None: raise CommandError( 1, "You should select auth type (use_keystone parameter)") if self.options.use_keystone: self.auth_keystone() else: self.auth_nova() else: self.auth_headers = { "X-Auth-Token": self.__token, }
def handle_request(self, socket_file): first_byte = socket_file.read(1) if not first_byte: raise Disconnect() try: # Delegate to the appropriate handler based on # the first byte. return self.handlers[first_byte](socket_file) except KeyError: raise CommandError('bad request')
def get_response(self, data): """Here we'll actually unpack the data sent by the client, execute the command they specified, and pass back the return value. """ if not isinstance(data, list): try: data = data.split() except: CommandError('Request must be list or simple string.') if not data: raise CommandError('Missing command') command = data[0].upper() if command not in self._commands: raise CommandError('unrecognized command: %s' % command) logger.info("{} request received.".format(command)) return self._commands[command](*data[1:])
def getAllArguments(command): ''' Function to get the arguments of All command :param command: a list containing the whitespace-split command from the user :return: either 'in' or 'out' parsed from what the user inserted :raises exception whenever there is a syntax error, a value error or an invalid parameter error. ''' if len(command) < 2: raise CommandError("All filter - syntax error!") if command[1] != "in" and command[1] != 'out': raise InvalidParameters("All filter - the only known types are in/out") return command[1]
def getSumArgument(command): ''' Function to get the arguments of Sum command :param command: a list containing the whitespace-split command from the user :return: an integer representing the sum of all the 'in' transaction or 'out' transaction. :raises exception whenever there is a syntax error, a value error or an invalid parameter error. ''' if len(command) < 2: raise CommandError("Sum command - Syntax error!") if command[1] != 'in' and command[1] != 'out': raise InvalidParameters("Sum command - Unknown transaction type!") return command[1]
def getBalanceArguments(command): ''' Function to get the arguments of Balance command :param command: a list containing the whitespace-split command from the user :return: an integer representing the day when the use wants to know it's balance :raises exception whenever there is a syntax error, a value error or an invalid parameter error. ''' if len(command) < 2: raise CommandError("Balance - syntax error!") if not representsInt(command[1]): raise InvalidParameters("Balance - day should be integer!") if int(command[1]) <= 0: raise InvalidParameters("Balance - day should be positive!") return int(command[1])
def auth_nova(self): auth_headers = { "X-Auth-User": self.options.username, "X-Auth-Key": self.options.password, "X-Auth-Project-Id": self.options.tenant_name } resp, _ = self.request(self.options.auth_url, "GET", headers=auth_headers) self.__token = resp.getheader("X-Auth-Token") if not self.__token: raise CommandError(1, "You are not authorized") if not self.management_url: self.management_url = resp.getheader("X-Server-Management-Url") self.auth_headers = { "X-Auth-Project-Id": self.options.tenant_name, "X-Auth-Token": self.__token }
def getFilterArguments(command): ''' Function to return a list of arguments which represents the Filter command arguments :param command: a list of strings which is the input string split by whitespaces :return: ''' if len(command) < 2: raise CommandError("Filter command - Syntax Error.") if command[1] != 'in' and command[1] != 'out': raise InvalidParameters( "Filter command - the first parameter should be either in or out.") if len(command) > 2 and not representsInt(command[2]): raise InvalidParameters( "Filter command - the second arguments should be an integer.") if len(command) > 2 and not int(command[2]) < 0: raise InvalidParameters( "Filter command - the second arguments should be positive.") args = [command[1]] if len(command) > 2: args.append(command[2]) return args
def _write(self, buf, data): if isinstance(data, str): data = data.encode('utf-8') if isinstance(data, bytes): buf.write('$%s\r\n%s\r\n' % (len(data), data.decode('utf-8'))) elif isinstance(data, int): buf.write(':%s\r\n' % data) elif isinstance(data, Error): buf.write('-%s\r\n' % data.message) elif isinstance(data, (list, tuple)): buf.write('*%s\r\n' % len(data)) for item in data: self._write(buf, item) elif isinstance(data, dict): buf.write('%%%s\r\n' % len(data)) for key in data: self._write(buf, key) self._write(buf, data[key]) elif data is None: buf.write('$-1\r\n') else: raise CommandError("unrecognized type: '%s'" % type(data))
def getRemoveTransactionInterval(command): ''' A function to handle the Remove Interval Transaction :param command: the command the user has inputted :return a tuple (startDay, endDay) which describes the date interval that the user wants to remoev or None if there is a command syntax error :raise CommandError, ValueError, SyntaxError ''' if command[1] != 'from' or command[3] != 'to': raise CommandError("Remove command - Syntax Error!") if representsInt(command[2]) == False or representsInt( command[4]) == False: raise InvalidParameters("Remove command - Dates should be integers!") if int(command[2]) <= 0: raise InvalidParameters("Remove command - Days should be strictly!") startDate = int(command[2]) endDate = int(command[4]) if startDate > endDate: raise InvalidParameters( "Remove command - Dates do not form an interval!") return (startDate, endDate)
def execute(self, *args): self._protocol.write_response(self._fh, args) resp = self._protocol.handle_request(self._fh) if isinstance(resp, Error): raise CommandError(resp.message) return resp
def test_command_error(self): cmd = "" with self.assertRaises(CommandError) as context: if cmd == "": raise CommandError("Enter is not an option.") self.assertTrue("\n[COMMAND ERROR] -> Enter is not an option." in str(context.exception))
def callCommand(self, commands, command): #calls the specific function in a given dict if command not in commands: raise CommandError(str(command) + " is not an option.") commands[command]()