Best Python code snippet using autotest_python
coverage.py
Source:coverage.py
...179 if os.path.exists(self.cache):180 os.remove(self.cache)181 # save(). Save coverage data to the coverage cache.182 def save(self):183 self.canonicalize_filenames()184 cache = open(self.cache, 'wb')185 import marshal186 marshal.dump(self.cexecuted, cache)187 cache.close()188 # restore(). Restore coverage data from the coverage cache (if it189 # exists).190 def restore(self):191 global c192 c = {}193 self.cexecuted = {}194 if not os.path.exists(self.cache):195 return196 try:197 cache = open(self.cache, 'rb')198 import marshal199 cexecuted = marshal.load(cache)200 cache.close()201 if isinstance(cexecuted, types.DictType):202 self.cexecuted = cexecuted203 except:204 pass205 # canonical_filename(filename). Return a canonical filename for the206 # file (that is, an absolute path with no redundant components and207 # normalized case). See [GDR 2001-12-04b, 3.3].208 def canonical_filename(self, filename):209 if not self.canonical_filename_cache.has_key(filename):210 f = filename211 if os.path.isabs(f) and not os.path.exists(f):212 f = os.path.basename(f)213 if not os.path.isabs(f):214 for path in [os.curdir] + sys.path:215 g = os.path.join(path, f)216 if os.path.exists(g):217 f = g218 break219 cf = os.path.normcase(os.path.abspath(f))220 self.canonical_filename_cache[filename] = cf221 return self.canonical_filename_cache[filename]222 # canonicalize_filenames(). Copy results from "executed" to223 # "cexecuted", canonicalizing filenames on the way. Clear the224 # "executed" map.225 def canonicalize_filenames(self):226 global c227 for filename, lineno in c.keys():228 f = self.canonical_filename(filename)229 if not self.cexecuted.has_key(f):230 self.cexecuted[f] = {}231 self.cexecuted[f][lineno] = 1232 c = {}233 # morf_filename(morf). Return the filename for a module or file.234 def morf_filename(self, morf):235 if isinstance(morf, types.ModuleType):236 if not hasattr(morf, '__file__'):237 raise self.error, "Module has no __file__ attribute."238 file = morf.__file__239 else:240 file = morf241 return self.canonical_filename(file)242 # analyze_morf(morf). Analyze the module or filename passed as243 # the argument. If the source code can't be found, raise an error.244 # Otherwise, return a pair of (1) the canonical filename of the245 # source code for the module, and (2) a list of lines of statements246 # in the source code.247 def analyze_morf(self, morf):248 if self.analysis_cache.has_key(morf):249 return self.analysis_cache[morf]250 filename = self.morf_filename(morf)251 ext = os.path.splitext(filename)[1]252 if ext == '.pyc':253 if not os.path.exists(filename[0:-1]):254 raise self.error, ("No source for compiled code '%s'."255 % filename)256 filename = filename[0:-1]257 elif ext != '.py':258 raise self.error, "File '%s' not Python source." % filename259 source = open(filename, 'r')260 import parser261 tree = parser.suite(source.read()).totuple(1)262 source.close()263 statements = {}264 self.find_statements(tree, statements)265 lines = statements.keys()266 lines.sort()267 result = filename, lines268 self.analysis_cache[morf] = result269 return result270 # find_statements(tree, dict). Find each statement in the parse271 # tree and record the line on which the statement starts in the272 # dictionary (by assigning it to 1).273 #274 # It works by walking the whole tree depth-first. Every time it275 # comes across a statement (symbol.stmt -- this includes compound276 # statements like 'if' and 'while') it calls find_statement, which277 # descends the tree below the statement to find the first terminal278 # token in that statement and record the lines on which that token279 # was found.280 #281 # This algorithm may find some lines several times (because of the282 # grammar production statement -> compound statement -> statement),283 # but that doesn't matter because we record lines as the keys of the284 # dictionary.285 #286 # See also [GDR 2001-12-04b, 3.2].287 def find_statements(self, tree, dict):288 import symbol, token289 if token.ISNONTERMINAL(tree[0]):290 for t in tree[1:]:291 self.find_statements(t, dict)292 if tree[0] == symbol.stmt:293 self.find_statement(tree[1], dict)294 elif (tree[0] == token.NAME295 and tree[1] in ['elif', 'except', 'finally']):296 dict[tree[2]] = 1297 def find_statement(self, tree, dict):298 import token299 while token.ISNONTERMINAL(tree[0]):300 tree = tree[1]301 dict[tree[2]] = 1302 # format_lines(statements, lines). Format a list of line numbers303 # for printing by coalescing groups of lines as long as the lines304 # represent consecutive statements. This will coalesce even if305 # there are gaps between statements, so if statements =306 # [1,2,3,4,5,10,11,12,13,14] and lines = [1,2,5,10,11,13,14] then307 # format_lines will return "1-2, 5-11, 13-14".308 def format_lines(self, statements, lines):309 pairs = []310 i = 0311 j = 0312 start = None313 pairs = []314 while i < len(statements) and j < len(lines):315 if statements[i] == lines[j]:316 if start == None:317 start = lines[j]318 end = lines[j]319 j = j + 1320 elif start:321 pairs.append((start, end))322 start = None323 i = i + 1324 if start:325 pairs.append((start, end))326 def stringify(pair):327 start, end = pair328 if start == end:329 return "%d" % start330 else:331 return "%d-%d" % (start, end)332 import string333 return string.join(map(stringify, pairs), ", ")334 def analysis(self, morf):335 filename, statements = self.analyze_morf(morf)336 self.canonicalize_filenames()337 if not self.cexecuted.has_key(filename):338 self.cexecuted[filename] = {}339 missing = []340 for line in statements:341 if not self.cexecuted[filename].has_key(line):342 missing.append(line)343 return (filename, statements, missing,344 self.format_lines(statements, missing))345 def morf_name(self, morf):346 if isinstance(morf, types.ModuleType):347 return morf.__name__348 else:349 return os.path.splitext(os.path.basename(morf))[0]350 def report(self, morfs, show_missing=1, ignore_errors=0):...
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!!