21

Is it possible to work with multiline statements using python doctest?

For example, the following is not working in doctest:

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

I need the above three statements to be executed from doctest.

Asclepius
  • 57,944
  • 17
  • 167
  • 143
Rajesh Kumar
  • 1,270
  • 4
  • 15
  • 31

2 Answers2

34

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 just fine:

$ 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 please note that doctest captures both the return value and the output:

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

Any expected output must immediately follow the final '>>> ' or '... ' line containing the code, and the expected output (if any) extends to the next '>>> ' or all-whitespace line.

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

raacer
  • 5,302
  • 3
  • 27
  • 46
-3

Edit: my answer is wrong; see the comment from raacer below. I can't delete this because it's the accepted answer.

That's not how doctest works. It tests an expression that evaluates to a value; it does not capture and test output. So what you want to do is create a list that can be tested, which you can easily do in a single 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]
kindall
  • 178,883
  • 35
  • 278
  • 309
  • But in my project,if something fails in doctest, then it displays HTTP 401 error, so i need it to be worked using doctest module only. If it does not work then I need to comeup with all in single statement which becomes very complicated.it is bad to me that doctest wont work for multiline statements. Thanks for the information. – Rajesh Kumar May 26 '15 at 03:43
  • Well, there's no reason you have to use `doctest` for all your testing. – kindall May 26 '15 at 04:33
  • Also, you can write your test as a function, then call that from `doctest`. – kindall May 26 '15 at 16:02
  • 1
    This is not true. Doctest actually tests both return value and output. – raacer Apr 10 '17 at 16:32