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)