cardamom
cardamom

Reputation: 7441

inform the user if a certain exception is raised while running unittest

I have been writing unittests. Although there must be a way, I find it exceptionally difficult to get any print statement in a unittest class method to print anything, but can see what is going on when unittest shows me the diffs.

Have previously tested for exceptions with assertRaises as described here, but this is about detecting not asserting.

The tests assume a certain hardware device is plugged into the USB port when they run. The program being tested raises the following if someone tries to run it without the device connected:

RuntimeError('Device not reachable. Please connect it to USB')

I just tested sys.exit(0) inside a unittest method and that didn't exit either. Still, exiting is not that important, is probably better if all the tests fail, but it would be polite if the first test detects that Exception then prints a message to the user such as "The device needs to be connected before running unittests.". Does anyone know how to achieve this?

It is the standard class as described in the docs inheriting from unittest.TestCase with a setUp and tearDown method and the tests in between.

Upvotes: 1

Views: 73

Answers (1)

olinox14
olinox14

Reputation: 6662

There are a few solutions you could try:

To intercept every exception raised:

SYS_EXCEPT_HOOK = sys.excepthook
def _excepthook(typ, value, trace):
    if typ is RuntimeError:
        print("{}\n{}\n{}".format(typ.__name__, value, ''.join(traceback.format_tb(trace))))
    SYS_EXCEPT_HOOK(typ, value, trace)
sys.excepthook = _excepthook

Upvotes: 1

Related Questions