Depending on how your tests are organized, you could also catch the KeyboardInterrupt
and call the tearDown
method in the except
block:
import unittest
class MyTestCase(unittest.TestCase):
def test_one(self):
for i in range(1 << 20):
if i % 271 == 0:
print i
@classmethod
def tearDownClass(cls):
print("\nteardown")
if __name__ == '__main__':
try:
unittest.main()
except KeyboardInterrupt:
MyTestCase.tearDownClass()
The solution I found was to override the unittest.TextTestRunner
and catch the KeyboardInterrupt
in the run()
method, and then run the module tear down.
class CustomTestRunner(unittest.TextTestRunner):
def _makeResult(self):
self.my_result = self.resultclass(self.stream, self.descriptions, self.verbosity)
return self.my_result
def run(self, test):
try:
return super().run(test)
except KeyboardInterrupt:
self.stream.writeln("Caught KeyboardInterrupt.")
self.my_result.printErrors()
test._handleModuleTearDown(self.my_result) # do cleanup
return self.my_result
The unittest module provides a rich set of tools for constructing and running tests. This section demonstrates that a small subset of the tools suffice to meet the needs of most users.,Run the test without collecting the result. This allows exceptions raised by the test to be propagated to the caller, and can be used to support running tests under a debugger.,A command-line program that loads a set of tests from module and runs them; this is primarily for making test modules conveniently executable. The simplest use for this function is to include the following line at the end of a test script:,Run the tests associated with this suite without collecting the result. This allows exceptions raised by the test to be propagated to the caller and can be used to support running tests under a debugger.
import unittest
class TestStringMethods(unittest.TestCase):
def test_upper(self):
self.assertEqual('foo'.upper(), 'FOO')
def test_isupper(self):
self.assertTrue('FOO'.isupper())
self.assertFalse('Foo'.isupper())
def test_split(self):
s = 'hello world'
self.assertEqual(s.split(), ['hello', 'world'])
# check that s.split fails when the separator is not a string
with self.assertRaises(TypeError):
s.split(2)
if __name__ == '__main__':
unittest.main()
... -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- Ran 3 tests in 0.000 s OK
test_isupper(__main__.TestStringMethods)...ok test_split(__main__.TestStringMethods)...ok test_upper(__main__.TestStringMethods)...ok -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- Ran 3 tests in 0.001 s OK
python - m unittest test_module1 test_module2 python - m unittest test_module.TestClass python - m unittest test_module.TestClass.test_method
python - m unittest tests / test_something.py
python - m unittest - v test_module
Python provides the unittest module to test the unit of source code. The unittest plays an essential role when we are writing the huge code, and it provides the facility to check whether the output is correct or not.,The unittest is built into the Python standard library since 2.1. The best thing about the unittest, it comes with both a test framework and a test runner. There are few requirements of the unittest to write and execute the code.,This process takes lots of time. To overcome this problem, Python introduces the unittest module. We can also check the application's performance by using it.,On the other hand, the automated testing executes the code according to our code plan which means it runs a part of the code that we want to test, the order in which we want to test them by a script instead of a human.
$ python sum.py Everything is correct
Everything is correct
Traceback (most recent call last):
File "<string>", line 13, in <module>
File "<string>", line 9, in test_sum_tuple
AssertionError: It should be 10
.F
-
FAIL: test_sum_tuple (__main__.TestingSum)
--
Traceback (most recent call last):
File "<string>", line 11, in test_sum_tuple
AssertionError: 9 != 10 : It should be 10
----------------------------------------------------------------------
Ran 2 tests in 0.001s
FAILED (failures=1)
Traceback (most recent call last):
File "<string>", line 14, in <module>
File "/usr/lib/python3.8/unittest/main.py", line 101, in __init__
self.runTests()
File "/usr/lib/python3.8/unittest/main.py", line 273, in runTests
sys.exit(not self.result.wasSuccessful())
SystemExit: True
FAIL: test_sum_tuple(__main__.TestSum)
--
Traceback(most recent call last):
File "test_sum_unittest.py", line 10, in test_sum_tuple
self.assertEqual(sum((2, 3, 5)), 10, "It should be 10")
AssertionError: It should be 10
--
Ran 2 tests in 0.001 s
FAILED(failures = 1)
. -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- Ran 1 test in 0.000 s OK
Peter Decosta has been added with id 0
The user associated with id 0 is Peter