doctest¶For your convenience, this notebook includes the entire contents of accountdoctest.py so you can modify it and rerun the tests. When you execute the cell containing accountdoctest.py, the doctests will execute.
doctest and the testmod Function¶doctest module helps you test your code and conveniently retest it after you make modificationsdoctest module’s testmod function, it inspects your functions’, methods’ and classes' docstrings looking for sample Python statements preceded by >>>, each followed on the next line by the given statement’s expected output (if any)testmod executes those statements and confirms that they produce the expected outputtestmod reports errors indicating which tests failed so you can locate and fix the problems in your codeAccount Class¶The file accountdoctest.py contains the class Account from this chapter’s first example
__init__’s docstring to include four tests which can be used to ensure that the method works correctly:Account object named account1account1’s name attribute should be if the first test executed successfully account1’s balance attribute should be if the first test executed successfullyAccount object with an invalid initial balanceValueError exception should occur in this case# accountdoctest.py
"""Account class definition."""
from decimal import Decimal
class Account:
"""Account class for demonstrating doctest."""
def __init__(self, name, balance):
"""Initialize an Account object.
>>> account1 = Account('John Green', Decimal('50.00'))
>>> account1.name
'John Green'
>>> account1.balance
Decimal('50.00')
The balance argument must be greater than or equal to 0.
>>> account2 = Account('John Green', Decimal('-50.00'))
Traceback (most recent call last):
...
ValueError: Initial balance must be >= to 0.00.
"""
# if balance is less than 0.00, raise an exception
if balance < Decimal('0.00'):
raise ValueError('Initial balance must be >= to 0.00.')
self.name = name
self.balance = balance
def deposit(self, amount):
"""Deposit money to the account."""
# if amount is less than 0.00, raise an exception
if amount < Decimal('0.00'):
raise ValueError('amount must be positive.')
self.balance += amount
if __name__ == '__main__':
import doctest
doctest.testmod(verbose=True)
__main__¶__name__'__main__' as the module’s name__name__ in an if statement to specify code that should execute only if the source file is executed as a scriptdoctest module and call the module’s testmod function to execute the docstring unit tests accountdoctest.py as a script to execute the teststestmod with no arguments, it does not show test results for successful teststestmod with the keyword argument verbose=True, which shows every test’s resultsaccountdoctest.py by preceding each with a #, then run accountdoctest.py as a script%doctest_mode Magic¶In [] and Out[] prompts are not compatible with doctest, so IPython provides the magic %doctest_mode to display prompts in the correct doctest format©1992–2020 by Pearson Education, Inc. All Rights Reserved. This content is based on Chapter 5 of the book Intro to Python for Computer Science and Data Science: Learning to Program with AI, Big Data and the Cloud.
DISCLAIMER: The authors and publisher of this book have used their best efforts in preparing the book. These efforts include the development, research, and testing of the theories and programs to determine their effectiveness. The authors and publisher make no warranty of any kind, expressed or implied, with regard to these programs or to the documentation contained in these books. The authors and publisher shall not be liable in any event for incidental or consequential damages in connection with, or arising out of, the furnishing, performance, or use of these programs.