Files
LektorenPlan/web/pdf/pdf_test.go
T
2026-11-19 08:14:13 +01:00

311 lines
11 KiB
Go

package pdf
import (
"bytes"
"compress/zlib"
"fmt"
"io"
"regexp"
"strconv"
"strings"
"testing"
"time"
"lektorenplan/domain"
)
func sampleRows() (domain.DayRange, []domain.DayPlanRow, []domain.Church, []domain.Person) {
church := domain.Church{ID: "c1", Name: "St. Andreas", ShortName: "Andreas",
Symbol: domain.SymbolBasilica, ColorHex: "#9B5B44", Address: "Andreasstraße 1", SortIndex: 0}
person := domain.Person{ID: "p1", FirstName: "Anna", LastName: "Berg",
Roles: []domain.Role{domain.RoleLector}, Active: true}
service := domain.ServiceOccurrence{
ID: "s1", ChurchID: "c1", Date: domain.MustDate("2026-11-15"),
TimeMinutes: 9*60 + 30, Title: "Hochamt", LectorsNeeded: 1, HelpersNeeded: 2,
Kind: domain.KindRegular, CreatedAt: time.Now(),
}
assignment := domain.Assignment{ID: "a1", ServiceID: "s1", PersonID: "p1", Role: domain.RoleLector}
liturgy := domain.LiturgicalDay{
Date: domain.MustDate("2026-11-15"), Title: "33. Sonntag im Jahreskreis",
Rank: domain.RankSolemnity, Color: domain.ColorGreen,
Readings: domain.Readings{First: "Mal 3, 19-20a", Gospel: "Lk 21, 5-19"},
IsObligation: true, Source: "test",
}
row := domain.DayPlanRow{
Date: domain.MustDate("2026-11-15"), LiturgicalDay: &liturgy,
Services: []domain.ServiceWithAssignments{{Service: service, Church: church, Assignments: []domain.Assignment{assignment}}},
}
r := domain.NewDayRange(domain.MustDate("2026-11-15"), domain.MustDate("2026-11-15"))
return r, []domain.DayPlanRow{row}, []domain.Church{church}, []domain.Person{person}
}
func umlautRows() (domain.DayRange, []domain.DayPlanRow, []domain.Church, []domain.Person) {
location := "Mariä-Himmelfahrt-Kapelle"
church := domain.Church{ID: "c1", Name: "St. Mariä Himmelfahrt", ShortName: "Mariä",
Symbol: domain.SymbolBasilica, ColorHex: "#9B5B44", Address: "Andreasstraße 1", SortIndex: 0}
person := domain.Person{ID: "p1", FirstName: "Jürgen", LastName: "Müller",
Roles: []domain.Role{domain.RoleLector}, Active: true}
service := domain.ServiceOccurrence{
ID: "s1", ChurchID: "c1", Date: domain.MustDate("2026-11-15"),
TimeMinutes: 9*60 + 30, Title: "Hochamt für die Gemeinde", Location: &location,
LectorsNeeded: 1, HelpersNeeded: 1, Kind: domain.KindRegular, CreatedAt: time.Now(),
}
assignment := domain.Assignment{ID: "a1", ServiceID: "s1", PersonID: "p1", Role: domain.RoleLector}
liturgy := domain.LiturgicalDay{
Date: domain.MustDate("2026-11-15"), Title: "Hochfest Mariä Himmelfahrt",
Rank: domain.RankSolemnity, Color: domain.ColorWhite,
Readings: domain.Readings{First: "Jes 61, 9a.10b", Gospel: "Lk 1, 39-56"},
IsObligation: true, Source: "test",
}
row := domain.DayPlanRow{
Date: domain.MustDate("2026-11-15"), LiturgicalDay: &liturgy,
Services: []domain.ServiceWithAssignments{{Service: service, Church: church, Assignments: []domain.Assignment{assignment}}},
}
r := domain.NewDayRange(domain.MustDate("2026-11-15"), domain.MustDate("2026-11-15"))
return r, []domain.DayPlanRow{row}, []domain.Church{church}, []domain.Person{person}
}
// pdfContentStreams returns the decoded page content streams of a PDF. Text
// written with core fonts is stored there as single-byte cp1252 strings.
func pdfContentStreams(t *testing.T, data []byte) []byte {
t.Helper()
var out bytes.Buffer
for {
open := bytes.Index(data, []byte("stream"))
if open < 0 {
break
}
start := open + len("stream")
if start < len(data) && data[start] == '\r' {
start++
}
if start < len(data) && data[start] == '\n' {
start++
}
end := bytes.Index(data[start:], []byte("endstream"))
if end < 0 {
break
}
raw := bytes.TrimRight(data[start:start+end], "\r\n")
if reader, err := zlib.NewReader(bytes.NewReader(raw)); err == nil {
decoded, err := io.ReadAll(reader)
reader.Close()
if err == nil {
out.Write(decoded)
out.WriteByte('\n')
}
} else {
out.Write(raw)
out.WriteByte('\n')
}
data = data[start+end+len("endstream"):]
}
if out.Len() == 0 {
t.Fatal("no content streams found in PDF")
}
return out.Bytes()
}
func TestPDFUmlautsAreEncoded(t *testing.T) {
r, rows, churches, people := umlautRows()
person := people[0]
cover := CoverData{
TenantName: "Köln", Diocese: "Erzbistum Köln", Range: r, Person: person,
Intro: "Grüße aus dem Pfarrbüro.",
Greeting: "Herzliche Grüße",
Assignments: []DispatchAssignment{{
Date: domain.MustDate("2026-11-15"), TimeMinutes: 9*60 + 30,
Church: "St. Mariä Himmelfahrt", Title: "Hochamt für die Gemeinde", Role: domain.RoleLector,
}},
GeneratedAt: time.Now(),
}
documents := []struct {
name string
render func(io.Writer) error
present []string
}{
{
name: "full",
render: func(w io.Writer) error {
return FullPlan(w, r, rows, churches, people, Options{TenantName: "Köln", Diocese: "Erzbistum Köln"})
},
present: []string{"K\xf6ln", "M\xfcller", "Andreasstra\xdfe", "Mari\xe4", "f\xfcr"},
},
{
name: "compact",
render: func(w io.Writer) error {
return CompactPlan(w, r, rows, people, Options{TenantName: "Köln", Diocese: "Erzbistum Köln"})
},
present: []string{"K\xd6LN", "M\xfcller", "Mari\xe4", "f\xfcr"},
},
{
name: "cover",
render: func(w io.Writer) error { return Cover(w, cover) },
present: []string{
"K\xf6ln", "M\xfcller", "Mari\xe4", "f\xfcr", "Gr\xfc\xdfe",
},
},
}
for _, document := range documents {
t.Run(document.name, func(t *testing.T) {
var buf bytes.Buffer
if err := document.render(&buf); err != nil {
t.Fatalf("render: %v", err)
}
content := pdfContentStreams(t, buf.Bytes())
for _, want := range document.present {
if !bytes.Contains(content, []byte(want)) {
t.Errorf("cp1252 sequence %q missing from PDF content", want)
}
}
for _, raw := range []string{
"K\xc3\xb6ln", "M\xc3\xbcller", "Andreasstra\xc3\x9fe", "Mari\xc3\xa4", "f\xc3\xbcr", "Gr\xc3\xbc\xc3\x9fe",
} {
if bytes.Contains(content, []byte(raw)) {
t.Errorf("raw UTF-8 sequence %q found in PDF content", raw)
}
}
})
}
}
func TestFullPlan(t *testing.T) {
r, rows, churches, people := sampleRows()
var buf bytes.Buffer
if err := FullPlan(&buf, r, rows, churches, people, Options{TenantName: "Bad Godesberg"}); err != nil {
t.Fatalf("render: %v", err)
}
if buf.Len() < 1000 || !bytes.HasPrefix(buf.Bytes(), []byte("%PDF")) {
t.Fatalf("unexpected PDF output (%d bytes)", buf.Len())
}
}
func multiPageRows() (domain.DayRange, []domain.DayPlanRow, []domain.Church, []domain.Person) {
_, _, churches, people := sampleRows()
church := churches[0]
person := people[0]
start := domain.MustDate("2026-01-01")
var rows []domain.DayPlanRow
for index := 0; index < 60; index++ {
date := domain.AddingDays(index, start)
var services []domain.ServiceWithAssignments
for slot := 0; slot < 3; slot++ {
id := fmt.Sprintf("s-%d-%d", index, slot)
services = append(services, domain.ServiceWithAssignments{
Service: domain.ServiceOccurrence{
ID: id, ChurchID: church.ID, Date: date,
TimeMinutes: 8*60 + slot, Title: "Hochamt",
LectorsNeeded: 1, HelpersNeeded: 1,
Kind: domain.KindRegular, CreatedAt: time.Now(),
},
Church: church,
Assignments: []domain.Assignment{{
ID: "a-" + id, ServiceID: id, PersonID: person.ID,
Role: domain.RoleLector, CreatedAt: time.Now(),
}},
})
}
rows = append(rows, domain.DayPlanRow{Date: date, Services: services})
}
return domain.NewDayRange(start, rows[len(rows)-1].Date), rows, churches, people
}
func TestFullPlanPaginatesWithTotalPageCount(t *testing.T) {
r, rows, churches, people := multiPageRows()
var buf bytes.Buffer
if err := FullPlan(&buf, r, rows, churches, people, Options{TenantName: "Bad Godesberg"}); err != nil {
t.Fatalf("render: %v", err)
}
content := string(pdfContentStreams(t, buf.Bytes()))
if strings.Contains(content, "Fortsetzung") {
t.Fatal("continuation title must not appear on later pages")
}
match := regexp.MustCompile(`Seite 1 von (\d+)`).FindStringSubmatch(content)
if match == nil {
t.Fatalf("first page footer is missing the total page count:\n%s", content)
}
total, err := strconv.Atoi(match[1])
if err != nil || total < 2 {
t.Fatalf("total pages = %q, want at least 2", match[1])
}
if !strings.Contains(content, fmt.Sprintf("Seite %d von %d", total, total)) {
t.Fatalf("last page footer is missing: want Seite %d von %d", total, total)
}
if got := strings.Count(content, "Seite "); got != total {
t.Fatalf("footer count = %d, want %d", got, total)
}
}
func TestFullPlanRowHeightGrowsWithSeveralServices(t *testing.T) {
_, rows, _, people := sampleRows()
pdf := newPDF("L")
tr := translator(pdf)
peopleByID := map[string]domain.Person{}
for _, person := range people {
peopleByID[person.ID] = person
}
churchWidth := (297.0 - 8.5*2 - 17.0 - 57.0 - 1.35*5) / 4
row := rows[0]
oneService := fullPlanRowHeight(pdf, tr, row, churchWidth, peopleByID)
base := row.Services[0]
for index := 0; index < 3; index++ {
extra := base
extra.Service.ID = fmt.Sprintf("extra-%d", index)
extra.Service.TimeMinutes = 11*60 + index
row.Services = append(row.Services, extra)
}
fourServices := fullPlanRowHeight(pdf, tr, row, churchWidth, peopleByID)
if fourServices <= oneService {
t.Fatalf("row height did not grow: one service %.1f, four services %.1f", oneService, fourServices)
}
// A row must have room for all four service blocks, not a fixed cap.
if fourServices-oneService < 3*9 {
t.Fatalf("row height %.1f is too small for four services (one service %.1f)", fourServices, oneService)
}
}
func TestCompactPlan(t *testing.T) {
r, rows, _, people := sampleRows()
var buf bytes.Buffer
if err := CompactPlan(&buf, r, rows, people, Options{TenantName: "Bad Godesberg"}); err != nil {
t.Fatalf("render: %v", err)
}
if buf.Len() < 1000 || !bytes.HasPrefix(buf.Bytes(), []byte("%PDF")) {
t.Fatalf("unexpected PDF output (%d bytes)", buf.Len())
}
}
func TestCompactPlanPaginatesWithoutContinuationTitle(t *testing.T) {
r, rows, _, people := multiPageRows()
var buf bytes.Buffer
if err := CompactPlan(&buf, r, rows, people, Options{TenantName: "Bad Godesberg"}); err != nil {
t.Fatalf("render: %v", err)
}
content := string(pdfContentStreams(t, buf.Bytes()))
if strings.Contains(content, "Fortsetzung") {
t.Fatal("continuation title must not appear on later pages")
}
if strings.Contains(content, "A4 hoch") {
t.Fatal("paper hint must not appear in the compact header")
}
match := regexp.MustCompile(`Seite 1 von (\d+)`).FindStringSubmatch(content)
if match == nil {
t.Fatalf("first page footer is missing the total page count:\n%s", content)
}
total, err := strconv.Atoi(match[1])
if err != nil || total < 2 {
t.Fatalf("total pages = %q, want at least 2", match[1])
}
if !strings.Contains(content, fmt.Sprintf("Seite %d von %d", total, total)) {
t.Fatalf("last page footer is missing: want Seite %d von %d", total, total)
}
if got := strings.Count(content, "Seite "); got != total {
t.Fatalf("footer count = %d, want %d", got, total)
}
}