4. Simple GET
For this lesson we are not going to use Django REST Framework (or DRF), only Django. This is because certain Endpoints (routes we can invoke) are so simple that it is counterproductive to add the complexity that DRF does offer us.
We will create the classic ping-pong to check that the server is alive.
We build the view with the response.
# app/libros/views.py
from django.http import JsonResponse
def ping(request):
data = {"ping": "pong!"}
return JsonResponse(data)
We add the route.
# proyecto/urls.py
from django.contrib import admin
from django.urls import path
from app.libros.views import ping # new
urlpatterns = [
path('admin/', admin.site.urls),
path('ping/', ping, name="ping"), # new
]
We start the server.
python3 manage.py runserver
And we send an HTTP request from the terminal with curl to check that it gives us the expected response.
curl http://localhost:8000/ping/
It will return the following JSON.
{"ping": "pong!"}
It is time to create a new test. We create test_ping.py.
tests
└── libros
└── test_ejemplo.py
test_ping.py
# tests/libros/test_ping.py
import json
from django.urls import reverse
def test_ping(client):
# We get the "ping" route
url = reverse("ping")
# We make a GET request with the Django test client
response = client.get(url)
# I receive a JSON that I convert to a dictionary to handle it
content = json.loads(response.content)
# The asserts help me make the checks.
# Do I receive code 200?
assert response.status_code == 200
# Is the content of Ping equal to Pong?> {"ping": "pong!"}
assert content["ping"] == "pong!"
client is a helper fixture from pytest-django that provides an instance of django.test.Client. Basically it is an HTTP client that we can use inside the tests.
You can now run the test.
pytest
=================================================== 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 2 items
tests/libros/test_ejemplo.py . [ 50%]
tests/libros/test_ping.py . [100%]
==================================================== 2 passed in 0.05s ====================================================
Everything passed, great!
To write different tests, a good pattern is Given-When-Then. A structure of 3 informal comment blocks to divide the code.
- Given: State before the code. You prepare the scenario and the conditions of the test, such as data in the database, states, or tools.
- When: The test code. You execute the actions that test the different features.
- Then: Checks or asserts to verify that the expected cases have been met.
The previous code would look like this.
# tests/libros/test_ping.py
import json
from django.urls import reverse
def test_ping(client):
## Given
# Nothing to manipulate in the database
## When
url = reverse("ping")
response = client.get(url)
content = json.loads(response.content)
## Then
assert response.status_code == 200
assert content["ping"] == "pong!"
This work is under a Attribution-NonCommercial-NoDerivatives 4.0 International license.
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 bookWill you buy me a coffee?
This is how I keep writing without ads or paywalls.
Sure, it's on me!
Comments
There are no comments yet.