简体   繁体   中英

Running all unittest.TestCase imported using from .. import *

I have the following package:

  • tests.py
  • tests
    • __init__.py
    • test_module_a.py
    • test_module_b.py

In my tests.py file I do the following:

import unittest

from tests import *

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

In my tests/__init__.py the following:

__all__ = ["test_module_a", "test_module_b"]

In my tests/test_module_a.py and tests/test_module_b.py files, I have the following:

import unittest

class TestMyModule(unittest.TestCase):

  def test_something(self):
    self.assertTrue(True)

When I run python tests.py , the submodules seem to be imported but my unittest.TestCase 's are not run. Why? Thank.

Use a test loader and import explicitly every test case (to be more readable) :

import unittest

from test_module_a import TestMyModule1
from test_module_b import TestMyModule2

if __name__ == "__main__":
    loader = unittest.TestLoader()
    suite = unittest.TestSuite((loader.loadTestsFromTestCase(TestMyModule1),
                                loader.loadTestsFromTestCase(TestMyModule2),
                                )
                               )
    runner = unittest.TextTestRunner(verbosity=2)
    runner.run(suite)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM