Python unit-testing in multiple threads
I would like to unit-test the functionality of a few classes that mainly do file in- and output. Furthermore I would like to do that on multiple cores (--jobs=4).
The problem is, that the files that are created by the classes often have the same name and they get mixed up in multiple threads. What I do currently is that I run each unit-test in a separate directory like so:
def test(self):
if os.path.exists("UniqueDir"):
os.system("rm -rf UniqueDir")
os.mkdir("UniqueDir")
os.chdir("UniqueDir")
#Do the actual testing
os.chdir("..")
os.rmdir("UniqueDir")
The downsides are very obvious:
- Each test must receive a unique directory name
- Each test has this overhead of source which really is not pleasant to look at at all
What approach could I use to 1. separate my tests from one another but 2. 开发者_Python百科do it in a more elegant way?
Any help, suggestion etc. is appreciated!
Cherio Woltan
I would suggest to use the unittest module and build the classes like this:
import unittest
from tempfile import mkdtemp
class Test(unittest.TestCase):
def setUp(self):
self.tempdir = mkdtemp()
os.chdir(self.tempdir)
def tearDown(self):
os.rmdir(self.tempdir)
def testName(self):
#Do the actual testing
pass
if __name__ == "__main__":
unittest.main()
Additionally you could add multiprocessing to create 4 threads.
Edit: removed the os.mkdir because mkdtemp creates a temp directory so it's bogus. Thx Sebastian.
精彩评论