Add unified shift reporting
This commit is contained in:
1 parent
1b060377aa
commit
41a5ae7a63
30 files changed
+3751
-9
No files matched your search
@@ -0,0 +1,302 @@
|
||||
import re
|
||||
import traceback
|
||||
from dataclasses import FrozenInstanceError
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from decimal import Decimal
|
||||
from unittest.mock import MagicMock
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
import pytest
|
||||
|
||||
from production_analytics.erp import (
|
||||
ErpProductionConfirmationGateway,
|
||||
ErpReadError,
|
||||
ErpSettings,
|
||||
ProductionConfirmation,
|
||||
)
|
||||
|
||||
BERLIN = ZoneInfo("Europe/Berlin")
|
||||
START = datetime(2026, 9, 4, 6, tzinfo=BERLIN)
|
||||
END = START + timedelta(hours=8)
|
||||
DB_TIME = datetime(2026, 9, 4, 8, 20)
|
||||
ROW = (
|
||||
"tenant ",
|
||||
"order-001 ",
|
||||
DB_TIME,
|
||||
"BENTO 1 ",
|
||||
"article-001 ",
|
||||
"4.85 x 40 m ",
|
||||
"roll-001 ",
|
||||
Decimal("194.0000"),
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
Decimal("194.0000"),
|
||||
Decimal("0"),
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def db(monkeypatch):
|
||||
connect = MagicMock()
|
||||
monkeypatch.setattr("production_analytics.erp.gateway.pymssql.connect", connect)
|
||||
connection = connect.return_value.__enter__.return_value
|
||||
cursor = connection.cursor.return_value.__enter__.return_value
|
||||
cursor.fetchall.return_value = [ROW]
|
||||
return connect, connection, cursor
|
||||
|
||||
|
||||
def gateway():
|
||||
return ErpProductionConfirmationGateway(
|
||||
ErpSettings("localhost", 49601, "NV_DWH", "private-user", "private-password")
|
||||
)
|
||||
|
||||
|
||||
def read(**kwargs):
|
||||
return gateway().get_confirmations(
|
||||
**{"workplace": "BENTO 1", "start": START, "end": END, **kwargs}
|
||||
)
|
||||
|
||||
|
||||
def test_finished_goods_mapping_and_connection_lifecycle(db):
|
||||
connect, connection, cursor = db
|
||||
confirmation = read()[0]
|
||||
assert isinstance(confirmation, ProductionConfirmation)
|
||||
assert confirmation.workplace == "BENTO 1"
|
||||
assert confirmation.production_order == "order-001"
|
||||
assert confirmation.tenant == "tenant"
|
||||
assert confirmation.article_number == "article-001"
|
||||
assert confirmation.article_description == "4.85 x 40 m"
|
||||
assert confirmation.roll_number == "roll-001"
|
||||
assert confirmation.production_quantity_m2 == confirmation.feedback_quantity_m2 == 194.0
|
||||
assert type(confirmation.feedback_quantity_m2) is float
|
||||
assert confirmation.raw_material_quantity == 0.0
|
||||
assert confirmation.raw_material_number is None
|
||||
assert confirmation.raw_material_description is None
|
||||
assert confirmation.batch_number is None
|
||||
assert confirmation.is_finished_goods
|
||||
assert confirmation.timestamp == DB_TIME.replace(tzinfo=BERLIN)
|
||||
assert confirmation.timestamp.tzinfo is BERLIN
|
||||
assert confirmation.timestamp.astimezone(UTC) == datetime(2026, 9, 4, 6, 20, tzinfo=UTC)
|
||||
with pytest.raises(FrozenInstanceError):
|
||||
confirmation.workplace = "other"
|
||||
connect.assert_called_once_with(
|
||||
server="localhost",
|
||||
port=49601,
|
||||
database="NV_DWH",
|
||||
user="private-user",
|
||||
password="private-password",
|
||||
login_timeout=10,
|
||||
timeout=10,
|
||||
)
|
||||
cursor.fetchall.assert_called_once_with()
|
||||
connection.cursor.return_value.__exit__.assert_called_once()
|
||||
connect.return_value.__exit__.assert_called_once()
|
||||
connection.commit.assert_not_called()
|
||||
|
||||
|
||||
def test_exact_parameterized_workplace_and_half_open_window(db):
|
||||
workplace = " BENTO 1'; DELETE FROM anything; -- "
|
||||
read(workplace=workplace, start=START.astimezone(UTC), end=END.astimezone(UTC))
|
||||
sql, params = db[2].execute.call_args.args
|
||||
assert params == (workplace.strip(), START.replace(tzinfo=None), END.replace(tzinfo=None))
|
||||
assert workplace.strip() not in sql
|
||||
assert "WHERE [Arbeitsplatz] = %s AND [Zeitstempel] >= %s AND [Zeitstempel] < %s" in sql
|
||||
assert re.findall(r"FROM\s+(\S+)", sql) == ["[dbo].[GRAFANA_PRODUCTION_CONFIRMATION]"]
|
||||
assert "ORDER BY [Zeitstempel], [Mandant], [Fertigungsauftragsnummer], [Rollennummer]" in sql
|
||||
assert not re.search(r"\b(INSERT|UPDATE|DELETE|MERGE|EXEC|TOP|LIKE)\b", sql, re.I)
|
||||
assert "[Rückmeldemenge] >" not in sql
|
||||
|
||||
|
||||
def test_half_open_boundaries_with_query_simulation(db):
|
||||
rows = [
|
||||
tuple([*ROW[:2], timestamp, *ROW[3:]])
|
||||
for timestamp in (
|
||||
START.replace(tzinfo=None) - timedelta(seconds=1),
|
||||
START.replace(tzinfo=None),
|
||||
END.replace(tzinfo=None) - timedelta(seconds=1),
|
||||
END.replace(tzinfo=None),
|
||||
)
|
||||
]
|
||||
|
||||
def execute(sql, params):
|
||||
assert "[Zeitstempel] >= %s AND [Zeitstempel] < %s" in sql
|
||||
db[2].fetchall.return_value = [row for row in rows if params[1] <= row[2] < params[2]]
|
||||
|
||||
db[2].execute.side_effect = execute
|
||||
assert [value.timestamp for value in read()] == [START, END - timedelta(seconds=1)]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("workplace", [None, 123, "", " ", "BENTO\x00 1"])
|
||||
def test_invalid_workplace_before_connect(db, workplace):
|
||||
with pytest.raises(ValueError, match="workplace"):
|
||||
read(workplace=workplace)
|
||||
db[0].assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("field", ["start", "end"])
|
||||
@pytest.mark.parametrize("value", [DB_TIME, None, "2026-09-04"])
|
||||
def test_requires_aware_datetimes(db, field, value):
|
||||
with pytest.raises(ValueError, match=f"{field} must be a timezone-aware datetime"):
|
||||
read(**{field: value})
|
||||
db[0].assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("end", [START, START - timedelta(seconds=1)])
|
||||
def test_end_must_follow_start(db, end):
|
||||
with pytest.raises(ValueError, match="end must follow start"):
|
||||
read(end=end)
|
||||
db[0].assert_not_called()
|
||||
|
||||
|
||||
def test_raw_material_row_returned_without_finished_goods_filter(db):
|
||||
row = list(ROW)
|
||||
row[6:13] = [
|
||||
None,
|
||||
Decimal("0"),
|
||||
"raw-001 ",
|
||||
"Raw material ",
|
||||
"batch-001 ",
|
||||
Decimal("0"),
|
||||
Decimal("123.1250"),
|
||||
]
|
||||
db[2].fetchall.return_value = [ROW, row]
|
||||
finished, material = read()
|
||||
assert finished.is_finished_goods
|
||||
assert not material.is_finished_goods
|
||||
assert material.production_quantity_m2 == material.feedback_quantity_m2 == 0.0
|
||||
assert material.raw_material_quantity == 123.125
|
||||
assert (
|
||||
material.raw_material_number,
|
||||
material.raw_material_description,
|
||||
material.batch_number,
|
||||
) == ("raw-001", "Raw material", "batch-001")
|
||||
assert material.roll_number is None
|
||||
|
||||
|
||||
def test_nullable_fields_and_empty_result(db):
|
||||
db[2].fetchall.return_value = [(None, "order", DB_TIME, "K7", *([None] * 9))]
|
||||
value = read(workplace="K7")[0]
|
||||
assert not value.is_finished_goods
|
||||
assert all(
|
||||
getattr(value, field) is None
|
||||
for field in (
|
||||
"tenant",
|
||||
"article_number",
|
||||
"article_description",
|
||||
"roll_number",
|
||||
"production_quantity_m2",
|
||||
"feedback_quantity_m2",
|
||||
"raw_material_number",
|
||||
"raw_material_description",
|
||||
"batch_number",
|
||||
"raw_material_quantity",
|
||||
)
|
||||
)
|
||||
db[2].fetchall.return_value = []
|
||||
assert read() == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("index", [7, 11, 12])
|
||||
@pytest.mark.parametrize(
|
||||
"value",
|
||||
[
|
||||
Decimal("NaN"),
|
||||
Decimal("Infinity"),
|
||||
Decimal("1e999"),
|
||||
float("nan"),
|
||||
float("-inf"),
|
||||
True,
|
||||
"private-password",
|
||||
],
|
||||
)
|
||||
def test_invalid_numeric_values_are_safe(db, index, value):
|
||||
row = list(ROW)
|
||||
row[index] = value
|
||||
db[2].fetchall.return_value = [row]
|
||||
with pytest.raises(ErpReadError, match="invalid row") as error:
|
||||
read()
|
||||
assert "private-password" not in "".join(traceback.format_exception(error.value))
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"row",
|
||||
[
|
||||
ROW[:-1],
|
||||
(*ROW, "extra"),
|
||||
(*ROW[:2], None, *ROW[3:]),
|
||||
(*ROW[:2], DB_TIME.replace(tzinfo=UTC), *ROW[3:]),
|
||||
(*ROW[:3], None, *ROW[4:]),
|
||||
(ROW[0], 123, *ROW[2:]),
|
||||
],
|
||||
)
|
||||
def test_malformed_rows_are_safe(db, row):
|
||||
db[2].fetchall.return_value = [row]
|
||||
with pytest.raises(ErpReadError, match="invalid row"):
|
||||
read()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("stage", ["connect", "execute", "fetch", "cursor_close", "close"])
|
||||
def test_driver_errors_are_safe(db, stage):
|
||||
connect, connection, cursor = db
|
||||
target = {
|
||||
"connect": connect,
|
||||
"execute": cursor.execute,
|
||||
"fetch": cursor.fetchall,
|
||||
"cursor_close": connection.cursor.return_value.__exit__,
|
||||
"close": connect.return_value.__exit__,
|
||||
}[stage]
|
||||
target.side_effect = RuntimeError("private-user private-password")
|
||||
with pytest.raises(ErpReadError, match="read failed") as error:
|
||||
read()
|
||||
rendered = "".join(traceback.format_exception(error.value))
|
||||
assert "private-user" not in rendered and "private-password" not in rendered
|
||||
if stage != "connect":
|
||||
connect.return_value.__exit__.assert_called_once()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"local,offset",
|
||||
[
|
||||
(datetime(2026, 3, 29, 1, 30), 1),
|
||||
(datetime(2026, 3, 29, 3, 30), 2),
|
||||
(datetime(2026, 10, 25, 1, 30), 2),
|
||||
(datetime(2026, 10, 25, 3, 30), 1),
|
||||
],
|
||||
)
|
||||
def test_dst_offsets_follow_local_plant_time(db, local, offset):
|
||||
db[2].fetchall.return_value = [(*ROW[:2], local, *ROW[3:])]
|
||||
start = local.replace(tzinfo=BERLIN)
|
||||
confirmation = read(start=start.astimezone(UTC), end=start + timedelta(minutes=10))[0]
|
||||
assert confirmation.timestamp.replace(tzinfo=None) == local
|
||||
assert confirmation.timestamp.utcoffset() == timedelta(hours=offset)
|
||||
assert db[2].execute.call_args.args[1][1] == local
|
||||
|
||||
|
||||
def test_window_across_spring_dst_transition(db):
|
||||
start = datetime(2026, 3, 29, 0, 30, tzinfo=UTC)
|
||||
end = datetime(2026, 3, 29, 1, 30, tzinfo=UTC)
|
||||
read(start=start, end=end)
|
||||
assert db[2].execute.call_args.args[1][1:] == (
|
||||
datetime(2026, 3, 29, 1, 30),
|
||||
datetime(2026, 3, 29, 3, 30),
|
||||
)
|
||||
|
||||
|
||||
def test_ambiguous_db_timestamp_uses_documented_first_occurrence(db):
|
||||
local = datetime(2026, 10, 25, 2, 30)
|
||||
db[2].fetchall.return_value = [(*ROW[:2], local, *ROW[3:])]
|
||||
confirmation = read(
|
||||
start=datetime(2026, 10, 25, 0, tzinfo=UTC), end=datetime(2026, 10, 25, 3, tzinfo=UTC)
|
||||
)[0]
|
||||
assert confirmation.timestamp.fold == 0
|
||||
assert confirmation.timestamp.astimezone(UTC) == datetime(2026, 10, 25, 0, 30, tzinfo=UTC)
|
||||
|
||||
|
||||
def test_unrepresentable_repeated_hour_interval_is_rejected(db):
|
||||
with pytest.raises(ValueError, match="plant-local SQL time"):
|
||||
read(
|
||||
start=datetime(2026, 10, 25, 2, 45, tzinfo=BERLIN, fold=0),
|
||||
end=datetime(2026, 10, 25, 2, 15, tzinfo=BERLIN, fold=1),
|
||||
)
|
||||
db[0].assert_not_called()
|
||||
Reference in new issue
Block a user