Skip to content

Commit 1aa6221

Browse files
test(auth_route): Tests for authentication route
Tests dedicated to authentication routes added.
1 parent 1d97913 commit 1aa6221

File tree

6 files changed

+61
-61
lines changed

6 files changed

+61
-61
lines changed

requirements.txt

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
annotated-types==0.7.0
22
anyio==4.10.0
3+
bcrypt==4.0.1
34
certifi==2025.8.3
45
cffi==2.0.0
56
click==8.1.8
@@ -17,16 +18,20 @@ httpcore==1.0.9
1718
httptools==0.6.4
1819
httpx==0.28.1
1920
idna==3.10
21+
iniconfig==2.1.0
2022
Jinja2==3.1.6
2123
markdown-it-py==3.0.0
2224
MarkupSafe==3.0.2
2325
mdurl==0.1.2
26+
packaging==25.0
2427
passlib==1.7.4
28+
pluggy==1.6.0
2529
pycparser==2.23
2630
pydantic==2.11.9
2731
pydantic_core==2.33.2
2832
Pygments==2.19.2
2933
PyMySQL==1.1.2
34+
pytest==8.4.2
3035
python-dotenv==1.1.1
3136
python-multipart==0.0.20
3237
PyYAML==6.0.2
@@ -38,6 +43,7 @@ shellingham==1.5.4
3843
sniffio==1.3.1
3944
SQLAlchemy==2.0.43
4045
starlette==0.48.0
46+
tomli==2.2.1
4147
typer==0.19.1
4248
typing-inspection==0.4.1
4349
typing_extensions==4.15.0

src/modules/database_conection.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
1+
import os
12
from sqlalchemy import create_engine
2-
from sqlalchemy.ext.declarative import declarative_base
33
from sqlalchemy.orm import sessionmaker
4-
import os
4+
from sqlalchemy.orm import declarative_base
55

66
"""
77
Database connection module using SQLAlchemy.

src/schemas/users/CRUD/create.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
from src.schemas.users.users_schema import UserCreate
44
from passlib.context import CryptContext
55

6-
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
6+
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto", bcrypt__ident="2b")
77

88
def create_user(db: Session, user_data: UserCreate):
99
"""

src/schemas/users/users_schema.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1-
from pydantic import BaseModel, EmailStr, constr
2-
from datetime import date, datetime
31
from typing import Optional
2+
from datetime import date, datetime
3+
from pydantic import BaseModel, EmailStr, constr, ConfigDict
44

55

66
class UserCreate(BaseModel):
@@ -58,5 +58,4 @@ class UserResponse(BaseModel):
5858
created_at: datetime
5959
updated_at: datetime
6060

61-
class Config:
62-
from_attributes = True
61+
model_config = ConfigDict(from_attributes=True)

src/tests/routes/test_auth.py

Lines changed: 13 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -1,47 +1,6 @@
11
import pytest
2-
from fastapi.testclient import TestClient
3-
from sqlalchemy import create_engine, text
4-
from sqlalchemy.orm import sessionmaker
5-
from sqlalchemy.pool import StaticPool
6-
7-
from src.main import app
8-
from src.utils.utils import get_db
9-
from src.models.user_model import Base, User
10-
11-
# =========================================
12-
# CONFIGURAÇÃO DE BANCO PARA TESTES
13-
# =========================================
14-
# 🔹 Opção 1 → Usar SQLite em memória (mais rápido, isolado)
15-
SQLALCHEMY_DATABASE_URL = "sqlite:///:memory:"
16-
17-
# 🔹 Opção 2 → Usar o mesmo MySQL do Docker (testes de integração reais)
18-
# SQLALCHEMY_DATABASE_URL = "mysql+pymysql://app:app_pass@localhost:3307/todolist"
19-
20-
engine = create_engine(
21-
SQLALCHEMY_DATABASE_URL,
22-
connect_args={"check_same_thread": False} if "sqlite" in SQLALCHEMY_DATABASE_URL else {},
23-
poolclass=StaticPool if "sqlite" in SQLALCHEMY_DATABASE_URL else None,
24-
)
25-
26-
TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
27-
28-
# Cria as tabelas no banco de teste
29-
Base.metadata.create_all(bind=engine)
30-
31-
32-
# =========================================
33-
# FIXTURES E DEPENDÊNCIAS
34-
# =========================================
35-
def override_get_db():
36-
db = TestingSessionLocal()
37-
try:
38-
yield db
39-
finally:
40-
db.close()
41-
42-
43-
app.dependency_overrides[get_db] = override_get_db
44-
client = TestClient(app)
2+
from sqlalchemy import text
3+
from src.tests.utils.test_utils import client, engine
454

465

476
@pytest.fixture(autouse=True)
@@ -53,53 +12,53 @@ def clean_db():
5312
connection.commit()
5413

5514

56-
# =========================================
57-
# TESTES DA ROTA /auth/register
58-
# =========================================
15+
# Test for user registration
5916
def test_register_user_success():
6017
payload = {
6118
"name": "Juju Fonseca",
6219
"email": "juju@example.com",
6320
"password": "123456",
6421
"phone": "999999999",
65-
"birth_date": "2000-01-01"
22+
"birth_date": "2000-01-01",
6623
}
6724

6825
response = client.post("/auth/register", json=payload)
6926

70-
assert response.status_code == 200 # ajuste se rota retorna 201
27+
assert response.status_code == 200
7128
data = response.json()
7229
assert data["email"] == payload["email"]
7330
assert "id" in data
7431
assert data["name"] == payload["name"]
7532

7633

34+
# Test for user registration with existing email
7735
def test_register_user_already_exists():
7836
payload = {
7937
"name": "Juju Fonseca",
8038
"email": "juju@example.com",
8139
"password": "123456",
8240
"phone": "999999999",
83-
"birth_date": "2000-01-01"
41+
"birth_date": "2000-01-01",
8442
}
8543

86-
# Primeiro cadastro
44+
# register the user first
8745
client.post("/auth/register", json=payload)
88-
# Tentativa de duplicar
46+
# try to register again with the same email
8947
response = client.post("/auth/register", json=payload)
9048

9149
assert response.status_code == 400
9250
assert response.json()["detail"] == "User already exists."
9351

9452

53+
# Test for user registration with invalid data
9554
def test_register_user_invalid_data():
9655
payload = {
9756
"name": "Juju Fonseca",
98-
# faltando email
57+
# witout email
9958
"password": "123456",
10059
"phone": "999999999",
101-
"birth_date": "2000-01-01"
60+
"birth_date": "2000-01-01",
10261
}
10362

10463
response = client.post("/auth/register", json=payload)
105-
assert response.status_code == 422 # erro de validação
64+
assert response.status_code == 422 # validation error

src/tests/utils/test_utils.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
from src.main import app
2+
from src.utils.utils import get_db
3+
from sqlalchemy import create_engine
4+
from src.models.user_model import Base
5+
from sqlalchemy.pool import StaticPool
6+
from sqlalchemy.orm import sessionmaker
7+
from fastapi.testclient import TestClient
8+
9+
10+
SQLALCHEMY_DATABASE_URL = "mysql+pymysql://app:app_pass@localhost:3307/todolist"
11+
12+
engine = create_engine(
13+
SQLALCHEMY_DATABASE_URL,
14+
connect_args={"check_same_thread": False}
15+
if "sqlite" in SQLALCHEMY_DATABASE_URL
16+
else {},
17+
poolclass=StaticPool if "sqlite" in SQLALCHEMY_DATABASE_URL else None,
18+
)
19+
20+
TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
21+
22+
# Create the database tables in the test database
23+
Base.metadata.create_all(bind=engine)
24+
25+
26+
# Dependency override to use the test database
27+
def override_get_db():
28+
db = TestingSessionLocal()
29+
try:
30+
yield db
31+
finally:
32+
db.close()
33+
34+
35+
app.dependency_overrides[get_db] = override_get_db
36+
client = TestClient(app)

0 commit comments

Comments
 (0)