官方文档 : http://tox.readthedocs.io/en/latest/example/basic.html
参考文档 : http://www.tuicool.com/articles/UnQbyyv
tox是什么
tox是通用的虚拟环境管理和测试命令行工具,旨在使Python测试标准化、自动化,可以使用它:
- 用不同的Python版本和解释器检查你的软件包是否正确安装
- 在不同的虚拟环境中运行测试,配置你选择的测试工具
- 作为持续集成服务器的前端,大大减少了样板和合并CI和基于shell的测试
安装
$ pip install tox
在需要运行的python项目目录中建立tox.ini文件,在tox.ini文件中配置你的项目的基本信息和你想要的测试环境。
你还可以通过运行tox-quickstart来自动生成一个tox.ini文件。
在Python2.6和Python2.7的环境来安装和测试你的项目,只需运行命令:
tox
这将打包源码(sdist-package)到当前的项目,创建虚拟环境,并在其中运行指定的命令tox -e py26。
首次运行需要安装依赖创建环境,运行时间较长,第二次开始,运行会很快。
详细配置示例:
[tox]
minversion = 1.6
#最低tox版本
skipsdist = True
#跳过本地软件包安装到virtualenv中步骤
envlist = py27,pep8,com
# envlist 表示 tox 中配置的环境都有哪些
[testenv]
# testenv 是默认配置,如果某个环境自身的 section 中没有定义这些配置, 那么就从这个 section 中读取
setenv = VIRTUAL_ENV={envdir}
PYTHONHASHSEED=0
PYCURL_SSL_LIBRARY=openssl
# setenv 列出了虚拟机环境中生效的环境变量,一些配色方案和单元测试标志
usedevelop = True
# usedevelop 表示安装 virtualenv 时, 项目自身是采用开发模式安装的, 所以不会拷贝代码到 virtualenv 目录中, 只是做个链接
install_command = pip install {opts} {packages}
# 表示构建环境的时候要执行的命令,一般是使用 pip 安装
deps = -r{toxinidir}/requirements.txt
-r{toxinidir}/test-requirements.txt
# deps 指定构建环境时需要安装的第三方依赖包
# 每个虚拟环境创建的时候, 会通过 pip install -r requirements.txt 和 pip install -r test-requirements.txt 安装依赖包到虚拟环境
# 一般的项目会直接安装 requirements 和 test-requirements 两个文件中的所有依赖包
commands = ostestr {posargs}
# commands 表示构建好 virtualenv 之后要执行的命令
# 这里调用了 ostestr 指令来调用 testrepository 执行单元测试用例
# {posargs} 参数就是可以将 tox 指令的参数传递给 ostestr
whitelist_externals = bash
passenv = http_proxy HTTP_PROXY https_proxy HTTPS_PROXY no_proxy NO_PROXY
[testenv:py34]
commands =
python -m testtools.run
# 这个 section 是为 py34 环境定制某些配置的,没有定制的配置,将会从 [testenv] 读取
[testenv:pep8]
commands =
flake8 {posargs} ./egis egis/common
# Check that .po and .pot files are valid:
bash -c "find egis -type f -regex '.*\.pot?' -print0|xargs -0 -n 1 msgfmt --check-format -o /dev/null"
{toxinidir}/tools/config/check_uptodate.sh
{toxinidir}/tools/check_exec.py {toxinidir}/egis
# 执行 tox -e pep8 进行代码检查, 实际上是执行了上述指令来进行代码的语法规范检查
[tox:jenkins]
downloadcache = ~/cache/pip
# 定义了 CI server jenkins 的集成配置
# 指定了 pip 的下载 cache 目录,提高构建虚拟环境的速度
[testenv:cover]
# Also do not run test_coverage_ext tests while gathering coverage as those
# tests conflict with coverage.
commands =
python setup.py testr --coverage \
--testr-args='^(?!.*test.*coverage).*$'
# 定义一个 cover 虚拟环境,使单元测试的时候,自动应用 coverage
...
其他常用配置:
setenv = VIRTUAL_ENV={envdir}
PYTHONHASHSEED=0
#设置环境变量
usedevelop = True
#项目应该使用setup.py开发安装到环境中,而不是使用setup.py install来构建和安装其源代码。
依赖requirements.txt文件
将requirements.txt文件添加到deps的三种方式:
deps = -r requirements.txt
deps = -c constraints.txt
deps = -r requirements.txt -c constraints.txt
进行测试
所有的令都是在{toxinidir}(tox.ini所在的目录)作为当前工作目录执行的。
在当前目录执行:
$ tox [-e py27] [subpath]
subpath以Python模块形式用"."一级一级连接