版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Sophisticated_/article/details/84037307
错误处理
Python内置的try...except...finally
用来处理错误
raise
语句抛出一个错误
try:
print('try...')
r = 10 / int('2')
print('result:', r)
except ValueError as e:
print('ValueError:', e)
except ZeroDivisionError as e:
print('ZeroDivisionError:', e)
else:
print('no error!')
finally:
print('finally...')
print('END')
如果没有错误发生,可以在except
语句块后面加一个else
,当没有错误发生时,会自动执行else语句
与Java的错误处理机制
try/catch
非常类似
调试
logging
logging.info()
就可以输出一段文本
import logging
s = '0'
n = int(s)
logging.info('n = %d' % n)
print(10 / n)
允许你指定记录信息的级别,有debug
,info
,warning
,error
等几个级别,当我们指定level=INFO
时,logging.debug
就不起作用了
import logging
logging.basicConfig(level=logging.INFO)
pdb
Python的调试器pdb
,让程序以单步方式运行
# err.py
s = '0'
n = int(s)
print(10 / n)
$ python -m pdb err.py
> /Users/michael/Github/learn-python3/samples/debug/err.py(2)<module>()
-> s = '0'
与C语言的gdb调试非常类似
单元测试
引入Python自带的unittest
模块
import unittest
from mydict import Dict
class TestDict(unittest.TestCase):
def test_init(self):
d = Dict(a=1, b='test')
self.assertEqual(d.a, 1)
self.assertEqual(d.b, 'test')
self.assertTrue(isinstance(d, dict))
def test_key(self):
d = Dict()
d['key'] = 'value'
self.assertEqual(d.key, 'value')
def test_attr(self):
d = Dict()
d.key = 'value'
self.assertTrue('key' in d)
self.assertEqual(d['key'], 'value')
def test_keyerror(self):
d = Dict()
with self.assertRaises(KeyError):
value = d['empty']
def test_attrerror(self):
d = Dict()
with self.assertRaises(AttributeError):
value = d.empty
编写一个测试类,从unittest.TestCase
继承。以test
开头的方法就是测试方法,对每一类测试都需要编写一个test_xxx()
方法,最常用的断言就是assertEqual()
运行单元测试:
if __name__ == '__main__':
unittest.main()
或者在命令行通过参数-m unittest
直接运行单元测试:
$ python -m unittest mydict_test
.....
----------------------------------------------------------------------
Ran 5 tests in 0.000s
OK
单元测试中编写两个特殊的setUp()
和tearDown()
方法。这两个方法会分别在每调用一个测试方法的前后分别被执行。