WIP T-19f: ?filtro=estrato:valor en /datos y /figuras, 400 si mal escrito o no declarado; pruebas
CSO5.5 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -233,3 +233,28 @@ def test_un_indicador_desconocido_o_un_periodo_sin_reporte_da_404(client, indica
|
||||
|
||||
assert response.status_code == 404
|
||||
assert "error" in response.get_json()
|
||||
|
||||
|
||||
# --- Los filtros (T-19f) ---
|
||||
|
||||
|
||||
@pytest.mark.parametrize("query", ["?filtro=grupo_edad", "?filtro=:25-34", "?filtro=grupo_edad:25-34,grupo_edad:35-44",
|
||||
"?filtro=grupo_edad:25-34", "?filtro=ronda:1"])
|
||||
def test_un_filtro_mal_escrito_o_no_declarado_da_400(client, query):
|
||||
"""Ningún indicador vivo declara filtros todavía: todo `?filtro=` da 400, en datos y en figuras."""
|
||||
for response in (_ruta(client, INDICADOR, "datos", query), _figura(client, query=query)):
|
||||
assert response.status_code == 400
|
||||
assert "error" in response.get_json()
|
||||
|
||||
|
||||
def test_sin_filtro_los_datos_no_traen_la_llave_filtros(client):
|
||||
assert "filtros" not in _ruta(client, INDICADOR, "datos").get_json()
|
||||
|
||||
|
||||
def test_los_filtros_se_leen_como_estrato_y_valor():
|
||||
from webapi.indicadores import filtros_pedidos
|
||||
|
||||
assert filtros_pedidos(None) == {} and filtros_pedidos("") == {}
|
||||
assert filtros_pedidos("grupo_edad:25-34,ronda:1") == {"grupo_edad": "25-34", "ronda": "1"}
|
||||
with pytest.raises(ValueError, match="mal escrito"):
|
||||
filtros_pedidos("grupo_edad")
|
||||
|
||||
+31
-4
@@ -4,15 +4,20 @@
|
||||
|
||||
GET /indicadores catálogo de indicadores
|
||||
GET /indicadores/<id>/periodos periodos con reporte
|
||||
GET /indicadores/<id>/datos?periodos=&estrato= los números, sin figura
|
||||
GET /indicadores/<id>/datos?periodos=&estrato=&filtro= los números, sin figura
|
||||
GET /indicadores/<id>/metadatos ficha metodológica
|
||||
GET /indicadores/<id>/figuras/<figura>?periodos=&tema=
|
||||
GET /indicadores/<id>/figuras/<figura>?periodos=&tema=&filtro=
|
||||
|
||||
Las definiciones salen del kit (`measures_de`), los datos de
|
||||
`indicadores_kit.serving.datos` y las figuras de
|
||||
`indicadores_kit.serving.figuras`; aquí solo se valida, se abre la sesión y
|
||||
se traducen los errores a códigos HTTP. La forma de cada respuesta es un
|
||||
contrato con el frontend: no se quita ni se renombra un campo.
|
||||
|
||||
`?filtro=estrato:valor[,estrato:valor]` (T-19f) cuenta lo mismo solo con las
|
||||
unidades que tienen esos valores: el mismo contrato, y en `/datos` la llave
|
||||
`filtros`. Solo se aceptan los filtros que el indicador declara
|
||||
(`extension.filtros`) y los valores de su catálogo; si no, 400.
|
||||
"""
|
||||
|
||||
import json
|
||||
@@ -21,6 +26,7 @@ from collections.abc import Callable
|
||||
|
||||
from flask import Blueprint, Response, jsonify, request
|
||||
from indicadores_kit.registry.measures import Measure, measures_de
|
||||
from indicadores_kit.serving.contratos import FiltroNoDeclarado
|
||||
from indicadores_kit.serving.datos import datos_de, metadatos_de, periodos_de, resumen_de
|
||||
from indicadores_kit.serving.figuras import (
|
||||
TEMAS,
|
||||
@@ -59,6 +65,21 @@ def _tipo_de(periodo: str, tipos: list[str]) -> str | None:
|
||||
return next((tipo for tipo in tipos if FORMATOS[tipo][0].fullmatch(periodo)), None)
|
||||
|
||||
|
||||
def filtros_pedidos(texto: str | None) -> dict[str, str]:
|
||||
"""`estrato:valor[,estrato:valor]` -> `{estrato: valor}`. Vacío si no se pidió; `ValueError` si viene mal escrito."""
|
||||
if not texto:
|
||||
return {}
|
||||
filtros = {}
|
||||
for parte in texto.split(","):
|
||||
estrato, separador, valor = parte.partition(":")
|
||||
if not separador or not estrato or not valor:
|
||||
raise ValueError(f"filtro mal escrito {parte!r}; use estrato:valor")
|
||||
if estrato in filtros:
|
||||
raise ValueError(f"el filtro {estrato!r} va dos veces")
|
||||
filtros[estrato] = valor
|
||||
return filtros
|
||||
|
||||
|
||||
def periodos_pedidos(texto: str | None, medida: Measure) -> tuple[list[str], str | None]:
|
||||
"""Los periodos de `?periodos=` y su tipo. Sin parámetro (o vacío): `([], None)`.
|
||||
|
||||
@@ -139,6 +160,7 @@ def registrar_indicadores(
|
||||
)
|
||||
try:
|
||||
periodos, _ = periodos_pedidos(request.args.get("periodos"), medida)
|
||||
filtros = filtros_pedidos(request.args.get("filtro"))
|
||||
except ValueError as error:
|
||||
return _error(str(error), 400)
|
||||
|
||||
@@ -147,7 +169,9 @@ def registrar_indicadores(
|
||||
periodos = _periodos_o_los_que_haya(sesion, medida, periodos)
|
||||
if not periodos:
|
||||
return _error("el indicador no tiene reportes calculados", 404)
|
||||
datos = datos_de(sesion, medida, periodos, tablas=tablas, estrato=estrato)
|
||||
datos = datos_de(sesion, medida, periodos, tablas=tablas, estrato=estrato, filtros=filtros or None)
|
||||
except FiltroNoDeclarado as error:
|
||||
return _error(str(error), 400)
|
||||
except KeyError:
|
||||
# KeyError también es LookupError: aquí es un error interno (500), no un periodo sin reporte.
|
||||
raise
|
||||
@@ -171,6 +195,7 @@ def registrar_indicadores(
|
||||
return _error(f"tema desconocido {tema!r}; use claro u oscuro", 400)
|
||||
try:
|
||||
periodos, tipo = periodos_pedidos(request.args.get("periodos"), medida)
|
||||
filtros = filtros_pedidos(request.args.get("filtro"))
|
||||
except ValueError as error:
|
||||
return _error(str(error), 400)
|
||||
|
||||
@@ -180,7 +205,9 @@ def registrar_indicadores(
|
||||
periodos = periodos or periodos_por_defecto(sesion, medida, figura, tablas=tablas)
|
||||
if not periodos:
|
||||
return _error("el indicador no tiene reportes calculados", 404)
|
||||
texto = figura_json(sesion, medida, periodos, figura, tablas=tablas, tema=tema)
|
||||
texto = figura_json(sesion, medida, periodos, figura, tablas=tablas, tema=tema, filtros=filtros or None)
|
||||
except FiltroNoDeclarado as error:
|
||||
return _error(str(error), 400)
|
||||
except KeyError:
|
||||
# KeyError también es LookupError: aquí es un error interno (500), no un periodo sin reporte.
|
||||
raise
|
||||
|
||||
Reference in New Issue
Block a user