This commit is contained in:
1 parent
2223debc11
commit
86e3321000
22 files changed
+1157
No files matched your search
@@ -0,0 +1,11 @@
|
||||
# Se construye desde la RAÍZ del repo (el CI hace: docker build -f api/Dockerfile .)
|
||||
FROM python:3.12-slim
|
||||
WORKDIR /app
|
||||
COPY api/requirements.txt .
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
COPY api/ .
|
||||
COPY alumnos.csv .
|
||||
ENV DB_PATH=/data/votos.db CENSO_PATH=/app/alumnos.csv
|
||||
RUN mkdir -p /data
|
||||
EXPOSE 8000
|
||||
CMD ["gunicorn", "-b", "0.0.0.0:8000", "-w", "2", "--threads", "4", "app:app"]
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
"""API de la votación del viaje de fin de curso (Ibiza contra Praga).
|
||||
|
||||
Esqueleto de partida: ARRANCA, pero no cumple el contrato (mirad CONTRATO.md y openapi.yaml).
|
||||
Hay al menos un fallo de seguridad grave a propósito. Encontradlo antes que el árbitro.
|
||||
"""
|
||||
import csv
|
||||
import os
|
||||
import sqlite3
|
||||
|
||||
from flask import Flask, jsonify, request
|
||||
|
||||
DB_PATH = os.environ.get("DB_PATH", "/data/votos.db")
|
||||
CENSO_PATH = os.environ.get("CENSO_PATH", "alumnos.csv")
|
||||
OPCIONES = ["Ibiza", "Praga"]
|
||||
|
||||
app = Flask(__name__)
|
||||
|
||||
|
||||
def conectar():
|
||||
con = sqlite3.connect(DB_PATH)
|
||||
con.execute("CREATE TABLE IF NOT EXISTS votos (codigo TEXT, opcion TEXT)")
|
||||
return con
|
||||
|
||||
|
||||
def cargar_censo():
|
||||
with open(CENSO_PATH, newline="") as f:
|
||||
return {fila["codigo"] for fila in csv.DictReader(f)}
|
||||
|
||||
|
||||
CENSO = cargar_censo()
|
||||
|
||||
|
||||
@app.get("/healthz")
|
||||
def healthz():
|
||||
return "ok", 200
|
||||
|
||||
|
||||
@app.get("/api/opciones")
|
||||
def opciones():
|
||||
return jsonify(OPCIONES)
|
||||
|
||||
|
||||
@app.post("/api/votos")
|
||||
def votar():
|
||||
datos = request.get_json(force=True)
|
||||
codigo = datos["codigo"]
|
||||
opcion = datos["opcion"]
|
||||
# TODO nivel 2: un voto por alumno, solo alumnos del censo, solo opciones válidas
|
||||
con = conectar()
|
||||
con.execute(f"INSERT INTO votos VALUES ('{codigo}', '{opcion}')")
|
||||
con.commit()
|
||||
return jsonify({"ok": True}) # TODO nivel 1: ¿qué código HTTP pide el contrato?
|
||||
|
||||
|
||||
@app.get("/api/resultados")
|
||||
def resultados():
|
||||
con = conectar()
|
||||
filas = con.execute("SELECT opcion, COUNT(*) FROM votos GROUP BY opcion").fetchall()
|
||||
cuenta = {opcion: n for opcion, n in filas}
|
||||
return jsonify(cuenta) # TODO nivel 1: faltan las opciones con 0 votos y el "total"
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
app.run(host="0.0.0.0", port=8000, debug=True)
|
||||
@@ -0,0 +1,3 @@
|
||||
flask==3.1.2
|
||||
gunicorn==23.0.0
|
||||
pytest==8.4.2
|
||||
@@ -0,0 +1,46 @@
|
||||
"""Tests del contrato (niveles 1 y 2). NO los modifiquéis para que pasen: arreglad la API.
|
||||
Ejecutar desde api/: python -m pytest -q
|
||||
"""
|
||||
import importlib
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
API_DIR = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(API_DIR))
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def cliente(tmp_path, monkeypatch):
|
||||
monkeypatch.setenv("DB_PATH", str(tmp_path / "votos.db"))
|
||||
monkeypatch.setenv("CENSO_PATH", str(API_DIR.parent / "alumnos.csv"))
|
||||
import app as modulo
|
||||
importlib.reload(modulo)
|
||||
return modulo.app.test_client()
|
||||
|
||||
|
||||
def test_opciones(cliente):
|
||||
assert cliente.get("/api/opciones").get_json() == ["Ibiza", "Praga"]
|
||||
|
||||
|
||||
def test_nivel1_voto_valido_cuenta(cliente):
|
||||
r = cliente.post("/api/votos", json={"codigo": "A0001", "opcion": "Ibiza"})
|
||||
assert r.status_code == 201
|
||||
assert cliente.get("/api/resultados").get_json() == {"Ibiza": 1, "Praga": 0, "total": 1}
|
||||
|
||||
|
||||
def test_nivel2_repetir_codigo_da_409(cliente):
|
||||
cliente.post("/api/votos", json={"codigo": "A0002", "opcion": "Praga"})
|
||||
r = cliente.post("/api/votos", json={"codigo": "A0002", "opcion": "Ibiza"})
|
||||
assert r.status_code == 409
|
||||
|
||||
|
||||
def test_nivel2_codigo_fuera_del_censo_da_403(cliente):
|
||||
r = cliente.post("/api/votos", json={"codigo": "Z9999", "opcion": "Ibiza"})
|
||||
assert r.status_code == 403
|
||||
|
||||
|
||||
def test_nivel2_opcion_desconocida_da_400(cliente):
|
||||
r = cliente.post("/api/votos", json={"codigo": "A0003", "opcion": "Roma"})
|
||||
assert r.status_code == 400
|
||||
Reference in new issue
Block a user