Extend shift reporting and downtime analytics

This commit is contained in:
admin committed 2026-10-20 14:16:58 +02:00
1 parent 41a5ae7a63
commit 6e8eb6f50f
74 files changed
+5397 -238

No files matched your search

+105 -1
View File
@@ -16,6 +16,7 @@ from production_analytics.calculations.material_consumption import (
area_application_rate_kg_per_hour,
)
from production_analytics.enlyze.gateway import EnlyzeApiGateway, EnlyzeProductionRun
from production_analytics.erp import ErpReadError
from production_analytics.service.material_context import ErpNominalWidthProvider
from production_analytics.service.material_polling import MaterialPollingService
from production_analytics.service.material_state_store import JsonMaterialStateStore
@@ -69,7 +70,7 @@ def test_missing_or_invalid_spreader_fails(bad):
)
def width_provider():
def width_provider(fallback_nominal_width_m=None):
erp = Mock()
erp.get_current_workplace_status.return_value = SimpleNamespace(
workplace='Bento 1', production_order='12026000814', article_number='180305',
@@ -77,9 +78,111 @@ def width_provider():
)
return ErpNominalWidthProvider(
erp, workplace='Bento 1', format_template='Bento 1-{production_order}',
fallback_nominal_width_m=fallback_nominal_width_m,
)
def test_erp_width_takes_priority_over_fallback(caplog):
provider = width_provider(5.0)
provider.gateway.get_current_workplace_status.return_value.article_description = '4,00 x 40 m'
assert provider('Bento 1-12026000814') == 4.0
assert not caplog.records
@pytest.mark.parametrize('fallback', [None, 5.0])
def test_combined_order_width_fallback(fallback, caplog):
provider = width_provider(fallback)
order = 'Bento 1-12026001005-Bento 1-12026001014'
if fallback is None:
with pytest.raises(ValueError, match='ERP context does not match the production order'):
provider(order)
assert not caplog.records
else:
assert provider(order) == 5.0
assert len(caplog.records) == 1
assert caplog.records[0].levelname == 'WARNING'
assert 'ERP nominal-width resolution failed' in caplog.text
assert order in caplog.text
assert 'fallback nominal width 5.0 m' in caplog.text
def test_fallback_warns_once_per_order_per_provider(caplog):
provider = width_provider(5.0)
first_order = 'Bento 1-12026001005-Bento 1-12026001014'
second_order = 'Bento 1-12026001015'
for order in (first_order, first_order, second_order, second_order, first_order):
assert provider(order) == 5.0
assert len(caplog.records) == 2
assert all(record.levelname == 'WARNING' for record in caplog.records)
assert first_order in caplog.records[0].getMessage()
assert second_order in caplog.records[1].getMessage()
# A fresh provider has its own warning history.
assert width_provider(5.0)(first_order) == 5.0
assert len(caplog.records) == 3
def test_erp_resolution_still_runs_after_fallback(caplog):
provider = width_provider(5.0)
order = 'Bento 1-12026000814'
status = provider.gateway.get_current_workplace_status.return_value
status.article_description = None
assert provider(order) == 5.0
status.article_description = '4,00 x 40 m'
assert provider(order) == 4.0
status.article_description = None
assert provider(order) == 5.0
assert len(caplog.records) == 1
@pytest.mark.parametrize('failure', ['missing_status', 'missing_width', 'read_error'])
@pytest.mark.parametrize('fallback', [None, 5.0])
def test_other_erp_width_failures(failure, fallback):
provider = width_provider(fallback)
gateway = provider.gateway
if failure == 'missing_status':
gateway.get_current_workplace_status.return_value = None
elif failure == 'missing_width':
gateway.get_current_workplace_status.return_value.article_description = None
else:
gateway.get_current_workplace_status.side_effect = ErpReadError('ERP read failed')
if fallback is None:
with pytest.raises(ErpReadError if failure == 'read_error' else ValueError):
provider('Bento 1-12026000814')
else:
assert provider('Bento 1-12026000814') == 5.0
@pytest.mark.parametrize('value', [0, -1, float('nan'), float('inf'), -float('inf'),
True, '5.0', None, [], {}])
def test_invalid_fallback_configuration(tmp_path, value):
with open('config/bento1-material-consumption.yaml') as stream:
document = yaml.safe_load(stream)
document['calculations'][0]['fallback_nominal_width_m'] = value
path = tmp_path / 'config.yaml'
path.write_text(yaml.safe_dump(document))
with pytest.raises(CalculationConfigError, match='fallback_nominal_width_m'):
load_material_calculation(path)
@pytest.mark.parametrize('path', [
'config/bento1-material-consumption.yaml',
'config/bento1-spreader3-material-consumption.yaml',
])
def test_bento_fallback_configuration(path):
assert load_material_calculation(path).fallback_nominal_width_m == 5.0
def test_direct_mass_rate_rejects_width_fallback(tmp_path):
with open('config/k7-material-consumption.yaml') as stream:
document = yaml.safe_load(stream)
document['calculations'][0]['fallback_nominal_width_m'] = 5.0
path = tmp_path / 'config.yaml'
path.write_text(yaml.safe_dump(document))
with pytest.raises(CalculationConfigError, match='width-based source mode'):
load_material_calculation(path)
@pytest.mark.parametrize('configured,returned', [
('Bento 1', 'BENTO 1'),
('Bento 1', ' \tBENTO 1\n'),
@@ -195,6 +298,7 @@ def test_bento_rpm_bootstrap_and_persistent_resume(tmp_path, inter_run_gap_secon
def test_k7_config_defaults_remain_direct():
config = load_material_calculation('config/k7-material-consumption.yaml')
assert config.source_mode == 'direct_mass_rate'
assert config.fallback_nominal_width_m is None
assert config.rotational_speed_signal_refs == ()
assert config.application_signal_refs == ()
assert config.gate_threshold == 0.5
+95
View File
@@ -0,0 +1,95 @@
"""Configured downtime runners share the existing machine and order contracts."""
from datetime import timedelta
from pathlib import Path
import pytest
from production_analytics.context import build_enlyze_production_order
from production_analytics.service import downtime_runtime
from production_analytics.service.downtime_runtime import load_downtime_config
from production_analytics.service.shift_report_config import load_shift_report_config
ROOT = Path(__file__).resolve().parents[1]
NEW_RUNNERS = (
("e4", "E4", "12026001013", "E 4-12026001013"),
("gitter1", "Gitter 1", "82026400869", "Gitter 1-82026400869"),
("gitter2", "Gitter 2", "82026400909", "Gitter 2-82026400909"),
("gitter3", "Gitter 3", "82026400900", "Gitter 3-82026400900"),
("gitter4", "Gitter 4", "82026400876", "Gitter 4-82026400876"),
("k5", "K5", "82026400921", "K 5-82026400921"),
("secumat12", "Secumat 1/2", "82026400920", "Sec 1/2-82026400920"),
("secumat3", "Secumat 3", "82026400912", "Sec 3-82026400912"),
)
@pytest.mark.parametrize("slug,name,erp_order,enlyze_order", NEW_RUNNERS)
def test_new_downtime_config_matches_report_machine_and_verified_order(
slug, name, erp_order, enlyze_order,
):
config = load_downtime_config(ROOT / "config" / f"{slug}-downtime.yaml")
report_config = load_shift_report_config(ROOT / "config" / "shift-report-machines.yaml")
machine = report_config.machines[name]
assert (config.machine_id, config.erp_workplace) == (
machine.machine_id, machine.erp_workplace,
)
assert build_enlyze_production_order(erp_order, config.production_order_format) == enlyze_order
assert (config.poll_interval_seconds, config.lookback_hours,
config.full_reconciliation_hours, config.completion_tolerance_m2) == (
300, 48, 24, 0.001,
)
assert machine.capabilities.production and machine.capabilities.downtime
assert not machine.capabilities.material and machine.material is None
speed_enabled = name in {"Gitter 1", "Gitter 2", "Gitter 3", "Gitter 4", "K5"}
assert machine.capabilities.speed is speed_enabled
assert (machine.speed is not None) is speed_enabled
unit = ROOT / "deploy" / "systemd" / f"production-analytics-downtime-{slug}.service"
text = unit.read_text(encoding="utf-8")
assert f"--config {ROOT / 'config' / f'{slug}-downtime.yaml'}" in text
assert "run downtime-reconcile" in text
assert "--secrets-file" in text and "--erp-secrets-file" in text
def test_existing_downtime_configs_and_capabilities_are_unchanged():
machines = load_shift_report_config(ROOT / "config" / "shift-report-machines.yaml").machines
for slug, name in (("bento1", "B1"), ("e1", "E1"), ("k7", "K7")):
config = load_downtime_config(ROOT / "config" / f"{slug}-downtime.yaml")
assert config.machine_id == machines[name].machine_id
assert machines[name].capabilities.downtime
assert (config.poll_interval_seconds, config.lookback_hours,
config.full_reconciliation_hours, config.completion_tolerance_m2) == (
300, 48, 24, 0.001,
)
@pytest.mark.parametrize("slug,name,erp_order,enlyze_order", NEW_RUNNERS)
def test_existing_generic_runtime_builds_each_new_runner(
monkeypatch, slug, name, erp_order, enlyze_order,
):
monkeypatch.setattr(downtime_runtime, "load_secret_file", lambda path: {})
for settings in (downtime_runtime.ExplorationSettings,
downtime_runtime.ErpSettings, downtime_runtime.PostgresSettings):
monkeypatch.setattr(settings, "from_environment", lambda env: object())
runner = downtime_runtime.build_downtime_runner(
ROOT / "config" / f"{slug}-downtime.yaml",
secrets_file=ROOT / "secrets" / "enlyze.env",
erp_secrets_file=ROOT / "secrets" / "erp.env",
)
report_config = load_shift_report_config(ROOT / "config" / "shift-report-machines.yaml")
machine = report_config.machines[name]
assert runner.machine_id == runner.service.machine_id == machine.machine_id
assert runner.service.workplace == machine.erp_workplace
assert runner.interval == 300
assert runner.service.lookback == timedelta(hours=48)
assert runner.service.full_reconciliation_interval == timedelta(hours=24)
assert runner.service.tolerance == 0.001
assert build_enlyze_production_order(
erp_order, runner.service.production_order_format) == enlyze_order
def test_only_expected_machines_have_downtime_enabled():
machines = load_shift_report_config(ROOT / "config" / "shift-report-machines.yaml").machines
assert {name for name, config in machines.items() if config.capabilities.downtime} == {
"B1", "E1", "K7", *(name for _, name, _, _ in NEW_RUNNERS),
}
+76
View File
@@ -0,0 +1,76 @@
import traceback
from decimal import Decimal
from unittest.mock import MagicMock
import pytest
from test_erp_gateway import ENV
from production_analytics.erp import ErpFiberBookingGateway, ErpReadError, ErpSettings
@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 = [("12026000994 ", "41070418 ", "Fiber ", Decimal("6877.80"))]
return connect, connection, cursor
def gateway():
return ErpFiberBookingGateway(ErpSettings.from_environment(ENV))
def test_order_query_is_parameterized_positive_and_not_shift_bounded(db):
connect, connection, cursor = db
rows = gateway().get_fiber_bookings("12026000994")
assert len(rows) == 1
assert rows[0].production_order == "12026000994"
assert rows[0].material_number == "41070418"
assert rows[0].material_name == "Fiber"
assert rows[0].quantity_kg == 6877.8
sql, parameters = cursor.execute.call_args.args
assert parameters == ("12026000994",)
assert "[Fertigungsauftragsnummer] = %s" in sql
assert "[Fasermenge] > 0" in sql
assert "NULLIF(LTRIM(RTRIM([Rohstoffnummer])), '') IS NOT NULL" in sql
assert "Zeitstempel" not in sql
assert "12026000994" not in sql
connect.assert_called_once_with(
server="localhost",
port=49601,
database="NV_DWH",
user=ENV["ERP_DB_USER"],
password=ENV["ERP_DB_PASSWORD"],
login_timeout=10,
timeout=10,
)
connection.commit.assert_not_called()
connection.cursor.return_value.__exit__.assert_called_once()
connect.return_value.__exit__.assert_called_once()
def test_no_rows_returns_empty(db):
db[2].fetchall.return_value = []
assert gateway().get_fiber_bookings("123") == []
@pytest.mark.parametrize("order", [None, "", " ", "\x00"])
def test_invalid_order_rejected_before_connect(db, order):
with pytest.raises(ValueError):
gateway().get_fiber_bookings(order)
db[0].assert_not_called()
def test_read_failure_does_not_expose_credentials(db):
db[2].execute.side_effect = RuntimeError(ENV["ERP_DB_PASSWORD"])
with pytest.raises(ErpReadError, match="read failed") as caught:
gateway().get_fiber_bookings("123")
assert ENV["ERP_DB_PASSWORD"] not in "".join(traceback.format_exception(caught.value))
def test_invalid_numeric_row_rejected(db):
db[2].fetchall.return_value = [("123", "M1", "Fiber", float("nan"))]
with pytest.raises(ErpReadError, match="invalid row"):
gateway().get_fiber_bookings("123")
+33
View File
@@ -108,6 +108,39 @@ def test_exact_parameterized_workplace_and_half_open_window(db):
assert "[Rückmeldemenge] >" not in sql
@pytest.mark.parametrize("timezone_name,expected_utc_hour", [
("Europe/Berlin", 6), ("Asia/Kuala_Lumpur", 0),
])
def test_explicit_site_timezone_interprets_naive_sql_rows(
db, timezone_name, expected_utc_hour,
):
timezone = ZoneInfo(timezone_name)
start = datetime(2026, 10, 19, 6, tzinfo=timezone)
end = datetime(2026, 10, 19, 14, tzinfo=timezone)
local_row = datetime(2026, 10, 19, 8, 20)
db[2].fetchall.return_value = [(*ROW[:2], local_row, *ROW[3:])]
confirmation = read(start=start.astimezone(UTC), end=end.astimezone(UTC),
timezone=timezone)[0]
assert db[2].execute.call_args.args[1] == (
"BENTO 1", datetime(2026, 10, 19, 6), datetime(2026, 10, 19, 14),
)
assert confirmation.timestamp == local_row.replace(tzinfo=timezone)
assert confirmation.timestamp.tzinfo is timezone
assert confirmation.timestamp.astimezone(UTC).hour == expected_utc_hour
def test_malaysia_evening_confirmation_remains_local_evening(db):
malaysia = ZoneInfo("Asia/Kuala_Lumpur")
local_row = datetime(2026, 10, 19, 18)
db[2].fetchall.return_value = [(*ROW[:2], local_row, *ROW[3:])]
confirmation = read(
start=datetime(2026, 10, 19, 14, tzinfo=malaysia),
end=datetime(2026, 10, 19, 22, tzinfo=malaysia), timezone=malaysia,
)[0]
assert confirmation.timestamp.hour == 18
assert confirmation.timestamp.astimezone(UTC) == datetime(2026, 10, 19, 10, tzinfo=UTC)
def test_half_open_boundaries_with_query_simulation(db):
rows = [
tuple([*ROW[:2], timestamp, *ROW[3:]])
+250
View File
@@ -0,0 +1,250 @@
from dataclasses import replace
from math import fsum
from unittest.mock import Mock
import pytest
from test_shift_report import END, START, composition
from production_analytics.calculations.fiber_allocation import (
FiberBooking,
allocate_fiber_materials,
)
from production_analytics.calculations.shift_material import ShiftMaterialSummary
from production_analytics.presentation.shift_report import (
MaterialPieBlock,
TableBlock,
present_report,
render_pdf,
)
from production_analytics.service.fiber_allocation import K7FiberAllocationService
ORDER = "12026000994"
NAMES = ("PP 1A, weiß, 6,0, hf - 90- Drittland", "PP 1A, weiß, 6,0, hf - 90")
BOOKINGS = (
FiberBooking(ORDER, "41070418", NAMES[0], 6878),
FiberBooking(ORDER, "41070419", NAMES[1], 3122),
)
def measured_item(order=f"K 7-{ORDER}", quantity=3468.77):
_, stubs, _, _ = composition("K7")
return replace(
stubs["materials"].result.items[0], production_order=order, consumption_kg=quantity
)
def test_ratios_allocate_measured_mass_without_rounding():
item = measured_item()
allocated = allocate_fiber_materials(item, BOOKINGS, erp_order=ORDER)
assert [value.material_number for value in allocated] == ["41070418", "41070419"]
assert [value.erp_booking_share for value in allocated] == pytest.approx([0.6878, 0.3122])
assert [value.consumption_kg for value in allocated] == pytest.approx(
[2385.819006, 1082.950994]
)
assert fsum(value.consumption_kg for value in allocated) == pytest.approx(item.consumption_kg)
assert allocated[0].consumption_kg != pytest.approx(item.consumption_kg * 0.69)
assert all(value.baseline_timestamp == item.baseline_timestamp for value in allocated)
assert all(value.end_timestamp == item.end_timestamp for value in allocated)
assert all(value.baseline_missing == item.baseline_missing for value in allocated)
assert item.material_number is None
def test_duplicate_bookings_aggregate_by_number_and_name():
allocated = allocate_fiber_materials(
measured_item(),
[
FiberBooking(ORDER, "M1", "Fiber", 20),
FiberBooking(ORDER, "M1", "Fiber", 30),
FiberBooking(ORDER, "M2", "Fiber", 50),
],
erp_order=ORDER,
)
assert len(allocated) == 2
assert [item.material_number for item in allocated] == ["M1", "M2"]
assert [item.erp_booking_share for item in allocated] == [0.5, 0.5]
@pytest.mark.parametrize(
"bookings",
[
[],
[FiberBooking(ORDER, "181900", "Product", 0)],
[
FiberBooking(ORDER, "M1", "Fiber", -1),
FiberBooking(ORDER, "", "Fiber", 10),
FiberBooking(ORDER, None, "Fiber", 10),
FiberBooking(ORDER, "M1", "Fiber", None),
],
],
)
def test_no_usable_bookings_preserves_unassigned_measured_item(bookings):
item = measured_item()
assert allocate_fiber_materials(item, bookings, erp_order=ORDER) == (item,)
def test_invalid_rows_ignored_and_single_material_has_full_share():
allocated = allocate_fiber_materials(
measured_item(),
[
FiberBooking(ORDER, "M1", "Fiber", 25),
FiberBooking(ORDER, "M2", "Fiber", 0),
FiberBooking(ORDER, "M3", "Fiber", -10),
FiberBooking(ORDER, " ", "Fiber", 100),
FiberBooking(ORDER, "M4", "Fiber", float("nan")),
FiberBooking("other", "M5", "Fiber", 1000),
],
erp_order=ORDER,
)
assert len(allocated) == 1
assert allocated[0].material_number == "M1"
assert allocated[0].erp_booking_share == 1
assert allocated[0].consumption_kg == 3468.77
def test_order_aware_service_preserves_totals_runs_and_caches_order_reads():
reader = Mock()
reader.get_fiber_bookings.side_effect = lambda order: (
BOOKINGS if order == ORDER else [FiberBooking(order, "M3", "Other fiber", 1)]
)
items = (
measured_item(quantity=100),
replace(measured_item(quantity=200), run_id="run2"),
measured_item("K 7-123", 400),
)
measured = ShiftMaterialSummary(items[0].machine_id, START, END, 700, items)
allocated = K7FiberAllocationService(reader).allocate(measured)
assert allocated.total_consumption_kg == measured.total_consumption_kg
assert fsum(item.consumption_kg for item in allocated.items) == pytest.approx(700)
assert len(allocated.items) == 5
assert allocated.items[-1].material_number == "M3"
assert allocated.items[-1].production_order == "K 7-123"
assert reader.get_fiber_bookings.call_count == 2
assert measured.items == items
@pytest.mark.parametrize("order", ["K 7-123-K 7-456", "unknown", ""])
def test_ambiguous_order_never_queries_or_invents_recipe(order):
reader = Mock()
item = measured_item(order)
measured = ShiftMaterialSummary(item.machine_id, START, END, item.consumption_kg, (item,))
allocated = K7FiberAllocationService(reader).allocate(measured)
assert allocated.items == measured.items
reader.get_fiber_bookings.assert_not_called()
@pytest.mark.parametrize("machine", ["B1", "E1", "K7"])
def test_report_wiring_applies_adapter_only_to_k7(machine):
service, stubs, _, _ = composition(machine)
reader = Mock()
reader.get_fiber_bookings.return_value = BOOKINGS
service.material_allocators = {"K7": K7FiberAllocationService(reader)}
stubs["materials"].result = (
replace(stubs["materials"].result, items=(measured_item(quantity=42),))
if machine == "K7"
else stubs["materials"].result
)
value = service.build(machine_name=machine, start=START, end=END)
if machine == "K7":
assert len(value.materials.items) == 2
reader.get_fiber_bookings.assert_called_once_with(ORDER)
else:
reader.get_fiber_bookings.assert_not_called()
assert (
value.materials is stubs["channel_materials" if machine == "E1" else "materials"].result
)
def test_same_allocation_behavior_for_differently_named_machine():
service, stubs, _, config = composition("K7")
service.machines = {"Synthetic": config}
reader = Mock()
reader.get_fiber_bookings.return_value = BOOKINGS
service.material_allocators = {"Synthetic": K7FiberAllocationService(reader)}
item = measured_item(quantity=42)
stubs["materials"].result = replace(stubs["materials"].result, items=(item,))
report = service.build(machine_name="Synthetic", start=START, end=END)
assert len(report.materials.items) == 2
assert sum(part.consumption_kg for part in report.materials.items) == pytest.approx(42)
reader.get_fiber_bookings.assert_called_once_with(ORDER)
def test_pdf_displays_whole_shares_and_estimation_note():
service, stubs, _, _ = composition("K7")
item = measured_item()
stubs["materials"].result = replace(
stubs["materials"].result, items=(item,), total_consumption_kg=item.consumption_kg
)
reader = Mock()
reader.get_fiber_bookings.return_value = BOOKINGS
service.material_allocators = {"K7": K7FiberAllocationService(reader)}
report = service.build(machine_name="K7", start=START, end=END)
blocks = present_report(report)
table = next(
block for block in blocks if isinstance(block, TableBlock) and "ERP-Anteil" in block.headers
)
rows = {row[2]: row for row in table.rows}
assert rows["41070418"][1:] == (NAMES[0], "41070418", "2.385,82 kg", "69%")
assert rows["41070419"][1:] == (NAMES[1], "41070419", "1.082,95 kg", "31%")
assert any(
getattr(block, "text", "")
== "Verbrauchsaufteilung geschätzt nach ERP-Buchungsverhältnis; Gesamtverbrauch aus ENLYZE."
for block in blocks
)
chart = next(block for block in blocks if isinstance(block, MaterialPieBlock))
assert fsum(chart.consumption_kg) == pytest.approx(3468.77)
def test_source_ratios_retain_precision_beyond_displayed_percentage():
bookings = (replace(BOOKINGS[0], quantity_kg=6877.8), replace(BOOKINGS[1], quantity_kg=3122.2))
allocated = allocate_fiber_materials(measured_item(), bookings, erp_order=ORDER)
assert [item.consumption_kg for item in allocated] == pytest.approx(
[2385.7496306, 1083.0203694]
)
assert [f"{item.erp_booking_share * 100:.0f}%" for item in allocated] == ["69%", "31%"]
assert fsum(item.consumption_kg for item in allocated) == pytest.approx(3468.77)
def test_pdf_keeps_different_order_shares_separate_and_combines_material_pie():
service, stubs, _, _ = composition("K7")
items = (measured_item(quantity=100), measured_item("K 7-123", 200))
stubs["materials"].result = replace(
stubs["materials"].result, items=items, total_consumption_kg=300
)
reader = Mock()
reader.get_fiber_bookings.side_effect = lambda order: (
BOOKINGS if order == ORDER else [replace(BOOKINGS[0], production_order=order)]
)
service.material_allocators = {"K7": K7FiberAllocationService(reader)}
report = service.build(machine_name="K7", start=START, end=END)
blocks = present_report(report)
table = next(
block for block in blocks if isinstance(block, TableBlock) and "ERP-Anteil" in block.headers
)
assert len(table.rows) == 3
assert {(row[0], row[-1]) for row in table.rows} == {
(f"K 7-{ORDER}", "69%"),
(f"K 7-{ORDER}", "31%"),
("K 7-123", "100%"),
}
chart = next(block for block in blocks if isinstance(block, MaterialPieBlock))
assert len(chart.labels) == 2
assert sorted(chart.consumption_kg) == pytest.approx([31.22, 268.78])
assert render_pdf(report) == render_pdf(report)
def test_missing_erp_data_keeps_pdf_unassigned_and_measured_total():
service, stubs, _, _ = composition("K7")
stubs["materials"].result = replace(
stubs["materials"].result, items=(measured_item(),), total_consumption_kg=3468.77
)
reader = Mock()
reader.get_fiber_bookings.return_value = []
service.material_allocators = {"K7": K7FiberAllocationService(reader)}
report = service.build(machine_name="K7", start=START, end=END)
table = next(
block
for block in present_report(report)
if isinstance(block, TableBlock) and "Materialname" in block.headers
)
assert table.rows == (("Materialzuordnung fehlt", "–", "3.468,77 kg"),)
assert report.materials.total_consumption_kg == 3468.77
+548
View File
@@ -0,0 +1,548 @@
from dataclasses import replace
from datetime import UTC, datetime
from types import SimpleNamespace
from unittest.mock import MagicMock
import pytest
from production_analytics.enlyze.gateway import EnlyzeProductionRun
from production_analytics.service.historical_reconcile import (
Decision,
HistoricalRecord,
decide,
reconcile_machine,
reconciliation_window,
)
from production_analytics.service.postgres_historical_reconcile import PostgresHistoricalRepository
def at(hour=12):
return datetime(2026, 10, 13, hour, tzinfo=UTC)
def record(order="old", machine="generic"):
return HistoricalRecord("material_consumption_snapshots", ("calc", machine, at()),
machine, at(), order, "retained-counter-run")
def run(order="Machine-123", machine="generic"):
return EnlyzeProductionRun("source-run", machine, None, order, at(10), at(14))
def confirmation(order="123", hour=12):
return SimpleNamespace(production_order=order, workplace="workplace",
timestamp=at(hour), is_finished_goods=True)
def decision(r=None, runs=None, confirmations=None):
return decide(r or record(), runs if runs is not None else [run()],
confirmations if confirmations is not None else [confirmation()],
"workplace", "Machine-{production_order}")
def test_correct_and_stale_assignments():
assert decision(record("Machine-123")).order == "Machine-123"
d = decision()
assert d.order == "Machine-123"
assert d.record.run_id == "retained-counter-run"
@pytest.mark.parametrize("machine", ["arbitrary-machine", "another-machine"])
def test_machine_independent(machine):
assert decision(record(machine=machine), [run(machine=machine)]).order == "Machine-123"
@pytest.mark.parametrize("runs, confirmations", [
([run(), run("Machine-456")], [confirmation()]),
([run()], [confirmation(), confirmation("456")]),
([], [confirmation()]),
([replace(run(), end=None)], [confirmation()]),
([run(), replace(run(), end=None)], [confirmation()]),
([run()], []),
])
def test_ambiguous_or_missing_evidence(runs, confirmations):
assert decision(runs=runs, confirmations=confirmations).order is None
def test_previous_order_at_start_is_ignored_when_current_order_is_inside():
start = confirmation("1030", 10)
current = confirmation("12026001032")
d = decide(record("K 7-12026001030", "reference-machine"),
[replace(run("K 7-12026001032", "reference-machine"),
start=at(10), end=at(14))], [start, current],
"workplace", "K 7-{production_order}")
assert d.order == "K 7-12026001032"
def test_interior_conflicting_order_remains_unresolved():
assert decision(confirmations=[confirmation("123"), confirmation("456", 13)]).order is None
def test_correct_order_at_start_without_interior_evidence_is_unresolved():
boundary = confirmation("123", 10)
assert decision(confirmations=[boundary]).order is None
def test_correct_order_strictly_inside_run_reconciles():
assert decision(confirmations=[confirmation("123", 11)]).order == "Machine-123"
def test_confirmation_at_run_end_is_ignored():
end = confirmation("123", 14)
assert decision(confirmations=[end]).order is None
def test_shared_boundary_confirmation_corroborates_neither_adjacent_run():
left = replace(run("Machine-123"), start=at(10), end=at(12))
right = replace(run("Machine-456"), uuid="right", start=at(12), end=at(14))
boundary = confirmation("123", 12)
left_record = replace(record(), timestamp=at(11))
right_record = replace(record(), timestamp=at(13))
assert decide(left_record, [left, right], [boundary], "workplace",
"Machine-{production_order}").order is None
assert decide(right_record, [left, right], [boundary], "workplace",
"Machine-{production_order}").order is None
def test_k7_repaired_1030_to_1032_boundary_case_is_correctable():
r = record("K 7-12026001030", "reference-machine")
run_start = at(11)
k7_run = replace(run("K 7-12026001032", "reference-machine"),
start=run_start, end=at(17))
previous = confirmation("12026001030", 11)
d = decide(r, [k7_run], [previous, confirmation("12026001032", 12)],
"workplace", "K 7-{production_order}")
assert d.order == "K 7-12026001032"
d = decide(r, [k7_run], [confirmation("12026001032"), confirmation("12026001037", 13)],
"workplace", "K 7-{production_order}")
assert d.order is None
def test_calendar_days_and_berlin_dst():
start, end = reconciliation_window(datetime(2026, 10, 15, 2, 30, tzinfo=UTC))
assert start.isoformat() == "2026-10-12T00:00:00+02:00"
assert end.isoformat() == "2026-10-15T00:00:00+02:00"
start, end = reconciliation_window(datetime(2026, 10, 27, tzinfo=UTC))
assert (end.timestamp() - start.timestamp()) / 3600 == 73
# UTC date still previous day; use Berlin's date.
assert reconciliation_window(datetime(2026, 10, 14, 23, tzinfo=UTC))[1].day == 15
@pytest.mark.parametrize("days", [0, -1, True])
def test_invalid_window(days):
with pytest.raises(ValueError):
reconciliation_window(at(), days)
def test_dry_run_and_source_failure():
repository = MagicMock()
repository.read.return_value = [record()]
repository.guard_runs.side_effect = lambda decisions: decisions
source = MagicMock()
source.get_production_runs.return_value = [run()]
erp = MagicMock()
erp.get_confirmations.return_value = [confirmation()]
config = SimpleNamespace(machine_id="generic", erp_workplace="workplace")
decisions, applied = reconcile_machine(repository, source, erp, config,
"Machine-{production_order}", at(11), at(13), True)
assert decisions[0].order == "Machine-123" and applied == 0
repository.apply.assert_not_called()
assert erp.get_confirmations.call_args.kwargs["start"] == at(10)
assert erp.get_confirmations.call_args.kwargs["end"] == at(14)
source.get_production_runs.side_effect = RuntimeError("source unavailable")
with pytest.raises(RuntimeError, match="source unavailable"):
reconcile_machine(repository, source, erp, config, "Machine-{production_order}",
at(11), at(13))
repository.apply.assert_not_called()
def repository_with_connection():
repository = PostgresHistoricalRepository(None)
connection = MagicMock()
repository.connect = MagicMock()
repository.connect.return_value.__enter__.return_value = connection
return repository, connection
def test_atomic_update_audit_and_repeated_run():
repository, connection = repository_with_connection()
connection.execute.return_value.fetchone.side_effect = [(1,), (at(),)]
assert repository.apply([decision()]) == 1
calls = connection.execute.call_args_list
assert len(calls) == 5 # isolation, lock, run guard, update, audit
update_args = calls[3].args[1]
assert update_args == ("Machine-123", "calc", "generic", at(), "old", "retained-counter-run")
audit_args = calls[4].args[1]
assert audit_args[0] == "generic"
assert audit_args[3:6] == ("old", "Machine-123", "retained-counter-run")
connection.reset_mock()
assert repository.apply([decision(record("Machine-123"))]) == 0
assert connection.execute.call_count == 2 # no update or audit
def test_concurrent_change_fails_without_audit():
repository, connection = repository_with_connection()
connection.execute.return_value.fetchone.side_effect = [(1,), None]
with pytest.raises(RuntimeError, match="concurrently"):
repository.apply([decision()])
assert connection.execute.call_count == 4
assert repository.connect.return_value.__exit__.call_args.args[0] is RuntimeError
def test_partial_and_split_run_guard():
repository, connection = repository_with_connection()
connection.execute.return_value.fetchone.return_value = (2,)
assert repository.guard_runs([decision()])[0].order is None
d = decision()
other = replace(d, record=replace(d.record, timestamp=at(13)), order="Machine-456")
assert repository.guard_runs([d, other]) == [d, other]
assert all(d.order is None for d in repository.guard_runs([d, replace(other, order=None)]))
connection.execute.return_value.fetchone.return_value = (1,)
assert repository.guard_runs([decision()])[0].order == "Machine-123"
def test_database_failure_propagates():
repository = PostgresHistoricalRepository(None)
repository.connect = MagicMock(side_effect=RuntimeError("database unavailable"))
with pytest.raises(RuntimeError, match="database unavailable"):
repository.read("machine", at(10), at(14))
def test_cli_defaults():
from production_analytics.cli.__main__ import _parser
args = _parser().parse_args(["historical-reconcile", "--dry-run"])
assert args.lookback_days == 3 and args.dry_run and not args.verbose
assert _parser().parse_args(["historical-reconcile", "--verbose"]).verbose
assert _parser().parse_args(["historical-reconcile", "--dry-run", "--verbose"]).verbose
@pytest.mark.parametrize("split", [False, True])
def test_end_to_end_dry_run_idempotency_and_physical_values(sqlite_schema, split):
import sqlite3
database = sqlite3.connect(":memory:")
database.executescript(sqlite_schema)
database.execute(
"INSERT INTO material_consumption_snapshots VALUES (?, ?, ?, ?, ?, ?)",
(at().isoformat(), "calc", "generic", "old", "retained-counter-run", 1234.5),
)
if split:
database.execute("DELETE FROM material_consumption_snapshots")
database.executemany(
"INSERT INTO material_consumption_snapshots VALUES (?, ?, ?, ?, ?, ?)",
[(at(hour).isoformat(), "calc", "generic", "OLD", "R1", value)
for hour, value in zip([10, 11, 12, 13], [1000, 1010, 1025, 1040])],
)
class Connection:
def __enter__(self):
return self
def __exit__(self, exc_type, *_):
database.rollback() if exc_type else database.commit()
def execute(self, statement, parameters=()):
statement = statement if isinstance(statement, str) else statement.as_string()
if statement.startswith(("SET TRANSACTION", "SELECT pg_advisory")):
return None
parameters = tuple(
str(p.obj) if hasattr(p, "obj") else p.isoformat()
if isinstance(p, datetime) else p for p in parameters
)
return database.execute(statement.replace("%s", "?"), parameters)
class Repository(PostgresHistoricalRepository):
def connect(self):
return Connection()
def read(self, machine_id, start, end):
return [replace(r, timestamp=datetime.fromisoformat(r.timestamp),
identity=(*r.identity[:2], datetime.fromisoformat(r.identity[2])))
for r in super().read(machine_id, start, end)]
repository = Repository(None)
source = SimpleNamespace(get_production_runs=lambda machine: [run()])
erp = SimpleNamespace(get_confirmations=lambda **kwargs: [confirmation()])
config = SimpleNamespace(machine_id="generic", erp_workplace="workplace")
if split:
source = SimpleNamespace(get_production_runs=lambda machine: [
replace(run("1032"), start=at(10), end=at(12)),
replace(run("1037"), uuid="second", start=at(12), end=at(14)),
])
erp = SimpleNamespace(get_confirmations=lambda **kwargs: [
confirmation("1032", 11), confirmation("1037", 13)])
template = "{production_order}" if split else "Machine-{production_order}"
args = (repository, source, erp, config, template, at(10), at(14))
decisions, count = reconcile_machine(*args, dry_run=True)
assert count == 0 and decisions[0].order == ("1032" if split else "Machine-123")
assert database.execute("SELECT count(*) FROM historical_assignment_audit").fetchone() == (0,)
assert database.execute(
"SELECT production_order FROM material_consumption_snapshots"
).fetchone() == (("OLD",) if split else ("old",))
assert reconcile_machine(*args)[1] == (4 if split else 1)
assert reconcile_machine(*args)[1] == 0
assert database.execute("SELECT count(*) FROM historical_assignment_audit").fetchone() == (
4 if split else 1,)
if split:
from production_analytics.calculations.shift_material import (
ShiftMaterialSnapshot,
aggregate_shift_material,
)
from production_analytics.service.historical_reconcile import grouped_counts
assert grouped_counts(decisions) == (1, 1, 2, 0, 0)
rows = database.execute(
"SELECT timestamp, calculation_id, machine_id, production_order, run_id, "
"consumption_kg FROM material_consumption_snapshots ORDER BY timestamp"
).fetchall()
snapshots = [ShiftMaterialSnapshot(datetime.fromisoformat(r[0]), *r[1:]) for r in rows]
assert [(r.timestamp.hour, r.run_id, r.consumption_kg) for r in snapshots] == [
(10, "R1", 1000), (11, "R1", 1010), (12, "R1", 1025), (13, "R1", 1040)]
summary = aggregate_shift_material(snapshots, machine_id="generic",
calculation_ids=("calc",), start=at(10), end=at(14))
assert [(i.production_order, i.consumption_kg) for i in summary.items] == [
("1032", 10), ("1037", 30)]
assert summary.total_consumption_kg == 40
return
assert database.execute(
"SELECT timestamp, run_id, consumption_kg, production_order "
"FROM material_consumption_snapshots"
).fetchone() == (at().isoformat(), "retained-counter-run", 1234.5, "Machine-123")
def test_erp_failure_never_becomes_no_changes():
repository = MagicMock()
repository.read.return_value = [record()]
source = SimpleNamespace(get_production_runs=lambda machine: [run()])
erp = MagicMock()
erp.get_confirmations.side_effect = RuntimeError("ERP offline")
with pytest.raises(RuntimeError, match="ERP offline"):
reconcile_machine(repository, source, erp,
SimpleNamespace(machine_id="generic", erp_workplace="workplace"),
"Machine-{production_order}", at(10), at(14))
repository.apply.assert_not_called()
def test_runtime_reports_machine_failures_and_continues(monkeypatch, capsys):
from pathlib import Path
from production_analytics.service import historical_runtime
for factory in ("PostgresHistoricalRepository", "EnlyzeApiGateway",
"ExplorationClient", "ErpProductionConfirmationGateway"):
monkeypatch.setattr(historical_runtime, factory, MagicMock())
for settings in (historical_runtime.PostgresSettings, historical_runtime.ErpSettings,
historical_runtime.ExplorationSettings):
monkeypatch.setattr(settings, "from_environment", MagicMock())
reconcile = MagicMock(side_effect=[RuntimeError("source offline"), ([], 0), ([], 0)])
monkeypatch.setattr(historical_runtime, "reconcile_machine", reconcile)
args = SimpleNamespace(lookback_days=3, dry_run=True,
config=Path("config/shift-report-machines.yaml"),
order_formats=Path("config/historical-order-formats.yaml"))
assert historical_runtime.run(args, {}) == 1
assert reconcile.call_count == 3
output = capsys.readouterr().out
assert "Physical runs inspected:" in output and "Unresolved segments:" in output
assert "Order segments proposed:" in output
assert "DRY RUN" in output and "FAILED B1" in output and "Failures: 1" in output
assert "source offline" in output
@pytest.mark.parametrize("dry_run", [True, False])
@pytest.mark.parametrize("verbose", [True, False])
def test_runtime_groups_record_output_and_preserves_totals(monkeypatch, capsys, dry_run, verbose):
from datetime import timedelta
from pathlib import Path
from production_analytics.service import historical_runtime
for factory in ("PostgresHistoricalRepository", "EnlyzeApiGateway",
"ExplorationClient", "ErpProductionConfirmationGateway"):
monkeypatch.setattr(historical_runtime, factory, MagicMock())
for settings in (historical_runtime.PostgresSettings, historical_runtime.ErpSettings,
historical_runtime.ExplorationSettings):
monkeypatch.setattr(settings, "from_environment", MagicMock())
start = at(10)
correction_reason = ("closed ENLYZE run e0f474e0-1234 "
"[2026-10-13T10:00:00+00:00, 2026-10-13T14:00:00+00:00) "
"corroborated by ERP order K 7-12026001032")
corrections = [
Decision(HistoricalRecord(
"material_consumption_snapshots", ("calc", "machine", start + timedelta(seconds=i)),
"machine", start + timedelta(seconds=i), "K 7-12026001030", "counter-run",
), "K 7-12026001032", correction_reason)
for i in range(1964)
]
unresolved = [
Decision(HistoricalRecord(
"material_application_snapshots", ("application", "machine",
start + timedelta(seconds=i)),
"machine", start + timedelta(seconds=i), "B 1-42", "application-run",
), None, "unresolved: missing or overlapping closed ENLYZE runs")
for i in range(8421)
]
reconcile = MagicMock(side_effect=[(corrections, 1964 if not dry_run else 0),
(unresolved, 0), ([], 0)])
monkeypatch.setattr(historical_runtime, "reconcile_machine", reconcile)
args = SimpleNamespace(lookback_days=3, dry_run=dry_run, verbose=verbose,
config=Path("config/shift-report-machines.yaml"),
order_formats=Path("config/historical-order-formats.yaml"))
assert historical_runtime.run(args, {}) == 0
output = capsys.readouterr().out
correction_action = "proposed" if dry_run else "corrected"
assert (f"B1 | {correction_action}: K 7-12026001030 -> K 7-12026001032 | "
"ENLYZE run e0f474e0-1234 | 1964 records") in output
assert ("E1 | unresolved: missing or overlapping closed ENLYZE runs | "
"physical run application-run | source material_application_snapshots/application | "
"8421 records | 2026-10-13T10:00:00+00:00 -> "
"2026-10-13T12:20:20+00:00") in output
assert output.count("1964 records") == 1
assert output.count("8421 records") == 1
if verbose:
assert output.count("Proposed B1 " if dry_run else "Corrected B1 ") == 1964
assert output.count("Unresolved E1 ") == 8421
else:
assert "Proposed B1 " not in output
assert "Corrected B1 " not in output
assert "Unresolved E1 " not in output
assert "('calc', 'machine'" not in output
assert len(output.splitlines()) == 15
assert "Machines checked: 3\nRecords inspected: 10385" in output
assert f"Corrections {'proposed' if dry_run else 'applied'}: 1964" in output
assert "Ambiguous/unresolved: 8421\nUnchanged: 0\nFailures: 0" in output
assert "Physical runs inspected: 2\nRuns with proposed corrections: 1" in output
assert f"Order segments {correction_action}: 1" in output
assert "Unresolved runs: 1\nUnresolved segments: 1" in output
def test_grouped_counts_distinguish_rows_runs_and_segments():
from production_analytics.service.historical_reconcile import grouped_counts
d = decision()
decisions = [replace(d, record=replace(d.record, timestamp=at(hour)), order=order)
for hour, order in [(10, "A"), (11, "A"), (12, "B"), (13, None)]]
assert grouped_counts(decisions) == (1, 1, 2, 1, 1)
assert grouped_counts([]) == (0, 0, 0, 0, 0)
@pytest.mark.parametrize("calculation", [
"bento1-fresh-bentonite-application", "bento1-spreader3-application",
])
def test_application_collision_deduplicates_audits_and_is_idempotent(
sqlite_schema, calculation,
):
database, repository = application_repository(sqlite_schema)
for hour in (11, 12, 13):
insert_application(database, calculation, hour, "old", "old-run", 4730.169159683733)
insert_application(database, calculation, hour, "Machine-123", "source-run",
4730.169159683733)
args = application_reconcile_args(repository)
decisions, count = reconcile_machine(*args, dry_run=True)
assert count == 0 and len([d for d in decisions if d.order != d.record.production_order]) == 3
assert application_rows(database, calculation) == 6
assert database.execute("SELECT count(*) FROM historical_assignment_audit").fetchone() == (0,)
assert reconcile_machine(*args)[1] == 3
assert application_rows(database, calculation) == 3
assert database.execute(
"SELECT production_order, run_id, application_g_m2 FROM material_application_snapshots "
"WHERE calculation_id = ? ORDER BY timestamp", (calculation,)
).fetchall() == [("Machine-123", "source-run", 4730.169159683733)] * 3
assert database.execute(
"SELECT previous_order, new_order, run_id, retained_run_id, action, reason, "
"record_identity FROM historical_assignment_audit ORDER BY id"
).fetchall() == [
("old", "Machine-123", "old-run", "source-run", "deduplicated",
decisions[0].reason, str({"calculation_id": calculation, "machine_id": "generic",
"timestamp": str(at(hour))}))
for hour in (11, 12, 13)
]
assert reconcile_machine(*args)[1] == 0
def test_application_without_target_updates_normally(sqlite_schema):
database, repository = application_repository(sqlite_schema)
insert_application(database, "calc", 12, "old", "old-run", 42.5)
assert reconcile_machine(*application_reconcile_args(repository))[1] == 1
assert database.execute(
"SELECT production_order, run_id, application_g_m2 FROM material_application_snapshots"
).fetchone() == ("Machine-123", "old-run", 42.5)
assert database.execute(
"SELECT action, retained_run_id FROM historical_assignment_audit"
).fetchone() == ("updated", None)
@pytest.mark.parametrize("target_value,target_run", [
(99.0, "source-run"), (42.5, "unexpected-run"),
])
def test_application_collision_rolls_back_whole_machine(
sqlite_schema, target_value, target_run,
):
database, repository = application_repository(sqlite_schema)
for hour in (11, 12):
insert_application(database, "calc", hour, "old", "old-run", 42.5)
insert_application(database, "calc", hour, "Machine-123", "source-run" if hour == 11
else target_run, 42.5 if hour == 11 else target_value)
with pytest.raises(RuntimeError, match="conflicting measurement|unexpected target run"):
reconcile_machine(*application_reconcile_args(repository))
assert application_rows(database, "calc") == 4
assert database.execute("SELECT count(*) FROM historical_assignment_audit").fetchone() == (0,)
def application_repository(sqlite_schema):
import sqlite3
database = sqlite3.connect(":memory:")
database.executescript(sqlite_schema)
class Connection:
def __enter__(self):
return self
def __exit__(self, exc_type, *_):
database.rollback() if exc_type else database.commit()
def execute(self, statement, parameters=()):
statement = statement if isinstance(statement, str) else statement.as_string()
if statement.startswith(("SET TRANSACTION", "SELECT pg_advisory")):
return None
parameters = tuple(
str(p.obj) if hasattr(p, "obj") else p.isoformat()
if isinstance(p, datetime) else p for p in parameters
)
return database.execute(statement.replace(" FOR UPDATE", "").replace("%s", "?"),
parameters)
class Repository(PostgresHistoricalRepository):
def connect(self):
return Connection()
def read(self, machine_id, start, end):
return [replace(r, timestamp=datetime.fromisoformat(r.timestamp),
identity=(*r.identity[:2], datetime.fromisoformat(r.identity[2])))
for r in super().read(machine_id, start, end)]
return database, Repository(None)
def insert_application(database, calculation, hour, order, run_id, value):
database.execute("INSERT INTO material_application_snapshots VALUES (?, ?, ?, ?, ?, ?)",
(at(hour).isoformat(), calculation, "generic", order, run_id, value))
database.commit()
def application_rows(database, calculation):
return database.execute(
"SELECT count(*) FROM material_application_snapshots WHERE calculation_id = ?",
(calculation,),
).fetchone()[0]
def application_reconcile_args(repository):
source = SimpleNamespace(get_production_runs=lambda machine: [run()])
erp = SimpleNamespace(get_confirmations=lambda **kwargs: [confirmation()])
config = SimpleNamespace(machine_id="generic", erp_workplace="workplace")
return repository, source, erp, config, "Machine-{production_order}", at(10), at(14)
+1
View File
@@ -120,6 +120,7 @@ def test_runtime_isolation_and_disjoint_runs(tmp_path, monkeypatch):
assert separate.service._signal_discharge == (
configs[0].specific_discharge_kg_per_signal_unit_m)
assert separate.service._nominal_width_provider.format_template == 'Bento 1-{production_order}'
assert separate.service._nominal_width_provider.fallback_nominal_width_m == 5.0
machine = configs[0].machine_ref
order = 'Bento 1-test'
separate_path = separate.service._state_store.store._path(machine, order)
@@ -119,4 +119,5 @@ def test_bento_runtime_wiring(tmp_path, monkeypatch):
assert service._gate_variable_id == 'fef41976-1103-4090-b780-eaeecc02fdfa'
assert service._config == MaterialIntegratorConfig(0.3, 20)
assert service._nominal_width_provider.workplace == 'Bento 1'
assert service._nominal_width_provider.fallback_nominal_width_m == 5.0
erp_settings.from_secret_file.assert_called_once_with(tmp_path / 'erp.env')
+152 -4
View File
@@ -1,3 +1,4 @@
import sqlite3
import traceback
from dataclasses import FrozenInstanceError, replace
from datetime import UTC, datetime, timedelta
@@ -83,6 +84,103 @@ def test_open_event_clipped_to_shift_end():
assert summary.events[0].source.source_end is None
def test_raw_closed_event_without_attribution():
source = event(start=START + timedelta(hours=1), end=START + timedelta(hours=2))
summary = summarize([source])
assert source.attributed_start is source.attributed_end is None
assert summary.events[0].start == source.source_start
assert summary.events[0].end == source.source_end
assert summary.total_downtime_seconds == 3600
def test_attributed_end_closes_raw_open_event():
attributed_end = START + timedelta(hours=2)
source = event(end=None, attributed_end=attributed_end)
summary = summarize([source])
assert summary.events[0].start == START
assert summary.events[0].end is attributed_end
assert summary.events[0].source.source_end is None
assert summary.total_downtime_seconds == 2 * 3600
def test_attributed_start_with_no_end_remains_open():
summary = summarize([event(end=None, attributed_start=START + timedelta(hours=7))])
assert summary.total_downtime_seconds == 3600
assert summary.events[0].end is END
def test_attribution_overrides_conflicting_raw_interval():
attributed_start = START + timedelta(hours=1)
attributed_end = START + timedelta(hours=2)
source = event(
start=END,
end=END + timedelta(hours=2),
attributed_start=attributed_start,
attributed_end=attributed_end,
)
summary = summarize([source])
assert summary.events[0].start is attributed_start
assert summary.events[0].end is attributed_end
assert summary.total_downtime_seconds == 3600
assert source.source_start == END
assert source.source_end == END + timedelta(hours=2)
def test_attributed_interval_clips_both_shift_boundaries():
source = event(
start=END,
end=END,
attributed_start=START - timedelta(hours=1),
attributed_end=END + timedelta(hours=1),
)
summary = summarize([source])
assert summary.events[0].start is START
assert summary.events[0].end is END
assert summary.total_downtime_seconds == 8 * 3600
def test_production_reconciled_no_data_event_does_not_overlap_later_shift():
source_start = datetime(2026, 10, 12, 8, 56, 30, tzinfo=UTC)
source = event(
start=source_start,
end=None,
attributed_start=source_start,
attributed_end=datetime(2026, 10, 12, 12, 36, 2, tzinfo=UTC),
)
summary = summarize(
[source],
start=datetime(2026, 10, 13, 12, tzinfo=UTC),
end=datetime(2026, 10, 13, 20, tzinfo=UTC),
)
assert summary.events == summary.reasons == ()
assert summary.total_downtime_seconds == 0
assert summary.non_downtime_seconds == 8 * 3600
def test_attributed_intervals_preserve_union_and_reason_aggregation():
sources = [
event(
identifier,
end=None,
reason=reason,
attributed_start=START + timedelta(hours=lower),
attributed_end=START + timedelta(hours=upper),
)
for identifier, reason, lower, upper in [
("a", "A", 0, 2),
("b", "A", 1, 3),
("c", "B", 2, 4),
]
]
summary = summarize(sources)
assert summary.total_downtime_seconds == 4 * 3600
assert summary.non_downtime_seconds == 4 * 3600
assert [
(reason.reason_name, reason.duration_seconds, reason.event_count)
for reason in summary.reasons
] == [("A", 3 * 3600, 2), ("B", 2 * 3600, 1)]
def test_overlap_nested_duplicates_and_adjacent_intervals_are_not_double_counted():
events = [
event("a", end=START + timedelta(hours=2)),
@@ -207,6 +305,8 @@ def db(monkeypatch):
None,
"UNKNOWN",
None,
START.astimezone(UTC),
END.astimezone(UTC),
)
]
repository = PostgresDowntimeRepository(PostgresSettings("localhost", 5432, "db", "user", "pw"))
@@ -218,10 +318,14 @@ def test_repository_sql_parameters_mapping_and_lifecycle(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 "WHERE machine_id = %s AND COALESCE(attributed_start, source_start) < %s" in sql
assert "COALESCE(attributed_end, source_end) IS NULL" in sql
assert "OR COALESCE(attributed_end, source_end) > %s" in sql
assert "ORDER BY COALESCE(attributed_start, source_start), external_id" in sql
assert "category, comment, attributed_start, attributed_end" in sql
assert "production_order" not in sql
assert values[0].attributed_start == START.astimezone(UTC)
assert values[0].attributed_end == END.astimezone(UTC)
assert len(values) == 1 and values[0].source_end is None
assert values[0].source_start.tzinfo is UTC
connect.assert_called_once_with(
@@ -245,6 +349,46 @@ def test_machine_id_is_parameterized(db):
assert params[0] == machine_id
def test_repository_excludes_production_reconciled_event_from_later_shift(db):
repository, _, connection = db
# Execute the repository's overlap predicate, translating only driver placeholders.
with sqlite3.connect(":memory:") as database:
database.execute(
"""CREATE TABLE production_downtime_events (
external_id, machine_id, source_start, source_end,
reason_id, reason_name, reason_description, reason_group,
category, comment, attributed_start, attributed_end)"""
)
database.execute(
"""INSERT INTO production_downtime_events
(external_id, machine_id, source_start, attributed_start, attributed_end)
VALUES (?, ?, ?, ?, ?)""",
(
"reconciled-no-data",
"machine",
"2026-10-12T08:56:30+00:00",
"2026-10-12T08:56:30+00:00",
"2026-10-12T12:36:02+00:00",
),
)
def execute(sql, params):
return database.execute(
sql.replace("%s", "?"),
tuple(
value.isoformat() if isinstance(value, datetime) else value
for value in params
),
)
connection.execute.side_effect = execute
assert repository.get_events(
machine_id="machine",
start=datetime(2026, 10, 13, 12, tzinfo=UTC),
end=datetime(2026, 10, 13, 20, tzinfo=UTC),
) == []
@pytest.mark.parametrize(
"changes",
[
@@ -291,6 +435,10 @@ def test_repository_errors_are_safe(db, stage):
[
{"source_start": START.replace(tzinfo=None)},
{"source_end": END.replace(tzinfo=None)},
{"attributed_start": START.replace(tzinfo=None)},
{"attributed_end": END.replace(tzinfo=None)},
{"attributed_start": "invalid"},
{"attributed_end": "invalid"},
{"source_end": START - timedelta(seconds=1)},
{"reason_name": 123},
],
+281 -14
View File
@@ -202,9 +202,8 @@ def test_channel_b_identity_attribution_and_no_null_carry_forward():
]
summary = aggregate(rows, channel=True)
assert [(item.material_name, item.consumption_kg) for item in summary.items] == [
("Material A", 30),
("Material A", 45),
(None, 10),
("Material A", 15),
("Material B", 10),
]
assert summary.items[1].material_mapping_status == "UNAVAILABLE"
@@ -243,6 +242,7 @@ def test_e1_historical_null_channel_fixtures():
for minutes, value in ((-1, 5000), (479, 5000 + delta))
]
summary = aggregate(rows, channel=True)
assert summary.total_consumption_kg == pytest.approx(24_886.805)
assert len(summary.items) == 14
assert {(item.extruder, item.doser_channel): item.consumption_kg for item in summary.items} == (
pytest.approx(
@@ -321,14 +321,54 @@ def test_service_composes_once_and_propagates_errors(channel):
@pytest.mark.parametrize("channel", [False, True])
def test_ambiguous_stream_timestamps_and_reappearing_runs_rejected(channel):
def test_ambiguous_stream_timestamps_and_reappearing_runs_allowed(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)
summary = aggregate([
sample(0, 100), sample(10, 110), sample(20, 500, run="r2"),
sample(30, 520, run="r2"), sample(40, 200), sample(50, 230),
], channel=channel)
assert summary.total_consumption_kg == 60
assert [(item.run_id, item.consumption_kg) for item in summary.items] == [
("r1", 10), ("r2", 20), ("r1", 30),
]
assert summary.items[2].baseline_missing
summary = aggregate([sample(0, 100), sample(10, 110, order="different")], channel=channel)
assert [(i.production_order, i.consumption_kg) for i in summary.items] == [("different", 10)]
@pytest.mark.parametrize("channel", [False, True])
def test_reappearing_run_keeps_order_attribution_within_each_segment(channel):
sample = channel_sample if channel else machine_sample
rows = [
sample(0, 100, run="A", order="first"),
sample(1, 110, run="A", order="second"),
sample(2, 500, run="B", order="second"),
sample(3, 520, run="B", order="third"),
sample(4, 200, run="A", order="third"),
sample(5, 230, run="A", order="fourth"),
]
summary = aggregate(rows, channel=channel)
assert [(i.run_id, i.production_order, i.consumption_kg) for i in summary.items] == [
("A", "second", 10), ("B", "third", 20), ("A", "fourth", 30),
]
def test_channel_identity_gap_does_not_bridge_across_reappearing_run_segment():
rows = [
channel_sample(0, 100, run="A", name="Known"),
channel_sample(1, 110, run="A", name=None),
channel_sample(2, 500, run="B", name="Other"),
channel_sample(3, 520, run="B", name="Other"),
channel_sample(4, 200, run="A", name=None),
channel_sample(5, 230, run="A", name="Known"),
]
summary = aggregate(rows, channel=True)
assert summary.total_consumption_kg == 60
assert [(item.run_id, item.material_name, item.consumption_kg) for item in summary.items] == [
("A", None, 10), ("B", "Other", 20), ("A", "Known", 30),
]
def test_machine_and_calculation_scoping():
@@ -375,17 +415,22 @@ def test_new_run_exactly_at_shift_start_is_its_own_baseline(channel):
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")],
[
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)
summary = aggregate(
[sample(0, 100), sample(10, None, run="r2"), sample(20, 120)], channel=channel
)
assert summary.total_consumption_kg == 0
@pytest.mark.parametrize("channel", [False, True])
@@ -401,7 +446,229 @@ def test_spring_dst_window_uses_elapsed_instants(channel):
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)]]
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
@pytest.mark.parametrize("middle", [None, "Material B"])
@pytest.mark.parametrize("missing", [False, True])
def test_repeated_channel_identity_consolidates_after_interval_attribution(middle, missing):
offset = 1 if missing else 0
rows = [
channel_sample(offset, 100, name="Material A"),
channel_sample(10, 110, name="Material A"),
channel_sample(20, 115, name=middle),
channel_sample(30, 135, name="Material A", quality=False),
]
summary = aggregate(rows, channel=True)
assert len(summary.items) == 2
a, other = summary.items
assert (a.material_name, a.consumption_kg) == ("Material A", 30)
assert (other.material_name, other.consumption_kg) == (middle, 5)
assert a.baseline_timestamp == rows[0].timestamp
assert a.end_timestamp == rows[-1].timestamp
assert not a.percentage_sum_valid
assert other.percentage_sum_valid
assert all(item.baseline_missing == missing for item in summary.items)
if middle is None:
assert other.material_mapping_status == "UNAVAILABLE"
assert summary.total_consumption_kg == 35
assert summary == aggregate(reversed(rows), channel=True)
def test_hundreds_of_alternating_channel_identities_consolidate():
rows = [channel_sample(0, 100)] + [
channel_sample(index, 100 + index, name="Material A" if index % 2 else None)
for index in range(1, 401)
]
summary = aggregate(rows, channel=True)
assert [(item.material_name, item.consumption_kg) for item in summary.items] == [
("Material A", 399),
(None, 1),
]
assert summary.total_consumption_kg == 400
assert summary == aggregate(reversed(rows), channel=True)
@pytest.mark.parametrize("context", ["channel", "extruder", "run", "order", "calculation"])
def test_channel_consolidation_keeps_unrelated_streams_and_runs_separate(context):
rows = [channel_sample(0, 100), channel_sample(10, 110)]
changes = {
"channel": {"doser_channel": "C2"},
"extruder": {"extruder": "Ex2"},
"run": {"run_id": "r2"},
"order": {"run_id": "r2", "production_order": "other"},
"calculation": {"calculation_id": "calc2"},
}[context]
rows += [
replace(channel_sample(20, 500), **changes),
replace(channel_sample(30, 520), **changes),
]
summary = aggregate(rows, channel=True, calculation_ids=("calc", "calc2"))
assert len(summary.items) == 2
assert sorted(item.consumption_kg for item in summary.items) == [10, 20]
assert summary.total_consumption_kg == 30
@pytest.mark.parametrize(
"field,value", [("material_number", "123"), ("material_mapping_status", "OTHER")]
)
def test_channel_consolidation_preserves_distinct_identity_metadata(field, value):
rows = [
channel_sample(0, 100),
channel_sample(10, 110),
replace(channel_sample(20, 120), **{field: value}),
channel_sample(30, 130),
]
summary = aggregate(rows, channel=True)
assert len(summary.items) == 2
assert sorted(item.consumption_kg for item in summary.items) == [10, 20]
assert summary.total_consumption_kg == 30
@pytest.mark.parametrize("include_zero", [False, True])
def test_consolidated_channel_zero_handling(include_zero):
rows = [
channel_sample(0, 100),
channel_sample(10, 100),
channel_sample(20, 105, name=None),
channel_sample(30, 105),
]
summary = aggregate(rows, channel=True, include_zero=include_zero)
assert summary.total_consumption_kg == 5
assert len(summary.items) == (2 if include_zero else 1)
if include_zero:
assert summary.items[0].consumption_kg == 0
assert summary.items[0].baseline_timestamp == rows[0].timestamp
assert summary.items[0].end_timestamp == rows[-1].timestamp
@pytest.mark.parametrize("minutes", [(0, 1, 2), (0, 0.5, 1, 1.5), (0, 5, 10)])
def test_short_bounded_unknown_gap_bridges_all_deltas(minutes):
rows = [
channel_sample(
minute,
100 + index * 10,
name=" Material A " if index in (0, len(minutes) - 1) else None,
quality=index != 1,
)
for index, minute in enumerate(minutes)
]
summary = aggregate(rows, channel=True)
assert len(summary.items) == 1
item = summary.items[0]
assert item.material_name == "Material A"
assert item.consumption_kg == (len(minutes) - 1) * 10
assert summary.total_consumption_kg == rows[-1].cumulative_consumption_kg - 100
assert item.baseline_timestamp == rows[0].timestamp
assert item.end_timestamp == rows[-1].timestamp
assert not item.percentage_sum_valid
assert not item.baseline_missing
assert summary == aggregate(reversed(rows), channel=True)
@pytest.mark.parametrize(
"names,minutes",
[
(("Material A", None, "Material B"), (0, 1, 2)),
(("Material A", None, None), (0, 1, 2)),
((None, None, "Material A"), (0, 1, 2)),
(("Material A", None, "Material A"), (0, 1, 25)),
(("Material A", None, "Material A"), (0, 5, 10.01)),
],
)
def test_ambiguous_unbounded_or_long_identity_gaps_stay_unknown(names, minutes):
rows = [
channel_sample(minute, 100 + index * 10, name=name)
for index, (minute, name) in enumerate(zip(minutes, names))
]
summary = aggregate(rows, channel=True)
unknown = next(item for item in summary.items if item.material_name is None)
assert unknown.consumption_kg == (20 if names[-1] is None else 10)
assert unknown.material_mapping_status == "UNAVAILABLE"
assert summary.total_consumption_kg == 20
@pytest.mark.parametrize(
"field,value", [("material_number", "M2"), ("material_mapping_status", "OTHER")]
)
def test_bridging_requires_exact_normalized_identity(field, value):
rows = [
channel_sample(0, 100, number="M1"),
channel_sample(0.5, 105, number="M1"),
channel_sample(1, 115, name=None),
replace(channel_sample(2, 120, number="M1"), **{field: value}),
]
summary = aggregate(rows, channel=True)
assert len(summary.items) == 3
assert summary.items[1].material_name is None
assert summary.items[1].consumption_kg == 10
assert summary.total_consumption_kg == 20
@pytest.mark.parametrize("boundary", ["run", "order", "channel", "extruder"])
def test_bridging_never_crosses_context_boundaries(boundary):
changes = {
"run": {"run": "r2"},
"order": {"run": "r2", "order": "new-order"},
"channel": {"channel": "C2"},
"extruder": {"extruder": "Ex2"},
}[boundary]
rows = [
channel_sample(0, 100),
channel_sample(1, 110, name=None),
channel_sample(2, 500, **changes),
channel_sample(3, 520, **changes),
]
summary = aggregate(rows, channel=True)
unknown = next(item for item in summary.items if item.material_name is None)
assert unknown.consumption_kg == 10
assert summary.total_consumption_kg == 30
def test_short_bridge_preserves_missing_baseline_and_zero_filter():
rows = [channel_sample(1, 100), channel_sample(2, 100, name=None), channel_sample(3, 100)]
summary = aggregate(rows, channel=True)
assert len(summary.items) == 1
assert summary.items[0].baseline_missing
assert summary.total_consumption_kg == 0
assert aggregate(rows, channel=True, include_zero=False).items == ()
@pytest.mark.parametrize("channel", [False, True])
def test_orders_within_physical_run_conserve_counter_and_use_end_order(channel):
sample = channel_sample if channel else machine_sample
rows = [sample(i, value, order=order) for i, value, order in
[(0, 1000, "1032"), (1, 1010, "1032"),
(2, 1025, "1037"), (3, 1040, "1037")]]
summary = aggregate(rows, channel=channel)
assert [(i.production_order, i.consumption_kg) for i in summary.items] == [
("1032", 10), ("1037", 30)]
assert {i.run_id for i in summary.items} == {"r1"}
assert summary.total_consumption_kg == 40
assert aggregate([replace(r, production_order="OLD") for r in rows],
channel=channel).total_consumption_kg == 40
rows[2] = sample(2, 1005, order="1037")
with pytest.raises(ValueError, match="decreased/reset"):
aggregate(rows, channel=channel)
@pytest.mark.parametrize("orders", [("X", "Y", "Y"), ("X", "X", "Y"), ("X", "Y", "X")])
def test_channel_unknown_gap_cannot_bridge_order_boundary(orders):
rows = [channel_sample(0, 100, order=orders[0]),
channel_sample(1, 110, name=None, order=orders[1]),
channel_sample(2, 120, order=orders[2])]
summary = aggregate(rows, channel=True)
unknown = [i for i in summary.items if i.material_name is None]
assert len(unknown) == 1
assert unknown[0].production_order == orders[1]
assert unknown[0].consumption_kg == 10
assert summary.total_consumption_kg == 20
+14
View File
@@ -216,6 +216,20 @@ def test_service_reads_once_and_preserves_boundary_timezones():
assert summary.items[0].first_confirmation_at.tzinfo is BERLIN
def test_service_passes_explicit_site_timezone_to_gateway():
malaysia = ZoneInfo("Asia/Kuala_Lumpur")
gateway = Mock()
gateway.get_confirmations.return_value = []
start = datetime(2026, 10, 19, 6, tzinfo=malaysia)
end = datetime(2026, 10, 19, 14, tzinfo=malaysia)
ShiftProductionService(gateway).summarize(
workplace="Malaysia", start=start, end=end, timezone=malaysia,
)
gateway.get_confirmations.assert_called_once_with(
workplace="Malaysia", start=start, end=end, timezone=malaysia,
)
def test_gateway_errors_propagate():
gateway = Mock()
gateway.get_confirmations.side_effect = ErpReadError("ERP production confirmation read failed")
+257 -9
View File
@@ -1,7 +1,8 @@
from copy import deepcopy
from dataclasses import FrozenInstanceError
from datetime import UTC, date, timedelta
from datetime import UTC, date, datetime, timedelta
from pathlib import Path
from zoneinfo import ZoneInfo
import pytest
import yaml
@@ -17,13 +18,20 @@ from production_analytics.calculations.shift_production import (
ShiftProductionItem,
ShiftProductionSummary,
)
from production_analytics.calculations.shift_report import shift_report_window
from production_analytics.calculations.shift_report import (
most_recent_completed_shift,
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
from production_analytics.service.shift_report_config import (
load_shift_report_config,
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")
SHIFT_TIMEZONE = ZoneInfo("Europe/Berlin")
START, END = shift_report_window(date(2026, 10, 7), "early", SHIFT_TIMEZONE)
class Stub:
@@ -58,11 +66,12 @@ def composition(name="B1"):
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"
channel = config.material is not None and 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,
calculation_id=config.material.calculation_ids[0] if config.material else "unused",
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,
@@ -89,7 +98,8 @@ 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}),
("production", {"workplace": workplace, "start": START, "end": END,
"timezone": SHIFT_TIMEZONE}),
("downtime", {"machine_id": config.machine_id, "start": START, "end": END}),
(mode, {"machine_id": config.machine_id, "calculation_ids": ids,
"start": START, "end": END}),
@@ -113,6 +123,172 @@ def test_machine_composition(name, workplace, mode, ids):
report.machine_name = "other"
@pytest.mark.parametrize("name", ["Gitter 1", "Gitter 2", "Gitter 3", "Gitter 4", "K5"])
def test_boolean_speed_machines_appear_in_report_without_material(name):
service, stubs, calls, config = composition(name)
report = service.build(machine_name=name, start=START, end=END)
assert [stage for stage, _ in calls] == ["production", "downtime", "speed"]
assert calls[-1][1]["config"] is config.speed
assert report.speed is stubs["speed"].result
assert report.materials is None
def test_sites_and_existing_machine_capabilities():
config = load_shift_report_config(CONFIG_PATH)
assert {key: site.display_name for key, site in config.sites.items()} == {
"espelkamp": "Espelkamp", "adorf": "Adorf", "malaysia": "Malaysia",
}
assert set(config.machines) == {
"B1", "E1", "K7", "K3/4", "E4", "Gitter 1", "Gitter 2",
"Gitter 3", "Gitter 4", "K5", "Secumat 1/2", "Secumat 3",
"Bento 2", "K1", "K6",
}
assert all(config.machines[name].site == "espelkamp" for name in ("B1", "E1", "K7"))
assert all(vars_for_capabilities(machine) == (True, True, True, True)
for name, machine in config.machines.items() if name in ("B1", "E1", "K7"))
assert config.machines["K7"].material.allocation == "erp_fiber_share"
assert config.machines["B1"].material.allocation == "none"
assert config.sites["espelkamp"].timezone is SHIFT_TIMEZONE
assert config.sites["adorf"].timezone is SHIFT_TIMEZONE
assert config.sites["malaysia"].timezone.key == "Asia/Kuala_Lumpur"
assert all(config.machines[name].timezone is SHIFT_TIMEZONE
for name in ("B1", "E1", "K7"))
with pytest.raises(TypeError):
config.sites["new"] = config.sites["adorf"]
def vars_for_capabilities(machine):
value = machine.capabilities
return value.production, value.downtime, value.material, value.speed
def test_new_production_machines_have_valid_sites_and_capabilities():
machines = load_shift_report_config(CONFIG_PATH).machines
expected = {
"K3/4": ("espelkamp", "K3/4", None),
"E4": ("espelkamp", "1568700", "646ebfa0-e97d-4970-b9f4-da94492aecc3"),
"Gitter 1": ("adorf", "GITTERANL", "35612735-03cc-4496-a72e-3c3e2216c720"),
"Gitter 2": ("adorf", "GITTER II", "5e89db10-ef0e-4224-866c-eee12bc3d27c"),
"Gitter 3": ("adorf", "GITTERIII", "ec3baac3-ccc1-4d1e-9b57-3f5ab2daa567"),
"Gitter 4": ("adorf", "GITTER IV", "ffa5de99-66a2-44bd-b039-9b4275bc5f9e"),
"K5": ("adorf", "K5", "8c094b9d-32d2-4ddf-b56a-2cd11a09eebf"),
"Secumat 1/2": ("adorf", "SECEXTRU", "16c0a111-3049-41d5-9e19-42ee0e047757"),
"Secumat 3": ("adorf", "SEC3", "0c207a7c-7813-4cff-90ba-6a0148919d38"),
"Bento 2": ("malaysia", "BENTO 2", "6201f3de-b940-45d7-930c-1481c5ae9e1d"),
"K1": ("malaysia", "K1", "40f1f58b-21fc-490a-8343-d1888938f11b"),
"K6": ("malaysia", "K6", "5e778f87-2d0f-47ac-a3ce-0c0dd9957918"),
}
assert len(machines) == 15
assert set(machines) - {"B1", "E1", "K7"} == set(expected)
downtime_enabled = {
"E4", "Gitter 1", "Gitter 2", "Gitter 3", "Gitter 4",
"K5", "Secumat 1/2", "Secumat 3",
}
for name, (site, workplace, machine_id) in expected.items():
machine = machines[name]
assert (machine.display_name, machine.site, machine.erp_workplace,
machine.machine_id) == (name, site, workplace, machine_id)
speed_enabled = name in {"Gitter 1", "Gitter 2", "Gitter 3", "Gitter 4", "K5"}
assert vars_for_capabilities(machine) == (True, name in downtime_enabled, False,
speed_enabled)
assert machine.material is None
assert (machine.speed is not None) == speed_enabled
assert machine.timezone.key == ("Asia/Kuala_Lumpur" if site == "malaysia"
else "Europe/Berlin")
ids = [machine.machine_id for machine in machines.values() if machine.machine_id]
assert len(ids) == len(set(ids)) == 14
@pytest.mark.parametrize("downtime", [False, True])
def test_partial_capabilities_skip_disabled_sources_and_render_unavailable(
downtime,
):
from dataclasses import replace
from production_analytics.presentation.shift_report import TextBlock, present_report
from production_analytics.service.shift_report_config import ShiftReportCapabilities
service, stubs, calls, config = composition()
partial = replace(config,
capabilities=ShiftReportCapabilities(True, downtime, False, False),
material=None, speed=None)
service.machines = {"Synthetic": partial}
report = service.build(machine_name="Synthetic", start=START, end=END)
expected = ["production", "downtime"] if downtime else ["production"]
assert [name for name, _ in calls] == expected
assert report.production is stubs["production"].result
assert report.downtime is (stubs["downtime"].result if downtime else None)
assert report.materials is None and report.speed is None
assert report.downtime_event_count == (1 if downtime else 0)
blocks = present_report(report)
unavailable = [b for b in blocks if isinstance(b, TextBlock)
and b.text == "Für diese Maschine nicht verfügbar."]
assert len(unavailable) == (2 if downtime else 3)
def test_downtime_only_machine_does_not_query_production():
from dataclasses import replace
from production_analytics.service.shift_report_config import ShiftReportCapabilities
service, stubs, calls, config = composition()
service.machines = {"DowntimeOnly": replace(
config, capabilities=ShiftReportCapabilities(False, True, False, False),
material=None, speed=None,
)}
report = service.build(machine_name="DowntimeOnly", start=START, end=END)
assert [name for name, _ in calls] == ["downtime"]
assert report.production is None and report.downtime is stubs["downtime"].result
@pytest.mark.parametrize("explicit_null", [False, True])
def test_production_only_machine_without_enlyze_id_loads_and_builds(tmp_path, explicit_null):
document = deepcopy(yaml.safe_load(CONFIG_PATH.read_text()))
document["machines"] = {"K3/4": {
"display_name": "K3/4", "site": "espelkamp", "erp_workplace": "K3/4",
"capabilities": {"production": True, "downtime": False,
"material": False, "speed": False},
}}
if explicit_null:
document["machines"]["K3/4"]["machine_id"] = None
path = tmp_path / "machines.yaml"
path.write_text(yaml.safe_dump(document))
machine = load_shift_report_config(path).machines["K3/4"]
assert machine.machine_id is None and machine.timezone is SHIFT_TIMEZONE
service, stubs, calls, _ = composition()
service.machines = {"K3/4": machine}
report = service.build(machine_name="K3/4", start=START, end=END)
assert report.machine_id is None and report.timezone is SHIFT_TIMEZONE
assert report.production is stubs["production"].result
assert report.downtime is report.materials is report.speed is None
assert [name for name, _ in calls] == ["production"]
def test_malaysia_report_carries_site_timezone_to_production_and_presentation():
from dataclasses import replace
from production_analytics.presentation.shift_report import TextBlock, present_report
from production_analytics.service.shift_report_config import ShiftReportCapabilities
malaysia = ZoneInfo("Asia/Kuala_Lumpur")
service, _, calls, config = composition()
service.machines = {"Synthetic": replace(
config, site="malaysia", timezone=malaysia, machine_id=None,
capabilities=ShiftReportCapabilities(True, False, False, False),
material=None, speed=None,
)}
start, end = shift_report_window(date(2026, 10, 19), "late", malaysia)
report = service.build(machine_name="Synthetic", start=start.astimezone(UTC),
end=end.astimezone(UTC))
assert report.timezone is malaysia
assert report.start == start and report.end == end
assert calls == [("production", {"workplace": config.erp_workplace,
"start": start, "end": end, "timezone": malaysia})]
texts = [block.text for block in present_report(report) if isinstance(block, TextBlock)]
assert "Zeitzone: Asia/Kuala_Lumpur" in texts
assert any("Schichtbeginn: 19.10.2026 14:00:00" in value for value in texts)
def test_top_three_and_fallback_preserve_reason_metadata_and_order():
service, stubs, _, _ = composition()
report = service.build(machine_name="B1", start=START, end=END)
@@ -191,7 +367,7 @@ def test_utc_input_is_normalized_to_berlin_without_changing_instants():
("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)
start, end = shift_report_window(date(2026, 10, 7), shift, SHIFT_TIMEZONE)
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
@@ -200,10 +376,28 @@ def test_shift_windows(shift, hours):
@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")
start, end = shift_report_window(day, "night", SHIFT_TIMEZONE)
assert (end.astimezone(UTC) - start.astimezone(UTC)).total_seconds() == hours * 3600
@pytest.mark.parametrize("shift,start_hour,end_hour", [
("early", 6, 14), ("late", 14, 22), ("night", 22, 6),
])
def test_malaysia_shift_windows_use_local_wall_clock(shift, start_hour, end_hour):
malaysia = ZoneInfo("Asia/Kuala_Lumpur")
start, end = shift_report_window(date(2026, 10, 19), shift, malaysia)
assert start.tzinfo is end.tzinfo is malaysia
assert (start.hour, end.hour) == (start_hour, end_hour)
assert (end.astimezone(UTC) - start.astimezone(UTC)).total_seconds() == 28800
def test_same_instant_has_different_site_completed_shifts():
now = datetime(2026, 10, 19, 11, tzinfo=UTC)
assert most_recent_completed_shift(now, SHIFT_TIMEZONE) == (date(2026, 10, 18), "night")
assert most_recent_completed_shift(now, ZoneInfo("Asia/Kuala_Lumpur")) == (
date(2026, 10, 19), "early")
@pytest.mark.parametrize("mutation", [
lambda d: d["machines"]["B1"].pop("erp_workplace"),
lambda d: d["machines"]["B1"].update(unknown=True),
@@ -221,6 +415,25 @@ def test_night_shift_dst_elapsed_duration(day, hours):
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),
lambda d: d["machines"]["B1"].update(site="unknown"),
lambda d: d["machines"]["B1"].update(site=[]),
lambda d: d["machines"]["B1"].pop("capabilities"),
lambda d: d["machines"]["B1"]["capabilities"].update(material=False),
lambda d: d["machines"]["B1"].pop("material"),
lambda d: d["machines"]["B1"]["capabilities"].update(speed=False),
lambda d: d["machines"]["B1"].pop("speed"),
lambda d: d["machines"]["B1"]["capabilities"].update(production="true"),
lambda d: d["machines"]["B1"].update(display_name=" "),
lambda d: d["sites"]["espelkamp"].update(display_name=""),
lambda d: d["sites"]["espelkamp"].update(extra=True),
lambda d: d["machines"]["B1"]["material"].update(allocation="unknown"),
lambda d: d["sites"]["malaysia"].update(timezone="Mars/Base"),
lambda d: d["sites"]["malaysia"].update(timezone=""),
lambda d: d["sites"]["malaysia"].pop("timezone"),
lambda d: d["machines"]["B1"].pop("machine_id"),
lambda d: d["machines"]["B1"].update(machine_id=None),
lambda d: d["machines"]["B1"]["capabilities"].update(
production=False, downtime=False, material=False, speed=False),
])
def test_strict_configuration(tmp_path, mutation):
document = deepcopy(yaml.safe_load(CONFIG_PATH.read_text()))
@@ -236,3 +449,38 @@ def test_duplicate_yaml_keys_rejected(tmp_path):
path.write_text("machines: {}\nmachines: {}\n")
with pytest.raises(ValueError, match="unique"):
load_shift_report_machines(path)
def test_duplicate_site_key_rejected(tmp_path):
document = CONFIG_PATH.read_text().replace(
" adorf:\n display_name: Adorf", " espelkamp:\n display_name: Adorf"
)
path = tmp_path / "machines.yaml"
path.write_text(document)
with pytest.raises(ValueError, match="unique"):
load_shift_report_config(path)
def test_duplicate_machine_key_rejected(tmp_path):
document = CONFIG_PATH.read_text().replace(" E1:\n", " B1:\n")
path = tmp_path / "machines.yaml"
path.write_text(document)
with pytest.raises(ValueError, match="unique"):
load_shift_report_config(path)
@pytest.mark.parametrize("capability", ["downtime", "material", "speed"])
def test_machine_id_required_for_nonproduction_capabilities(tmp_path, capability):
document = deepcopy(yaml.safe_load(CONFIG_PATH.read_text()))
machine = document["machines"]["B1"]
machine["capabilities"] = {name: name == capability
for name in ("production", "downtime", "material", "speed")}
machine.pop("machine_id")
if capability != "material":
machine.pop("material")
if capability != "speed":
machine.pop("speed")
path = tmp_path / "machines.yaml"
path.write_text(yaml.safe_dump(document))
with pytest.raises(ValueError):
load_shift_report_config(path)
+135
View File
@@ -0,0 +1,135 @@
from dataclasses import replace
from pathlib import Path
from types import SimpleNamespace
import pytest
from test_shift_report import END, START, composition
from production_analytics.cli import __main__ as cli
from production_analytics.presentation import shift_report as presenter
from production_analytics.service import shift_report_runtime as runtime
def arguments(*extra):
return [
"report",
"shift",
"--machine",
"E1",
"--start",
START.isoformat(),
"--end",
END.isoformat(),
"--output",
"/tmp/shift.pdf",
*extra,
]
@pytest.mark.parametrize(
"extra,message",
[
(["--machine", "UNKNOWN"], "Unknown shift-report machine"),
(["--start", "2026-10-07T06:00:00"], "timezone"),
(["--start", "invalid"], "Invalid isoformat"),
(["--end", START.isoformat()], "end must follow start"),
(["--end", "2026-10-06T06:00:00+02:00"], "end must follow start"),
],
)
def test_validation_before_settings_or_source_access(monkeypatch, capsys, extra, message):
def unexpected(*args, **kwargs):
pytest.fail("Invalid arguments reached runtime setup")
monkeypatch.setattr(cli, "_runtime_environment", unexpected)
assert cli.main(arguments(*extra)) == 2
assert message in capsys.readouterr().err
def test_start_end_and_output_are_required():
with pytest.raises(SystemExit) as caught:
cli.main(["report", "shift", "--machine", "E1"])
assert caught.value.code == 2
def test_cli_builds_one_report_and_passes_output(monkeypatch, capsys):
service, _, _, _ = composition("E1")
value = service.build(machine_name="E1", start=START, end=END)
calls = []
def environment(*paths):
calls.append(paths)
return {"settings": "supplied"}
def build(machines, env):
assert set(machines) == {
"B1", "E1", "K7", "K3/4", "E4", "Gitter 1", "Gitter 2",
"Gitter 3", "Gitter 4", "K5", "Secumat 1/2", "Secumat 3",
"Bento 2", "K1", "K6",
}
assert env == {"settings": "supplied"}
def report(**kwargs):
calls.append(kwargs)
return value
return SimpleNamespace(build=report)
monkeypatch.setattr(cli, "_runtime_environment", environment)
monkeypatch.setattr(runtime, "build_shift_report_service", build)
monkeypatch.setattr(
presenter, "write_pdf", lambda report, output: calls.append((report, output))
)
assert cli.main(arguments()) == 0
assert calls == [
(Path("secrets/enlyze.env"), Path("secrets/erp.env"), Path("secrets/postgres.env")),
{"machine_name": "E1", "start": START, "end": END},
(value, Path("/tmp/shift.pdf")),
]
assert capsys.readouterr().out.strip() == "/tmp/shift.pdf"
def test_runtime_wires_existing_readers_without_connecting(monkeypatch):
machines = composition("E1")[0].machines
tokens = {"postgres": object(), "erp": object(), "enlyze": object()}
for settings, token in (
(runtime.PostgresSettings, tokens["postgres"]),
(runtime.ErpSettings, tokens["erp"]),
(runtime.ExplorationSettings, tokens["enlyze"]),
):
monkeypatch.setattr(settings, "from_environment", lambda env, token=token: token)
service = runtime.build_shift_report_service(machines, {})
assert service.production.gateway._settings is tokens["erp"]
assert service.downtime.repository.settings is tokens["postgres"]
assert service.materials.repository.settings is tokens["postgres"]
assert service.channel_materials.repository.settings is tokens["postgres"]
assert isinstance(service.speed.gateway, runtime.EnlyzeApiGateway)
assert set(service.material_allocators) == {"K7"}
def test_allocator_selection_uses_strategy_for_any_machine_name(monkeypatch):
machines = dict(composition("K7")[0].machines)
k7 = machines.pop("K7")
machines["OtherMachine"] = replace(k7, machine_id="other-id", speed=None,
capabilities=replace(k7.capabilities, speed=False))
machines["B1"] = replace(machines["B1"], material=replace(
machines["B1"].material, allocation="none"))
for settings in (runtime.PostgresSettings, runtime.ErpSettings,
runtime.ExplorationSettings):
monkeypatch.setattr(settings, "from_environment", lambda env: object())
service = runtime.build_shift_report_service(machines, {})
assert set(service.material_allocators) == {"OtherMachine"}
assert isinstance(service.material_allocators["OtherMachine"],
runtime.K7FiberAllocationService)
def test_source_failure_is_safe_and_does_not_render(monkeypatch, capsys):
def fail(**kwargs):
raise RuntimeError("secret source details")
monkeypatch.setattr(cli, "_runtime_environment", lambda *args: {})
monkeypatch.setattr(
runtime, "build_shift_report_service", lambda *args: SimpleNamespace(build=fail)
)
monkeypatch.setattr(presenter, "write_pdf", lambda *args: pytest.fail("Rendered failed read"))
assert cli.main(arguments()) == 1
assert capsys.readouterr().err == "Report failed: RuntimeError\n"
+92
View File
@@ -0,0 +1,92 @@
from dataclasses import replace
from datetime import date, datetime
from html import escape
from zoneinfo import ZoneInfo
import pytest
from test_shift_report_pdf import material_report
from production_analytics.presentation.shift_report import MaterialPieBlock, present_report
from production_analytics.presentation.shift_report_html import render_page
SHIFT_TIMEZONE = ZoneInfo("Europe/Berlin")
def page(value):
return render_page(
machines={value.machine_name: None},
labels={"early": "Frühschicht"},
day=date(2026, 10, 14),
shift="early",
machine=value.machine_name,
report=value,
generated_at=datetime.now(SHIFT_TIMEZONE),
error=None,
)
def test_multiple_materials_chart_and_table():
html = page(material_report((10, 30)))
assert '<figure class="material-chart">' in html
assert '<svg viewBox="0 0 120 120"' in html
assert "Material-0: 10,00 kg (25,00 %)" in html
assert "Material-1: 30,00 kg (75,00 %)" in html
assert '<th scope="col">Materialname</th>' in html
assert "<td>Material-0</td>" in html and "<td>30,00 kg</td>" in html
def test_zero_entries_omitted_and_one_material_supported():
value = material_report((0, 12, 0))
html = page(value)
assert "Material-0" not in html and "Material-2" not in html
assert "Material-1: 12,00 kg (100,00 %)" in html
assert html.count("<circle ") == 1
# Existing PDF presentation still omits single-material charts.
assert not any(isinstance(block, MaterialPieBlock) for block in present_report(value))
@pytest.mark.parametrize("quantities", [(), (0, 0), (-2,)])
def test_no_positive_materials_no_chart(quantities):
html = page(material_report(quantities))
assert '<figure class="material-chart">' not in html
assert "<svg " not in html and "<circle " not in html
if not any(quantities):
assert "Keine Materialverbrauchsdaten vorhanden." in html
def test_sensitive_names_are_text_not_code():
value = material_report((10, 20))
name = '</script><script>alert("x")</script>&\' ${evil} \u2028'
items = tuple(
replace(item, material_name=name, material_number=f"M{index}")
for index, item in enumerate(value.materials.items)
)
html = page(replace(value, materials=replace(value.materials, items=items)))
assert "<script>" not in html and "</script>" not in html
assert escape(name + " (M0)") in html
assert escape(name + " (M1)") in html
assert "<td>" + escape(name) + "</td>" in html
@pytest.mark.parametrize("machine", ["B1", "E1", "K7"])
def test_chart_uses_shared_consolidated_material_totals(machine):
value = material_report((10, 20, 30))
items = tuple(
replace(
item,
material_name="Harz",
material_number="M1",
production_order=f"order-{index}",
erp_booking_share=0.5 if machine == "K7" else None,
)
for index, item in enumerate(value.materials.items)
)
value = replace(value, machine_name=machine, materials=replace(value.materials, items=items))
html = page(value)
assert "Harz: 60,00 kg (100,00 %)" in html
assert html.count("<circle ") == 1
if machine == "K7":
# The order-specific table is preserved alongside the material-level pie.
for index in range(3):
assert f"<td>order-{index}</td>" in html
assert "ERP-Anteil" in html
+326
View File
@@ -0,0 +1,326 @@
from dataclasses import replace
from datetime import UTC, datetime
import pytest
from test_shift_report import END, START, composition
from production_analytics.presentation.shift_report import (
MaterialPieBlock,
TableBlock,
TextBlock,
present_report,
render_pdf,
write_pdf,
)
def report(name="E1"):
service, _, _, _ = composition(name)
return service.build(machine_name=name, start=START, end=END)
def content(value):
return "\n".join(
block.text
if isinstance(block, TextBlock)
else "\n".join(" | ".join(row) for row in (block.headers, *block.rows))
for block in present_report(value)
if isinstance(block, (TextBlock, TableBlock))
)
def test_stable_model_required_labels_and_supplied_quantities():
value = report()
assert present_report(value) == present_report(value)
text = content(value)
for label in (
"Schichtbericht",
"Maschine: E1",
"Schichtbeginn",
"Schichtende",
"Produktion",
"Produktionsauftrag",
"Artikelnummer",
"Artikelbeschreibung",
"Rollen gesamt: 1",
"Gesamtmenge: 123,00 m²",
"Stillstand gesamt",
"Zeit ohne erfassten Stillstand",
"Materialverbrauch",
"42,00 kg",
"Liniengeschwindigkeit im Lauf",
"order",
"article",
"description",
):
assert label in text
assert "Produktionszeit" not in text
value = replace(value, speed=replace(value.speed, average_line_speed_m_min=12.345))
assert "12,35 m/min" in content(value)
def test_top_three_preserve_order_and_durations():
tables = [block for block in present_report(report()) if isinstance(block, TableBlock)]
reasons = next(block for block in tables if block.headers == ("Stillstandsgrund", "Dauer"))
assert reasons.rows == (
("Ohne Stillstandsgrund", "0 h 01 min 40,0 s"),
("Stop", "0 h 01 min 30,0 s"),
("Ohne Stillstandsgrund", "0 h 01 min 20,0 s"),
)
assert "Other" not in content(report())
def test_material_summary_names_numbers_and_unknown_label():
value = report()
assert "Materialzuordnung fehlt" in content(value)
assert "Ex1" not in content(value)
item = replace(value.materials.items[0], material_number="M123", material_name="Harz & Öl")
text = content(replace(value, materials=replace(value.materials, items=(item,))))
assert "M123" in text
assert "Harz & Öl" in text
def test_empty_sections_and_zero_totals():
value = report()
value = replace(
value,
production=replace(value.production, items=(), total_produced_m2=0, total_roll_count=0),
downtime=replace(value.downtime, events=(), reasons=(), total_downtime_seconds=0),
materials=replace(value.materials, items=(), total_consumption_kg=0),
)
text = content(value)
for message in (
"Keine Produktionsdaten vorhanden.",
"Keine Stillstandsgründe vorhanden.",
"Keine Stillstandsereignisse vorhanden.",
"Keine Materialverbrauchsdaten vorhanden.",
"keine Laufdaten",
"Gesamtmenge: 0,00 m²",
"Rollen gesamt: 0",
):
assert message in text
@pytest.mark.parametrize(
"start,end,expected",
[
(
datetime(2026, 1, 1, 5, tzinfo=UTC),
datetime(2026, 1, 1, 13, tzinfo=UTC),
("01.01.2026 06:00:00 CET (+0100)", "01.01.2026 14:00:00 CET (+0100)"),
),
(
datetime(2026, 10, 25, 0, 30, tzinfo=UTC),
datetime(2026, 10, 25, 1, 30, tzinfo=UTC),
("25.10.2026 02:30:00 CEST (+0200)", "25.10.2026 02:30:00 CET (+0100)"),
),
],
)
def test_berlin_display_including_dst_fold(start, end, expected):
text = content(replace(report(), start=start, end=end))
assert all(timestamp in text for timestamp in expected)
def test_pdf_is_repeatable_a4_and_written_to_requested_path(tmp_path):
pytest.importorskip("reportlab")
value = report()
payload = render_pdf(value)
assert payload == render_pdf(value)
assert payload.startswith(b"%PDF-")
assert b"/MediaBox [ 0 0 595.2756 841.8898 ]" in payload
output = tmp_path / "nested" / "shift.pdf"
write_pdf(value, output)
assert output.read_bytes() == payload
def test_pdf_paginates_long_reports_and_escapes_source_markup():
pytest.importorskip("reportlab")
value = report()
item = replace(value.production.items[0], article_description="<tag> & description " * 5)
value = replace(value, production=replace(value.production, items=(item,) * 60))
payload = render_pdf(value)
assert payload.count(b"/Type /Page\n") > 1
@pytest.mark.parametrize("name", ["B1", "E1", "K7"])
def test_every_machine_renders_supplied_values_without_correction(name):
value = report(name)
value = replace(value, production=replace(value.production, total_produced_m2=1234.56))
text = content(value)
assert f"Maschine: {name}" in text
assert "Gesamtmenge: 1.234,56 m²" in text
assert "123,00 m²" in text
assert "Materialverbrauch gesamt: 42,00 kg" in text
def material_report(quantities):
value = report()
template = value.materials.items[0]
items = tuple(
replace(
template,
calculation_id=f"calculation-{index}",
doser_channel=f"C{index + 1}",
consumption_kg=quantity,
material_name=f"Material-{index}",
)
for index, quantity in enumerate(quantities)
)
return replace(
value, materials=replace(value.materials, items=items, total_consumption_kg=sum(quantities))
)
def test_material_zero_filter_preserves_report_and_total():
value = material_report((0, 10, 0.001, -2))
original = value.materials
text = content(value)
assert "Material-0" not in text
assert "Material-1" in text
assert "Material-2" in text # Exactly zero, not rounded-to-zero filtering.
assert "Material-3" in text
assert "Materialverbrauch gesamt: 8,00 kg" in text
assert value.materials is original
assert len(value.materials.items) == 4
chart = next(block for block in present_report(value) if isinstance(block, MaterialPieBlock))
assert chart.consumption_kg == (10, 0.001)
assert chart.labels == ("Material-1", "Material-2")
@pytest.mark.parametrize("quantities", [(), (0, 0), (0, 12)])
def test_material_chart_requires_two_positive_items(quantities):
value = material_report(quantities)
assert not any(isinstance(block, MaterialPieBlock) for block in present_report(value))
if not any(quantities):
assert "Keine Materialverbrauchsdaten vorhanden." in content(value)
assert not any(
isinstance(block, TableBlock) and block.headers[0] == "Materialname"
for block in present_report(value)
)
assert render_pdf(value).startswith(b"%PDF-")
def test_material_chart_labels_and_repeatable_pdf():
value = material_report((10, 20, 30, 40))
items = list(value.materials.items)
items[0] = replace(items[0], material_name="Harz & Öl")
items[1] = replace(items[1], extruder=None, doser_channel=None, material_name="Polymer")
items[2] = replace(
items[2], extruder=None, doser_channel=None, material_number="M123", material_name=None
)
items[3] = replace(items[3], extruder=None, doser_channel=None, material_name=None)
value = replace(value, materials=replace(value.materials, items=tuple(items)))
blocks = present_report(value)
chart = next(block for block in blocks if isinstance(block, MaterialPieBlock))
assert chart.labels == ("Materialzuordnung fehlt", "M123", "Harz & Öl", "Polymer")
assert chart.consumption_kg == (40, 30, 10, 20)
assert blocks == present_report(value)
assert render_pdf(value) == render_pdf(value)
assert "Materialverbrauch gesamt: 100,00 kg" in content(value)
def test_material_chart_long_legend_paginates():
value = material_report((1,) * 80)
items = tuple(
replace(item, material_name=f"{index:02d} " + "Long material name <tag> & resin " * 3)
for index, item in enumerate(value.materials.items)
)
value = replace(value, materials=replace(value.materials, items=items))
assert render_pdf(value).count(b"/Type /Page\n") > 1
def material_table(value):
return next(
block
for block in present_report(value)
if isinstance(block, TableBlock) and block.headers[0] == "Materialname"
)
def test_material_summary_combines_channels_unknowns_and_uses_same_pie_totals():
value = material_report((10, 20, 5, 15, 30, 0))
items = tuple(
replace(
item,
extruder="Ex1" if index % 2 else "Ex2",
doser_channel="C7",
material_name=("Resin" if index < 2 else "Additive" if index == 4 else None),
)
for index, item in enumerate(value.materials.items)
)
value = replace(value, materials=replace(value.materials, items=items))
original = value.materials
assert material_table(value).rows == (
("Materialzuordnung fehlt", "–", "20,00 kg"),
("Additive", "–", "30,00 kg"),
("Resin", "–", "30,00 kg"),
)
chart = next(block for block in present_report(value) if isinstance(block, MaterialPieBlock))
assert chart.labels == ("Materialzuordnung fehlt", "Additive", "Resin")
assert chart.consumption_kg == (20, 30, 30)
assert sum(chart.consumption_kg) == value.materials.total_consumption_kg == 80
assert "Materialverbrauch gesamt: 80,00 kg" in content(value)
assert value.materials is original
assert value.materials.items == items
assert "Ex1" not in content(value) and "C7" not in content(value)
reversed_value = replace(
value, materials=replace(value.materials, items=tuple(reversed(items)))
)
assert present_report(value) == present_report(reversed_value)
assert render_pdf(value) == render_pdf(reversed_value)
def test_same_name_with_different_numbers_remains_distinct_and_legend_disambiguates():
value = material_report((10, 20))
items = tuple(
replace(item, material_name="Resin", material_number=f"M{index}")
for index, item in enumerate(value.materials.items)
)
value = replace(value, materials=replace(value.materials, items=items))
assert material_table(value).rows == (("Resin", "M0", "10,00 kg"), ("Resin", "M1", "20,00 kg"))
chart = next(block for block in present_report(value) if isinstance(block, MaterialPieBlock))
assert chart.labels == ("Resin (M0)", "Resin (M1)")
def test_historical_e1_unknown_channels_become_single_material_category():
from test_shift_material import aggregate, channel_sample
deltas = (
0,
4890.271,
4890.271,
1772.723,
0,
0,
672.412,
7596.677,
822.973,
2481.581,
1266.113,
0,
0,
493.784,
)
rows = [
channel_sample(
minute, counter, extruder=f"Ex{index // 7 + 1}", channel=f"C{index % 7 + 1}", name=None
)
for index, delta in enumerate(deltas)
for minute, counter in ((-1, 5000), (479, 5000 + delta))
]
summary = aggregate(rows, channel=True)
value = replace(report(), materials=summary)
assert len(summary.items) == 14
assert summary.total_consumption_kg == pytest.approx(24886.805)
assert material_table(value).rows == (("Materialzuordnung fehlt", "–", "24.886,81 kg"),)
assert not any(isinstance(block, MaterialPieBlock) for block in present_report(value))
def test_same_known_material_across_channels_has_one_row_and_no_pie():
value = material_report((10, 20, 0))
items = tuple(
replace(item, material_name="Resin", material_number="M1") for item in value.materials.items
)
value = replace(value, materials=replace(value.materials, items=items))
assert material_table(value).rows == (("Resin", "M1", "30,00 kg"),)
assert not any(isinstance(block, MaterialPieBlock) for block in present_report(value))
+255
View File
@@ -0,0 +1,255 @@
from dataclasses import replace
from datetime import UTC, date, datetime
from types import SimpleNamespace
from urllib.parse import urlencode
from wsgiref.util import setup_testing_defaults
from zoneinfo import ZoneInfo
import pytest
from test_shift_report_pdf import report
from production_analytics import web
from production_analytics.calculations.shift_report import (
most_recent_completed_shift,
shift_report_window,
)
from production_analytics.service.shift_report_config import (
load_shift_report_config,
load_shift_report_machines,
)
SHIFT_TIMEZONE = ZoneInfo("Europe/Berlin")
@pytest.mark.parametrize(
"hour,minute,day,shift",
[
(5, 0, 13, "late"),
(6, 0, 13, "night"),
(10, 0, 13, "night"),
(14, 0, 14, "early"),
(15, 46, 14, "early"),
(21, 59, 14, "early"),
(22, 0, 14, "late"),
(23, 0, 14, "late"),
(0, 0, 13, "late"),
],
)
def test_completed_shift(hour, minute, day, shift):
now = datetime(2026, 10, 14, hour, minute, tzinfo=SHIFT_TIMEZONE)
assert most_recent_completed_shift(now, SHIFT_TIMEZONE) == (date(2026, 10, day), shift)
start, end = shift_report_window(*most_recent_completed_shift(now, SHIFT_TIMEZONE),
SHIFT_TIMEZONE)
assert start.astimezone(UTC) < end.astimezone(UTC) <= now.astimezone(UTC)
@pytest.mark.parametrize("day,hours", [(date(2026, 3, 28), 7), (date(2026, 10, 24), 9)])
def test_dst_night(day, hours):
start, end = shift_report_window(day, "night", SHIFT_TIMEZONE)
assert (end.astimezone(UTC) - start.astimezone(UTC)).total_seconds() == hours * 3600
assert start.hour == 22 and end.hour == 6
assert most_recent_completed_shift(end, SHIFT_TIMEZONE) == (day, "night")
# Both occurrences of the autumn fold remain inside the running night shift.
for fold in (0, 1):
now = end.replace(hour=2, fold=fold)
assert most_recent_completed_shift(now, SHIFT_TIMEZONE) == (day, "late")
def test_clock_requires_timezone_and_accepts_utc():
with pytest.raises(ValueError):
most_recent_completed_shift(datetime(2026, 1, 1), SHIFT_TIMEZONE)
assert most_recent_completed_shift(datetime(2026, 10, 14, 12, tzinfo=UTC),
SHIFT_TIMEZONE) == (
date(2026, 10, 14),
"early",
)
def request(app, **params):
env = {}
setup_testing_defaults(env)
env["QUERY_STRING"] = urlencode(params)
response = []
payload = b"".join(app(env, lambda status, headers: response.append((status, dict(headers)))))
return *response[0], payload
@pytest.fixture
def application():
machines = load_shift_report_machines("config/shift-report-machines.yaml")
calls = []
value = report()
def build(**kwargs):
calls.append(kwargs)
return replace(
value, machine_name=kwargs["machine_name"], start=kwargs["start"], end=kwargs["end"]
)
app = web.create_app(
machines,
lambda: SimpleNamespace(build=build),
clock=lambda: datetime(2026, 10, 14, 15, 46, tzinfo=SHIFT_TIMEZONE),
)
return app, calls
def test_default_and_render(application):
app, calls = application
status, headers, body = request(app)
assert status == "200 OK"
assert calls == [
dict(
machine_name="B1",
start=shift_report_window(date(2026, 10, 14), "early", SHIFT_TIMEZONE)[0],
end=shift_report_window(date(2026, 10, 14), "early", SHIFT_TIMEZONE)[1],
)
]
text = body.decode()
for expected in (
"123,00 m²",
"42,00 kg",
"description",
"Ohne Stillstandsgrund",
"Nicht verfügbar",
"Datenstand: 14.10.2026 15:46:00 CEST",
"Europe/Berlin",
"Als PDF exportieren",
):
assert expected in text
assert headers["Cache-Control"] == "no-store"
def test_explicit_and_fresh_each_request(application):
app, calls = application
for _ in range(2):
assert request(app, date="2026-03-28", shift="night", machine="K7")[0] == "200 OK"
start, end = shift_report_window(date(2026, 3, 28), "night", SHIFT_TIMEZONE)
assert calls == [dict(machine_name="K7", start=start, end=end)] * 2
@pytest.mark.parametrize(
"params",
[
dict(machine="invalid"),
dict(shift="invalid"),
dict(date="bad"),
dict(date="9999-12-31", shift="night"),
],
)
def test_invalid_selection(application, params):
app, calls = application
status, _, body = request(app, **params)
assert status == "400 Bad Request"
assert "Ungültige Auswahl" in body.decode()
assert not calls
def test_failure_safe(application):
machines = load_shift_report_machines("config/shift-report-machines.yaml")
def fail():
raise RuntimeError("password=secret database.internal")
status, _, body = request(web.create_app(machines, fail))
assert status == "503 Service Unavailable"
assert "konnte nicht erstellt werden" in body.decode()
assert b"secret" not in body and b"database.internal" not in body
def test_pdf_uses_one_fresh_service_model(application, monkeypatch):
app, calls = application
rendered = []
def pdf(value):
rendered.append(value)
return b"%PDF-fake"
monkeypatch.setattr(web, "render_pdf", pdf)
status, headers, body = request(
app, date="2026-10-13", shift="night", machine="E1", format="pdf"
)
assert status == "200 OK" and headers["Content-Type"] == "application/pdf"
assert body == b"%PDF-fake"
assert len(calls) == len(rendered) == 1
assert rendered[0].machine_name == calls[0]["machine_name"]
assert (rendered[0].start, rendered[0].end) == shift_report_window(
date(2026, 10, 13), "night", SHIFT_TIMEZONE)
def test_source_markup_escaped():
from production_analytics.presentation.shift_report_html import render_page
value = report()
item = replace(value.production.items[0], article_description="<script>alert('x')</script>")
value = replace(value, production=replace(value.production, items=(item,)))
page = render_page(
machines={"E1": None},
labels=web.SHIFT_LABELS,
day=date(2026, 10, 14),
shift="early",
machine="E1",
report=value,
generated_at=datetime.now(SHIFT_TIMEZONE),
error=None,
)
assert "<script>" not in page and "&lt;script&gt;" in page
def test_site_metadata_reaches_web_presentation(monkeypatch):
config = load_shift_report_config("config/shift-report-machines.yaml")
received = []
def render_page(**kwargs):
received.append(kwargs["sites"])
return "page"
monkeypatch.setattr(web, "render_page", render_page)
app = web.create_app(config.machines, lambda: SimpleNamespace(build=lambda **kwargs: report()),
sites=config.sites)
assert request(app)[2] == b"page"
assert received[0]["malaysia"].display_name == "Malaysia"
def test_default_shift_uses_selected_machine_site_timezone():
config = load_shift_report_config("config/shift-report-machines.yaml")
malaysia = config.sites["malaysia"].timezone
machine = replace(config.machines["B1"], display_name="Synthetic Malaysia",
site="malaysia", timezone=malaysia, machine_id=None,
capabilities=replace(config.machines["B1"].capabilities,
downtime=False, material=False, speed=False),
material=None, speed=None)
machines = {"B1": config.machines["B1"], "Synthetic": machine}
calls = []
def build(**kwargs):
calls.append(kwargs)
selected = machines[kwargs["machine_name"]]
return replace(report(), machine_name=kwargs["machine_name"],
machine_id=selected.machine_id, timezone=selected.timezone,
start=kwargs["start"], end=kwargs["end"])
app = web.create_app(machines, lambda: SimpleNamespace(build=build),
clock=lambda: datetime(2026, 10, 19, 11, tzinfo=UTC))
assert request(app)[0] == "200 OK"
assert calls[-1]["machine_name"] == "B1"
assert (calls[-1]["start"], calls[-1]["end"]) == shift_report_window(
date(2026, 10, 18), "night", SHIFT_TIMEZONE)
status, _, body = request(app, machine="Synthetic")
assert status == "200 OK"
assert calls[-1]["machine_name"] == "Synthetic"
assert (calls[-1]["start"], calls[-1]["end"]) == shift_report_window(
date(2026, 10, 19), "early", malaysia)
assert b"Asia/Kuala_Lumpur" in body
assert request(app, machine="Synthetic", date="2026-10-18", shift="late")[0] == "200 OK"
assert (calls[-1]["start"], calls[-1]["end"]) == shift_report_window(
date(2026, 10, 18), "late", malaysia)
malaysia_first = web.create_app(
{"Synthetic": machine, "B1": config.machines["B1"]},
lambda: SimpleNamespace(build=build),
clock=lambda: datetime(2026, 10, 19, 11, tzinfo=UTC),
)
assert request(malaysia_first)[0] == "200 OK"
assert calls[-1]["machine_name"] == "Synthetic"
assert (calls[-1]["start"], calls[-1]["end"]) == shift_report_window(
date(2026, 10, 19), "early", malaysia)
+201
View File
@@ -1,3 +1,4 @@
from copy import deepcopy
from dataclasses import FrozenInstanceError, replace
from datetime import UTC, datetime, timedelta
from pathlib import Path
@@ -5,8 +6,10 @@ 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,
@@ -126,6 +129,101 @@ def test_zero_gate_excludes_zero_and_negative():
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
@@ -167,6 +265,53 @@ def test_gateway_pagination_column_order_and_unavailable_samples():
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": []}},
@@ -206,6 +351,62 @@ def test_validated_machine_configuration(name, machine, signal, gate):
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):