Files
BEYOND/scripts/pruebas.sh

201 lines
9.9 KiB
Bash
Executable File

#!/usr/bin/env bash
# Beyond test suite, on a throwaway database.
#
# WHY A CLEAN DATABASE. beyond_dev accumulates state that has nothing to do
# with the code: uninstalled modules, leftover demo companies, taxes edited by
# hand. Six tests failed there for reasons none of us caused, and a baseline
# that is not zero stops being a signal — nobody reads "6 failed" twice.
# The suite now runs against a database created from scratch on every run, so
# a failure means the code, always.
#
# beyond_dev is for looking at screens; this is for knowing whether it works.
#
# EL NAVEGADOR. The suite runs inside a throwaway container built from
# Dockerfile.test, which is the runtime image plus a pinned Chromium. Odoo
# drives it through browser_js to run the hoot unit tests and the tours;
# WITHOUT a browser it skips them and reports green. The dev compose and the
# production image are untouched — this is a third artifact, the same one the
# CI will use.
#
# The database is dropped at the end, including when a test fails. Keep it for
# a post mortem with: ./scripts/pruebas.sh --conservar
#
# Uso:
# ./scripts/pruebas.sh # los seis módulos
# ./scripts/pruebas.sh beyond_base # solo uno (y sus dependencias)
# ./scripts/pruebas.sh --conservar # no borra la base al terminar
set -euo pipefail
DB="${BEYOND_TEST_DB:-beyond_test}"
# beyond_product_capture se fue con el embudo (ADR-015 de Jorem) y entraron
# beyond_inventory y beyond_reports. La lista se queda escrita a mano y no se
# saca de addons/: correr la suite de un módulo que alguien acaba de añadir
# sin haberlo leído es peor que un error de lista.
MODULOS="beyond_base,beyond_branch,beyond_customer,beyond_attendance_qr,beyond_pos_theme,beyond_inventory,beyond_reports,beyond_pos"
CONSERVAR=0
SUITE_COMPLETA=1
for arg in "$@"; do
case "$arg" in
--conservar) CONSERVAR=1 ;;
--*) echo "Opción desconocida: $arg" >&2; exit 2 ;;
*) MODULOS="$arg"; SUITE_COMPLETA=0 ;;
esac
done
# Ports of their own. The suite now runs in its own container, so the clash
# with the dev server is gone, but the values stay explicit: the browser tests
# build their URLs from them.
PUERTO="${BEYOND_TEST_PORT:-8169}"
PUERTO_GEVENT="${BEYOND_TEST_GEVENT_PORT:-8172}"
limpiar() {
if [ "$CONSERVAR" -eq 1 ]; then
echo "[*] La base $DB se conserva (--conservar)."
return
fi
echo "[*] Borrando la base de pruebas $DB..."
# --force: Odoo leaves its connection pool open for a moment after
# --stop-after-init and plain dropdb refuses while anyone is attached.
docker compose exec -T db dropdb -U odoo --if-exists --force "$DB" || true
}
trap limpiar EXIT
echo "[*] Creando la base de pruebas $DB desde cero..."
docker compose exec -T db dropdb -U odoo --if-exists --force "$DB"
docker compose exec -T db createdb -U odoo -O odoo "$DB"
# Only OUR tests. --test-enable alone runs every installed module's suite,
# which here means ~3700 core tests, many of them browser tours that cannot
# pass without chromium in the container. Their noise is exactly what this
# script exists to remove.
ETIQUETAS="$(echo "$MODULOS" | tr ',' '\n' | sed 's|^|/|' | paste -sd, -)"
IMAGEN="${BEYOND_TEST_IMAGE:-beyond-test:local}"
RED="${BEYOND_TEST_NETWORK:-beyond_default}"
echo "[*] Construyendo la imagen de pruebas ($IMAGEN)..."
docker build -q -f Dockerfile.test -t "$IMAGEN" . > /dev/null
echo "[*] Instalando $MODULOS con datos demo y corriendo su suite..."
# -i and not -u: the point is a fresh install.
#
# --with-demo is REQUIRED, not decoration: in Odoo 19 demo data is off by
# default for new databases ("--without-demo ... (default)"), and beyond_dev
# only has it because it was created through the database manager with the box
# ticked. Without this flag there are no demo branches and the tests that look
# one up fail on an empty search. The demo data is also part of what has to
# keep working (CLAUDE.md, "demostrarlo en 2 minutos").
# --shm-size=1g: Chromium comparte memoria entre procesos por /dev/shm, y el
# valor por defecto de Docker (64 MB) lo hace caerse a media suite con
# «Target crashed». Es la causa clásica de una suite de navegador intermitente.
# --network: para alcanzar el Postgres del compose por su nombre de servicio,
# que es el que ya trae odoo.conf.
docker run --rm \
--network "$RED" \
--shm-size=1g \
-e PGPASSWORD="$(grep -E '^DB_PASSWORD=' .env | cut -d= -f2-)" \
-v "$PWD/addons:/mnt/extra-addons:ro" \
-v "$PWD/odoo.conf:/etc/odoo/odoo.conf:ro" \
"$IMAGEN" \
odoo -d "$DB" -i "$MODULOS" --with-demo \
--test-enable --test-tags="$ETIQUETAS" --stop-after-init \
--http-port="$PUERTO" --gevent-port="$PUERTO_GEVENT" \
2>&1 | tee /tmp/beyond_pruebas.log | grep -E \
"(FAIL|ERROR): Test|Traceback|tests\.stats|failed, .* error|Modules loaded" || true
# ── El bundle tiene que COMPILAR ──────────────────────────────────────────
# Un error de SCSS no rompe la carga de Odoo: se registra como aviso, el
# bundle sale con la última versión buena o vacío, y la suite sigue en verde
# mientras la pantalla se ve sin un solo estilo. Ya nos costó varias corridas
# persiguiendo defectos visuales que en realidad eran ESTE error.
if grep -q "assetsbundle: Error" /tmp/beyond_pruebas.log; then
echo
echo "[X] El bundle de assets NO compila. Los estilos no se aplicaron:"
grep -A3 "assetsbundle: Error" /tmp/beyond_pruebas.log | head -8 | sed 's/^/ /'
echo " Registro completo: /tmp/beyond_pruebas.log"
exit 1
fi
# ── Fallos esperados ──────────────────────────────────────────────────────
# Known-failing tests, with the ticket that owns each one. They are NOT
# silenced: they are counted and listed on every run, so the baseline stays
# honest and a NEW failure stands out immediately. A test that stops failing
# is also reported, so this list does not rot.
#
# ADR-014 (docs/adr/ADR-014-impuesto-propio.md): a clean install has no 16%
# tax at all, because l10n_mx only auto-installs when a company's country is
# Mexico and ours is set to the United States. The guarantee of ADR-010 —the
# displayed price is the total to pay— has nothing to stand on. These five
# tests are right and the product is wrong; they stay red until ADR-014 is
# decided.
# Los tres de TestBeyondTableros salieron de esta lista el 27-ago-2026: el
# diagnóstico era correcto —afirmaban totales absolutos sobre una base con
# datos demo— y se arreglaron acotando cada afirmación a lo que la propia
# prueba crea. Ya pasan en limpio.
ESPERADOS="TestBeyondIvaIncluido.test_el_iva_de_venta_esta_incluido_en_el_precio
TestBeyondIvaIncluido.test_la_aritmetica_es_de_extraccion_no_de_suma
TestBeyondIvaIncluido.test_repara_una_base_donde_el_iva_se_suma
TestBeyondIvaConCajaAbierta.test_al_cerrar_la_caja_entra_solo
TestBeyondIvaConCajaAbierta.test_con_una_venta_viva_se_difiere_en_vez_de_reventar"
# «Subtest» delante del nombre: un fallo dentro de un subTest se reporta como
# «FAIL: Subtest Clase.test (param=…)» y sin contemplarlo el barrido no ve
# ninguno —quince pasaron de largo—.
# `|| true` NO es decoración. El script corre con `set -e`, y cuando NO hay
# ni un rojo este grep no encuentra nada, devuelve 1, la sustitución hereda
# ese código y el script muere AQUÍ: sin veredicto, sin `[OK]`, y saliendo 1.
# O sea que una corrida perfecta se reportaba como fallo, y solo en ese caso
# —el único en el que uno quiere poder creerse el verde—. Se destapó el
# 27-ago-2026 corriendo un módulo suelto con la suite entera en verde.
REALES="$(grep -oE '(FAIL|ERROR): (Subtest )?[A-Za-z0-9_]+\.[A-Za-z0-9_]+' /tmp/beyond_pruebas.log \
| sed -E 's/^(FAIL|ERROR): (Subtest )?//' | sort -u || true)"
ESPERADOS_ORD="$(echo "$ESPERADOS" | sort -u)"
INESPERADOS="$(comm -23 <(echo "$REALES") <(echo "$ESPERADOS_ORD") | sed '/^$/d')"
ARREGLADOS="$(comm -13 <(echo "$REALES") <(echo "$ESPERADOS_ORD") | sed '/^$/d')"
echo
# Solo tiene sentido con la suite completa: corriendo un módulo suelto, los
# esperados de otro no aparecen y se leerían como «ya pasan».
if [ -n "$ARREGLADOS" ] && [ "$SUITE_COMPLETA" -eq 1 ]; then
echo "[!] Estos tests estaban en la lista de esperados y ya PASAN."
echo " Quítalos de ESPERADOS en este script:"
echo "$ARREGLADOS" | sed 's/^/ /'
echo
fi
ESPERADOS_VIVOS="$(comm -12 <(echo "$REALES") <(echo "$ESPERADOS_ORD") | sed '/^$/d')"
if [ -n "$ESPERADOS_VIVOS" ]; then
echo "[i] Fallos esperados (ADR-014, siguen rojos a propósito): $(echo "$ESPERADOS_VIVOS" | wc -l | tr -d ' ')"
echo "$ESPERADOS_VIVOS" | sed 's/^/ /'
echo
fi
if [ -n "$INESPERADOS" ]; then
echo "[X] Fallos NUEVOS, no esperados:"
echo "$INESPERADOS" | sed 's/^/ /'
echo " Registro completo: /tmp/beyond_pruebas.log"
exit 1
fi
# El resumen es la última palabra. Los errores de setUpClass se reportan como
# «ERROR: setUpClass (odoo.addons…)», sin Clase.test, así que el barrido por
# nombre no los ve: una vez pasaron veintiocho de largo y el script dijo verde.
RESUMEN="$(grep -oE '[0-9]+ failed, [0-9]+ error\(s\) of [0-9]+ tests' \
/tmp/beyond_pruebas.log | tail -1)"
if [ -n "$RESUMEN" ]; then
ROJOS=$(( $(echo "$RESUMEN" | awk '{print $1}') + $(echo "$RESUMEN" | awk '{print $3}') ))
CONTADOS="$(printf '%s\n%s\n' "$ESPERADOS_VIVOS" "$INESPERADOS" \
| sed '/^$/d' | wc -l | tr -d ' ')"
if [ "$ROJOS" -ne "$CONTADOS" ]; then
echo "[X] El resumen dice $ROJOS en rojo y por nombre solo salieron $CONTADOS."
echo " O son varios subtests del mismo test, o —más probable— un"
echo " error de setUpClass, que no lleva Clase.test:"
grep -oE 'ERROR: setUpClass \([^)]*\)' /tmp/beyond_pruebas.log \
| sort -u | sed 's/^/ /'
exit 1
fi
fi
echo "[OK] Sin fallos nuevos sobre base limpia."