python 持續整合實踐 - 程式碼規範檢查和單元測試
介紹
利用 pylint 和 pytest,分別作為 python 程式碼規範檢查和單元測試工具,並通過 與
jenkins 實現 python 持續整合
pylint 介紹
pylint 是一個 Python 程式碼分析工具,它分析 Python 程式碼中的錯誤,查詢不符合程式碼風格標準(Pylint 預設使用的程式碼風格是 PEP 8,具體資訊,請參閱參考資料)和有潛在問題的程式碼。
- pylint 是一個 Python 工具,除了平常程式碼分析工具的作用之外,它提供了更多的功能:如檢查一行程式碼的長度,變數名是否符合命名標準,一個宣告過的介面是否被真正實現等等。
- pylint 的一個很大的好處是它的高可配置性,高可定製性,並且可以很容易寫小外掛來新增功能。
- 目前在 PyCharm 外掛中集成了 pylint。
- pylint 輸出結構共有 4個 級別,分別是 C:Convention, R:Refactor, W:Warning, E:Error。
pytest 介紹
pytest 是一個非常成熟的全功能的 python 測試框架,主要特點有以下幾點:
- 簡單靈活,容易上手,文件豐富;
- 支援引數化,可以細粒度地控制要測試的測試用例;
- pytest具有很多第三方外掛,並且可以自定義擴充套件,比較好用的如pytest-selenium(整合selenium)、pytest-html(完美html測試報告生成)、pytest-rerunfailures(失敗case重複執行)、pytest-xdist(多CPU分發)等;;
- 可以很好的和 CI 工具結合,例如 jenkins
jenkins 整合 pylint 和 pytest
1.開啟 jenkins,進入 job 頁面

2.點選 “配置”

下面的配置都是在這裡頁面
3.配置 job 的原始碼
參考:
ofollow,noindex">https://www.jianshu.com/p/e7678dbe4222
4.配置 job 的構建
(1).增加構建步驟,選擇 “執行 shell”


分別介紹一下命令
(2).新增 docker-compose 命令,啟動映象
(3).新增 docker exec 命令,進入容器
docker exec -it <CONTAINER ID> /bin/bash
(4).新增 pylint 命令,配置程式碼規範檢查
--evaluation="error + warning + refactor + convention" 輸出程式碼規範檢查 4種 問題格式, 後期整合到流水線與閾值判斷要用
pylint $(find . -name "*.py") -f parseable -d I0011,R0801 --evaluation="error + warning + refactor + convention" | tee pylint.log
pylint.log:程式碼規範檢查輸出報告
(5).新增 pytest 命令,配置單元測試
py.test test --junit-xml=report.xml --cov-report=xml --cov=./
report.xml:單元測試結果報告
covage.xml:單元測試覆蓋率報告, 其中覆蓋率值後期整合到流水線與閾值判斷要用
4.配置 job 的構建後操作
(1).增加構建後操作步驟

image.png
(2).選擇 Report Vioations,整合程式碼規範檢查報告

(3).選擇 Publish JUnit test result report,整合單元測試結果報告

(4).選擇 Publish Cobertura Coverage Report,整合單元測試覆蓋率報告
