Arrays as expected results in doctest. Error with text 'Expected nothing'. Python 3.3.2

StackOverflow https://stackoverflow.com/questions/21874715

  •  13-10-2022
  •  | 
  •  

سؤال

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