Printing backtrace, traceback (Python)

Last edited on

import traceback

def main():
    func1()

def func1():
    func2()

def func2():
    log_backtrace()

    if not test.verify(False, "message"):
        log_backtrace()

def log_backtrace():
    backtrace_frames = traceback.extract_stack()

    filename, line_number, function, code = backtrace_frames[0]
    msg = "Backtrace: %s:%s: %s()\n" % (filename, line_number, function)
    detail = ""
    for frame in backtrace_frames[:-1]:
        filename, line_number, function, code = frame
        detail += "%s:%s: %s()\n" % (filename, line_number, function)
    test.log(msg, detail)
test.py

Resulting log entries (message in first line, details after that):

Log Backtrace: C:/Users/clemens/squish_test_suites/suite_qt4_py/tst_1/test.py:4: main()
Detail C:/Users/clemens/squish_test_suites/suite_qt4_py/tst_1/test.py:4: main()
C:/Users/clemens/squish_test_suites/suite_qt4_py/tst_1/test.py:7: func1()
C:/Users/clemens/squish_test_suites/suite_qt4_py/tst_1/test.py:10: func2()

Fail Not verified
Detail False expression

Log Backtrace: C:/Users/clemens/squish_test_suites/suite_qt4_py/tst_1/test.py:4: main()
Detail C:/Users/clemens/squish_test_suites/suite_qt4_py/tst_1/test.py:4: main()
C:/Users/clemens/squish_test_suites/suite_qt4_py/tst_1/test.py:7: func1()
C:/Users/clemens/squish_test_suites/suite_qt4_py/tst_1/test.py:13: func2()
Test Results