I want to split my Python 3.4 unit tests in separate modules and still be able to control which tests to run or skip from the command line, as if all tests were located in the same file. I'm having trouble doing so.
According to the docs, command line arguments can be used to select which tests to run. For example:
TestSeqFunc.py:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import random
import unittest
class TestSequenceFunctions(unittest.TestCase):
def setUp(self):
self.seq = list(range(10))
def test_shuffle(self):
# make sure the shuffled sequence does not lose any elements
random.shuffle(self.seq)
self.seq.sort()
self.assertEqual(self.seq, list(range(10)))
# should raise an exception for an immutable sequence
self.assertRaises(TypeError, random.shuffle, (1,2,3))
def test_choice(self):
element = random.choice(self.seq)
self.assertTrue(element in self.seq)
def test_sample(self):
with self.assertRaises(ValueError):
random.sample(self.seq, 20)
for element in random.sample(self.seq, 5):
self.assertTrue(element in self.seq)
if __name__ == '__main__':
unittest.main()
can be controlled with either:
./TestSeqFunc.py
to run all tests in the file,
./TestSeqFunc.py TestSequenceFunctions
to run all tests defined in the TestSequenceFunctions class, and finally:
./TestSeqFunc.py TestSequenceFunctions.test_sample
to run the specific test_sample()
method.
The problem I have is that I cannot find an organization of files that will allow me to:
- Have multiple modules containing multiple classes and methods in separate files
- Use a kind of wrapper script that will give the same kind of control over which tests (module/file, class, method) to run.
The problem I have is I cannot find a way to emulate the python3 -m unittest
behaviour using a run_tests.py
script. For example, I want to be able to do:
- Run all the tests in the current directory
So
./run_tests.py -v
should do do the same aspython3 -m unittest -v
- Run one module (file):
./run_tests.py -v TestSeqFunc
being equivalent topython3 -m unittest -v TestSeqFunc
- Run one class:
./run_tests.py -v TestSeqFunc.TestSequenceFunctions
being equivalent topython3 -m unittest -v TestSeqFunc.TestSequenceFunctions
- Run specific methods from a class:
./run_tests.py -v TestSeqFunc.TestSequenceFunctions.test_sample
being equivalent topython3 -m unittest -v TestSeqFunc.TestSequenceFunctions.test_sample
Note that I want to:
- be able to pass arguments to unittests, for example the verbose flag used previously;
- allow running specific modules, classes and even methods.
As of now, I use a suite()
function in my run_all.py
script which loads manually the modules and add their class to a suite using addTest(unittest.makeSuite(obj))
. Then, my main() is simple:
if __name__ == '__main__':
unittest.main(defaultTest='suite')
But using this I cannot run specific tests. In the end, I might just execute python3 -m unittest <sys.argv>
from inside the run_all.py
script, but that would be inelegant...
Any suggestions?!
Thanks!