85

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?

U13-Forward
  • 69,221
  • 14
  • 89
  • 114
Lorin Hochstein
  • 57,372
  • 31
  • 105
  • 141

3 Answers3

113

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
doctaphred
  • 2,504
  • 1
  • 23
  • 26
cnu
  • 36,135
  • 23
  • 65
  • 63
13
>>> 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.

runsun
  • 424
  • 5
  • 8
  • 5
    You can ignore the exception details by using the ellipsis `...` as in the other answers and the documentation: https://docs.python.org/3/library/doctest.html#what-about-exceptions I see ellipsis as the more readable variant. – pabouk - Ukraine stay strong Nov 16 '21 at 13:58
5
>>> 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

glickind
  • 61
  • 1
  • 2
  • Are you saying we can omit the ellipsis? It's not clear that we can, or how to do it, based on the answer. If we can, could you edit your answer to make that clearer please? It would be pretty useful. Thanks. – Carl Smith May 21 '18 at 12:23
  • 1
    You don't need ellipsis – SwimBikeRun Dec 08 '18 at 08:39