Sonntag, 27. April 2014

Python doctest

Most of my exercises for SCIP come as a stub function where you have to implement the logic. To provide a way to self test your implementation, the stub functions contain also something called doctests.

doctests are a nice way to quickly add tests to your functions. This is what the Python manual says: The doctest module searches for pieces of text that look like interactive Python sessions, and then executes those sessions to verify that they work exactly as shown.

Here is an example of one of my exercises:
from operator import add, sub
def a_plus_abs_b(a, b):
    """Return a+abs(b), but without calling abs.

    >>> a_plus_abs_b(2, 3)
    5
    >>> a_plus_abs_b(2, -3)
    5
    """
    if b < 0:
        op = sub
    else:
        op = add
    return op(a, b)
To run the two tests in the comment against the implementation I'm using the following command:
python3 -m doctest -v file.py

Keine Kommentare:

Kommentar veröffentlichen