Es un bloque de código que comprueba el correcto funcinamiento de una unidad de código fuente.
Kent Beck
No se escribe código sin antes escribir una prueba unitaria que especifica su objetivo y comprueba que se cumple.
Es un ambiente totalmente aislado donde puedes manipular las dependencias de tu proyecto con mayor flexibilidad.
pytest es un framework que hace fácil la creación de pequeñas pruebas unitarias hasta complejas pruebas funcionales.
https://github.com/mayela/clase-muestra-tdd.git
def test_add():
assert add() == 8
tests.py
$ venv/bin/pytest tests.py
=================================== test session starts ====================================
platform linux -- Python 3.6.6rc1, pytest-3.6.1, py-1.5.3, pluggy-0.6.0
rootdir: /data/Documentos/proyectos-python/demo-pytest, inifile:
collected 1 item
calc.py F [100%]
=================================== FAILURES ==============================================
___________________________________ test_add ______________________________________________
def test_add():
> assert add() == 8
E NameError: name 'add' is not defined
tests.py:2: NameError
================================= 1 failed in 0.08 seconds ================================
# calc.py
def add():
return 8
# tests.py
def test_add():
assert add() == 8
$ venv/bin/pytest tests.py
================================= test session starts =================================
platform linux -- Python 3.6.6rc1, pytest-3.6.1, py-1.5.3, pluggy-0.6.0
rootdir: /data/Documentos/proyectos-python/demo-pytest, inifile:
collected 1 item
tests.py . [100%]
================================= 1 passed in 0.07 seconds ============================
# calc.py
def add():
return 8
# tests.py
def test_add_equals_to_8():
assert add() == 8
def test_add_equals_to_5():
assert add() == 5
$ venv/bin/pytest tests.py
============================= test session starts ================================
platform linux -- Python 3.6.6rc1, pytest-3.6.1, py-1.5.3, pluggy-0.6.0
rootdir: /data/Documentos/proyectos-python/demo-pytest, inifile:
collected 2 items
calc.py .F [100%]
============================= FAILURES ===========================================
_____________________________ test_add_equals_to_5 _______________________________
def test_add_equals_to_5():
> assert add() == 5
E assert 8 == 5
E + where 8 = add()
tests.py:8: AssertionError
============================= 1 failed, 1 passed in 0.11 seconds =================
# calc.py
def add(first_number, second_number):
return first_number + second_number
# tests.py
def test_add_equals_to_8():
assert add(5, 3) == 8
def test_add_equals_to_5():
assert add(2, 3) == 5
$ venv/bin/pytest tests.py
============================== test session starts ================================
platform linux -- Python 3.6.6rc1, pytest-3.6.1, py-1.5.3, pluggy-0.6.0
rootdir: /data/Documentos/proyectos-python/demo-pytest, inifile:
collected 2 items
tests.py .. [100%]
============================== 2 passed in 0.07 seconds ============================