117 lines
5.1 KiB
Python
117 lines
5.1 KiB
Python
"""Runs the project end to end on one engine and saves every measure's answers, to compare engines.
|
|
|
|
For each domain: migrates its database, inserts the WebApi tests' synthetic staging, runs the whole cycle with a
|
|
manifest compiled for that engine, then asks every measure through the WebApi's routes. Run from the WebApi
|
|
project (its environment needs the engine's driver):
|
|
|
|
python run_engine.py --url 'mssql+pymssql://user:pw@host:1433/{domain}' --manifests DIR --out answers.json
|
|
|
|
`{domain}` in the URL becomes cacu or cama; DIR holds `<domain>/manifest.json`.
|
|
"""
|
|
import argparse
|
|
import json
|
|
import re
|
|
import sys
|
|
import time
|
|
from importlib import import_module
|
|
from pathlib import Path
|
|
|
|
from flask import Flask
|
|
from sqlalchemy import create_engine
|
|
from sqlmodel import Session
|
|
|
|
from webapi.kpis import kpis_blueprint
|
|
from webapi.orchestration import Context, run
|
|
from webapi.orchestration.connection import point_to
|
|
from webapi.orchestration.reference.rules import RUTA_PARAMETROS
|
|
from webapi.orchestration.repositories import repositories_of
|
|
|
|
YEAR = 2025
|
|
PERIODS = "2025-S1,2025-S2"
|
|
VOLATILE_KEYS = {"id", "date", "lastUpdated", "fullUrl", "meta"}
|
|
MOMENT = re.compile(r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}")
|
|
|
|
|
|
def stable(value):
|
|
"""The answer without what changes from run to run: ids, timestamps; floats rounded."""
|
|
if isinstance(value, dict):
|
|
return {k: stable(v) for k, v in sorted(value.items()) if k not in VOLATILE_KEYS}
|
|
if isinstance(value, list):
|
|
return [stable(v) for v in value]
|
|
if isinstance(value, float):
|
|
return round(value, 9)
|
|
if isinstance(value, str) and MOMENT.match(value):
|
|
return "<moment>"
|
|
return value
|
|
|
|
|
|
def parameters_without_suppression(folder: Path) -> Path:
|
|
"""`parametros.toml` with suppression threshold 1, as the WebApi tests use it, so small counts are compared."""
|
|
path = folder / "parametros.toml"
|
|
path.write_text(RUTA_PARAMETROS.read_text(encoding="utf-8").replace("valor = 5", "valor = 1"), encoding="utf-8")
|
|
return path
|
|
|
|
|
|
def run_domain(domain: str, url: str, manifest: Path, tests: Path, parameters: Path) -> dict:
|
|
point_to(domain, url)
|
|
# As the WebApi tests: parameters the clinic hasn't confirmed yet are used as proposed.
|
|
ctx = Context(domain, YEAR, YEAR, dbt_manifest=manifest, repos=repositories_of(domain),
|
|
parameters=parameters, allow_undecided=True)
|
|
report = {"steps": {}, "answers": {}, "errors": {}}
|
|
run(ctx, only=["migrate"])
|
|
engine = create_engine(url)
|
|
with Session(engine) as session:
|
|
sys.path.insert(0, str(tests))
|
|
import_module(f"staging.{domain}").insertar(session)
|
|
session.commit()
|
|
engine.dispose()
|
|
|
|
started = time.monotonic()
|
|
for step in run(ctx):
|
|
report["steps"][step.name] = {"summary": repr(step.summary)[:300], "seconds": round(step.seconds, 1)}
|
|
report["cycle_seconds"] = round(time.monotonic() - started, 1)
|
|
|
|
app = Flask(f"compare-{domain}")
|
|
app.register_blueprint(kpis_blueprint(domain, import_module(f"persistance.{domain}"), manifest),
|
|
url_prefix=f"/{domain}")
|
|
client = app.test_client()
|
|
for item in client.get(f"/{domain}/indicadores").get_json():
|
|
response = client.get(f"/{domain}/indicadores/{item['id']}?periodos={PERIODS}")
|
|
body = response.get_json(force=True, silent=True)
|
|
if response.status_code == 200:
|
|
report["answers"][item["id"]] = stable(body)
|
|
else:
|
|
report["errors"][item["id"]] = {"status": response.status_code, "body": body}
|
|
return report
|
|
|
|
|
|
def main() -> None:
|
|
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
|
parser.add_argument("--url", required=True, help="SQLAlchemy URL with {domain}")
|
|
parser.add_argument("--manifests", required=True, type=Path, help="folder with <domain>/manifest.json")
|
|
parser.add_argument("--tests", required=True, type=Path, help="the WebApi's tests folder (synthetic staging)")
|
|
parser.add_argument("--out", required=True, type=Path)
|
|
parser.add_argument("--domains", default="cacu,cama")
|
|
args = parser.parse_args()
|
|
|
|
result, failed = {}, False
|
|
parameters = parameters_without_suppression(args.out.parent)
|
|
for domain in args.domains.split(","):
|
|
try:
|
|
result[domain] = run_domain(domain, args.url.format(domain=domain),
|
|
args.manifests / domain / "manifest.json", args.tests, parameters)
|
|
answered, errors = len(result[domain]["answers"]), len(result[domain]["errors"])
|
|
print(f"{domain}: cycle {result[domain]['cycle_seconds']} s, {answered} measures answered, {errors} errors")
|
|
failed |= errors > 0
|
|
except Exception as error: # report the failure and go on with the next domain
|
|
import traceback
|
|
result[domain] = {"failure": traceback.format_exc()}
|
|
print(f"{domain}: FAILED: {type(error).__name__}: {str(error)[:500]}")
|
|
failed = True
|
|
args.out.write_text(json.dumps(result, indent=1, ensure_ascii=False, default=str), encoding="utf-8")
|
|
sys.exit(1 if failed else 0)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|