Source : CommitStrip
Note
Aucun test n’est parfait, mais cela permet quand même d’écarter de nombreuses erreurs.
A test resembles a scientific experiment.
It examines a hypothesis expressed in terms of three elements:
This examination is conducted
Be lazy : fewer tests, but useful ones!
There are many different types of tests, here are the main ones:
We will use the pytest package to perform our tests in Python.
operations_mathematiques.py
class MathOperations:
"""Mathematical Operations"""
def divide_five_by(self, nb) -> float:
"""Divides the number 5 by a given number.
Parameters
----------
nb : float or int
The number by which 5 will be divided.
Returns
-------
float or None
The result of dividing 5 by the given number.
If the number is equal to 0, the method returns None.
"""
if nb != 0:
return 5 / nb
else:
return NoneLet’s create a test class.
To test the nominal case (=“normal” case), we:
divide_five_by() methodBut this is not sufficient!
NoneWe call the method with this parameter: divide_five_by("a")?
You can also write a test to verify that your method indeed returns a TypeError exception in this case.
Unit tests:
joueur_service.py
class JoueurService:
def creer(self, pseudo, mdp, age, mail, fan_pokemon) -> Joueur:
nouveau_joueur = Joueur(
pseudo=pseudo,
mdp=hash_password(mdp, pseudo),
age=age,
mail=mail,
fan_pokemon=fan_pokemon,
)
creation_ok = JoueurDao().creer(nouveau_joueur)
if creation_ok:
return nouveau_joueur
else:
return Nonetest_joueur_service.py
from unittest.mock import MagicMock
def test_creer_ok():
"""Successful creation of Joueur"""
# GIVEN
pseudo, mdp, age, mail, fan_pokemon = "jp", "1234", 15, "z@mail.oo", True
JoueurDao().creer = MagicMock(return_value=True)
# WHEN
joueur = JoueurService().creer(pseudo, mdp, age, mail, fan_pokemon)
# THEN
assert isinstance(joueur, Joueur)
assert joueur.pseudo == pseudoAt the beginning!
Tip
The earlier you test, the more effective and less costly the tests are!
The best practice:
It may seem a bit strange !?
But…
When you code a function, you know before you start:
Important
Advantages >>> Disadvantages
Designate the Test Police (or the Quality Police)
Why ?