Home > front end >  How to run unittest tests from multiple directories
How to run unittest tests from multiple directories

Time:02-03

I have 2 directories containing tests:

project/
|
|-- test/
|    |
|    |-- __init__.py
|    |-- test_1.py
|
|-- my_submodule/
     |
     |-- test/
          |
          |-- __init__.py
          |-- test_2.py

How can I run all tests?

python -m unittest discover . only runs test_1.py

and obviously python -m unittest discover my_submodule only runs test_2.py

CodePudding user response:

unittest currently sees project/my_submodule as an arbitrary directory to ignore, not a package to import. Just add project/my_submodule/__init__.py to change that.

CodePudding user response:

Use a test suite file

A possible solution is to write a test suite file as following:

import unittest

from test import test_1
from my_submodule.test import test_2

loader = unittest.TestLoader()
suite = unittest.TestSuite()

suite.addTest(loader.loadTestsFromModule(test_1))
suite.addTest(loader.loadTestsFromModule(test_2))

runner = unittest.TextTestRunner(verbosity=3)

result = runner.run(suite)

Save the previous file in your folder project and call it runner_test.py.
I have written two example test files as following:

project/test/test_1.py

import unittest

class MyTestCase(unittest.TestCase):

    def test_1(self):
        print("test1")
        self.assertEqual("test1", "test1")


if __name__ == '__main__':
    unittest.main()

project/my_submodule/test/test_2.py

import unittest

class MyTestCase(unittest.TestCase):

    def test_1(self):
        print("test1")
        self.assertEqual("test1", "test1")


if __name__ == '__main__':
    unittest.main()

If you execute the following command:

> cd /path/to/folder/project

> python runner_test.py

The output of previous command (python runner_test.py) is:

test_1 (test.test_1.MyTestCase) ... test1
ok
test_2 (my_submodule.test.test_2.MyTestCase) ... test2
ok

----------------------------------------------------------------------
Ran 2 tests in 0.000s

OK

  • Related