Reputation: 48559
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?
Upvotes: 7
Views: 3725
Reputation: 391818
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.
Upvotes: 8
Reputation: 33215
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.
Upvotes: 6
Reputation: 18375
Yes to both:
setUp
will be called between each testtest2
will be called twice. If you would like to call a function inside a test, then omit the test
prefix.
Upvotes: 0
Reputation: 222802
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.
Upvotes: 0
Reputation: 879113
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.
Upvotes: 1