How to organize test cases with PyUnit

Syver Enstad syver-en+usenet at online.no
Sat Jul 20 11:43:24 EDT 2002


donnal at donnal.net (Donnal Walter) writes:

> 
> Yes, it's all very confusing to me. I love unit tests, but I've been
> unable to grok the API for TestSuites. Let's say I have a module named
> 
> "cell.py" and a corresponding test module "unit.cell_unit.py" with the
> 
> following code:
> 
> import unittest
> from cell import Cell
> 
> class Test(unittest.TestCase):
> 
>     def test1(self):
>         x = Cell()
>         self.failUnless(isinstance(x, Cell))
> 
>     def test2(self):
>         assert_(1 != 2)
> 
> if __name__ == '__main__':
>     unittest.main()
> 
> This is just as Peter suggested above, and I can run this unit test
> from the command line just fine. But, now let's say that I want to
> make it part of a test suite by adding the following code to cell.py:
> 
> if __name__ == '__main__':
>     import unittest
>     import unit.cell_unit
>     ts = unittest.TestSuite()
>     ts.addTest(unit.cell_unit.Test())
>     unittest.TextTestRunner().run(ts)
> 
> Now I get the following error:
> ValueError: no such test method in unit.cell_unit.Test: runTest
> 
> unless I add a runTest definition to cell_unit.Test:
> 
>     def runTest(self):
>         self.test1()
>         self.test2()
>         .
>         .
>         .
> 
> Somehow I don't think this is how it was intended to be used, but so
> far it is the only way I can figure out to make it work. Can anyone
> tell me what am I doing wrong?

The derived TestCase class works as follows, if you instantiate it
without any arguments to the ctor it will run setUp (if it exists)
then run the method runTest (which doesn't exist in your case) and
then run tearDown (if it exists). 

If you want to build you're own TestSuite with all methods prefixed
with test, you can do like this:

suite = TestSuite()
suite.addTest(unit.cell_unit.Test('test1'))
suite.addTest(unit.cell_unit.Test('test2'))

There is a TestLoader class (or hierarchy I can't remember) in
unitttest.py that will do this automagically for you by introspecting
your module and sucking out all TestCase derived classes and building
TestSuite objects with all 'test' prefixed methods.

As for me I just put:

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

In the bottom of my module and I can just run the module and it will
be done for me.

-- 

Vennlig hilsen 

Syver Enstad



More information about the Python-list mailing list