中文學(xué)習(xí)網(wǎng)站: 廖雪峰的官網(wǎng)網(wǎng)站https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000
3. 調(diào)試與測(cè)試
try except finally
- 執(zhí)行邏輯:先運(yùn)行try兔港,遇到異常,則跳出try,如果except捕獲異常,則執(zhí)行except塊,最后執(zhí)行finnally(不管是否異常都會(huì)執(zhí)行)
- Python的錯(cuò)誤其實(shí)也是class,所有的錯(cuò)誤類型都繼承自BaseException,except不僅會(huì)捕獲指定類型的錯(cuò)誤,還會(huì)捕獲其所有子類錯(cuò)誤垦江。比如
try:
foo()
except ValueError as e:
print('ValueError')
except UnicodeError as e: #第二個(gè)except永遠(yuǎn)也捕獲不到UnicodeError,因?yàn)閁nicodeError是ValueError的子類搅方,如果有比吭,也被第一個(gè)except給捕獲了。
print('UnicodeError')
- raise 拋出錯(cuò)誤類型姨涡。raise語(yǔ)句如果不帶參數(shù)衩藤,就會(huì)把當(dāng)前錯(cuò)誤原樣拋出。
- 常見(jiàn)的錯(cuò)誤類型和繼承關(guān)系參見(jiàn):
https://docs.python.org/3/library/exceptions.html#exception-hierarchy
BaseException
+-- SystemExit
+-- KeyboardInterrupt
+-- GeneratorExit
+-- Exception
+-- StopIteration
+-- StopAsyncIteration
+-- ArithmeticError
| +-- FloatingPointError
| +-- OverflowError
| +-- ZeroDivisionError
+-- AssertionError
+-- AttributeError
+-- BufferError
+-- EOFError
+-- ImportError
+-- ModuleNotFoundError
+-- LookupError
| +-- IndexError
| +-- KeyError
+-- MemoryError
+-- NameError
| +-- UnboundLocalError
+-- OSError
| +-- BlockingIOError
| +-- ChildProcessError
| +-- ConnectionError
| | +-- BrokenPipeError
| | +-- ConnectionAbortedError
| | +-- ConnectionRefusedError
| | +-- ConnectionResetError
| +-- FileExistsError
| +-- FileNotFoundError
| +-- InterruptedError
| +-- IsADirectoryError
| +-- NotADirectoryError
| +-- PermissionError
| +-- ProcessLookupError
| +-- TimeoutError
+-- ReferenceError
+-- RuntimeError
| +-- NotImplementedError
| +-- RecursionError
+-- SyntaxError
| +-- IndentationError
| +-- TabError
+-- SystemError
+-- TypeError
+-- ValueError
| +-- UnicodeError
| +-- UnicodeDecodeError
| +-- UnicodeEncodeError
| +-- UnicodeTranslateError
+-- Warning
+-- DeprecationWarning
+-- PendingDeprecationWarning
+-- RuntimeWarning
+-- SyntaxWarning
+-- UserWarning
+-- FutureWarning
+-- ImportWarning
+-- UnicodeWarning
+-- BytesWarning
+-- ResourceWarning
調(diào)試方法
- assert, 用法 assert 表達(dá)式, 表達(dá)式為false時(shí)的輸出, 運(yùn)行py文件時(shí)加入-O選項(xiàng)可以屏蔽所有斷言輸出
- log, 使用方法
import logging
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s', datefmt='%a, %d %b %Y %H:%M:%S', filename='myapp.log', filemode='w')#設(shè)置log等級(jí)涛漂,輸出格式赏表,輸出文件名检诗,默認(rèn)是輸出到屏幕
logging.debug('This is debug message')
logging.info('This is info message')
logging.warning('This is warning message')
- pdb
- 啟動(dòng)pdb: python3 -m pdb err.py
- n:?jiǎn)尾綀?zhí)行
- l:查看當(dāng)前代碼
- p 變量名:查看變量
- q:退出調(diào)試
- c:繼續(xù)執(zhí)行
- 代碼中pdb.set_trace()設(shè)置斷點(diǎn)
單元測(cè)試
步驟:
- 編寫一個(gè)測(cè)試類,從unittest.TestCase繼承
- 編寫單元測(cè)試函數(shù)瓢剿,以test開(kāi)頭的方法就是測(cè)試方法逢慌,不以test開(kāi)頭的方法不被認(rèn)為是測(cè)試方法,測(cè)試的時(shí)候不會(huì)被執(zhí)行间狂。
- 編寫setUp()和tearDown()函數(shù)攻泼。這兩個(gè)方法會(huì)分別在每調(diào)用一個(gè)測(cè)試方法的前后分別被執(zhí)行。
setUp()和tearDown()方法有什么用呢前标?設(shè)想你的測(cè)試需要啟動(dòng)一個(gè)數(shù)據(jù)庫(kù)坠韩,這時(shí),就可以在setUp()方法中連接數(shù)據(jù)庫(kù)炼列,在tearDown()方法中關(guān)閉數(shù)據(jù)庫(kù),這樣音比,不必在每個(gè)測(cè)試方法中重復(fù)相同的代碼
- 運(yùn)行單元測(cè)試俭尖,
- 方法1:在py文件中的最后運(yùn)行unittest.main(),
- 方法2(推薦):python3 -m unittest mydict_test
import unittest
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')
if __name__ == '__main__':
unittest.main()
文檔測(cè)試
- python支持在注釋中編寫樣例代碼洞翩,然后自動(dòng)測(cè)試注釋中的代碼稽犁。
- 應(yīng)該是通過(guò)>>>來(lái)判斷注釋中的樣例代碼,然后會(huì)對(duì)比注釋中的輸出和測(cè)試的輸出是否完全一致(就算是報(bào)錯(cuò)骚亿,報(bào)錯(cuò)信息也應(yīng)該完全一樣已亥,一個(gè)字符都不差)。如果不完全一致来屠,就會(huì)報(bào)錯(cuò)虑椎,如果完全一致,就什么都不輸出俱笛。
# mydict2.py
class Dict(dict):
'''
Simple dict but also support access as x.y style.
>>> d1 = Dict()
>>> d1['x'] = 100
>>> d1.x
100
>>> d1.y = 200
>>> d1['y']
200
>>> d2 = Dict(a=1, b=2, c='3')
>>> d2.c
'3'
>>> d2['empty']
Traceback (most recent call last):
...
KeyError: 'empty'
>>> d2.empty
Traceback (most recent call last):
...
AttributeError: 'Dict' object has no attribute 'empty'
'''
def __init__(self, **kw):
super(Dict, self).__init__(**kw)
def __getattr__(self, key):
try:
return self[key]
except KeyError:
raise AttributeError(r"'Dict' object has no attribute '%s'" % key)
def __setattr__(self, key, value):
self[key] = value
if __name__=='__main__':
import doctest
doctest.testmod()