Wednesday, April 24, 2013

Introduction - Basic testing in Python - Using doctest for function tests

You can use doctest to assert that your functions are returning or producing the output you expected.

Here is a very simple function that just returns (as a float type) the multiplication of 2 integers:

def multiply(a,b):
    """ (int,int) -> float

    >>> multiply(2,3)
    6.0
    >>> multiply(3,4)
    12.0
    """
    return float(a*b)

if __name__ == '__main__':
    import doctest
    doctest.testmod()

The important thing to keep from this basic example is that the function returns the multiplication of 2 ints, and converts its result to a float type. The documentation of the function (enclosed by the three ") explains that the function receives 2 ints and returns a float.

Doctest uses the docstring to test the function.

In this case, the call ">>> multiply(2,3)" runs internally in the Python interpreter, and compares the result with the one we wrote. Then it does the same with the second test. If you pay attention you will see that it is as if we were writing those calls in the console ourselves, but in this case using them from the function documentation (Python calls it docstring).

To put it simply, the body of the "if" function is executed if our module, the one with the "multiply" function, is executed directly, and NOT imported. If it is imported, you will be able to use the "multiply" function, but no tests will be run, nor any code in the body of the if statement.

Finally, all these tests run because we used the "import doctest" and "doctest.testmod()" to run these tests. doctest is the module that has the behavior to execute these test cases.

It is very simple, only to serve as a reference to anyone new to the language. Python is being actively used in the scientific community, so a lot of professionals without actual programming experience are using Python. To them, I will aim some of my introductory posts.

No comments:

Post a Comment