Tests unitaires

Principes d’ingénierie logicielle en Python

Adam Spannbauer

Machine Learning Engineer at Eastman

Pourquoi tester ?

  • Confirmer que le code fonctionne comme prévu
  • Assurer que les modifications d'une fonction n'en cassent pas une autre
  • Protéger contre les changements dans une dépendance
Principes d’ingénierie logicielle en Python

Tests en Python

  • doctest
  • pytest

logo pytest

Principes d’ingénierie logicielle en Python

Utiliser doctest

def square(x):
    """Élever le nombre x au carré

    :param x: nombre à élever au carré
    :return: x au carré

    >>> square(3)
    9
    """
    return x ** 3


import doctest doctest.testmod()
Exemple échoué :
    square(3)
Attendu :
    9
Obtenu :
    27
Principes d’ingénierie logicielle en Python

Structure de pytest

Structure du test

Principes d’ingénierie logicielle en Python

Structure de pytest

Structure du test

Principes d’ingénierie logicielle en Python

Écrire des tests unitaires

travail dans workdir/tests/test_document.py

from text_analyzer import Document


# Tester l'attribut tokens sur l'objet Document
def test_document_tokens():
    doc = Document('a e i o u')

    assert doc.tokens == ['a', 'e', 'i', 'o', 'u']

# Tester le cas limite d'un document vide def test_document_empty(): doc = Document('') assert doc.tokens == [] assert doc.word_counts == Counter()
Principes d’ingénierie logicielle en Python

Écrire des tests unitaires

# Créer 2 objets Document identiques
doc_a = Document('a e i o u')
doc_b = Document('a e i o u')

# Vérifier si les objets sont ==
print(doc_a == doc_b)

# Vérifier si les attributs sont == print(doc_a.tokens == doc_b.tokens) print(doc_a.word_counts == doc_b.word_counts)
False

True True
Principes d’ingénierie logicielle en Python

Exécuter pytest

travail avec terminal

datacamp@server:~/work_dir $ pytest
collected 2 items

tests/test_document.py ..                     [100%]

========== 2 passed in 0.61 seconds ==========
Principes d’ingénierie logicielle en Python

Exécuter pytest

travail avec terminal

datacamp@server:~/work_dir $ pytest tests/test_document.py
collected 2 items

tests/test_document.py ..                     [100%]

========== 2 passed in 0.61 seconds ==========
Principes d’ingénierie logicielle en Python

Tests échoués

travail avec terminal

datacamp@server:~/work_dir $ pytest
collected 2 items

tests/test_document.py F.

============== FAILURES ==============
________ test_document_tokens ________

def test_document_tokens(): doc = Document('a e i o u')

assert doc.tokens == ['a', 'e', 'i', 'o']
E AssertionError: assert ['a', 'e', 'i', 'o', 'u'] == ['a', 'e', 'i', 'o']
E Left contains more items, first extra item: 'u'
E Use -v to get the full diff

tests/test_document.py:7: AssertionError
====== 1 failed in 0.57 seconds ======
Principes d’ingénierie logicielle en Python

Passons à la pratique !

Principes d’ingénierie logicielle en Python

Preparing Video For Download...