From 7bf619451b6b2499281c6441f30d8eff766e0e1d Mon Sep 17 00:00:00 2001 From: Wagner Lacerda Date: Fri, 9 Oct 2026 10:36:43 -0300 Subject: [PATCH 01/22] ci: add lint and test workflow --- .github/workflows/ci.yml | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 .github/workflows/ci.yml diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..c91f494 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,23 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + branches: [main] + +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + cache: pip + - name: Install dependencies + run: pip install -r requirements-dev.txt + - name: Lint + run: ruff check . && ruff format --check . + - name: Run tests + run: pytest -v From 55792103e3731e46d1b98b2d0e15bfa8a944a801 Mon Sep 17 00:00:00 2001 From: Wagner Lacerda Date: Fri, 9 Oct 2026 10:36:47 -0300 Subject: [PATCH 02/22] build: add ruff configuration --- pyproject.toml | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 pyproject.toml diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..e3e67d8 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,6 @@ +[tool.ruff] +line-length = 100 +exclude = [".venv"] + +[tool.ruff.lint] +select = ["E", "F", "I", "UP", "RUF"] From 0f7a206d4641e1434bc145dd3c601ee3e97ec3f5 Mon Sep 17 00:00:00 2001 From: Wagner Lacerda Date: Fri, 9 Oct 2026 10:36:54 -0300 Subject: [PATCH 03/22] test: add pytest configuration --- pytest.ini | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 pytest.ini diff --git a/pytest.ini b/pytest.ini new file mode 100644 index 0000000..f607c7b --- /dev/null +++ b/pytest.ini @@ -0,0 +1,3 @@ +[pytest] +python_files = test_*.py +testpaths = tests From 22bc1fb625b07d2cfebeb02d145682b2ef5f1a16 Mon Sep 17 00:00:00 2001 From: Wagner Lacerda Date: Fri, 9 Oct 2026 15:58:09 -0300 Subject: [PATCH 04/22] build: add development requirements --- requirements-dev.txt | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 requirements-dev.txt diff --git a/requirements-dev.txt b/requirements-dev.txt new file mode 100644 index 0000000..5cede49 --- /dev/null +++ b/requirements-dev.txt @@ -0,0 +1,4 @@ +-r requirements.txt +pytest==9.1.1 +httpx==0.28.1 +ruff==0.16.9 From 038b9dd07b55fb4e9e2ef38823459c65126153fa Mon Sep 17 00:00:00 2001 From: Wagner Lacerda Date: Fri, 9 Oct 2026 15:58:13 -0300 Subject: [PATCH 05/22] build: add missing email-validator and pin bcrypt --- requirements.txt | 2 ++ 1 file changed, 2 insertions(+) diff --git a/requirements.txt b/requirements.txt index b601713..89af2e8 100644 --- a/requirements.txt +++ b/requirements.txt @@ -3,7 +3,9 @@ uvicorn[standard]==0.32.0 sqlalchemy==2.0.35 pydantic==2.9.2 pydantic-settings==2.5.2 +email-validator==2.2.0 python-jose[cryptography]==3.3.0 passlib[bcrypt]==1.7.4 +bcrypt==4.0.1 python-multipart==0.0.12 python-dotenv==1.0.1 From a09e0c000ab423e969e695aef0404cf6c36c9cfe Mon Sep 17 00:00:00 2001 From: Wagner Lacerda Date: Fri, 9 Oct 2026 15:58:19 -0300 Subject: [PATCH 06/22] refactor: translate main module to English --- app/main.py | 25 +++++++------------------ 1 file changed, 7 insertions(+), 18 deletions(-) diff --git a/app/main.py b/app/main.py index cebdea3..98cd388 100644 --- a/app/main.py +++ b/app/main.py @@ -1,21 +1,14 @@ -""" -FastAPI REST Boilerplate - Ponto de entrada da aplicação. - -Este módulo configura a aplicação FastAPI, CORS, e registra as rotas. -""" from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware -from app.database import engine, Base -from app.routers import users, items, auth +from app.database import Base, engine +from app.routers import auth, items, users -# Criar tabelas no banco de dados Base.metadata.create_all(bind=engine) -# Inicializar aplicação app = FastAPI( title="FastAPI REST Boilerplate", - description="Template profissional de API REST com autenticação JWT", + description="REST API template with JWT authentication and CRUD", version="1.0.0", contact={ "name": "Wagner Lacerda", @@ -23,7 +16,6 @@ }, ) -# Configurar CORS (ajuste allow_origins em produção) app.add_middleware( CORSMiddleware, allow_origins=["*"], @@ -32,17 +24,15 @@ allow_headers=["*"], ) -# Registrar rotas -app.include_router(auth.router, prefix="/auth", tags=["Autenticação"]) -app.include_router(users.router, prefix="/users", tags=["Usuários"]) -app.include_router(items.router, prefix="/items", tags=["Itens"]) +app.include_router(auth.router, prefix="/auth", tags=["Auth"]) +app.include_router(users.router, prefix="/users", tags=["Users"]) +app.include_router(items.router, prefix="/items", tags=["Items"]) @app.get("/", tags=["Root"]) def read_root(): - """Endpoint raiz - health check.""" return { - "message": "FastAPI REST Boilerplate está rodando!", + "message": "FastAPI REST Boilerplate is running", "docs": "/docs", "version": "1.0.0", } @@ -50,5 +40,4 @@ def read_root(): @app.get("/health", tags=["Root"]) def health_check(): - """Endpoint de health check para monitoramento.""" return {"status": "healthy"} From 20323b67dc5201c95dc8234dd66ff88e2707b21c Mon Sep 17 00:00:00 2001 From: Wagner Lacerda Date: Fri, 9 Oct 2026 15:58:32 -0300 Subject: [PATCH 07/22] refactor: translate auth module to English --- app/auth.py | 36 +++++++++++------------------------- 1 file changed, 11 insertions(+), 25 deletions(-) diff --git a/app/auth.py b/app/auth.py index 011a913..278001a 100644 --- a/app/auth.py +++ b/app/auth.py @@ -1,16 +1,12 @@ -""" -Módulo de autenticação - gerencia hash de senhas e tokens JWT. -""" import os -from datetime import datetime, timedelta, timezone -from typing import Optional +from datetime import UTC, datetime, timedelta -from jose import JWTError, jwt -from passlib.context import CryptContext +from dotenv import load_dotenv from fastapi import Depends, HTTPException, status from fastapi.security import OAuth2PasswordBearer +from jose import JWTError, jwt +from passlib.context import CryptContext from sqlalchemy.orm import Session -from dotenv import load_dotenv from app.database import get_db from app.models import User @@ -18,34 +14,25 @@ load_dotenv() -# Configurações de segurança (em produção, use variáveis de ambiente) -SECRET_KEY = os.getenv("SECRET_KEY", "mude_esta_chave_em_producao") +SECRET_KEY = os.getenv("SECRET_KEY", "change-this-key-in-production") ALGORITHM = os.getenv("ALGORITHM", "HS256") ACCESS_TOKEN_EXPIRE_MINUTES = int(os.getenv("ACCESS_TOKEN_EXPIRE_MINUTES", "30")) -# Context para hash de senhas pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") - -# OAuth2 scheme oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/auth/login") def verify_password(plain_password: str, hashed_password: str) -> bool: - """Verifica se a senha em texto plano bate com o hash.""" return pwd_context.verify(plain_password, hashed_password) def get_password_hash(password: str) -> str: - """Gera hash bcrypt da senha.""" return pwd_context.hash(password) -def create_access_token(data: dict, expires_delta: Optional[timedelta] = None) -> str: - """Cria token JWT com os dados fornecidos e expiração.""" +def create_access_token(data: dict, expires_delta: timedelta | None = None) -> str: to_encode = data.copy() - expire = datetime.now(timezone.utc) + ( - expires_delta or timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES) - ) + expire = datetime.now(UTC) + (expires_delta or timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)) to_encode.update({"exp": expire}) return jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) @@ -54,21 +41,20 @@ def get_current_user( token: str = Depends(oauth2_scheme), db: Session = Depends(get_db), ) -> User: - """Extrai e valida o usuário a partir do token JWT.""" credentials_exception = HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, - detail="Credenciais inválidas", + detail="Invalid credentials", headers={"WWW-Authenticate": "Bearer"}, ) try: payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) - email: str = payload.get("sub") + email: str | None = payload.get("sub") if email is None: raise credentials_exception token_data = TokenData(email=email) - except JWTError: - raise credentials_exception + except JWTError as exc: + raise credentials_exception from exc user = db.query(User).filter(User.email == token_data.email).first() if user is None: From 5dc52069ee7f5481a813b9f821347458c772a628 Mon Sep 17 00:00:00 2001 From: Wagner Lacerda Date: Fri, 9 Oct 2026 15:58:38 -0300 Subject: [PATCH 08/22] refactor: translate database module to English --- app/database.py | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) diff --git a/app/database.py b/app/database.py index 61720df..ecf1c14 100644 --- a/app/database.py +++ b/app/database.py @@ -1,18 +1,13 @@ -""" -Configuração da conexão com o banco de dados via SQLAlchemy. -""" import os -from sqlalchemy import create_engine -from sqlalchemy.ext.declarative import declarative_base -from sqlalchemy.orm import sessionmaker + from dotenv import load_dotenv +from sqlalchemy import create_engine +from sqlalchemy.orm import declarative_base, sessionmaker load_dotenv() -# URL do banco (padrão: SQLite local) DATABASE_URL = os.getenv("DATABASE_URL", "sqlite:///./app.db") -# Para SQLite precisamos do connect_args, para outros bancos não connect_args = {"check_same_thread": False} if DATABASE_URL.startswith("sqlite") else {} engine = create_engine(DATABASE_URL, connect_args=connect_args) @@ -21,7 +16,6 @@ def get_db(): - """Dependency para obter sessão do banco nas rotas.""" db = SessionLocal() try: yield db From 0cce8d06e5e47288c283b5f1c8c2b694c725e6a6 Mon Sep 17 00:00:00 2001 From: Wagner Lacerda Date: Fri, 9 Oct 2026 15:58:45 -0300 Subject: [PATCH 09/22] refactor: translate models module to English --- app/models.py | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/app/models.py b/app/models.py index 2d7b612..6c74e42 100644 --- a/app/models.py +++ b/app/models.py @@ -1,7 +1,4 @@ -""" -Modelos SQLAlchemy - Representação das tabelas do banco de dados. -""" -from sqlalchemy import Column, Integer, String, Boolean, DateTime, ForeignKey, Text +from sqlalchemy import Boolean, Column, DateTime, ForeignKey, Integer, String, Text from sqlalchemy.orm import relationship from sqlalchemy.sql import func @@ -9,7 +6,6 @@ class User(Base): - """Modelo de usuário do sistema.""" __tablename__ = "users" id = Column(Integer, primary_key=True, index=True) @@ -18,12 +14,10 @@ class User(Base): is_active = Column(Boolean, default=True) created_at = Column(DateTime(timezone=True), server_default=func.now()) - # Relacionamento com itens items = relationship("Item", back_populates="owner", cascade="all, delete-orphan") class Item(Base): - """Modelo de item - exemplo de recurso CRUD.""" __tablename__ = "items" id = Column(Integer, primary_key=True, index=True) @@ -33,5 +27,4 @@ class Item(Base): created_at = Column(DateTime(timezone=True), server_default=func.now()) updated_at = Column(DateTime(timezone=True), onupdate=func.now()) - # Relacionamento com usuário owner = relationship("User", back_populates="items") From 44b2563e52edf5cb274346d7d2abd95fcd5b4c2b Mon Sep 17 00:00:00 2001 From: Wagner Lacerda Date: Fri, 9 Oct 2026 15:58:51 -0300 Subject: [PATCH 10/22] refactor: translate schemas module to English --- app/schemas.py | 16 +++++----------- 1 file changed, 5 insertions(+), 11 deletions(-) diff --git a/app/schemas.py b/app/schemas.py index 9e02418..ba0bf69 100644 --- a/app/schemas.py +++ b/app/schemas.py @@ -1,12 +1,8 @@ -""" -Schemas Pydantic - Validação de dados de entrada e saída da API. -""" from datetime import datetime -from typing import Optional -from pydantic import BaseModel, EmailStr, ConfigDict + +from pydantic import BaseModel, ConfigDict, EmailStr -# ==================== USER SCHEMAS ==================== class UserBase(BaseModel): email: EmailStr @@ -23,20 +19,18 @@ class UserResponse(UserBase): model_config = ConfigDict(from_attributes=True) -# ==================== TOKEN SCHEMAS ==================== class Token(BaseModel): access_token: str token_type: str = "bearer" class TokenData(BaseModel): - email: Optional[str] = None + email: str | None = None -# ==================== ITEM SCHEMAS ==================== class ItemBase(BaseModel): title: str - description: Optional[str] = None + description: str | None = None class ItemCreate(ItemBase): @@ -51,6 +45,6 @@ class ItemResponse(ItemBase): id: int owner_id: int created_at: datetime - updated_at: Optional[datetime] = None + updated_at: datetime | None = None model_config = ConfigDict(from_attributes=True) From c607c4ea19c32e34a7d697c8779d5d4133a053ea Mon Sep 17 00:00:00 2001 From: Wagner Lacerda Date: Fri, 9 Oct 2026 15:58:59 -0300 Subject: [PATCH 11/22] refactor: translate auth router to English --- app/routers/auth.py | 30 ++++-------------------------- 1 file changed, 4 insertions(+), 26 deletions(-) diff --git a/app/routers/auth.py b/app/routers/auth.py index 454c6bd..4e21461 100644 --- a/app/routers/auth.py +++ b/app/routers/auth.py @@ -1,39 +1,24 @@ -""" -Router de autenticação - endpoints de registro e login. -""" from fastapi import APIRouter, Depends, HTTPException, status from fastapi.security import OAuth2PasswordRequestForm from sqlalchemy.orm import Session +from app.auth import create_access_token, get_password_hash, verify_password from app.database import get_db from app.models import User -from app.schemas import UserCreate, UserResponse, Token -from app.auth import ( - get_password_hash, - verify_password, - create_access_token, -) +from app.schemas import Token, UserCreate, UserResponse router = APIRouter() @router.post("/register", response_model=UserResponse, status_code=status.HTTP_201_CREATED) def register(user: UserCreate, db: Session = Depends(get_db)): - """ - Registra um novo usuário no sistema. - - - **email**: e-mail único do usuário - - **password**: senha (será armazenada com hash bcrypt) - """ - # Verificar se usuário já existe existing_user = db.query(User).filter(User.email == user.email).first() if existing_user: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, - detail="E-mail já cadastrado", + detail="Email already registered", ) - # Criar novo usuário com senha hasheada new_user = User( email=user.email, hashed_password=get_password_hash(user.password), @@ -49,18 +34,11 @@ def login( form_data: OAuth2PasswordRequestForm = Depends(), db: Session = Depends(get_db), ): - """ - Autentica usuário e retorna token JWT. - - Envie form-data com os campos: - - **username**: e-mail do usuário - - **password**: senha - """ user = db.query(User).filter(User.email == form_data.username).first() if not user or not verify_password(form_data.password, user.hashed_password): raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, - detail="E-mail ou senha incorretos", + detail="Incorrect email or password", headers={"WWW-Authenticate": "Bearer"}, ) From 03e35517d6511ffcb6a1b1beaf682d96eb9423b1 Mon Sep 17 00:00:00 2001 From: Wagner Lacerda Date: Fri, 9 Oct 2026 15:59:15 -0300 Subject: [PATCH 12/22] refactor: translate items router and extract ownership lookup --- app/routers/items.py | 71 +++++++++++--------------------------------- 1 file changed, 17 insertions(+), 54 deletions(-) diff --git a/app/routers/items.py b/app/routers/items.py index ca17622..e9d18ec 100644 --- a/app/routers/items.py +++ b/app/routers/items.py @@ -1,33 +1,32 @@ -""" -Router de itens - CRUD completo como exemplo de recurso protegido. -""" -from typing import List from fastapi import APIRouter, Depends, HTTPException, status from sqlalchemy.orm import Session +from app.auth import get_current_user from app.database import get_db from app.models import Item, User -from app.schemas import ItemCreate, ItemUpdate, ItemResponse -from app.auth import get_current_user +from app.schemas import ItemCreate, ItemResponse, ItemUpdate router = APIRouter() -@router.get("/", response_model=List[ItemResponse]) +def get_owned_item(db: Session, item_id: int, user: User) -> Item: + item = db.query(Item).filter(Item.id == item_id, Item.owner_id == user.id).first() + if not item: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="Item not found", + ) + return item + + +@router.get("/", response_model=list[ItemResponse]) def list_items( skip: int = 0, limit: int = 100, db: Session = Depends(get_db), current_user: User = Depends(get_current_user), ): - """Lista todos os itens do usuário autenticado (com paginação).""" - return ( - db.query(Item) - .filter(Item.owner_id == current_user.id) - .offset(skip) - .limit(limit) - .all() - ) + return db.query(Item).filter(Item.owner_id == current_user.id).offset(skip).limit(limit).all() @router.post("/", response_model=ItemResponse, status_code=status.HTTP_201_CREATED) @@ -36,7 +35,6 @@ def create_item( db: Session = Depends(get_db), current_user: User = Depends(get_current_user), ): - """Cria um novo item para o usuário autenticado.""" new_item = Item(**item.model_dump(), owner_id=current_user.id) db.add(new_item) db.commit() @@ -50,18 +48,7 @@ def get_item( db: Session = Depends(get_db), current_user: User = Depends(get_current_user), ): - """Obtém um item específico por ID.""" - item = ( - db.query(Item) - .filter(Item.id == item_id, Item.owner_id == current_user.id) - .first() - ) - if not item: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail="Item não encontrado", - ) - return item + return get_owned_item(db, item_id, current_user) @router.put("/{item_id}", response_model=ItemResponse) @@ -71,21 +58,9 @@ def update_item( db: Session = Depends(get_db), current_user: User = Depends(get_current_user), ): - """Atualiza um item existente.""" - item = ( - db.query(Item) - .filter(Item.id == item_id, Item.owner_id == current_user.id) - .first() - ) - if not item: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail="Item não encontrado", - ) - + item = get_owned_item(db, item_id, current_user) for key, value in item_update.model_dump(exclude_unset=True).items(): setattr(item, key, value) - db.commit() db.refresh(item) return item @@ -97,18 +72,6 @@ def delete_item( db: Session = Depends(get_db), current_user: User = Depends(get_current_user), ): - """Remove um item do sistema.""" - item = ( - db.query(Item) - .filter(Item.id == item_id, Item.owner_id == current_user.id) - .first() - ) - if not item: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail="Item não encontrado", - ) - + item = get_owned_item(db, item_id, current_user) db.delete(item) db.commit() - return None From 2c596cd0e7b44dababc6151a82f047c867f75889 Mon Sep 17 00:00:00 2001 From: Wagner Lacerda Date: Fri, 9 Oct 2026 15:59:19 -0300 Subject: [PATCH 13/22] refactor: translate users router to English --- app/routers/users.py | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/app/routers/users.py b/app/routers/users.py index ed7fa39..3c1c870 100644 --- a/app/routers/users.py +++ b/app/routers/users.py @@ -1,16 +1,12 @@ -""" -Router de usuários - endpoints relacionados ao usuário autenticado. -""" from fastapi import APIRouter, Depends +from app.auth import get_current_user from app.models import User from app.schemas import UserResponse -from app.auth import get_current_user router = APIRouter() @router.get("/me", response_model=UserResponse) def read_current_user(current_user: User = Depends(get_current_user)): - """Retorna dados do usuário autenticado.""" return current_user From a874ebb54a17772bd162ab5e7340c8a50b827de9 Mon Sep 17 00:00:00 2001 From: Wagner Lacerda Date: Fri, 9 Oct 2026 15:59:35 -0300 Subject: [PATCH 14/22] test: add tests package --- tests/__init__.py | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 tests/__init__.py diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..e69de29 From a1ddd1a74b6650ff7af98526254a9723e3863bf3 Mon Sep 17 00:00:00 2001 From: Wagner Lacerda Date: Fri, 9 Oct 2026 15:59:42 -0300 Subject: [PATCH 15/22] test: add shared fixtures with isolated in-memory database --- tests/conftest.py | 53 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 tests/conftest.py diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..86aed38 --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,53 @@ +import pytest +from fastapi.testclient import TestClient +from sqlalchemy import create_engine +from sqlalchemy.orm import sessionmaker +from sqlalchemy.pool import StaticPool + +from app.database import Base, get_db +from app.main import app + + +@pytest.fixture +def client(): + engine = create_engine( + "sqlite://", + connect_args={"check_same_thread": False}, + poolclass=StaticPool, + ) + Base.metadata.create_all(bind=engine) + testing_session = sessionmaker(autocommit=False, autoflush=False, bind=engine) + + def override_get_db(): + db = testing_session() + try: + yield db + finally: + db.close() + + app.dependency_overrides[get_db] = override_get_db + with TestClient(app) as test_client: + yield test_client + app.dependency_overrides.clear() + Base.metadata.drop_all(bind=engine) + engine.dispose() + + +@pytest.fixture +def credentials(): + return {"email": "user@example.com", "password": "s3cret-pass"} + + +@pytest.fixture +def make_auth_headers(client): + def _make(email="user@example.com", password="s3cret-pass"): + client.post("/auth/register", json={"email": email, "password": password}) + response = client.post("/auth/login", data={"username": email, "password": password}) + return {"Authorization": f"Bearer {response.json()['access_token']}"} + + return _make + + +@pytest.fixture +def auth_headers(make_auth_headers): + return make_auth_headers() From 79cbe0f7c8da70f6dffbe2c86f13f55d14903455 Mon Sep 17 00:00:00 2001 From: Wagner Lacerda Date: Fri, 9 Oct 2026 15:59:49 -0300 Subject: [PATCH 16/22] test: cover password hashing, tokens, registration and login --- tests/test_auth.py | 82 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 tests/test_auth.py diff --git a/tests/test_auth.py b/tests/test_auth.py new file mode 100644 index 0000000..87f94c3 --- /dev/null +++ b/tests/test_auth.py @@ -0,0 +1,82 @@ +from datetime import timedelta + +from jose import jwt + +from app.auth import ALGORITHM, SECRET_KEY, create_access_token, get_password_hash, verify_password + + +def test_password_hash_roundtrip(): + hashed = get_password_hash("secret") + + assert hashed != "secret" + assert verify_password("secret", hashed) + assert not verify_password("wrong", hashed) + + +def test_access_token_contains_subject_and_expiry(): + token = create_access_token({"sub": "user@example.com"}, timedelta(minutes=5)) + + payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) + + assert payload["sub"] == "user@example.com" + assert "exp" in payload + + +def test_register_creates_user(client, credentials): + response = client.post("/auth/register", json=credentials) + + assert response.status_code == 201 + body = response.json() + assert body["email"] == credentials["email"] + assert body["is_active"] is True + assert "password" not in body + assert "hashed_password" not in body + + +def test_register_rejects_duplicate_email(client, credentials): + client.post("/auth/register", json=credentials) + + response = client.post("/auth/register", json=credentials) + + assert response.status_code == 400 + assert response.json()["detail"] == "Email already registered" + + +def test_register_rejects_invalid_email(client): + response = client.post("/auth/register", json={"email": "not-an-email", "password": "x"}) + + assert response.status_code == 422 + + +def test_login_returns_bearer_token(client, credentials): + client.post("/auth/register", json=credentials) + + response = client.post( + "/auth/login", + data={"username": credentials["email"], "password": credentials["password"]}, + ) + + assert response.status_code == 200 + body = response.json() + assert body["token_type"] == "bearer" + assert body["access_token"] + + +def test_login_rejects_wrong_password(client, credentials): + client.post("/auth/register", json=credentials) + + response = client.post( + "/auth/login", + data={"username": credentials["email"], "password": "wrong-pass"}, + ) + + assert response.status_code == 401 + + +def test_login_rejects_unknown_user(client): + response = client.post( + "/auth/login", + data={"username": "ghost@example.com", "password": "whatever"}, + ) + + assert response.status_code == 401 From e2dabf45eb5de77015e86708c8a5e2bf21349e03 Mon Sep 17 00:00:00 2001 From: Wagner Lacerda Date: Fri, 9 Oct 2026 15:59:59 -0300 Subject: [PATCH 17/22] test: cover items CRUD, pagination and ownership isolation --- tests/test_items.py | 101 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 101 insertions(+) create mode 100644 tests/test_items.py diff --git a/tests/test_items.py b/tests/test_items.py new file mode 100644 index 0000000..96b8e2d --- /dev/null +++ b/tests/test_items.py @@ -0,0 +1,101 @@ +def create_item(client, headers, title="Item", description=None): + return client.post( + "/items/", + json={"title": title, "description": description}, + headers=headers, + ) + + +def test_items_require_authentication(client): + assert client.get("/items/").status_code == 401 + assert client.post("/items/", json={"title": "x"}).status_code == 401 + + +def test_create_item(client, auth_headers): + response = create_item(client, auth_headers, "Book", "Hardcover") + + assert response.status_code == 201 + body = response.json() + assert body["title"] == "Book" + assert body["description"] == "Hardcover" + assert body["owner_id"] == 1 + + +def test_create_item_requires_title(client, auth_headers): + response = client.post("/items/", json={"description": "no title"}, headers=auth_headers) + + assert response.status_code == 422 + + +def test_list_items_supports_pagination(client, auth_headers): + for index in range(3): + create_item(client, auth_headers, f"Item {index}") + + response = client.get("/items/", params={"skip": 1, "limit": 1}, headers=auth_headers) + + assert response.status_code == 200 + assert [item["title"] for item in response.json()] == ["Item 1"] + + +def test_list_items_only_returns_own_items(client, make_auth_headers): + first = make_auth_headers("first@example.com") + second = make_auth_headers("second@example.com") + create_item(client, first, "Private") + + response = client.get("/items/", headers=second) + + assert response.json() == [] + + +def test_get_item(client, auth_headers): + item_id = create_item(client, auth_headers, "Lookup").json()["id"] + + response = client.get(f"/items/{item_id}", headers=auth_headers) + + assert response.status_code == 200 + assert response.json()["title"] == "Lookup" + + +def test_get_missing_item_returns_404(client, auth_headers): + response = client.get("/items/999", headers=auth_headers) + + assert response.status_code == 404 + assert response.json()["detail"] == "Item not found" + + +def test_cannot_access_item_owned_by_another_user(client, make_auth_headers): + owner = make_auth_headers("owner@example.com") + intruder = make_auth_headers("intruder@example.com") + item_id = create_item(client, owner).json()["id"] + + assert client.get(f"/items/{item_id}", headers=intruder).status_code == 404 + assert client.delete(f"/items/{item_id}", headers=intruder).status_code == 404 + + +def test_update_item(client, auth_headers): + item_id = create_item(client, auth_headers, "Old").json()["id"] + + response = client.put( + f"/items/{item_id}", + json={"title": "New", "description": "Updated"}, + headers=auth_headers, + ) + + assert response.status_code == 200 + assert response.json()["title"] == "New" + assert response.json()["description"] == "Updated" + + +def test_update_missing_item_returns_404(client, auth_headers): + response = client.put("/items/999", json={"title": "New"}, headers=auth_headers) + + assert response.status_code == 404 + + +def test_delete_item(client, auth_headers): + item_id = create_item(client, auth_headers).json()["id"] + + response = client.delete(f"/items/{item_id}", headers=auth_headers) + + assert response.status_code == 204 + assert client.get(f"/items/{item_id}", headers=auth_headers).status_code == 404 From bac81e66476c29c23bf3ad5415149e14b894bee9 Mon Sep 17 00:00:00 2001 From: Wagner Lacerda Date: Fri, 9 Oct 2026 16:00:05 -0300 Subject: [PATCH 18/22] test: cover health, root and current user endpoints --- tests/test_users_and_health.py | 48 ++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 tests/test_users_and_health.py diff --git a/tests/test_users_and_health.py b/tests/test_users_and_health.py new file mode 100644 index 0000000..a972cff --- /dev/null +++ b/tests/test_users_and_health.py @@ -0,0 +1,48 @@ +from app.auth import create_access_token + + +def test_root_returns_service_info(client): + response = client.get("/") + + assert response.status_code == 200 + assert response.json()["docs"] == "/docs" + + +def test_health_check(client): + response = client.get("/health") + + assert response.status_code == 200 + assert response.json() == {"status": "healthy"} + + +def test_read_current_user(client, auth_headers): + response = client.get("/users/me", headers=auth_headers) + + assert response.status_code == 200 + assert response.json()["email"] == "user@example.com" + + +def test_current_user_requires_token(client): + assert client.get("/users/me").status_code == 401 + + +def test_current_user_rejects_malformed_token(client): + response = client.get("/users/me", headers={"Authorization": "Bearer invalid"}) + + assert response.status_code == 401 + + +def test_current_user_rejects_token_without_subject(client): + token = create_access_token({}) + + response = client.get("/users/me", headers={"Authorization": f"Bearer {token}"}) + + assert response.status_code == 401 + + +def test_current_user_rejects_token_for_unknown_user(client): + token = create_access_token({"sub": "ghost@example.com"}) + + response = client.get("/users/me", headers={"Authorization": f"Bearer {token}"}) + + assert response.status_code == 401 From 9c7492a3458da1eeeb57da286dc9aa63ce33dafa Mon Sep 17 00:00:00 2001 From: Wagner Lacerda Date: Fri, 9 Oct 2026 16:00:16 -0300 Subject: [PATCH 19/22] docs: add environment variables example --- .env.example | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 .env.example diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..2c5a4ca --- /dev/null +++ b/.env.example @@ -0,0 +1,4 @@ +SECRET_KEY=change-this-key-in-production +ALGORITHM=HS256 +ACCESS_TOKEN_EXPIRE_MINUTES=30 +DATABASE_URL=sqlite:///./app.db From 5a804f16c8235ba477321810a65600a6b88a89a2 Mon Sep 17 00:00:00 2001 From: Wagner Lacerda Date: Fri, 9 Oct 2026 16:00:21 -0300 Subject: [PATCH 20/22] docs: add CI badge, test instructions and accurate structure --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 78673d2..d204053 100644 --- a/README.md +++ b/README.md @@ -4,6 +4,7 @@ **A professional REST API template with JWT, full CRUD, and Swagger** +[![CI](https://github.com/LacerdaTraderCode/fastapi-rest-boilerplate/actions/workflows/ci.yml/badge.svg)](https://github.com/LacerdaTraderCode/fastapi-rest-boilerplate/actions/workflows/ci.yml) [![Python](https://img.shields.io/badge/Python-3.11%2B-blue?logo=python&logoColor=white)](https://www.python.org/) [![FastAPI](https://img.shields.io/badge/FastAPI-005571?logo=fastapi)](https://fastapi.tiangolo.com/) [![SQLAlchemy](https://img.shields.io/badge/SQLAlchemy-D71F00?logo=sqlalchemy&logoColor=white)](https://www.sqlalchemy.org/) From b40e612306adc3ce46d0fadaad8315df7a76ccad Mon Sep 17 00:00:00 2001 From: Wagner Lacerda Date: Fri, 9 Oct 2026 16:00:26 -0300 Subject: [PATCH 21/22] docs: document project structure and testing --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index d204053..4a8ccfd 100644 --- a/README.md +++ b/README.md @@ -54,9 +54,13 @@ fastapi-rest-boilerplate/ │ ├── schemas.py # Pydantic schemas │ ├── auth.py # JWT logic │ └── routers/ +│ ├── auth.py # Registration and login │ ├── users.py # User endpoints │ └── items.py # Item endpoints (CRUD) +├── tests/ +├── .github/workflows/ci.yml ├── requirements.txt +├── requirements-dev.txt ├── .env.example └── README.md ``` From f88fce4288989318ae5bebbf98cb029388ffb0b3 Mon Sep 17 00:00:00 2001 From: Wagner Lacerda Date: Fri, 9 Oct 2026 16:00:31 -0300 Subject: [PATCH 22/22] docs: add development section --- README.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/README.md b/README.md index 4a8ccfd..8ce3005 100644 --- a/README.md +++ b/README.md @@ -133,6 +133,18 @@ curl -X GET "http://localhost:8000/items/" \ --- +## 🧪 Development + +```bash +pip install -r requirements-dev.txt +ruff check . && ruff format --check . +pytest -v +``` + +Tests run against an isolated in-memory SQLite database. The same checks run on every push and pull request via GitHub Actions. + +--- + ## 🚀 Deploy Ready for deployment on: