def test_basics(self):
     linecache.clearcache()
     linecache.lazycache('f', globals())
     f = traceback.FrameSummary('f', 1, 'dummy')
     self.assertEqual(
         f, ('f', 1, 'dummy', '"""Test cases for traceback module"""'))
     self.assertEqual(
         tuple(f),
         ('f', 1, 'dummy', '"""Test cases for traceback module"""'))
     self.assertEqual(f, traceback.FrameSummary('f', 1, 'dummy'))
     self.assertEqual(f, tuple(f))
     self.assertEqual(tuple(f), f)
     self.assertIsNone(f.locals)
Beispiel #2
0
 def test_basics(self):
     linecache.clearcache()
     linecache.lazycache("f", globals())
     f = traceback.FrameSummary("f", 1, "dummy")
     self.assertEqual(f,
         ("f", 1, "dummy", '"""Test cases for traceback module"""'))
     self.assertEqual(tuple(f),
         ("f", 1, "dummy", '"""Test cases for traceback module"""'))
     self.assertEqual(f, traceback.FrameSummary("f", 1, "dummy"))
     self.assertEqual(f, tuple(f))
     # Since tuple.__eq__ doesn't support FrameSummary, the equality
     # operator fallbacks to FrameSummary.__eq__.
     self.assertEqual(tuple(f), f)
     self.assertIsNone(f.locals)
Beispiel #3
0
 def as_stdlib_summary(self,
                       *,
                       save_locals: bool = False) -> traceback.FrameSummary:
     if self.frame is None:
         return traceback.FrameSummary("??",
                                       self.lineno or 0,
                                       "??",
                                       line=self.override_line)
     return traceback.FrameSummary(
         self.frame.f_code.co_filename,
         self.lineno or 0,
         self.frame.f_code.co_name,
         locals=self.frame.f_locals if save_locals else None,
         line=self.override_line,
     )
Beispiel #4
0
 def test_basics(self):
     linecache.clearcache()
     linecache.lazycache("f", globals())
     f = traceback.FrameSummary("f", 1, "dummy")
     self.assertEqual(
         ("f", 1, "dummy", '"""Test cases for traceback module"""'),
         tuple(f))
     self.assertEqual(None, f.locals)
Beispiel #5
0
 def last(self) -> traceback.FrameSummary:
     try:
         return self.frame_summaries[-1][1]
     except Exception as e:
         print('FAILED getting ExcHandler.last()\n',
               ExcHandler(e).summary())
         fs = traceback.FrameSummary(__name__, -1, 'ExcHandler.last()')
         return fs
Beispiel #6
0
 def test_lazy_lines(self):
     linecache.clearcache()
     f = traceback.FrameSummary("f", 1, "dummy", lookup_line=False)
     self.assertEqual(None, f._line)
     linecache.lazycache("f", globals())
     self.assertEqual(
         '"""Test cases for traceback module"""',
         f.line)
Beispiel #7
0
def convert_stack_frame(frame):
  """Converts a TF stack frame into Python's."""
  # TODO(mihaimaruseac): Remove except case when dropping suport for py2
  try:
    return traceback.FrameSummary(
        frame.filename, frame.lineno, frame.name, line=frame.line)
  except AttributeError:
    # On Python < 3.5 (i.e., Python2), we don't have traceback.FrameSummary so
    # we don't need to match with that class. Instead, just a tuple is enough.
    return tuple(frame)
Beispiel #8
0
    def fix_tb_code_lines(self, fn):
        fn_source = inspect.findsource(fn)[0]

        for pos in range(len(self.source_tb)):
            fs = self.source_tb[pos]
            if fs.filename == fn.__code__.co_filename:
                line = fn_source[fs.lineno - 1].strip()
                self.source_tb[pos] = traceback.FrameSummary(fs.filename,
                                                             fs.lineno,
                                                             fs.name,
                                                             line=line)
Beispiel #9
0
def except_hook(
    exc_type: Type[BaseException], exc_value: BaseException, tb: TracebackType
) -> None:
    exception_config: Union[DeveloperExceptionConfig, None] = getattr(
        exc_value, _typer_developer_exception_attr_name, None
    )
    standard_traceback = os.getenv("_TYPER_STANDARD_TRACEBACK")
    if (
        standard_traceback
        or not exception_config
        or not exception_config.pretty_exceptions_enable
    ):
        _original_except_hook(exc_type, exc_value, tb)
        return
    typer_path = os.path.dirname(__file__)
    click_path = os.path.dirname(click.__file__)
    supress_internal_dir_names = [typer_path, click_path]
    exc = exc_value
    if rich:
        rich_tb = Traceback.from_exception(
            type(exc),
            exc,
            exc.__traceback__,
            show_locals=exception_config.pretty_exceptions_show_locals,
            suppress=supress_internal_dir_names,
        )
        console_stderr.print(rich_tb)
        return
    tb_exc = traceback.TracebackException.from_exception(exc)
    stack: List[FrameSummary] = []
    for frame in tb_exc.stack:
        if any(
            [frame.filename.startswith(path) for path in supress_internal_dir_names]
        ):
            if not exception_config.pretty_exceptions_short:
                # Hide the line for internal libraries, Typer and Click
                stack.append(
                    traceback.FrameSummary(
                        filename=frame.filename,
                        lineno=frame.lineno,
                        name=frame.name,
                        line="",
                    )
                )
        else:
            stack.append(frame)
    # Type ignore ref: https://github.com/python/typeshed/pull/8244
    final_stack_summary = StackSummary.from_list(stack)  # type: ignore
    tb_exc.stack = final_stack_summary
    for line in tb_exc.format():
        print(line, file=sys.stderr)
    return
Beispiel #10
0
 def replace_stack_item(item: traceback.FrameSummary) -> traceback.FrameSummary:
     m = re.match('^<hint(?P<index>[0-9]+)>$', item.filename)
     if not m:
         return item
     location = vm.get_location(vm.hint_pcs[int(m.group('index'))])
     if not (location and location.hint):
         return item
     line_num = (
         item.lineno + location.hint.location.start_line +
         location.hint.n_prefix_newlines - 1)
     return traceback.FrameSummary(
         filename=location.hint.location.input_file.filename,
         lineno=line_num,
         name=item.name)
Beispiel #11
0
def build_frames(tb):
    iterator = traceback.walk_tb(tb)
    next(iterator)  # skip main's frame

    for frame, lineno in iterator:
        fname = frame.f_code.co_filename
        summ = traceback.FrameSummary(
            filename=fname,
            lineno=lineno,
            name=frame.f_code.co_name,
            lookup_line=os.path.exists(fname),
            locals=frame.f_locals,
        )

        yield summ
Beispiel #12
0
 def replace_stack_item(item: traceback.FrameSummary) -> traceback.FrameSummary:
     m = re.match('^<hint(?P<index>[0-9]+)>$', item.filename)
     if not m:
         return item
     pc, index = vm.hint_pc_and_index[int(m.group('index'))]
     location = vm.get_location(pc)
     if location is None or location.hints[index] is None:
         return item
     hint_location = location.hints[index]
     line_num = (
         item.lineno + hint_location.location.start_line +
         hint_location.n_prefix_newlines - 1)
     return traceback.FrameSummary(
         filename=hint_location.location.input_file.filename,
         lineno=line_num,
         name=item.name)
    def generate_telemetry_stacktrace() -> str:
        # Get the current stack minus this function and the Error init function
        stack_frames = traceback.extract_stack()[:-2]
        filtered_frames = list()
        for frame in stack_frames:
            # Only add frames associated with the snowflake python connector to the telemetry stacktrace
            if connector_base_path in frame.filename:
                # Get the index to truncate the file path to hide any user path
                safe_path_index = frame.filename.find(connector_base_path)
                # Create a new frame with the truncated file name and without the line argument since that can
                # output sensitive data
                filtered_frames.append(
                    traceback.FrameSummary(frame.filename[safe_path_index:], frame.lineno, frame.name, line='')
                )

        return ''.join(traceback.format_list(filtered_frames))
Beispiel #14
0
    def test_syntax_error(self):
        handler = log.StackfulStreamHandler()
        try:
            raise SyntaxError('syntax error', ('file.py', 1, 4, 'line'))
        except SyntaxError:
            record = logging.LogRecord('name', 'level', 'pathname', 1, 'msg',
                                       [], sys.exc_info())
        with mock.patch.object(logging.StreamHandler, 'emit'):
            handler.emit(record)

        self.assertEqual(record.msg, 'syntax error')
        self.assertEqual(record.full_stack, [
            traceback.FrameSummary(
                'file.py', 1, '<module>', line='line\n       ^'),
        ])
        self.assertEqual(record.stack_pre, '')
        self.assertEqual(
            record.stack, '\n' + '  File "file.py", line 1, in <module>\n' +
            '    line\n' + '       ^')
        self.assertEqual(record.stack_post, '')
        self.assertEqual(record.user_pathname, 'file.py')
        self.assertEqual(record.user_lineno, 1)
Beispiel #15
0
    def as_stdlib_summary(self,
                          *,
                          capture_locals: bool = False
                          ) -> traceback.FrameSummary:
        """Return a representation of this frame as a standard
        `traceback.FrameSummary`. Unlike this `FrameInfo` object, the
        result can be pickled and will not keep frames alive, at the
        expense of some loss of information.

        If this frame introduces a context manager in an :ref:`enhanced traceback
        <enhanced-tb>`, information about the name and type of the context manager
        will be appended to the function *name* in the returned
        `~traceback.FrameSummary`, in parentheses after a space. This results
        in reasonable output from :meth:`traceback.StackSummary.format`.

        If *capture_locals* is True, then the returned `~traceback.FrameSummary`
        will contain the stringified object representations of all local variables
        in this frame.

        """
        funcname = self.funcname + self._context_descr
        if not capture_locals:
            save_locals = None
        elif self.context_manager is not None:
            save_locals = {"<context manager>": repr(self.context_manager)}
        else:
            save_locals = {
                name: repr(value)
                for name, value in self.frame.f_locals.items()
            }

        return traceback.FrameSummary(
            self.frame.f_code.co_filename,
            self.lineno,
            funcname,
            locals=save_locals,
            line=self.override_line,
        )
 def test_explicit_line(self):
     f = traceback.FrameSummary("f", 1, "dummy", line="line")
     self.assertEqual("line", f.line)
Beispiel #17
0
def get_json(tb, exc, text, remove, offset=0, end_offset=0, _globals=None):

    if isinstance(tb, list):  # tb can be a traceback or a list of frames
        msg = ""
    else:
        tb_exc = traceback.TracebackException(exc.__class__, exc, tb)
        msg = " ".join(tb_exc.format_exception_only())

    try:
        msg = exc.msg
    except AttributeError:
        msg = ": ".join(msg.split(": ")[1:]).split("\n")
        try:
            del msg[1]
        except IndexError:
            pass
        msg = "\n".join(msg)

    name = None
    suggestion = None
    try:
        if isinstance(exc, AttributeError) or isinstance(exc, NameError):
            name = exc.name
            suggestion = offer_suggestion(exc)
            if suggestion is not None:
                suggestion = suggestion.decode("utf-8")
    except AttributeError:
        pass

    traceback_json = {
        "exc_type": exc.__class__.__name__,
        "msg": msg,
        "as_text": text,
        "suggestion": suggestion,
        "name": name,
        "offset": offset,
        "end_offset": end_offset
    }

    stack_json = []

    if isinstance(tb, list):
        stack = tb
    else:
        stack = traceback.extract_tb(tb)

    for _ in range(remove):
        del stack[0]

    try:
        frame_stack = [exc.__traceback__]
        while frame_stack[-1].tb_next is not None:
            frame_stack.append(frame_stack[-1].tb_next)

        frame_stack.reverse()
    except AttributeError:
        frame_stack = None

    try:

        def get_filename():
            if isinstance(tb, list):
                return os.path.abspath(stack[0].f_code.co_filename)
            else:
                return stack[0].filename

        while len(stack) > 0 and (
                get_filename().endswith("/Lib/console.py")
                or get_filename().startswith("<frozen importlib")):
            del stack[0]
            del frame_stack[0]
    except IndexError:
        pass

    if isinstance(exc, SyntaxError):
        if len(stack) == 0 or (stack[-1].filename != exc.filename
                               or stack[-1].lineno != exc.lineno):
            frame = traceback.FrameSummary(exc.filename,
                                           exc.lineno,
                                           None,
                                           line=exc.text)
            stack.append(frame)

    stack.reverse()
    i = 0

    if frame_stack is not None:
        _id = ''.join(
            random.choice([chr(i) for i in range(ord('a'), ord('z'))])
            for _ in range(10))
        holders = []
        strong = []
        for _frame in frame_stack:
            _frame = _frame.tb_frame
            holder = NamespaceHolder(_frame.f_locals, _frame.f_globals)
            strong.append(holder)
            holders.append(weakref.ref(holder))

        if _globals is not None:
            _globals["__namespaces__"] = strong

        console.namespaces[_id] = holders
    else:
        _id = None

    for frame in stack:

        if isinstance(tb, list):

            path = os.path.abspath(frame.f_code.co_filename)
            line = ""
            try:
                with open(path, "r", encoding="utf-8") as f:
                    line = f.read().split("\n")[frame.f_lineno - 1]
            except (FileNotFoundError, IndexError):
                pass

            while line.startswith(" ") or line.startswith("\t"):
                line = line[1:]

            stack_json.append({
                "file_path": path,
                "lineno": frame.f_lineno,
                "line": line,
                "name": frame.f_code.co_name,
                "index": i,
                "_id": None,
            })
        else:
            stack_json.append({
                "file_path": frame.filename,
                "lineno": frame.lineno,
                "line": frame.line,
                "name": frame.name,
                "index": i,
                "_id": _id
            })
        i += 1

    traceback_json["stack"] = stack_json

    data = json.dumps(traceback_json, indent=True)
    return data
Beispiel #18
0
 def test_len(self):
     f = traceback.FrameSummary("f", 1, "dummy", line="line")
     self.assertEqual(len(f), 4)
 def test_explicit_line(self):
     f = traceback.FrameSummary('f', 1, 'dummy', line='line')
     self.assertEqual('line', f.line)