unittest 3.2版中更新了signal信号量的功能,用于在遇到Ctrl+C键盘中断时优雅的结束。
当用户按下Ctrl+C时,会立即或等当前用例执行完后再停止运行,并输出结果,如果用户再次按下Ctrl+C,则会立即抛出KeyboardInterrupt异常并停止。
启用singal功能的方法有以下3种:
示例用例test_demo.py内容如下:
import unittest
class TestDemo(unittest.TestCase):
def test_a(self):
pass
def test_b(self):
time.sleep(10)
def test_c(self):
time.sleep(10)
pass
命令行运行时加上-c或--catch参数
python -m unittest -vvv -c test_demo
此时按下Ctrl+C,会立即停止运行,并输出结果:
test_a (test_demo1.TestDemo) ... ok
test_b (test_demo1.TestDemo) ... ^Cok
----------------------------------------------------------------------
Ran 2 tests in 1.106s
OK
在unittest.main()中使用参数catchbreak=True
在脚本test_demo.py中添加:
if __name__ == '__main__':
unittest.main(verbosity=2, catchbreak=True)
命令行中使用python命令运行该脚本:
python test_demo.py
按下Ctrl+C,此时程序不会立即停止运行,而是等该用例执行完后,再停止运行,输出结果如下:
test_a (__main__.TestDemo) ... ok
test_b (__main__.TestDemo) ... ^Cok
----------------------------------------------------------------------
Ran 2 tests in 30.005s
在suite中使用signal
新建run.py,代码如下:
import unittest
import test_demo
# 启用信号量功能
result = unittest.TestResult()
unittest.installHandler()
unittest.registerResult(result)
suite = unittest.defaultTestLoader.loadTestsFromModule(test_demo)
runner = unittest.TextTestRunner(verbosity=2)
runner.run(suite)
命令行使用python运行run.py:
python run.py
按下Ctrl+C,等待第二条用例执行完后会停止运行,结果同上一个结果。再次按下Ctrl+C则会立即停止,输出如下:
test_a (test_demo1.TestDemo) ... ok
test_b (test_demo1.TestDemo) ... ^C^CTraceback (most recent call last):
File "run.py", line 11, in <module>
runner.run(suite)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/unittest/runner.py", line 176, in run
test(result)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/unittest/suite.py", line 84, in __call__
return self.run(*args, **kwds)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/unittest/suite.py", line 122, in run
test(result)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/unittest/suite.py", line 84, in __call__
return self.run(*args, **kwds)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/unittest/suite.py", line 122, in run
test(result)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/unittest/case.py", line 653, in __call__
return self.run(*args, **kwds)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/unittest/case.py", line 605, in run
testMethod()
File "/Users/apple/Documents/Projects/Secoo/rpa/outputs/test_demo1.py", line 12, in test_b
time.sleep(30)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/unittest/signals.py", line 36, in __call__
self.default_handler(signum, frame)
KeyboardInterrupt