Book Image

Practical Maya Programming with Python

By : Robert Galanakis
Book Image

Practical Maya Programming with Python

By: Robert Galanakis

Overview of this book

Table of Contents (17 chapters)
Practical Maya Programming with Python
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Using the doctest module


All of the example code in this book that is executed at the interactive interpreter (like the String formatting example code in this appendix) was created using Python's doctest module. The doctest module allows the writing of executable test code within the docstrings of modules, classes, functions, and methods. It is a great way to not just test your code, but provide executable documentation. For example, we could create a file C:\mayapybook\pylib\doctestexample.py with the following:

def adder(a, b):
    """
    Return a added to b.

    >>> adder(1, 2)
    3
    >>> adder('a', 'b')
    'ab'
    >>> adder(1, 'b')
    Traceback (most recent call last):
    TypeError: unsupported operand type(s) for +: 'int' and 'str'
    """
    return a + b

Now if you run this file through the doctest module, it will run all the prompt-like lines and ensure they produce the correct result. If the module is successful, you will get no feedback.

> mayapy –m doctest doctestexample.py

If we change one of the tests to force a failure (for example, change adder(1, 2) to adder(1, 3)) and run the command line again, we should get the following feedback:

> mayapy -m doctest doctestexample.py
******************************************************************
File " C:\mayapybook\pylib\doctestexample.py", line 6, in doctestexample.adder
Failed example:
    adder(1, 3)
Expected:
    3
Got:
    4
******************************************************************
1 items had failures:
   1 of 3 in doctestexample.adder
***Test Failed*** 1 failures.

There is a lot more to doctest that isn't covered in this section, including how to customize the way it runs. I mention doctest here for two reasons. The first is that it was used extensively behind the scenes to develop the code for this book. If you look at the source code repository (see the Using the GitHub repository for this book section later in this appendix), you will see it used in every chapter. It was an essential tool for writing correct examples.

The second reason I mention doctest, which is personal for me, is that doctest was my first introduction to unit testing. I consider unit testing an essential Python practice (see the Starting Test-Driven Development section next). It is much easier to get into doctest than any unit testing framework, and even when you start to use a different test framework heavily, using doctest to achieve correct, executable examples in your docstrings is a great practice.

If you have never done automated testing in Python, I highly recommend taking a look at doctest.