[Tutor] my text adventure

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Fri Dec 2 22:23:32 CET 2005



> i am attempting to write a dig function that will create rooms.
> i have succeeded only in getting a headache :)
> any suggestions on where i am going wrong would
> be super helpful.

Hi David,

You may want to write a unit test to make sure that all the methods of
your class are doing the right thing.  The issue with programs is that,
when something goes wrong, any component might be responsible: unit tests
allow us to get more confidence that all components are working.

(And actually, they is something wrong with one of your helper functions;
that's why I'm encouraging writing the proper test cases.  *grin*)


Here's one that will help point out a problem:

####################################################
import unittest

class TestRoom(unittest.TestCase):
    def testNorthFromOrigin(self):
        room1 = Room('startroom',[0,0])
        self.assertEqual([0, 1], room1.nextdoor('n'))

    def testSouthFromOrigin(self):
        room1 = Room('startroom',[0,0])
        self.assertEqual([0, -1], room1.nextdoor('s'))

    def testEastFromOrigin(self):
        room1 = Room('startroom',[0,0])
        self.assertEqual([1, 0], room1.nextdoor('e'))

    def testWestFromOrigin(self):
        room1 = Room('startroom',[0,0])
        self.assertEqual([-1, 0], room1.nextdoor('w'))

if __name__ == '__main__':
    unittest.main()
####################################################


Do these tests make sense?  It's just making sure that nextdoor is doing
something reasonable and returning the proper coordinates that we expect.
Try testing your code, and you should see something.



For a more comprehensive example of unit testing, you might want to look
at:

    http://diveintopython.org/unit_testing/

which has a good long-running example of Python's unittest module.



Hope this helps!



More information about the Tutor mailing list