1

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.

1
  • The solution is to mock the USB interface calls. Commented Jun 5, 2019 at 10:46

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

Unittest swallows the print statements, so going by this, I will put in some kind of dummy assertEqual just so I can use the msg otherwise probably won't get it to print.
Does it swallow logging too? Did you try?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.