Search code examples
pythondoctest

python doctest exception test handling


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.


Solution

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