Files
production-analytics/tests/test_shift_report_pdf.py

342 lines
13 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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",
"order",
"article",
"description",
):
assert label in text
assert "Produktionszeit" not in text
assert "Liniengeschwindigkeit im Lauf" not in text
assert "Durchschnittliche Liniengeschwindigkeit" not in text
def test_production_pdf_table_contains_attributed_kpis_as_plain_text():
value = report("K7")
first = replace(value.production.items[0], production_order="12026001032",
average_speed_m_min=10.24, material_consumption_kg=3317.58)
second = replace(first, production_order="12026001037",
average_speed_m_min=None, material_consumption_kg=0)
value = replace(value, production=replace(value.production, items=(first, second)))
table = next(block for block in present_report(value)
if isinstance(block, TableBlock) and "Ø Geschwindigkeit" in block.headers)
assert table.rows[0][-2:] == ("10,24 m/min", "3.317,58 kg")
assert table.rows[1][-2:] == ("—", "0,00 kg")
assert table.rows[0][0] == "12026001032"
assert "Materialverbrauch gesamt: 42,00 kg" in content(value)
assert "Liniengeschwindigkeit im Lauf" not in content(value)
assert render_pdf(value).startswith(b"%PDF-")
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.",
"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))