使用 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 等集成。

上一篇:Loadrunner模拟JSON接口请求进行测试


下一篇:Python 小游戏 Bunny