importCottonKitimportFoundationimport XCTest@testable importCottonUI#if os(iOS)/// Delete account (assets/design/shared/DELETE_ACCOUNT.md "Tests that stand for the contract"): a wrong code deletes/// nothing; the code typed back deletes and the app is told the database id; Go back asks nothing. The same part/// stands in Words, Days and Story, so one flow's cases stand for the three.@MainActorfinalclassDeleteAccountTests: XCTestCase {privatefunc opened(_ deleting: FakeDeleting) async -> DeleteAccountFlow {let flow = DeleteAccountFlow(app: "Cotton Days", deleting: deleting)await flow.load() flow.open = truereturn flow }func testAWrongCodeDeletesNothing() async {let deleting = FakeDeleting(right: "123456")let flow = await opened(deleting)await flow.send() XCTAssertEqual(flow.sent, "We sent a code by text message to +15550101234.") flow.code = "999999"let done = await flow.confirm() XCTAssertNil(done) XCTAssertEqual(flow.problem, "That code is wrong or too old. Please try again.") XCTAssertTrue(flow.open, "the page stays") XCTAssertEqual(flow.code, "999999", "the field is kept")let deleted = await deleting.deleted XCTAssertFalse(deleted) }func testTheCodeTypedBackDeletesAndNamesTheDatabase() async {let deleting = FakeDeleting(right: "123456")let flow = await opened(deleting)await flow.send() flow.code = "12 34-56" XCTAssertEqual(flow.code, "123456", "digits only")let done = await flow.confirm() XCTAssertEqual(done?.databaseId, "db-walk") XCTAssertEqual(done?.line?.isEmpty, false) XCTAssertFalse(flow.open)let asked = await deleting.asked XCTAssertEqual(asked.last, "delete:challenge-1:123456:Cotton Days", "the app names itself") }func testGoBackAsksNothing() async {let deleting = FakeDeleting(right: "123456")let flow = await opened(deleting) flow.close() XCTAssertFalse(flow.open)let asked = await deleting.asked XCTAssertEqual(asked, ["page:Cotton Days"], "no code was sent, nothing deleted") }// RULE (DELETE_ACCOUNT.md "(30 days)"): the page's words decode with `when`, and with an older core's `undo`. A// required `undo` failed against the 30-day core and the row vanished from Words, Days and Story.func testThePageReadsWhenAndAnOlderUndo() throws {let base = #"{"row":"Delete account","heading":"h","whatGoes":"g","whatStays":"s","otherApps":"o","send":"Send","codeLabel":"Code","confirm":"Delete","cancel":"Go back","working":"…""#let now = try JSONDecoder().decode(DeleteAccountWords.self, from: Data((base + #","when":"Deleted30 days after you ask."}"#).utf8)) XCTAssertEqual(now.warning, "Deleted 30 days after you ask.")let older = try JSONDecoder().decode(DeleteAccountWords.self, from: Data((base + #","undo":"This cannot be undone."}"#).utf8)) XCTAssertEqual(older.warning, "This cannot be undone.") }// RULE: an account deleted elsewhere is its own event (410 `account_deleted`), its line carried; an ordinary// sign-out is unchanged.func testDeletedElsewhereIsReadApartFromASignOut() {let deleted = ClientEvent.from(CottonEvent(kind: "client", payload: .object(["phase": .string("personal"), "stage": .string("signed_out"), "code": .string("account_deleted"), "deleted": .bool(true),"words": .object(["heading": .string("Your account was deleted"), "line": .string("This phone has removed its copy too.")]), ]))) XCTAssertEqual(deleted, .personalDeleted(line: "This phone has removed its copy too."))let signedOut = ClientEvent.from(CottonEvent(kind: "client", payload: .object(["phase": .string("personal"), "stage": .string("signed_out"), "code": .string("unauthorized"), ]))) XCTAssertEqual(signedOut, .personalSignedOut(code: "unauthorized")) }// RULE (launch-ios walk, 22 Nov 2026): a passing line the shell says (the account deleted) is drawn once, in the// app's look: the window's receipt overlay stands inside the app look, and one beneath it in the same// presentation stays quiet. Both drew it, one in the paper strip.func testAPassingLineIsDrawnOnceInTheAppsLook() throws {let root = SourceSweep.withoutComments(trySourceSweep.mustRead("apps/cotton/Sources/CottonUI/Boot/RootView.swift", ownedBy: "launch-ios"))let window = try XCTUnwrap(root.range(of: ".cottonToasts(toasts)"))let look = try XCTUnwrap(root.range(of: ".environment(\\.vaultLook, appLook)")) XCTAssertLessThan(window.lowerBound, look.lowerBound, "the window's overlay is inside the app look")let toast = SourceSweep.withoutComments(trySourceSweep.mustRead("apps/cotton/Sources/CottonUI/Chrome/Toast.swift", ownedBy: "launch-ios")) XCTAssertTrue(toast.contains("ToastKnobs.draws(cover: cover, hungAbove: hungAbove)"), "an overlay beneath another in its presentation stays quiet") XCTAssertFalse(ToastKnobs.draws(cover: false, hungAbove: true), "an overlay beneath another in its presentation stays quiet") }}/// The 30 days (DELETE_ACCOUNT.md "Signing in during the 30 days"): a sign-in answered with `deleting` keeps nothing/// and asks Keep or Leave; Keep keeps the credential as any sign-in, Leave keeps nothing.@MainActorfinalclassSetToGoSignInTests: XCTestCase {privatefunc client(_ core: SetToGoCore, _ store: InMemorySecretStore) -> BusinessClient {BusinessClient(core: core, address: BusinessAddress(server: "https://cottondb.example.com", window: [:]), store: store) }privatefunc signingIn(_ client: BusinessClient) asyncthrows -> AccountSetToGo {do { _ = tryawait client.signIn(phone: "+15550100777", challenge: BusinessChallenge(challengeId: "c1", databaseId: "db-gone"), code: "123456") } catchlet setToGo asAccountSetToGo {return setToGo } XCTFail("a sign-in to an account set to be deleted went on")throwCancellationError() }// RULE: nothing is kept until the person chooses; the core's words are what the card says.func testASignInToAnAccountSetToGoKeepsNothingAndAsks() asyncthrows {let store = InMemorySecretStore()let setToGo = tryawait signingIn(client(SetToGoCore(), store)) XCTAssertEqual(setToGo.words.keep, "Keep my account") XCTAssertEqual(setToGo.words.leave, "Leave it to be deleted") XCTAssertTrue(setToGo.words.line.contains("22 December")) XCTAssertNil(client(SetToGoCore(), store).session(), "no credential kept") }// RULE: Keep asks account.keep with the sign-in's own credential, then keeps it as any sign-in does.func testKeepKeepsTheCredentialAsAnySignIn() asyncthrows {let store = InMemorySecretStore()let core = SetToGoCore()let client = client(core, store)let setToGo = tryawait signingIn(client)let session = tryawait client.keep(setToGo) XCTAssertEqual(session.databaseId, "db-gone")let asked = await core.asked XCTAssertEqual(asked.last?.method, "account.keep") XCTAssertTrue(asked.last?.body.contains("synthetic.gone.credential") == true) XCTAssertNotNil(self.client(core, store).session(), "kept once the person said Keep") }// RULE: Leave asks account.leave and keeps nothing.func testLeaveKeepsNothing() asyncthrows {let store = InMemorySecretStore()let core = SetToGoCore()let client = client(core, store)tryawait client.leave(tryawait signingIn(client))let asked = await core.asked XCTAssertEqual(asked.last?.method, "account.leave") XCTAssertNil(self.client(core, store).session()) }}/// A core whose account is set to be deleted: `personal.signIn` answers `deleting`.private actor SetToGoCore: CottonCalling {private(set) var asked: [(method: String, body: String)] = []func callRaw(_ method: String, requestJSON: String) asyncthrows -> String { asked.append((method, requestJSON))switch method {case"personal.signIn":return #"{"ok":true,"data":{"credential":"synthetic.gone.credential","person":{"id":"p1","phone":"+15550100777"},"expiresIn":3600,"databaseId":"db-gone","deleting":{"eraseAt":"2026-12-22T10:00:00Z","date":"22December","heading":"Your account is set to be deleted","line":"Your account is set to be deleted on 22December. You can keep it, or leave it to be deleted on that day.","keep":"Keep my account","leave":"Leave it to be deleted"}}}"#case"account.keep": return #"{"ok":true,"data":{"kept":true,"line":"Your account is kept."}}"#case"account.leave": return #"{"ok":true,"data":{"left":true}}"#default: return #"{"ok":true,"data":{}}"# } }func subscribe(_ handler: @escaping @Sendable (CottonEvent) -> Void) async {}func close() async {}}private actor FakeDeleting: AccountDeleting {let right: Stringprivate(set) var asked: [String] = []private(set) var deleted = falseinit(right: String) { self.right = right }func page(app: String) asyncthrows -> DeleteAccountWords { asked.append("page:\(app)")returnDeleteAccountWords(row: "Delete account", heading: "Delete your Cotton account", whatGoes: "Everything.", whatStays: "Messages.", when: "Your account is deleted 30 days after you ask.", otherApps: "Every Cotton app, not only \(app).", send: "Send code by text", codeLabel: "Code from text", confirm: "Delete my account", cancel: "Go back", working: "Deleting your account", offline: "Connect and try again.") }func code() asyncthrows -> DeleteAccountCode { asked.append("code")returnDeleteAccountCode(challengeId: "challenge-1", sent: "We sent a code by text message to +15550101234.") }func delete(challengeId: String, code: String, app: String) asyncthrows -> DeleteAccountDone { asked.append("delete:\(challengeId):\(code):\(app)")guard code == right else { throwCottonCallError(code: "invalid_code", message: "That code is wrong or too old. Please try again.") } deleted = truereturnDeleteAccountDone(heading: "Your account is deleted", line: "Cotton Days now starts fresh on this phone.", databaseId: "db-walk") }}#endif