Can you check that an exception is thrown with doctest in Python?

Question:

Is it possible to write a doctest unit test that will check that an exception is raised?
For example, if I have a function foo(x) that is supposed to raise an exception if x < 0, how would I write the doctest for that?

Asked By: Lorin Hochstein

||

Answers:

Yes. You can do it. The doctest module documentation and Wikipedia has an example of it.

   >>> x
   Traceback (most recent call last):
     ...
   NameError: name 'x' is not defined
Answered By: cnu
>>> import math
>>> math.log(-2)
Traceback (most recent call last):
 ...
ValueError: math domain error

ellipsis flag # doctest: +ELLIPSIS is not required to use … in Traceback doctest

Answered By: glickind
>>> scope # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
NameError: name 'scope' is not defined

Don’t know why the previous answers don’t have the IGNORE_EXCEPTION_DETAIL. I need this for it to work. Py versioin: 3.7.3.

Answered By: runsun
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.