Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python unittest methods

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?

like image 316
Falmarri Avatar asked Aug 09 '10 22:08

Falmarri


People also ask

Which is better Pytest or unittest?

Which is better – pytest or unittest? Although both the frameworks are great for performing testing in python, pytest is easier to work with. The code in pytest is simple, compact, and efficient. For unittest, we will have to import modules, create a class and define the testing functions within that class.


2 Answers

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.

like image 191
S.Lott Avatar answered Sep 21 '22 05:09

S.Lott


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.

like image 31
satoru Avatar answered Sep 20 '22 05:09

satoru