How to optimise this code?

Peter Otten __peter__ at web.de
Tue Aug 21 18:15:53 CEST 2007


David N Montgomery wrote:

> class testCase:
>     def __init__(self, tc):
>         if tc == 1:self.testCase1()
>         if tc == 2:self.testCase2()
>         if tc == 3:self.testCase3()
>         if tc == 4:self.testCase4()
>         if tc == 5:self.testCase5()
>         if tc == 6:self.testCase6()
> 
>     def testCase1(self):
>         print "tc1"
> 
>     def testCase2(self):
>         print "tc2"
> 
>     def testCase3(self):
>         print "tc3"
> 
>     def testCase4(self):
>         print "tc4"
> 
>     def testCase5(self):
>         print "tc5"
> 
>     def testCase6(self):
>         print "tc6"
> 
> 
>     def testCaseX(self):
>         print "tcX"
> 
> totalNumberOfTestCases = 6
> x = 0
> while x <= totalNumberOfTestCases:
>     x += 1
>     testCase(x)
> 
> 
> This template code is working, but I envisage having 100+ test cases and
> am concerned about my useage of if statements. I would be grateful for
> any pointers as to how I can run all tests cases, regardless of how
> many, in a more efficient manner.

Have a look at the unittest module in the standard library

http://docs.python.org/lib/module-unittest.html

It can do the bookkeeping for you:

>>> import unittest
>>> class TestCase(unittest.TestCase):
...     def testCase1(self):
...             print "first"
...     def testCaseN(self):
...             print "last"
...
>>> unittest.main()
first
.last
.
----------------------------------------------------------------------
Ran 2 tests in 0.001s

OK

Peter



More information about the Python-list mailing list