- 1 year ago
Return status of python unittest
In Python, the unittest
module provides a framework for writing and running unit tests. When you run the unit tests using unittest
, it provides different ways to report the status of the tests.
Command-Line Output: By default, when you run the test script from the command line,
unittest
will print the test results directly to the console. The test results will include information about which tests passed and which tests failed.Test Result Object: You can capture the test results in a
TestResult
object by using theunittest.TestRunner
class. This allows you to programmatically access the test results and perform further actions based on the test outcomes.
Here's an example of how to use unittest.TestRunner
to get the test results programmatically:
pythonimport unittest
class MyTest(unittest.TestCase):
def test_something(self):
self.assertEqual(1 + 1, 2)
if __name__ == '__main__':
# Create a test suite and add the test case
test_suite = unittest.TestSuite()
test_suite.addTest(unittest.makeSuite(MyTest))
# Create a test runner
test_runner = unittest.TextTestRunner()
# Run the test suite
test_result = test_runner.run(test_suite)
# Check the status of the tests
if test_result.wasSuccessful():
print("All tests passed.")
else:
print("Some tests failed.")
In this example, the TextTestRunner
runs the test suite, and the TestResult
object (test_result
) contains the outcome of the tests. You can use the wasSuccessful()
method of the TestResult
object to check if all the tests passed.
Note that there are also other test runners available in the unittest
module, such as HTMLTestRunner
, which can generate HTML reports of test results.
Keep in mind that the exact approach to reporting test status may vary depending on how you run your tests (e.g., command-line, test framework integration, continuous integration systems, etc.).