views:

86

answers:

5

Can I call a test method from within the test class in python? For example:


class Test(unittest.TestCase):
    def setUp(self):
        #do stuff

    def test1(self):
        self.test2()

    def test2(self):
        #do stuff

update: I forgot the other half of my question. Will setup or teardown be called only after the method that the tester calls? Or will it get called between test1 entering and after calling test2 from test1?

A: 

All methods whose name begins with the string 'test' are considered unit tests (i.e. they get run when you call unittest.main()). So you can call methods from within the Test class, but you should name it something that does not start with the string 'test' unless you want it to be also run as a unit test.

unutbu
A: 

sure, why not -- however that means test2 will be called twice -- once by test1 and then again as its own test, since all functions named test will be called.

nosklo
I think the answer should be "Technically yes, **but don't**." Further, I think they want inheritance among their test cases, not delegation.
S.Lott
I was just wondering if doing this would cause the testing class to get screwed up in number of tests its run or just something weird like that
Falmarri
A: 

Yes to both:

  • setUp will be called between each test
  • test2 will be called twice.

If you would like to call a function inside a test, then omit the test prefix.

Tim McNamara
+2  A: 

Try running the following code:

import unittest

class Test(unittest.TestCase):
    def setUp(self):
        print 'Setting Up'

    def test1(self):
        print 'In test1'
        self.test2()

    def test2(self):
        print 'In test2'

    def tearDown(self):
        print 'Tearing Down'

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

And the results is:

Setting Up
In test1
In test2
Tearing Down
.Setting Up
In test2
Tearing Down
.
----------------------------------------------------------------------
Ran 2 tests in 0.000s

OK

Now you see, setUp get called before a test method get called by unittest, and tearDown is called after the call.

Satoru.Logic
Chosen for doing what I should have done
Falmarri
+3  A: 

This is pretty much a Do Not Do That. If you want tests run in a specific order define a runTest method and do not name your methods test....

class Test_Some_Condition( unittest.TestCase ):
def setUp( self ):
    ...
def runTest( self ):
    step1()
    step2()
    step3()
def tearDown( self ):
    ...

This will run the steps in order with one (1) setUp and one (1) tearDown. No mystery.

S.Lott