Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : SP Keyboard9// File : Shared/Tests/KeyboardCoreTests/KeyboardCoreTests.swift10// Description : Layouts, shift, capitalisation, deletion and graphemes,11// accents, smart punctuation, suggestions, autocorrection12// and its undo, cursor movement, text analysis, settings13// migration, emoji search.14// Module : KeyboardCoreTests15// Repository : https://git.spboucher.ai/sp-keyboard16// Created : 2026-12-0117// Last Modified : 2026-12-0118//19// =============================================================================20// AUTHOR & PROFESSIONAL AFFILIATION21// =============================================================================22//23// Author : Simon-Pierre Boucher24// Position : Professor of Finance25// Institution : Université du Québec en Outaouais (UQO)26// Department : Département des sciences administratives27// Organization : SP Boucher28//29// Website : https://spboucher.ai30// Git : https://git.spboucher.ai31//32// =============================================================================33// OFFICIAL CONTACT DIRECTORY34// =============================================================================35//36// General : info@spboucher.ai37// Professional : contact@spboucher.ai38// Direct : simon@spboucher.ai39// Research : research@spboucher.ai40// Development : dev@spboucher.ai41// Support : support@spboucher.ai42// Security/Admin : admin@spboucher.ai43// Notifications : notifications@spboucher.ai44//45// Preferred Contact: support@spboucher.ai46//47// =============================================================================48// COPYRIGHT & INTELLECTUAL PROPERTY49// =============================================================================50//51// Copyright (c) 202652// Simon-Pierre Boucher53//54// All rights reserved where applicable.55//56// This file is governed by the applicable project license,57// copyright notices, institutional agreements and relevant law.58//59// Unless expressly authorized by the applicable license or60// rights holder, copying, redistribution, sublicensing,61// publication and commercial exploitation are not permitted.62//63// Existing third-party rights and notices remain unaffected.64//65// =============================================================================66// CONFIDENTIALITY & SECURITY67// =============================================================================68//69// Classification : Public70// Distribution : Public repository; use is governed by the project license71// Security Contact : admin@spboucher.ai72//73// Access to this source does not independently grant permission74// to redistribute or disclose confidential materials.75//76// Do not embed credentials, private keys, access tokens,77// certificates or confidential personal information.78//79// =============================================================================80// LICENSE & MAINTENANCE81// =============================================================================82//83// License : None specified (no license file in this repository)84// Maintainer : Simon-Pierre Boucher85// Technical Contact: dev@spboucher.ai86//87// =============================================================================88// END OF SP BOUCHER SOURCE HEADER89// =============================================================================9091import XCTest92import PredictionCore93import SecureStorage94@testable import KeyboardCore9596@MainActor97final class LayoutTests: XCTestCase {98 func testEveryLanguageHasACompleteLetterPage() {99 for language in KeyboardLanguage.allCases {100 let layout = LayoutBuilder.layout(for: LayoutRequest(language: language, showsGlobe: true, showsLanguageKey: true))101 XCTAssertEqual(layout.rows.count, 4, language.rawValue)102 let letters = Set(layout.keys.compactMap { key -> String? in103 if case .character(let text) = key.action, text.count == 1, text.first!.isLetter { return text }104 return nil105 })106 for letter in "abcdefghijklmnopqrstuvwxyz" { XCTAssertTrue(letters.contains(String(letter)), "\(language.rawValue) lacks \(letter)") }107 for id in ["shift", "backspace", "space", "return", "globe", "language", "page.numbers"] {108 XCTAssertEqual(layout.keys.filter { $0.id == id }.count, 1, "\(language.rawValue) \(id)")109 }110 XCTAssertEqual(Set(layout.keys.map(\.id)).count, layout.keys.count, "duplicate key id in \(language.rawValue)")111 for row in layout.rows { XCTAssertLessThanOrEqual(row.reduce(0) { $0 + $1.width }, 10.001, language.rawValue) }112 }113 }114115 func testLanguageSpecificKeys() {116 let fr = LayoutBuilder.layout(for: LayoutRequest(language: .frenchCanada))117 XCTAssertEqual(fr.rows[0].map(\.id).prefix(6).joined(), "qwerty")118 XCTAssertTrue(fr.keys.contains { $0.id == "é" })119 XCTAssertTrue(fr.keys.contains { $0.id == "'" })120 let es = LayoutBuilder.layout(for: LayoutRequest(language: .spanish))121 XCTAssertTrue(es.keys.contains { $0.id == "ñ" })122 let azerty = LayoutBuilder.layout(for: LayoutRequest(language: .frenchAZERTY))123 XCTAssertEqual(azerty.rows[0].map(\.id).prefix(6).joined(), "azerty")124 XCTAssertEqual(KeyboardLanguage.frenchAZERTY.geometry, .azerty)125 XCTAssertEqual(KeyboardLanguage.frenchCanada.lexicon, .french)126 }127128 func testUppercaseLabelsAndAccents() {129 let upper = LayoutBuilder.layout(for: LayoutRequest(language: .frenchCanada, uppercase: true))130 let e = upper.keys.first { $0.id == "e" }!131 XCTAssertEqual(e.label, "E")132 XCTAssertEqual(e.action, .character("E"))133 XCTAssertEqual(e.alternates.first, "É")134 XCTAssertTrue(e.alternates.contains("È"))135 XCTAssertEqual(Accents.alternates(for: "n", language: .spanish).first, "ñ")136 XCTAssertEqual(Accents.alternates(for: "a", language: .spanish).first, "á")137 XCTAssertEqual(Accents.alternates(for: "a", language: .frenchCanada).first, "à")138 XCTAssertTrue(Accents.alternates(for: "c", language: .frenchCanada).contains("ç"))139 XCTAssertTrue(Accents.alternates(for: "q", language: .english).isEmpty)140 }141142 func testGlobeAndLanguageKeysAreConditional() {143 let bare = LayoutBuilder.layout(for: LayoutRequest(language: .english, showsGlobe: false, showsLanguageKey: false))144 XCTAssertFalse(bare.keys.contains { $0.id == "globe" })145 XCTAssertFalse(bare.keys.contains { $0.id == "language" })146 XCTAssertEqual(bare.rows[3].reduce(0) { $0 + $1.width }, 10, accuracy: 0.001)147 }148149 func testURLAndEmailBottomRows() {150 let url = LayoutBuilder.layout(for: LayoutRequest(language: .english, variant: .url))151 XCTAssertTrue(url.rows[3].contains { $0.id == "/" })152 XCTAssertTrue(url.rows[3].first { $0.id == "." }!.alternates.contains(".com"))153 let email = LayoutBuilder.layout(for: LayoutRequest(language: .english, variant: .email))154 XCTAssertTrue(email.rows[3].contains { $0.id == "@" })155 }156157 func testPads() {158 for variant in [LayoutVariant.numberPad, .decimalPad, .phonePad] {159 let pad = LayoutBuilder.layout(for: LayoutRequest(language: .english, variant: variant))160 XCTAssertEqual(pad.rows.count, 4)161 let digits = pad.keys.compactMap { key -> String? in162 if case .character(let text) = key.action, text.count == 1, text.first!.isNumber { return text }163 return nil164 }165 XCTAssertEqual(digits.sorted(), ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"])166 XCTAssertTrue(pad.keys.contains { $0.action == .backspace })167 }168 XCTAssertTrue(LayoutBuilder.layout(for: LayoutRequest(language: .english, variant: .decimalPad)).keys.contains { $0.id == "decimal" })169 XCTAssertTrue(LayoutBuilder.layout(for: LayoutRequest(language: .english, variant: .phonePad)).keys.contains { $0.id == "+" })170 }171172 func testDeveloperAndFinancePages() {173 let dev = LayoutBuilder.layout(for: LayoutRequest(language: .english, page: .developer))174 for symbol in ["{", "}", "[", "]", "`", "|", "&", "=", "<", ">", "\\"] { XCTAssertTrue(dev.keys.contains { $0.id == symbol }, symbol) }175 XCTAssertTrue(dev.keys.first { $0.id == "=" }!.alternates.contains("=>"))176 XCTAssertTrue(dev.keys.contains { $0.action == .character("\t") })177 let finance = LayoutBuilder.layout(for: LayoutRequest(language: .english, page: .finance))178 for symbol in ["%", "$", "€", "Δ", "σ", "β", "Σ", "√", "²"] { XCTAssertTrue(finance.keys.contains { $0.id == symbol }, symbol) }179 XCTAssertTrue(finance.keys.first { $0.id == "²" }!.alternates.contains("⁹"))180 for layout in [dev, finance] {181 XCTAssertEqual(Set(layout.keys.map(\.id)).count, layout.keys.count)182 for row in layout.rows { XCTAssertLessThanOrEqual(row.reduce(0) { $0 + $1.width }, 10.001) }183 }184 }185186 func testReturnLabels() {187 XCTAssertEqual(LayoutBuilder.returnLabel(.send, language: .frenchCanada), "envoyer")188 XCTAssertEqual(LayoutBuilder.returnLabel(.search, language: .english), "search")189 XCTAssertEqual(LayoutBuilder.returnLabel(.go, language: .spanish), "ir")190 let layout = LayoutBuilder.layout(for: LayoutRequest(language: .frenchCanada, returnKey: .search))191 XCTAssertEqual(layout.keys.first { $0.id == "return" }?.label, "chercher")192 }193194 func testNumbersAndPunctuationStartsOnNumbers() {195 let layout = LayoutBuilder.layout(for: LayoutRequest(language: .english, variant: .numbersAndPunctuation))196 XCTAssertTrue(layout.keys.contains { $0.id == "1" })197 }198}199200final class LayoutTwoTests: XCTestCase {201 func testNumberHintsOnTheTopRow() {202 let layout = LayoutBuilder.layout(for: LayoutRequest(language: .frenchCanada, numberHints: true))203 XCTAssertEqual(layout.rows.count, 4)204 XCTAssertEqual(layout.rows[0].map(\.hint), ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"])205 let q = layout.rows[0][0], e = layout.rows[0][2]206 XCTAssertEqual(q.alternates.first, "1", "no accent: the digit is the default pick")207 XCTAssertEqual(e.alternates.first, "é", "an accented letter keeps its accent first")208 XCTAssertEqual(e.alternates[1], "3")209 XCTAssertTrue(layout.rows[1].allSatisfy { $0.hint == nil })210 let plain = LayoutBuilder.layout(for: LayoutRequest(language: .frenchCanada))211 XCTAssertTrue(plain.keys.allSatisfy { $0.hint == nil })212 XCTAssertFalse(plain.rows[0][0].alternates.contains("1"))213 }214215 func testNumberRowReplacesHints() {216 let layout = LayoutBuilder.layout(for: LayoutRequest(language: .english, uppercase: true, numberRow: true, numberHints: true))217 XCTAssertEqual(layout.rows.count, 5)218 XCTAssertEqual(layout.rows[0].map(\.label), ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"])219 XCTAssertEqual(layout.rows[1].first?.label, "Q")220 XCTAssertTrue(layout.rows[1].allSatisfy { $0.hint == nil })221 XCTAssertEqual(Set(layout.keys.map(\.id)).count, layout.keys.count, "key identifiers stay unique")222 XCTAssertEqual(LayoutBuilder.layout(for: LayoutRequest(language: .english, page: .numbers, numberRow: true)).rows.count, 4)223 }224225 func testEmojiKeyOnlyWhenTheSpaceBarKeepsItsWidth() {226 func bottom(globe: Bool, language: Bool, variant: LayoutVariant = .standard) -> [Key] {227 LayoutBuilder.layout(for: LayoutRequest(language: .frenchCanada, variant: variant, showsGlobe: globe, showsLanguageKey: language)).rows.last ?? []228 }229 for (globe, language, expected) in [(false, false, true), (false, true, true), (true, false, true), (true, true, false)] {230 let row = bottom(globe: globe, language: language)231 XCTAssertEqual(row.contains { $0.id == "emoji" }, expected, "globe \(globe) language \(language)")232 XCTAssertEqual(row.reduce(0) { $0 + $1.width }, 10, accuracy: 1e-9)233 XCTAssertGreaterThanOrEqual(row.first { $0.id == "space" }?.width ?? 0, 3.3 - 1e-9)234 }235 XCTAssertEqual(bottom(globe: false, language: false).first { $0.id == "emoji" }?.action, .panel(.emoji))236 XCTAssertFalse(bottom(globe: false, language: true, variant: .email).contains { $0.id == "emoji" }, "no room beside @ and .")237 }238239 @MainActor240 func testReturnKeyWaitsForTextWhenTheFieldAsks() {241 let engine = KeyboardEngine()242 func returnEnabled(hasText: Bool) -> Bool? {243 LayoutBuilder.layout(for: engine.layoutRequest(showsGlobe: false, hasText: hasText)).keys.first { $0.id == "return" }?.isEnabled244 }245 engine.traits.enablesReturnKeyAutomatically = true246 XCTAssertEqual(returnEnabled(hasText: false), false)247 XCTAssertEqual(returnEnabled(hasText: true), true)248 engine.traits.enablesReturnKeyAutomatically = false249 XCTAssertEqual(returnEnabled(hasText: false), true)250 }251}252253@MainActor254final class EngineTests: XCTestCase {255 private var engine: KeyboardEngine!256 private var proxy: InMemoryTextProxy!257 private var clock = 0.0258259 override func setUp() async throws {260 engine = KeyboardEngine()261 proxy = InMemoryTextProxy()262 clock = 100263 }264265 @discardableResult266 private func tap(_ action: KeyAction, after delay: Double = 1) -> EngineOutcome {267 clock += delay268 return engine.handle(action, proxy: proxy, time: clock)269 }270271 /// Types text the way a user would: letters honour the shift state, spaces and newlines use their keys.272 private func type(_ text: String) {273 for character in text {274 switch character {275 case " ": tap(.space)276 case "\n": tap(.returnKey)277 default:278 let letter = engine.shift.isUppercase && character.isLetter ? String(character).uppercased() : String(character)279 tap(.character(letter))280 }281 }282 }283284 private func predict(_ word: String, suggestions: [Suggestion] = [], autocorrection: String? = nil) {285 let correction = autocorrection.map { Suggestion(text: $0, kind: .correction, score: 1) }286 engine.setPrediction(PredictionResult(suggestions: suggestions, autocorrection: correction), forWord: word)287 }288289 // Glide typing290291 func testGlideSpacesCapitalisesAndLeavesAnAutomaticSpace() {292 engine.refreshShift(proxy: proxy)293 XCTAssertTrue(engine.insertGlide("bonjour", proxy: proxy).textChanged)294 XCTAssertEqual(proxy.text, "Bonjour ")295 _ = engine.insertGlide("tout", proxy: proxy)296 _ = engine.insertGlide("le", proxy: proxy)297 XCTAssertEqual(proxy.text, "Bonjour tout le ")298 tap(.character("."))299 XCTAssertEqual(proxy.text, "Bonjour tout le.", "punctuation takes the automatic space back")300 _ = engine.insertGlide("monde", proxy: proxy)301 XCTAssertEqual(proxy.text, "Bonjour tout le. Monde ", "a glide after a full stop is spaced and capitalised")302 }303304 func testGlideAfterATypedWordAndAfterAnApostrophe() {305 type("salut")306 _ = engine.insertGlide("toi", proxy: proxy)307 XCTAssertEqual(proxy.text, "salut toi ")308 proxy.reset("l'")309 _ = engine.contextDidChange(proxy: proxy)310 _ = engine.insertGlide("homme", proxy: proxy)311 XCTAssertEqual(proxy.text, "l'homme ")312 proxy.reset("(")313 _ = engine.contextDidChange(proxy: proxy)314 _ = engine.insertGlide("voir", proxy: proxy)315 XCTAssertEqual(proxy.text, "(voir ")316 }317318 func testGlideHonoursCapsLock() {319 proxy.reset("ok ")320 _ = engine.contextDidChange(proxy: proxy)321 tap(.shift)322 tap(.shift, after: 0.1)323 XCTAssertEqual(engine.shift, .locked)324 _ = engine.insertGlide("merci", proxy: proxy)325 XCTAssertEqual(proxy.text, "ok MERCI ")326 }327328 func testBackspaceTakesAGlidedWordBackWhole() {329 proxy.reset("Je suis")330 _ = engine.contextDidChange(proxy: proxy)331 _ = engine.insertGlide("content", proxy: proxy)332 XCTAssertEqual(proxy.text, "Je suis content ")333 tap(.backspace)334 XCTAssertEqual(proxy.text, "Je suis")335 tap(.backspace)336 XCTAssertEqual(proxy.text, "Je sui", "only the first backspace is a whole-word undo")337 }338339 func testGlideAlternativeReplacesTheWordAndKeepsItsCase() {340 engine.refreshShift(proxy: proxy)341 _ = engine.insertGlide("bon", proxy: proxy)342 XCTAssertTrue(engine.canReplaceGlide(proxy: proxy))343 _ = engine.replaceGlide(with: "bien", proxy: proxy)344 XCTAssertEqual(proxy.text, "Bien ")345 XCTAssertTrue(engine.canReplaceGlide(proxy: proxy), "another alternative can still be picked")346 tap(.character("x"))347 XCTAssertFalse(engine.canReplaceGlide(proxy: proxy))348 XCTAssertFalse(engine.replaceGlide(with: "non", proxy: proxy).textChanged)349 XCTAssertEqual(proxy.text, "Bien x")350 }351352 // The host echoes the keyboard's own edits353354 func testAutocorrectionUndoSurvivesTheHostEchoingTheEdit() {355 proxy.reset("ok ")356 _ = engine.contextDidChange(proxy: proxy)357 type("bonjuor")358 predict("bonjuor", autocorrection: "bonjour")359 tap(.space)360 XCTAssertEqual(proxy.text, "ok bonjour ")361 // What UIInputViewController.textDidChange triggers after the keyboard's own insertion.362 _ = engine.contextDidChange(proxy: proxy)363 tap(.backspace)364 XCTAssertEqual(proxy.text, "ok bonjuor", "the typed word comes back even though the host reported a change")365 }366367 func testAutomaticSpaceSurvivesTheEchoButNotAnExternalChange() {368 proxy.reset("ok ")369 _ = engine.contextDidChange(proxy: proxy)370 _ = engine.apply(Suggestion(text: "merci", kind: .completion, score: 1), proxy: proxy)371 _ = engine.contextDidChange(proxy: proxy)372 tap(.character(","))373 XCTAssertEqual(proxy.text, "ok merci,")374 _ = engine.apply(Suggestion(text: "bien", kind: .nextWord, score: 1), proxy: proxy)375 proxy.reset("autre chose ")376 _ = engine.contextDidChange(proxy: proxy)377 tap(.character(","))378 XCTAssertEqual(proxy.text, "autre chose ,", "text that changed under the keyboard is not touched")379 }380381 func testExternalChangeDropsTheGlideUndo() {382 _ = engine.insertGlide("merci", proxy: proxy)383 proxy.reset("merci ")384 _ = engine.contextDidChange(proxy: proxy)385 XCTAssertTrue(engine.canReplaceGlide(proxy: proxy), "same text: seen as the echo")386 proxy.reset("merci beaucoup ")387 _ = engine.contextDidChange(proxy: proxy)388 XCTAssertFalse(engine.canReplaceGlide(proxy: proxy))389 }390391 // Shift392393 func testAutoCapitalisesSentences() {394 engine.refreshShift(proxy: proxy)395 XCTAssertEqual(engine.shift, .once)396 type("bonjour. ca va? oui! ok\nfin")397 XCTAssertEqual(proxy.text, "Bonjour. Ca va? Oui! Ok\nFin")398 XCTAssertEqual(engine.shift, .off)399 }400401 func testShiftOnceAndCapsLock() {402 proxy.reset("a")403 engine.refreshShift(proxy: proxy)404 XCTAssertEqual(engine.shift, .off)405 tap(.shift)406 XCTAssertEqual(engine.shift, .once)407 type("b")408 XCTAssertEqual(engine.shift, .off)409 tap(.shift)410 tap(.shift, after: 0.2) // double tap411 XCTAssertEqual(engine.shift, .locked)412 type("cd. ef")413 XCTAssertEqual(engine.shift, .locked)414 XCTAssertEqual(proxy.text, "aBCD. EF")415 tap(.shift)416 XCTAssertEqual(engine.shift, .off)417 tap(.shift)418 tap(.shift, after: 2) // slow second tap just turns it off419 XCTAssertEqual(engine.shift, .off)420 }421422 func testCapitalisationModesAndFieldTypes() {423 engine.traits.autocapitalization = .words424 engine.refreshShift(proxy: proxy)425 type("jean tremblay")426 XCTAssertEqual(proxy.text, "Jean Tremblay")427 proxy.reset()428 engine.resetForNewField()429 engine.traits.autocapitalization = .allCharacters430 engine.refreshShift(proxy: proxy)431 type("abc")432 XCTAssertEqual(proxy.text, "ABC")433 proxy.reset()434 engine.resetForNewField()435 engine.traits.autocapitalization = .sentences436 engine.traits.variant = .email437 engine.refreshShift(proxy: proxy)438 type("jean")439 XCTAssertEqual(proxy.text, "jean")440 proxy.reset()441 engine.resetForNewField()442 engine.traits.variant = .standard443 engine.settings.autoCapitalization = false444 engine.refreshShift(proxy: proxy)445 type("a. b")446 XCTAssertEqual(proxy.text, "a. b")447 }448449 // Deletion450451 func testBackspaceRespectsGraphemes() {452 for sample in ["e\u{301}", "👨👩👧👦", "🇨🇦", "👍🏽", "é", "한"] {453 proxy.reset("a" + sample)454 XCTAssertEqual(proxy.text.count, 2, sample)455 tap(.backspace)456 XCTAssertEqual(proxy.text, "a", sample)457 }458 }459460 func testBackspaceOnHostsThatDeleteByScalar() {461 proxy.deletesByScalar = true462 for sample in ["e\u{301}", "👨👩👧👦", "🇨🇦", "👍🏽"] {463 proxy.reset("ab" + sample)464 tap(.backspace)465 XCTAssertEqual(proxy.text, "ab", sample)466 }467 proxy.reset("ab")468 tap(.backspace)469 XCTAssertEqual(proxy.text, "a")470 }471472 func testBackspaceOnEmptyFieldAndSelection() {473 tap(.backspace)474 XCTAssertEqual(proxy.text, "")475 proxy.reset("bonjour le monde")476 proxy.select(lastCharacters: 5)477 tap(.backspace)478 XCTAssertEqual(proxy.text, "bonjour le ")479 }480481 func testWordDeletion() {482 proxy.reset("Bonjour le monde ")483 _ = engine.deleteStep(.word, proxy: proxy)484 XCTAssertEqual(proxy.text, "Bonjour le ")485 _ = engine.deleteStep(.word, proxy: proxy)486 XCTAssertEqual(proxy.text, "Bonjour ")487 _ = engine.deleteStep(.character, proxy: proxy)488 XCTAssertEqual(proxy.text, "Bonjour")489 _ = engine.deleteStep(.word, proxy: proxy)490 XCTAssertEqual(proxy.text, "")491 _ = engine.deleteStep(.word, proxy: proxy)492 XCTAssertEqual(proxy.text, "")493 XCTAssertEqual(engine.shift, .once)494 }495496 func testDeleteAccelerationIsBoundedAndMonotonic() {497 var previous = Double.infinity498 for n in 0..<DeleteAcceleration.wordThreshold {499 let interval = DeleteAcceleration.interval(forRepeat: n)500 XCTAssertLessThanOrEqual(interval, previous)501 XCTAssertGreaterThanOrEqual(interval, DeleteAcceleration.minimumInterval)502 XCTAssertEqual(DeleteAcceleration.granularity(forRepeat: n), .character)503 previous = interval504 }505 XCTAssertEqual(DeleteAcceleration.granularity(forRepeat: 500), .word)506 XCTAssertGreaterThanOrEqual(DeleteAcceleration.interval(forRepeat: 100_000), DeleteAcceleration.minimumInterval)507 }508509 // Space and punctuation510511 func testDoubleSpaceInsertsPeriod() {512 type("Bon")513 tap(.space)514 tap(.space, after: 0.3)515 XCTAssertEqual(proxy.text, "Bon. ")516 XCTAssertEqual(engine.shift, .once)517 tap(.space, after: 0.3) // a third tap is just a space518 XCTAssertEqual(proxy.text, "Bon. ")519 }520521 func testDoubleSpaceRespectsSettingTimingAndContext() {522 type("Bon")523 tap(.space)524 tap(.space, after: 3)525 XCTAssertEqual(proxy.text, "Bon ")526 proxy.reset("Bon,")527 tap(.space)528 tap(.space, after: 0.2)529 XCTAssertEqual(proxy.text, "Bon, ")530 proxy.reset("Bon")531 engine.settings.doubleSpacePeriod = false532 tap(.space)533 tap(.space, after: 0.2)534 XCTAssertEqual(proxy.text, "Bon ")535 engine.settings.doubleSpacePeriod = true536 engine.traits.variant = .url537 proxy.reset("Bon")538 tap(.space)539 tap(.space, after: 0.2)540 XCTAssertEqual(proxy.text, "Bon ")541 }542543 func testSmartQuotesAndApostropheAreOptIn() {544 proxy.reset("Il dit ")545 tap(.character("\""))546 XCTAssertEqual(proxy.text, "Il dit \"")547 engine.settings.smartQuotes = true548 engine.settings.smartApostrophe = true549 proxy.reset("Il dit ")550 tap(.character("\""))551 type("allo")552 tap(.character("\""))553 XCTAssertEqual(proxy.text, "Il dit «\u{00A0}allo\u{00A0}»")554 engine.switchLanguage(to: .english)555 proxy.reset("He said ")556 tap(.character("\""))557 type("hi")558 tap(.character("\""))559 XCTAssertEqual(proxy.text, "He said “hi”")560 proxy.reset("l")561 tap(.character("'"))562 XCTAssertEqual(proxy.text, "l’")563 engine.traits.variant = .url564 proxy.reset("l")565 tap(.character("'"))566 XCTAssertEqual(proxy.text, "l'")567 }568569 func testPageReturnsToLettersAfterSpace() {570 tap(.page(.numbers))571 XCTAssertEqual(engine.page, .numbers)572 tap(.character("4"))573 XCTAssertEqual(engine.page, .numbers)574 tap(.space)575 XCTAssertEqual(engine.page, .letters)576 tap(.page(.developer))577 tap(.character("{"))578 tap(.space)579 XCTAssertEqual(engine.page, .developer, "the developer page stays until the user leaves it")580 }581582 // Suggestions and autocorrection583584 func testApplyingASuggestionReplacesTheWordAndSwallowsTheSpace() {585 proxy.reset("Je vais au dep")586 _ = engine.apply(Suggestion(text: "dépanneur", kind: .completion, score: 1), proxy: proxy)587 XCTAssertEqual(proxy.text, "Je vais au dépanneur ")588 tap(.character("."))589 XCTAssertEqual(proxy.text, "Je vais au dépanneur.")590 proxy.reset("Je ")591 _ = engine.apply(Suggestion(text: "suis", kind: .nextWord, score: 1), proxy: proxy)592 XCTAssertEqual(proxy.text, "Je suis ")593 type("la")594 XCTAssertEqual(proxy.text, "Je suis la")595 }596597 func testAutocorrectionOnSpaceAndItsUndo() {598 proxy.reset("Je voudrias")599 predict("voudrias", autocorrection: "voudrais")600 XCTAssertEqual(engine.pendingAutocorrection(proxy: proxy)?.text, "voudrais")601 let outcome = tap(.space)602 XCTAssertTrue(outcome.autocorrected)603 XCTAssertEqual(proxy.text, "Je voudrais ")604 let undone = tap(.backspace)605 XCTAssertTrue(undone.restoredOriginal)606 XCTAssertEqual(proxy.text, "Je voudrias")607 // The restored word is not corrected a second time.608 predict("voudrias", autocorrection: "voudrais")609 XCTAssertNil(engine.pendingAutocorrection(proxy: proxy))610 tap(.space)611 XCTAssertEqual(proxy.text, "Je voudrias ")612 }613614 func testAutocorrectionOnPunctuationAndReturn() {615 proxy.reset("Cest bein")616 predict("bein", autocorrection: "bien")617 tap(.character("!"))618 XCTAssertEqual(proxy.text, "Cest bien!")619 proxy.reset("teh")620 engine.switchLanguage(to: .english)621 predict("teh", autocorrection: "the")622 tap(.returnKey)623 XCTAssertEqual(proxy.text, "the\n")624 }625626 func testUndoOnlyWhileContextIsIntact() {627 proxy.reset("teh")628 predict("teh", autocorrection: "the")629 tap(.space)630 type("x")631 tap(.backspace)632 tap(.backspace)633 XCTAssertEqual(proxy.text, "the", "after typing something else, backspace only deletes")634 }635636 func testStalePredictionIsIgnored() {637 proxy.reset("bonjour")638 predict("bonjou", autocorrection: "bijou") // computed for an earlier state of the word639 tap(.space)640 XCTAssertEqual(proxy.text, "bonjour ")641 }642643 func testNoAutocorrectionWhereItDoesNotBelong() {644 func attempt(_ configure: () -> Void) -> String {645 proxy.reset("teh")646 engine.resetForNewField()647 engine.traits = InputTraits()648 engine.settings = KeyboardSettings()649 configure()650 predict("teh", autocorrection: "the")651 tap(.space)652 return proxy.text653 }654 XCTAssertEqual(attempt {}, "the ")655 XCTAssertEqual(attempt { self.engine.settings.autocorrection = false }, "teh ")656 XCTAssertEqual(attempt { self.engine.traits.allowsAutocorrection = false }, "teh ")657 XCTAssertEqual(attempt { self.engine.traits.variant = .url }, "teh ")658 XCTAssertEqual(attempt { self.engine.traits.variant = .email }, "teh ")659 proxy.reset("v2teh")660 predict("v2teh", autocorrection: "the")661 tap(.space)662 XCTAssertEqual(proxy.text, "v2teh ")663 proxy.reset("snake_teh")664 predict("snake_teh", autocorrection: "the")665 tap(.space)666 XCTAssertEqual(proxy.text, "snake_teh ")667 }668669 func testVerbatimSuggestionKeepsTheWord() {670 proxy.reset("Tremblayy")671 _ = engine.apply(Suggestion(text: "Tremblayy", kind: .verbatim, score: 1), proxy: proxy)672 XCTAssertEqual(proxy.text, "Tremblayy ")673 proxy.reset("Tremblayy")674 predict("Tremblayy", autocorrection: "Tremblay")675 tap(.space)676 XCTAssertEqual(proxy.text, "Tremblayy ")677 }678679 func testUnknownWordIsReportedForOptInLearning() {680 proxy.reset("clavardons")681 predict("clavardons", suggestions: [Suggestion(text: "clavardons", kind: .verbatim, score: 1)])682 XCTAssertEqual(tap(.space).unknownWordCommitted, "clavardons")683 proxy.reset("bonjour")684 predict("bonjour", suggestions: [Suggestion(text: "bonjour", kind: .completion, score: 1)])685 XCTAssertNil(tap(.space).unknownWordCommitted)686 }687688 func testSnippetSuggestionInsertsWithoutExtraSpaceWhenMultiline() {689 proxy.reset("gl")690 _ = engine.apply(Suggestion(text: "ligne 1\nligne 2", kind: .shortcut, score: 1), proxy: proxy)691 XCTAssertEqual(proxy.text, "ligne 1\nligne 2")692 }693694 // Requests, language, cursor695696 func testGlobePanelAndLanguage() {697 XCTAssertEqual(tap(.globe).request, .advanceToNextInputMode)698 XCTAssertEqual(tap(.panel(.ai)).request, .openPanel(.ai))699 XCTAssertEqual(proxy.text, "")700 XCTAssertEqual(engine.language, .frenchCanada)701 XCTAssertTrue(tap(.nextLanguage).layoutChanged)702 XCTAssertEqual(engine.language, .english)703 tap(.nextLanguage)704 tap(.nextLanguage)705 XCTAssertEqual(engine.language, .frenchCanada)706 engine.switchLanguage(to: .frenchAZERTY) // not enabled707 XCTAssertEqual(engine.language, .frenchCanada)708 XCTAssertTrue(engine.layoutRequest(showsGlobe: false).showsLanguageKey)709 engine.settings.enabledLanguages = [.spanish]710 engine.settings = engine.settings.migrated()711 XCTAssertEqual(engine.language, .spanish)712 XCTAssertFalse(engine.layoutRequest(showsGlobe: false).showsLanguageKey)713 }714715 func testCursorMovesByGraphemes() {716 proxy.reset("a👨👩👧👦b")717 engine.moveCursor(by: -1, proxy: proxy)718 XCTAssertEqual(proxy.before, "a👨👩👧👦")719 engine.moveCursor(by: -1, proxy: proxy)720 XCTAssertEqual(proxy.before, "a")721 XCTAssertEqual(proxy.after, "👨👩👧👦b")722 engine.moveCursor(by: 2, proxy: proxy)723 XCTAssertEqual(proxy.after, "")724 engine.moveCursor(by: 5, proxy: proxy)725 engine.moveCursor(by: -50, proxy: proxy)726 XCTAssertEqual(proxy.before, "")727 XCTAssertEqual(proxy.text, "a👨👩👧👦b")728 }729730 func testHostThatHidesContextAfterEmojiDoesNotForceCapitals() {731 proxy.hidesContextWithEmoji = true732 engine.refreshShift(proxy: proxy)733 XCTAssertEqual(engine.shift, .once)734 _ = engine.insertVerbatim("❤️", proxy: proxy)735 XCTAssertNil(proxy.contextBefore, "the simulated host reports nothing once an emoji is present")736 _ = engine.contextDidChange(proxy: proxy) // the host echoes the change737 XCTAssertEqual(engine.shift, .off)738 type("ok")739 _ = engine.contextDidChange(proxy: proxy)740 XCTAssertEqual(proxy.text, "❤️ok")741 XCTAssertEqual(engine.shift, .off)742 type(". b")743 XCTAssertEqual(proxy.text, "❤️ok. B", "a real sentence end still capitalises")744 // The host clears the field (message sent): the next letter starts a sentence again.745 proxy.reset()746 _ = engine.contextDidChange(proxy: proxy)747 XCTAssertEqual(engine.shift, .once)748 }749750 func testInsertVerbatim() {751 _ = engine.insertVerbatim("🎉", proxy: proxy)752 _ = engine.insertVerbatim("", proxy: proxy)753 XCTAssertEqual(proxy.text, "🎉")754 }755756 func testLimitedContextWindowDoesNotBreakEditing() {757 proxy.contextWindow = 6758 proxy.reset("Un très long texte déjà présent dans le champ")759 type(" ok")760 tap(.backspace)761 XCTAssertEqual(proxy.text, "Un très long texte déjà présent dans le champ o")762 }763}764765final class TextAnalysisTests: XCTestCase {766 func testCurrentWord() {767 XCTAssertEqual(TextAnalysis.currentWord(in: nil), "")768 XCTAssertEqual(TextAnalysis.currentWord(in: "Bonjour le mon"), "mon")769 XCTAssertEqual(TextAnalysis.currentWord(in: "Bonjour "), "")770 XCTAssertEqual(TextAnalysis.currentWord(in: "l'école"), "l'école")771 XCTAssertEqual(TextAnalysis.currentWord(in: "peut-être"), "peut-être")772 XCTAssertEqual(TextAnalysis.currentWord(in: "(test"), "test")773 XCTAssertEqual(TextAnalysis.currentWord(in: "dit 'allo"), "allo")774 XCTAssertEqual(TextAnalysis.currentWord(in: "niño"), "niño")775 }776777 func testPreviousWords() {778 XCTAssertEqual(TextAnalysis.previousWords(in: "Je vais au dep"), ["vais", "au"])779 XCTAssertEqual(TextAnalysis.previousWords(in: "Je vais au "), ["vais", "au"])780 XCTAssertEqual(TextAnalysis.previousWords(in: "Fini. Je "), ["Je"])781 XCTAssertEqual(TextAnalysis.previousWords(in: "mot"), [])782 XCTAssertEqual(TextAnalysis.previousWords(in: ""), [])783 }784785 func testSentenceStart() {786 XCTAssertTrue(TextAnalysis.isSentenceStart(nil))787 XCTAssertTrue(TextAnalysis.isSentenceStart(""))788 XCTAssertTrue(TextAnalysis.isSentenceStart("Fini. "))789 XCTAssertTrue(TextAnalysis.isSentenceStart("Quoi? "))790 XCTAssertTrue(TextAnalysis.isSentenceStart("ligne\n"))791 XCTAssertTrue(TextAnalysis.isSentenceStart("Il a dit «\u{00A0}oui.\u{00A0}» "))792 XCTAssertFalse(TextAnalysis.isSentenceStart("Fini."))793 XCTAssertFalse(TextAnalysis.isSentenceStart("Bonjour "))794 XCTAssertFalse(TextAnalysis.isSentenceStart("un, "))795 }796797 func testMachineTokens() {798 for token in ["a@b.ca", "https://x", "snake_case", "v2", "spboucher.ai", "3.14"] { XCTAssertTrue(TextAnalysis.looksLikeMachineToken(token), token) }799 for word in ["bonjour", "l'école", "fin."] { XCTAssertFalse(TextAnalysis.looksLikeMachineToken(word), word) }800 }801}802803final class SettingsTests: XCTestCase {804 func testDefaultsRoundTripThroughTheStore() {805 let store = InMemorySettingsStore()806 var loaded = store.load(KeyboardSettings.self)807 XCTAssertEqual(loaded.outcome, .missing)808 XCTAssertEqual(loaded.value, KeyboardSettings())809 var settings = KeyboardSettings()810 settings.oneHanded = .left811 settings.heightScale = 1.1812 settings.enabledLanguages = [.english, .frenchAZERTY]813 settings.currentLanguage = .english814 let before = store.revision815 store.save(settings)816 XCTAssertEqual(store.revision, before + 1)817 loaded = store.load(KeyboardSettings.self)818 XCTAssertEqual(loaded.outcome, .stored)819 XCTAssertEqual(loaded.value, settings)820 }821822 func testCorruptedAndFutureBlobsFallBack() {823 let store = InMemorySettingsStore()824 store.set(Data("{{{".utf8), forKey: KeyboardSettings.storageKey)825 XCTAssertEqual(store.load(KeyboardSettings.self).outcome, .corrupted)826 XCTAssertEqual(store.load(KeyboardSettings.self).value, KeyboardSettings())827 store.set(Data(#"{"schemaVersion":99}"#.utf8), forKey: KeyboardSettings.storageKey)828 XCTAssertEqual(store.load(KeyboardSettings.self).outcome, .newerSchema)829 store.set(Data(count: 600 * 1024), forKey: KeyboardSettings.storageKey)830 XCTAssertEqual(store.load(KeyboardSettings.self).outcome, .corrupted)831 }832833 func testPartialOrOddBlobKeepsWhatItCan() {834 let store = InMemorySettingsStore()835 store.set(Data(#"{"schemaVersion":1,"autocorrection":false,"oneHanded":"sideways","heightScale":9,"enabledLanguages":["en","en","xx"],"currentLanguage":"es","glideTyping":true}"#.utf8),836 forKey: KeyboardSettings.storageKey)837 let (settings, outcome) = store.load(KeyboardSettings.self)838 XCTAssertEqual(outcome, .stored)839 XCTAssertFalse(settings.autocorrection)840 XCTAssertEqual(settings.oneHanded, .off)841 XCTAssertEqual(settings.heightScale, 1.25)842 XCTAssertTrue(settings.predictions)843 XCTAssertTrue(settings.glideTyping)844 XCTAssertTrue(settings.numberHints)845 XCTAssertFalse(settings.numberRow)846 XCTAssertTrue(settings.enabledLanguages.contains(settings.currentLanguage))847 }848849 func testSchemaTwoTurnsGlideOnOnceThenRespectsTheChoice() {850 let store = InMemorySettingsStore()851 store.set(Data(#"{"schemaVersion":1,"glideTyping":false,"activeThemeID":"aurora-sp"}"#.utf8), forKey: KeyboardSettings.storageKey)852 var settings = store.load(KeyboardSettings.self).value853 XCTAssertTrue(settings.glideTyping, "1.x stored false because the feature did not exist")854 XCTAssertEqual(settings.activeThemeID, "atelier-clair")855 settings.glideTyping = false856 store.save(settings)857 XCTAssertFalse(store.load(KeyboardSettings.self).value.glideTyping, "a 2.0 choice survives")858 }859860 func testMigrationRepairsLanguages() {861 var settings = KeyboardSettings()862 settings.enabledLanguages = []863 XCTAssertEqual(settings.migrated().enabledLanguages, [.frenchCanada])864 settings.enabledLanguages = [.english, .english, .spanish]865 settings.currentLanguage = .frenchAZERTY866 let migrated = settings.migrated()867 XCTAssertEqual(migrated.enabledLanguages, [.english, .spanish])868 XCTAssertEqual(migrated.currentLanguage, .english)869 XCTAssertEqual(migrated.nextLanguage(after: .spanish), .english)870 }871872 func testUserDictionary() {873 var dictionary = UserDictionary()874 XCTAssertTrue(dictionary.addWord(" Saguenay "))875 XCTAssertFalse(dictionary.addWord("saguenay"))876 XCTAssertFalse(dictionary.addWord("deux mots"))877 XCTAssertFalse(dictionary.addWord(""))878 XCTAssertEqual(dictionary.words, ["Saguenay"])879 XCTAssertFalse(dictionary.recordLearned("clavardons"))880 XCTAssertTrue(dictionary.activeLearned.isEmpty)881 XCTAssertTrue(dictionary.recordLearned("clavardons"))882 XCTAssertEqual(dictionary.activeLearned, ["clavardons": 2])883 XCTAssertFalse(dictionary.recordLearned("clavardons"))884 XCTAssertEqual(dictionary.triggers["omw"], "Je suis en route, j'arrive dans quelques minutes.")885 for index in 0..<(UserDictionary.maxLearned + 50) { _ = dictionary.recordLearned("mot\(index)") }886 XCTAssertLessThanOrEqual(dictionary.learned.count, UserDictionary.maxLearned)887 dictionary.snippets.append(Snippet(title: "vide", text: ""))888 dictionary.snippets.append(Snippet(title: "long", trigger: "a b c", text: String(repeating: "x", count: 9000)))889 let migrated = dictionary.migrated()890 XCTAssertFalse(migrated.snippets.contains { $0.title == "vide" })891 XCTAssertEqual(migrated.snippets.last?.text.count, UserDictionary.maxSnippetLength)892 XCTAssertEqual(migrated.snippets.last?.trigger, "abc")893 }894895 func testSettingsExportRoundTripAndValidation() throws {896 var dictionary = UserDictionary()897 _ = dictionary.addWord("Chicoutimi")898 _ = dictionary.recordLearned("secretword")899 _ = dictionary.recordLearned("secretword")900 var settings = KeyboardSettings()901 settings.keySound = true902 let data = try SettingsExport(settings: settings, dictionary: dictionary).encoded()903 let text = String(decoding: data, as: UTF8.self)904 XCTAssertFalse(text.contains("secretword"), "learned words are not exported")905 XCTAssertFalse(text.contains("sk-ant"))906 let decoded = try SettingsExport.decode(data)907 XCTAssertEqual(decoded.settings, settings)908 XCTAssertEqual(decoded.words, ["Chicoutimi"])909 XCTAssertEqual(decoded.snippets, dictionary.snippets)910 XCTAssertThrowsError(try SettingsExport.decode(Data("{}".utf8))) { XCTAssertEqual($0 as? SettingsExport.ImportError, .notRecognized) }911 XCTAssertThrowsError(try SettingsExport.decode(Data(count: SettingsExport.maxImportBytes + 1))) { XCTAssertEqual($0 as? SettingsExport.ImportError, .tooLarge) }912 XCTAssertThrowsError(try SettingsExport.decode(Data(text.replacingOccurrences(of: "\"schemaVersion\" : 1,\n \"settings\"", with: "\"schemaVersion\" : 7,\n \"settings\"").utf8))) {913 XCTAssertEqual($0 as? SettingsExport.ImportError, .unsupportedVersion)914 }915 }916}917918final class EmojiTests: XCTestCase {919 func testCatalogue() {920 XCTAssertGreaterThanOrEqual(EmojiCatalog.categories.count, 8)921 XCTAssertGreaterThan(EmojiCatalog.all.count, 700)922 XCTAssertEqual(Set(EmojiCatalog.categories.map(\.id)).count, EmojiCatalog.categories.count)923 for emoji in EmojiCatalog.all { XCTAssertEqual(emoji.count, 1, "\(emoji) is not a single grapheme") }924 XCTAssertEqual(Set(EmojiCatalog.all).count, EmojiCatalog.all.count, "duplicate emoji")925 }926927 func testSearchInFrenchAndEnglish() {928 XCTAssertTrue(EmojiCatalog.search("coeur").contains("❤️"))929 XCTAssertTrue(EmojiCatalog.search("cœur brisé").contains("💔") || EmojiCatalog.search("coeur brise").contains("💔"))930 XCTAssertTrue(EmojiCatalog.search("ERABLE").contains("🍁"))931 XCTAssertTrue(EmojiCatalog.search("grinning").contains("😀"))932 XCTAssertTrue(EmojiCatalog.search("pizza").contains("🍕"))933 XCTAssertTrue(EmojiCatalog.search("hockey").contains("🏒"))934 XCTAssertTrue(EmojiCatalog.search("zzzzqqq").isEmpty)935 XCTAssertTrue(EmojiCatalog.search(" ").isEmpty)936 XCTAssertLessThanOrEqual(EmojiCatalog.search("face", limit: 5).count, 5)937 }938}939