"""Explicit LOCAL integration test. Installs patch and exercises SQL, then rolls back. Run from the repository root: python tests/validate_picking_pair_sql.py Requires the restored test lists 233 and 244 on HOMESERVER/Mediseawall. Never commits: reservations, skips and one real legacy movement are rolled back. Do not run concurrently with operators on this development database. """ import asyncio from pathlib import Path import re import sys import pyodbc ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT)) from db_config import load_db_config from barcode_repository import BarcodeRepository from barcode_pair_service import BarcodePairService from pickinglist_pair_repository import PickingPairRepository class TransactionClient: """Same SQL and parameters as production, but all calls share one rollback.""" def __init__(self, connection): self.connection = connection async def query_json(self, sql, params=None, *, commit=False): params = params or {} args = [] def parameter(match): args.append(params[match.group(1)]) return "?" sql = re.sub(r":([a-zA-Z_]\w*)", parameter, sql) cursor = self.connection.cursor() try: cursor.execute(sql, *args) rows = [] columns = [] while True: if cursor.description: columns = [c[0] for c in cursor.description] rows = [list(r) for r in cursor.fetchall()] if not cursor.nextset(): break return {"columns": columns, "rows": rows} finally: cursor.close() async def exercise(connection): client = TransactionClient(connection) pair_repo = PickingPairRepository(client) assert await pair_repo.snapshot() is None, "Un giro e gia aperto: test annullato." await pair_repo.command("R", 1, documents=("233", "244")) initial = await pair_repo.snapshot() route = initial.route() print("Route:", len(route.pending), "UDC; area", route.area) assert route.pending and route.pending[0].cell_id == 1000 await pair_repo.command("R", 1, documents=("233", "244")) assert (await pair_repo.snapshot()).run_id == initial.run_id service = BarcodePairService(BarcodeRepository(client), 1, pair_repo) proposed = await service.start_priority_queue(1) saved = proposed.state service.begin_priority_pause(1) resumed = await service.resume_pair(saved) assert resumed.state.expected_pallet == saved.expected_pallet shipped_pallet = resumed.state.expected_pallet shipped = await service.submit(scanned_pallet=shipped_pallet, destination_barcode="9000000") assert shipped.ok, shipped.message assert shipped.state.auto_advance_delay_ms == 3000 current = await service.repository.fetch_current_location_by_pallet(shipped_pallet) assert int(current["IDCella"]) == 9999 print("Movement verified inside rollback:", shipped_pallet) after_move = await pair_repo.snapshot() assert shipped_pallet not in {c.pallet for c in after_move.route().pending} # Skip all residuals of role 1. Role 2 must retain its identity and route. first_residuals = [c for c in after_move.route().pending if c.document == "233"] for candidate in first_residuals: await pair_repo.command("K", 1, run_id=initial.run_id, document="233", pallet=candidate.pallet) await pair_repo.command("F", 1, run_id=initial.run_id) one_left = await pair_repo.snapshot() assert one_left.active == frozenset({"244"}) assert len(one_left.route().pending) > 0 next_item = await service.start_priority_queue(1) assert next_item.state.pair_slot == 2 # Residuals are still in the operative view, not marked shipped. count = await client.query_json("SELECT COUNT(DISTINCT Pallet) AS N FROM dbo.py_ViewPackingListRestante WHERE Documento=233") assert count["rows"][0][0] == len(first_residuals) await pair_repo.release_selected(["244"], 1) assert await pair_repo.snapshot() is None assert await service.repository.fetch_next_picking(0, documento="233") is None await pair_repo.command("R", 1, documents=("233", "244")) restarted = await pair_repo.snapshot() assert restarted.run_id != initial.run_id assert any(c.document == "233" for c in restarted.route().pending) assert not restarted.route().skipped await pair_repo.release_selected(["233", "244"], 1) await pair_repo.reserve_single("233", 1) assert await pair_repo.snapshot() is None await pair_repo.release_selected(["233"], 1) print("SQL integration passed: reserve, idempotence, pause, move, skip, release, re-reserve, monolist") def main(): c = load_db_config() connection = pyodbc.connect( "DRIVER={" + c["driver"] + "};SERVER=" + c["server"] + ";DATABASE=" + c["database"] + ";UID=" + c["user"] + ";PWD=" + c["password"] + ";TrustServerCertificate=yes;", timeout=10) try: cursor = connection.cursor() identity = cursor.execute("SELECT @@SERVERNAME,DB_NAME()").fetchone() assert tuple(identity) == ("HOMESERVER", "Mediseawall"), "Database non autorizzato per questo test" for batch in re.split(r"^\s*GO\s*$", (ROOT / "apply_pickinglist_pair_patch.sql").read_text(), flags=re.M | re.I): if batch.strip(): cursor.execute(batch) while cursor.nextset(): pass asyncio.run(exercise(connection)) finally: connection.rollback() connection.close() print("ROLLBACK completed: no persistent movement or reservation") if __name__ == "__main__": main()