Home Backend Development Python Tutorial Test Python Code Like a Pro with Poetry, Tox, Nox and CI/CD

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

Jan 07, 2025 am 07:07 AM

Hey there!

Got a Python project and need to make sure it works on every version of Python out there? Trust me, that can be a HUGE headache. But don't worry, I’ve got your back. In this guide, I’ll show you how to use Tox, Nox and CI/CD, awesome tools, to test your code across multiple Python versions.

And guess what? It’s easier than you think.

By the time you’re done reading this, you’ll be running tests like a pro across Python 3.8 to 3.13. We’ll keep things simple, fun, and totally actionable. Sound good? Let’s dive in.


Why Should You Even Care About Multi-Version Testing?

Picture this: You write some cool Python code, and it works on your computer. But then, BAM! A user emails you, saying it breaks on Python 3.9. You try it, and sure enough, something’s off.

Why?

Because Python’s got all these versions, and each one has its quirks. If you don’t test your code on multiple versions, you’re flying blind.

But the GOOD NEWS is, you don’t have to manually install a bunch of Python versions and run tests on each. That’s where Tox and Nox swoop in like superheroes.


What Are Tox and Nox?

Let’s break it down:

  • Tox: Think of it as a robot that tests your code in different Python environments. It’s super organized and follows your instructions from a simple tox.ini file. You tell Tox what to do, and it does it.

  • Nox: It’s like Tox, but cooler in some ways. Why? Because instead of a config file, you get to write a Python script (noxfile.py). Want to add custom logic or conditions? Nox has your back.

So which one’s better? Honestly, it depends. If you like things neat and straightforward, go with Tox. If you’re the creative type and love flexibility, Nox is your jam.


Let’s Build Something Cool

Here’s the deal:

We’re gonna create a mini project with two simple functions:

  • Add two numbers.
  • Subtract one number from another.

We’ll write some tests to make sure they work, and then we’ll use Tox and Nox to test them on Python versions from 3.8 to 3.13.

Sounds fun, right?

Here’s the file structure we’re working with:

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
Copy after login
Copy after login

Step 1: Write the Code

Here’s our 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
Copy after login
Copy after login

Simple, right? Let’s keep it that way.


Step 2: Write Some Tests

Time to make sure our code works. Here’s our 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
Copy after login
Copy after login

We’re using pytest, a testing tool that’s basically the MVP of Python testing. If you’ve never used it, don’t sweat it, it’s super easy to pick up.


Step 3: Manage Dependencies with Poetry

Okay, so how do we make sure everyone working on this project uses the same dependencies? We use Poetry, which is like a supercharged requirements.txt file.

Here’s what our pyproject.toml looks like:

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
Copy after login
Copy after login

To install everything, just run:

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
Copy after login

Step 4: Run unit tests with Pytest

You can run the basic unit tests this way:

[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@gmail.com>"]
license = "MIT"

[tool.poetry.dependencies]
python = "^3.8"
pytest = "^8.3"
nox = "^2024.10.9"
tox = "^4.23.2"
Copy after login

And will see a standard unit test running output.


Step 5: Test with Tox

Tox is all about automation. Here’s our tox.ini:

poetry install
Copy after login

Run Tox with one command:

poetry run pytest --verbose
Copy after login

And boom! Tox will test your code across every version of Python listed. See and example output here:

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


Step 6: Test with Nox

Want more control? Nox lets you get creative. Here’s our 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
Copy after login

Run Nox with:

poetry run tox
Copy after login

Now you’ve got full flexibility to add logic, skip environments, or do whatever else you need. See and example output here:

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


Step 7: Automate with CI/CD

Why stop at local testing? Let’s set this up to run automatically on GitHub Actions and GitLab CI/CD.

GitHub Actions

Here’s a workflow file .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")
Copy after login

GitLab CI/CD

Here’s a .gitlab-ci.yml:

poetry run nox
Copy after login

Let’s Wrap It Up

You did it! You now know how to test Python code across multiple versions using Tox, Nox, and Poetry.

Here’s what to remember:

  1. Tox is your go-to for simple, automated testing.
  2. Nox gives you the freedom to customize.
  3. Poetry makes managing dependencies a breeze.
  4. CI/CD ensures your tests run automatically.

References, of course

This project uses Tox, Nox, Poetry, and Pytest for test automation. For detailed documentation, take a look at:

Tox Documentation
Nox Documentation
Poetry Documentation
Pytest Documentation


Need the full code and examples? Check out the repo on GitHub: tox-nox-python-tests.

For other interesting subjects and technical discussions, check my LinkedIn page.

Now go out there and make your Python projects bulletproof! ?

The above is the detailed content of Test Python Code Like a Pro with Poetry, Tox, Nox and CI/CD. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1266
29
C# Tutorial
1239
24
Python vs. C  : Applications and Use Cases Compared Python vs. C : Applications and Use Cases Compared Apr 12, 2025 am 12:01 AM

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

The 2-Hour Python Plan: A Realistic Approach The 2-Hour Python Plan: A Realistic Approach Apr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python: Games, GUIs, and More Python: Games, GUIs, and More Apr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

Python vs. C  : Learning Curves and Ease of Use Python vs. C : Learning Curves and Ease of Use Apr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

How Much Python Can You Learn in 2 Hours? How Much Python Can You Learn in 2 Hours? Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

Python and Time: Making the Most of Your Study Time Python and Time: Making the Most of Your Study Time Apr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python: Exploring Its Primary Applications Python: Exploring Its Primary Applications Apr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

Python: Automation, Scripting, and Task Management Python: Automation, Scripting, and Task Management Apr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

See all articles