sample code https://github.com/arthas989/python2022

內容 / 重點 / 注意事項 / 其他或補充

114. Context Manager

115. Pylint、116. pylintrc

117. Unittest

Chapter 8 - Error Handling and Exceptions
114. Context Manager context manager 資源管理器
自動管理資源,不用管資源有沒有關閉

傳統: f=open(filename) try: pass finally: f.close()

with語法 with open(filename) as f:

也可以自製自己的資源管理 https://docs.python.org/3/library/contextlib.html https://blog.gtwang.org/programming/python-with-context-manager-tutorial/ | | | 115. Pylint | pylint是什麼? 一個程式碼分析工具 找錯誤、給建議、產生報告、打分數 給的建議有特定的規則風格 例如: snake_case naming style

在有compiler的語言中,可靠compiler抓到錯誤 但在直譯的語言中像python就沒有 wilson老師講的應該是語言的特性,不過有錯就沒辦法跑了吧!! 另外像vs code提供的intellisense(pylance)也很好用 用過就回不去了

優點:肉眼很難找的錯誤,用工具 缺點:大型專案容易給出無用建議(Twisted,Django,Flask,Sphinx) 建議:補.pylintrc文件關掉不需要的建議

pylint -h 得知 pylint -r y 是指 是否產出完整report 或只有訊息 Tells whether to display a full report or only the messages. (default: False) | | | 116. pylintrc file | | | | 117. Unittest | 單元測試 一、用python內建的工具unittest 二、用單元測試過function功能正確才能與專案其他部份整合

示範unittest流程: cap.py def cap_text(text): return text.capitalize() 內容是把傳入的text變大寫

main_program.py import unittest import cap 定義一個class名字自取,繼承unittest.TestCase 裡面每一個測試def名字都要是test開頭 class MyTest(unittest.TestCase) def test_one(self): text = “sample” result = cap.cap_text(text) self.assertEqual(result,”Sample”)

def test_two(self):
      text = “just testing”
      result = cap.cap_text(text)
      self.assertEqual(result,”Just Testing”

if __name__ == ‘__main__’: unittest.main()

補充資料: unittest 模組主要包括四個部份: 測試案例(Test case)測試的最小單元。<<test開頭>>

測試設備(Test fixture)執行一或多個測試前必要的預備資源,以及相關的清除資源動作。<<setUp與tearDown>> 情境:例如測試前要設定好參數、建立測試資料;測試完要清空測試資料、關閉資源等……

測試套件(Test suite)一組測試案例、測試套件或者是兩者的組合。

測試執行器(Test runner)負責執行測試並提供測試結 看

範例看 117-3_unittest.py、calculator.py

參考來源: 一、https://openhome.cc/Gossip/CodeData/PythonTutorial/UnitTestPy3.html TestCase、TestSuite、TestLoader、TextTestRunner的範例

二、https://docs.python.org/zh-tw/3/library/unittest.html 官方文件

三、https://www.it145.com/9/71884.html TestCase、TestSuite、TestLoader、TextTestRunner的範例

四、https://www.pythontutorial.net/python-unit-testing/python-test-fixtures/ 對test fixtures執行順序有興趣的可參考,寫的很清楚 | | | | https://www.pythontutorial.net/python-unit-testing/python-test-fixtures/ | |