Is it possible to work with multi-line statements using doctest?

Is it possible to work with multi-line statements using python doctest

For example, in doctest does not work

>>> for s in [1,2,3]:
...     for t in [4,5,6]:
...         print s*t

      

I need more than 3 statements to be executed from doctest, please help.

Thank you in advance

+3


source to share


2 answers


It doesn't work doctest

. It tests an expression that evaluates to a value; it does not capture or test the output. So what you want to do is create a list that you can test, which you can easily do in one line using a list comprehension:



>>> [s * t for s in [1, 2, 3] for t in [4, 5, 6]]
[4, 5, 6, 8, 10, 12, 12, 15, 18]

      

+1


source


You probably did something wrong. Below is the correct example.

test.py:

"""
>>> for s in [1,2,3]:
...     for t in [4,5,6]:
...         print s*t
4
5
6
8
10
12
12
15
18
"""

      

It works great:

$ python -m doctest -v test.py
Trying:
    for s in [1,2,3]:
        for t in [4,5,6]:
            print s*t
Expecting:
    4
    5
    6
    8
    10
    12
    12
    15
    18
ok
1 items had no tests:
    test.print_and_return
1 items passed all tests:
   1 tests in test
1 tests in 2 items.
1 passed and 0 failed.
Test passed.

      



Also note that it doctest

captures both the return value and the output:

def print_and_return():
    """
    >>> print_and_return()
    1
    2
    """
    print(1)
    return 2

      

Any expected result must immediately follow the final "→>" or "..." line containing the code, and the expected result (if any) propagates to the next "→>" or all-spaces.

https://docs.python.org/2/library/doctest.html#how-it-works

+7


source







All Articles