412 lines · 17.1 KB · SwiftRaw
// `/search`, in three layers: the list's shape, the recents, and the model// that debounces and asks.//// The sections, their order, their words, their counts and every hit's title,// caption and route are the core's (`read.find`'s `sections`,// `crates/cotton-ffi/src/phone/find_words_tests.rs`); what is tested here is// that Search draws them as answered.//// No wall clock anywhere: the debounce runs through `ManualToastScheduler`.import CottonKitimport XCTest@testable import CottonUI// MARK: - Fixtures/// A worded hit, as a section lists it.private func hit(_ id: String, kind: String = "todo", title: String = "A todo") -> FindHit { FindHit(kind: kind, id: id, title: title, opens: Route.parse("/todos/todo/\(id)"), card: .init(table: kind, id: id))}/// A section as the core answers it.private func section(_ id: String, words: String = "Todos", count: Int? = nil, _ hits: [FindHit]) -> FindSection { FindSection(id: id, words: words, count: count ?? hits.count, kinds: [id], hits: hits)}/// Three tools, standing in for the directory where the case is about the RAIL/// rather than about the directory (which `HomeDataTests` owns).private let threeTools: [FindTool] = [ FindTool(key: "todos", name: "Todos", icon: "circle-check", path: "/todos"), FindTool(key: "calendar", name: "Calendar", icon: "calendar-days", path: "/calendar"), FindTool(key: "about", name: "About", icon: "info", path: "/about"),]private func kinds(_ items: [SearchItem]) -> [String] { items.map { item in switch item { case .recentsLabel: return "recentsLabel" case .recent: return "recent" case .placeChips: return "placeChips" case .sectionLabel: return "sectionLabel" case .hit: return "hit" case .seeAll: return "seeAll" } }}private func hitIds(_ items: [SearchItem]) -> [String] { items.compactMap { if case .hit(_, let hit, _, _) = $0 { return hit.recordId } else { return nil } }}private func chips(_ items: [SearchItem]) -> [SearchPlaceChip] { for item in items { if case .placeChips(_, let chips) = item { return chips } } return []}private func sections(_ items: [SearchItem]) -> [String] { items.compactMap { if case .sectionLabel(_, let section, _, _) = $0 { return section } else { return nil } }}// MARK: - searchItems, at restfinal class FindItemsAtRestTests: XCTestCase { func testKeepsTheRecentsInTheOrderItWasHandedNewestFirst() { let items = searchItems(tools: threeTools, recents: ["net-45", "quote v2"], query: "") let words = items.compactMap { if case .recent(_, let query) = $0 { return query } else { return nil } } XCTAssertEqual(words, ["net-45", "quote v2"]) }}// MARK: - searchItems, typedfinal class FindItemsTypedTests: XCTestCase { func testAnswersMatchingPlacesAsOneRailByNameMatch() { let items = searchItems(tools: threeTools, query: "cal") XCTAssertEqual(chips(items).map(\.label), ["Calendar"]) } func testDrawsTheAnswersSectionsInItsOrderWithItsWordsAndCounts() { // The core's order, not one remembered here: People before Todos. let answer = [ section("person", words: "People", count: 4, [hit("p1", kind: "person", title: "Quillon Walker")]), section("todo", words: "Todos", count: 2, [hit("t1"), hit("t2")]), FindSection(id: "recipe", words: "Recipes", count: 1, defined: true, hits: [hit("r1", kind: "recipe", title: "Dal")]), ] let items = searchItems(tools: [], sections: answer, query: "x") XCTAssertEqual(sections(items), ["person", "todo", "recipe"]) let heads = items.compactMap { item -> String? in if case .sectionLabel(_, _, let words, let count) = item { return "\(words) \(count)" } else { return nil } } XCTAssertEqual(heads, ["People 4", "Todos 2", "Recipes 1"]) XCTAssertEqual(kinds(items), ["sectionLabel", "hit", "seeAll", "sectionLabel", "hit", "hit", "sectionLabel", "hit"]) guard case .seeAll(_, "person", "People", let remaining) = items[2] else { return XCTFail("no See-all row") } XCTAssertEqual(remaining, 3, "the answer's count less the hits shown") } func testCollapsesAtThreeAndCountsWhatTheDatabaseHolds() { let todos = (0..<5).map { hit("t\($0)") } let items = searchItems(tools: [], sections: [section("todo", count: 45, todos)], query: "x") XCTAssertEqual(hitIds(items), ["t0", "t1", "t2"]) guard case .seeAll(_, _, _, let remaining) = items.last else { return XCTFail("no See-all row") } XCTAssertEqual(remaining, 45 - searchSectionCollapsed) } func testExpandsASectionInPlaceAndDropsItsSeeAll() { let todos = (0..<5).map { hit("t\($0)") } let items = searchItems(tools: [], sections: [section("todo", todos)], expanded: ["todo"], query: "x") XCTAssertEqual(hitIds(items).count, 5) XCTAssertFalse(kinds(items).contains("seeAll")) } func testAnswersWithNothingAtAllWhenTheQueryMatchesNothing() { XCTAssertTrue(searchItems(tools: threeTools, query: "zzz").isEmpty) } func testTheRailIsCappedAtEight() { let many = (0..<12).map { FindTool(key: "t\($0)", name: "Thing \($0)", icon: "circle-check", path: "/todos") } XCTAssertEqual(chips(searchItems(tools: many, query: "thing")).count, searchPlaceChipCap) }}// MARK: - The recentsfinal class FindRecentsTests: XCTestCase { func testPutsTheNewestSearchFirst() { XCTAssertEqual(rememberRecent(["old"], "new"), ["new", "old"]) } func testDedupesCaseInsensitivelyNewestCasingWinning() { XCTAssertEqual(rememberRecent(["ravi", "lease"], "Ravi"), ["Ravi", "lease"]) } func testIgnoresAnEmptySearch() { XCTAssertEqual(rememberRecent(["kept"], " "), ["kept"]) } func testCapsTheList() { let full = (0..<searchRecentsCap).map { "q\($0)" } let next = rememberRecent(full, "fresh") XCTAssertEqual(next.count, searchRecentsCap) XCTAssertEqual(next.first, "fresh") XCTAssertFalse(next.contains("q\(searchRecentsCap - 1)")) } func testTheStoreIsTheOnlyThingPersisted() { let store = InMemorySearchRecents(["one"]) XCTAssertEqual(store.load(), ["one"]) store.save(["two", "one"]) XCTAssertEqual(store.load(), ["two", "one"]) }}// MARK: - The model@MainActorfinal class FindModelTests: XCTestCase { private func subject( _ answer: String = #"{ "hits": [], "sections": [] }"#, recents: [String] = [] ) -> (SearchModel, ScriptedCore, ManualToastScheduler, InMemorySearchRecents) { let core = ScriptedCore([CottonMethod.readFind: .ok(answer)]) let clock = ManualToastScheduler() let store = InMemorySearchRecents(recents) return (SearchModel(core: core, recents: store, scheduler: clock), core, clock, store) } /// Let the debounce fall due and the flight land. Nothing sleeps. private func settle(_ model: SearchModel, _ clock: ManualToastScheduler) async { clock.advance() await model.searchTask?.value } private static let oneTodo = """ { "sections": [ { "id": "todo", "words": "Todos", "count": 1, "kinds": ["todo"], "hits": [ { "id": "t1", "kind": "todo", "title": "Call the plumber", "opens": { "table": "todo", "id": "t1", "path": "/todos/todo/t1", "screen": "deck" }, "record": { "table": "todo", "id": "t1" } } ] } ] } """ /// The answer's hits, section by section. private func hits(_ model: SearchModel) -> [FindHit] { model.sections.flatMap(\.hits) } // ── At rest ────────────────────────────────────────────────────────── func testAtRestTheScreenAsksTheDatabaseNOTHING() async { // No skeleton and no read: Find is a question, and a screen that queried // on appear would be answering one nobody asked. let (model, core, _, _) = subject() model.load() XCTAssertTrue(model.items.isEmpty) let asked = await core.methodsCalled() XCTAssertEqual(asked, []) } func testAtRestTheRecentsComeOffThisDevice() { let (model, _, _, _) = subject(recents: ["quote v2"]) model.load() XCTAssertEqual(model.recents, ["quote v2"]) XCTAssertEqual(kinds(model.items), ["recentsLabel", "recent"]) } // ── The four rules ─────────────────────────────────────────────────── func testTypingAWordIsONEQueryRatherThanFive() async { let (model, core, clock, _) = subject(FindModelTests.oneTodo) model.type("p") model.type("pl") model.type("plu") model.type("plumber") await settle(model, clock) let asked = await core.methodsCalled() XCTAssertEqual(asked, [CottonMethod.readFind]) XCTAssertEqual(model.settled, "plumber") } func testTheDebounceIsTheDeclaredWindow() { let (model, _, clock, _) = subject() model.type("pl") XCTAssertEqual(clock.scheduledWindows, [Double(searchDebounceMs) / 1000]) } func testAOneCharacterQueryNEVERASKS() async { let (model, core, clock, _) = subject() model.type("p") await settle(model, clock) let asked = await core.methodsCalled() XCTAssertEqual(asked, []) XCTAssertFalse(model.bites) } func testTheROWSALREADYINHANDSurviveTheNextKeystroke() async { let (model, core, clock, _) = subject(FindModelTests.oneTodo) model.type("plumber") await settle(model, clock) XCTAssertEqual(hits(model).map(\.recordId), ["t1"]) // The next query is in flight; the list must not flicker empty. await core.answer(CottonMethod.readFind, .ok(#"{ "hits": [], "sections": [] }"#)) model.type("plumbers") XCTAssertEqual(hits(model).map(\.recordId), ["t1"]) await settle(model, clock) XCTAssertEqual(hits(model), []) } func testAFAILEDSearchKeepsTheRowsAndSaysTheSEARCHFailed() async { let (model, core, clock, _) = subject(FindModelTests.oneTodo) model.type("plumber") await settle(model, clock) await core.answer(CottonMethod.readFind, .refuse(code: "unreadable", message: "offline")) model.type("plumbers") await settle(model, clock) XCTAssertTrue(model.searchFailed) // A failure loses to rows already in hand. XCTAssertEqual(hits(model).map(\.recordId), ["t1"]) } func testAQueryThatNEVERRANCannotHaveFailed() async { let (model, core, clock, _) = subject() await core.answer(CottonMethod.readFind, .refuse(code: "unreadable", message: "offline")) model.type("north") await settle(model, clock) XCTAssertTrue(model.searchFailed) // Back below the floor: the verdict goes with the query. model.type("n") await settle(model, clock) XCTAssertFalse(model.searchFailed) XCTAssertTrue(model.sections.isEmpty) } // ── A place is a swap, a hit is a push ─────────────────────────────── func testEveryDirectoryRowsPathParsesIntoARouteThisAppCanDraw() { // The rail can only be a swap if every row it can offer resolves. A row // whose path this app cannot parse would be a chip that does nothing. let (model, _, _, _) = subject() for tool in model.tools { XCTAssertNotNil(Route.parse(tool.path), "\(tool.key): \(tool.path)") } } func testPushesARecordHitAndRemembersTheSearchThatFoundIt() async { let (model, _, clock, store) = subject(FindModelTests.oneTodo) model.type("plumber") await settle(model, clock) XCTAssertEqual(hits(model).count, 1) XCTAssertEqual(model.open(hits(model)[0])?.path, "/todos/todo/t1") XCTAssertEqual(model.recents, ["plumber"]) // …and it survives the screen: the list is device-local, not per visit. XCTAssertEqual(store.load(), ["plumber"]) } func testTheRecentsKeepTheDEBOUNCEDWordsNeverAHalfTypedPrefix() async { let (model, _, clock, _) = subject(FindModelTests.oneTodo) model.type("plumber") await settle(model, clock) // A keystroke lands after the answer and before the tap. model.type("plumberr") _ = model.open(hits(model)[0]) XCTAssertEqual(model.recents, ["plumber"]) } func testAHitThatOPENSNOTHINGRemembersNothingEither() async { let bus = """ { "sections": [ { "id": "session_message", "words": "Session messages", "count": 1, "hits": [ { "id": "sm1", "kind": "session_message", "title": "a line" } ] } ] } """ let (model, _, clock, _) = subject(bus) model.type("plumber") await settle(model, clock) XCTAssertNil(model.open(hits(model)[0])) XCTAssertEqual(model.recents, []) } func testClearingTheFieldLandsBackOnTheRecentsAndClearEmptiesThem() async { let (model, _, clock, store) = subject(FindModelTests.oneTodo) model.type("plumber") await settle(model, clock) _ = model.open(hits(model)[0]) model.type("") await settle(model, clock) XCTAssertEqual(kinds(model.items), ["recentsLabel", "recent"]) model.clearRecents() XCTAssertTrue(model.items.isEmpty) XCTAssertEqual(store.load(), []) } func testARecentRunsAgainFromItsRow() async { let (model, _, clock, _) = subject(FindModelTests.oneTodo, recents: ["plumber"]) model.load() model.type("plumber") await settle(model, clock) XCTAssertEqual(sections(model.items), ["todo"]) } func testTheRequestIsTheOneArgumentTheCrateReads() throws { let body = try JSONEncoder().encode(SearchRequest(query: "nilgiri", timezone: "Europe/London")) let sent = try XCTUnwrap(JSONSerialization.jsonObject(with: body) as? [String: String]) XCTAssertEqual(sent, ["query": "nilgiri", "timezone": "Europe/London"], "the words and the reader's zone") } // ── See all ────────────────────────────────────────────────────────── func testSeeAllPagesTheSectionToItsLastHitAndANewQueryClosesItAgain() async { func todos(_ range: Range<Int>, total: Int) -> String { let rows = range.map { index in "{ \"kind\": \"todo\", \"id\": \"t\(index)\", \"title\": \"Call \(index)\" }" } return "{ \"sections\": [ { \"id\": \"todo\", \"words\": \"Todos\", \"count\": \(total), " + "\"kinds\": [\"todo\"], \"hits\": [\(rows.joined(separator: ","))] } ] }" } // The first page is the collapsed three, with the section's exact total. let (model, core, clock, _) = subject(todos(0..<searchSectionCollapsed, total: 5)) model.type("call") await settle(model, clock) XCTAssertEqual(hitIds(model.items).count, searchSectionCollapsed) XCTAssertTrue(kinds(model.items).contains("seeAll")) // Expanding reads the kind's next page; a short page is its last. await core.answer(CottonMethod.readFind, .ok(todos(searchSectionCollapsed..<5, total: 5))) model.expand("todo", page: 50) await model.searchTask?.value XCTAssertEqual(hitIds(model.items).count, 5) XCTAssertFalse(kinds(model.items).contains("seeAll")) model.more("todo", page: 50) let asked = await core.methodsCalled() XCTAssertEqual(asked.count, 2, "a kind read to its end is not asked again") // An expansion is an answer to THIS answer, not a setting. model.type("calls") XCTAssertEqual(model.expanded, []) }}/// Which of the four things the answer area shows — the rule that a verdict on/// somebody's records is only ever drawn over a query that actually ran, and/// that the rest state carries a hint rather than nothing at all (the Mac/// walk, finding 15).final class SearchArmTests: XCTestCase { func testNothingAskedYetIsTheRestHintAndNeverAVerdict() { XCTAssertEqual(SearchArm.of(settled: "", failed: false, items: 0), .rest) // Even a failure flag left over from an earlier query does not put a // verdict over an empty field. XCTAssertEqual(SearchArm.of(settled: "", failed: true, items: 0), .rest) } func testAQueryThatRanAndFoundNothingSaysSo() { XCTAssertEqual(SearchArm.of(settled: "alpaca", failed: false, items: 0), .noMatch) } func testAQueryThatFellOverIsNotAnEmptyAnswer() { XCTAssertEqual(SearchArm.of(settled: "alpaca", failed: true, items: 0), .failed) } func testHitsOutrankEveryOtherArm() { XCTAssertEqual(SearchArm.of(settled: "alpaca", failed: true, items: 3), .results) XCTAssertEqual(SearchArm.of(settled: "", failed: false, items: 3), .results) }}