3. Testing

We are going to add pytest as a testing tool so that it uses Django's configuration. To do this, we will create the file pytest.ini in the root of the project with the following content.

[pytest]
DJANGO_SETTINGS_MODULE = proyecto.settings

# Optional, but recommended
python_files = tests.py test_*.py *_tests.py

For this project, we are going to keep all our tests together in a single tests directory divided by applications.

Create a new directory called tests and inside it another directory called libros. Finally, inside libros create a file called test_ejemplo.py.

tests
    └── libros
            └── test_ejemplo.py

By default, pytest will find test files that start or end with the word test. For example, test_*.py or *test.py. Test functions must start with test, and if you want to use classes they must start with Test.

Add the following content.

# tests/libros/test_ejemplo.py

# Functions must start with "test_"
def test_titulo():
    assert "a song of ice and fire" != "game of thrones"

To run all the tests, just run.

pytest

It will let you know that the test passed without any problems.

=================================================== test session starts ===================================================
platform linux -- Python 3.9.2, pytest-6.2.4, py-1.10.0, pluggy-0.13.1
django: settings: proyecto.settings (from ini)
plugins: django-4.4.0
collected 1 item

tests/libros/test_ejemplo.py .                                                                                      [100%]

==================================================== 1 passed in 0.04s ====================================================

This work is under a Attribution-NonCommercial-NoDerivatives 4.0 International license.

Desafíos de programación atemporales y multiparadigmáticos

Desafíos de programación atemporales y multiparadigmáticos

Te encuentras ante un librillo de actividades, divididas en 2 niveles de dificultad. Te enfrentarás a los casos más comunes que te puedes encontrar en pruebas técnicas o aprender conceptos elementales de programación.

Buy the book

Will you buy me a coffee?

This is how I keep writing without ads or paywalls.

Comments

There are no comments yet.