Source : CommitStrip
Note
No test is perfect, but it still helps eliminate many errors.
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:
player_service.py
test_player_service.py
from unittest.mock import MagicMock
def test_create_ok():
"""Successful creation of Player"""
# GIVEN
pseudo, mdp, age, mail, fan_pokemon = "jp", "1234", 15, "z@mail.oo", True
PlayerDao().creer = MagicMock(return_value=True)
# WHEN
player = PlayerService().creer(pseudo, mdp, age, mail, fan_pokemon)
# THEN
assert isinstance(player, Player)
assert player.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 ?