As of 2.7 (per the documentation) you get setUpClass and tearDownClass which execute before and after the tests in a given class are run, respectively. Alternatively, if you have a group of them in one file, you can use setUpModule and tearDownModule (documentation).
EDIT: Note that setUpClass and tearDownClass must be declared using @classmethod. Another answer to this question includes sample code.
Otherwise your best bet is probably going to be to create your own derived TestSuite and override run(). All other calls would be handled by the parent, and run would call your setup and teardown code around a call up to the parent's run method.
As of 2.7 (per the documentation) you get setUpClass and tearDownClass which execute before and after the tests in a given class are run, respectively. Alternatively, if you have a group of them in one file, you can use setUpModule and tearDownModule (documentation).
EDIT: Note that setUpClass and tearDownClass must be declared using @classmethod. Another answer to this question includes sample code.
Otherwise your best bet is probably going to be to create your own derived TestSuite and override run(). All other calls would be handled by the parent, and run would call your setup and teardown code around a call up to the parent's run method.
I have the same scenario, for me setUpClass and tearDownClass methods works perfectly
import unittest
class Test(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls._connection = createExpensiveConnectionObject()
@classmethod
def tearDownClass(cls):
cls._connection.destroy()
unit testing - Python unittests, statement before test cases - Stack Overflow
Python unittest startTestRun to execute setup only once before all tests - Stack Overflow
How to a run specific code before & after each unit test in Python - Stack Overflow
Is there a Python unittest function that runs once at the start and end of a test suite? - TestMu AI Community
The problem was that in those 2 answers, the startTestRun method was not in any class. It should be like this:
import unittest
class TestResult(object):
def startTestRun(self):
print('once before all tests')
setattr(unittest.TestResult, 'startTestRun', TestResult.startTestRun)
If you need to tidy up after all tests, that's the same with stopTestRun:
import unittest
class TestResult(object):
def stopTestRun(self):
print('once after all tests')
setattr(unittest.TestResult, 'stopTestRun', TestResult.stopTestRun)
import sys
sys.path.insert(0, '../src')
import vader
import unittest
class TestVader(unittest.TestCase):
def setUp(self):
self.testDbData = [DATA]
def test_build_training_data(self):
dataStruct = vader.build_data_struct(self.testDbData)
def test_get_points(self):
dataStruct = vader.build_data_struct(self.testDbData)
this is what i did for one of my project