搜索
首页后端开发Python教程像专业人士一样使用 Poetry、Tox、Nox 和 CI/CD 测试 Python 代码

嘿那里!

有一个 Python 项目并需要确保它适用于 Python 的每个版本?相信我,这可能会让人非常头疼。但别担心,我会支持你的。在本指南中,我将向您展示如何使用 ToxNoxCI/CD 这些很棒的工具来跨多个 Python 版本测试您的代码。

你猜怎么着?这比你想象的要容易。

当您读完本文时,您将像专业人士一样在 Python 3.8 到 3.13 上运行测试。我们会让事情变得简单、有趣并且完全可行。听起来不错吗?让我们深入了解一下。


为什么你应该关心多版本测试?

想象一下:您编写了一些很酷的 Python 代码,并且它可以在您的计算机上运行。但随后,嘭!一位用户给您发电子邮件,说它在 Python 3.9 上崩溃了。你尝试了一下,果然出了问题。

为什么?

因为Python有所有这些版本,并且每个版本都有其怪癖。如果你不在多个版本上测试你的代码,那么你就是盲目的。

但好消息是,您不必手动安装一堆 Python 版本并对每个版本运行测试。这就是 Tox 和 Nox 像超级英雄一样突然出现的地方。


什么是Tox和Nox?

让我们来分解一下:

  • Tox:将其视为在不同 Python 环境中测试代码的机器人。它组织得非常好,并遵循简单的 tox.ini 文件中的指令。你告诉 Tox 做什么,它就会这么做。

  • Nox:它就像 Tox,但在某些方面更酷。为什么?因为您不需要编写配置文件,而是编写 Python 脚本 (noxfile.py)。想要添加自定义逻辑或条件? Nox 为您提供支持。

那么哪个更好呢?老实说,这取决于。如果您喜欢简洁明了的事物,请选择 Tox。如果您是创意型人士并且喜欢灵活性,Nox 就是您的选择。


让我们构建一些很酷的东西

这是交易:

我们将创建一个具有两个简单功能的迷你项目:

  • 添加两个数字。
  • 用一个数字减去另一个数字。

我们将编写一些测试来确保它们工作,然后我们将使用 Tox 和 Nox 在 Python 版本 3.8 到 3.13 上测试它们。

听起来很有趣,对吧?

这是我们正在使用的文件结构:

tox-nox-python-test-automation/
├── tox_nox_python_test_automation/
│   ├── __init__.py
│   ├── main.py
│   └── calculator.py
├── tests/
│   ├── __init__.py
│   └── test_calculator.py
├── pyproject.toml
├── tox.ini
├── noxfile.py
├── README.md

第 1 步:编写代码

这是我们的calculator.py

def add(a, b):
    """Returns the sum of two numbers."""
    return a + b

def subtract(a, b):
    """Returns the difference of two numbers."""
    return a - b

简单吧?让我们保持这样吧。


第 2 步:编写一些测试

是时候确保我们的代码有效了。这是我们的test_calculator.py

tox-nox-python-test-automation/
├── tox_nox_python_test_automation/
│   ├── __init__.py
│   ├── main.py
│   └── calculator.py
├── tests/
│   ├── __init__.py
│   └── test_calculator.py
├── pyproject.toml
├── tox.ini
├── noxfile.py
├── README.md

我们正在使用pytest,这是一个测试工具,基本上是 Python 测试的 MVP。如果您从未使用过它,请不要担心,它非常容易上手。


第三步:用 Poetry 管理依赖关系

好的,那么我们如何确保参与该项目的每个人都使用相同的依赖项?我们使用 Poetry,它就像一个增压的 requests.txt 文件。

这是我们的 pyproject.toml 的样子:

def add(a, b):
    """Returns the sum of two numbers."""
    return a + b

def subtract(a, b):
    """Returns the difference of two numbers."""
    return a - b

要安装所有内容,只需运行:

import pytest
from tox_nox_python_test_automation.calculator import add, subtract

@pytest.mark.parametrize("a, b, expected", [
    (1, 2, 3),
    (-1, 1, 0),
    (0, 0, 0),
])
def test_add(a, b, expected):
    assert add(a, b) == expected

@pytest.mark.parametrize("a, b, expected", [
    (5, 3, 2),
    (10, 5, 5),
    (-1, -1, 0),
])

def test_subtract(a, b, expected):
    assert subtract(a, b) == expected

第 4 步:使用 Pytest 运行单元测试

您可以这样运行基本单元测试:

[tool.poetry]
name = "tox_nox_python_tests"
version = "0.1.0"
description = "Testing with multiple Python versions using Tox and Nox."
authors = ["Wallace Espindola <wallace.espindola>"]
license = "MIT"

[tool.poetry.dependencies]
python = "^3.8"
pytest = "^8.3"
nox = "^2024.10.9"
tox = "^4.23.2"
</wallace.espindola>

并且将看到标准单元测试运行输出。


第 5 步:使用 Tox 进行测试

Tox 就是自动化。这是我们的tox.ini

poetry install

使用一个命令运行 Tox:

poetry run pytest --verbose

繁荣! Tox 将在列出的每个 Python 版本上测试您的代码。请参阅此处的示例输出:

Test Python Code Like a Pro with Poetry, Tox, Nox and CI/CD


第 6 步:使用 Nox 进行测试

想要更多控制权? Nox 让您发挥创意。这是我们的noxfile.py

[tox]
envlist = py38, py39, py310, py311, py312, py313

[testenv]
allowlist_externals = poetry
commands_pre =
    poetry install --no-interaction --no-root
commands =
    poetry run pytest

运行 Nox:

poetry run tox

现在您可以完全灵活地添加逻辑、跳过环境或执行您需要的任何其他操作。请参阅此处的示例输出:

Test Python Code Like a Pro with Poetry, Tox, Nox and CI/CD


第 7 步:使用 CI/CD 实现自动化

为什么要停止本地测试?让我们将其设置为在 GitHub Actions 和 GitLab CI/CD 上自动运行。

GitHub 操作

这是一个工作流程文件.github/workflows/python-tests.yml:

import nox

@nox.session(python=["3.8", "3.9", "3.10", "3.11", "3.12", "3.13"])
def tests(session):
    session.install("poetry")
    session.run("poetry", "install", "--no-interaction", "--no-root")
    session.run("pytest")

GitLab CI/CD

这是一个 .gitlab-ci.yml:

poetry run nox

让我们总结一下

你做到了!您现在知道如何使用 Tox、Nox 和 Poetry 跨多个版本测试 Python 代码。

以下是要记住的内容:

  1. Tox 是您进行简单自动化测试的首选。
  2. Nox 让您可以自由定制。
  3. Poetry 使管理依赖关系变得轻而易举。
  4. CI/CD 确保您的测试自动运行。

当然是参考资料

此项目使用 ToxNoxPoetryPytest 进行测试自动化。详细文档请查看:

毒性文档
Nox 文档
诗歌文献
Pytest 文档


需要完整的代码和示例吗?查看 GitHub 上的存储库:tox-nox-python-tests。

有关其他有趣的主题和技术讨论,请查看我的 LinkedIn 页面。

现在就出去让你的 Python 项目防弹吧! ?

以上是像专业人士一样使用 Poetry、Tox、Nox 和 CI/CD 测试 Python 代码的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
列表和阵列之间的选择如何影响涉及大型数据集的Python应用程序的整体性能?列表和阵列之间的选择如何影响涉及大型数据集的Python应用程序的整体性能?May 03, 2025 am 12:11 AM

ForhandlinglargedatasetsinPython,useNumPyarraysforbetterperformance.1)NumPyarraysarememory-efficientandfasterfornumericaloperations.2)Avoidunnecessarytypeconversions.3)Leveragevectorizationforreducedtimecomplexity.4)Managememoryusagewithefficientdata

说明如何将内存分配给Python中的列表与数组。说明如何将内存分配给Python中的列表与数组。May 03, 2025 am 12:10 AM

Inpython,ListSusedynamicMemoryAllocationWithOver-Asalose,而alenumpyArraySallaySallocateFixedMemory.1)listssallocatemoremoremoremorythanneededinentientary上,respizeTized.2)numpyarsallaysallaysallocateAllocateAllocateAlcocateExactMemoryForements,OfferingPrediCtableSageButlessemageButlesseflextlessibility。

您如何在Python数组中指定元素的数据类型?您如何在Python数组中指定元素的数据类型?May 03, 2025 am 12:06 AM

Inpython,YouCansspecthedatatAtatatPeyFelemereModeRernSpant.1)Usenpynernrump.1)Usenpynyp.dloatp.dloatp.ploatm64,formor professisconsiscontrolatatypes。

什么是Numpy,为什么对于Python中的数值计算很重要?什么是Numpy,为什么对于Python中的数值计算很重要?May 03, 2025 am 12:03 AM

NumPyisessentialfornumericalcomputinginPythonduetoitsspeed,memoryefficiency,andcomprehensivemathematicalfunctions.1)It'sfastbecauseitperformsoperationsinC.2)NumPyarraysaremorememory-efficientthanPythonlists.3)Itoffersawiderangeofmathematicaloperation

讨论'连续内存分配”的概念及其对数组的重要性。讨论'连续内存分配”的概念及其对数组的重要性。May 03, 2025 am 12:01 AM

Contiguousmemoryallocationiscrucialforarraysbecauseitallowsforefficientandfastelementaccess.1)Itenablesconstanttimeaccess,O(1),duetodirectaddresscalculation.2)Itimprovescacheefficiencybyallowingmultipleelementfetchespercacheline.3)Itsimplifiesmemorym

您如何切成python列表?您如何切成python列表?May 02, 2025 am 12:14 AM

SlicingaPythonlistisdoneusingthesyntaxlist[start:stop:step].Here'showitworks:1)Startistheindexofthefirstelementtoinclude.2)Stopistheindexofthefirstelementtoexclude.3)Stepistheincrementbetweenelements.It'susefulforextractingportionsoflistsandcanuseneg

在Numpy阵列上可以执行哪些常见操作?在Numpy阵列上可以执行哪些常见操作?May 02, 2025 am 12:09 AM

numpyallowsforvariousoperationsonArrays:1)basicarithmeticlikeaddition,减法,乘法和division; 2)evationAperationssuchasmatrixmultiplication; 3)element-wiseOperations wiseOperationswithOutexpliitloops; 4)

Python的数据分析中如何使用阵列?Python的数据分析中如何使用阵列?May 02, 2025 am 12:09 AM

Arresinpython,尤其是Throughnumpyandpandas,weessentialFordataAnalysis,offeringSpeedAndeffied.1)NumpyArseNable efflaysenable efficefliceHandlingAtaSetSetSetSetSetSetSetSetSetSetSetsetSetSetSetSetsopplexoperationslikemovingaverages.2)

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

mPDF

mPDF

mPDF是一个PHP库,可以从UTF-8编码的HTML生成PDF文件。原作者Ian Back编写mPDF以从他的网站上“即时”输出PDF文件,并处理不同的语言。与原始脚本如HTML2FPDF相比,它的速度较慢,并且在使用Unicode字体时生成的文件较大,但支持CSS样式等,并进行了大量增强。支持几乎所有语言,包括RTL(阿拉伯语和希伯来语)和CJK(中日韩)。支持嵌套的块级元素(如P、DIV),

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )专业的PHP集成开发工具