Best Python code snippet using autotest_python
mock.py
Source:mock.py
...24class equality_comparator(argument_comparator):25 def __init__(self, value):26 self.value = value27 @staticmethod28 def _types_match(arg1, arg2):29 if isinstance(arg1, basestring) and isinstance(arg2, basestring):30 return True31 return type(arg1) == type(arg2)32 @classmethod33 def _compare(cls, actual_arg, expected_arg):34 if isinstance(expected_arg, argument_comparator):35 return expected_arg.is_satisfied_by(actual_arg)36 if not cls._types_match(expected_arg, actual_arg):37 return False38 if isinstance(expected_arg, list) or isinstance(expected_arg, tuple):39 # recurse on lists/tuples40 if len(actual_arg) != len(expected_arg):41 return False42 for actual_item, expected_item in zip(actual_arg, expected_arg):43 if not cls._compare(actual_item, expected_item):44 return False45 elif isinstance(expected_arg, dict):46 # recurse on dicts47 if not cls._compare(sorted(actual_arg.keys()),48 sorted(expected_arg.keys())):49 return False50 for key, value in actual_arg.iteritems():...
validator.py
Source:validator.py
2from StructNoSQL.models import DatabasePathElement3from StructNoSQL.fields import BaseItem, BaseField, MapModel, DictModel4from StructNoSQL.practical_logger import message_with_vars5from StructNoSQL.utils.misc_fields_items import try_to_get_primitive_default_type_of_item6def _types_match(type_to_check: type, expected_type: type) -> bool:7 processed_expected_type: type = try_to_get_primitive_default_type_of_item(expected_type)8 # The type_to_check will always be a primitive Python type, where as the expected_type can also be a StructNoSQL9 # model type. In which case, we try_to_get_primitive_default_type_of_item. If the type was not a StructNoSQL10 # model type and did not had a primitive_default_type, the returned type will be the source type we passed.11 if processed_expected_type is Any:12 return True13 elif type_to_check != processed_expected_type:14 return False15 return True16def validate_data(17 value: Any, expected_value_type: Any,18 item_type_to_return_to: Optional[BaseItem] = None19) -> Tuple[Any, bool]:20 value_type = type(value)21 # We do not try_to_get_primitive_default_type_of_item here, because depending on the value_type, we might trigger different behaviors.22 # For example, a list or tuple will be considered as collection of multiple fields types that needs to be looked at individually.23 if expected_value_type == Any:24 return value, True25 if type(expected_value_type) in [list, tuple]:26 has_found_match = False27 for acceptable_value_type in expected_value_type:28 if _types_match(type_to_check=value_type, expected_type=acceptable_value_type):29 has_found_match = True30 break31 if has_found_match is not True:32 vars_dict = {'value': value, 'valueType': value_type, 'expectedValueType': expected_value_type}33 if item_type_to_return_to is not None:34 vars_dict['itemExpectedTypeDatabasePath'] = item_type_to_return_to.database_path35 print(message_with_vars(36 message=f"Primitive value did not match any of the possible "37 f"expected types. Value of None is being returned.",38 vars_dict=vars_dict39 ))40 return None, False41 else:42 if not _types_match(type_to_check=value_type, expected_type=expected_value_type):43 vars_dict = {'value': value, 'valueType': value_type, 'expectedValueType': expected_value_type}44 if item_type_to_return_to is not None:45 vars_dict['itemExpectedTypeDatabasePath'] = item_type_to_return_to.database_path46 print(message_with_vars(47 message=f"Primitive value did not match expected "48 f"type. Value of None is being returned.",49 vars_dict=vars_dict50 ))51 return None, False52 if value_type == dict:53 value: dict54 # todo: fix a bug, where for some reasons, when calling the get_field function, if what55 # we get is a dict that has only key and one item, instead of returning the dict, we will return the value in the dict56 item_keys_to_pop: List[str] = []57 if item_type_to_return_to is not None:58 if (59 item_type_to_return_to.map_model is not None and60 not isinstance(item_type_to_return_to.map_model, DictModel)61 ):62 populated_required_fields: List[BaseField] = []63 item_keys_to_pop: List[str] = []64 for key, item in value.items():65 item_matching_validation_model_variable: Optional[BaseField] = getattr(item_type_to_return_to.map_model, key, None)66 if item_matching_validation_model_variable is not None:67 item, valid = validate_data(68 value=item, item_type_to_return_to=item_matching_validation_model_variable,69 expected_value_type=item_matching_validation_model_variable.field_type70 )71 if valid is True:72 value[key] = item73 if item_matching_validation_model_variable.required is True:74 populated_required_fields.append(item_matching_validation_model_variable)75 else:76 item_keys_to_pop.append(key)77 else:78 item_keys_to_pop.append(key)79 print(message_with_vars(80 message=f"No map validator was found in a nested item of a dict. Item will be removed from data.",81 vars_dict={"key": key, "item": item}82 ))83 map_model_required_fields: Optional[List[BaseField]] = getattr(item_type_to_return_to.map_model, 'required_fields', None)84 if map_model_required_fields is None:85 raise Exception("Missing required_fields")86 if len(map_model_required_fields) != len(populated_required_fields):87 missing_required_fields_database_paths: List[List[DatabasePathElement]] = []88 for current_required_field in map_model_required_fields:89 if current_required_field not in populated_required_fields:90 missing_required_fields_database_paths.append(current_required_field.database_path)91 print(message_with_vars(92 message="Missing required fields on map element. Returning None and valid to False.",93 vars_dict={"missingRequiredFieldsDatabasePaths": missing_required_fields_database_paths}94 ))95 return None, False96 else:97 for key, item in value.items():98 if item_type_to_return_to.key_expected_type is not None:99 key_type = type(key)100 if not _types_match(type_to_check=key_type, expected_type=item_type_to_return_to.key_expected_type):101 print(message_with_vars(102 message=f"Key of an item in a dict did not match expected key type. Item will be removed from data.",103 vars_dict={"key": key, "item": item, "keyType": key_type, "expectedKeyType": item_type_to_return_to.key_expected_type}104 ))105 item_keys_to_pop.append(key)106 continue107 if item_type_to_return_to.items_excepted_type is not None:108 if hasattr(item_type_to_return_to.items_excepted_type, '__bases__') and MapModel in item_type_to_return_to.items_excepted_type.__bases__:109 # We check if the items_excepted_type contains the __bases__ attributes, because form values (like the Any value that is assigned both when110 # using an untyped dict or when using Any in a typed Dict) will not contain the __bases__ attribute and will raise if trying to access it.111 element_item_keys_to_pop: List[str] = []112 item_type = type(item)113 if not _types_match(type_to_check=item_type, expected_type=dict):114 print(message_with_vars(115 message=f"Received data that should be set inside a nested MapModel "116 f"was not of type dict. Item will be removed from data.",117 vars_dict={"key": key, "item": item, "itemType": item_type}118 ))119 item_keys_to_pop.append(key)120 continue121 item: dict122 item_matching_validation_model_variable: Optional[BaseField] = getattr(item_type_to_return_to.map_model, key, None)123 if item_matching_validation_model_variable is not None:124 for element_item_key, element_item_value in item.items():125 element_item_matching_validation_model_variable: Optional[BaseField] = getattr(126 item_matching_validation_model_variable, element_item_key, None127 )128 if element_item_matching_validation_model_variable is not None:129 element_item_value, valid = validate_data(130 value=element_item_value, item_type_to_return_to=element_item_matching_validation_model_variable,131 expected_value_type=element_item_matching_validation_model_variable.field_type,132 )133 if valid is True:134 item[element_item_key] = element_item_value135 else:136 if element_item_matching_validation_model_variable.required is not True:137 element_item_keys_to_pop.append(element_item_key)138 else:139 item_keys_to_pop.append(key)140 break141 else:142 element_item_keys_to_pop.append(element_item_key)143 print(message_with_vars(144 message=f"No map validator was found in a nested item of a dict. Item will be removed from data.",145 vars_dict={"elementItemKey": key, "elementItemValue": element_item_value}146 ))147 else:148 print(message_with_vars(149 message=f"No map validator was found in a item of a dict. Item will be removed from data.",150 vars_dict={"itemKey": key, "itemValue": item}151 ))152 for element_item_key_to_pop in element_item_keys_to_pop:153 item.pop(element_item_key_to_pop)154 else:155 if not _types_match(type_to_check=type(item), expected_type=item_type_to_return_to.items_excepted_type):156 item_keys_to_pop.append(key)157 print(message_with_vars(158 message=f"Value of nested item of dict did not match expected type. Item will be removed from data.",159 vars_dict={"item": item, "itemKey": key, "expectedItemValueType": item_type_to_return_to.items_excepted_type}160 ))161 else:162 value[key] = item163 num_dict_items = len(value)164 if num_dict_items > 0 and (len(item_keys_to_pop) == num_dict_items):165 print(message_with_vars(166 message="The value dict to validate was not empty, but all of its items have been "167 "removed because they did not matched the model. Value of None is returned.",168 vars_dict={"value": value, "item_keys_to_pop": item_keys_to_pop}169 ))170 return None, False171 else:172 for item_key_to_pop in item_keys_to_pop:173 value.pop(item_key_to_pop)174 return value, True175 elif value_type == list:176 value: list177 if True: # list_items_models is not None: # todo: add type checking fo list models178 indexes_to_pop: List[int] = []179 for i, item in enumerate(value):180 if item_type_to_return_to.map_model is not None:181 item, valid = validate_data(182 value=item, expected_value_type=item_type_to_return_to.map_model,183 )184 if valid is False:185 indexes_to_pop.append(i)186 elif item_type_to_return_to.items_excepted_type is not None:187 item, valid = validate_data(188 value=item, expected_value_type=item_type_to_return_to.items_excepted_type,189 )190 if valid is False:191 indexes_to_pop.append(i)192 # If no map validator has been found, this means we have an untyped list. So, we will193 # not perform any data validation on the list items and consider all the items valid.194 """else:195 indexes_to_pop.append(i)196 print(message_with_vars(197 message=f"No map validator was found in a nested item of a list. Value will be removed from data.",198 vars_dict={"listValue": value, "item": item, "itemIndex": i}199 ))"""200 indexes_to_pop.reverse()201 for index in indexes_to_pop:202 value.pop(index)203 elif value_type == set:204 value: set205 if item_type_to_return_to.items_excepted_type is not None:206 items_keys_values_to_remove = []207 for set_item in value:208 item_type = type(set_item)209 if not _types_match(type_to_check=item_type, expected_type=item_type_to_return_to.items_excepted_type):210 items_keys_values_to_remove.append(set_item)211 print(message_with_vars(212 message=f"Value of item of set did not match expected type. Item will be removed from data.",213 vars_dict={'item': set_item, 'itemType': item_type, 'expectedItemValueType': item_type_to_return_to.items_excepted_type}214 ))215 num_set_items = len(value)216 if num_set_items > 0 and (len(items_keys_values_to_remove) == num_set_items):217 print(message_with_vars(218 message="The value set to validate was not empty, but all of its items have been "219 "removed because they did not matched the model. Value of None is returned.",220 vars_dict={'value': value, 'itemsToRemove': items_keys_values_to_remove}221 ))222 return None, False223 else:...
ast.py
Source:ast.py
...18 I16 = Type('untyped_int', 'signed short')19 I32 = Type('untyped_int', 'signed long')20 I64 = Type('untyped_int', 'signed long long')21 UNTYPED_INT = Type('', '')22def _types_match(first_type: Types, second_type: Types) -> bool:23 untyped_type = None24 concrete_type = None25 if first_type in (Types.UNTYPED_INT,):26 untyped_type = first_type27 elif second_type in (Types.UNTYPED_INT,):28 untyped_type = second_type29 if first_type not in (Types.UNTYPED_INT,):30 concrete_type = first_type31 elif second_type not in (Types.UNTYPED_INT,):32 concrete_type = second_type33 if untyped_type is None:34 return first_type == second_type35 elif untyped_type == Types.UNTYPED_INT and concrete_type.value.base_type == 'untyped_int':36 return True37 38 return False39Expression = Union['Identifier', 'Integer']40Stmt = 'Assignment'41class Program:42 def __init__(self, stmts: "list['Stmt']") -> None:43 self._stmts = stmts44 def gen_code(self) -> str:45 program = ''46 for stmt in self._stmts:47 program += f' {stmt.gen_code()}\n'48 return PROGRAM_TEMPLATE.format(program.rstrip('\n')).lstrip('\n')49class Assignment:50 def __init__(self, type_tok: Token, ident: 'Identifier', expression: 'Expression') -> None:51 self._type_tok = type_tok52 self._ident = ident53 self._assignment_type = Types[type_tok.value.upper()]54 self._expression = expression55 def resolve_type(self):56 expr_type = self._expression.resolve_type()57 if not _types_match(expr_type, self._assignment_type):58 error(59 MISMATCHED_TYPES.format(expr_type.name.lower(), self._assignment_type.name.lower()),60 self._type_tok.line,61 self._type_tok.column62 )63 64 def gen_code(self) -> str:65 self.resolve_type()66 return '{} {} = {};'.format(67 # Make sure to use the type of the assignment here, since the type68 # of the expression may be an unconcrete type, like untyped int.69 self._assignment_type.value.c_name, 70 self._ident.gen_code(),71 self._expression.gen_code()...
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!!