Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python doctest exception test handling

Tags:

python

doctest

I have the following contents in a file called test2.txt.

>>> def faulty():  
... yield 5  
... return 7  
Traceback(most recent call last):  
SyntaxError: 'return' with argument inside generator(<doctest test.txt[0]>,line 3)  

I invoke the test run with python -m test2.txt. The results below are quite out of my expectation.

screenshot of terminal output

My thought was that the test should be successful because I have written the expected output in my test2.txt file and it 'almost' matches what I got from the console output. I tried adding the 'File "G:\"'.... line? but the test still failed.

like image 514
Tracy Avatar asked Aug 30 '11 15:08

Tracy


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.

How do you assert exceptions in Python?

There are two ways you can use assertRaises: using keyword arguments. Just pass the exception, the callable function and the parameters of the callable function as keyword arguments that will elicit the exception. Make a function call that should raise the exception with a context.

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 test an exception in unit testing?

assertRaises(exception, callable, *args, **kwds) To catch any of a group of exceptions, a tuple containing the exception classes may be passed as exception. In the example below, a test function is defined to check whether ZeroDivisionError is raised.


1 Answers

doctest is extremely careful with the format of expected exceptions. You missed a space:

Traceback(most recent call last): should be Traceback (most recent call last):

Moreover, this would still fail, as your traceback message is overly specific (and also has incorrect whitespace)! Use the ELLIPSIS or IGNORE_EXCEPTION_DETAIL flags to doctest to make doctest less picky about matching exceptions, as so:

>>> def faulty(): # doctest: +IGNORE_EXCEPTION_DETAIL  
...     yield 5  
...     return 7  
Traceback (most recent call last):  
SyntaxError: 'return' with argument inside generator (...)

(ELLIPSIS would work here too)

like image 193
Devin Jeanpierre Avatar answered Sep 18 '22 12:09

Devin Jeanpierre