Posts Play a bit with doctest
Post
Cancel

Play a bit with doctest

I discover randomly the doctest module and decided to play a bit with it. This module allows you to write tests inside your docstring and to execute it. Can be useful if you want to provide easily some examples on how to use the function-

Easy example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import doctest


def my_function(a, b):
    """
    Returns a * b.
    Works with numbers:
    >>> my_function(2, 3)
    6
    and strings:
    >>> my_function('a', 3)
    'aaa'
    """
    return a * b


if __name__ == "__main__":
    doctest.testmod()

If you want to run the test, and see the results, you need to execute your file with the following command

1
python3 my_file_name.py -v

Example with a class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import doctest


class MyClass:
    """MyClass
    >>> m = MyClass()
    >>> m.hello()
    hello
    >>> m.world()
    world
    """

    def hello(self):
        """method hello"""
        print('hello')

    def world(self):
        """method world"""
        print('world')


if __name__ == "__main__":
    doctest.testmod()

More examples and full project

I implemented more examples with complex structures and doctest string in a specific RST file in this Github repo

This post is licensed under CC BY 4.0 by the author.