318 lines
11 KiB
Python
318 lines
11 KiB
Python
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)
|