sort of a beginner question about globals

Scott David Daniels Scott.Daniels at Acm.Org
Fri Apr 15 15:07:44 EDT 2005


Duncan Booth wrote:
> fred.dixon wrote:
> 
>>:) unit test is something on my to-learn list. seems involved and i
>>haven't seen any straight forward tutorials yet. as yet i still
>>consider myself a hobbyist  at best.
> 
> Hmm, I believe you are right. I can't see any straight-forward tutorials 
> which use Python. I found a tutorial at onlamp.com, but it doesn't seem to 
> me to explain TDD at all clearly.
> 

Here's a simple sketch of how to start:

Create a file named "test_prog.py" (where "prog.py" is the module you
are going to develop).  Then stick in the following as the initial
contents of the file (I'm over-indenting by four here):

     import unittest
     import prog   # this should be your module

     class TestCase(unittest.TestCase):
         def setUp(self):
             self.whatever = 'build commonly used data'
             # this picks up any setup common to any test case

         def test_first(self):
             '''Simplest functioning test use of our function'''
             self.assertEqual(42, prog.magic(1)) # use a better test

         def test_second(self):
             '''magic should fail with an appropriate exceptions'''
             self.assertRaises(TypeError, prog.magic, 'q')


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


More details can be found in the unittest documentation, but this may
be enough to get you started testing.  Essentially, new test cases
are added as methods on your class(es).  setUp is called before each
test case, so saving a data structure as self.something eliminates
boilerplate at the top of every test; if you don't need anything in
common, don't bother defining setUp.  The test methods should be
named "test_..."; the name is how unittest know which are test cases.
If you have a more elaborate setup for a bunch of tests, create a new
class as a subclass of unittest.TestCase (or eventually inherriting
from it).  unittest uses all classes defined in the test_prog module
that are subclasses of unittest.TestCase.

To run all of these the tests, at a command prompt type:
     python test_prog.py

To run them all and see which are being run,
     python test_prog.py -v

You can run individual tests with:
     python test_prog.py TestCase.test_second

TestCase here is the name of the class you chose to hold a block of test
cases.  You can run all of the tests under a single class as:
     python test_prog.py TestCase.test_second

--Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Python-list mailing list