Add unified shift reporting

This commit is contained in:
admin committed 2026-10-07 21:58:18 +02:00
1 parent 1b060377aa
commit 41a5ae7a63
30 files changed
+3751 -9

No files matched your search

+17 -3
View File
@@ -1,9 +1,10 @@
import re
import traceback
from dataclasses import FrozenInstanceError, replace
from datetime import UTC, datetime
from datetime import UTC, datetime, timedelta
from decimal import Decimal
from unittest.mock import MagicMock
from zoneinfo import ZoneInfo
import pytest
@@ -90,8 +91,9 @@ def test_valid_row_and_resource_lifecycle(db):
assert status.production_order == '12026000815'
assert status.article_number == '212520'
assert status.article_description == 'Stex R 1501 C (PR) 5,80 x 50 m'
assert status.feedback_timestamp is NOW
assert status.feedback_timestamp.tzinfo is None
assert status.feedback_timestamp.isoformat() == '2026-09-04T21:20:50+02:00'
assert status.feedback_timestamp.tzinfo == ZoneInfo('Europe/Berlin')
assert status.feedback_timestamp.utcoffset() == timedelta(hours=2)
assert (status.order_quantity_m2, status.good_quantity_m2, status.remaining_quantity_m2,
status.remaining_time_hours, status.remaining_rolls) == (
80040., 69281., 10759., 17., 38.,
@@ -117,6 +119,8 @@ def test_leading_whitespace_and_timezone_preserved(db):
assert (status.workplace, status.production_order, status.article_number,
status.article_description) == (' K7', ' K 7-001', ' 001', ' description')
assert status.feedback_timestamp is row[4]
assert status.feedback_timestamp.tzinfo is UTC
assert status.feedback_timestamp.isoformat() == '2026-09-04T21:20:50+00:00'
def test_nullable_fields(db):
@@ -185,3 +189,13 @@ def test_driver_errors_are_safe(db, stage):
assert 'private-password' not in rendered
if stage != 'connect':
connect.return_value.__exit__.assert_called_once()
def test_naive_winter_timestamp_uses_berlin_standard_time(db):
row = list(ROW)
row[4] = datetime(2026, 1, 4, 21, 20, 50)
db[2].fetchmany.return_value = [row]
status = read().get_current_workplace_status('K7')
assert status.feedback_timestamp.isoformat() == '2026-01-04T21:20:50+01:00'
assert status.feedback_timestamp.tzinfo == ZoneInfo('Europe/Berlin')
assert status.feedback_timestamp.utcoffset() == timedelta(hours=1)
+302
View File
@@ -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()
+215
View File
@@ -0,0 +1,215 @@
import traceback
from datetime import UTC, datetime, timedelta
from unittest.mock import MagicMock
import pytest
from production_analytics.service.postgres_material import PostgresSettings
from production_analytics.service.postgres_shift_material import (
PostgresShiftChannelMaterialRepository,
PostgresShiftMaterialRepository,
ShiftMaterialReadError,
)
START = datetime(2026, 10, 7, 4, tzinfo=UTC)
END = START + timedelta(hours=8)
@pytest.fixture(params=[False, True], ids=["machine", "channel"])
def db(request, monkeypatch):
connect = MagicMock()
monkeypatch.setattr("psycopg.connect", connect)
connection = connect.return_value.__enter__.return_value
channel = request.param
row = (
(
START,
"calc",
"machine",
"Ex1",
"C2",
"order",
"run",
123.0,
None,
None,
"UNAVAILABLE",
True,
)
if channel
else (START, "calc", "machine", "order", "run", 123.0)
)
connection.execute.return_value.fetchall.return_value = [row]
cls = PostgresShiftChannelMaterialRepository if channel else PostgresShiftMaterialRepository
return (
cls(PostgresSettings("localhost", 5432, "db", "user", "pw")),
connect,
connection,
channel,
)
def read(repository, **changes):
return repository.get_snapshots(
**{
"machine_id": "machine",
"calculation_ids": ("calc",),
"start": START,
"end": END,
**changes,
}
)
def test_one_query_parameterization_baseline_and_strict_end(db):
repository, connect, connection, channel = db
snapshots = read(repository)
sql, params = connection.execute.call_args.args
assert params == ("machine", ["calc"], START, END)
assert "timestamp <= r.start_time" in sql
assert "timestamp > r.start_time AND timestamp < r.end_time" in sql
assert "UNION ALL" in sql
assert "EXISTS" not in sql and "DENSE_RANK" not in sql and "scoped" not in sql
assert "MIN(" not in sql and "MAX(" not in sql
assert "calculation_id = ANY(r.calculation_ids)" in sql
assert ("FROM channel_material_consumption_snapshots" in sql) is channel
assert ("FROM material_consumption_snapshots" in sql) is not channel
if channel:
assert "DISTINCT ON (s.calculation_id, extruder, doser_channel)" in sql
assert "ORDER BY s.calculation_id, extruder, doser_channel, timestamp DESC" in sql
else:
assert "unnest(r.calculation_ids)" in sql
assert "calculation_id = ids.calculation_id AND machine_id = r.machine_id" in sql
assert "ORDER BY timestamp DESC, run_id, production_order" in sql
assert "LIMIT 1" in sql
# Valid baseline filters never affect the in-window branch, which must keep
# null, non-finite, and negative counters for run/reset validation.
baseline, window = sql.split("UNION ALL")
counter = "cumulative_consumption_kg" if channel else "consumption_kg"
assert f"{counter} >= 0" in baseline
assert f"{counter} < 'Infinity'::double precision" in baseline
assert f"{counter} >=" not in window and f"{counter} <" not in window
order = "calculation_id, " + ("extruder, doser_channel, " if channel else "")
assert sql.rstrip().endswith(f"ORDER BY {order}timestamp, run_id, production_order")
connection.execute.assert_called_once()
connection.execute.return_value.fetchall.assert_called_once()
connect.assert_called_once_with(
host="localhost",
port=5432,
dbname="db",
user="user",
password="pw",
connect_timeout=10,
options="-c statement_timeout=10000",
)
connect.return_value.__exit__.assert_called_once()
assert snapshots[0].run_id == "run"
assert snapshots[0].timestamp is START
if channel:
assert snapshots[0].material_name is None
assert snapshots[0].doser_channel == "C2"
assert snapshots[0].material_mapping_status == "UNAVAILABLE"
connection.commit.assert_not_called()
def test_parameterized_multiple_calculations(db):
ids = ("calc'; DELETE FROM x; --", "second")
read(db[0], calculation_ids=ids)
sql, params = db[2].execute.call_args.args
assert params[1] == list(ids)
assert ids[0] not in sql
def test_validation_before_connect(db):
for changes in (
{"start": START.replace(tzinfo=None)},
{"end": START},
{"machine_id": "bad\x00"},
{"calculation_ids": ()},
):
with pytest.raises(ValueError):
read(db[0], **changes)
db[1].assert_not_called()
def test_empty_result(db):
db[2].execute.return_value.fetchall.return_value = []
assert read(db[0]) == []
@pytest.mark.parametrize("stage", ["connect", "execute", "fetch", "close"])
def test_safe_driver_errors(db, stage):
repository, connect, connection, _ = db
target = {
"connect": connect,
"execute": connection.execute,
"fetch": connection.execute.return_value.fetchall,
"close": connect.return_value.__exit__,
}[stage]
target.side_effect = RuntimeError("private-password")
with pytest.raises(ShiftMaterialReadError, match="read failed") as error:
read(repository)
assert "private-password" not in "".join(traceback.format_exception(error.value))
def test_invalid_row_shape_wrapped(db):
db[2].execute.return_value.fetchall.return_value = [("bad",)]
with pytest.raises(ShiftMaterialReadError, match="invalid row"):
read(db[0])
def test_multiple_baselines_and_raw_window_rows_are_preserved(db):
repository, _, connection, channel = db
original = connection.execute.return_value.fetchall.return_value[0]
counter_index = 7 if channel else 5
def row(timestamp, value, calculation="calc", stream="C2"):
values = list(original)
values[0], values[1], values[counter_index] = timestamp, calculation, value
if channel:
values[4] = stream
return tuple(values)
# A baseline per calculation (and per channel), exact-start baseline, and
# raw null/reset rows all survive repository decoding without carry-forward.
rows = [
row(START, 100),
row(START + timedelta(seconds=1), None),
row(START + timedelta(seconds=2), -1),
row(END - timedelta(microseconds=1), 110),
]
if channel:
rows += [row(START, 200, stream="C3"), row(START + timedelta(seconds=1), 205, stream="C3")]
rows += [row(START - timedelta(seconds=1), 300, calculation="second")]
connection.execute.return_value.fetchall.return_value = rows
snapshots = read(repository, calculation_ids=("calc", "second"))
assert [snapshot.timestamp for snapshot in snapshots] == [row[0] for row in rows]
counter = "cumulative_consumption_kg" if channel else "consumption_kg"
assert [getattr(snapshot, counter) for snapshot in snapshots] == [
row[counter_index] for row in rows
]
assert {snapshot.calculation_id for snapshot in snapshots} == {"calc", "second"}
if channel:
assert {snapshot.doser_channel for snapshot in snapshots} == {"C2", "C3"}
assert all(snapshot.material_name is None for snapshot in snapshots)
connection.execute.assert_called_once()
def test_missing_baseline_leaves_in_window_sample_for_fallback(db):
repository, _, connection, _ = db
values = list(connection.execute.return_value.fetchall.return_value[0])
values[0] = START + timedelta(minutes=1)
connection.execute.return_value.fetchall.return_value = [tuple(values)]
snapshots = read(repository)
assert len(snapshots) == 1
assert snapshots[0].timestamp == START + timedelta(minutes=1)
from production_analytics.calculations.shift_material import (
aggregate_shift_channel_material,
aggregate_shift_material,
)
aggregate = aggregate_shift_channel_material if db[3] else aggregate_shift_material
summary = aggregate(snapshots, machine_id="machine", calculation_ids=("calc",),
start=START, end=END)
assert summary.total_consumption_kg == 0
assert summary.items[0].baseline_missing
+317
View File
@@ -0,0 +1,317 @@
import traceback
from dataclasses import FrozenInstanceError, replace
from datetime import UTC, datetime, timedelta
from unittest.mock import MagicMock, Mock
from zoneinfo import ZoneInfo
import pytest
from production_analytics.calculations.shift_downtime import (
ShiftDowntimeEvent,
aggregate_shift_downtime,
)
from production_analytics.service.postgres_downtime import (
DowntimeReadError,
PostgresDowntimeRepository,
)
from production_analytics.service.postgres_material import PostgresSettings
from production_analytics.service.shift_downtime import ShiftDowntimeService
BERLIN = ZoneInfo("Europe/Berlin")
START = datetime(2026, 10, 7, 6, tzinfo=BERLIN)
END = START + timedelta(hours=8)
def event(identifier="event", *, start=START, end=END, reason="Reason", **changes):
return replace(
ShiftDowntimeEvent(
identifier,
"machine",
start,
end,
"reason-id",
reason,
"Description",
"Group",
"PLANNED",
"Comment",
),
**changes,
)
def summarize(events, **changes):
return aggregate_shift_downtime(
events,
**{
"machine_id": "machine",
"start": START,
"end": END,
**changes,
},
)
def test_clip_both_boundaries_preserve_source_and_immutable_results():
source = event(start=START - timedelta(hours=1), end=END + timedelta(hours=1))
summary = summarize([source])
assert summary.shift_duration_seconds == summary.total_downtime_seconds == 480 * 60
assert summary.non_downtime_seconds == 0
clipped = summary.events[0]
assert clipped.source is source
assert clipped.start is START and clipped.end is END
assert clipped.duration_seconds == 480 * 60
assert summary.reasons[0].duration_seconds == 480 * 60
assert summary.reasons[0].event_count == 1
assert summary.reasons[0].reason_description == "Description"
assert clipped.source.comment == "Comment"
for value, field in (
(source, "comment"),
(summary, "machine_id"),
(clipped, "start"),
(summary.reasons[0], "reason_name"),
):
with pytest.raises(FrozenInstanceError):
setattr(value, field, None)
def test_open_event_clipped_to_shift_end():
summary = summarize([event(start=START + timedelta(hours=7), end=None)])
assert summary.total_downtime_seconds == 3600
assert summary.non_downtime_seconds == 7 * 3600
assert summary.events[0].end is END
assert summary.events[0].source.source_end is None
def test_overlap_nested_duplicates_and_adjacent_intervals_are_not_double_counted():
events = [
event("a", end=START + timedelta(hours=2)),
event("b", start=START + timedelta(hours=1), end=START + timedelta(hours=3)),
event("c", start=START + timedelta(minutes=30), end=START + timedelta(hours=1)),
event("d", start=START + timedelta(hours=3), end=START + timedelta(hours=4)),
]
summary = summarize([*events, events[0]])
assert summary.total_downtime_seconds == 4 * 3600
assert summary.non_downtime_seconds == 4 * 3600
assert summary.reasons[0].duration_seconds == 4 * 3600
def test_overlapping_different_reasons_do_not_inflate_total():
summary = summarize(
[
event("a", end=START + timedelta(hours=2), reason="A"),
event(
"b", start=START + timedelta(hours=1), end=START + timedelta(hours=3), reason="B"
),
]
)
assert summary.total_downtime_seconds == 3 * 3600
assert sum(reason.duration_seconds for reason in summary.reasons) == 4 * 3600
assert summary.non_downtime_seconds == 5 * 3600
def test_half_open_window_excludes_touching_zero_length_and_other_machine_events():
summary = summarize(
[
event("before", start=START - timedelta(hours=1), end=START),
event("after", start=END, end=END + timedelta(hours=1)),
event("zero", start=START, end=START),
event("other", machine_id="other"),
event("future-open", start=END, end=None),
]
)
assert summary.events == summary.reasons == ()
assert summary.total_downtime_seconds == 0
assert summary.non_downtime_seconds == 480 * 60
def test_empty_shift():
summary = summarize([])
assert summary.total_downtime_seconds == 0
assert summary.non_downtime_seconds == summary.shift_duration_seconds == 480 * 60
def test_example_reason_totals_using_synthetic_intervals_matching_supplied_approximations():
# Exact synthetic durations chosen within the supplied rounded real-data examples.
intervals = [
("clean", "Reinigung", -10, 50.84),
("setup1", "Rüstzeit Auftragsbeginn", 60, 91.34),
("mechanical", "212 - Hülsenzuführung mechanisch", 180, 59.22),
("setup2", "Rüstzeit Auftragsbeginn", 469.2, 10.8),
]
events = [
event(
identifier,
reason=reason,
start=START + timedelta(minutes=minute),
end=START + timedelta(minutes=max(0, minute) + duration),
)
for identifier, reason, minute, duration in intervals
]
summary = summarize(events)
assert summary.total_downtime_seconds / 60 == pytest.approx(212.2)
assert summary.non_downtime_seconds / 60 == pytest.approx(267.8)
assert [
(value.reason_name, round(value.duration_seconds / 60, 1)) for value in summary.reasons
] == [
("Rüstzeit Auftragsbeginn", 102.1),
("212 - Hülsenzuführung mechanisch", 59.2),
("Reinigung", 50.8),
]
assert summary.reasons[0].event_count == 2
def test_nullable_reasons_and_deterministic_order():
events = [
event(
"z",
reason=None,
reason_id=None,
reason_description=None,
reason_group=None,
category=None,
comment=None,
end=START + timedelta(minutes=1),
),
event("a", reason="A", end=START + timedelta(minutes=1)),
]
summary = summarize(events)
assert summary == summarize(reversed(events))
assert [value.source.external_id for value in summary.events] == ["a", "z"]
assert any(reason.reason_id is None for reason in summary.reasons)
@pytest.mark.parametrize("date,hours", [(datetime(2026, 3, 29), 7), (datetime(2026, 10, 25), 9)])
def test_dst_uses_elapsed_time_not_wall_clock_duration(date, hours):
start = date.replace(tzinfo=BERLIN)
end = start + timedelta(hours=8)
summary = summarize([event(start=start, end=end)], start=start, end=end)
assert summary.total_downtime_seconds == summary.shift_duration_seconds == hours * 3600
assert summary.start is start and summary.end is end
@pytest.fixture
def db(monkeypatch):
connect = MagicMock()
monkeypatch.setattr("psycopg.connect", connect)
connection = connect.return_value.__enter__.return_value
connection.execute.return_value.fetchall.return_value = [
(
"id",
"machine",
START.astimezone(UTC),
None,
None,
None,
None,
None,
"UNKNOWN",
None,
)
]
repository = PostgresDowntimeRepository(PostgresSettings("localhost", 5432, "db", "user", "pw"))
return repository, connect, connection
def test_repository_sql_parameters_mapping_and_lifecycle(db):
repository, connect, connection = db
values = repository.get_events(machine_id="machine", start=START, end=END)
sql, params = connection.execute.call_args.args
assert params == ("machine", END, START)
assert "WHERE machine_id = %s AND source_start < %s" in sql
assert "source_end IS NULL OR source_end > %s" in sql
assert "ORDER BY source_start, external_id" in sql
assert "attributed_" not in sql and "production_order" not in sql
assert len(values) == 1 and values[0].source_end is None
assert values[0].source_start.tzinfo is UTC
connect.assert_called_once_with(
host="localhost",
port=5432,
dbname="db",
user="user",
password="pw",
connect_timeout=10,
options="-c statement_timeout=10000",
)
connect.return_value.__exit__.assert_called_once()
connection.commit.assert_not_called()
def test_machine_id_is_parameterized(db):
machine_id = "id'; DELETE FROM anything; --"
db[0].get_events(machine_id=machine_id, start=START, end=END)
sql, params = db[2].execute.call_args.args
assert machine_id not in sql
assert params[0] == machine_id
@pytest.mark.parametrize(
"changes",
[
{"machine_id": ""},
{"machine_id": " "},
{"machine_id": "bad\x00"},
{"start": START.replace(tzinfo=None)},
{"end": END.replace(tzinfo=None)},
{"start": None},
{"end": START},
{"end": START - timedelta(seconds=1)},
],
)
def test_invalid_window_before_database_read(db, changes):
inputs = {"machine_id": "machine", "start": START, "end": END, **changes}
with pytest.raises(ValueError):
db[0].get_events(**inputs)
db[1].assert_not_called()
with pytest.raises(ValueError):
aggregate_shift_downtime([], **inputs)
reader = Mock()
with pytest.raises(ValueError):
ShiftDowntimeService(reader).summarize(**inputs)
reader.get_events.assert_not_called()
@pytest.mark.parametrize("stage", ["connect", "execute", "fetch", "close"])
def test_repository_errors_are_safe(db, stage):
repository, connect, connection = db
target = {
"connect": connect,
"execute": connection.execute,
"fetch": connection.execute.return_value.fetchall,
"close": connect.return_value.__exit__,
}[stage]
target.side_effect = RuntimeError("private-password")
with pytest.raises(DowntimeReadError, match="read failed") as error:
repository.get_events(machine_id="machine", start=START, end=END)
assert "private-password" not in "".join(traceback.format_exception(error.value))
@pytest.mark.parametrize(
"changes",
[
{"source_start": START.replace(tzinfo=None)},
{"source_end": END.replace(tzinfo=None)},
{"source_end": START - timedelta(seconds=1)},
{"reason_name": 123},
],
)
def test_invalid_source_model(changes):
with pytest.raises(ValueError):
event(**changes)
def test_repository_invalid_row_is_wrapped(db):
db[2].execute.return_value.fetchall.return_value = [("invalid-row",)]
with pytest.raises(DowntimeReadError, match="invalid row"):
db[0].get_events(machine_id="machine", start=START, end=END)
def test_service_reads_once_and_propagates_errors():
reader = Mock()
reader.get_events.return_value = [event()]
summary = ShiftDowntimeService(reader).summarize(machine_id="machine", start=START, end=END)
assert summary == summarize([event()])
reader.get_events.assert_called_once_with(machine_id="machine", start=START, end=END)
reader.get_events.side_effect = DowntimeReadError("read failed")
with pytest.raises(DowntimeReadError):
ShiftDowntimeService(reader).summarize(machine_id="machine", start=START, end=END)
+407
View File
@@ -0,0 +1,407 @@
from dataclasses import FrozenInstanceError, replace
from datetime import UTC, datetime, timedelta
from unittest.mock import Mock
from zoneinfo import ZoneInfo
import pytest
from production_analytics.calculations.shift_material import (
ShiftChannelMaterialSnapshot,
ShiftMaterialSnapshot,
aggregate_shift_channel_material,
aggregate_shift_material,
)
from production_analytics.service.shift_material import (
ShiftChannelMaterialService,
ShiftMaterialService,
)
START = datetime(2026, 10, 7, 6, tzinfo=ZoneInfo("Europe/Berlin"))
END = START + timedelta(hours=8)
def machine_sample(minutes=0, value=100.0, *, run="r1", calculation="calc", order="order"):
return ShiftMaterialSnapshot(
START + timedelta(minutes=minutes), calculation, "machine", order, run, value
)
def channel_sample(
minutes=0,
value=100.0,
*,
name="Material A",
number=None,
status="ASSIGNED",
run="r1",
extruder="Ex1",
channel="C1",
order="order",
quality=True,
):
return ShiftChannelMaterialSnapshot(
START + timedelta(minutes=minutes),
"calc",
"machine",
extruder,
channel,
order,
run,
value,
number,
name,
status,
quality,
)
def aggregate(rows, *, channel=False, **changes):
function = aggregate_shift_channel_material if channel else aggregate_shift_material
return function(
rows,
**{
"machine_id": "machine",
"calculation_ids": ("calc",),
"start": START,
"end": END,
**changes,
},
)
def test_single_run_boundary_baseline_and_end_are_latest_not_min_max():
summary = aggregate(
[
machine_sample(-20, 1),
machine_sample(-1, 100),
machine_sample(10, 110),
machine_sample(479, 120),
machine_sample(480, 500),
machine_sample(500, 600),
]
)
assert summary.total_consumption_kg == 20
assert summary.items[0].baseline_timestamp == START - timedelta(minutes=1)
assert summary.items[0].end_timestamp == END - timedelta(minutes=1)
assert not summary.items[0].baseline_missing
assert summary.items[0].material_name is None
assert summary.items[0].production_order == "order"
assert summary.items[0].run_id == "r1"
assert isinstance(summary.items, tuple)
with pytest.raises(FrozenInstanceError):
summary.total_consumption_kg = 0
with pytest.raises(FrozenInstanceError):
summary.items[0].consumption_kg = 0
def test_exact_start_baseline_and_end_exclusion():
summary = aggregate(
[
machine_sample(-1, 90),
machine_sample(0, 100),
machine_sample(479, 125),
machine_sample(480, 500),
]
)
assert summary.total_consumption_kg == 25
assert summary.items[0].baseline_timestamp is not None
assert summary.items[0].baseline_timestamp == START
@pytest.mark.parametrize("channel", [False, True])
def test_run_change_never_differences_counters_across_runs(channel):
sample = channel_sample if channel else machine_sample
summary = aggregate(
[
sample(-1, 100),
sample(120, 120),
sample(121, 10, run="r2", order="order-2"),
sample(479, 45, run="r2", order="order-2"),
],
channel=channel,
)
assert [item.consumption_kg for item in summary.items] == [20, 35]
assert summary.total_consumption_kg == 55
assert summary.items[1].baseline_missing
assert summary.items[1].production_order == "order-2"
@pytest.mark.parametrize("channel", [False, True])
def test_missing_baseline_uses_first_sample_without_fabricating_consumption(channel):
sample = channel_sample if channel else machine_sample
summary = aggregate([sample(10, 1000), sample(20, 1005)], channel=channel)
assert summary.total_consumption_kg == 5
assert all(item.baseline_missing for item in summary.items)
assert aggregate([sample(10, 1000)], channel=channel).total_consumption_kg == 0
@pytest.mark.parametrize("channel", [False, True])
def test_no_samples_and_zero_items_filter(channel):
assert aggregate([], channel=channel).items == ()
sample = channel_sample if channel else machine_sample
rows = [sample(0, 100), sample(10, 100)]
summary = aggregate(rows, channel=channel)
assert len(summary.items) == 1 and summary.total_consumption_kg == 0
assert aggregate(rows, channel=channel, include_zero=False).items == ()
@pytest.mark.parametrize("channel", [False, True])
@pytest.mark.parametrize("values", [(100, 90), (100, 90, 150)])
def test_counter_reset_rejected_even_when_final_value_recovers(channel, values):
sample = channel_sample if channel else machine_sample
with pytest.raises(ValueError, match="decreased/reset"):
aggregate(
[sample(index * 10, value) for index, value in enumerate(values)], channel=channel
)
def test_last_valid_baseline_and_end_skip_null_and_nonfinite_counters():
summary = aggregate(
[
machine_sample(-2, 100),
machine_sample(-1, None),
machine_sample(0, float("nan")),
machine_sample(10, 105),
machine_sample(479, float("inf")),
]
)
assert summary.total_consumption_kg == 5
assert summary.items[0].baseline_timestamp == START - timedelta(minutes=2)
assert summary.items[0].end_timestamp == START + timedelta(minutes=10)
def test_multiple_calculations_and_supplied_k7_b1_examples():
examples = {
"k7-fiber-consumption": (12083.537, 15552.303, 3468.766),
"bento1-fresh-bentonite-consumption": (34604.833, 47320.628, 12715.795),
"bento1-spreader3-consumption": (9540.429, 11303.167, 1762.738),
}
rows = [
machine_sample(minutes, value, calculation=calculation)
for calculation, (baseline, end, _) in examples.items()
for minutes, value in ((-1, baseline), (479, end))
]
summary = aggregate(rows, calculation_ids=tuple(examples))
assert {item.calculation_id: item.consumption_kg for item in summary.items} == pytest.approx(
{calculation: values[2] for calculation, values in examples.items()}
)
assert summary.total_consumption_kg == pytest.approx(
sum(values[2] for values in examples.values())
)
def test_channel_b_identity_attribution_and_no_null_carry_forward():
rows = [
channel_sample(-1, 100, name="Old"),
channel_sample(10, 110, name="Material A"),
channel_sample(20, 130, name="Material A"),
channel_sample(30, 135, name=None),
channel_sample(40, 140, name=" "),
channel_sample(50, 155, name="Material A"),
channel_sample(60, 165, name="Material B"),
]
summary = aggregate(rows, channel=True)
assert [(item.material_name, item.consumption_kg) for item in summary.items] == [
("Material A", 30),
(None, 10),
("Material A", 15),
("Material B", 10),
]
assert summary.items[1].material_mapping_status == "UNAVAILABLE"
assert all(item.material_number is None for item in summary.items)
assert summary.total_consumption_kg == 65
assert all(item.material_name != "Old" for item in summary.items)
def test_material_number_metadata_and_quality_are_preserved():
summary = aggregate(
[
channel_sample(0, 100, number="123", name=None),
channel_sample(10, 105, number="123", name=None, quality=False),
channel_sample(20, 110, number="123", name=None, quality=True),
],
channel=True,
)
item = summary.items[0]
assert item.material_number == "123" and item.material_name is None
assert item.material_mapping_status == "ASSIGNED"
assert not item.percentage_sum_valid
assert item.consumption_kg == 10
def test_e1_historical_null_channel_fixtures():
expected = {
"Ex1": [0, 4890.271, 4890.271, 1772.723, 0, 0, 672.412],
"Ex2": [7596.677, 822.973, 2481.581, 1266.113, 0, 0, 493.784],
}
rows = [
channel_sample(
minutes, value, extruder=extruder, channel=f"C{index}", name=None, status="UNAVAILABLE"
)
for extruder, deltas in expected.items()
for index, delta in enumerate(deltas, 1)
for minutes, value in ((-1, 5000), (479, 5000 + delta))
]
summary = aggregate(rows, channel=True)
assert len(summary.items) == 14
assert {(item.extruder, item.doser_channel): item.consumption_kg for item in summary.items} == (
pytest.approx(
{
(extruder, f"C{index}"): delta
for extruder, deltas in expected.items()
for index, delta in enumerate(deltas, 1)
}
)
)
assert all(item.material_name is None for item in summary.items)
assert all(item.material_mapping_status == "UNAVAILABLE" for item in summary.items)
assert summary == aggregate(reversed(rows), channel=True)
assert len(aggregate(rows, channel=True, include_zero=False).items) == 9
@pytest.mark.parametrize("channel", [False, True])
def test_dst_fold_boundaries_use_instants(channel):
berlin = ZoneInfo("Europe/Berlin")
start = datetime(2026, 10, 25, 2, 30, tzinfo=berlin, fold=0)
end = start.replace(fold=1)
sample = channel_sample if channel else machine_sample
rows = [
replace(sample(value=value), timestamp=timestamp)
for timestamp, value in (
(start, 100),
(datetime(2026, 10, 25, 1, 20, tzinfo=UTC), 110),
(end, 500),
)
]
summary = aggregate(rows, channel=channel, start=start, end=end)
assert summary.total_consumption_kg == 10
assert summary.start is start and summary.end is end
@pytest.mark.parametrize("channel", [False, True])
def test_invalid_windows_precede_reader_call(channel):
reader = Mock()
service = ShiftChannelMaterialService(reader) if channel else ShiftMaterialService(reader)
for changes in (
{"start": START.replace(tzinfo=None)},
{"end": END.replace(tzinfo=None)},
{"end": START},
{"end": START - timedelta(hours=1)},
{"machine_id": ""},
{"calculation_ids": ()},
{"calculation_ids": ("calc", "calc")},
):
inputs = {
"machine_id": "machine",
"calculation_ids": ("calc",),
"start": START,
"end": END,
**changes,
}
with pytest.raises(ValueError):
service.summarize(**inputs)
with pytest.raises(ValueError):
aggregate([], channel=channel, **changes)
reader.get_snapshots.assert_not_called()
@pytest.mark.parametrize("channel", [False, True])
def test_service_composes_once_and_propagates_errors(channel):
reader = Mock()
reader.get_snapshots.return_value = [channel_sample() if channel else machine_sample()]
service = ShiftChannelMaterialService(reader) if channel else ShiftMaterialService(reader)
inputs = {"machine_id": "machine", "calculation_ids": ("calc",), "start": START, "end": END}
assert service.summarize(**inputs) == aggregate(
reader.get_snapshots.return_value, channel=channel
)
reader.get_snapshots.assert_called_once_with(**inputs)
reader.get_snapshots.side_effect = RuntimeError("reader failed")
with pytest.raises(RuntimeError, match="reader failed"):
service.summarize(**inputs)
@pytest.mark.parametrize("channel", [False, True])
def test_ambiguous_stream_timestamps_and_reappearing_runs_rejected(channel):
sample = channel_sample if channel else machine_sample
with pytest.raises(ValueError, match="same stream timestamp"):
aggregate([sample(0, 100), sample(0, 100)], channel=channel)
with pytest.raises(ValueError, match="reappeared"):
aggregate([sample(0, 100), sample(10, 10, run="r2"), sample(20, 200)], channel=channel)
with pytest.raises(ValueError, match="Production order"):
aggregate([sample(0, 100), sample(10, 110, order="different")], channel=channel)
def test_machine_and_calculation_scoping():
summary = aggregate(
[
machine_sample(),
machine_sample(10, 110),
replace(machine_sample(20, 1000), machine_id="other"),
machine_sample(20, 1000, calculation="other"),
]
)
assert summary.total_consumption_kg == 10
def test_channel_invalid_numeric_samples_are_not_used_as_baseline_or_end():
summary = aggregate(
[
channel_sample(-2, 100),
channel_sample(-1, None),
channel_sample(10, 120, name=None),
channel_sample(479, float("nan")),
],
channel=True,
)
assert summary.total_consumption_kg == 20
assert summary.items[0].material_name is None
assert summary.items[0].material_mapping_status == "UNAVAILABLE"
@pytest.mark.parametrize("channel", [False, True])
def test_new_run_exactly_at_shift_start_is_its_own_baseline(channel):
sample = channel_sample if channel else machine_sample
summary = aggregate(
[sample(-1, 10000, run="old"), sample(0, 50, run="new"), sample(10, 60, run="new")],
channel=channel,
)
assert len(summary.items) == 1
assert summary.items[0].run_id == "new"
assert not summary.items[0].baseline_missing
assert summary.total_consumption_kg == 10
@pytest.mark.parametrize("channel", [False, True])
def test_invalid_counters_do_not_hide_run_boundaries(channel):
sample = channel_sample if channel else machine_sample
summary = aggregate(
[sample(-2, 1000), sample(-1, None, run="r2"),
sample(10, 50, run="r2"), sample(20, 60, run="r2")],
channel=channel,
)
assert summary.total_consumption_kg == 10
assert len(summary.items) == 1
assert summary.items[0].run_id == "r2"
assert summary.items[0].baseline_missing
with pytest.raises(ValueError, match="reappeared"):
aggregate([sample(0, 100), sample(10, None, run="r2"), sample(20, 120)],
channel=channel)
@pytest.mark.parametrize("channel", [False, True])
def test_negative_counter_is_rejected(channel):
sample = channel_sample if channel else machine_sample
with pytest.raises(ValueError, match="non-negative"):
aggregate([sample(0, 100), sample(10, -1)], channel=channel)
@pytest.mark.parametrize("channel", [False, True])
def test_spring_dst_window_uses_elapsed_instants(channel):
berlin = ZoneInfo("Europe/Berlin")
start = datetime(2026, 3, 29, 1, 30, tzinfo=berlin)
end = datetime(2026, 3, 29, 3, 30, tzinfo=berlin)
sample = channel_sample if channel else machine_sample
rows = [replace(sample(value=value), timestamp=timestamp) for timestamp, value in
[(start, 100), (datetime(2026, 3, 29, 1, 20, tzinfo=UTC), 110), (end, 999)]]
assert (end.astimezone(UTC) - start.astimezone(UTC)).total_seconds() == 3600
assert aggregate(rows, channel=channel, start=start, end=end).total_consumption_kg == 10
+250
View File
@@ -0,0 +1,250 @@
from dataclasses import FrozenInstanceError, replace
from datetime import UTC, datetime, timedelta
from unittest.mock import Mock
from zoneinfo import ZoneInfo
import pytest
from production_analytics.calculations.shift_production import aggregate_shift_production
from production_analytics.erp import ErpReadError, ProductionConfirmation
from production_analytics.service.shift_production import ShiftProductionService
BERLIN = ZoneInfo("Europe/Berlin")
START = datetime(2026, 9, 4, 6, tzinfo=BERLIN)
END = START + timedelta(hours=8)
ROW = ProductionConfirmation(
workplace="arbitrary-workplace",
production_order="order-1",
timestamp=START,
article_number="article-1",
article_description="4.85 x 40 m",
roll_number="roll-1",
production_quantity_m2=194.0,
feedback_quantity_m2=194.0,
raw_material_number=None,
raw_material_description=None,
batch_number=None,
raw_material_quantity=0.0,
tenant="tenant",
)
def summarize(rows, **kwargs):
return aggregate_shift_production(
rows,
**{
"workplace": ROW.workplace,
"start": START,
"end": END,
**kwargs,
},
)
def test_one_article_order_uses_feedback_area_and_tracks_times():
rows = [
ROW,
replace(
ROW,
timestamp=START + timedelta(hours=1),
roll_number="roll-2",
feedback_quantity_m2=1500.0,
production_quantity_m2=999.0,
),
]
summary = summarize(iter(reversed(rows)))
assert summary.total_produced_m2 == 1694.0
assert summary.total_roll_count == 2
assert len(summary.items) == 1
item = summary.items[0]
assert (item.production_order, item.article_number, item.article_description) == (
"order-1",
"article-1",
"4.85 x 40 m",
)
assert item.produced_m2 == 1694.0
assert item.roll_count == 2
assert item.first_confirmation_at is START
assert item.last_confirmation_at == START + timedelta(hours=1)
assert summary.start is START and summary.end is END
assert isinstance(summary.items, tuple)
with pytest.raises(FrozenInstanceError):
item.produced_m2 = 0
with pytest.raises(FrozenInstanceError):
summary.total_produced_m2 = 0
def test_articles_orders_and_descriptions_form_separate_groups():
rows = [
ROW,
replace(ROW, article_number="article-2", feedback_quantity_m2=2500.0),
replace(ROW, production_order="order-2", feedback_quantity_m2=1500.0),
replace(ROW, article_description="Different description", feedback_quantity_m2=100.0),
]
summary = summarize(rows)
assert len(summary.items) == 4
assert summary.total_produced_m2 == 4294.0
# The same roll number is distinct within each group, not across the shift.
assert summary.total_roll_count == 4
assert summary.total_produced_m2 == sum(item.produced_m2 for item in summary.items)
assert summary.total_roll_count == sum(item.roll_count for item in summary.items)
def test_raw_material_null_zero_and_negative_feedback_do_not_contribute():
rows = [
ROW,
*[
replace(
ROW,
feedback_quantity_m2=quantity,
production_quantity_m2=0,
raw_material_quantity=999,
roll_number="raw-roll",
)
for quantity in (None, 0.0, -10.0)
],
]
summary = summarize(rows)
assert summary.total_produced_m2 == 194.0
assert summary.total_roll_count == 1
def test_repeated_roll_numbers_deduplicate_only_roll_count():
rows = [ROW, ROW, replace(ROW, roll_number=" roll-1 "), replace(ROW, roll_number="roll-2")]
summary = summarize(rows)
assert summary.total_produced_m2 == 4 * 194.0
assert summary.total_roll_count == summary.items[0].roll_count == 2
@pytest.mark.parametrize("roll", [None, "", " "])
def test_missing_roll_number_still_contributes_area(roll):
summary = summarize([replace(ROW, roll_number=roll)])
assert summary.total_produced_m2 == 194.0
assert summary.total_roll_count == 0
def test_exact_workplace_and_half_open_boundaries():
summary = summarize(
[
replace(ROW, timestamp=START - timedelta(microseconds=1)),
ROW,
replace(ROW, timestamp=END - timedelta(microseconds=1), roll_number="last"),
replace(ROW, timestamp=END),
replace(ROW, workplace="different-workplace"),
],
workplace=" arbitrary-workplace ",
)
assert summary.workplace == ROW.workplace
assert summary.total_produced_m2 == 388.0
assert summary.total_roll_count == 2
assert summary.items[0].last_confirmation_at == END - timedelta(microseconds=1)
def test_empty_shift_and_material_only_shift():
for rows in ([], [replace(ROW, feedback_quantity_m2=0.0)]):
summary = summarize(rows)
assert summary.items == ()
assert summary.total_produced_m2 == 0.0
assert summary.total_roll_count == 0
def test_deterministic_order_with_nullable_article_identifiers():
rows = [
replace(ROW, production_order="z", timestamp=START + timedelta(minutes=1)),
replace(ROW, article_number="z"),
replace(ROW, article_number=None),
replace(ROW, article_number="", article_description=None),
replace(ROW, article_number="", article_description=""),
]
summary = summarize(rows)
assert summary == summarize(reversed(rows))
assert [(item.article_number, item.article_description) for item in summary.items[:4]] == [
(None, "4.85 x 40 m"),
("", None),
("", ""),
("z", "4.85 x 40 m"),
]
assert summary.items[-1].production_order == "z"
@pytest.mark.parametrize(
"kwargs",
[
{"start": START.replace(tzinfo=None)},
{"end": END.replace(tzinfo=None)},
{"start": None},
{"end": START},
{"end": START - timedelta(seconds=1)},
{"workplace": ""},
{"workplace": " "},
{"workplace": "bad\x00"},
],
)
def test_validation_precedes_gateway_read(kwargs):
gateway = Mock()
service = ShiftProductionService(gateway)
inputs = {"workplace": ROW.workplace, "start": START, "end": END, **kwargs}
with pytest.raises(ValueError):
aggregate_shift_production([], **inputs)
with pytest.raises(ValueError):
service.summarize(**inputs)
gateway.get_confirmations.assert_not_called()
def test_naive_confirmation_timestamp_is_rejected():
with pytest.raises(ValueError, match="confirmation timestamp"):
summarize([replace(ROW, timestamp=START.replace(tzinfo=None))])
@pytest.mark.parametrize("quantity", [float("nan"), float("inf"), True])
def test_invalid_feedback_quantity_rejected(quantity):
with pytest.raises(ValueError, match="finite"):
summarize([replace(ROW, feedback_quantity_m2=quantity)])
def test_service_reads_once_and_preserves_boundary_timezones():
gateway = Mock()
gateway.get_confirmations.return_value = [ROW]
summary = ShiftProductionService(gateway).summarize(
workplace=" arbitrary-workplace ",
start=START,
end=END,
)
gateway.get_confirmations.assert_called_once_with(workplace=ROW.workplace, start=START, end=END)
assert summary == summarize([ROW])
assert summary.start.tzinfo is summary.end.tzinfo is BERLIN
assert summary.items[0].first_confirmation_at.tzinfo is BERLIN
def test_gateway_errors_propagate():
gateway = Mock()
gateway.get_confirmations.side_effect = ErpReadError("ERP production confirmation read failed")
with pytest.raises(ErpReadError, match="read failed"):
ShiftProductionService(gateway).summarize(workplace=ROW.workplace, start=START, end=END)
def test_dst_fold_order_and_window_compare_instants_without_changing_timestamps():
start = datetime(2026, 10, 25, 2, 15, tzinfo=BERLIN, fold=0)
end = datetime(2026, 10, 25, 2, 45, tzinfo=BERLIN, fold=1)
early = datetime(2026, 10, 25, 2, 30, tzinfo=BERLIN, fold=0)
late = early.replace(fold=1)
summary = summarize(
[
replace(ROW, timestamp=late),
replace(ROW, timestamp=early),
replace(ROW, timestamp=end),
],
start=start,
end=end,
)
assert summary.total_produced_m2 == 388.0
assert summary.items[0].first_confirmation_at is early
assert summary.items[0].last_confirmation_at is late
assert summary.start is start and summary.end is end
def test_aware_other_timezone_compares_same_instants_without_rewriting():
instant = START.astimezone(UTC)
summary = summarize([replace(ROW, timestamp=instant)])
assert summary.items[0].first_confirmation_at is instant
assert summary.start is START
+238
View File
@@ -0,0 +1,238 @@
from copy import deepcopy
from dataclasses import FrozenInstanceError
from datetime import UTC, date, timedelta
from pathlib import Path
import pytest
import yaml
from production_analytics.calculations.shift_downtime import (
ClippedShiftDowntimeEvent,
ShiftDowntimeEvent,
ShiftDowntimeReason,
ShiftDowntimeSummary,
)
from production_analytics.calculations.shift_material import ShiftMaterialItem, ShiftMaterialSummary
from production_analytics.calculations.shift_production import (
ShiftProductionItem,
ShiftProductionSummary,
)
from production_analytics.calculations.shift_report import shift_report_window
from production_analytics.calculations.shift_speed import aggregate_shift_speed
from production_analytics.service.shift_report import ShiftReportService
from production_analytics.service.shift_report_config import load_shift_report_machines
CONFIG_PATH = Path(__file__).resolve().parents[1] / "config/shift-report-machines.yaml"
START, END = shift_report_window(date(2026, 10, 7), "early")
class Stub:
def __init__(self, name, result, calls):
self.name, self.result, self.calls = name, result, calls
self.error = None
def summarize(self, **kwargs):
self.calls.append((self.name, kwargs))
if self.error is not None:
raise self.error
return self.result
def composition(name="B1"):
machines = load_shift_report_machines(CONFIG_PATH)
config = machines[name]
calls = []
production = ShiftProductionSummary(
START, END, config.erp_workplace, 123, 1,
(ShiftProductionItem("order", "article", "description", 123, 1, START, START),),
)
reasons = tuple(
ShiftDowntimeReason(str(index), reason_name, "description", "group", "category",
duration, 1)
for index, (reason_name, duration) in enumerate(
[(None, 100), ("Stop", 90), (" ", 80), ("Other", 70)]
)
)
source = ShiftDowntimeEvent("event", config.machine_id, START,
START + timedelta(seconds=100), None, None, None, None, None, None)
event = ClippedShiftDowntimeEvent(source, START, source.source_end, 100)
downtime = ShiftDowntimeSummary(config.machine_id, START, END, 28800, 100, 28700,
(event,), reasons)
channel = config.material.mode == "channel"
item = ShiftMaterialItem(
source="channel_material_consumption_snapshots" if channel
else "material_consumption_snapshots",
calculation_id=config.material.calculation_ids[0], machine_id=config.machine_id,
production_order="order", run_id="run", consumption_kg=42,
baseline_timestamp=START, end_timestamp=END - timedelta(seconds=1),
baseline_missing=False, extruder="Ex1" if channel else None,
doser_channel="C2" if channel else None, material_name=None,
material_mapping_status="UNAVAILABLE" if channel else None,
)
materials = ShiftMaterialSummary(config.machine_id, START, END, 42, (item,))
speed = aggregate_shift_speed([], config=config.speed, start=START, end=END)
stubs = {key: Stub(key, value, calls) for key, value in [
("production", production), ("downtime", downtime), ("materials", materials),
("channel_materials", materials), ("speed", speed),
]}
service = ShiftReportService(machines=machines, **stubs)
return service, stubs, calls, config
@pytest.mark.parametrize("name,workplace,mode,ids", [
("B1", "BENTO 1", "materials",
("bento1-fresh-bentonite-consumption", "bento1-spreader3-consumption")),
("E1", "1568705", "channel_materials", ("e1-channel-material-consumption",)),
("K7", "K7", "materials", ("k7-fiber-consumption",)),
])
def test_machine_composition(name, workplace, mode, ids):
service, stubs, calls, config = composition(name)
report = service.build(machine_name=name, start=START, end=END)
assert calls == [
("production", {"workplace": workplace, "start": START, "end": END}),
("downtime", {"machine_id": config.machine_id, "start": START, "end": END}),
(mode, {"machine_id": config.machine_id, "calculation_ids": ids,
"start": START, "end": END}),
("speed", {"config": config.speed, "start": START, "end": END}),
]
assert report.machine_name == name and report.machine_id == config.machine_id
assert report.production is stubs["production"].result
assert report.downtime is stubs["downtime"].result
assert report.materials is stubs[mode].result
assert report.speed is stubs["speed"].result
assert report.materials.items[0].consumption_kg == 42
assert report.materials.items[0].material_name is None
if name == "E1":
assert report.materials.items[0].extruder == "Ex1"
assert report.materials.items[0].doser_channel == "C2"
assert report.materials.items[0].material_mapping_status == "UNAVAILABLE"
assert report.downtime.non_downtime_seconds == 28700
assert report.downtime_event_count == 1
assert report.production.items[0].article_description == "description"
with pytest.raises(FrozenInstanceError):
report.machine_name = "other"
def test_top_three_and_fallback_preserve_reason_metadata_and_order():
service, stubs, _, _ = composition()
report = service.build(machine_name="B1", start=START, end=END)
assert len(report.downtime_reasons) == 4
assert len(report.top_downtime_reasons) == 3
assert [reason.display_name for reason in report.top_downtime_reasons] == [
"Ohne Stillstandsgrund", "Stop", "Ohne Stillstandsgrund",
]
for index, view in enumerate(report.top_downtime_reasons):
assert view.reason is stubs["downtime"].result.reasons[index]
assert view.reason.duration_seconds == [100, 90, 80][index]
assert view.reason.reason_description == "description"
assert report.downtime.reasons[0].reason_name is None
with pytest.raises(FrozenInstanceError):
report.top_downtime_reasons[0].display_name = "changed"
def test_legitimate_empty_sources_are_kept():
service, stubs, _, config = composition()
stubs["production"].result = ShiftProductionSummary(START, END, config.erp_workplace, 0, 0, ())
stubs["downtime"].result = ShiftDowntimeSummary(config.machine_id, START, END, 28800,
0, 28800, (), ())
stubs["materials"].result = ShiftMaterialSummary(config.machine_id, START, END, 0, ())
report = service.build(machine_name="B1", start=START, end=END)
assert report.production.items == () and report.production.total_produced_m2 == 0
assert report.materials.items == () and report.materials.total_consumption_kg == 0
assert report.speed.average_line_speed_m_min is None
assert report.top_downtime_reasons == ()
assert report.downtime_event_count == 0
@pytest.mark.parametrize("name,stage", [
("B1", "production"), ("B1", "downtime"), ("B1", "materials"),
("E1", "channel_materials"), ("K7", "speed"),
])
def test_mandatory_failures_propagate_without_reading_later_sources(name, stage):
service, stubs, calls, _ = composition(name)
error = RuntimeError("source failed")
stubs[stage].error = error
with pytest.raises(RuntimeError) as caught:
service.build(machine_name=name, start=START, end=END)
assert caught.value is error
assert calls[-1][0] == stage
sequence = ["production", "downtime",
"channel_materials" if name == "E1" else "materials", "speed"]
assert [call[0] for call in calls] == sequence[:sequence.index(stage) + 1]
@pytest.mark.parametrize("start,end", [
(START.replace(tzinfo=None), END), (START, END.replace(tzinfo=None)),
(START, START), (END, START),
])
def test_invalid_window_precedes_source_calls(start, end):
service, _, calls, _ = composition()
with pytest.raises(ValueError):
service.build(machine_name="B1", start=start, end=end)
assert calls == []
def test_unknown_machine_precedes_source_calls():
service, _, calls, _ = composition()
with pytest.raises(ValueError, match="Unknown"):
service.build(machine_name="unknown", start=START, end=END)
assert calls == []
def test_utc_input_is_normalized_to_berlin_without_changing_instants():
service, _, calls, _ = composition()
report = service.build(machine_name="B1", start=START.astimezone(UTC), end=END.astimezone(UTC))
assert report.start.tzinfo.key == "Europe/Berlin"
assert report.start == START and report.end == END
assert all(call[1]["start"].tzinfo.key == "Europe/Berlin" for call in calls)
@pytest.mark.parametrize("shift,hours", [
("early", (6, 14)), ("late", (14, 22)), ("night", (22, 6)),
])
def test_shift_windows(shift, hours):
start, end = shift_report_window(date(2026, 10, 7), shift)
assert (start.hour, end.hour) == hours
expected_end_day = date(2026, 10, 8) if shift == "night" else start.date()
assert end.date() == expected_end_day
assert (end.astimezone(UTC) - start.astimezone(UTC)).total_seconds() == 28800
@pytest.mark.parametrize("day,hours", [(date(2026, 3, 28), 7), (date(2026, 10, 24), 9)])
def test_night_shift_dst_elapsed_duration(day, hours):
start, end = shift_report_window(day, "night")
assert (end.astimezone(UTC) - start.astimezone(UTC)).total_seconds() == hours * 3600
@pytest.mark.parametrize("mutation", [
lambda d: d["machines"]["B1"].pop("erp_workplace"),
lambda d: d["machines"]["B1"].update(unknown=True),
lambda d: d["machines"]["B1"]["material"].update(mode="erp"),
lambda d: d["machines"]["B1"]["material"].update(calculation_ids=[]),
lambda d: d["machines"]["B1"]["material"].update(calculation_ids="calc"),
lambda d: d["machines"]["B1"]["material"].update(calculation_ids=["calc", "calc"]),
lambda d: d["machines"]["B1"]["material"].update(calculation_ids=[None]),
lambda d: d["machines"]["B1"]["material"].update(extra=True),
lambda d: d["machines"]["B1"]["speed"].pop("signal_ref"),
lambda d: d["machines"]["B1"]["speed"].update(extra=True),
lambda d: d["machines"]["B1"]["speed"].update(signal=" "),
lambda d: d["machines"]["B1"]["speed"].update(unit="rpm"),
lambda d: d["machines"]["B1"]["speed"].update(production_gate_m_min=float("nan")),
lambda d: d["machines"]["E1"].update(machine_id=d["machines"]["B1"]["machine_id"]),
lambda d: d["machines"]["B1"].update(erp_workplace=1568705),
lambda d: d.update(extra=True),
])
def test_strict_configuration(tmp_path, mutation):
document = deepcopy(yaml.safe_load(CONFIG_PATH.read_text()))
mutation(document)
path = tmp_path / "machines.yaml"
path.write_text(yaml.safe_dump(document))
with pytest.raises(ValueError):
load_shift_report_machines(path)
def test_duplicate_yaml_keys_rejected(tmp_path):
path = tmp_path / "machines.yaml"
path.write_text("machines: {}\nmachines: {}\n")
with pytest.raises(ValueError, match="unique"):
load_shift_report_machines(path)
+215
View File
@@ -0,0 +1,215 @@
from dataclasses import FrozenInstanceError, replace
from datetime import UTC, datetime, timedelta
from pathlib import Path
from unittest.mock import Mock
from zoneinfo import ZoneInfo
import pytest
from production_analytics.calculations.shift_speed import (
ShiftSpeedConfig,
ShiftSpeedSample,
aggregate_shift_speed,
)
from production_analytics.enlyze.gateway import EnlyzeApiGateway
from production_analytics.service.shift_report_config import load_shift_report_machines
from production_analytics.service.shift_speed import ShiftSpeedService
START = datetime(2026, 10, 7, 6, tzinfo=ZoneInfo("Europe/Berlin"))
END = START + timedelta(hours=8)
CONFIG = ShiftSpeedConfig("machine", "speed", 0.5)
CONFIG_PATH = Path(__file__).resolve().parents[1] / "config/shift-report-machines.yaml"
def summarize(values, **kwargs):
return aggregate_shift_speed(
[ShiftSpeedSample(START + timedelta(seconds=index), value)
for index, value in enumerate(values)],
config=CONFIG, start=START, end=END, **kwargs,
)
def test_active_filtering_counts_and_statistics():
summary = summarize([0, -1, 0.2, 0.5, 1, 2, 6, None, float("nan"),
float("inf"), -float("inf"), "3", True, 10**1000])
assert summary.sample_count == 7
assert summary.active_sample_count == 3
assert summary.inactive_sample_count == 4
assert summary.invalid_sample_count == 7
assert summary.average_line_speed_m_min == 3
assert summary.minimum_active_speed_m_min == 1
assert summary.maximum_active_speed_m_min == 6
assert summary.machine_id == CONFIG.machine_id
assert summary.speed_signal_ref == CONFIG.speed_signal_ref
assert summary.production_gate_m_min == 0.5
assert summary.unit == "m/min"
with pytest.raises(FrozenInstanceError):
summary.sample_count = 1
with pytest.raises(FrozenInstanceError):
CONFIG.production_gate_m_min = 0
@pytest.mark.parametrize("values", [[], [None, float("nan")], [-1, 0, 0.5]])
def test_no_active_samples(values):
summary = summarize(values)
assert summary.active_sample_count == 0
assert summary.average_line_speed_m_min is None
assert summary.minimum_active_speed_m_min is None
assert summary.maximum_active_speed_m_min is None
def test_sample_mean_is_not_time_weighted():
samples = [ShiftSpeedSample(START, 1), ShiftSpeedSample(END - timedelta(seconds=1), 9)]
summary = aggregate_shift_speed(samples, config=CONFIG, start=START, end=END)
assert summary.average_line_speed_m_min == 5
def test_exact_boundaries_and_missing_timestamps():
samples = [
ShiftSpeedSample(START - timedelta(microseconds=1), 100),
ShiftSpeedSample(START, 2),
ShiftSpeedSample(END - timedelta(microseconds=1), 4),
ShiftSpeedSample(END, 200),
ShiftSpeedSample(END + timedelta(seconds=1), None),
ShiftSpeedSample(None, 10),
ShiftSpeedSample(START.replace(tzinfo=None), 10),
]
summary = aggregate_shift_speed(samples, config=CONFIG, start=START, end=END)
assert summary.average_line_speed_m_min == 3
assert summary.sample_count == 2
assert summary.invalid_sample_count == 2
@pytest.mark.parametrize("start,end", [
(START.replace(tzinfo=None), END), (START, END.replace(tzinfo=None)),
(START, START), (END, START),
])
def test_invalid_windows_fail_before_gateway(start, end):
gateway = Mock()
with pytest.raises(ValueError):
ShiftSpeedService(gateway).summarize(config=CONFIG, start=start, end=end)
gateway.get_speed_samples.assert_not_called()
with pytest.raises(ValueError):
aggregate_shift_speed([], config=CONFIG, start=start, end=end)
client = Mock()
with pytest.raises(ValueError):
EnlyzeApiGateway(client).get_speed_samples(
machine_id="machine", speed_signal_ref="speed", start=start, end=end,
)
client.post_json.assert_not_called()
def test_dst_fold_compares_elapsed_instants():
berlin = ZoneInfo("Europe/Berlin")
start = datetime(2026, 10, 25, 2, 30, tzinfo=berlin, fold=0)
end = start.replace(fold=1)
samples = [ShiftSpeedSample(start, 2),
ShiftSpeedSample(datetime(2026, 10, 25, 1, 20, tzinfo=UTC), 4),
ShiftSpeedSample(end, 100)]
summary = aggregate_shift_speed(samples, config=CONFIG, start=start, end=end)
assert summary.average_line_speed_m_min == 3
assert summary.active_sample_count == 2
@pytest.mark.parametrize("gate", [-1, None, True, "0.5", float("nan"), float("inf")])
def test_invalid_gate_rejected(gate):
with pytest.raises(ValueError):
replace(CONFIG, production_gate_m_min=gate)
def test_zero_gate_excludes_zero_and_negative():
summary = aggregate_shift_speed(
[ShiftSpeedSample(START, value) for value in [-1, 0, 1]],
config=replace(CONFIG, production_gate_m_min=0), start=START, end=END,
)
assert summary.active_sample_count == 1
assert summary.average_line_speed_m_min == 1
def test_large_finite_speeds_do_not_overflow_mean():
assert summarize([1e308, 1e308]).average_line_speed_m_min == 1e308
def test_service_composes_gateway_and_propagates_read_failure():
gateway = Mock()
gateway.get_speed_samples.return_value = [ShiftSpeedSample(START, 2)]
service = ShiftSpeedService(gateway)
assert service.summarize(config=CONFIG, start=START, end=END).average_line_speed_m_min == 2
gateway.get_speed_samples.assert_called_once_with(
machine_id="machine", speed_signal_ref="speed", start=START, end=END,
)
gateway.get_speed_samples.side_effect = RuntimeError("read failed")
with pytest.raises(RuntimeError, match="read failed"):
service.summarize(config=CONFIG, start=START, end=END)
def page(records, cursor=None, columns=None):
return Mock(body={"data": {"columns": columns or ["time", "speed"], "records": records},
"metadata": {"next_cursor": cursor}})
def test_gateway_pagination_column_order_and_unavailable_samples():
client = Mock()
client.post_json.side_effect = [
page([[2, START.isoformat()], [None, START.isoformat()]], "next", ["speed", "time"]),
page([[START.isoformat(), 4], [START.isoformat(), float("nan")],
["invalid-time", 3], None, [START.isoformat()]]),
]
summary = ShiftSpeedService(EnlyzeApiGateway(client)).summarize(
config=CONFIG, start=START, end=END,
)
assert summary.average_line_speed_m_min == 3
assert summary.sample_count == 2
assert summary.invalid_sample_count == 5
body = {"machine": "machine", "start": START.astimezone(UTC).isoformat(),
"end": END.astimezone(UTC).isoformat(), "variables": [{"uuid": "speed"}]}
assert client.post_json.call_args_list[0].args == ("/v2/timeseries", body)
assert client.post_json.call_args_list[1].args == ("/v2/timeseries", {**body, "cursor": "next"})
@pytest.mark.parametrize("body", [
{"data": {"columns": ["time"], "records": []}},
{"data": {"columns": ["time", "speed", "speed"], "records": []}},
{"data": {"columns": ["time", "speed"], "records": None}},
{"data": {"columns": ["time", "speed"], "records": []}, "metadata": {}},
])
def test_gateway_structural_errors_fail_read(body):
client = Mock()
client.post_json.return_value = Mock(body=body)
with pytest.raises(ValueError, match="Invalid speed timeseries response"):
EnlyzeApiGateway(client).get_speed_samples(
machine_id="machine", speed_signal_ref="speed", start=START, end=END,
)
def test_gateway_repeated_cursor_rejected():
client = Mock()
client.post_json.side_effect = [page([], "same"), page([], "same")]
with pytest.raises(ValueError, match="already been followed"):
EnlyzeApiGateway(client).get_speed_samples(
machine_id="machine", speed_signal_ref="speed", start=START, end=END,
)
assert client.post_json.call_count == 2
@pytest.mark.parametrize("name,machine,signal,gate", [
("B1", "5f42a4f6-9ca0-4f6f-9786-40d50a35b230", "fef41976-1103-4090-b780-eaeecc02fdfa", 0.3),
("E1", "8302e3d1-b1e5-42f1-8540-615eb6c73e08", "488e28a9-79a6-44c4-9cc2-c021bb2108ec", 0.5),
("K7", "c220f95c-a65e-4cb7-99b7-0626d6c7508c", "823867bb-f5d2-40eb-b875-657155addfd0", 0.5),
])
def test_validated_machine_configuration(name, machine, signal, gate):
config = load_shift_report_machines(CONFIG_PATH)[name].speed
assert config.machine_id == machine
assert config.speed_signal_ref == signal
assert config.production_gate_m_min == gate
assert config.unit == "m/min"
assert config.signal
@pytest.mark.parametrize("document", ["machines: {}", "other: {}", "machines: []",
"machines:\n B1: {}", "machines:\n B1: null"])
def test_invalid_configuration(tmp_path, document):
path = tmp_path / "machines.yaml"
path.write_text(document)
with pytest.raises(ValueError):
load_shift_report_machines(path)