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

PythonDoctest

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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

Solution 2 - Python

>>> 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.

Solution 3 - Python

>>> 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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLorin HochsteinView Question on Stackoverflow
Solution 1 - PythoncnuView Answer on Stackoverflow
Solution 2 - PythonrunsunView Answer on Stackoverflow
Solution 3 - PythonglickindView Answer on Stackoverflow