How to avoid showing orginal exception in pytest when reraising exception?

Question:

I use a library with very deep stack. When there is an exception, trace is enormous (~6 pages), even the true reason is a side effect (no permission), and it’s very clear from exception text. It is really confusing in tests, so I wrote this code:

def _command(self, lib_handler, cmd):
    try:
        lib_handler.run(cmd)
    except Exception as e:
        raise MyError(e) from e

The problem is that when exception happens in tests, and there is MyError exception, pytest shows original (enormous) traceback, then write The above exception was the direct cause of the following exception: and shows my (tiny and reasonable) traceback.

I want to disable showing the original traceback and keep pytest to shorter traceback in mine code (without unwinding traceback into the library call). Is it possible? How to do it?

Asked By: George Shuklin

||

Answers:

To avoid chaining the exception you need to raise your custom exception from None and not from the expected exception

def _command(self, lib_handler, cmd):
    try:
        lib_handler.run(cmd)
    except Exception as e:
        raise MyError(e) from None
Answered By: Guy
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.