from copy import deepcopy 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 import yaml from production_analytics.calculations.shift_speed import ( NumericDwellGate, 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_boolean_gate_uses_status_instead_of_numeric_threshold(): config = replace(CONFIG, production_gate_m_min=None, running_signal_ref="status", running_when=False) samples = [ShiftSpeedSample(START + timedelta(seconds=i), speed, status) for i, (speed, status) in enumerate([ (0, False), (0.2, False), (8, True), (4, False), (6, None), (7, 0), (9, "false"), (None, False), ])] summary = aggregate_shift_speed(samples, config=config, start=START, end=END) assert (summary.sample_count, summary.active_sample_count, summary.inactive_sample_count, summary.invalid_sample_count) == (4, 3, 1, 4) assert summary.average_line_speed_m_min == pytest.approx(4.2 / 3) assert summary.minimum_active_speed_m_min == 0 assert summary.maximum_active_speed_m_min == 4 def test_boolean_gate_defaults_to_true_and_unweighted_mean(): config = replace(CONFIG, production_gate_m_min=None, running_signal_ref="status") samples = [ShiftSpeedSample(START, 1, True), ShiftSpeedSample(END - timedelta(seconds=1), 9, True), ShiftSpeedSample(START, 100, False)] summary = aggregate_shift_speed(samples, config=config, start=START, end=END) assert summary.average_line_speed_m_min == 5 assert summary.inactive_sample_count == 1 DWELL = NumericDwellGate("gate", 50, "below", 150) def dwell_summary(rows, gate=DWELL): config = replace(CONFIG, production_gate_m_min=None, numeric_dwell_gate=gate) samples = [ShiftSpeedSample(START + timedelta(seconds=second), speed, gate_value=value) for second, speed, value in rows] return aggregate_shift_speed(samples, config=config, start=START, end=END) @pytest.mark.parametrize("duration,expected_inactive", [(149, 0), (150, 2), (230, 2)]) def test_dwell_duration_includes_first_crossing(duration, expected_inactive): summary = dwell_summary([(-1, 1, 50), (0, 2, 49), (duration - 1, 4, 49), (duration, 8, 50)]) assert summary.inactive_sample_count == expected_inactive assert summary.active_sample_count == 3 - expected_inactive assert summary.average_line_speed_m_min == (8 if expected_inactive else 14 / 3) def test_separate_short_excursions_do_not_merge_and_equality_is_active(): summary = dwell_summary([(-10, 1, 50), (0, 2, 49), (80, 3, 50), (100, 4, 49), (200, 5, 50)]) assert summary.active_sample_count == 4 assert summary.inactive_sample_count == 0 assert summary.average_line_speed_m_min == 3.5 def test_irregular_timestamps_use_elapsed_time_and_arithmetic_mean(): summary = dwell_summary([(-5, 1, 50), (0, 2, 49), (7, 4, 49), (149, 6, 49), (150, 8, 50), (200, 10, 50)]) assert summary.inactive_sample_count == 3 assert summary.average_line_speed_m_min == 9 @pytest.mark.parametrize("bad", [None, float("nan"), float("inf"), "49", True]) def test_invalid_dwell_gate_breaks_interval_and_excludes_speed(bad): summary = dwell_summary([(-1, 1, 50), (0, 2, 49), (50, 3, bad), (100, 4, 49), (200, 5, 50)]) assert summary.active_sample_count == 1 assert summary.invalid_sample_count == 3 assert summary.average_line_speed_m_min == 5 def test_open_short_dwell_interval_is_unknown_at_window_boundary(): summary = dwell_summary([(0, 2, 49), (10, 4, 49)]) assert summary.sample_count == 0 assert summary.invalid_sample_count == 2 def test_dwell_uses_both_sides_of_window_for_classification(): summary = dwell_summary([(-150, 1, 49), (0, 2, 49), (30, 4, 50), (END.timestamp() - START.timestamp() - 1, 6, 49), (END.timestamp() - START.timestamp() + 149, 8, 50)]) assert summary.inactive_sample_count == 2 assert summary.active_sample_count == 1 assert summary.average_line_speed_m_min == 4 @pytest.mark.parametrize("changes", [ {"running_signal_ref": ""}, {"running_signal_ref": "speed"}, {"running_signal_ref": 123}, {"running_when": 0}, {"production_gate_m_min": None}, ]) def test_invalid_boolean_configuration_rejected(changes): with pytest.raises(ValueError): replace(CONFIG, **changes) 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"}) def test_gateway_two_variable_response_and_single_request(): client = Mock() client.post_json.return_value = page([ [False, 0.2, START.isoformat()], [True, 10, START.isoformat()], [None, 20, START.isoformat()], [START.isoformat()], ], columns=["status", "speed", "time"]) config = replace(CONFIG, production_gate_m_min=None, running_signal_ref="status", running_when=False) summary = ShiftSpeedService(EnlyzeApiGateway(client)).summarize( config=config, start=START, end=END) assert summary.average_line_speed_m_min == 0.2 assert (summary.active_sample_count, summary.inactive_sample_count, summary.invalid_sample_count) == (1, 1, 2) assert client.post_json.call_count == 1 assert client.post_json.call_args.args[1]["variables"] == [ {"uuid": "speed"}, {"uuid": "status"}] def test_gateway_requires_status_column_when_configured(): client = Mock() client.post_json.return_value = page([], columns=["time", "speed"]) with pytest.raises(ValueError, match="required columns"): EnlyzeApiGateway(client).get_speed_samples( machine_id="machine", speed_signal_ref="speed", running_signal_ref="status", start=START, end=END) def test_dwell_gateway_requests_both_signals_with_expanded_window(): client = Mock() client.post_json.return_value = page([ [50, START.isoformat(), 1], [49, (START + timedelta(seconds=10)).isoformat(), 2], [49, (START + timedelta(seconds=160)).isoformat(), 4], [50, (START + timedelta(seconds=170)).isoformat(), 8], ], columns=["gate", "time", "speed"]) config = replace(CONFIG, production_gate_m_min=None, numeric_dwell_gate=DWELL) summary = ShiftSpeedService(EnlyzeApiGateway(client)).summarize( config=config, start=START, end=END) assert summary.average_line_speed_m_min == 4.5 assert summary.inactive_sample_count == 2 assert client.post_json.call_count == 1 body = client.post_json.call_args.args[1] assert body["variables"] == [{"uuid": "speed"}, {"uuid": "gate"}] assert body["start"] == (START - timedelta(seconds=150)).astimezone(UTC).isoformat() assert body["end"] == (END + timedelta(seconds=150)).astimezone(UTC).isoformat() @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("name,speed,gate,threshold", [ ("Gitter 1", "33abccf8-8dee-4b40-b0ce-63c3c0fd2cd9", "620511e3-a46b-47c4-8514-f2d4bde29e2b", 50), ("Gitter 2", "d3acefd8-1013-4b59-a235-fa265fd85fae", "1ae8fb5d-1d25-414a-9181-d35b6cdde507", 27000), ("Gitter 3", "88641764-6fd1-4733-a054-80fa43a62470", "f78bd11f-b2a8-4454-86a0-c8de576799c2", 31000), ("Gitter 4", "1d7660d4-10f4-4466-b1fd-076f9fd504fe", "5685fb13-861d-4e95-8a98-e39d4fc3e059", 2), ]) def test_dwell_machine_configuration(name, speed, gate, threshold): machine = load_shift_report_machines(CONFIG_PATH)[name] assert machine.capabilities.speed and not machine.capabilities.material assert machine.speed.speed_signal_ref == speed assert machine.speed.numeric_dwell_gate.signal_ref == gate assert machine.speed.numeric_dwell_gate.threshold == threshold assert machine.speed.numeric_dwell_gate.comparison == "below" assert machine.speed.numeric_dwell_gate.minimum_duration_seconds == 150 assert machine.speed.running_signal_ref is None assert machine.speed.production_gate_m_min is None def test_k5_boolean_machine_configuration(): config = load_shift_report_machines(CONFIG_PATH)["K5"].speed assert config.speed_signal_ref == "c3ae3002-b75c-4d7c-bb33-f10265fcf428" assert config.running_signal_ref == "507b1225-2992-4dd1-8412-34969466722f" assert config.running_when is False assert config.numeric_dwell_gate is None summary = aggregate_shift_speed([ ShiftSpeedSample(START, 1, False), ShiftSpeedSample(START + timedelta(seconds=1), 9, True), ShiftSpeedSample(START + timedelta(seconds=2), 10, None), ], config=config, start=START, end=END) assert summary.average_line_speed_m_min == 1 assert (summary.active_sample_count, summary.inactive_sample_count, summary.invalid_sample_count) == (1, 1, 1) @pytest.mark.parametrize("change", [ {"running_signal_ref": "status"}, {"running_when": False}, {"production_gate_m_min": 0.5}, {"unexpected": True}, {"numeric_dwell_gate": {"signal_ref": "gate"}}, {"numeric_dwell_gate": {"signal_ref": "gate", "threshold": 50, "comparison": "below", "minimum_duration_seconds": 0}}, {"numeric_dwell_gate": {"signal_ref": "gate", "threshold": float("nan"), "comparison": "below", "minimum_duration_seconds": 150}}, ]) def test_dwell_yaml_validation(tmp_path, change): document = deepcopy(yaml.safe_load(CONFIG_PATH.read_text())) document["machines"]["Gitter 2"]["speed"].update(change) path = tmp_path / "machines.yaml" path.write_text(yaml.safe_dump(document)) with pytest.raises(ValueError): load_shift_report_machines(path) @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)