2.11. 测试调试
2.11.1. 在单元测试中测试异常情况
import unittest
def parse_int(s):
return int(s)
class TestConversion(unittest.TestCase):
def test_bad_int(self):
self.assertRaises(ValueError, parse_int, 'N/A')
if __name__ == '__main__':
unittest.main()
2.11.2. 将测试输出用日志记录到文件中
import sys
import unittest
def main(out=sys.stderr, verbosity=2):
loader = unittest.TestLoader()
suite = loader.loadTestsFromModule(sys.modules[__name__])
unittest.TextTestRunner(out,verbosity=verbosity).run(suite)
if __name__ == '__main__':
with open('testing.out', 'w') as f:
main(f)
2.11.3. 忽略或期望测试失败
import unittest
import os
import platform
class Tests(unittest.TestCase):
@unittest.skip('skipped test')
def test_1(self):
self.fail('should have failed!')
@unittest.skipIf(os.name=='posix', 'Not supported on Unix')
def test_2(self):
import winreg
@unittest.skipUnless(platform.system() == 'Darwin', 'Mac specific test')
def test_3(self):
self.assertTrue(True)
@unittest.expectedFailure
def test_4(self):
self.assertEqual(2+2, 5)
if __name__ == '__main__':
unittest.main()
2.11.4. 处理多个异常
try:
f = open(filename)
except (FileNotFoundError, PermissionError):
pass
try:
f = open(filename)
except OSError:
pass
2.11.5. 捕获所有异常
try:
...
except Exception as e:
...
log('Reason:', e) # Important!
2.11.6. 创建自定义异常
需要继承 Exception
2.11.7. 捕获异常后抛出另外的异常
try:
...
except SomeException as e:
raise DifferentException() from e
2.11.8. 重新抛出被捕获的异常
try:
...
except SomeException as e:
raise
2.11.9. 输出警告信息
import warnings
def func(x, y, logfile=None, debug=False):
if logfile is not None:
warnings.warn('logfile argument deprecated', DeprecationWarning)
...
2.11.10. 调试基本的程序崩溃错误
print
pdb
traceback.print_stack()