在不同環境中測試你的套件

開發 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,將 pyXY 加到 envlist
  • 你要測的 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 套件

一起來練習吧!

開發 Python 套件

Preparing Video For Download...