Programmation Orientée Objet en Python
  • Back to Main Website
  • Home
  • Introduction: Histoire et Concepts
    • Introduction: Histoire et Concepts
    • Histoire de la programmation
    • Première Structuration des données
    • Naissance de la POO
    • Python: tout n’est qu’objet
    • Python : Simplicité des objets et performance sous-jacente
    • Classes en Python : Concepts fondamentaux

    • Travaux Pratiques
    • Construire sa propre Liste
    • Construire son propre DataFrame
  • Encapsulation, Héritage, Composition et Dunder
    • Encapsulation, Heritage, Composition et Dunder
    • Encapsulation en Python
    • Héritage en Python : Concept et intérêt
    • Héritage vs Composition
    • Méthodes Dunder en Python
    • Python call Method: A Fun Exploration

    • Travaux Pratiques
    • TP: Heritage avec le pricing d’option
    • TP : Ajouter des méthodes dunder à DataFrameSimple
    • TP : Étendre la classe Liste avec des méthodes dunder
    • TP: Dunder Method with Tensor for Automatic Differentiation
  • Polymorphisme et Surcharge
    • Polymorphisme et Surcharge
    • Polymorphism in Object-Oriented Programming
    • Polymorphism in Python: Function Overloading and Type Checking
    • Class Creation: Standard vs type()
    • Type Hinting, Typing Module, and Linters in Python
    • Abstract Classes
    • Protocol Classes

    • Travaux Pratiques
    • TP
  • Decorators
    • Design Patterns
    • The decorator pattern
    • Decorator Practically
    • Built-in Decorators and Standard Library Decorators in Python
    • Practical Decorators in Python Libraries

    • Travaux Pratiques
    • TP: Monte Carlo Option Pricing with Decorators
    • TP: Optimizing Heston Model Monte Carlo Simulation
  • Project Management and Packaging
    • Project and Package
    • Organizing Python Projects
    • Understanding imports
    • Python Package Management and Virtual Environments
    • Unit Testing in Python

    • Travaux Pratiques
    • TP: Creating a Linear Regression Package
  • Design Patterns
    • OOP Design Patterns
    • Python-Specific Design Patterns
    • Creation Design Patterns
    • Structural Design Patterns
    • Behavioral Design Pattern

    • Travaux Pratiques
    • TP
  • Sujets de Projets possibles
    • Projets
    • Projets POO - 2024-2025
  • Code source
  1. Unit Testing in Python
  • Project and Package
  • Organizing Python Projects
  • Understanding imports
  • Python Package Management and Virtual Environments
  • Unit Testing in Python
  • Travaux Pratiques
    • TP: Creating a Linear Regression Package

On this page

  • Unit Testing in Python
    • Popular Python Testing Frameworks:
    • Basic pytest Usage
    • Integrating pytest with Poetry
    • Advanced pytest Configuration
    • Running Tests with Poetry
    • Continuous Integration
    • Best Practices

Unit Testing in Python

Cours
Fondamentaux
Learn how to write and run unit tests in Python using the pytest framework.
Author

Remi Genet

Published

2024-10-21

Unit Testing in Python


Unit testing is a software development practice where individual components or functions of a program are tested in isolation. The primary goals of unit testing are:

  1. To verify that each part of the program works correctly on its own.
  2. To catch and fix bugs early in the development process.
  3. To facilitate refactoring and maintenance of code.
  4. To serve as documentation for how components should behave.

A unit test typically follows this pattern: 1. Set up the test conditions. 2. Call the function or method being tested. 3. Assert that the output or behavior matches the expected result.

Python offers several frameworks to help write and run unit tests efficiently. While the built-in unittest module is available, many developers prefer pytest for its simplicity and powerful features.

Popular Python Testing Frameworks:

  1. unittest: Python’s built-in testing framework.
  2. pytest: A more advanced, feature-rich testing framework.
  3. nose: An extension of unittest (less common nowadays).

We’ll focus on pytest due to its popularity and ease of use, especially when integrated with modern Python project management tools like Poetry.

Basic pytest Usage

  1. Install pytest:

    pip install pytest
  2. Write a test file (e.g., test_example.py):

  3. Run tests:

    pytest

Integrating pytest with Poetry

  1. Add pytest to your project’s dev-dependencies:

    poetry add --dev pytest
  2. Update your pyproject.toml:

    [tool.poetry.dev-dependencies]
    pytest = "^7.4.0"
    
    [tool.pytest.ini_options]
    testpaths = ["tests"]

    This configuration tells pytest to look for tests in the tests directory.

  3. Organize your project structure:

    myproject/
    ├── src/
    │   └── mypackage/
    │       └── example.py
    ├── tests/
    │   └── test_example.py
    └── pyproject.toml
  4. Write your tests in the tests directory.

  5. Run tests using Poetry:

    poetry run pytest

Advanced pytest Configuration

You can add more options to your pyproject.toml:

[tool.pytest.ini_options]
testpaths = ["tests"]
addopts = "-v --cov=src"

This configuration: - Runs tests verbosely (-v) - Includes coverage reporting (--cov=src)

Running Tests with Poetry

To make running tests easier, you can add a script to your pyproject.toml:

[tool.poetry.scripts]
test = "pytest"

Now you can run tests with:

poetry run test

Continuous Integration

For CI/CD pipelines, you can use Poetry to install dependencies and run tests:

# Example GitHub Actions workflow
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v2
    - name: Set up Python
      uses: actions/setup-python@v2
      with:
        python-version: 3.9
    - name: Install dependencies
      run: |
        pip install poetry
        poetry install
    - name: Run tests
      run: poetry run pytest

This setup ensures your tests are run automatically on every push or pull request.

Best Practices

  1. Write tests for all new features and bug fixes.
  2. Aim for high test coverage, but focus on critical paths.
  3. Use meaningful test names that describe the behavior being tested.
  4. Keep tests independent and avoid dependencies between tests.
  5. Use fixtures and parametrization to reduce code duplication in tests.

By integrating pytest with Poetry, you create a streamlined development workflow where dependency management, building, and testing are all handled by a single tool.

Back to top
Python Package Management and Virtual Environments
TP: Creating a Linear Regression Package

Programmation Orienté Object en Python, Rémi Genet.
Licence
Code source disponible sur Github

 

Site construit avec et Quarto
Inspiration pour la mise en forme du site ici
Code source disponible sur GitHub