O'Reilly logo

Python Testing Beginner's Guide by Daniel Arbuckle

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Time for action - embedding a doctest in a docstring

We'll embed a test right inside the Python source file that it tests, by placing it inside a docstring.

  1. Create a file called test.py with the following contents:
    def testable(x):
    r"""
    The `testable` function returns the square root of its
    parameter, or 3, whichever is larger.
    >>> testable(7)
    3.0
    >>> testable(16)
    4.0
    >>> testable(9)
    3.0
    >>> testable(10) == 10 ** 0.5
    True
    """
    if x < 9:
    return 3.0
    return x ** 0.5
    
  2. At the command prompt, change to the directory where you saved test.py and then run the tests by typing:
    $ python ‑m doctest test.py
    
    

    Note

    As mentioned earlier before, if you have an older version of Python, this isn't going to work for you. Instead, you need to type python ‑c "__import__('doctest').testmod(__import__('test'))" ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required