How to use tb_next method in Slash

Best Python code snippet using slash

debug.py

Source:debug.py Github

copy

Full Screen

1import platform2import sys3import typing as t4from types import CodeType5from types import TracebackType6from .exceptions import TemplateSyntaxError7from .utils import internal_code8from .utils import missing9if t.TYPE_CHECKING:10 from .runtime import Context11def rewrite_traceback_stack(source: t.Optional[str] = None) -> BaseException:12 """Rewrite the current exception to replace any tracebacks from13 within compiled template code with tracebacks that look like they14 came from the template source.15 This must be called within an ``except`` block.16 :param source: For ``TemplateSyntaxError``, the original source if17 known.18 :return: The original exception with the rewritten traceback.19 """20 _, exc_value, tb = sys.exc_info()21 exc_value = t.cast(BaseException, exc_value)22 tb = t.cast(TracebackType, tb)23 if isinstance(exc_value, TemplateSyntaxError) and not exc_value.translated:24 exc_value.translated = True25 exc_value.source = source26 # Remove the old traceback, otherwise the frames from the27 # compiler still show up.28 exc_value.with_traceback(None)29 # Outside of runtime, so the frame isn't executing template30 # code, but it still needs to point at the template.31 tb = fake_traceback(32 exc_value, None, exc_value.filename or "<unknown>", exc_value.lineno33 )34 else:35 # Skip the frame for the render function.36 tb = tb.tb_next37 stack = []38 # Build the stack of traceback object, replacing any in template39 # code with the source file and line information.40 while tb is not None:41 # Skip frames decorated with @internalcode. These are internal42 # calls that aren't useful in template debugging output.43 if tb.tb_frame.f_code in internal_code:44 tb = tb.tb_next45 continue46 template = tb.tb_frame.f_globals.get("__jinja_template__")47 if template is not None:48 lineno = template.get_corresponding_lineno(tb.tb_lineno)49 fake_tb = fake_traceback(exc_value, tb, template.filename, lineno)50 stack.append(fake_tb)51 else:52 stack.append(tb)53 tb = tb.tb_next54 tb_next = None55 # Assign tb_next in reverse to avoid circular references.56 for tb in reversed(stack):57 tb_next = tb_set_next(tb, tb_next)58 return exc_value.with_traceback(tb_next)59def fake_traceback( # type: ignore60 exc_value: BaseException, tb: t.Optional[TracebackType], filename: str, lineno: int61) -> TracebackType:62 """Produce a new traceback object that looks like it came from the63 template source instead of the compiled code. The filename, line64 number, and location name will point to the template, and the local65 variables will be the current template context.66 :param exc_value: The original exception to be re-raised to create67 the new traceback.68 :param tb: The original traceback to get the local variables and69 code info from.70 :param filename: The template filename.71 :param lineno: The line number in the template source.72 """73 if tb is not None:74 # Replace the real locals with the context that would be75 # available at that point in the template.76 locals = get_template_locals(tb.tb_frame.f_locals)77 locals.pop("__jinja_exception__", None)78 else:79 locals = {}80 globals = {81 "__name__": filename,82 "__file__": filename,83 "__jinja_exception__": exc_value,84 }85 # Raise an exception at the correct line number.86 code: CodeType = compile(87 "\n" * (lineno - 1) + "raise __jinja_exception__", filename, "exec"88 )89 # Build a new code object that points to the template file and90 # replaces the location with a block name.91 location = "template"92 if tb is not None:93 function = tb.tb_frame.f_code.co_name94 if function == "root":95 location = "top-level template code"96 elif function.startswith("block_"):97 location = f"block {function[6:]!r}"98 if sys.version_info >= (3, 8):99 code = code.replace(co_name=location)100 else:101 code = CodeType(102 code.co_argcount,103 code.co_kwonlyargcount,104 code.co_nlocals,105 code.co_stacksize,106 code.co_flags,107 code.co_code,108 code.co_consts,109 code.co_names,110 code.co_varnames,111 code.co_filename,112 location,113 code.co_firstlineno,114 code.co_lnotab,115 code.co_freevars,116 code.co_cellvars,117 )118 # Execute the new code, which is guaranteed to raise, and return119 # the new traceback without this frame.120 try:121 exec(code, globals, locals)122 except BaseException:123 return sys.exc_info()[2].tb_next # type: ignore124def get_template_locals(real_locals: t.Mapping[str, t.Any]) -> t.Dict[str, t.Any]:125 """Based on the runtime locals, get the context that would be126 available at that point in the template.127 """128 # Start with the current template context.129 ctx: "t.Optional[Context]" = real_locals.get("context")130 if ctx is not None:131 data: t.Dict[str, t.Any] = ctx.get_all().copy()132 else:133 data = {}134 # Might be in a derived context that only sets local variables135 # rather than pushing a context. Local variables follow the scheme136 # l_depth_name. Find the highest-depth local that has a value for137 # each name.138 local_overrides: t.Dict[str, t.Tuple[int, t.Any]] = {}139 for name, value in real_locals.items():140 if not name.startswith("l_") or value is missing:141 # Not a template variable, or no longer relevant.142 continue143 try:144 _, depth_str, name = name.split("_", 2)145 depth = int(depth_str)146 except ValueError:147 continue148 cur_depth = local_overrides.get(name, (-1,))[0]149 if cur_depth < depth:150 local_overrides[name] = (depth, value)151 # Modify the context with any derived context.152 for name, (_, value) in local_overrides.items():153 if value is missing:154 data.pop(name, None)155 else:156 data[name] = value157 return data158if sys.version_info >= (3, 7):159 # tb_next is directly assignable as of Python 3.7160 def tb_set_next(161 tb: TracebackType, tb_next: t.Optional[TracebackType]162 ) -> TracebackType:163 tb.tb_next = tb_next164 return tb165elif platform.python_implementation() == "PyPy":166 # PyPy might have special support, and won't work with ctypes.167 try:168 import tputil # type: ignore169 except ImportError:170 # Without tproxy support, use the original traceback.171 def tb_set_next(172 tb: TracebackType, tb_next: t.Optional[TracebackType]173 ) -> TracebackType:174 return tb175 else:176 # With tproxy support, create a proxy around the traceback that177 # returns the new tb_next.178 def tb_set_next(179 tb: TracebackType, tb_next: t.Optional[TracebackType]180 ) -> TracebackType:181 def controller(op): # type: ignore182 if op.opname == "__getattribute__" and op.args[0] == "tb_next":183 return tb_next184 return op.delegate()185 return tputil.make_proxy(controller, obj=tb) # type: ignore186else:187 # Use ctypes to assign tb_next at the C level since it's read-only188 # from Python.189 import ctypes190 class _CTraceback(ctypes.Structure):191 _fields_ = [192 # Extra PyObject slots when compiled with Py_TRACE_REFS.193 ("PyObject_HEAD", ctypes.c_byte * object().__sizeof__()),194 # Only care about tb_next as an object, not a traceback.195 ("tb_next", ctypes.py_object),196 ]197 def tb_set_next(198 tb: TracebackType, tb_next: t.Optional[TracebackType]199 ) -> TracebackType:200 c_tb = _CTraceback.from_address(id(tb))201 # Clear out the old tb_next.202 if tb.tb_next is not None:203 c_tb_next = ctypes.py_object(tb.tb_next)204 c_tb.tb_next = ctypes.py_object()205 ctypes.pythonapi.Py_DecRef(c_tb_next)206 # Assign the new tb_next.207 if tb_next is not None:208 c_tb_next = ctypes.py_object(tb_next)209 ctypes.pythonapi.Py_IncRef(c_tb_next)210 c_tb.tb_next = c_tb_next...

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 Slash 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