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", "Datenstand: 14.10.2026 15:46:00 CEST", "Europe/Berlin", "Als PDF exportieren", ): assert expected in text assert "Durchschnittliche Liniengeschwindigkeit im Lauf" not 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="") 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 "