Files
production-analytics/tests/test_postgres_shift_material.py
2026-10-07 21:58:18 +02:00

216 lines
8.1 KiB
Python

import traceback
from datetime import UTC, datetime, timedelta
from unittest.mock import MagicMock
import pytest
from production_analytics.service.postgres_material import PostgresSettings
from production_analytics.service.postgres_shift_material import (
PostgresShiftChannelMaterialRepository,
PostgresShiftMaterialRepository,
ShiftMaterialReadError,
)
START = datetime(2026, 10, 7, 4, tzinfo=UTC)
END = START + timedelta(hours=8)
@pytest.fixture(params=[False, True], ids=["machine", "channel"])
def db(request, monkeypatch):
connect = MagicMock()
monkeypatch.setattr("psycopg.connect", connect)
connection = connect.return_value.__enter__.return_value
channel = request.param
row = (
(
START,
"calc",
"machine",
"Ex1",
"C2",
"order",
"run",
123.0,
None,
None,
"UNAVAILABLE",
True,
)
if channel
else (START, "calc", "machine", "order", "run", 123.0)
)
connection.execute.return_value.fetchall.return_value = [row]
cls = PostgresShiftChannelMaterialRepository if channel else PostgresShiftMaterialRepository
return (
cls(PostgresSettings("localhost", 5432, "db", "user", "pw")),
connect,
connection,
channel,
)
def read(repository, **changes):
return repository.get_snapshots(
**{
"machine_id": "machine",
"calculation_ids": ("calc",),
"start": START,
"end": END,
**changes,
}
)
def test_one_query_parameterization_baseline_and_strict_end(db):
repository, connect, connection, channel = db
snapshots = read(repository)
sql, params = connection.execute.call_args.args
assert params == ("machine", ["calc"], START, END)
assert "timestamp <= r.start_time" in sql
assert "timestamp > r.start_time AND timestamp < r.end_time" in sql
assert "UNION ALL" in sql
assert "EXISTS" not in sql and "DENSE_RANK" not in sql and "scoped" not in sql
assert "MIN(" not in sql and "MAX(" not in sql
assert "calculation_id = ANY(r.calculation_ids)" in sql
assert ("FROM channel_material_consumption_snapshots" in sql) is channel
assert ("FROM material_consumption_snapshots" in sql) is not channel
if channel:
assert "DISTINCT ON (s.calculation_id, extruder, doser_channel)" in sql
assert "ORDER BY s.calculation_id, extruder, doser_channel, timestamp DESC" in sql
else:
assert "unnest(r.calculation_ids)" in sql
assert "calculation_id = ids.calculation_id AND machine_id = r.machine_id" in sql
assert "ORDER BY timestamp DESC, run_id, production_order" in sql
assert "LIMIT 1" in sql
# Valid baseline filters never affect the in-window branch, which must keep
# null, non-finite, and negative counters for run/reset validation.
baseline, window = sql.split("UNION ALL")
counter = "cumulative_consumption_kg" if channel else "consumption_kg"
assert f"{counter} >= 0" in baseline
assert f"{counter} < 'Infinity'::double precision" in baseline
assert f"{counter} >=" not in window and f"{counter} <" not in window
order = "calculation_id, " + ("extruder, doser_channel, " if channel else "")
assert sql.rstrip().endswith(f"ORDER BY {order}timestamp, run_id, production_order")
connection.execute.assert_called_once()
connection.execute.return_value.fetchall.assert_called_once()
connect.assert_called_once_with(
host="localhost",
port=5432,
dbname="db",
user="user",
password="pw",
connect_timeout=10,
options="-c statement_timeout=10000",
)
connect.return_value.__exit__.assert_called_once()
assert snapshots[0].run_id == "run"
assert snapshots[0].timestamp is START
if channel:
assert snapshots[0].material_name is None
assert snapshots[0].doser_channel == "C2"
assert snapshots[0].material_mapping_status == "UNAVAILABLE"
connection.commit.assert_not_called()
def test_parameterized_multiple_calculations(db):
ids = ("calc'; DELETE FROM x; --", "second")
read(db[0], calculation_ids=ids)
sql, params = db[2].execute.call_args.args
assert params[1] == list(ids)
assert ids[0] not in sql
def test_validation_before_connect(db):
for changes in (
{"start": START.replace(tzinfo=None)},
{"end": START},
{"machine_id": "bad\x00"},
{"calculation_ids": ()},
):
with pytest.raises(ValueError):
read(db[0], **changes)
db[1].assert_not_called()
def test_empty_result(db):
db[2].execute.return_value.fetchall.return_value = []
assert read(db[0]) == []
@pytest.mark.parametrize("stage", ["connect", "execute", "fetch", "close"])
def test_safe_driver_errors(db, stage):
repository, connect, connection, _ = db
target = {
"connect": connect,
"execute": connection.execute,
"fetch": connection.execute.return_value.fetchall,
"close": connect.return_value.__exit__,
}[stage]
target.side_effect = RuntimeError("private-password")
with pytest.raises(ShiftMaterialReadError, match="read failed") as error:
read(repository)
assert "private-password" not in "".join(traceback.format_exception(error.value))
def test_invalid_row_shape_wrapped(db):
db[2].execute.return_value.fetchall.return_value = [("bad",)]
with pytest.raises(ShiftMaterialReadError, match="invalid row"):
read(db[0])
def test_multiple_baselines_and_raw_window_rows_are_preserved(db):
repository, _, connection, channel = db
original = connection.execute.return_value.fetchall.return_value[0]
counter_index = 7 if channel else 5
def row(timestamp, value, calculation="calc", stream="C2"):
values = list(original)
values[0], values[1], values[counter_index] = timestamp, calculation, value
if channel:
values[4] = stream
return tuple(values)
# A baseline per calculation (and per channel), exact-start baseline, and
# raw null/reset rows all survive repository decoding without carry-forward.
rows = [
row(START, 100),
row(START + timedelta(seconds=1), None),
row(START + timedelta(seconds=2), -1),
row(END - timedelta(microseconds=1), 110),
]
if channel:
rows += [row(START, 200, stream="C3"), row(START + timedelta(seconds=1), 205, stream="C3")]
rows += [row(START - timedelta(seconds=1), 300, calculation="second")]
connection.execute.return_value.fetchall.return_value = rows
snapshots = read(repository, calculation_ids=("calc", "second"))
assert [snapshot.timestamp for snapshot in snapshots] == [row[0] for row in rows]
counter = "cumulative_consumption_kg" if channel else "consumption_kg"
assert [getattr(snapshot, counter) for snapshot in snapshots] == [
row[counter_index] for row in rows
]
assert {snapshot.calculation_id for snapshot in snapshots} == {"calc", "second"}
if channel:
assert {snapshot.doser_channel for snapshot in snapshots} == {"C2", "C3"}
assert all(snapshot.material_name is None for snapshot in snapshots)
connection.execute.assert_called_once()
def test_missing_baseline_leaves_in_window_sample_for_fallback(db):
repository, _, connection, _ = db
values = list(connection.execute.return_value.fetchall.return_value[0])
values[0] = START + timedelta(minutes=1)
connection.execute.return_value.fetchall.return_value = [tuple(values)]
snapshots = read(repository)
assert len(snapshots) == 1
assert snapshots[0].timestamp == START + timedelta(minutes=1)
from production_analytics.calculations.shift_material import (
aggregate_shift_channel_material,
aggregate_shift_material,
)
aggregate = aggregate_shift_channel_material if db[3] else aggregate_shift_material
summary = aggregate(snapshots, machine_id="machine", calculation_ids=("calc",),
start=START, end=END)
assert summary.total_consumption_kg == 0
assert summary.items[0].baseline_missing