Files
production-analytics/tests/test_production_order.py
T

272 lines
12 KiB
Python

"""Order search, shift assignment, and read-only web routes use fake ERP rows."""
from datetime import date, datetime
from unittest.mock import MagicMock
from urllib.parse import urlencode
from wsgiref.util import setup_testing_defaults
from zoneinfo import ZoneInfo
import pytest
from production_analytics import web
from production_analytics.erp.gateway import (
ErpProductionConfirmationGateway,
ErpSettings,
OrderConfirmationGroup,
OrderConfirmationRow,
)
from production_analytics.presentation.production_order_html import render_detail, render_search
from production_analytics.service.production_order import ProductionOrderService
from production_analytics.service.shift_report_config import load_shift_report_machines
ORDER = "82026400900"
BERLIN = ZoneInfo("Europe/Berlin")
MALAYSIA = ZoneInfo("Asia/Kuala_Lumpur")
MACHINES = load_shift_report_machines("config/shift-report-machines.yaml")
def row(hour, minute, *, workplace="GITTERIII", day=19, amount=10,
order=ORDER, article="A"):
return OrderConfirmationRow(order, workplace, article, "Article name",
datetime(2026, 10, day, hour, minute), amount)
class FakeGateway:
def __init__(self, rows=(), groups=()):
self.rows = list(rows)
self.groups = list(groups)
self.calls = []
def search_orders(self, query, *, limit=25):
self.calls.append(("search", query, limit))
return self.groups
def get_order_confirmations(self, production_order):
self.calls.append(("detail", production_order))
return self.rows
def group(order=ORDER, workplace="GITTERIII", article="A"):
return OrderConfirmationGroup(order, workplace, article, "Article name",
datetime(2026, 10, 19, 6), datetime(2026, 10, 19, 14))
def test_search_trims_and_collapses_rows_by_fa_with_multiple_workplaces():
gateway = FakeGateway(groups=[group(workplace="BENTO 1"), group(),
group("82026400901"), group(article="B")])
result = ProductionOrderService(gateway, MACHINES).search(" 82026400900 ")
assert gateway.calls == [("search", ORDER, 25)]
assert [entry.production_order for entry in result] == [ORDER, "82026400901"]
assert len(result[0].placements) == 3
assert {place.machine_name for place in result[0].placements} == {"B1", "Gitter 3"}
assert {place.timezone for place in result[0].placements} == {BERLIN}
def test_search_limit_and_order_are_deterministic_even_with_unsorted_gateway():
groups = [group("8202642"), group("8202641"), group("8202643"), group("8202641")]
service = ProductionOrderService(FakeGateway(groups=groups), MACHINES)
assert [value.production_order for value in service.search("820264", limit=2)] == [
"8202641", "8202642"]
assert [value.production_order for value in service.search("8202642", limit=2)] == [
"8202642", "8202641"]
@pytest.mark.parametrize("query", ["", " ", "\x00", "x" * 81])
def test_blank_or_invalid_search_never_queries_gateway(query):
gateway = FakeGateway()
with pytest.raises(ValueError):
ProductionOrderService(gateway, MACHINES).search(query)
assert gateway.calls == []
def test_unknown_workplace_is_visible_without_shift_assignment():
gateway = FakeGateway(rows=[row(7, 0, workplace="UNCONFIGURED")],
groups=[group(workplace="UNCONFIGURED")])
service = ProductionOrderService(gateway, MACHINES)
placement = service.search(ORDER)[0].placements[0]
assert placement.mapping_status == "unknown"
assert placement.machine_name is placement.site is placement.timezone is None
detail = service.detail(ORDER)
assert detail.placements[0].mapping_status == "unknown"
assert detail.shifts == ()
def test_ambiguous_workplace_is_visible_without_arbitrary_machine_choice():
from dataclasses import replace
machines = {"B1": MACHINES["B1"],
"Other": replace(MACHINES["B1"], display_name="Other")}
service = ProductionOrderService(FakeGateway(rows=[row(7, 0, workplace="BENTO 1")],
groups=[group(workplace="BENTO 1")]), machines)
assert service.search(ORDER)[0].placements[0].mapping_status == "ambiguous"
assert service.detail(ORDER).shifts == ()
def test_one_shift_aggregates_positive_feedback_and_confirmation_bounds():
service = ProductionOrderService(FakeGateway(rows=[row(6, 1, amount=2),
row(13, 59, amount=3)]), MACHINES)
detail = service.detail(ORDER)
assert len(detail.shifts) == 1
item = detail.shifts[0]
assert (item.machine_name, item.site, item.date, item.shift, item.produced_m2) == (
"Gitter 3", "adorf", date(2026, 10, 19), "early", 5)
assert (item.first_confirmation.hour, item.last_confirmation.hour) == (6, 13)
assert (item.shift_start.hour, item.shift_end.hour) == (6, 14)
def test_two_shifts_and_night_across_midnight():
rows = [row(13, 59), row(14, 0), row(22, 0), row(5, 59, day=20),
row(6, 0, day=20)]
shifts = ProductionOrderService(FakeGateway(rows=rows), MACHINES).detail(ORDER).shifts
assert [(item.date, item.shift, item.produced_m2) for item in shifts] == [
(date(2026, 10, 19), "early", 10),
(date(2026, 10, 19), "late", 10),
(date(2026, 10, 19), "night", 20),
(date(2026, 10, 20), "early", 10),
]
assert shifts[2].shift_end == datetime(2026, 10, 20, 6, tzinfo=BERLIN)
def test_same_fa_on_multiple_machines_uses_each_site_timezone():
rows = [row(7, 0), row(7, 0, workplace="K1", amount=4)]
shifts = ProductionOrderService(FakeGateway(rows=rows), MACHINES).detail(ORDER).shifts
assert len(shifts) == 2
assert {(item.machine_name, item.timezone) for item in shifts} == {
("Gitter 3", BERLIN), ("K1", MALAYSIA)}
assert shifts[0].shift_start.astimezone(ZoneInfo("UTC")) != (
shifts[1].shift_start.astimezone(ZoneInfo("UTC")))
def test_malaysia_before_six_belongs_to_previous_night_start_date():
shift = ProductionOrderService(FakeGateway(rows=[row(5, 45, workplace="K1",
day=20)]), MACHINES).detail(ORDER).shifts[0]
assert (shift.date, shift.shift, shift.timezone) == (
date(2026, 10, 19), "night", MALAYSIA)
assert shift.shift_start == datetime(2026, 10, 19, 22, tzinfo=MALAYSIA)
assert shift.shift_end == datetime(2026, 10, 20, 6, tzinfo=MALAYSIA)
def web_request(app, path, query="", method="GET"):
env = {}
setup_testing_defaults(env)
env.update(PATH_INFO=path, QUERY_STRING=query, REQUEST_METHOD=method)
result = []
body = b"".join(app(env, lambda status, headers: result.append((status, headers))))
return result[0][0], body.decode()
def test_search_and_detail_web_pages_and_encoded_report_link():
gateway = FakeGateway(rows=[row(7, 0)], groups=[group()])
service = ProductionOrderService(gateway, MACHINES)
app = web.create_app(MACHINES, lambda: None,
order_service_factory=lambda: service)
status, text = web_request(app, "/orders")
assert status == "200 OK" and "Fertigungsauftrag suchen" in text
assert gateway.calls == []
status, text = web_request(app, "/orders", urlencode({"q": " 820264 "}))
assert status == "200 OK" and ORDER in text and "/order?production_order=" in text
status, text = web_request(app, "/order", urlencode({"production_order": ORDER}))
assert status == "200 OK"
assert '<a href="/orders" aria-current="page">Fertigungsauftrag</a>' in text
assert "Article name" in text and "10.00 m²" in text
assert "Schichtbericht" in text
assert "/?date=2026-10-19&amp;shift=early&amp;machine=Gitter+3" in text
@pytest.mark.parametrize("html", [render_search(), render_detail(detail=None)],
ids=["search", "detail"])
def test_order_pages_mark_order_mode_active(html):
assert '<nav class="mode-nav" aria-label="Bereich wählen">' in html
assert '<a href="/">Schichtbericht</a>' in html
assert '<a href="/orders" aria-current="page">Fertigungsauftrag</a>' in html
assert html.split("</style>", 1)[1].count('aria-current="page"') == 1
assert ".mode-nav a:focus-visible" in html
def test_order_pages_escape_erp_text():
unsafe = "<script>alert(1)</script>"
gateway = FakeGateway(
rows=[OrderConfirmationRow(ORDER, "GITTERIII", "A", unsafe,
datetime(2026, 10, 19, 7), 1)],
groups=[OrderConfirmationGroup(ORDER, "GITTERIII", "A", unsafe,
datetime(2026, 10, 19, 7),
datetime(2026, 10, 19, 7))],
)
app = web.create_app(MACHINES, lambda: None,
order_service_factory=lambda: ProductionOrderService(gateway, MACHINES))
for path, query in (("/orders", "q=820264"), ("/order", f"production_order={ORDER}")):
assert "<script>" not in web_request(app, path, query)[1]
assert "&lt;script&gt;" in web_request(app, path, query)[1]
@pytest.mark.parametrize("path,query,status", [
("/orders", "q=", "400 Bad Request"),
("/order", "", "400 Bad Request"),
("/order", "production_order=", "400 Bad Request"),
("/orders", "q=a&q=b", "400 Bad Request"),
("/orders", "extra=1", "400 Bad Request"),
])
def test_malformed_web_parameters_do_not_query(path, query, status):
gateway = FakeGateway()
service = ProductionOrderService(gateway, MACHINES)
app = web.create_app(MACHINES, lambda: None, order_service_factory=lambda: service)
actual, _ = web_request(app, path, query)
assert actual == status
assert gateway.calls == []
def test_order_web_errors_are_safe():
def fail():
raise RuntimeError("password=secret.internal")
app = web.create_app(MACHINES, lambda: None, order_service_factory=fail)
status, body = web_request(app, "/orders", "q=820264")
assert status == "503 Service Unavailable"
assert "secret.internal" not in body
assert web_request(app, "/order", "production_order=820264")[0] == (
"503 Service Unavailable")
assert web_request(app, "/orders", "q=820264", method="POST")[0] == (
"405 Method Not Allowed")
def test_missing_order_returns_404_without_source_details():
gateway = FakeGateway()
app = web.create_app(MACHINES, lambda: None, order_service_factory=lambda: (
ProductionOrderService(gateway, MACHINES)))
status, body = web_request(app, "/order", f"production_order={ORDER}")
assert status == "404 Not Found"
assert "nicht gefunden" in body
def test_gateway_search_is_parameterized_bounded_and_escapes_like(monkeypatch):
connect = MagicMock()
monkeypatch.setattr("production_analytics.erp.gateway.pymssql.connect", connect)
cursor = connect.return_value.__enter__.return_value.cursor.return_value.__enter__.return_value
cursor.fetchall.return_value = [
(ORDER, "GITTERIII", "A", "Article name", datetime(2026, 10, 19, 6),
datetime(2026, 10, 19, 14)),
(ORDER, "K1", "A", "Article name", datetime(2026, 10, 19, 6),
datetime(2026, 10, 19, 14)),
]
gateway = ErpProductionConfirmationGateway(ErpSettings("host", 1433, "db", "u", "p"))
result = gateway.search_orders(" 820264%_ ", limit=12)
assert len(result) == 2
sql, params = cursor.execute.call_args.args
assert "TOP (%s)" in sql and "GROUP BY" in sql
assert params == (12, "%820264\\%\\_%", "820264%_", "820264%_")
assert "820264%_" not in sql
assert connect.return_value.__exit__.called
def test_gateway_detail_uses_exact_fa_and_reuses_positive_feedback_semantics(monkeypatch):
connect = MagicMock()
monkeypatch.setattr("production_analytics.erp.gateway.pymssql.connect", connect)
cursor = connect.return_value.__enter__.return_value.cursor.return_value.__enter__.return_value
cursor.fetchall.return_value = [(ORDER, "GITTERIII", "A", "Article name",
datetime(2026, 10, 19, 7), 3)]
gateway = ErpProductionConfirmationGateway(ErpSettings("host", 1433, "db", "u", "p"))
assert gateway.get_order_confirmations(" " + ORDER + " ")[0].feedback_quantity_m2 == 3
sql, params = cursor.execute.call_args.args
assert params == (ORDER,)
assert "[Fertigungsauftragsnummer] = %s" in sql
assert "[Rückmeldemenge] > 0" in sql