Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .env.test
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
APP_ENV=test
MONGO_URL=mongodb://localhost:27017
180 changes: 180 additions & 0 deletions .github/workflows/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,180 @@
# GitHub Actions Workflows

Este directorio contiene los workflows de CI/CD para el proyecto Portfolio Backend.

## 📋 Workflows Disponibles

### 1. **lint.yml** - Code Quality & Linting

Ejecuta verificaciones de calidad de código en cada push y pull request.

**Verifica:**
- ✅ **Black**: Formateo de código
- ✅ **Isort**: Ordenamiento de imports
- ✅ **Ruff**: Linting general
- ✅ **MyPy**: Type checking
- ✅ **Bandit**: Análisis de seguridad
- ✅ **Safety**: Vulnerabilidades en dependencias

**Se ejecuta en:**
- Python 3.12 y 3.13
- Branches: `main`, `develop`, `feature/**`

### 2. **tests.yml** - Tests

Ejecuta todos los tests del proyecto con cobertura.

**Incluye:**
- 🧪 Tests unitarios
- 🔗 Tests de integración
- 🌐 Tests end-to-end
- 📊 Reporte de cobertura (Codecov)
- 🗄️ MongoDB 8.0 service

**Se ejecuta en:**
- Python 3.12 y 3.13
- Branches: `main`, `develop`, `feature/**`

## 🔐 Configuración de Secretos

Para que los workflows funcionen correctamente, necesitas configurar los siguientes secretos en GitHub:

### Pasos para configurar secretos:

1. Ve a tu repositorio en GitHub
2. Click en `Settings` > `Secrets and variables` > `Actions`
3. Click en `New repository secret`
4. Agrega los siguientes secretos:

### Secretos Requeridos:

#### **CODECOV_TOKEN** (Opcional pero recomendado)
Para subir reportes de cobertura a Codecov.

```
1. Ve a https://codecov.io/
2. Conecta tu repositorio de GitHub
3. Copia el token de Codecov
4. Agrégalo como secreto en GitHub con el nombre: CODECOV_TOKEN
```

#### **MONGODB_URL** (Opcional)
URL de conexión a MongoDB para tests. Si no se configura, usa `mongodb://localhost:27017` por defecto.

```
Nombre: MONGODB_URL
Valor: mongodb://localhost:27017
```

#### **SECRET_KEY** (Futuro)
Clave secreta para la aplicación. Si no se configura, usa un valor por defecto para testing.

```
Nombre: SECRET_KEY
Valor: tu-clave-secreta-aqui
```

## 📊 Badges para README

Puedes agregar estos badges a tu README.md principal:

```markdown
![Code Quality](https://github.com/USUARIO/REPO/workflows/Code%20Quality%20&%20Linting/badge.svg)
![Tests](https://github.com/USUARIO/REPO/workflows/Tests/badge.svg)
[![codecov](https://codecov.io/gh/USUARIO/REPO/branch/main/graph/badge.svg)](https://codecov.io/gh/USUARIO/REPO)
```

Reemplaza `USUARIO` y `REPO` con tu información.

## 🚀 Ejecución Manual

Puedes ejecutar los workflows manualmente desde la pestaña "Actions" en GitHub:

1. Ve a la pestaña `Actions`
2. Selecciona el workflow que quieres ejecutar
3. Click en `Run workflow`
4. Selecciona la branch
5. Click en `Run workflow`

## 🔧 Configuración Local

Para ejecutar las mismas validaciones localmente:

### Code Quality:

```bash
# Formateo
black app/ tests/
isort app/ tests/

# Linting
ruff check app/ tests/

# Type checking
mypy app/

# Security
bandit -r app/
safety check
```

### Tests:

```bash
# Todos los tests
pytest tests/ -v

# Solo unitarios
pytest tests/unit/ -v

# Con cobertura
pytest tests/ --cov=app --cov-report=html

# En paralelo
pytest tests/ -n auto
```

## 📁 Estructura de Artifacts

Los workflows generan artifacts que puedes descargar:

### Lint Workflow:
- `bandit-report-py3.12.json`
- `bandit-report-py3.13.json`

### Tests Workflow:
- `test-results-unit-py3.12/`
- `test-results-integration-py3.12/`
- `test-results-e2e-py3.12/`
- (Similar para Python 3.13)

Cada artifact incluye:
- Archivo JUnit XML con resultados
- Reporte HTML de cobertura

## 🐛 Troubleshooting

### Error: "MongoDB not ready"

Si los tests fallan porque MongoDB no está listo:
- El workflow ya incluye un paso `Wait for MongoDB`
- Aumenta el tiempo de espera si es necesario

### Error: "Module not found"

Si falta alguna dependencia:
1. Verifica que esté en `requirements-dev.txt`
2. Haz commit y push de los cambios
3. El workflow instalará la nueva dependencia

### Error: "Coverage upload failed"

Si Codecov falla:
- Verifica que el token `CODECOV_TOKEN` esté configurado
- El workflow está configurado con `fail_ci_if_error: false`, así que no bloqueará el CI

## 📖 Documentación Adicional

- [GitHub Actions Documentation](https://docs.github.com/en/actions)
- [Codecov Documentation](https://docs.codecov.com/)
- [pytest Documentation](https://docs.pytest.org/)
59 changes: 59 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
name: CI Pipeline

on:
push:
branches: ["main", "develop"]
pull_request:
branches: ["main", "develop"]

jobs:
test:
runs-on: ubuntu-latest

services:
mongo:
image: mongo:6
ports:
- 27017:27017
options: >-
--health-cmd="mongosh --eval 'db.runCommand({ ping: 1 })'"
--health-interval=10s
--health-timeout=5s
--health-retries=5

steps:
- name: Checkout repository
uses: actions/checkout@v4

- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: "3.11"

- name: Install dependencies
run: |
pip install --upgrade pip
pip install -r requirements-dev.txt

- name: Copy test environment variables
run: |
cp .env.test .env

- name: Run linters (ruff)
run: ruff check .

- name: Run unit tests
run: pytest tests/unit -vv

- name: Run integration tests
env:
MONGO_URL: mongodb://localhost:27017
run: pytest tests/integration -vv

- name: Run E2E tests
env:
MONGO_URL: mongodb://localhost:27017
run: pytest tests/e2e -vv

- name: Build Docker image
run: docker build -t portfolio-backend .
85 changes: 85 additions & 0 deletions .github/workflows/lint.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
name: Code Quality & Linting

on:
push:
branches:
- main
- develop
- 'feature/**'
pull_request:
branches:
- main
- develop

jobs:
lint:
name: Code Quality Checks
runs-on: ubuntu-latest

strategy:
matrix:
python-version: ['3.12', '3.13']

steps:
- name: Checkout code
uses: actions/checkout@v4

- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}
cache: 'pip'

- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -r requirements-dev.txt

- name: Check code formatting with Black
run: |
black --check app/ tests/
continue-on-error: false

- name: Check import sorting with isort
run: |
isort --check-only app/ tests/
continue-on-error: false

- name: Lint with Ruff
run: |
ruff check app/ tests/
continue-on-error: false

- name: Type checking with MyPy
run: |
mypy app/ --install-types --non-interactive
continue-on-error: false

- name: Security check with Bandit
run: |
bandit -r app/ -f json -o bandit-report.json
continue-on-error: true

- name: Check dependencies for vulnerabilities
run: |
safety check --json
continue-on-error: true

- name: Upload Bandit report
if: always()
uses: actions/upload-artifact@v4
with:
name: bandit-report-py${{ matrix.python-version }}
path: bandit-report.json
retention-days: 30

- name: Summary
if: always()
run: |
echo "### Code Quality Check Results 🔍" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo "- ✅ Black formatting check" >> $GITHUB_STEP_SUMMARY
echo "- ✅ Isort import sorting check" >> $GITHUB_STEP_SUMMARY
echo "- ✅ Ruff linting check" >> $GITHUB_STEP_SUMMARY
echo "- ✅ MyPy type checking" >> $GITHUB_STEP_SUMMARY
echo "- ℹ️ Security checks (see artifacts)" >> $GITHUB_STEP_SUMMARY
Loading
Loading