Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

doctest

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?

like image 407
Lorin Hochstein Avatar asked Aug 15 '08 18:08

Lorin Hochstein


People also ask

Can doctest be used to test docstrings?

There are several common ways to use doctest: To check that a module's docstrings are up-to-date by verifying that all interactive examples still work as documented. To perform regression testing by verifying that interactive examples from a test file or a test object work as expected.

Can we handle unpredictable output using doctest in Python?

When the tests include values that are likely to change in unpredictable ways, and where the actual value is not important to the test results, you can use the ELLIPSIS option to tell doctest to ignore portions of the verification value.

How do you use ellipsis doctest?

The “ #doctest: +ELLIPSIS ” comment after the call to unpredictable() tells doctest to turn on the ELLIPSIS option for that test. The ... replaces the memory address in the object id, so that portion of the expected value is ignored and the actual output matches and the test passes.


2 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 
like image 71
cnu Avatar answered Oct 06 '22 02:10

cnu


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

like image 34
runsun Avatar answered Oct 06 '22 02:10

runsun