Pruebe endpoints autenticados
Inicie sesión dentro de las pruebas para acceder a rutas protegidas.
Pruebe endpoints autenticados es una lección gratuita de Flask Academy en CoddyKit. Esta es la lección 4 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Flask Academy, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Flask Academy incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
The Challenge of Auth Tests
Protected routes refuse anonymous visitors. To test them, your client must first log in, just like a real user would before reaching guarded pages.
Confirm the Guard Works
Start by proving the gate is closed. Request the route logged out and assert you get a redirect or a 401 response.
resp = client.get('/dashboard')
assert resp.status_code == 302Log In via the Login Route
The realistic way to authenticate is to post credentials to your login endpoint. The client stores the session cookie automatically.
client.post('/login', data={'email': 'a@b.com', 'password': 'pw'})The Client Keeps Cookies
One handy detail: the test client remembers cookies between calls. After login, later requests stay authenticated with no extra work.
Reach a Protected Route
Now that you are logged in, request the guarded page again. This time assert you get a 200 and see the protected content.
resp = client.get('/dashboard')
assert resp.status_code == 200A Helper to Log In
Repeating the login post gets noisy. Wrap it in a small helper function so every auth test reads cleanly in one line.
def login(client):
return client.post('/login', data={'email': 'a@b.com', 'password': 'pw'})An Authenticated Fixture
Even better, make a fixture that returns an already-logged-in client. Tests that need auth just request it and skip the setup.
@pytest.fixture
def auth_client(client):
login(client)
yield clientTest the Logout Flow
Auth is not done until logout works. Hit /logout, then confirm the protected route again rejects the now anonymous client.
client.get('/logout')
assert client.get('/dashboard').status_code == 302Bypass Login for Speed
For Flask-Login apps you can skip the form and set the session directly. It is faster but tests less of the real login path.
with client.session_transaction() as sess:
sess['_user_id'] = '1'Test Token-Protected APIs
For JWT APIs there is no cookie. Send the token in an Authorization header on each request to reach a protected endpoint.
client.get('/api/me', headers={'Authorization': 'Bearer ' + token})Test Both Sides of the Gate
Strong auth tests check both outcomes: anonymous users are blocked, and authenticated users are allowed. Cover the happy and the sad path.
Quick Check
You need to test a login-only dashboard. What makes it work?
Recap: Authenticated Tests
You log in through the client, lean on its cookie memory, and assert both blocked and allowed paths. Your auth is now fully covered. 🔐
Preguntas frecuentes
¿La lección «Pruebe endpoints autenticados» es gratis?
Sí — el texto completo de «Pruebe endpoints autenticados» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Flask Academy, actualiza a CoddyKit PRO. El curso de Flask Academy incluye 4 lecciones en total.
¿Qué aprenderé en «Pruebe endpoints autenticados»?
Inicie sesión dentro de las pruebas para acceder a rutas protegidas. Practicas Flask Academy con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar Flask Academy?
No se requiere experiencia previa. Flask Academy en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 4 de 4.
¿Cuánto tiempo toma la lección «Pruebe endpoints autenticados»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de Flask Academy?
Sí. Cada lección de Flask Academy incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- El cliente de pruebas y los fixtures
- Compruebe rutas y JSON
- Aísle las pruebas con una base de datos de prueba
- Pruebe endpoints autenticados