使用 tox flake8 pytest 規范 python 項目


使用 tox flake8 pytest 規范 python 項目

python 中有些很好的工作來規范整個項目的開發,而其中使用較多的就是使用 tox 、 flake8 、 pytest 。

tox 管理 virtualenv 環境,可在一個 python 項目中定義多個版本的 python 環境,從而檢查項目源代碼的兼容性。flake8 進行源代碼檢查,根據 pep8 檢查源代碼是否符合規范(也可使用 pylint ,pylint 較嚴格)。 pytest 進行單元測試,或者通過 pytest 的插件 pytest-cov 同時進行代碼覆蓋率測試。

示例

假設項目布局如下 ::

.
├── CHANGELOG
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── doc
├── requirements.txt
├── myproj
├── test-requirements.txt
├── tests
├── tools
├── tox.ini
└── venv

源代碼目錄為 myproj ,測試代碼目錄為 tests ,當前的 vitualenv 在 venv 目錄中。

在 python 項目中,安裝 tox ::

pip intall tox

並把 flake8 和 pytest 、 pytest-cov 加入到測試依賴 test-requirements.txt ::

pytest
pytest-cov
mock
testtools
fixtures
flake8
coverage

配置 tox ,定義所需要支持的環境,和運行的任務,寫入 tox.ini 配置文件,如下 ::

[tox]
envlist = py,py27,py{34,35},pep8
skip_missing_interpreters = True
skipsdist = True
indexserver = default = https://pypi.doubanio.com/simple

[testenv]
passenv = *
install_command = pip install -U {opts} {packages}
setenv = PYTHONPATH={toxinidir}/
deps = -rrequirements.txt
       -rtest-requirements.txt
commands = py.test

[pytest]
testpaths = tests
addopts = --maxfail=2 -rf

[testenv:pep8]
commands = flake8 myproj
           flake8 tests

[flake8]
exclude = env,venv,.venv,.git,.tox,dist,doc

[testenv:cover]
commands = py.test --cov

為了支持覆蓋測試(使用 coverage),加入 .coveragerc 配置文件 ::

[run]
omit = tests/*
source = myproj

[paths]
source = myproj

然后運行 tox ::

tox     # 創建不同的 python 環境並運行 pytest ,最后運行 pep8
tox -e pep8  # 單獨運行 pep8
tox -e cover # 代碼覆蓋率

這些工具都是標准工具,以后還可以和 jenkins 等集成。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM