Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 9 additions & 12 deletions pykern/pkdebug.py
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ def pkdc(fmt, *args, **kwargs):
_printer._write(fmt, args, kwargs, with_control=True)


def pkdexc(exc_info=None):
def pkdexc(exc_info=None, simplify=False):
"""Return last exception and stack as a string

Must be called from an ``except``. This function removes
Expand All @@ -193,27 +193,24 @@ def pkdexc(exc_info=None):

Args:
exc_info (tuple): (type(e), e, traceback) [sys.exc_info]
simplify (bool): only print the first stack trace
Returns:
str: formatted exception and stack trace
"""
try:
e = exc_info or sys.exc_info()
if hasattr(traceback, "TracebackException"):
return "".join(
traceback.format_exception(*e)
+ ["\nException was printed at:\n\n"]
rv = traceback.format_exception(*e)
if not simplify:
rv += (
["\nException was printed at:\n\n"]
+ traceback.format_exception_only(e[0], e[1])
+ traceback.format_stack()[:-2],
)

else:
return "".join(
traceback.format_exception_only(e[0], e[1])
+ traceback.format_stack()[:-2]
+ traceback.format_tb(e[2]),
)
return "".join(rv)

except Exception as e:
raise
pkdlog("{}", e)
return "pykern.pkdebug.pkdexc: unable to retrieve exception info"


Expand Down
13 changes: 7 additions & 6 deletions tests/pkdebug1_test.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
# -*- coding: utf-8 -*-
"""pytest for `pykern.pkdebug`

:copyright: Copyright (c) 2015-2020 RadiaSoft LLC. All Rights Reserved.
:license: http://www.apache.org/licenses/LICENSE-2.0.html
"""
from __future__ import absolute_import, division, print_function

import inspect
import os
Expand Down Expand Up @@ -259,6 +257,7 @@ def test_pkdc_deviance(capsys):
def test_pkdexc():
"""Verify `pkdexc` includes down the stack that print_exception"""
from pykern.pkdebug import init, pkdexc
from pykern import pkunit

init()

Expand All @@ -273,10 +272,12 @@ def tag1234():

actual = tag1234()
for expect in "xyzzy", "force_error", "tag1234", "test_pkdexc":
assert expect in actual, "{}: call not found: {}".format(expect, actual)
assert not re.search(
r"tag1234.*tag1234.*tag1234", actual, flags=re.DOTALL
), "tag1234: found routine thrice in exception stack: {}".format(actual)
pkunit.pkok(expect in actual, "{}: call not found: {}", expect, actual)
pkunit.pkok(
not re.search(r"tag1234.*tag1234.*tag1234", actual, flags=re.DOTALL),
"tag1234: found routine thrice in exception stack: {}",
actual,
)


def test_pkdp(capsys):
Expand Down