11import pytest
22import pytest_asyncio
3+ from fastapi import status
4+ from httpx import AsyncClient
35from services .database .models import Community
4- from sqlmodel import select
56from sqlmodel .ext .asyncio .session import AsyncSession
67
7- from httpx import AsyncClient
8- from fastapi import status
9- from typing import Mapping
108from app .services .auth import hash_password
119
1210password = "123Asd!@#"
1311
14- ## gerar usuario para autenticação
12+
13+ # gerar usuario para autenticação
1514@pytest_asyncio .fixture
1615async def community (session : AsyncSession ):
17- hashed_password = hash_password (password )
18- community = Community (username = "username" , email = "username@test.com" , password = hashed_password )
16+ hashed_password = hash_password (password )
17+ community = Community (
18+ username = "username" , email = "username@test.com" , password = hashed_password
19+ )
1920 session .add (community )
2021 await session .commit ()
2122 await session .refresh (community )
@@ -24,23 +25,20 @@ async def community(session: AsyncSession):
2425
2526@pytest .mark .asyncio
2627async def test_authentication_token_endpoint (
27- async_client : AsyncClient ,
28- community : Community # Adicionando a comunidade do fixture
28+ async_client : AsyncClient ,
29+ community : Community , # Adicionando a comunidade do fixture
2930):
3031 """
3132 Testa o endpoint de login (/token) com credenciais válidas e inválidas.
3233 """
3334 # 1. Teste de login com credenciais válidas
3435 # O OAuth2PasswordRequestForm espera 'username' e 'password'
35- form_data = {
36- "username" : community .username ,
37- "password" : password
38- }
39-
36+ form_data = {"username" : community .username , "password" : password }
37+
4038 response = await async_client .post (
4139 "/api/authentication/token" ,
4240 data = form_data ,
43- headers = {"Content-Type" : "application/x-www-form-urlencoded" }
41+ headers = {"Content-Type" : "application/x-www-form-urlencoded" },
4442 )
4543
4644 # Validar a resposta
@@ -51,17 +49,77 @@ async def test_authentication_token_endpoint(
5149
5250 # 2. Teste de login com credenciais inválidas
5351 invalid_form_data = {
54- "username" : "wrong_username" ,
55- "password" : "wrong_password"
52+ "username" : "wrong_username" ,
53+ "password" : "wrong_password" ,
5654 }
5755
5856 response_invalid = await async_client .post (
5957 "/api/authentication/token" ,
6058 data = invalid_form_data ,
61- headers = {"Content-Type" : "application/x-www-form-urlencoded" }
59+ headers = {"Content-Type" : "application/x-www-form-urlencoded" },
6260 )
63-
61+
6462 # Validar que o status é 401 Unauthorized
6563 assert response_invalid .status_code == status .HTTP_401_UNAUTHORIZED
6664 assert response_invalid .json ()["detail" ] == "Credenciais inválidas"
6765
66+
67+ @pytest .mark .asyncio
68+ async def test_community_me_with_valid_token (
69+ async_client : AsyncClient , community : Community
70+ ):
71+ """
72+ Testa se o endpoint protegido /authenticate/me/ retorna os dados do usuário com um token válido.
73+ """
74+ # 1. Obter um token de acesso primeiro
75+ form_data = {
76+ "grant_type" : "password" ,
77+ "username" : community .username ,
78+ "password" : password ,
79+ }
80+ token_response = await async_client .post (
81+ "/api/authentication/token" ,
82+ data = form_data ,
83+ headers = {"Content-Type" : "application/x-www-form-urlencoded" },
84+ )
85+ assert token_response .status_code == status .HTTP_200_OK
86+ token = token_response .json ()["access_token" ]
87+
88+ # 2. Acessar o endpoint protegido com o token
89+ headers = {"Authorization" : f"Bearer { token } " }
90+ response = await async_client .get ("/api/authentication/me" , headers = headers )
91+
92+ # Validar a resposta
93+ assert response .status_code == status .HTTP_200_OK
94+ user_data = response .json ()
95+ assert user_data ["username" ] == community .username
96+ assert user_data ["email" ] == community .email
97+ # Assegurar que a senha não é retornada na resposta
98+ assert "password" not in user_data
99+
100+
101+ @pytest .mark .asyncio
102+ async def test_community_me_without_token (async_client : AsyncClient ):
103+ """
104+ Testa se o endpoint protegido authentication/me/ retorna um erro 401 sem um token de acesso.
105+ """
106+ response = await async_client .get ("/api/authentication/me" )
107+
108+ # Validar a resposta
109+ assert response .status_code == status .HTTP_401_UNAUTHORIZED
110+ assert "detail" in response .json ()
111+ assert response .json ()["detail" ] == "Not authenticated"
112+
113+
114+ @pytest .mark .asyncio
115+ async def test_community_me_with_bad_token (async_client : AsyncClient ):
116+ """
117+ Testa se o endpoint protegido authentication/me/ retorna um erro 401 sem um token de acesso.
118+ """
119+ headers = {"Authorization" : "Bearer WrongToken" }
120+ response = await async_client .get ("/api/authentication/me" , headers = headers )
121+
122+ # Validar a resposta
123+ assert response .status_code == status .HTTP_401_UNAUTHORIZED
124+ assert "detail" in response .json ()
125+ assert response .json ()["detail" ] == "Could not validate credentials"
0 commit comments