Exemples pratiques

Introduction aux tests en Python

Alexander Levin

Data Scientist

Données et pipeline

Données : salaires en science des données.

Chaque ligne décrit une personne qui travaille en science des données avec son salaire, son titre et d'autres attributs.

table des salaires en science des données

Pipeline : calculer le salaire moyen :

  1. Lire les données
  2. Filtrer par type d'emploi
  3. Calculer le salaire moyen
  4. Enregistrer les résultats
Introduction aux tests en Python

Code du pipeline

import pandas as pd

# Fixture to get the data
@pytest.fixture
def read_df():
    return pd.read_csv('ds_salaries.csv')
# Function to filter the data
def filter_df(df):
    return df[df['employment_type'] == 'FT']
# Function to get the mean
def get_mean(df):   
    return df['salary_in_usd'].mean()
Introduction aux tests en Python

Tests d'intégration

Cas de test :

  • Lecture des données
  • Écriture dans le fichier

Code :

def test_read_df(read_df):
    # Check the type of the dataframe
    assert isinstance(read_df, pd.DataFrame)
    # Check that df contains rows
    assert read_df.shape[0] > 0
Introduction aux tests en Python

Tests d'intégration

Exemple pour vérifier que Python peut créer des fichiers.

def test_write():
    # Opening a file in writing mode
    with open('temp.txt', 'w') as wfile:
        # Writing the text to the file
        wfile.write('Testing stuff is awesome')
    # Checking the file exists
    assert os.path.exists('temp.txt')
    # Don't forget to clean after yourself
    os.remove('temp.txt')
Introduction aux tests en Python

Tests unitaires

Cas de test :

  • L'ensemble filtré ne contient que le type d'emploi « FT »
  • La fonction get_mean() retourne un nombre

Code :

def test_units(read_df):
    filtered = filter_df(read_df)
    assert filtered['employment_type'].unique() == ['FT']
    assert isinstance(get_mean(filtered), float)
Introduction aux tests en Python

Tests de fonctionnalité

Cas de test :

  • La moyenne est supérieure à zéro
  • La moyenne n'excède pas le salaire maximal de l'ensemble de données

Code :

def test_feature(read_df):
    # Filtering the data
    filtered = filter_df(read_df)
    # Test case: mean is greater than zero
    assert get_mean(filtered) > 0
    # Test case: mean is not bigger than the maximum
    assert get_mean(filtered) <= read_df['salary_in_usd'].max()
Introduction aux tests en Python

Tests de performance

Cas de test :

  • Temps d'exécution du pipeline de bout en bout

Code :

def test_performance(benchmark, read_df):
    # Benchmark decorator
    @benchmark
    # Function to measure
    def get_result():
        filtered = filter_df(read_df)
        return get_mean(filtered)
Introduction aux tests en Python

Batterie de tests finale

import pytest

## Integration Tests
def test_read_df(read_df):
      # Check the type of the dataframe
    assert isinstance(read_df, pd.DataFrame)
    # Check that df contains rows
    assert read_df.shape[0] > 0
def test_write():
    with open('temp.txt', 'w') as wfile:
        wfile.write('12345')
    assert os.path.exists('temp.txt')
    os.remove('temp.txt')

## Unit Tests
def test_units(read_df):
    filtered = filter_df(read_df)
    assert filtered['employment_type'].unique() == ['FT']
    assert isinstance(get_mean(filtered), float)
## Feature Tests
def test_feature(read_df):
    # Filtering the data
    filtered = filter_df(read_df)
    # Test case: mean is greater than zero
    assert get_mean(filtered) > 0
    # Test case: mean is not bigger than the maximum
    assert get_mean(filtered) <= read_df['salary_in_usd'].max()

## Performance Tests
def test_performance(benchmark, read_df):
    # Benchmark decorator
    @benchmark
    # Function to measure
    def pipeline():
        filtered = filter_df(read_df)
        return get_mean(filtered)
Introduction aux tests en Python

Passons à la pratique !

Introduction aux tests en Python

Preparing Video For Download...