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?
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.
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.
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.
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
>>> 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With