Python doctests: test for None

2019-04-18 15:32发布

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?

2条回答
兄弟一词,经得起流年.
2楼-- · 2019-04-18 15:53

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
查看更多
我命由我不由天
3楼-- · 2019-04-18 16:14

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

Test for is None instead:

>>> six_or_none(4) is None
True
查看更多
登录 后发表回答