在不同环境中测试你的包

开发 Python 包

James Fulton

Climate informatics researcher

测试多个 Python 版本

setup.py 允许使用 Python 2.7 起的任意版本。

from setuptools import setup, find_packages

setup(
    ...
    python_requires='>=2.7',
)

要测试这些 Python 版本,需:

  • 安装所有这些 Python 版本
  • 在每个 Python 中安装你的包及其依赖
  • 运行 pytest
开发 Python 包

测试多个 Python 版本

setup.py 允许使用 Python 2.7 起的任意版本。

from setuptools import setup, find_packages

setup(
    ...
    python_requires='>=2.7',
)

要测试这些 Python 版本,需:

  • 安装所有这些 Python 版本
  • 运行 tox
开发 Python 包

什么是 tox?

  • 用于在多个 Python 版本下运行测试
开发 Python 包

配置 tox

配置文件 - tox.ini

mysklearn/
|-- mysklearn
|   |-- ...
|-- tests
|   |-- ...
|-- setup.py
|-- LICENSE
|-- MANIFEST.in
|-- tox.ini   <--- 配置文件
开发 Python 包

配置 tox

配置文件 - tox.ini

[tox]

envlist = py27, py35, py36, py37
[testenv]
deps = pytest
commands = pytest
echo "run more commands" ...
  • 标题用方括号 [...] 包裹。
  • 要测试 Python 版本 X.Y,向 envlist 添加 pyXY
  • 需要预先安装这些 Python 版本。
  • commands 参数列出 tox 将运行的终端命令。
  • commands 可包含任意可在终端运行的命令,如 lscdecho 等。
开发 Python 包

运行 tox

tox
mysklearn/    <-- 进入此目录
|-- mysklearn
|   |-- ...
|-- tests
|   |-- ...
|-- setup.py
|-- LICENSE
|-- MANIFEST.in
|-- tox.ini
开发 Python 包

tox 输出

py27 create: /mypackages/mysklearn/.tox/py27
py27 installdeps: pytest
py27 inst: /mypackages/mysklearn/.tox/.tmp/package/1/mysklearn-0.1.0.zip
py27 installed: mysklearn==0.1.0,numpy==1.16.6,pandas==0.24.2,pytest==4.6.11,...
py27 run-test-pre: PYTHONHASHSEED='2837498672'
...
开发 Python 包

tox 输出

py27 run-test: commands[0] | pytest
======================== test session starts ========================
platform linux2 -- Python 2.7.17, ...
rootdir: /home/workspace/mypackages/mysklearn
collected 6 items                         

tests/preprocessing/test_normalize.py ...                     [ 50%]
tests/preprocessing/test_standardize.py ...                   [100%]

========================= 6 passed in 0.23s =========================
开发 Python 包

tox 输出

...
__________________________ summary __________________________
  py27: commands succeeded
  py35: commands succeeded
  py36: commands succeeded
  py37: commands succeeded
开发 Python 包

tox 输出

...
__________________________ summary __________________________
  py27: commands succeeded
  py35: commands succeeded
  py36: commands succeeded
ERROR:   py37: commands failed
开发 Python 包

Vamos praticar!

开发 Python 包

Preparing Video For Download...