Automating Test Execution with Python's unittest Discover Method
To execute multiple test scripts efficiently, Python's unittest module provides the discover method for loading test cases. This approach allows batch execution using TextTestRunner.
Setting Up a Test Project
Create a new Pythonn project in PyCharm named test_project. Inside, create a tests directory with subdirectories module_a and module_b, each containing test scripts like test_alpha.py and test_beta.py.
Example test script:
import unittest
class SampleTest(unittest.TestCase):
def setUp(self):
print("Test setup complete.")
def tearDown(self):
print("Test cleanup complete.")
def test_case_one(self):
print("Running test case one.")
def test_case_two(self):
print("Running test case two.")
if __name__ == "__main__":
unittest.main()
Loading Tests with Discover
Create a runner script execute_tests.py in the project root. Use discover to load tests from a directory.
Parameters for discover:
start_dir: Directory containing test scripts.pattern: File pattern to match (e.g.,"test*.py").top_level_dir: Optional top-level directory; set toNonefor default.
Example implementation:
import unittest
def load_test_cases():
test_dir = "./tests"
test_suite = unittest.TestSuite()
discovered_tests = unittest.defaultTestLoader.discover(
test_dir,
pattern="test*.py",
top_level_dir=None
)
test_suite.addTests(discovered_tests)
return test_suite
if __name__ == "__main__":
runner = unittest.TextTestRunner()
runner.run(load_test_cases())
Running the Test Suite
The discover method recursively searches start_dir for Python files matching pattern. It returns a TestSuite containing all discovered test cases. Use TextTestRunner().run() to execute them.
Alternative directory specification:
import os
test_dir = os.path.join(os.getcwd(), "tests")
This method simplifies batch execution by automating test discovery and suite assembly.