You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesi贸n a prueba de IA

Antes: $249

Currency
$209
Suscr铆bete

Termina en:

2 D铆as
5 Hrs
10 Min
18 Seg

Pruebas Unitarias con PyTest en Python

19/20
Resources

Python offers a wide variety of tools, and one of the most useful for automated testing is PyTest. PyTest greatly enhances the developer experience by allowing you to write and run tests more efficiently. In this guide we will see how to install PyTest, create parameterized tests and run a basic example.

How to install and configure PyTest?

  • Open the terminal and run the following command to install PyTest
    :pip install pytest
  • Remember to add it to your requirements.txt file with
    :pip freeze | grep pytest > requirements.txt

How to create a test with PyTest?

  1. In the test folder, create a file called test_pytest.py.
  2. Import PyTest into your file
    :import pytest
  3. Create a simple test function like this
    :def test_sum():a = 4b = 4 assert a + b == 8
  4. Run the test with the following command
    :pytest test_pytest.py

PyTest does not require the creation of classes to group tests, which simplifies the code. In this case, tests are grouped by file.

How to parameterize a test in PyTest?

  1. Use PyTest decorators to parameterize the
     prueba:@pytest.mark.parametrize("amount, expected", [(100, 5000), (200, 5500), (300, 6000) ])def test_balance(amount, expected): assert calculate_balance(amount) == expected
  2. In this example, the test function receives several cases with different values of amount and expected.
  3. Run the tests
    :pytest -v

What are the advantages of PyTest when running tests?

  • PyTest provides detailed, easy-to-read error messages, highlighted with colors.
  • The errors include the specific values that caused the failure.
  • With the -v option, PyTest details which tests were run and their results.

What happens if a test fails?

If a test fails, PyTest will tell you exactly which values did not match. For example, if one of the expected values is incorrect:

def test_balance(): assert calculate_balance(100) == 5400 # This value is incorrect.

When you run the test again, PyTest will show you the difference between the expected value and the actual value.

Challenge

Refactor all the tests in your project to use PyTest, applying what we have seen about parameterization and the use of simpler asserts.

Contributions 6

Questions 0

Sort by:

Want to see more contributions, questions and answers from the community?

Yo realic茅 el curso usando `pytest`, por aqu铆 dejo el repo por si quieren ver las diferencias con `unittest`: <https://github.com/JimcostDev/unit-testing>
* **Pytest** es ideal si buscas una herramienta flexible, con una sintaxis m谩s limpia y una comunidad activa que ofrece muchos plugins. * **Unittest** es una buena opci贸n si prefieres una herramienta integrada en la biblioteca est谩ndar de Python y una estructura m谩s cl谩sica.
En windows se puede usar el comando pip freeze de la siguiente manera: py -m pip freeze > requirements.txt
Yo de mero macho voy a hacer el curso de nuevo solo utilizando pytest. Like si vas por lo mismo.
```python @pytest.fixture def account(): return BankAccount() @patch("src.BankAccount.datetime") def test_withdraw_off_business_days_fails(mock_datetime, account): mock_datetime.now.return_value.hour = 9 mock_datetime.now.return_value.weekday.return_value = 6 with pytest.raises(OutOfScheduleError): account.withdraw(1000) ```
Por ac谩 comparto como se captura las excepciones en pytest: ```python def test_divide_zero(): with pytest.raises(ValueError,match="No se puede dividir entre 0"): c.divide(4,0) ```