1
1
import pytest
2
2
import pytest_asyncio
3
+ from fastapi import status
4
+ from httpx import AsyncClient
3
5
from services .database .models import Community
4
- from sqlmodel import select
5
6
from sqlmodel .ext .asyncio .session import AsyncSession
6
7
7
- from httpx import AsyncClient
8
- from fastapi import status
9
- from typing import Mapping
10
8
from app .services .auth import hash_password
11
9
12
10
password = "123Asd!@#"
13
11
14
- ## gerar usuario para autenticação
12
+
13
+ # gerar usuario para autenticação
15
14
@pytest_asyncio .fixture
16
15
async def community (session : AsyncSession ):
17
- hashed_password = hash_password (password )
18
- community = Community (
username = "username" ,
email = "[email protected] " ,
password = hashed_password )
16
+ hashed_password = hash_password (password )
17
+ community = Community (
18
+ username = "username" ,
email = "[email protected] " ,
password = hashed_password
19
+ )
19
20
session .add (community )
20
21
await session .commit ()
21
22
await session .refresh (community )
@@ -24,23 +25,20 @@ async def community(session: AsyncSession):
24
25
25
26
@pytest .mark .asyncio
26
27
async 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
29
30
):
30
31
"""
31
32
Testa o endpoint de login (/token) com credenciais válidas e inválidas.
32
33
"""
33
34
# 1. Teste de login com credenciais válidas
34
35
# 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
+
40
38
response = await async_client .post (
41
39
"/api/authentication/token" ,
42
40
data = form_data ,
43
- headers = {"Content-Type" : "application/x-www-form-urlencoded" }
41
+ headers = {"Content-Type" : "application/x-www-form-urlencoded" },
44
42
)
45
43
46
44
# Validar a resposta
@@ -51,17 +49,77 @@ async def test_authentication_token_endpoint(
51
49
52
50
# 2. Teste de login com credenciais inválidas
53
51
invalid_form_data = {
54
- "username" : "wrong_username" ,
55
- "password" : "wrong_password"
52
+ "username" : "wrong_username" ,
53
+ "password" : "wrong_password" ,
56
54
}
57
55
58
56
response_invalid = await async_client .post (
59
57
"/api/authentication/token" ,
60
58
data = invalid_form_data ,
61
- headers = {"Content-Type" : "application/x-www-form-urlencoded" }
59
+ headers = {"Content-Type" : "application/x-www-form-urlencoded" },
62
60
)
63
-
61
+
64
62
# Validar que o status é 401 Unauthorized
65
63
assert response_invalid .status_code == status .HTTP_401_UNAUTHORIZED
66
64
assert response_invalid .json ()["detail" ] == "Credenciais inválidas"
67
65
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