288 lines
15 KiB
Python
288 lines
15 KiB
Python
"""Reset tests; optional SQL cases write exclusively to connection-local fixtures.
|
|
|
|
RESET_TEST_CONFIG=db_connection.json enables SQL Server execution. Every real
|
|
object and the reservation procedure are replaced before the batch is run.
|
|
"""
|
|
import ast
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import re
|
|
import unittest
|
|
from types import SimpleNamespace
|
|
from unittest.mock import AsyncMock, Mock
|
|
|
|
from reset_corsie_service import SQL_RESET_PALLET, reset_pallet_async
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
|
|
|
|
class ResetTests(unittest.IsolatedAsyncioTestCase):
|
|
async def test_classification_is_returned_by_transaction_not_ui(self):
|
|
for target in (1000, 9999):
|
|
db = unittest.mock.Mock()
|
|
db.query_json = AsyncMock(return_value={"rows": [[target]]})
|
|
self.assertEqual(await reset_pallet_async(db, barcode_pallet=" 600001 ",
|
|
source_idcella=1106, utente="MAG1"), target)
|
|
db.query_json.assert_awaited_once_with(SQL_RESET_PALLET,
|
|
{"barcode_pallet": "600001", "source_idcella": 1106, "utente": "MAG1"},
|
|
commit=True)
|
|
|
|
async def test_db_error_is_not_reported_as_success(self):
|
|
db = unittest.mock.Mock()
|
|
db.query_json = AsyncMock(side_effect=RuntimeError("rollback"))
|
|
with self.assertRaisesRegex(RuntimeError, "rollback"):
|
|
await reset_pallet_async(db, barcode_pallet="600001", source_idcella=1106, utente="MAG1")
|
|
|
|
def test_classification_has_no_history_date_filter(self):
|
|
self.assertIn("bt.STATO = 'D'", SQL_RESET_PALLET)
|
|
self.assertNotIn("ANNDOC", SQL_RESET_PALLET)
|
|
self.assertNotIn("ViewPackingListStorico", SQL_RESET_PALLET)
|
|
|
|
def test_sqlalchemy_bind_parameters(self):
|
|
from sqlalchemy import text
|
|
self.assertEqual(set(text(SQL_RESET_PALLET).compile().params),
|
|
{"barcode_pallet", "source_idcella", "utente"})
|
|
|
|
def test_confirmation_and_result_localized(self):
|
|
catalog = json.loads((ROOT / "locale.json").read_text(encoding="utf-8"))
|
|
for lang in ("IT", "ENG"):
|
|
confirmation = catalog[lang]["reset.confirm"].format(udc=2, cells=1, aisle="1A")
|
|
self.assertIn("9999", confirmation)
|
|
self.assertIn("9001000", confirmation)
|
|
result = catalog[lang]["reset.result"].format(aisle="1A", success=2, total=2,
|
|
shipped=1, non_shelved=1)
|
|
self.assertIn("1000", result)
|
|
|
|
def test_virtual_cells_not_resettable(self):
|
|
module = ast.parse((ROOT / "reset_corsie.py").read_text(encoding="utf-8"))
|
|
queries = {node.targets[0].id: ast.literal_eval(node.value) for node in module.body
|
|
if isinstance(node, ast.Assign) and isinstance(node.value, ast.Constant)
|
|
and isinstance(node.targets[0], ast.Name) and node.targets[0].id.startswith("SQL_")}
|
|
for query in ("SQL_CORSIE", "SQL_RIEPILOGO", "SQL_DETTAGLIO", "SQL_COUNT_RESET", "SQL_UDC_RESET"):
|
|
self.assertIn("NOT IN (1000, 9999)", queries[query])
|
|
|
|
async def test_window_worker_reports_mixed_results_and_errors(self):
|
|
# Execute the real callback body without opening a Tk window or DB.
|
|
module = ast.parse((ROOT / "reset_corsie.py").read_text(encoding="utf-8"))
|
|
cls = next(n for n in module.body if isinstance(n, ast.ClassDef) and n.name == "ResetCorsieWindow")
|
|
method = next(n for n in cls.body if isinstance(n, ast.FunctionDef) and n.name == "_do_reset")
|
|
method.decorator_list = []
|
|
move = AsyncMock(side_effect=[9999, RuntimeError("failure"), 1000])
|
|
messages = Mock()
|
|
from locale_text import text
|
|
namespace = dict(_log_sql=Mock(), _log_dataset=Mock(), _MODULE_LOGGER=Mock(),
|
|
MODULE_LOG_PATH=Path("reset_corsie.log"), SQL_UDC_RESET="SELECT fixture",
|
|
reset_pallet_async=move, messagebox=messages, loc_text=text, Any=object)
|
|
exec(compile(ast.Module(body=[method], type_ignores=[]), "reset_corsie.py", "exec"), namespace)
|
|
runner = Mock()
|
|
fake = SimpleNamespace(_async=runner, _busy=object(),
|
|
_locale_catalog=json.loads((ROOT / "locale.json").read_text(encoding="utf-8")),
|
|
db=SimpleNamespace(query_json=AsyncMock(return_value={"rows": [
|
|
["600001",1106,"1A.1.a"], ["600002",1106,"1A.1.a"], ["600003",1107,"1A.1.b"]]})),
|
|
session=SimpleNamespace(login="MAG1"), refresh=Mock())
|
|
namespace["_do_reset"](fake, "1A")
|
|
coroutine, on_ok, on_error = runner.run.call_args.args
|
|
result = await coroutine
|
|
self.assertEqual((result["success"], result["shipped"], result["non_shelved"]), (2,1,1))
|
|
self.assertEqual(result["failed"][0]["barcode_pallet"], "600002")
|
|
self.assertEqual(move.await_count, 3)
|
|
on_ok(result)
|
|
messages.showwarning.assert_called_once()
|
|
self.assertIn("Spedite in 9999 / 7G.1.1: 1", messages.showwarning.call_args.args[1])
|
|
fake.refresh.assert_called_once()
|
|
|
|
|
|
@unittest.skipUnless(os.environ.get("RESET_TEST_CONFIG"), "SQL fixture test is opt-in")
|
|
class ResetSQLTests(unittest.TestCase):
|
|
def setUp(self):
|
|
import pyodbc
|
|
with open(os.environ["RESET_TEST_CONFIG"], encoding="utf-8") as handle:
|
|
c = json.load(handle)
|
|
self.cn = pyodbc.connect("DRIVER={" + c["driver"] + "};SERVER=" + c["server"]
|
|
+ ";DATABASE=" + c["database"] + ";UID=" + c["user"] + ";PWD=" + c["password"]
|
|
+ ";TrustServerCertificate=yes;", timeout=5)
|
|
self.cn.timeout = 30
|
|
self.addCleanup(self.cn.close)
|
|
self.addCleanup(self.cn.rollback)
|
|
self.cur = self.cn.cursor()
|
|
definitions = {
|
|
"MagazziniPallet": "ID int IDENTITY PRIMARY KEY, Tipo char(1), IDRiferimento int, "
|
|
"NumeroPallet int, Attributo varchar(32), IDMagazzino int, IDArea int, IDCella int, "
|
|
"DataMagazzino datetime, PesoUnitario float, Tara float, InsUtente varchar(128), "
|
|
"InsDataOra datetime, ModUtente varchar(128), ModDataOra datetime",
|
|
"Celle": "ID int PRIMARY KEY, IDArea int, IDStato int, DelDataOra datetime, "
|
|
"ModUtente varchar(128), ModDataOra datetime",
|
|
"Aree": "ID int PRIMARY KEY, IDMagazzino int",
|
|
"LOTSER": "ID int, NUMSER varchar(32)",
|
|
"LOTTIBF": "IDLOTSER int, IDFATRIG int",
|
|
"FATRIG": "ID int, IDBAM int",
|
|
"BAMTES": "ID int, STATO char(1), ANNDOC int",
|
|
}
|
|
for name, definition in definitions.items():
|
|
self.cur.execute(f"CREATE TABLE #reset_{name} ({definition})")
|
|
self.cur.execute("CREATE TABLE #reset_refresh (Called int)")
|
|
self.sql = SQL_RESET_PALLET
|
|
for name in definitions:
|
|
self.sql = self.sql.replace("SAMA1.dbo." + name, "#reset_" + name)
|
|
self.sql = self.sql.replace("dbo." + name, "#reset_" + name)
|
|
# Same V-minus-P balance and grouping as the real XMag views.
|
|
self.stock = """SELECT mp.Attributo AS BarcodePallet, mp.IDCella
|
|
FROM #reset_MagazziniPallet mp JOIN #reset_Celle c ON c.ID=mp.IDCella
|
|
WHERE mp.Tipo IN ('V', 'P')
|
|
GROUP BY mp.Attributo, mp.NumeroPallet, mp.IDMagazzino, mp.IDArea, mp.IDCella, c.IDStato
|
|
HAVING SUM(CASE WHEN mp.Tipo='V' THEN mp.PesoUnitario ELSE -mp.PesoUnitario END)>0"""
|
|
self.sql = self.sql.replace("dbo.XMag_GiacenzaPallet", "(" + self.stock + ") AS g")
|
|
self.sql = self.sql.replace("EXEC dbo.py_sp_ControllaPrenotazionePackingListPalletNew;",
|
|
"INSERT INTO #reset_refresh VALUES (1);")
|
|
self.assertNotIn("dbo.", self.sql)
|
|
self.cur.execute("INSERT INTO #reset_Aree VALUES (1,1)")
|
|
self.cur.execute("INSERT INTO #reset_Celle (ID,IDArea,IDStato) VALUES (1106,1,1),(1107,1,0),(1000,1,0),(9999,1,0)")
|
|
self.udc("600001", 1106)
|
|
self.cn.commit()
|
|
|
|
def udc(self, pallet, cell):
|
|
self.cur.execute("""INSERT INTO #reset_MagazziniPallet
|
|
(Tipo, NumeroPallet, Attributo, IDMagazzino, IDArea, IDCella, PesoUnitario, Tara, InsUtente)
|
|
VALUES ('V',?,?,1,1,?,1,0,'OLD')""", int(pallet), pallet, cell)
|
|
|
|
def document(self, state, *, pallet="600001", year=2026, identity=1):
|
|
self.cur.execute("INSERT INTO #reset_BAMTES VALUES (?,?,?)", identity, state, year)
|
|
self.cur.execute("INSERT INTO #reset_FATRIG VALUES (?,?)", identity, identity)
|
|
self.cur.execute("INSERT INTO #reset_LOTTIBF VALUES (?,?)", identity, identity)
|
|
self.cur.execute("INSERT INTO #reset_LOTSER VALUES (?,?)", identity, pallet + "/123456")
|
|
|
|
def run_move(self, pallet="600001", source=1106, sql=None):
|
|
params = {"barcode_pallet": pallet, "source_idcella": source, "utente": "MAG1"}
|
|
values = []
|
|
def bind(match):
|
|
values.append(params[match[1]])
|
|
return "?"
|
|
batch = re.sub(r":(barcode_pallet|source_idcella|utente)\b", bind, sql or self.sql)
|
|
self.cur.execute(batch, values)
|
|
return self.cur.fetchval()
|
|
|
|
def locations(self, pallet="600001"):
|
|
return [r[0] for r in self.cur.execute("SELECT IDCella FROM (" + self.stock + ") g WHERE BarcodePallet=?", pallet)]
|
|
|
|
def test_definitive_document_ships_and_records_p_v(self):
|
|
self.document("D")
|
|
self.assertEqual(self.run_move(), 9999)
|
|
self.assertEqual(self.locations(), [9999])
|
|
rows = self.cur.execute("SELECT Tipo,IDCella,InsUtente,DataMagazzino FROM #reset_MagazziniPallet WHERE ID>1 ORDER BY ID").fetchall()
|
|
self.assertEqual([(r[0], r[1], r[2]) for r in rows], [("P",1106,"MAG1"),("V",9999,"MAG1")])
|
|
self.assertIsNotNone(rows[0][3])
|
|
self.assertEqual(rows[0][3], rows[1][3])
|
|
self.assertEqual(self.cur.execute("SELECT COUNT(*) FROM #reset_refresh").fetchval(), 1)
|
|
|
|
def test_old_definitive_document_is_not_lost_by_year_filter(self):
|
|
self.document("D", year=2010)
|
|
self.assertEqual(self.run_move(), 9999)
|
|
|
|
def test_open_document_becomes_non_shelved(self):
|
|
self.document("P")
|
|
self.assertEqual(self.run_move(), 1000)
|
|
self.assertEqual(self.locations(), [1000])
|
|
|
|
def test_no_document_becomes_non_shelved(self):
|
|
self.assertEqual(self.run_move(), 1000)
|
|
|
|
def test_closed_document_of_another_udc_does_not_ship_this_one(self):
|
|
self.document("D", pallet="600002")
|
|
self.assertEqual(self.run_move(), 1000)
|
|
|
|
def test_any_definitive_document_wins_and_multiple_lots_do_not_duplicate_move(self):
|
|
self.document("P")
|
|
self.document("D", identity=2)
|
|
self.document("D", identity=3)
|
|
self.assertEqual(self.run_move(), 9999)
|
|
self.assertEqual(self.cur.execute("SELECT COUNT(*) FROM #reset_MagazziniPallet").fetchval(), 3)
|
|
|
|
def test_different_udcs_in_same_cell_have_independent_destinations(self):
|
|
self.udc("600002", 1106)
|
|
self.document("D")
|
|
self.assertEqual(self.run_move(), 9999)
|
|
self.assertEqual(self.run_move("600002"), 1000)
|
|
self.assertEqual(self.locations(), [9999])
|
|
self.assertEqual(self.locations("600002"), [1000])
|
|
|
|
def test_moved_udc_is_blocked(self):
|
|
with self.assertRaisesRegex(Exception, "51002"):
|
|
self.run_move(source=1107)
|
|
self.cn.rollback()
|
|
self.assertEqual(self.locations(), [1106])
|
|
|
|
def test_multiple_locations_are_blocked(self):
|
|
self.udc("600001", 1107)
|
|
self.cn.commit()
|
|
with self.assertRaisesRegex(Exception, "51002"):
|
|
self.run_move()
|
|
self.cn.rollback()
|
|
self.assertEqual(set(self.locations()), {1106, 1107})
|
|
|
|
def test_missing_target_rolls_back(self):
|
|
self.cur.execute("DELETE FROM #reset_Celle WHERE ID=1000")
|
|
self.cn.commit()
|
|
with self.assertRaisesRegex(Exception, "51003"):
|
|
self.run_move()
|
|
self.cn.rollback()
|
|
self.assertEqual(self.locations(), [1106])
|
|
|
|
def test_inconsistent_double_balance_rolls_back_instead_of_leaving_two_cells(self):
|
|
self.udc("600001", 1106)
|
|
self.cn.commit()
|
|
with self.assertRaisesRegex(Exception, "51005"):
|
|
self.run_move()
|
|
self.cn.rollback()
|
|
self.assertEqual(self.locations(), [1106])
|
|
self.assertEqual(self.cur.execute("SELECT COUNT(*) FROM #reset_MagazziniPallet").fetchval(), 2)
|
|
|
|
def test_reservation_failure_rolls_back_both_movements(self):
|
|
sql = self.sql.replace("INSERT INTO #reset_refresh VALUES (1);",
|
|
"THROW 51009, 'Test refresh failure', 1;")
|
|
with self.assertRaisesRegex(Exception, "51009"):
|
|
self.run_move(sql=sql)
|
|
self.cn.rollback()
|
|
self.assertEqual(self.locations(), [1106])
|
|
self.assertEqual(self.cur.execute("SELECT COUNT(*) FROM #reset_MagazziniPallet").fetchval(), 1)
|
|
self.assertEqual(self.cur.execute("SELECT IDStato FROM #reset_Celle WHERE ID=1106").fetchval(), 1)
|
|
|
|
def test_residuals_outside_reset_aisle_are_not_changed(self):
|
|
self.udc("600002", 1107)
|
|
self.udc("600003", 1000)
|
|
self.document("D")
|
|
self.assertEqual(self.run_move(), 9999)
|
|
self.assertEqual(self.locations("600002"), [1107])
|
|
self.assertEqual(self.locations("600003"), [1000])
|
|
|
|
def test_real_history_query_closes_only_after_last_residual(self):
|
|
# Feed the unmodified history summary SQL with connection-local rows.
|
|
tree = ast.parse((ROOT / "storico_pickinglist.py").read_text(encoding="utf-8"))
|
|
sql = next(ast.literal_eval(n.value) for n in tree.body if isinstance(n, ast.Assign)
|
|
and isinstance(n.value, ast.Constant) and isinstance(n.value.value, str)
|
|
and "AS StatoOperativo" in n.value.value)
|
|
self.cur.execute("CREATE TABLE #reset_history (Pallet varchar(32))")
|
|
self.cur.execute("INSERT INTO #reset_history VALUES ('600001'),('600002')")
|
|
self.udc("600002", 1107)
|
|
self.document("D")
|
|
self.document("D", pallet="600002", identity=2)
|
|
source = """(SELECT h.Pallet, 244 AS Documento, 46000 AS DataDocumento,
|
|
'D' AS StatoDocumento, 'IT' AS NAZIONE, 'IT' AS CodNazione,
|
|
1 AS Ordinamento, 0 AS IDStato, COALESCE(g.IDCella,1000) AS Cella
|
|
FROM #reset_history h LEFT JOIN (""" + self.stock + """
|
|
) g ON g.BarcodePallet=h.Pallet) AS fixture"""
|
|
sql = sql.replace("dbo.py_XMag_ViewPackingListStorico", source).replace(":documento", "NULL")
|
|
self.assertNotIn("dbo.", sql)
|
|
def state():
|
|
self.cur.execute(sql)
|
|
return dict(zip([c[0] for c in self.cur.description], self.cur.fetchone()))["StatoOperativo"]
|
|
self.assertEqual(state(), "Chiusa ERP con residui")
|
|
self.run_move()
|
|
self.assertEqual(state(), "Chiusa ERP con residui")
|
|
self.run_move("600002", source=1107)
|
|
self.assertEqual(state(), "Chiusa")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|