Best Python code snippet using autotest_python
comparer.py
Source:comparer.py
...72 self.config_file_right = right_filename73 #self.load_files()74 #self.parse_files()75 76 def _parse_config_line(self, buff):77 """78 [Internal Function] Config line parser.79 This parser is designed to parse a single config line.80 A config line can be in normal format, also can be a comment. This function81 will parse them properly.82 It is called by parse_files().83 Parameters:84 buff - the config line to be parsed.85 Returns:86 A tuple of parsed config item. 87 Format is (CONFIG_NAME, CONFIG_VALUE).88 """89 # Regex to parse config items. Format is "CONFIG_XXXX=<value>".90 # All spaces wrapping the equal mark, and trailing spaces, will be trimmed.91 # NOTICE: items not leading with "CONFIG_" or having leading spaces92 # will be WARNED by kernel's lexer.93 # e.g.94 # ( â )CONFIG_I_AM_NORMAL_ITEM=y95 # ( â )CONFIG_SPACES_WRAPPED_EQUAL_MARK = y96 # ( Ã )I_AM_NOT_LEAD_WITH_CONFIG=y97 # ( Ã ) CONFIG_I_HAVE_LEADING_SPACES=y98 config_item_matcher = re.compile(r"^(CONFIG_.*?)\s*=\s*(\S*)")99 config_name = ""100 config_value = Unset101 # Check comment102 if re.match(r'\s*#', buff):103 # Check if it is an explicitly unset item104 if buff.find("is not set") > -1:105 config_name = re.findall(r"(CONFIG_.*?)\s", buff)[0]106 config_value = Unset107 return (config_name, config_value)108 # If not, ignore it, then return false109 else:110 return False111 # If there's no comment, it could be a valid config item112 elif config_item_matcher.match(buff):113 parse_result = config_item_matcher.findall(buff)114 config_name = parse_result[0][0]115 config_value = parse_result[0][1]116 return (config_name, config_value)117 # Otherwise, omit.118 # The process above will filter illegal inputs, 119 # so finally you will get an empty config_{left,right}.120 return False121 def load_files(self):122 """123 Load config files.124 Parameters:125 No need of parameters, as filenames are specified in config_file_left(right).126 Behavior:127 This function will call open() to open config files in TEXT FORMAT.128 If exceptions occur, it will directly print an error message, 129 then exit Karison.130 """131 # TODO: Raise error if non-text file detected.132 try:133 self.f_left = open(self.config_file_left, "r")134 self.f_right = open(self.config_file_right, "r")135 except FileNotFoundError as e:136 err_fatal("File not found: %s" % e.filename)137 sys.exit(ExitValues.EXIT_FATAL)138 except IsADirectoryError as e:139 err_error("Given path is a directory: %s" % e.filename)140 sys.exit(ExitValues.EXIT_ERROR)141 except PermissionError as e:142 err_error("Permission denied while reading %s" % e.filename)143 sys.exit(ExitValues.EXIT_ERROR)144 except Exception as e:145 err_other_exception(e)146 sys.exit(ExitValues.EXIT_ERROR)147 def parse_files(self):148 """149 Parse config files.150 Parameters:151 No need of parameters, as filenames are specified in config_file_left(right).152 Returns:153 No need of returns, as parsed data will store in config_left(right).154 Data Format:155 config_left(right) is a dict, its format is:156 { 'CONFIG_NAME': value, ... }157 """158 # Won't allow that file is not open159 if not self.f_left or not self.f_right:160 raise ValueError("You must run load_files() to load config files properly.")161 # Seek from head, as you may call this function several times162 self.f_left.seek(0)163 self.f_right.seek(0)164 # Parse config files165 # NOTICE:166 # Here I will gather duplicated items.167 # In kernel compilation, if the lexer has found duplicated items,168 # the value appears at last will be accepted, and A WARNING WILL OCCUR.169 # So I will also warn if you have duplicated items in input files.170 # If non-text character found (usually you inputed binary file(s)),171 # treat as fatal error, then exit.172 # How to determine if a non-text char exists? Focus on UnicodeDecodeError.173 try: # Ready to catch decode error174 # (1) Parse the left one175 while True:176 buff = self.f_left.readline()177 if not buff: # reached EOF178 break179 180 p = self._parse_config_line(buff)181 if p: 182 # Gather duplicated items183 if p[0] in self.config_left.keys():184 self.duplicated_items_left.add( p[0] )185 self.config_left[ p[0] ] = p[1]186 except UnicodeDecodeError:187 err_fatal("Your left input file is not a valid text file (may be binary). Karison will exit.")188 sys.exit(ExitValues.EXIT_FATAL)189 try:190 # (2) Parse the right one191 while True:192 buff = self.f_right.readline()193 if not buff: # reached EOF194 break195 196 p = self._parse_config_line(buff)197 if p:198 # Gather duplicated items199 if p[0] in self.config_right.keys():200 self.duplicated_items_right.add( p[0] )201 self.config_right[ p[0] ] = p[1]202 except UnicodeDecodeError:203 err_fatal("Your right input file is not a valid text file (may be binary). Karison will exit.")204 sys.exit(ExitValues.EXIT_FATAL)205 # Warn if the process ends up with an empty result.206 # This is usually because the user passes an invalid or empty file,207 # whose lines will be omitted by the parser.208 # Usually a kernel config file has string "CONFIG_" at least.209 if len(self.config_left.keys()) <= 0 or len(self.config_right.keys()) <= 0:210 err_error(textwrap.dedent("Your input file is not a valid kernel config file. Karison will discontinue."))...
commands.py
Source:commands.py
...65 def __init__(self, *args, **kwargs):66 super(Commands, self).__init__(*args, **kwargs)67 self.init()68 @staticmethod69 def _parse_config_line(value, **command_kwargs):70 """Parse one config value"""71 value = value.strip().split(',')72 cmd = value.pop(0).strip()73 doc = ''74 for i, opt in enumerate(value):75 opt = opt.strip()76 if opt == 'command':77 continue78 elif opt in COMMAND_FLAGS:79 cmd_flag = COMMAND_FLAGS[opt]80 command_kwargs[cmd_flag[0]] = cmd_flag[1]81 else:82 doc = ','.join(value[i:]).strip()83 break84 return cmd, command(**command_kwargs), doc85 @staticmethod86 def _get_fun(name, cmd, command_decorator, doc):87 """Return dynamic function"""88 def fun(obj, msg, *args):89 # noinspection PyProtectedMember90 return obj._execute(msg, name, cmd, *args)91 fun.__name__ = name92 fun.__doc__ = doc93 return command_decorator(fun)94 def init(self):95 """Initialize commands from config file"""96 logger.debug('Initializing dynamic commands')97 for name, value in self.config.items():98 try:99 fun_name = name.strip().replace('-', '_')100 if fun_name == 'pass_through':101 _, cmd_decorator, doc = self._parse_config_line(value, parse_parameters=False)102 fun = self._get_fun(fun_name, None, cmd_decorator, doc)103 else:104 fun = self._get_fun(fun_name, *self._parse_config_line(value))105 if fun:106 logger.info('Registering dynamic command: %s', name)107 setattr(self, fun_name, MethodType(fun, self))108 else:109 raise ValueError('Error while decorating dynamic command function')110 except Exception as e:111 logger.error('Dynamic command "%s" could not be registered (%s)', name, e)112 @property113 def _pass_through_mode(self):114 return bool(getattr(self, 'pass_through', False))115 def __post_init__(self):116 if self._pass_through_mode:117 logger.warning('You have enabled pass-through mode in the commands plugin. '118 '_ALL_ bot commands will be passed to the operating system!')...
config_parser.py
Source:config_parser.py
...70class VsftpdConfigParser(object):71 def __init__(self, config_content):72 self._option_parser = VsftpdConfigOptionParser()73 self.parsed_config = self._parse_config(config_content)74 def _parse_config_line(self, line, conf_dict):75 if not line or line.startswith('#') or line.isspace():76 return77 try:78 option, value = line.split('=', 1)79 except ValueError:80 raise ParsingError("The line does not have the form 'option=value': %s" % line)81 option = option.strip()82 value = value.strip()83 value = self._option_parser.parse_value(option, value)84 conf_dict[option] = value85 def _parse_config(self, contents):86 res = {}87 try:88 for (ix, line) in enumerate(contents.split('\n')):89 self._parse_config_line(line, res)90 return res91 except ParsingError as e:...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!