Best Python code snippet using toolium_python
dataset.py
Source:dataset.py
...90 # String transformations that do not allow type inference91 new_param, param_replaced = _replace_param_transform_string(new_param)92 if not param_replaced and infer_param_type:93 # Type inference94 new_param = _infer_param_type(new_param)95 if param != new_param:96 if type(new_param) == str:97 logger.debug(f'Replaced param from "{param}" to "{new_param}"')98 else:99 logger.debug(f'Replaced param from "{param}" to {new_param}')100 return new_param101def _replace_param_type(param):102 """103 Replace param with a new param type.104 Available replacements: [MISSING_PARAM], [TRUE], [FALSE], [NULL]105 :param param: parameter value106 :return: tuple with replaced value and boolean to know if replacement has been done107 """108 param_types = {109 '[MISSING_PARAM]': None,110 '[TRUE]': True,111 '[FALSE]': False,112 '[NULL]': None113 }114 new_param = param115 param_replaced = False116 for key in param_types.keys():117 if key in param:118 new_param = param_types[key]119 param_replaced = True120 break121 return new_param, param_replaced122def _find_param_date_expressions(param):123 """124 Finds in a param one or several date expressions. 125 For example, for a param like "it happened on [NOW - 1 MONTH] of the last year and will happen [TODAY('%d/%m')]",126 this method returns an array with two string elements: "[NOW - 1 MONTH]" and [TODAY('%d/%m')]"127 The kind of expressions to search are based on these rules:128 - expression is sorrounded by [ and ]129 - first word of the expression is either NOW or TODAY130 - when first word is NOW, it can have an addtional format for the date between parenthesis, 131 like NOW(%Y-%m-%dT%H:%M:%SZ). The definition of the format is the same as considered by the132 python strftime function of the datetime module133 - and optional offset can be given by indicating how many days, hours, etc.. to add or remove to the current datetime.134 This part of the expression includes a +/- symbol plus a number and a unit135 Some valid expressions are:136 [NOW]137 [TODAY]138 [NOW(%Y-%m-%dT%H:%M:%SZ)]139 [NOW(%Y-%m-%dT%H:%M:%SZ) - 180 DAYS]140 [NOW(%H:%M:%S) + 4 MINUTES]141 :param param: parameter value142 :param language: language to configure date format for NOW and TODAY143 :return: An array with all the matching date expressions found in the param144 """145 return re.findall(r"\[(?:NOW(?:\((?:[^\(\)]*)\))?|TODAY)(?:\s*[\+|-]\s*\d+\s*\w+\s*)?\]", param)146def _replace_param_replacement(param, language):147 """148 Replace param with a new param value.149 Available replacements: [EMPTY], [B], [RANDOM], [TIMESTAMP], [DATETIME], [NOW], [TODAY]150 :param param: parameter value151 :param language: language to configure date format for NOW and TODAY152 :return: tuple with replaced value and boolean to know if replacement has been done153 """154 date_format = '%d/%m/%Y %H:%M:%S' if language == 'es' else '%Y/%m/%d %H:%M:%S'155 date_day_format = '%d/%m/%Y' if language == 'es' else '%Y/%m/%d'156 alphanums = ''.join([string.ascii_lowercase, string.digits]) # abcdefghijklmnopqrstuvwxyz0123456789157 replacements = {158 '[EMPTY]': '',159 '[B]': ' ',160 # make sure random is not made up of digits only, by forcing the first char to be a letter161 '[RANDOM]': ''.join([r.choice(string.ascii_lowercase), *(r.choice(alphanums) for i in range(7))]),162 '[RANDOM_PHONE_NUMBER]': ''.join(['+', '3', '4', '6', '5', '4'] + [str(r.randint(0, 9)) for i in range(1, 7)]),163 '[TIMESTAMP]': str(int(datetime.datetime.timestamp(datetime.datetime.utcnow()))),164 '[DATETIME]': str(datetime.datetime.utcnow()),165 '[NOW]': str(datetime.datetime.utcnow().strftime(date_format)),166 '[TODAY]': str(datetime.datetime.utcnow().strftime(date_day_format))167 }168 169 # append date expressions found in param to the replacement dict 170 date_expressions = _find_param_date_expressions(param)171 for date_expr in date_expressions:172 replacements[date_expr] = _replace_param_date(date_expr, language)[0]173 new_param = param174 param_replaced = False175 for key in replacements.keys():176 if key in new_param:177 new_param = new_param.replace(key, replacements[key])178 param_replaced = True179 return new_param, param_replaced180def _replace_param_transform_string(param):181 """182 Transform param value according to the specified prefix.183 Available transformations: DICT, LIST, INT, FLOAT, STR, UPPER, LOWER184 :param param: parameter value185 :return: tuple with replaced value and boolean to know if replacement has been done186 """187 type_mapping_regex = r'\[(DICT|LIST|INT|FLOAT|STR|UPPER|LOWER):(.*)\]'188 type_mapping_match_group = re.match(type_mapping_regex, param)189 new_param = param190 param_transformed = False191 if type_mapping_match_group:192 param_transformed = True193 if type_mapping_match_group.group(1) == 'STR':194 new_param = type_mapping_match_group.group(2)195 elif type_mapping_match_group.group(1) in ['LIST', 'DICT', 'INT', 'FLOAT']:196 exec('exec_param = {type}({value})'.format(type=type_mapping_match_group.group(1).lower(),197 value=type_mapping_match_group.group(2)))198 new_param = locals()['exec_param']199 elif type_mapping_match_group.group(1) == 'UPPER':200 new_param = type_mapping_match_group.group(2).upper()201 elif type_mapping_match_group.group(1) == 'LOWER':202 new_param = type_mapping_match_group.group(2).lower()203 return new_param, param_transformed204def _replace_param_date(param, language):205 """206 Transform param value in a date after applying the specified delta.207 E.g. [TODAY - 2 DAYS], [NOW - 10 MINUTES]208 An specific format could be defined in the case of NOW this way: NOW('THEFORMAT')209 where THEFORMAT is any valid format accepted by the python 210 [datetime.strftime](https://docs.python.org/3/library/datetime.html#datetime.date.strftime) function 211 :param param: parameter value212 :param language: language to configure date format for NOW and TODAY213 :return: tuple with replaced value and boolean to know if replacement has been done214 """215 def _date_matcher():216 return re.match(r'\[(NOW(?:\((?:.*)\)|)|TODAY)(?:\s*([\+|-]\s*\d+)\s*(\w+)\s*)?\]', param)217 def _offset_datetime(amount, units):218 now = datetime.datetime.utcnow()219 if not amount or not units:220 return now221 the_amount = int(amount.replace(' ',''))222 the_units = units.lower()223 return now + datetime.timedelta(**dict([(the_units, the_amount)]))224 def _is_only_date(base):225 return 'TODAY' in base226 def _default_format(base):227 date_format = '%d/%m/%Y' if language == 'es' else '%Y/%m/%d'228 if _is_only_date(base):229 return date_format230 return f'{date_format} %H:%M:%S'231 def _get_format(base):232 format_matcher = re.match(r'.*\((.*)\).*', base)233 if format_matcher and len(format_matcher.groups()) == 1:234 return format_matcher.group(1)235 return _default_format(base)236 matcher = _date_matcher()237 if not matcher:238 return param, False239 base, amount, units = list(matcher.groups())240 format_str = _get_format(base)241 date = _offset_datetime(amount, units)242 return date.strftime(format_str), True243def _replace_param_fixed_length(param):244 """245 Generate a fixed length data element if param matches the expression [<type>_WITH_LENGTH_<length>]246 where <type> can be: STRING, INTEGER, STRING_ARRAY, INTEGER_ARRAY, JSON.247 E.g. [STRING_WITH_LENGTH_15]248 :param param: parameter value249 :return: tuple with replaced value and boolean to know if replacement has been done250 """251 new_param = param252 param_replaced = False253 if param.startswith('[') and param.endswith(']'):254 if any(x in param for x in ['STRING_ARRAY_WITH_LENGTH_', 'INTEGER_ARRAY_WITH_LENGTH_']):255 seeds = {'STRING': 'a', 'INTEGER': 1}256 seed, length = param[1:-1].split('_ARRAY_WITH_LENGTH_')257 new_param = list(seeds[seed] for x in range(int(length)))258 param_replaced = True259 elif 'JSON_WITH_LENGTH_' in param:260 length = int(param[1:-1].split('JSON_WITH_LENGTH_')[1])261 new_param = dict((str(x), str(x)) for x in range(length))262 param_replaced = True263 elif any(x in param for x in ['STRING_WITH_LENGTH_', 'INTEGER_WITH_LENGTH_']):264 seeds = {'STRING': 'a', 'INTEGER': '1'}265 # The chain to be generated can be just a part of param266 start = param.find('[')267 end = param.find(']')268 seed, length = param[start + 1:end].split('_WITH_LENGTH_')269 generated_part = seeds[seed] * int(length)270 placeholder = '[' + seed + '_WITH_LENGTH_' + length + ']'271 new_param = param.replace(placeholder, generated_part)272 param_replaced = True273 if seed == 'INTEGER':274 new_param = int(new_param)275 return new_param, param_replaced276def _infer_param_type(param):277 """278 Transform the param from a string representing a built-in data type or a JSON object/list to the279 corresponding built-in data type. If no conversion is possible, the original param is returned.280 E.g. "1234" -> 1234, "0.50" -> 0.5, "True" -> True, "None" -> None,281 "['a', None]" -> ['a', None], "{'a': None}" -> {'a': None},282 '["a", null]' -> ["a", None], '{"a": null}' -> {"a": None}283 :param param: data to be transformed284 :return data with the inferred type285 """286 new_param = param287 # attempt direct conversion to a built-in data type288 try:289 new_param = literal_eval(param)290 except Exception:...
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!!