views:

117

answers:

2

I am using python unit test module. I am wondering is there anyway to add some delay between every 2 test cases? Because my unit test is just making http request and I guess the server may block the frequent request from the same ip.

+1  A: 
import time
time.sleep(2.5) # sleeps for 2.5 seconds

You might want to consider making the delay a random value between x and y.

ChristopheD
you mean i have to put this after every test case? Is there any universal settings i can use to achieve the same thing?
sza
Hard to tell without seeing your code... but you probably could make all your test cases inherit from one common testcase which provides a `def setUp(self):` method which does the `time.sleep` call.
ChristopheD
+5  A: 

Put a sleep inside the tearDown method of your TestCase

class ExampleTestCase(unittest.TestCase):
    def setUp(self):
        pass

    def tearDown(self):
        time.sleep(1)  # sleep time in seconds

This will execute after every test within that TestCase

EDIT: added setUp because the documentation seems to perhaps indicate that you can't have a tearDown without one, but it's not clear

Daniel DiPaolo
Just for clarification, I did it in the `tearDown` instead of `setUp` because it said "between" and that automatically made me think that it was desirable that the first one run immediately (which in this case is unclear). If it didn't matter about the delay being before or after the first test, putting it in `setUp` and leaving `tearDown` out would work just fine as well.
Daniel DiPaolo
this worked. thank you very much
sza