Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python doctests: test for None

Tags:

python

doctest

Using Python 2.7 I'm trying to test that the result of a particular function call is None

I would expect these tests to pass (excuse the rather silly example)

def six_or_none(val):     """     >>> six_or_none(6)     6     >>> six_or_none(4)     None     """     if val == 6:         return 6     return None 

However they yield the following result

Failed example:     six_or_none(4) Expected:     None Got nothing 

What's the correct way to test for None in doctests?

like image 595
robert_b_clarke Avatar asked Nov 18 '13 12:11

robert_b_clarke


People also ask

What is the correct way to run all the Doctests?

Right click on a blank space in the python code, and there is a menu option to run all the Doctests found in the file, not just the tests for one function.

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?

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.


2 Answers

The Python interpreter ignores None return values, so doctests do the same.

Test for is None instead:

>>> six_or_none(4) is None True 
like image 128
Martijn Pieters Avatar answered Sep 17 '22 19:09

Martijn Pieters


Other option would be a direct check for None:

def six_or_none(val):     """     >>> six_or_none(6)     6     >>> six_or_none(4)     """     if val == 6:         return 6     return None 
like image 23
alko Avatar answered Sep 18 '22 19:09

alko