How to use explanation method in Sure

Best Python code snippet using sure_python

exprinfo.py

Source:exprinfo.py Github

copy

Full Screen

...38 except passthroughex:39 raise40 except:41 raise Failure(self)42 def nice_explanation(self):43 # uck! See CallFunc for where \n{ and \n} escape sequences are used44 raw_lines = (self.explanation or '').split('\n')45 # escape newlines not followed by { and }46 lines = [raw_lines[0]]47 for l in raw_lines[1:]:48 if l.startswith('{') or l.startswith('}'):49 lines.append(l)50 else:51 lines[-1] += '\\n' + l52 53 result = lines[:1]54 stack = [0]55 stackcnt = [0]56 for line in lines[1:]:57 if line.startswith('{'):58 if stackcnt[-1]:59 s = 'and '60 else:61 s = 'where '62 stack.append(len(result))63 stackcnt[-1] += 164 stackcnt.append(0)65 result.append(' +' + ' '*(len(stack)-1) + s + line[1:])66 else:67 assert line.startswith('}')68 stack.pop()69 stackcnt.pop()70 result[stack[-1]] += line[1:]71 assert len(stack) == 172 return '\n'.join(result)73class Name(Interpretable):74 __view__ = ast.Name75 def is_local(self, frame):76 co = compile('%r in locals() is not globals()' % self.name, '?', 'eval')77 try:78 return frame.is_true(frame.eval(co))79 except passthroughex:80 raise81 except:82 return False83 def is_global(self, frame):84 co = compile('%r in globals()' % self.name, '?', 'eval')85 try:86 return frame.is_true(frame.eval(co))87 except passthroughex:88 raise89 except:90 return False91 def is_builtin(self, frame):92 co = compile('%r not in locals() and %r not in globals()' % (93 self.name, self.name), '?', 'eval')94 try:95 return frame.is_true(frame.eval(co))96 except passthroughex:97 raise98 except:99 return False100 def eval(self, frame):101 super(Name, self).eval(frame)102 if not self.is_local(frame):103 self.explanation = self.name104class Compare(Interpretable):105 __view__ = ast.Compare106 def eval(self, frame):107 expr = Interpretable(self.expr)108 expr.eval(frame)109 for operation, expr2 in self.ops:110 expr2 = Interpretable(expr2)111 expr2.eval(frame)112 self.explanation = "%s %s %s" % (113 expr.explanation, operation, expr2.explanation)114 co = compile("__exprinfo_left %s __exprinfo_right" % operation,115 '?', 'eval')116 try:117 self.result = frame.eval(co, __exprinfo_left=expr.result,118 __exprinfo_right=expr2.result)119 except passthroughex:120 raise121 except:122 raise Failure(self)123 if not frame.is_true(self.result):124 break125 expr = expr2126class And(Interpretable):127 __view__ = ast.And128 def eval(self, frame):129 explanations = []130 for expr in self.nodes:131 expr = Interpretable(expr)132 expr.eval(frame)133 explanations.append(expr.explanation)134 self.result = expr.result135 if not frame.is_true(expr.result):136 break137 self.explanation = '(' + ' and '.join(explanations) + ')'138class Or(Interpretable):139 __view__ = ast.Or140 def eval(self, frame):141 explanations = []142 for expr in self.nodes:143 expr = Interpretable(expr)144 expr.eval(frame)145 explanations.append(expr.explanation)146 self.result = expr.result147 if frame.is_true(expr.result):148 break149 self.explanation = '(' + ' or '.join(explanations) + ')'150# == Unary operations ==151keepalive = []152for astclass, astpattern in {153 ast.Not : 'not __exprinfo_expr',154 ast.Invert : '(~__exprinfo_expr)',155 }.items():156 class UnaryArith(Interpretable):157 __view__ = astclass158 def eval(self, frame, astpattern=astpattern,159 co=compile(astpattern, '?', 'eval')):160 expr = Interpretable(self.expr)161 expr.eval(frame)162 self.explanation = astpattern.replace('__exprinfo_expr',163 expr.explanation)164 try:165 self.result = frame.eval(co, __exprinfo_expr=expr.result)166 except passthroughex:167 raise168 except:169 raise Failure(self)170 keepalive.append(UnaryArith)171# == Binary operations ==172for astclass, astpattern in {173 ast.Add : '(__exprinfo_left + __exprinfo_right)',174 ast.Sub : '(__exprinfo_left - __exprinfo_right)',175 ast.Mul : '(__exprinfo_left * __exprinfo_right)',176 ast.Div : '(__exprinfo_left / __exprinfo_right)',177 ast.Mod : '(__exprinfo_left % __exprinfo_right)',178 ast.Power : '(__exprinfo_left ** __exprinfo_right)',179 }.items():180 class BinaryArith(Interpretable):181 __view__ = astclass182 def eval(self, frame, astpattern=astpattern,183 co=compile(astpattern, '?', 'eval')):184 left = Interpretable(self.left)185 left.eval(frame)186 right = Interpretable(self.right)187 right.eval(frame)188 self.explanation = (astpattern189 .replace('__exprinfo_left', left .explanation)190 .replace('__exprinfo_right', right.explanation))191 try:192 self.result = frame.eval(co, __exprinfo_left=left.result,193 __exprinfo_right=right.result)194 except passthroughex:195 raise196 except:197 raise Failure(self)198 keepalive.append(BinaryArith)199class CallFunc(Interpretable):200 __view__ = ast.CallFunc201 def is_bool(self, frame):202 co = compile('isinstance(__exprinfo_value, bool)', '?', 'eval')203 try:204 return frame.is_true(frame.eval(co, __exprinfo_value=self.result))205 except passthroughex:206 raise207 except:208 return False209 def eval(self, frame):210 node = Interpretable(self.node)211 node.eval(frame)212 explanations = []213 vars = {'__exprinfo_fn': node.result}214 source = '__exprinfo_fn('215 for a in self.args:216 if isinstance(a, ast.Keyword):217 keyword = a.name218 a = a.expr219 else:220 keyword = None221 a = Interpretable(a)222 a.eval(frame)223 argname = '__exprinfo_%d' % len(vars)224 vars[argname] = a.result225 if keyword is None:226 source += argname + ','227 explanations.append(a.explanation)228 else:229 source += '%s=%s,' % (keyword, argname)230 explanations.append('%s=%s' % (keyword, a.explanation))231 if self.star_args:232 star_args = Interpretable(self.star_args)233 star_args.eval(frame)234 argname = '__exprinfo_star'235 vars[argname] = star_args.result236 source += '*' + argname + ','237 explanations.append('*' + star_args.explanation)238 if self.dstar_args:239 dstar_args = Interpretable(self.dstar_args)240 dstar_args.eval(frame)241 argname = '__exprinfo_kwds'242 vars[argname] = dstar_args.result243 source += '**' + argname + ','244 explanations.append('**' + dstar_args.explanation)245 self.explanation = "%s(%s)" % (246 node.explanation, ', '.join(explanations))247 if source.endswith(','):248 source = source[:-1]249 source += ')'250 co = compile(source, '?', 'eval')251 try:252 self.result = frame.eval(co, **vars)253 except passthroughex:254 raise255 except:256 raise Failure(self)257 if not node.is_builtin(frame) or not self.is_bool(frame):258 r = frame.repr(self.result)259 self.explanation = '%s\n{%s = %s\n}' % (r, r, self.explanation)260class Getattr(Interpretable):261 __view__ = ast.Getattr262 def eval(self, frame):263 expr = Interpretable(self.expr)264 expr.eval(frame)265 co = compile('__exprinfo_expr.%s' % self.attrname, '?', 'eval')266 try:267 self.result = frame.eval(co, __exprinfo_expr=expr.result)268 except passthroughex:269 raise270 except:271 raise Failure(self)272 self.explanation = '%s.%s' % (expr.explanation, self.attrname)273 # if the attribute comes from the instance, its value is interesting274 co = compile('hasattr(__exprinfo_expr, "__dict__") and '275 '%r in __exprinfo_expr.__dict__' % self.attrname,276 '?', 'eval')277 try:278 from_instance = frame.is_true(279 frame.eval(co, __exprinfo_expr=expr.result))280 except passthroughex:281 raise282 except:283 from_instance = True284 if from_instance:285 r = frame.repr(self.result)286 self.explanation = '%s\n{%s = %s\n}' % (r, r, self.explanation)287# == Re-interpretation of full statements ==288import __builtin__289BuiltinAssertionError = __builtin__.AssertionError290class Assert(Interpretable):291 __view__ = ast.Assert292 def run(self, frame):293 test = Interpretable(self.test)294 test.eval(frame)295 # simplify 'assert False where False = ...'296 if (test.explanation.startswith('False\n{False = ') and297 test.explanation.endswith('\n}')):298 test.explanation = test.explanation[15:-2]299 # print the result as 'assert <explanation>'300 self.result = test.result301 self.explanation = 'assert ' + test.explanation302 if not frame.is_true(test.result):303 try:304 raise BuiltinAssertionError305 except passthroughex:306 raise307 except:308 raise Failure(self)309class Assign(Interpretable):310 __view__ = ast.Assign311 def run(self, frame):312 expr = Interpretable(self.expr)313 expr.eval(frame)314 self.result = expr.result315 self.explanation = '... = ' + expr.explanation316 # fall-back-run the rest of the assignment317 ass = ast.Assign(self.nodes, ast.Name('__exprinfo_expr'))318 mod = ast.Module(None, ast.Stmt([ass]))319 mod.filename = '<run>'320 co = pycodegen.ModuleCodeGenerator(mod).getCode()321 try:322 frame.exec_(co, __exprinfo_expr=expr.result)323 except passthroughex:324 raise325 except:326 raise Failure(self)327class Discard(Interpretable):328 __view__ = ast.Discard329 def run(self, frame):330 expr = Interpretable(self.expr)331 expr.eval(frame)332 self.result = expr.result333 self.explanation = expr.explanation334class Stmt(Interpretable):335 __view__ = ast.Stmt336 def run(self, frame):337 for stmt in self.nodes:338 stmt = Interpretable(stmt)339 stmt.run(frame)340def report_failure(e):341 explanation = e.node.nice_explanation()342 if explanation:343 explanation = ", in: " + explanation344 else:345 explanation = ""346 print "%s: %s%s" % (e.exc.__name__, e.value, explanation)347def check(s, frame=None):348 if frame is None:349 import sys350 frame = sys._getframe(1)351 frame = py.code.Frame(frame)352 expr = parse(s, 'eval')353 assert isinstance(expr, ast.Expression)354 node = Interpretable(expr.node)355 try:356 node.eval(frame)357 except passthroughex:358 raise359 except Failure, e:360 report_failure(e)361 else:362 if not frame.is_true(node.result):363 print "assertion failed:", node.nice_explanation()364###########################################################365# API / Entry points366# #########################################################367def interpret(source, frame, should_fail=False):368 module = Interpretable(parse(source, 'exec').node)369 #print "got module", module370 if isinstance(frame, py.std.types.FrameType):371 frame = py.code.Frame(frame)372 try:373 module.run(frame)374 except Failure, e:375 return getfailure(e)376 except passthroughex:377 raise378 except:379 import traceback380 traceback.print_exc()381 if should_fail:382 return "(inconsistently failed then succeeded)"383 else:384 return None385def getmsg(excinfo):386 if isinstance(excinfo, tuple):387 excinfo = py.code.ExceptionInfo(excinfo)388 #frame, line = gettbline(tb)389 #frame = py.code.Frame(frame)390 #return interpret(line, frame)391 tb = excinfo.traceback[-1] 392 source = str(tb.statement).strip()393 x = interpret(source, tb.frame, should_fail=True)394 if not isinstance(x, str):395 raise TypeError, "interpret returned non-string %r" % (x,)396 return x397def getfailure(e):398 explanation = e.node.nice_explanation()399 if str(e.value):400 lines = explanation.split('\n')401 lines[0] += " << %s" % (e.value,)402 explanation = '\n'.join(lines)403 text = "%s: %s" % (e.exc.__name__, explanation)404 if text.startswith('AssertionError: assert '):405 text = text[16:]406 return text407def run(s, frame=None):408 if frame is None:409 import sys410 frame = sys._getframe(1)411 frame = py.code.Frame(frame)412 module = Interpretable(parse(s, 'exec').node)...

Full Screen

Full Screen

explanation.py

Source:explanation.py Github

copy

Full Screen

...13def get_object_from_json(json_object):14 self_thawed = jsonpickle.decode(json_object)15 return self_thawed16# takes in a triple of (explanation_type,object_id,count)17def get_explanation(explanation_triple, imdb_id, user_id, settings):18 movie_title_and_poster = settings[1]19 random_explanations = settings[2]20 21 tmp_explanation = Explanation()22 tmp_explanation.user_id = user_id23 tmp_explanation.explanation_type = explanation_triple[0]24 tmp_explanation.object_id = explanation_triple[1]25 tmp_explanation.count = explanation_triple[2]26 tmp_explanation.imdb_id = imdb_id27 movie_title = get_movie_name_from_id(imdb_id)28 if movie_title_and_poster == 1:29 tmp_explanation.explanation = movie_title + " : "30 else:31 tmp_explanation.explanation = ""32 tmp_explanation.explanation += print_explanation(explanation_triple[0],33 explanation_triple[1],34 explanation_triple[2])35 if random_explanations == 1:36 tmp_explanation.get_random_rating()37 else:38 tmp_explanation.get_rating_for_explanation()39 40 tmp_explanation.explanation += " "41 # tmp_explanation.explanation += str(tmp_explanation.rating)42 # print(tmp_explanation.explanation)43 # print("\n\n\n\n\n\n")44 # print(tmp_explanation.rating)45 # add title to explanation at the start46 return tmp_explanation47class Explanation:48 def __init__(self):49 # text to print to screen50 self.explanation = None51 # ratings should be values between -1 and 152 self.rating = 053 # types like actor or poster or something54 self.explanation_type = None55 self.object_id = None56 57 # if its metadata number of times an actor shows up.58 self.count = None59 self.user_id = None60 self.imdb_id = None61 def get_rating(self):62 return self.rating63 def set_explanation(self, explanation):64 self.explanation = explanation65 return66 def set_rating(self, rating):67 self.rating = rating68 return69 def rank_explanation(self):70 # this should change the rating of the explanation based on the type71 # and value72 # different types will have different good values73 return74 def get_object_id(self):75 return self.object_id76 def get_object_string(self):77 # object type , object id , count78 self.explanation = print_explanation(self.explanation_type,79 self.object_id,80 self.count)81 def get_random_rating(self):82 self.rating = random.randint(0, 100)/10083 def get_json_for_object(self):84 self_frozen = jsonpickle.encode(self)85 return self_frozen86 def get_rating_for_explanation(self):87 if RANDOM_SCORING:88 self.rating = random.randint(0, 100)/10089 else:90 # self.rating = 091 if self.explanation_type == 1:92 # actor93 # print("getting score for type 1")94 score = self.get_score_for_type()95 # print("got score for type 1")96 # print(score)97 self.rating = score + 0.598 # self.rating == "HIGH if low"99 elif self.explanation_type == 2:100 # year...

Full Screen

Full Screen

_assertionnew.py

Source:_assertionnew.py Github

copy

Full Screen

...48 if frame is None:49 frame = py.code.Frame(sys._getframe(1))50 return interpret(offending_line, frame)51def getfailure(failure):52 explanation = _format_explanation(failure.explanation)53 value = failure.cause[1]54 if str(value):55 lines = explanation.splitlines()56 if not lines:57 lines.append("")58 lines[0] += " << %s" % (value,)59 explanation = "\n".join(lines)60 text = "%s: %s" % (failure.cause[0].__name__, explanation)61 if text.startswith("AssertionError: assert "):62 text = text[16:]63 return text64operator_map = {65 ast.BitOr : "|",66 ast.BitXor : "^",...

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Sure automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful