Best Python code snippet using autotest_python
def_project.py
Source:def_project.py
...25 """Parses all the class files and generates a hash table with classname:classobj.""" 26 self.classlist = {}27 for classfile in self.filelist:28 classobj = ClassDef(classfile)29 self.classlist[classobj.get_classname()] = classobj30 def get_superclass (self, name):31 """Returns the super class of the class with the given name."""32 if self.classlist[name].get_supername() not in self.classlist: return None33 if self.classlist[name].get_supername().split('/')[0] == 'java': return None34 return self.classlist[self.classlist[name].get_supername()]35 def get_childclass (self, name):36 """Returns an array of classes inheriting from the class with the given name."""37 childlist = []38 for classentry in self.classlist.values():39 if classentry.get_supername() == name:40 childlist.append(classentry)41 return childlist42 def get_interfclass(self, name):43 """Returns an array of all the interfaces for the given class."""44 return [self.classlist[i] for i in self.classlist[name].get_intername() if i in self.classlist]45 def get_package(self, name):46 """Look for class in the class list and return the leading package. Careful to have different names in each package!"""47 for classname in self.classlist.keys():48 if classname.split('/')[-1] == name:49 return '/'.join(classname.split('/')[:-1])50 def get_allinterfaces(self):51 """Returns an array of all the interfaces in the current project."""52 if self.interfaces:53 return self.interfaces54 55 interfaces_list = []56 for classobj in self.classlist.values():57 interfaces_list.extend(classobj.get_intername())58 59 interfaces_list = set(interfaces_list)60 61 self.interfaces = interfaces_list62 return interfaces_list63 64 def get_impleminterfclass(self, name):65 """Returns an array of all the classes implementing a given interface."""66 implementlist = []67 for classentry in self.classlist.values():68 if name in classentry.get_intername():69 implementlist.append(classentry)70 return implementlist71 def get_implementinginterface(self, name):72 """Returns an array of all the classes implementing a given interface."""73 implementlist = []74 for classentry in self.classlist.values():75 if name in classentry.get_intername():76 implementlist.append(classentry.get_classname())77 return implementlist78 79 def get_classesref (self, name):80 """Returns all the class references in the given class."""81 return self.classlist[name].get_classref()82 def get_methodsref (self, name):83 """Returns all the methods references in the given class."""84 return self.classlist[name].get_methodsref()85 def get_fieldsref (self, name):86 """Returns all the fields references in the given class."""87 return self.classlist[name].get_fieldsref()88 def get_methods (self, name):89 """Returns all the methods in the given class."""90 return self.classlist[name].get_methods()91 def get_fields (self, name):92 """Returns all the fields in the given class."""93 return self.classlist[name].get_fields()94 def get_methods_fullname (self, name):95 """Returns all the methods in the given class."""96 return self.classlist[name].get_methods_fullname()97 def get_fields_fullname (self, name):98 """Returns all the fields in the given class."""99 return self.classlist[name].get_fields_fullname()100 def get_methods_desc (self, name):101 """Returns all the methods in the given class."""102 return self.classlist[name].get_methods_desc()103 def get_constructors (self, name):104 """Returns all the methods in the given class."""105 return self.classlist[name].get_constructors()106 def get_fields_desc (self, name):107 """Returns all the fields in the given class."""108 return self.classlist[name].get_fields_desc()109 def get_field_desc(self, classname, name):110 desc = None111 while not desc and self.get_superclass(classname):112 desc = self.classlist[classname].get_field_desc(classname, name)113 classname = self.get_superclass(classname).get_classname()114 return desc115 def get_method_desc(self, classname, name):116 desc = None117 while not desc and self.get_superclass(classname):118 desc = self.classlist[classname].get_method_desc(classname, name)119 classname = self.get_superclass(classname).get_classname()120 return desc 121 def get_method_desc_inclass(self, classobj, classname, name):122 return classobj.get_method_desc(classname, name)123 def get_field_desc_inclass(self, classobj, classname, name):124 return classobj.get_field_desc(classname, name)125 def get_ancestors (self, name):126 ancestor_class_list = []127 128 ancestor_class_list = [name]129 ancestor = self.get_superclass(name)130 while ancestor:131 ancestor_class_list.append(ancestor.get_classname())132 ancestor = self.get_superclass(ancestor.get_classname()) 133 134 return ancestor_class_list135 def get_children (self, name):136 children_class_list = []137 138 def recur_get_child(classobj, classlist):139 for child in self.get_childclass(classobj.get_classname()):140 classlist.append(child.get_classname())141 recur_get_child(child, classlist)142 143 recur_get_child(self.classlist[name], children_class_list) 144 145 return children_class_list146 def get_brothers (self, name):147 brothers = []148 if self.get_superclass(name):149 ancestor = self.get_superclass(name).get_classname()150 brothers = self.get_children(ancestor)151 return brothers152 def get_cousins (self, name):153 interfaces = [i.get_classname() for i in self.get_interfclass(name)]154 cousins = []155 for i in interfaces:156 cousins.extend(self.get_implementinginterface(i))157 return cousins158 def get_uncles (self,name):159 ancestors = self.get_ancestors(name)160 interfaces = []161 for i in ancestors:162 interfaces.extend(self.get_interfaces(i))163 uncles = []164 for i in interfaces:165 uncles.extend(self.get_implementinginterface(i))166 return uncles167 def get_interfaces (self, name):168 return [i.get_classname() for i in self.get_interfclass(name)]169 def get_inherit_tree (self, name):170 """Returns an array containing both the parents, interfaces and children names of a given class."""171 172 if name in self.inherit_trees:173 return self.inherit_trees[name]174 175 ancestor_class_list = []176 177 ancestor_class_list = [name]178 ancestor = self.get_superclass(name)179 while ancestor:180 ancestor_class_list.append(ancestor.get_classname())181 ancestor = self.get_superclass(ancestor.get_classname()) 182 inter_class_list = []183 for classname in ancestor_class_list:184 inter_class_list.append(classname)185 for interface in self.get_interfclass(classname):186 inter_class_list.append(interface.get_classname())187 188 def recur_get_child(classobj, classlist):189 for child in self.get_childclass(classobj.get_classname()):190 classlist.append(child.get_classname())191 recur_get_child(child, classlist)192 193 recur_get_child(self.classlist[name], inter_class_list)194 inter_class_list = set(inter_class_list)195 196 #for entry in inter_class_list:197 self.inherit_trees[name] = inter_class_list198 199 return inter_class_list200 def get_full_inherit_tree (self, name):201 """Returns an array containing both the parents, interfaces and children names of a given class."""202 203 if name in self.inherit_full_trees:204 return self.inherit_full_trees[name]205 206 ancestor_class_list = []207 208 ancestor_class_list = [name]209 ancestor = self.get_superclass(name)210 while ancestor:211 ancestor_class_list.append(ancestor.get_classname())212 ancestor = self.get_superclass(ancestor.get_classname()) 213 214 def recur_get_child(classobj, classlist):215 for child in self.get_childclass(classobj.get_classname()):216 classlist.append(child.get_classname())217 recur_get_child(child, classlist)218 219 child_class_list = []220 for ances_class in ancestor_class_list:221 child_class_list.append(ances_class)222 recur_get_child(self.classlist[ances_class], child_class_list)223 inter_class_list = []224 for classname in child_class_list:225 inter_class_list.append(classname)226 for interface in self.get_interfclass(classname):227 inter_class_list.append(interface.get_classname())228 implem_class_list = []229 for classname in inter_class_list:230 implem_class_list.append(classname)231 for interface in self.get_impleminterfclass(classname):232 implem_class_list.append(interface.get_classname()) 233 implem_class_list = set(implem_class_list)234 235 for entry in implem_class_list:236 self.inherit_full_trees[entry] = implem_class_list237 238 return implem_class_list239 def apply_changes(self, name):240 self.classlist[name].apply_changes()241 def find_classes_implementing(self, member_type, name):242 """Returns an array of all the classes implementing a certain method/field.243 The method/field is given by its full name, including package and class (ie: /net/minecraft/src/Block/func_xxxx)."""244 class_name = '/'.join(name.split('/')[:-1])245 member_name = name.split('/')[-1]246 247 if not class_name in self.classlist:248 return []249 #raise Warning('Invalid class. Not found !')250 251 #if not member_name in self.classlist[class_name].get_members(member_type):252 # return []253 #raise Warning('Invalid %s %s for class %s. Not found !'%(member_type, member_name, class_name))254 #inherit_list = self.get_full_inherit_tree(class_name)255 inherit_list = self.get_inherit_tree(class_name)256 class_list = []257 258 259 for classname in inherit_list:260 if member_name in self.classlist[classname].get_members(member_type):261 class_list.append(classname)262 return class_list263 def normalize_mapping_table (self, classname, mappingtable):264 """Take a class to be renamed and a mapping table. It looks at all the entries in the class, and compare them to the265 mapping table. It creates a mapping table with the proper matchings"""266 267 #First we get the list of method, class and field references from the class268 if classname not in self.classlist:269 sys.stderr.write('ERROR : Class file for %s not found. Please check your compilation logs for errors.\n'%classname)270 sys.exit(0)271 272 ref = {}273 ref['Class'] = self.get_classesref(classname)274 ref['Method'] = self.get_methodsref(classname)275 ref['Field'] = self.get_fieldsref (classname)276 ref['Method'].extend(self.get_methods_fullname(classname))277 ref['Field'] .extend(self.get_fields_fullname(classname))278 279 #self.classlist[classname].print_fieldsref()280 #self.classlist[classname].print_methodsref()281 282 ref['Class'] = set(ref['Class'])283 ref['Method'] = set(ref['Method'])284 ref['Field'] = set(ref['Field'])285 286 member_array = []287 map_table = {}288 map_table['Class'] = {}289 map_table['Method'] = {}290 map_table['Field'] = {}291 292 if 'Class' in mappingtable:293 map_table['Class'] = mappingtable['Class']294 295 if 'Option' in mappingtable:296 map_table['Option'] = mappingtable['Option']297 map_table['Package'] = {}298 for entry in map_table['Option']:299 if entry['command'] == 'strip_package':300 map_table['Package'][entry['argument']] = '' 301 302 #Now we go through all the method references and check if we have a match in the hashtable303 members_keys = ['Method', 'Field']304 for member_key in members_keys:305 for member in ref[member_key]:306 307 308 member_name = member.split('/')[-1]309 member_class = '/'.join(member.split('/')[:-1])310 member_sig = None311 if member_key == 'Method':312 member_sig = self.get_method_desc_inclass(self.classlist[classname], member_class, member_name)313 if member_sig:314 #We obfuscate the signature for comparison315 sig_regex = r'L([\w/]+);'316 results = re.findall(sig_regex, member_sig)317 for result in results:318 try:319 pack_result = '/'.join(result.split('/')[:-1])320 member_sig = member_sig.replace('L%s;'%result, 'L%s/%s;'%(pack_result, mappingtable['Class'][result]))321 except:322 pass323 for orig, dest in map_table['Package'].items():324 if dest == '':325 orig += '/'326 327 member_sig = member_sig.replace(orig, dest)328 329 #This is to protect all the methods & fields from outside the game.330 #If we have a class which is not in the map, we don't even consider renaming anything in it.331 if member_class not in self.classlist: continue332 333 #We don't care about creators, as they are renamed at the class renaming stage334 #Also some other protection on enums335 if member_name in ['<init>', '<clinit>', '_mthclass$']: continue336 337 #If the member is directly in the map, we just add it and continue338 if member in mappingtable[member_key]:339 map_table[member_key][member] = mappingtable[member_key][member]340 continue341 342 #We create a set of potential candidates343 candidate_list = [i for i in mappingtable[member_key].keys() if i.split('/')[-1] == member.split('/')[-1]]344 #For the methods, we check the signature345 if member_key == 'Method':346 candidate_list = [i for i in candidate_list if mappingtable['Signature'][i] == member_sig]347 if len([i for i in candidate_list if '/'.join(i.split('/')[:-1]) in self.get_children(member_class)]) == 1:348 candidate_list = [i for i in candidate_list if '/'.join(i.split('/')[:-1]) in self.get_children(member_class)]349 if len([i for i in candidate_list if '/'.join(i.split('/')[:-1]) in self.get_ancestors(member_class)]) == 1:350 candidate_list = [i for i in candidate_list if '/'.join(i.split('/')[:-1]) in self.get_ancestors(member_class)]351 if len([i for i in candidate_list if '/'.join(i.split('/')[:-1]) in self.get_brothers(member_class)]) == 1:352 candidate_list = [i for i in candidate_list if '/'.join(i.split('/')[:-1]) in self.get_brothers(member_class)]353 if len([i for i in candidate_list if '/'.join(i.split('/')[:-1]) in self.get_interfaces(member_class)]) == 1:354 candidate_list = [i for i in candidate_list if '/'.join(i.split('/')[:-1]) in self.get_interfaces(member_class)]355 if len([i for i in candidate_list if '/'.join(i.split('/')[:-1]) in self.get_implementinginterface(member_class)]) == 1:356 candidate_list = [i for i in candidate_list if '/'.join(i.split('/')[:-1]) in self.get_implementinginterface(member_class)]357 if len([i for i in candidate_list if '/'.join(i.split('/')[:-1]) in self.get_cousins(member_class)]) == 1:358 candidate_list = [i for i in candidate_list if '/'.join(i.split('/')[:-1]) in self.get_cousins(member_class)] 359 if len([i for i in candidate_list if '/'.join(i.split('/')[:-1]) in self.get_uncles(member_class)]) == 1:360 candidate_list = [i for i in candidate_list if '/'.join(i.split('/')[:-1]) in self.get_uncles(member_class)] 361 #We only have one possibility362 if len(candidate_list) == 1:363 map_table[member_key][member] = mappingtable[member_key][candidate_list[0]]364 continue365 print "\t+ Found %d potential candidates for %s %s"%(len(candidate_list), member, member_sig)366 for i in candidate_list:367 print "\t\t",i368 369 #If the member is not in the table, it means we don't have a good match370# if member not in map_table[member_key]:371# sys.stderr.write("WARNING : Cannot find a proper entry for %s %s. Will not be reobfuscated.\n"%(member_key, member))372 #=========OLD VERSION===========373 374 #Now, we have the case where the member is not in the mappingtable and is from a known class375 #We check if it is defined somewhere else in his own heritance tree376# member_family_array = [u'%s/%s'%(i,member_name) for i in self.get_inherit_tree(member_class)]377# for sibling in member_family_array:378# if sibling in mappingtable[member_key]:379# map_table[member_key][member] = mappingtable[member_key][sibling]380# break381 382# if member in map_table[member_key]: continue383 384 #We also check if the member is implemented somewhere else, as it would be the case for references.385# member_imp_array = ([u'%s/%s'%(i,member_name) for i in self.find_classes_implementing(member_key, member)])386# for implement in member_imp_array:387# if implement in mappingtable[member_key]:388# map_table[member_key][member] = mappingtable[member_key][implement]389# break390 391# if member in map_table[member_key]: continue392 393 #And the classes implementing a given interface394# class_itr_array = []395# for interface in self.get_allinterfaces():396# class_itr_array.extend(self.get_impleminterfclass(interface))397# member_itr_array = ([u'%s/%s'%(i.get_classname(),member_name) for i in class_itr_array])398# for implement in member_itr_array:399# if implement in mappingtable[member_key]:400# map_table[member_key][member] = mappingtable[member_key][implement]401# break 402 403# if member in map_table[member_key]: continue404 405 #Finally, the most dangerous case, a full tree search, up down and sideway. We HAVE to stop as soon as we are found one406# member_family_array = [u'%s/%s'%(i,member_name) for i in self.get_full_inherit_tree(member_class)]407# for sibling in member_family_array:408# if sibling in mappingtable[member_key]:409# map_table[member_key][member] = mappingtable[member_key][sibling]410# break411 412# if member in map_table[member_key]: continue413 414 #If the member is not in the table, it means we don't have a good match415# if member not in map_table[member_key]:416# print "WARNING : Cannot find a proper entry for %s %s. Will not be reobfuscated."%(member_key, member)417 418 return map_table419 def remap_all (self, classname, mappingtable):420 self.classlist[classname].remap_methods (mappingtable['Method'], mappingtable['Class'])421 self.classlist[classname].remap_fields (mappingtable['Field'], mappingtable['Class'])422 self.classlist[classname].remap_classes (mappingtable['Class'])423 def remap_packages (self, classname, mappingtable):424 self.classlist[classname].remap_packages(mappingtable['Package'])425 def write_class(self, classname, directory):426 class_path = self.classlist[classname].get_classname()427 if os.sep != '/': class_path = class_path.replace('/', os.sep)428 self.classlist[classname].write_class(os.path.join(directory, class_path + '.class'))429 def print_dbformat(self, classname):430 a = self.classlist[classname].get_classname()431 b = self.classlist[classname].get_supername()432 c = self.classlist[classname].get_intername()433 434 if b.split('/')[0] == 'java':435 b = 'null'436 437 buffer = '%s %s'%(a,str(b))438 for i in c:439 buffer += ' +%s'%i440 ...
model.py
Source:model.py
...18 def notify_listeners(self, event):19 for listener in self.listeners:20 listener.notify(event)21 def create(selfs, data):22 id = selfs.get_classname() + ":" + str(uuid.uuid4())23 selfs.attributes = data24 r.set(id, json.dumps(data))25 selfs.notify_listeners("create new " + selfs.get_classname())26 def update(selfs, data):27 selfs.attributes = data28 r.set(selfs.id, json.dumps(data))29 selfs.notify_listeners("update " + selfs.get_classname() + " (" + selfs.id + ") Set new attributes=" + str(data))30 def read(selfs, id=""):31 if (id):32 selfs.notify_listeners("read by id" + selfs.get_classname())33 else:34 selfs.notify_listeners("read all" + selfs.get_classname())35 out = []36 if (not id):37 keys = r.keys(selfs.get_classname() + ":*")38 else:39 keys = [id]40 for key in keys:41 if(not isinstance(key, str)):42 key = key.decode("utf-8")43 try:44 out.append({"key": key, "value": json.loads(r.get(key).decode("utf-8"))})45 except:46 print(key+" Not found")47 return out48 def delete(selfs):49 r.delete(selfs.id)50 selfs.notify_listeners("delete " + selfs.get_classname() + " (" + selfs.id + ")")51 @classmethod52 def get_classname(cls):53 return cls.__name__54 def use_classname(self):...
MRO_Raymond.py
Source:MRO_Raymond.py
1# https://www.youtube.com/watch?v=61UuKJRl2m0&feature=youtu.be2class A:3 def get_classname(self):4 return 'A'5class B(A):6 pass7class C(A):8 def get_classname(self):9 return 'C'10class D(B, C):11 pass12print(A().get_classname()) # A13print(B().get_classname()) # A14print(C().get_classname()) # C15print(D().get_classname()) # C16help(D)17print(D.__bases__)18"""19 A20 / \21B C22 \ /23 D24D -> B -> С -> A...
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!!