Guglie
Guglie

Reputation: 2441

How to run unittest tests from multiple directories

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

Upvotes: 3

Views: 490

Answers (2)

User051209
User051209

Reputation: 2503

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 name it runner_test.py. The code uses 3 class of the module unittest:

  • TestLoader ---> see the instruction:
loader = unittest.TestLoader()
  • TestSuite ---> see instructions:
suite = unittest.TestSuite()
suite.addTest(...)
  • TextTestRunner ---> see instructions:
runner = unittest.TextTestRunner(verbosity=3)
result = runner.run(suite)

Info about these classes can be found into the documentation.

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

Note

There are other ways to write a test suite: for example see this post and links connected to it.

Upvotes: 2

chepner
chepner

Reputation: 530920

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.

Upvotes: 6

Related Questions