Files
LektorenPlan/Tests/LektorenPlanCoreTests/CoreTests.swift
T

331 lines
14 KiB
Swift
Raw 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.
import XCTest
@testable import LektorenPlanCore
final class CoreTests: XCTestCase {
func testEasterDates() {
XCTAssertEqual(DayMath.key(LiturgicalCalendarEngine.easterSunday(year: 2026)), "2026-04-05")
XCTAssertEqual(DayMath.key(LiturgicalCalendarEngine.easterSunday(year: 2027)), "2027-03-28")
XCTAssertEqual(DayMath.key(LiturgicalCalendarEngine.adventStart(year: 2026)), "2026-11-29")
XCTAssertEqual(DayMath.key(LiturgicalCalendarEngine.pentecost(year: 2026)), "2026-05-24")
}
func testLocalCalendarHighFeasts() {
let christmas = LiturgicalCalendarEngine.localDay(for: DayMath.date(fromKey: "2026-12-25")!)
XCTAssertTrue(christmas.isHighFeast)
XCTAssertTrue(christmas.isObligation)
XCTAssertFalse(christmas.readings.isEmpty)
let ordinary = LiturgicalCalendarEngine.localDay(for: DayMath.date(fromKey: "2026-11-10")!)
XCTAssertFalse(ordinary.isObligation)
}
func testDatabaseSeedAndCRUD() throws {
let db = try AppDatabase.makeInMemory(seedDemo: true)
XCTAssertEqual(try db.churches().count, 4)
XCTAssertGreaterThan(try db.services(in: DayRange.year(2026)).count, 300)
XCTAssertNotNil(try db.liturgicalDay(on: DayMath.date(fromKey: "2026-12-25")!))
let person = try XCTUnwrap(try db.person(id: "p-anna"))
XCTAssertTrue(person.roles.contains(.lector))
}
func testDemoResetRecreatesData() throws {
let db = try AppDatabase.makeInMemory(seedDemo: true)
let serviceCount = try db.serviceCount()
XCTAssertEqual(try db.churches().count, 4)
XCTAssertGreaterThan(serviceCount, 0)
try db.deleteAllData()
XCTAssertEqual(try db.churches().count, 0)
XCTAssertEqual(try db.people().count, 0)
XCTAssertEqual(try db.serviceCount(), 0)
XCTAssertEqual(try db.assignmentCount(), 0)
try db.resetDemoData()
XCTAssertEqual(try db.churches().count, 4)
XCTAssertEqual(try db.people().count, 22)
XCTAssertEqual(try db.serviceCount(), serviceCount)
XCTAssertGreaterThan(try db.assignments(in: DayRange.year(2025)).count, 0)
}
func testDeleteAllDataDoesNotReseedOnReopen() throws {
let url = FileManager.default.temporaryDirectory
.appendingPathComponent("lp-\(UUID().uuidString).sqlite")
defer { try? FileManager.default.removeItem(at: url) }
do {
let db = try AppDatabase(path: url.path, seedDemo: true)
XCTAssertEqual(try db.churches().count, 4)
try db.deleteAllData()
XCTAssertEqual(try db.churches().count, 0)
XCTAssertEqual(db.setting("suppressDemoSeed"), "1")
}
// Reopening must not silently restore the demo dataset.
let reopened = try AppDatabase(path: url.path, seedDemo: true)
XCTAssertEqual(try reopened.churches().count, 0)
// Explicitly restoring the demo clears the marker.
try reopened.resetDemoData()
XCTAssertEqual(try reopened.churches().count, 4)
XCTAssertNil(reopened.setting("suppressDemoSeed"))
}
func testSpecialServiceLocationRoundTrip() throws {
let db = try AppDatabase.makeInMemory(seedDemo: true)
let date = DayMath.date(fromKey: "2026-07-12")!
let service = ServiceOccurrence(
churchID: Church.andreasID,
location: "Open-Air auf dem Theaterplatz",
date: date,
timeMinutes: 18 * 60,
title: "Open-Air-Messe",
kind: .special
)
try db.upsert(service)
let loaded = try XCTUnwrap(try db.service(id: service.id))
XCTAssertEqual(loaded.location, "Open-Air auf dem Theaterplatz")
let church = try XCTUnwrap(try db.churches().first { $0.id == Church.andreasID })
XCTAssertEqual(loaded.placeName(church: church), "Open-Air auf dem Theaterplatz")
var cleared = loaded
cleared.location = " "
try db.upsert(cleared)
XCTAssertNil(try db.service(id: service.id)?.location)
}
func testPlannerRespectsAbsenceAndFillsSlots() throws {
let db = try AppDatabase.makeInMemory(seedDemo: false)
let church = Church(id: "c1", name: "Testkirche", shortName: "Test", symbol: .chapel, colorHex: "#000000")
try db.upsert(church)
let personA = Person(id: "a", firstName: "A", lastName: "A", roles: [.lector], maxPerMonth: 10)
let personB = Person(id: "b", firstName: "B", lastName: "B", roles: [.lector], maxPerMonth: 10)
try db.upsert(personA)
try db.upsert(personB)
let date = DayMath.date(fromKey: "2026-11-08")! // Sunday
try db.upsert(Absence(personID: "a", start: date, end: date, reason: "Test"))
let service = ServiceOccurrence(churchID: "c1", date: date, timeMinutes: 600, title: "Messe", lectorsNeeded: 1, helpersNeeded: 0)
try db.upsert(service)
let planner = ServicePlanner(
people: try db.people(),
absences: try db.absences(),
services: [service],
churches: [church]
)
let result = planner.plan()
XCTAssertEqual(result.filledCount, 1)
XCTAssertEqual(result.assignments.first?.personID, "b")
}
func testPlannerAssignsSamePersonToBothComplementaryRoles() {
let date = DayMath.date(fromKey: "2026-11-08")! // Sunday
let dual = Person(id: "dual", firstName: "Dana", lastName: "Doppel", roles: [.lector, .helper], maxPerMonth: 10)
let lectorOnly = Person(
id: "lector", firstName: "Lea", lastName: "Lektor", roles: [.lector],
preferredChurchIDs: ["c1"], maxPerMonth: 10
)
let helperOnly = Person(
id: "helper", firstName: "Hanna", lastName: "Helfer", roles: [.helper],
preferredChurchIDs: ["c1"], maxPerMonth: 10
)
let service = ServiceOccurrence(
churchID: "c1",
date: date,
timeMinutes: 600,
title: "Messe",
lectorsNeeded: 1,
helpersNeeded: 1
)
let planner = ServicePlanner(
people: [dual, lectorOnly, helperOnly],
absences: [],
services: [service]
)
let result = planner.plan()
XCTAssertEqual(result.filledCount, 2)
XCTAssertEqual(result.assignments.filter { $0.personID == "dual" }.count, 2)
XCTAssertEqual(Set(result.assignments.filter { $0.personID == "dual" }.map(\.role)), Set(Role.allCases))
XCTAssertEqual(result.assignments.count, 2)
}
func testPlannerFairnessOverridesDualRolePreference() {
let start = DayMath.date(fromKey: "2026-11-01")!
let dual = Person(id: "dual", firstName: "Dana", lastName: "Doppel", roles: [.lector, .helper], maxPerMonth: 10)
let lectorOnly = Person(id: "lector", firstName: "Lea", lastName: "Lektor", roles: [.lector], maxPerMonth: 10)
let helperOnly = Person(id: "helper", firstName: "Hanna", lastName: "Helfer", roles: [.helper], maxPerMonth: 10)
// The dual-role person already has many assignments; the others have none.
var services: [ServiceOccurrence] = []
var existing: [Assignment] = []
for index in 0..<5 {
let service = ServiceOccurrence(
id: "history-\(index)",
churchID: "c1",
date: DayMath.adding(days: index, to: start),
timeMinutes: 600,
title: "Messe",
lectorsNeeded: 0,
helpersNeeded: 0
)
services.append(service)
existing.append(Assignment(id: "history-a-\(index)", serviceID: service.id, personID: "dual", role: .lector))
}
let target = ServiceOccurrence(
id: "target",
churchID: "c1",
date: DayMath.adding(days: 10, to: start),
timeMinutes: 600,
title: "Messe",
lectorsNeeded: 1,
helpersNeeded: 1
)
services.append(target)
let planner = ServicePlanner(
people: [dual, lectorOnly, helperOnly],
absences: [],
services: services,
existingAssignments: existing
)
let result = planner.plan()
let targetAssignments = result.assignments.filter { $0.serviceID == target.id }
XCTAssertEqual(targetAssignments.count, 2)
XCTAssertEqual(Set(targetAssignments.map(\.personID)), Set(["lector", "helper"]))
XCTAssertFalse(targetAssignments.contains { $0.personID == "dual" })
}
func testPlannerStillRejectsDuplicateRoleForSamePerson() {
let date = DayMath.date(fromKey: "2026-11-08")!
let dual = Person(id: "dual", firstName: "Dana", lastName: "Doppel", roles: [.lector, .helper], maxPerMonth: 10)
let service = ServiceOccurrence(
churchID: "c1",
date: date,
timeMinutes: 600,
title: "Messe",
lectorsNeeded: 2,
helpersNeeded: 0
)
let planner = ServicePlanner(people: [dual], absences: [], services: [service])
let result = planner.plan()
XCTAssertEqual(result.filledCount, 1)
XCTAssertEqual(result.assignments.count, 1)
XCTAssertEqual(result.unfilled.count, 1)
}
func testDatabaseAllowsSamePersonInBothRoles() throws {
let db = try AppDatabase.makeInMemory(seedDemo: false)
let church = Church(id: "c1", name: "Testkirche", shortName: "Test", symbol: .chapel, colorHex: "#000000")
try db.upsert(church)
let person = Person(id: "dual", firstName: "Dana", lastName: "Doppel", roles: [.lector, .helper], maxPerMonth: 10)
try db.upsert(person)
let date = DayMath.date(fromKey: "2026-11-08")!
let service = ServiceOccurrence(
churchID: "c1",
date: date,
timeMinutes: 600,
title: "Messe",
lectorsNeeded: 1,
helpersNeeded: 1
)
try db.upsert(service)
try db.setAssignment(serviceID: service.id, role: .lector, personID: person.id)
try db.setAssignment(serviceID: service.id, role: .helper, personID: person.id)
let assignments = try db.assignments(serviceIDs: [service.id])
XCTAssertEqual(assignments.filter { $0.personID == person.id }.count, 2)
XCTAssertEqual(Set(assignments.filter { $0.personID == person.id }.map(\.role)), Set(Role.allCases))
}
func testExchangeRoundTrip() throws {
let source = try AppDatabase.makeInMemory(seedDemo: true)
let range = DayRange.quarter(containing: DayMath.date(fromKey: "2026-11-07")!)
let exchange = try source.exportPlan(range: range)
XCTAssertGreaterThan(exchange.services.count, 50)
let target = try AppDatabase.makeInMemory(seedDemo: false)
let summary = try target.applyPlanExchange(exchange)
XCTAssertEqual(summary.services, exchange.services.count)
XCTAssertEqual(try target.services(in: range).count, exchange.services.count)
XCTAssertGreaterThan(try target.assignments(in: range).count, 0)
}
func testStatisticsCoherence() throws {
let db = try AppDatabase.makeInMemory(seedDemo: true)
let range = DayRange.quarter(containing: DayMath.date(fromKey: "2026-11-07")!)
let services = try db.services(in: range)
let assignments = try db.assignments(in: range)
let stats = StatisticsCalculator.compute(
range: range,
services: services,
assignments: assignments,
people: try db.people(),
churches: try db.churches(),
absences: try db.absences()
)
XCTAssertEqual(stats.assignmentCount, assignments.count)
XCTAssertLessThanOrEqual(stats.openSlots, stats.requiredSlots)
XCTAssertEqual(stats.churchStats.reduce(0) { $0 + $1.services }, services.count)
}
func testDemoCoverage() throws {
let db = try AppDatabase.makeInMemory(seedDemo: true)
for label in ["Q4 2026", "2026", "2025"] {
let range: DayRange
if label == "Q4 2026" { range = DayRange.quarter(containing: DayMath.date(fromKey: "2026-11-07")!) }
else if label == "2026" { range = DayRange.year(2026) }
else { range = DayRange.year(2025) }
let stats = StatisticsCalculator.compute(
range: range,
services: try db.services(in: range),
assignments: try db.assignments(in: range),
people: try db.people(),
churches: try db.churches(),
absences: try db.absences()
)
print("DEMO \(label): services=\(stats.serviceCount) required=\(stats.requiredSlots) assigned=\(stats.assignmentCount) open=\(stats.openSlots) coverage=\(String(format: "%.1f", stats.coverageRate * 100))% preference=\(String(format: "%.1f", stats.preferenceRate * 100))%")
}
}
func testAbbreviatedNameKeepsFullSurname() {
let person = Person(firstName: "Anna", lastName: "Berg")
XCTAssertEqual(person.abbreviatedName, "A. Berg")
}
func testRangeLabelsAndPreferenceRate() {
let range = DayRange(
start: DayMath.date(fromKey: "2026-10-01")!,
end: DayMath.date(fromKey: "2026-12-31")!
)
XCTAssertEqual(range.shortTitle, "1. Okt. – 31. Dez. 2026")
var stats = RangeStatistics.empty
stats.assignmentCount = 10
stats.preferenceHits = 3
stats.preferenceEligible = 4
XCTAssertEqual(stats.preferenceRate, 0.75, accuracy: 0.0001)
stats.preferenceEligible = 0
XCTAssertEqual(stats.preferenceRate, 0)
}
func testAPIParsing() throws {
let json = """
{"Kalendername":"Test","Zelebrationen":{
"a":{"Datum":"2026-12-25","Tl":"Weihnachten","Rang":"H","Farbe":"w","L1":"Jes 52","EV":"Joh 1","Bem":"Am Tag"},
"b":{"Datum":"2026-12-25","Tl":"Weihnachten","Rang":"H","Farbe":"w","L1":"Jes 9","EV":"Lk 2","Bem":"In der Heiligen Nacht"}
}}
""".data(using: .utf8)!
let days = try LiturgicalCalendarAPI.parse(data: json, year: 2026)
let christmas = try XCTUnwrap(days.first { $0.dateKey == "2026-12-25" })
XCTAssertEqual(christmas.title, "Weihnachten")
XCTAssertEqual(christmas.readings.gospel, "Joh 1")
XCTAssertTrue(christmas.isObligation)
}
}