Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiline statements using Python doctest

Tags:

python

doctest

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.

like image 759
Rajesh Kumar Avatar asked May 26 '15 03:05

Rajesh Kumar


People also ask

What is the use of doctest in Python?

doctest is a module included in the Python programming language's standard library that allows the easy generation of tests based on output from the standard Python interpreter shell, cut and pasted into docstrings.

Can we handle unpredictable output using doctest in Python?

When the tests include values that are likely to change in unpredictable ways, and where the actual value is not important to the test results, you can use the ELLIPSIS option to tell doctest to ignore portions of the verification value.


1 Answers

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

like image 120
raacer Avatar answered Oct 11 '22 13:10

raacer