SPB Git

Repository Public

FeaturesTests.swift 9.5 KB 138 lines swift

1import Foundation2import Testing3@testable import MCCCore45@Suite("Shared feature models")6@MainActor7struct FeaturesTests {8    @Test("setup links: the token is taken from the fragment; anything else is refused")9    func setupLinks() {10        let token = String(repeating: "aB3-_", count: 9)11        #expect(SetupLink.token(from: "https://clustr.spboucher.ai/setup#\(token)") == token)12        #expect(SetupLink.token(from: "\n http://localhost:8760/setup#\(token) ") == token)13        #expect(SetupLink.token(from: token) == token)14        #expect(SetupLink.token(from: "https://clustr.spboucher.ai/setup") == nil)15        #expect(SetupLink.token(from: "https://clustr.spboucher.ai/setup?token=\(token)") == nil)   // never in the query16        #expect(SetupLink.token(from: "https://clustr.spboucher.ai/nodes#\(token)") == nil)17        #expect(SetupLink.token(from: "abc") == nil)18        #expect(SetupLink.isSetupURL(URL(string: "https://clustr.spboucher.ai/setup#\(token)")!))19    }2021    @Test("JSON Schema → form fields (kinds, required first, defaults, bounds)")22    func schemaFields() {23        let schema = Fixture.json(#"{"type":"object","required":["profile"],"properties":{"profile":{"type":"string","enum":["basic","network","disk"],"description":"Diagnostic profile."},"lines":{"type":"integer","minimum":1,"maximum":500,"default":200},"ratio":{"type":"number"},"follow":{"type":"boolean"},"extra":{"type":"object"},"note":{"type":"string","title":"Note"}}}"#)24        let fields = SchemaField.fields(from: schema)25        #expect(fields.map(\.name) == ["profile", "extra", "follow", "lines", "note", "ratio"])26        #expect(fields[0].kind == .choice(["basic", "network", "disk"]) && fields[0].required && fields[0].help == "Diagnostic profile.")27        #expect(fields.first { $0.name == "lines" }?.kind == .integer(min: 1, max: 500))28        #expect(fields.first { $0.name == "lines" }?.defaultValue == .number(200))29        #expect(fields.first { $0.name == "follow" }?.kind == .boolean)30        #expect(fields.first { $0.name == "extra" }?.kind == .json)31        #expect(fields.first { $0.name == "note" }?.title == "Note")32        #expect(SchemaField.fields(from: Fixture.json(#"{"type":"object"}"#)).isEmpty)33    }3435    private func occurrence(_ title: String, start: String, end: String) -> API.MaintenanceOccurrence {36        try! JSONDecoder.mcc.decode(API.MaintenanceOccurrence.self, from: Data(#"{"window":{"id":"0199aaaa-0000-7000-8000-0000000000e1","title":"\#(title)","description":"","category":"planned","starts_at":"\#(start)","ends_at":"\#(end)","timezone":"America/Toronto","recurrence":"none","scope":{"node_ids":[]},"set_maintenance_mode":true,"silence_alerts":true,"status":"scheduled","created_at":"2026-11-01T00:00:00Z","updated_at":"2026-11-01T00:00:00Z"},"occurrence_start":"\#(start)","occurrence_end":"\#(end)","note_count":0}"#.utf8))37    }3839    @Test("calendar math: month grid, week start by language, overlaps across midnight, agenda")40    func calendarMath() {41        let tz = TimeZone(identifier: "America/Toronto")!42        let fr = CalendarMath.calendar(language: .fr, timeZone: tz), en = CalendarMath.calendar(language: .en, timeZone: tz)43        let day = try! Date.ISO8601FormatStyle().parse("2026-11-18T17:00:00Z")      // Wednesday 18 Nov 2026, noon in Toronto44        let grid = CalendarMath.monthGrid(containing: day, calendar: fr, today: day)45        #expect(grid.count == 42)46        #expect(fr.component(.weekday, from: grid[0].date) == 2)                    // Monday first in French47        #expect(en.component(.weekday, from: CalendarMath.monthGrid(containing: day, calendar: en)[0].date) == 1)48        #expect(grid.filter(\.inDisplayedMonth).count == 30)49        #expect(grid.filter(\.isToday).count == 1)50        #expect(fr.component(.day, from: grid.first { $0.inDisplayedMonth }!.date) == 1)51        let week = CalendarMath.week(containing: day, calendar: fr, today: day)52        #expect(week.count == 7 && fr.component(.day, from: week[0].date) == 16)53        let window = CalendarMath.window(for: week, calendar: fr)!54        #expect(window.to.timeIntervalSince(window.from) == 7 * 86_400)55        #expect(CalendarMath.weekdaySymbols(calendar: fr).count == 7)5657        // 22:00 → 02:00 local: appears on both days.58        let overnight = occurrence("Overnight", start: "2026-11-19T03:00:00Z", end: "2026-11-19T07:00:00Z")59        let morning = occurrence("Morning", start: "2026-11-18T14:00:00Z", end: "2026-11-18T15:00:00Z")60        let list = [overnight, morning]61        #expect(CalendarMath.occurrences(on: day, in: list, calendar: fr).map(\.window.title) == ["Morning", "Overnight"])62        let next = fr.date(byAdding: .day, value: 1, to: day)!63        #expect(CalendarMath.occurrences(on: next, in: list, calendar: fr).map(\.window.title) == ["Overnight"])64        #expect(CalendarMath.occurrences(on: fr.date(byAdding: .day, value: 2, to: day)!, in: list, calendar: fr).isEmpty)65        let agenda = CalendarMath.agenda(list, calendar: fr)66        #expect(agenda.count == 1 && agenda[0].items.map(\.window.title) == ["Morning", "Overnight"])67        #expect(abs(CalendarMath.dayFraction(of: morning.occurrenceStart, in: day, calendar: fr) - 9.0 / 24) < 0.001)   // 09:00 local68        #expect(CalendarMath.dayFraction(of: overnight.occurrenceEnd, in: day, calendar: fr) == 1)                    // clamped69        #expect(overnight.occurrenceID != morning.occurrenceID)70    }7172    private func session(_ server: StubServer) -> AppSession {73        let config = CoreConfiguration(origin: server.origin, secureStore: InMemorySecureStore(), passkeys: SoftwareAuthenticator(origin: "http://localhost"),74                                       cacheDirectory: nil) { DeviceInfo(kind: .macos, label: "t", model: "t", osVersion: "t", appVersion: "t") }75        return AppSession(configuration: config, protocolClasses: server.protocolClasses)76    }7778    @Test("invitation setup: expired / used link is a dead end; profile step is driven by the server")79    func invitationSetupModel() async {80        let server = StubServer()81        let mode = Box("gone")82        server.handle { r in83            switch (r.method, r.path) {84            case ("POST", "/api/v1/invitations/exchange"):85                if mode.value == "gone" { return .error(410, code: "invitation_invalid", message: "This invitation is no longer valid.") }86                return .json(200, Fixture.json(#"{"purpose":"new_account","role":"operator","requires_existing_account":false,"profile_required":true,"expires_at":"2026-11-18T21:10:00Z","inviter_display_name":"Owner","transaction_token":"tx"}"#))87            case ("POST", "/api/v1/invitations/transaction/profile"):88                return r.json?["handle"]?.stringValue == "taken" ? .error(409, code: "handle_taken", message: "This handle is already in use.")89                    : .json(200, Fixture.json(#"{"purpose":"new_account","role":"operator","handle":"new","display_name":"New","requires_existing_account":false,"profile_required":false,"expires_at":"2026-11-18T21:10:00Z","inviter_display_name":"Owner"}"#))90            default: return .http(status: 404)91            }92        }93        let s = session(server)94        let dead = InvitationSetupModel(session: s)95        await dead.begin(token: "x")96        #expect(dead.step == .invalid)97        #expect(dead.error?.isGone == true && dead.error?.correlationID != nil)9899        mode.value = "ok"100        let m = InvitationSetupModel(session: s)101        await m.begin(token: "y")102        #expect(m.step == .review)103        #expect(m.transaction?.role == ._operator && m.transaction?.inviterDisplayName == "Owner")104        m.acceptReview()105        #expect(m.step == .profile)                 // the server said profile_required106        m.handle = "Taken"; m.displayName = "New"107        await m.submitProfile()108        #expect(m.step == .profile && m.error?.code == "handle_taken")109        m.handle = "new"110        await m.submitProfile()111        #expect(m.step == .createPasskey && m.error == nil)112        #expect(server.requests("POST", "/api/v1/invitations/transaction/profile").first?.json?["handle"]?.stringValue == "taken")   // lowercased113    }114115    @Test("universal search: debounced, superseded queries dropped, unavailable is explicit")116    func searchModel() async {117        let server = StubServer()118        server.handle { r in119            guard r.path == "/api/v1/search" else { return .http(status: 404) }120            if r.query["q"] == "boom" { return .error(501, code: "not_implemented") }121            return .json(200, Fixture.json(#"{"query":"\#(r.query["q"] ?? "")","items":[{"kind":"node","id":"\#(Fixture.nodeID)","title":"\#(r.query["q"] ?? "")","score":1}]}"#))122        }123        let store = Fixture.signedInStore(for: server)124        let config = CoreConfiguration(origin: server.origin, secureStore: store, passkeys: SoftwareAuthenticator(origin: "http://localhost"), cacheDirectory: nil)125        let s = AppSession(configuration: config, protocolClasses: server.protocolClasses)126        let model = SearchModel(session: s, debounce: 0.05)127        model.query = "m"; model.query = "m4"; model.query = "m4m"128        #expect(await eventuallyMain { model.results.first?.title == "m4m" })129        #expect(server.requests("GET", "/api/v1/search").count == 1)       // only the last keystroke reached the server130        model.query = "boom"131        #expect(await eventuallyMain { model.state.unavailableReason == .notImplemented })132        #expect(model.results.isEmpty)133        model.query = "  "134        #expect(model.results.isEmpty)135        if case .idle = model.state {} else { Issue.record("an empty query is idle") }136    }137}138
Files main
Menu

Theme