Best Python code snippet using autotest_python
methods.py
Source:methods.py
1from data.types import ModificationType2from data.parameters import MethodParameter3from utils.parsing import ParseMethod, ParseTestMethod, GetReturnType, GetAccessModifier, GetMethodName, \4 GetFullParameters5from typing import List, Tuple6import difflib7import re8java_test_annotations = ["@BeforeClass", "@AfterClass", "@Before", "@After", "@Test", "@Parameters",9 "@ParameterizedTest", "@MethodSource"]10modifiers = ["public", "protected", "private", "static", "final", "native", "synchronized", "abstract"]11class Method:12 """13 This class represents a method that contains various informations.14 """15 def __init__(self, func, sourceCode, commitInfo):16 self.name = func.name17 self.long_name = func.long_name18 self.parameters = func.parameters19 self.start_line = func.start_line20 self.end_line = func.end_line21 self.length = func.length22 self.source_code = sourceCode23 self.file_name = func.name.split("::")[0] + ".java"24 self.test_method = self.__IsTestMethod(self.source_code)25 self.commit = commitInfo26 @staticmethod27 def __IsTestMethod(source_code) -> bool:28 lines = source_code.splitlines()29 for line in lines:30 if any(annotation in line for annotation in java_test_annotations):31 return True32 return False33 @property34 def code_lines(self) -> List[Tuple[int, str]]:35 """Returns a list of code lines corresponding to (line number, actual line)."""36 code_lines = self.__CalculateCodeLines()37 return code_lines38 def __CalculateCodeLines(self) -> List[Tuple[int, str]]:39 lines = self.source_code.splitlines()40 lineNumber = self.start_line41 code_lines = []42 for line in lines:43 line = line.rstrip()44 if any(x in line for x in java_test_annotations):45 if any(y in line for y in modifiers):46 code_lines.append((lineNumber, line))47 lineNumber = lineNumber + 148 else:49 code_lines.append((lineNumber, line))50 lineNumber = lineNumber + 151 return code_lines52 @property53 def signature(self) -> str:54 """Returns the signature of a method."""55 lines = self.source_code.splitlines()56 if any(modifier in lines[0] for modifier in modifiers):57 signature = lines[0]58 else:59 if any(annotation in lines[0] for annotation in java_test_annotations):60 signature = lines[1]61 else:62 signature = lines[0]63 signature = re.sub("{", "", signature)64 signature = re.sub("@Test", "", signature)65 return signature66 @property67 def method_body(self) -> str:68 """Returns the body of a method."""69 method_body = ""70 match = re.findall(r'{(.+)}', self.source_code, re.S)71 for x in match:72 method_body += x73 return method_body74 @property75 def access_modifier(self) -> str:76 """Returns the qualifier of a method."""77 return GetAccessModifier(self.signature)78 @property79 def return_type(self) -> str:80 """Returns the return type."""81 return GetReturnType(self.signature)82 @property83 def full_parameters(self) -> List[MethodParameter]:84 """Returns a list of full parameters."""85 return GetFullParameters(self.signature)86 @property87 def parsed_method_name(self) -> str:88 """Returns the method name obtained fromm parsing."""89 return GetMethodName(self.signature)90class ModifiedMethod(Method):91 """92 This class represents a modified methods that contains various information about the modifications93 """94 def __init__(self, methodBefore=None, methodAfter=None, modificationType=None, ratio=None, lines=None):95 if methodAfter is not None and methodBefore is not None:96 super().__init__(methodAfter, methodAfter.source_code, methodAfter.commit)97 self.__source_code_after = methodAfter.source_code98 self.__source_code_before = methodBefore.source_code99 elif methodAfter is not None and methodBefore is None:100 super().__init__(methodAfter, methodAfter.source_code, methodAfter.commit)101 self.__source_code_after = methodAfter.source_code102 self.__source_code_before = ""103 elif methodAfter is None and methodBefore is not None:104 super().__init__(methodBefore, methodBefore.source_code, methodBefore.commit)105 self.__source_code_after = ""106 self.__source_code_before = methodBefore.source_code107 elif methodAfter is None and methodBefore is None:108 raise SystemExit("methodAfter and methodBefore are none")109 self._type = modificationType110 if lines is not None:111 self.__added_lines_from_diff = lines[0]112 self.__deleted_lines_from_diff = lines[1]113 # TODO: summarize to properties?114 if modificationType == ModificationType.RENAMED.name:115 self.old_name = methodBefore.name116 self.old_long_name = methodBefore.long_name117 self.old_signature = methodBefore.signature118 self.multiple_renamed = False119 self.renamed_methods = []120 if ratio is not None:121 self.ratio_signature = ratio[0]122 self.ratio_method_body = ratio[1]123 self.__change_frequency = 0124 self.__added, self.__added_lines = self.__CalculateLines(methodAfter, self.__added_lines_from_diff)125 self.__deleted, self.__deletedLines = self.__CalculateLines(methodBefore, self.__deleted_lines_from_diff)126 self.__code_churn = self.__added + self.__deleted127 def __GetDiffLines(self, methodBefore, methodAfter):128 sourceCodeBefore = methodBefore.strip().splitlines()129 sourceCodeAfter = methodAfter.strip().splitlines()130 diff = difflib.unified_diff(sourceCodeBefore, sourceCodeAfter, fromfile=self.file_name, tofile=self.file_name,131 lineterm='')132 lines = list(diff)[2:]133 return lines134 @property135 def source_code_before(self) -> str:136 return self.__source_code_before137 @property138 def change_frequency(self) -> int:139 """Returns the change frequency."""140 return self.__change_frequency141 @change_frequency.setter142 def change_frequency(self, value):143 """Sets the change frequency."""144 self.__change_frequency = value145 @property146 def type(self) -> str:147 """Returns the change type."""148 if self._type is not None:149 return self._type150 else:151 return ModificationType.UNKOWN.name152 @property153 def diff(self) -> str:154 diff = ""155 lines = self.__GetDiffLines(self.__source_code_before, self.__source_code_after)156 for line in lines:157 if not line.startswith('@@'):158 diff = diff + line + "\n"159 return diff160 @property161 def added_lines(self) -> List[str]:162 return self.__added_lines163 @property164 def added(self) -> int:165 return self.__added166 @property167 def deleted_lines(self) -> List[str]:168 return self.__deletedLines169 @property170 def deleted(self) -> int:171 return self.__deleted172 @property173 def code_churn(self) -> int:174 return self.__code_churn175 @code_churn.setter176 def code_churn(self, value):177 self.__code_churn = value178 @property179 def parsed_method(self):180 """181 Returns information for methods obtained from parsing.182 """183 if not self.test_method:184 return ParseMethod(self.source_code)185 else:186 return ParseTestMethod(self.source_code)187 @staticmethod188 def __CalculateLines(method, lines):189 counter = 0190 modified_lines = []191 if method is not None:192 code_lines = method.code_lines193 for code_line in code_lines:194 if code_line in lines:195 counter += 1196 modified_lines.append(code_line)197 return counter, modified_lines198class SummarizedMethod:199 def __init__(self, methods, isTestMethod):200 self.isTestMethod = isTestMethod201 if isTestMethod:202 self.test_methods = methods203 self.summarized_test_method = methods[-1]204 else:205 self.methods = methods206 self.summarized_production_method = methods[-1]207 @property208 def name(self) -> str:209 if self.isTestMethod:210 names = [x.long_name for x in self.test_methods]211 else:212 names = [x.long_name for x in self.methods]213 if len(set(names)) <= 1:214 name = list(set(names))[0]215 return name216 else:217 print("something went wrong")218 @property219 def summarized_method(self) -> Method:220 if self.isTestMethod:221 # code_churn = self.__CalculateCodeChurn(self.test_methods)222 test_method = self.test_methods[-1]223 # test_method.code_churn = code_churn224 return test_method225 else:226 # code_churn = self.__CalculateCodeChurn(self.methods)227 method = self.methods[-1]228 # method.code_churn = code_churn...
helpers.py
Source:helpers.py
2sys.path.insert(0, 'lib')3def fixedGetTestCaseNames(self, testCaseClass):4 """Return a sorted sequence of method names found within testCaseClass5 """6 def isTestMethod(attrname, testCaseClass=testCaseClass, prefix=self.testMethodPrefix):7 attr = getattr(testCaseClass, attrname)8 if attrname.startswith(prefix) and callable(attr):9 return True10 return hasattr(attr, "_unittest_test")11 testFnNames = filter(isTestMethod, dir(testCaseClass))12 for baseclass in testCaseClass.__bases__:13 for testFnName in self.getTestCaseNames(baseclass):14 if testFnName not in testFnNames: # handle overridden methods15 testFnNames.append(testFnName)16 if self.sortTestMethodsUsing:17 testFnNames.sort(self.sortTestMethodsUsing)18 return testFnNames19unittest.TestLoader.getTestCaseNames = fixedGetTestCaseNames20def test(f):...
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!!