I've tried to use doctest for following source:

def add_greeting(L=[]):
    """ (list) -> NoneType

    Append 'hello' to L and print L.

    >>> greetings_list = ['hi', 'bonjour']
    >>> add_greeting(greetings_list)
    >>> greetings_list
    ['hi', 'bonjour', 'hello']
    """

    L.append('hello')
    print(L)


if __name__ == '__main__':
    import doctest
    print(doctest.testmod())

When I've launched this file like 'python my_file.py', I got the following:

python my_file.py
**********************************************************************
File "my_file.py", line 9, in __main__.add_greeting
Failed example:
    add_greeting(greetings_list)
Expected nothing
Got:
    ['hi', 'bonjour', 'hello']
**********************************************************************
1 items had failures:
   1 of   3 in __main__.add_greeting
***Test Failed*** 1 failures.
TestResults(failed=1, attempted=3)

Could anyone help me with this error, please? Why I've got 'Expected nothing' in this case? How it could be fixed?

有帮助吗?

解决方案

Try

def add_greeting(L=[]):
    """ (list) -> NoneType

    Append 'hello' to L and print L.

    >>> greetings_list = ['hi', 'bonjour']
    >>> add_greeting(greetings_list)
    ['hi', 'bonjour', 'hello']
    >>> greetings_list
    ['hi', 'bonjour', 'hello']
    """

    L.append('hello')
    print(L)


if __name__ == '__main__':
    import doctest
    print(doctest.testmod())

You get the error because you have print(L) at the end of add_greeting but your sample console output in the docstring does not expect anything to be printed or returned by add_greeting.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top