SPB Git

Repository Public

CoreTests.swift 24.3 KB 345 lines swift

1//2//  SP Chat iOS3//  File: SPChat-iOS/Tests/CoreTests.swift4//  Description: Unit tests of the core: SSE parsing, stream reducer, decoding of backend payloads, Markdown, local store.5//6//  Author: Simon-Pierre Boucher7//  Contact: contact@spboucher.ai8//910import Foundation11import Testing12import UIKit13@testable import SPChat1415@Suite struct SSEParserTests {16    @Test func parsesEventsSplitAcrossAnyByte() {17        let raw = "retry: 2000\n\nid: 0\nevent: run\ndata: {\"runId\":\"run_1\"}\n\n: ping\n\nid: 1\nevent: text\ndata: {\"delta\":\"héllo\"}\n\n"18        let bytes = Array(raw.utf8)19        // whatever the chunk size, the same events come out20        for size in [1, 2, 3, 7, 64, bytes.count] {21            var p = SSEParser(); var out: [SSEParser.Output] = []22            var i = 023            while i < bytes.count { out += p.feed(bytes[i..<min(i + size, bytes.count)]); i += size }24            #expect(out == [.event(SSEEvent(event: "run", data: "{\"runId\":\"run_1\"}", id: 0)), .heartbeat, .event(SSEEvent(event: "text", data: "{\"delta\":\"héllo\"}", id: 1))])25        }26    }2728    @Test func handlesCRLFAndMultilineData() {29        var p = SSEParser()30        let out = p.feed(Array("event: x\r\ndata: a\r\ndata: b\r\n\r\n".utf8))31        #expect(out == [.event(SSEEvent(event: "x", data: "a\nb", id: nil))])32    }3334    @Test func ignoresEventsWithoutData() {35        var p = SSEParser()36        #expect(p.feed(Array("event: x\n\n\n\n".utf8)).isEmpty)37    }3839    @Test func decodesTheBackendVocabulary() {40        func ev(_ name: String, _ json: String) -> ChatStreamEvent { ChatStreamEvent(sse: SSEEvent(event: name, data: json, id: nil)) }41        #expect(ev("run", #"{"runId":"run_9"}"#) == .run(id: "run_9"))42        #expect(ev("text", #"{"delta":"a\nb"}"#) == .text("a\nb"))43        #expect(ev("conversation", #"{"id":"conv_1","userMessageId":"msg_1","created":true}"#) == .conversation(id: "conv_1", created: true, userMessageId: "msg_1", regenerated: nil, edited: nil))44        #expect(ev("error", #"{"message":"Limite quotidienne atteinte","code":"budget","partial":false}"#) == .error(message: "Limite quotidienne atteinte", code: "budget", partial: false))45        #expect(ev("end", "{}") == .end)46        #expect(ev("something_new", "{}") == .unknown("something_new"))47        if case .toolCall(let t) = ev("tool_call", #"{"id":"tc1","name":"web_search","input":{"query":"x"},"status":"running"}"#) { #expect(t.name == "web_search" && t.status == .running && t.input["query"]?.stringValue == "x") } else { Issue.record("tool_call") }48        if case .usage(let u, let cost, let lat, _, _) = ev("usage", #"{"usage":{"input":10,"output":20},"costUsd":0.01,"latencyMs":1200,"ttftMs":null}"#) { #expect(u == TokenUsage(input: 10, output: 20) && cost == 0.01 && lat == 1200) } else { Issue.record("usage") }49    }50}5152@Suite struct StreamReducerTests {53    private func items(_ events: [String]) -> [StreamItem] {54        var p = SSEParser()55        return p.feed(Array(events.joined().utf8)).compactMap { if case .event(let e) = $0 { return StreamItem(index: e.id, event: ChatStreamEvent(sse: e)) } else { return nil } }56    }57    private func user(_ id: String, _ text: String) -> ChatMessage {58        ChatMessage(id: id, conversationId: "", parentId: nil, role: .user, parts: [.text(text)], modelId: nil, provider: nil, applied: nil, routing: nil, usage: nil, costUsd: nil, latencyMs: nil, ttftMs: nil, status: .complete, error: nil, errorCode: nil, active: true, createdAt: Date())59    }6061    @Test func aNewConversationTurnEndsComplete() {62        var s = ThreadState(messages: [user("tmp_1", "Bonjour")])63        let ctx = TurnContext(optimisticUserId: "tmp_1")64        for i in items(SSE.run(deltas: ["Bon", "jour", " !"])) { StreamReducer.apply(i, to: &s, context: ctx) }65        #expect(s.conversationId == "conv_test1" && s.createdConversation && s.runId == "run_abc" && s.ended)66        #expect(s.messages.map(\.id) == ["msg_user1", "msg_asst1"])           // the optimistic id was replaced by the server's67        #expect(s.messages[1].text == "Bonjour !" && s.messages[1].status == .complete)68        #expect(s.messages[1].usage == TokenUsage(input: 12, output: 34) && s.messages[1].costUsd == 0.00042)69        #expect(s.messages[1].applied?.applied["effort"]?.stringValue == "low")70    }7172    @Test func replayedEventsAfterAReconnectionAreAppliedOnce() {73        var s = ThreadState(messages: [user("tmp_1", "x")])74        let all = items(SSE.run(deltas: ["a", "b", "c", "d"]))75        for i in all.prefix(5) { StreamReducer.apply(i, to: &s, context: TurnContext(optimisticUserId: "tmp_1")) }   // run, conversation, start, a, b76        #expect(s.lastIndex == 4 && s.messages.last?.text == "ab")77        // the client re-attaches from an older index: everything is replayed, nothing may be duplicated78        for i in all { StreamReducer.apply(i, to: &s) }79        #expect(s.messages.last?.text == "abcd" && s.messages.count == 2 && s.ended)80    }8182    @Test func textAfterAToolCallStartsANewPartInOrder() {83        var s = ThreadState(conversationId: "conv_test1", messages: [user("msg_user1", "x")])84        let events = [SSE.event("start", #"{"messageId":"m2","model":"gpt","provider":"openai"}"#), SSE.event("reasoning", #"{"delta":"je réfléchis"}"#), SSE.event("text", #"{"delta":"Avant. "}"#),85                      SSE.event("tool_call", #"{"id":"tc1","name":"python","input":{"code":"1+1"},"status":"running"}"#), SSE.event("tool_result", #"{"id":"tc1","status":"ok","output":"2","durationMs":40}"#), SSE.event("text", #"{"delta":"Après."}"#)]86        for i in items(events) { StreamReducer.apply(i, to: &s) }87        let parts = s.messages.last!.parts88        #expect(parts.count == 4)89        if case .reasoning(let r, _) = parts[0] { #expect(r == "je réfléchis") } else { Issue.record("reasoning first") }90        #expect(parts[1] == .text("Avant. ") && parts[3] == .text("Après."))91        if case .toolCall(let t) = parts[2] { #expect(t.status == .ok && t.output == .string("2") && t.durationMs == 40) } else { Issue.record("tool") }92    }9394    @Test func regenerateReplacesTheOldAnswerAndEditReplacesTheBranch() {95        var assistant = user("old_a", "ancienne"); assistant.role = .assistant96        var s = ThreadState(conversationId: "conv_test1", messages: [user("u1", "q"), assistant])97        for i in items([SSE.event("conversation", #"{"id":"conv_test1","userMessageId":"u1","regenerated":"old_a"}"#), SSE.event("start", #"{"messageId":"new_a","model":"m","provider":"xai"}"#), SSE.event("text", #"{"delta":"nouvelle"}"#)]) {98            StreamReducer.apply(i, to: &s, context: TurnContext(replaceAssistantId: "old_a", parentMessageId: "u1"))99        }100        #expect(s.messages.map(\.id) == ["u1", "new_a"] && s.messages[1].parentId == "u1")101102        var e = ThreadState(conversationId: "conv_test1", messages: [user("u1", "q"), assistant, user("tmp_e", "q modifiée")])103        for i in items([SSE.event("conversation", #"{"id":"conv_test1","userMessageId":"u2","edited":"u1"}"#)]) { StreamReducer.apply(i, to: &e, context: TurnContext(optimisticUserId: "tmp_e")) }104        #expect(e.messages.map(\.id) == ["u2"] && e.messages[0].text == "q modifiée")105    }106107    @Test func errorsMapToIncompleteOrErrorAndPreflightErrorsGoToTheThread() {108        var s = ThreadState(conversationId: "c", messages: [])109        for i in items([SSE.event("start", #"{"messageId":"a","model":"m","provider":"openai"}"#), SSE.event("text", #"{"delta":"début"}"#), SSE.event("error", #"{"message":"coupé","code":"network","partial":true}"#)]) { StreamReducer.apply(i, to: &s) }110        #expect(s.messages[0].status == .incomplete && s.messages[0].error == "coupé" && s.messages[0].text == "début")111        var t = ThreadState()112        for i in items([SSE.event("error", #"{"message":"Limite quotidienne atteinte","code":"budget"}"#), SSE.event("end", "{}")]) { StreamReducer.apply(i, to: &t) }113        #expect(t.error == "Limite quotidienne atteinte" && t.errorCode == "budget" && t.ended && t.messages.isEmpty)114    }115116    @Test func resyncAsksForAReload() {117        var s = ThreadState(conversationId: "c")118        StreamReducer.apply(StreamItem(index: 900, event: .resync), to: &s)119        #expect(s.needsReload && s.assistantId == nil && s.lastIndex == 900)120    }121}122123@Suite struct DecodingTests {124    @Test func decodesConversationsAndDetailFromRealShapes() throws {125        let list = try JSONDecoder().decode([Conversation].self, from: Data("[\(Fixtures.conversationJSON())]".utf8))126        #expect(list[0].id == "conv_test1" && list[0].routingMode == "manual" && list[0].toolsEnabled == true && list[0].totalCostUsd == 0.000556)127        #expect(list[0].lastMessageAt != nil && !list[0].isArchived)128        let detail = try JSONDecoder().decode(ConversationDetail.self, from: Data(Fixtures.detailJSON(messages: [Fixtures.messageJSON(id: "m1", role: "user", text: "Salut"), Fixtures.messageJSON(id: "m2", role: "assistant", text: "Bonjour", parent: "m1"), Fixtures.messageJSON(id: "m3", role: "assistant", text: "vieux", parent: "m1", active: false)], liveRun: "run_1").utf8))129        #expect(detail.messages.count == 3 && detail.activeMessages.map(\.id) == ["m1", "m2"] && detail.liveRun == "run_1")130        #expect(detail.messages[1].usage?.output == 34 && detail.messages[1].costUsd == 0.00042 && detail.messages[1].status == .complete)131    }132133    @Test func numericColumnsMayArriveAsStrings() throws {134        let json = #"{"totals":{"requests":766,"cost":0.32,"input_tokens":"522324","output_tokens":"176205","avg_latency":2948,"errors":2},"daily":[{"day":"2026-11-01T00:00:00.000Z","provider":"anthropic","cost":0.03,"requests":5}],"byModel":[{"model_id":"claude-haiku-5-5","provider":"anthropic","requests":496,"cost":0.1}],"spending":{"today":0.17,"month":0.32,"limits":{"dailyLimitUsd":10,"alertAtPercent":80,"monthlyLimitUsd":150}}}"#135        let r = try JSONDecoder().decode(UsageReport.self, from: Data(json.utf8))136        #expect(r.totals.inputTokens == 522_324 && r.totals.outputTokens == 176_205 && r.daily.count == 1 && r.spending.limits.monthlyLimitUsd == 150)137    }138139    @Test func partsRoundTripAndUnknownPartsSurvive() throws {140        let json = #"[{"type":"text","text":"a"},{"type":"image","attachmentId":"att_1","mime":"image/png","name":"x.png"},{"type":"file","attachmentId":"att_2","mime":"application/pdf","name":"d.pdf","size":1200,"pages":3},{"type":"tool_call","id":"t","name":"web_search","input":{"query":"q"},"status":"pending_approval"},{"type":"artifact","artifactId":"art_1","title":"T","artifactType":"html","language":"html"},{"type":"citation","url":"https://e.x","title":"E"},{"type":"generated_image","attachmentId":"att_3","prompt":"p","model":"gpt-image"},{"type":"hologram","x":1}]"#141        let parts = try JSONDecoder().decode([MessagePart].self, from: Data(json.utf8))142        #expect(parts.count == 8 && parts[7] == .unknown(type: "hologram"))143        let again = try JSONDecoder().decode([MessagePart].self, from: JSONEncoder().encode(parts))144        #expect(again == parts)145    }146147    @Test func modelsDecodeCapabilitiesAndSelectability() throws {148        let json = #"{"id":"claude-fable-5","provider":"anthropic","displayName":"Claude Fable 5","kind":"chat","api":null,"status":"verified","available":true,"tested":true,"capabilities":{"text":true,"tools":true,"vision":true,"reasoning":true,"effortLevels":["low","high"]},"contextWindow":1000000,"maxOutputTokens":128000,"pricing":{"input":10,"output":50},"benchmark":{"p50TtftMs":1862,"qualityScore":100},"hidden":false,"favorite":false}"#149        let m = try JSONDecoder().decode(AIModel.self, from: Data(json.utf8))150        #expect(m.isSelectableForChat && m.vision && m.reasoning && m.priceOutput == 50 && m.shortName == "Fable 5" && m.effortLevels == ["low", "high"] && m.p50TtftMs == 1862)151        var embedding = m; embedding.kind = "embedding"152        var unavailable = m; unavailable.available = false153        #expect(!embedding.isSelectableForChat && !unavailable.isSelectableForChat)154        #expect(try JSONDecoder().decode(AIModel.self, from: JSONEncoder().encode(m)) == m)155    }156157    @Test func sendOptionsOmitTheModelOutsideManualRouting() {158        #expect(SendOptions(modelId: "m", routingMode: .manual, effort: .high, toolsEnabled: false).payload() == ["routingMode": .string("manual"), "modelId": .string("m"), "settings": .object(["effort": .string("high")]), "toolsEnabled": .bool(false)])159        #expect(SendOptions(modelId: "m", routingMode: .economy).payload() == ["routingMode": .string("economy")])160    }161162    @Test func requestIdsMatchTheServerPattern() {163        let ids = (0..<50).map { _ in ChatAPI.requestId() }164        #expect(Set(ids).count == 50)165        #expect(ids.allSatisfy { $0.range(of: #"^[A-Za-z0-9_-]{16,64}$"#, options: .regularExpression) != nil })166    }167168    @Test func base64URLRoundTrips() {169        let d = Data((0..<255).map { UInt8($0) })170        let s = d.base64URLEncodedString()171        #expect(!s.contains("+") && !s.contains("/") && !s.contains("=") && Data(base64URLEncoded: s) == d)172    }173}174175@Suite struct MarkdownTests {176    @Test func parsesTheCommonBlocks() {177        let md = "# Titre\n\nUn *paragraphe*\nsur deux lignes.\n\n```swift\nlet x = 1\n```\n\n> citation\n> suite\n\n---\n\n| A | B |\n|:--|--:|\n| 1 | 2 |\n| 3 | 4 |\n\n$$\nE = mc^2\n$$"178        let b = MarkdownParser.parse(md)179        #expect(b.count == 7)180        #expect(b[0] == .heading(level: 1, text: "Titre"))181        #expect(b[1] == .paragraph("Un *paragraphe*\nsur deux lignes."))182        #expect(b[2] == .code(language: "swift", code: "let x = 1", closed: true))183        #expect(b[3] == .quote([.paragraph("citation\nsuite")]))184        #expect(b[4] == .rule)185        #expect(b[5] == .table(header: ["A", "B"], alignments: [.leading, .trailing], rows: [["1", "2"], ["3", "4"]]))186        #expect(b[6] == .math("E = mc^2"))187    }188189    @Test func nestedAndTaskLists() {190        let b = MarkdownParser.parse("1. un\n2. deux\n   - a\n   - b\n3. trois\n\n- [x] fait\n- [ ] à faire")191        guard case .list(true, 1, let items) = b[0] else { Issue.record("ordered"); return }192        #expect(items.count == 3)193        #expect(items[1].blocks.count == 2)194        if case .list(false, _, let inner) = items[1].blocks[1] { #expect(inner.count == 2) } else { Issue.record("nested") }195        guard case .list(false, _, let tasks) = b[1] else { Issue.record("tasks"); return }196        #expect(tasks.map(\.checked) == [true, false])197    }198199    @Test func streamingTextNeverBreaksTheParser() {200        // an answer cut at any character must parse (unterminated fence, half table, half math…)201        let full = "Voici :\n\n```python\nprint('x')\n```\n\n| a | b |\n|---|---|\n| 1 | 2 |\n\n$$\n\\frac{1}{2}\n$$\n\n- un\n  - deux"202        for end in full.indices { _ = MarkdownParser.parse(String(full[..<end])) }203        #expect(MarkdownParser.parse("```js\nconst a = 1") == [.code(language: "js", code: "const a = 1", closed: false)])204    }205206    @Test func dollarsAreMathOnlyWhenTheyLookLikeMath() {207        #expect(InlineMath.split("Ça coûte 5 $ et 10 $ au total") == [.text("Ça coûte 5 $ et 10 $ au total")])208        #expect(InlineMath.split("It costs $5 and $10") == [.text("It costs $5 and $10")])209        #expect(InlineMath.split("Soit $x^2 + 1$ alors") == [.text("Soit "), .math("x^2 + 1"), .text(" alors")])210        #expect(InlineMath.split(#"et \(a+b\) ici"#) == [.text("et "), .math("a+b"), .text(" ici")])211        #expect(InlineMath.split("code `$x$` intact") == [.text("code `$x$` intact")])212    }213214    @Test func tableCellsRespectEscapesAndCode() {215        #expect(MarkdownParser.cells(#"| a \| b | `x | y` | c |"#) == ["a | b", "`x | y`", "c"])216    }217218    @Test func highlighterKeepsTheTextIntact() {219        for (lang, code) in [("swift", "let x: Int = 42 // c\nfunc f() -> String { \"a\\\"b\" }"), ("python", "def f(x):\n    '''doc'''\n    return x # c"), ("json", "{\"k\": [1, true, null]}"), ("html", "<div class=\"a\">t</div><!-- c -->"), ("sql", "SELECT * FROM t -- c"), ("unknown", "whatever")] {220            let a = SyntaxHighlighter.highlight(code, language: lang)221            #expect(String(a.characters) == code)222        }223    }224}225226@Suite struct LocalStoreTests {227    private func conv(_ id: String, title: String = "T", pinned: Bool = false, archived: Bool = false) throws -> Conversation {228        try JSONDecoder().decode(Conversation.self, from: Data(Fixtures.conversationJSON(id: id, title: title, pinned: pinned, archived: archived).utf8))229    }230231    @Test func cachesListsAndDetailsAndPrunesWhatTheServerDropped() async throws {232        let store = try LocalStore(directory: nil)233        await store.replaceConversations([try conv("conv_a", title: "Alpha"), try conv("conv_b", title: "Beta", pinned: true)], archived: false)234        await store.replaceConversations([try conv("conv_z", title: "Zed", archived: true)], archived: true)235        #expect(await store.conversations().map(\.id) == ["conv_b", "conv_a"])          // pinned first236        #expect(await store.conversations(archived: true).map(\.id) == ["conv_z"])237        let detail = try JSONDecoder().decode(ConversationDetail.self, from: Data(Fixtures.detailJSON(id: "conv_a", messages: [Fixtures.messageJSON(id: "m1", role: "user", text: "le mot girafe est ici")], liveRun: "run_x").utf8))238        await store.saveDetail(detail)239        let cached = await store.detail("conv_a")240        #expect(cached?.detail.messages.first?.text == "le mot girafe est ici" && cached?.detail.liveRun == nil)   // a live run is never cached241        #expect(await store.searchCached("girafe").map(\.id) == ["conv_a"])242        #expect(await store.searchCached("Beta").map(\.id) == ["conv_b"])243        // conv_a disappeared from the server: its detail goes too244        await store.replaceConversations([try conv("conv_b")], archived: false)245        let gone = await store.detail("conv_a"); let left = await store.conversations().map(\.id)246        #expect(gone == nil && left == ["conv_b"])247    }248249    @Test func outboxIsOrderedIdempotentAndWiped() async throws {250        let store = try LocalStore(directory: nil)251        let a = OutboxItem(id: "req_aaaaaaaaaaaaaaaa", conversationId: "conv_a", projectId: nil, text: "un", attachments: [], options: SendOptions(modelId: "m", routingMode: .manual), createdAt: Date(timeIntervalSince1970: 10), lastError: nil)252        let b = OutboxItem(id: "req_bbbbbbbbbbbbbbbb", conversationId: nil, projectId: nil, text: "deux", attachments: [], options: SendOptions(), createdAt: Date(timeIntervalSince1970: 20), lastError: "hors ligne")253        await store.enqueue(b); await store.enqueue(a); await store.enqueue(a)254        #expect(await store.outbox() == [a, b])255        await store.removeFromOutbox(a.id)256        #expect(await store.outbox() == [b])257        await store.setValue(["x"], for: "k")258        await store.wipe()259        let c = await store.counts()260        #expect(c.conversations == 0 && c.details == 0 && c.outbox == 0)261        #expect(await store.value([String].self, for: "k") == nil)262    }263264    @Test func theDatabaseFileIsProtectedAndExcludedFromBackups() async throws {265        let dir = FileManager.default.temporaryDirectory.appendingPathComponent("spchat-store-\(UUID().uuidString)", isDirectory: true)266        defer { try? FileManager.default.removeItem(at: dir) }267        let store = try LocalStore(directory: dir)268        await store.setValue("v", for: "k")269        #expect(FileManager.default.fileExists(atPath: dir.appendingPathComponent("spchat.sqlite").path))270        #expect(try dir.resourceValues(forKeys: [.isExcludedFromBackupKey]).isExcludedFromBackup == true)271        // reopening the same file gives the data back272        let again = try LocalStore(directory: dir)273        #expect(await again.value(String.self, for: "k") == "v")274    }275}276277@Suite struct MiscTests {278    @Test func conversationBuckets() throws {279        var c = try JSONDecoder().decode(Conversation.self, from: Data(Fixtures.conversationJSON().utf8))280        let now = Date(); let cal = Calendar.current281        c.lastMessageAt = now; #expect(c.bucket(now: now) == .today)282        c.lastMessageAt = cal.date(byAdding: .day, value: -1, to: now); #expect(c.bucket(now: now) == .yesterday)283        c.lastMessageAt = cal.date(byAdding: .day, value: -4, to: now); #expect(c.bucket(now: now) == .week)284        c.lastMessageAt = cal.date(byAdding: .day, value: -20, to: now); #expect(c.bucket(now: now) == .month)285        c.lastMessageAt = cal.date(byAdding: .day, value: -90, to: now); #expect(c.bucket(now: now) == .older)286        c.pinned = true; #expect(c.bucket(now: now) == .pinned)287    }288289    @Test func configurationDerivesOriginRelyingPartyAndCookieNames() {290        let prod = AppConfiguration(baseURL: URL(string: "https://chat.spboucher.ai")!, userAgent: "x")291        #expect(prod.origin == "https://chat.spboucher.ai" && prod.relyingParty == "chat.spboucher.ai" && prod.sessionCookieName == "__Host-csa_session")292        let dev = AppConfiguration(baseURL: URL(string: "http://localhost:8510")!, userAgent: "x")293        #expect(dev.origin == "http://localhost:8510" && dev.sessionCookieName == "csa_session" && dev.transientCookieNames.contains("csa_ceremony"))294    }295296    @Test func multipartBodyIsWellFormed() {297        var f = MultipartForm(); f.addField("conversationId", "conv_1"); f.addFile("file", filename: "a\"b.txt", mime: "text/plain", content: Data("hello".utf8))298        let s = String(decoding: f.finalized(), as: UTF8.self)299        #expect(s.contains("name=\"conversationId\"\r\n\r\nconv_1\r\n") && s.contains("filename=\"a_b.txt\"\r\nContent-Type: text/plain\r\n\r\nhello\r\n") && s.hasSuffix("--\(f.boundary)--\r\n"))300    }301302    @Test func apiErrorsAreClassified() {303        #expect(APIError.from(status: 401, data: Data(#"{"error":"Session requise","code":"locked"}"#.utf8), lockedHeader: true).kind == .locked)304        #expect(APIError.from(status: 403, data: Data(#"{"error":"Confirme","code":"reauth_required"}"#.utf8), lockedHeader: false).kind == .reauthRequired)305        #expect(APIError.from(status: 429, data: Data(), lockedHeader: false).kind == .rateLimited)306        let busy = APIError.from(status: 409, data: Data(#"{"error":"Une réponse est déjà en cours dans cette conversation.","code":"busy"}"#.utf8), lockedHeader: false)307        #expect(busy.kind == .http && busy.code == "busy" && busy.message.contains("déjà en cours"))308        #expect(APIError.from(URLError(.notConnectedToInternet), offline: false).kind == .network)309        #expect(APIError.from(URLError(.cancelled), offline: false).kind == .cancelled)310        #expect(APIError.from(CancellationError(), offline: false).kind == .cancelled)311    }312313    @MainActor @Test func imagesArePreparedForUpload() {314        let big = UIGraphicsImageRenderer(size: CGSize(width: 3000, height: 2000)).image { ctx in315            for i in 0..<400 { UIColor(hue: CGFloat(i) / 400, saturation: 0.8, brightness: 0.9, alpha: 1).setFill(); ctx.fill(CGRect(x: CGFloat(i) * 7.5, y: CGFloat((i * 37) % 2000), width: 180, height: 180)) }316        }.pngData()!317        let out = ImageTools.prepareForUpload(big, filename: "capture.png", mime: "image/png", compress: true)318        if big.count > 1_200_000 {319            #expect(out.mime == "image/jpeg" && out.filename == "capture.jpg" && out.data.count < big.count)320            let size = UIImage(data: out.data)!.size321            #expect(max(size.width, size.height) <= 2048)322        }323        let small = Data([0x47, 0x49, 0x46])324        #expect(ImageTools.prepareForUpload(small, filename: "a.gif", mime: "image/gif", compress: true).data == small)325        #expect(ImageTools.prepareForUpload(big, filename: "capture.png", mime: "image/png", compress: false).data == big)326        #expect(ImageTools.mime(forFilename: "rapport.pdf") == "application/pdf")327    }328329    @MainActor @Test func appLockHonoursItsGracePeriod() {330        let d = UserDefaults(suiteName: "spchat.tests.lock.\(UUID().uuidString)")!331        d.set(true, forKey: "applock.enabled"); d.set(60, forKey: "applock.grace")332        let lock = AppLock(defaults: d)333        #expect(lock.isEnabled && lock.isLocked && lock.grace == .oneMinute)      // locked at launch334        lock.reset()335        #expect(!lock.isEnabled && !lock.isLocked && d.bool(forKey: "applock.enabled") == false)336    }337338    @MainActor @Test func mathTypesetsAndReportsFailures() {339        #expect(MathRenderer.render(#"\frac{a}{b} + \sqrt{x^2 + 1}"#, fontSize: 17, display: true) != nil)340        #expect(MathRenderer.render(#"\sum_{i=1}^{n} i = \frac{n(n+1)}{2}"#, fontSize: 17, display: false) != nil)341        #expect(MathRenderer.render(#"\begin{align} a &= b \\ c &= d \end{align}"#, fontSize: 17, display: true) != nil)342        #expect(MathRenderer.render(#"\frac{a}{"#, fontSize: 17, display: true) == nil)343    }344}345
Files main
Menu

Theme