改进 Ceph python 脚本测试
Ceph 的 Ceph 命令行 和 ceph-disk 辅助脚本都有集成测试(ceph-disk.sh 和 test.sh)。添加单元测试和 pep8 检查将会很有用。
可以通过创建一个 python 模块而不是一个孤立的文件来实现(例如 ceph-detect-init)和一个包含 pep8、python2 和 python3 测试环境的 tox.ini 文件。
由于 Ceph 依赖于 autotools,可以使用 -local 目标来使用 setup.py。例如
all-local:: python setup.py build clean-local:: python setup.py clean install-data-local:: python setup.py install --root=$(DESTDIR) --install-layout=deb
注意双 : 表示它会附加到现有规则而不是覆盖它。 –root=$(DESTDIR) 会在构建软件包时将模块文件安装到适当的目录中。
tox 使用 pip 从 PyPI 获取运行测试所需的依赖项,但有时测试在没有网络访问权限的情况下运行。可以使用 wheel 收集依赖项,例如
pip wheel -r requirements.txt
这将创建一个 wheelhouse 目录,稍后可以使用
pip install --no-index --use-wheel --find-links=wheelhouse \ -r requirements.txt
virtualenv、pip 和 wheel ¶
pip 版本必须大于或等于 6.1,否则可能无法正确安装 wheelhouse 目录中的软件包。在 CentOS 7 上运行时,创建 virtualenv 时默认提供的 pip 版本为 pip 1.4.1,需要使用 pip install –upgrade ‘pip >= 6.1′ distribute 进行升级。如果使用 wheelhouse 目录运行此操作,则必须使用类似 pip wheel -r requirements.txt ‘pip >= 6.1′ 的方法进行准备,因为模块的依赖项通常不需要特定的 pip 或 distribute 实例。
构建依赖和 virtualenv ¶
确保安装了所需的软件包来构建 Ceph 并运行测试,依赖于软件包的构建要求(debian/control 或 ceph.spec)。python 模块的构建依赖项列在 test-requirements.txt 文件中,将该列表复制到软件包构建要求中会容易出错。在较旧的系统上匹配依赖项要求也很困难。构建要求可以限制为包含 virtualenv。运行测试时,将创建一个 virtualenv,并将依赖项安装到其中,使用 test-requirements.txt 列表。由于在没有网络访问权限(或不可能在没有网络访问权限的情况下)运行时,从网络获取依赖项是不受欢迎的,因此需要在安装构建要求软件包的同时收集它们。这可以类似于
apt-get build-dep ceph pip wheel -r test-requirements.txt
发布到 PyPI ¶
可以使用以下命令将模块注册到 PyPI
python setup.py register
并在有新版本可用时发布
python setup.py sdist upload --sign
打包和开发 ¶
虽然在打包的上下文中 wheel 有用,但在开发环境中并不重要,并且直接从 PyPI 获取模块比使用 pip wheel 预加载它们更方便。可以将 tox.ini 文件设置为
[testenv] deps = {env:NO_INDEX:} --use-wheel --find-links={toxinidir}/wheelhouse -r{toxinidir}/requirements.txt -r{toxinidir}/test-requirements.txt
如果可用,这将使用 wheelhouse 目录中的 python 模块,否则将从 PyPI 获取它们。可以使用类似以下的 run-tox.sh 脚本运行 tox
virtualenv make-check . make-check/bin/activate pip install --upgrade 'pip >= 6.1' pip install --no-index --use-wheel --find-links=wheelhouse 'tox >=1.9' if test -d wheelhouse ; then export NO_INDEX=--no-index fi tox
只有当旧版本的 tox 无法解释 {env:NO_INDEX:} 表达式时,才需要 run-tox.sh。
从源代码使用模块 ¶
可以通过以下方式以开发/可编辑模式安装来自源代码的模块
DIR=test-ceph-disk virtualenv virtualenv-$DIR . virtualenv-$DIR/bin/activate ( if test -d ceph-detect-init/wheelhouse ; then wheelhouse="--no-index --use-wheel --find-links=ceph-detect-init/wheelhouse" fi pip install $wheelhouse --editable ceph-detect-init )
activate 命令会将环境变量(PATH 和 PYTHONPATH)添加到环境中,其余的测试脚本将在主机操作系统上安装的之前找到 python 模块文件和控制台脚本。如果找到 wheelhouse 目录,则将从其中提取软件包,从而确保可以在没有网络访问权限的情况下运行测试脚本。
集成测试 ¶
当运行集成测试时,它们需要一个环境和资源,这些环境和资源不易表示为构建要求,并且超出了持续集成机器的预期。它们应该实现到一个单独的目录中(例如 integration),并为它们提供一个单独的 tox 环境,例如
[testenv:integration] basepython = python2 setenv = VIRTUAL_ENV={envdir} deps = -r{toxinidir}/requirements.txt -r{toxinidir}/test-requirements.txt commands = {envbindir}/py.test -v integration/test_main.py
此测试将为每个平台创建一个 docker 镜像,并在其中运行 ceph-detect-init 脚本,以验证它是否返回预期的值。