Testing

So far we've added read and write functionality to the Address class and added functionality for reading in an entire dictionary of addresses and for writing an entire dictionary of address instances. Now we need to update getAddresses () to une all of these functions. Before w e do that, though, we need to test read Addresses () and writeAddresses (), which means more scaffolding code.

TT TT

Scaffolding code to test reading and writing dictionaries of addresses.

TT TT TT

# populate a dictionary object with some sample data di ct={}

address = Address("Rick Hightower", "920-555-12 12", ["123 Main S dict["Rick Hightower"] = address address = Address("Missy Hightower", "92 0-5 55-1212", ["123 Main dict["Missy Hightower"]=address address = Address("Martha Hightower", "602-555-1212", ["123 Main dict["Martha Hightower"]=address address = Address("Mary Hightower", "52 0-555-12 12", []) dict["Mary Hightower"]=address fname="\\dat\\testaddr.txt" #to hold output filename

# write the dictionary full of addresses out to the file print "calling writeAddresses"

writeAddresses(fname, dict)

# read in the dictionary full of addresses back from # the file we just wrote it to dict_in = {} #to hold input addresses print "calling readAddresses" readAddresses(fname, dict_in)

#show that the input matches the output print "Input" print dict_in print "Output" print dict

#return whether these equal each other return dict==dict_in

Essentially, our scaffolding code populates a Python dictionary with address instances. Then it writes the dictionary to a file and reads it back. Next it displays the input and output dictionaries so that you can test them visually. Finally it tells us whether the input dictionary is equal to the output dictionary. With the way the code is written, it should work until we hit the last line.

For the last line to work, we need to add a_cmp_method to our Address class that iterates through all items in the dictionary and compares them. If all of the items are equal,__cmp_returns that the dictionaries themselves are equal. Here's how we add_cmp_to the Address class:

def cmp (self,other):

Compares one address instance to another.

If the address instances are equal the _cmp_ returns 0.

If the address instances are not equal then we return a non-zero value.

# To implement this all we do is compare the

# dictionaries of the class

# The _dict_ member of the instance holds all

# of the instance fields in a dictionary return cmp(self.__dict_ ,other._dict__)

Was this article helpful?

0 0

Post a comment