[Tutor] Class tests

Daniel Yoo dyoo@hkn.eecs.berkeley.edu
Fri, 12 Jan 2001 07:53:25 -0800 (PST)


On Fri, 12 Jan 2001, Sharriff Aina wrote:

> I have just finished coding a class withe several class methods, can
> someone show me how to programmatically test each function in the
> class safely?

There's a Python idiom that lets you make a "main" function --- it looks
like this:

###
if __name__ == '__main__':
    # Rest of the body goes here
###

The body of this if-statement is the traditional place to put stuff that
tests out the class.  You can make an instance of your class, and then
start trying out the class's methods.  Afterwards, running Python on your
program will do the testing.


Let's try one of the classic examples, an Account class that keeps track
of someone's finances.

### account.py
class Account:
    def __init__(self, amount): self.amount = amount
    def withdraw(self, x): self.amount -= x
    def report(self): return "Current balance: %s" % self.amount


if __name__ == '__main__':
    myaccount = Account(100)
    print myaccount.report()
    myaccount.withdraw(42)
    print myaccount.report()
###

Here, I'm just making sure that my member functions are doing the right
thing --- I call each one in turn, and then ask my instance for a
report().

One other thing you can do is use the interpreter --- since you can do
anything in the interpreter, you can also make instances of classes that
you've designed.

Good luck!