oficina / sheets Public

Clone
git clone https://amadan.net/oficina/sheets

Plain git — no account needed to clone.

Download

Download this file

1import Combine
2import Foundation
3import Observation
4import Synchronization
5import RastrilloApple
6import RastrilloTestSupport
7import XCTest
8@testable import SheetsKit
9
10/// Sheets on Oficina ID (Home spec 2026-11-14-oficina-id-native, slice A,
11/// and Paul's straight-in ruling of 2026-11-19), against the kit's in-memory
12/// Home, directory and instances. Two models sharing one shared store and
13/// App Group are two apps on one device.
14@MainActor final class OficinaIDAdoptionTests: XCTestCase {
15 /// `.invalid`, so a workspace that does talk to it fails at once.
16 static let sheetsOrigin = URL(string: "https://paulca.sheets.invalid")!
17 static let docsOrigin = URL(string: "https://paulca.docs.invalid")!
18
19 var service: FakeOficinaIDService!
20 var shared: OficinaMemoryStore!
21 var notifier: OficinaLocalNotifier!
22 var suites: [String] = []
23 lazy var group = defaults()
24
25 override func setUp() async throws {
26 service = FakeOficinaIDService()
27 shared = OficinaMemoryStore()
28 notifier = OficinaLocalNotifier()
29 }
30
31 override func tearDown() async throws {
32 for suite in suites { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }
33 }
34
35 func defaults() -> UserDefaults {
36 let suite = "SheetsOficinaIDTests.\(UUID().uuidString)"
37 suites.append(suite)
38 return UserDefaults(suiteName: suite)!
39 }
40
41 func model(_ slug: String, _ name: String) -> OficinaIDModel {
42 let store = OficinaIDStore(shared: shared, appPrivate: OficinaMemoryStore(), group: group, notifier: notifier)
43 return OficinaIDModel(configuration: OficinaIDConfiguration(app: slug, appName: name, platform: "macos"), store: store,
44 service: service, passkeys: FakePasskeys(), makeKey: { OficinaSoftwareKey() }, appDefaults: defaults())
45 }
46
47 /// Paul on one team with Docs and Sheets, signed in on this device by Docs:
48 /// the saved identity Sheets finds at launch.
49 @discardableResult
50 func savedIdentity() async throws -> OficinaTeam {
51 let apps = [OficinaTeamApp(app: "docs", origin: Self.docsOrigin.absoluteString, consumerID: "t1-docs"),
52 OficinaTeamApp(app: "sheets", origin: Self.sheetsOrigin.absoluteString, consumerID: "t1-sheets")]
53 let paulca = OficinaTeam(sqid: "t1", label: "paulca", name: "Paul", role: "member", apps: apps)
54 service.addPerson(email: "paul@tito.io", identityID: "id-1")
55 service.setTeams([paulca], for: "id-1")
56 service.admit("id-1", at: Self.docsOrigin, as: .linked)
57 service.admit("id-1", at: Self.sheetsOrigin, as: .linked)
58 let docs = model("docs", "Docs")
59 await docs.start()
60 docs.continueWithEmail()
61 docs.email = "paul@tito.io"
62 await docs.submitEmail()
63 docs.code = FakeOficinaIDService.goodCode
64 await docs.submitCode()
65 // A fixture that cannot sign in fails the test: skipping would hide the
66 // launch suite behind it.
67 guard case .signedIn = docs.step else {
68 XCTFail("Docs did not sign in: \(docs.step)")
69 throw CancellationError()
70 }
71 return paulca
72 }
73
74 // MARK: Straight in
75
76 /// One Oficina ID on the device: Sheets opens its team with no screen,
77 /// and the launch is not counted as a sign-in made here.
78 func testASavedIdentitySignsSheetsStraightIn() async throws {
79 let paulca = try await savedIdentity()
80 let sheets = SheetsOficinaSession(model: model("sheets", "Sheets"))
81 var steps: [String] = []
82 let watching = sheets.model.$step.sink { steps.append("\($0)".components(separatedBy: "(").first ?? "") }
83 await sheets.start()
84 watching.cancel()
85 let mounted = try XCTUnwrap(sheets.mounted)
86 XCTAssertEqual(mounted.team, paulca)
87 XCTAssertEqual(mounted.origin, Self.sheetsOrigin)
88 XCTAssertEqual(Set(steps), ["loading", "signedIn"], "no screen on the way in")
89 XCTAssertEqual(sheets.signIns, 0, "a launch going straight in does not choose the route")
90 XCTAssertEqual(service.calls.filter { $0.hasPrefix("startCode") }.count, 1, "one sign-in for both apps")
91 }
92
93 /// Sheets' last route was its own sign-in: nothing goes straight in, and
94 /// no network is used, until the person comes back to Oficina ID.
95 func testTheServerRouteSuspendsStraightIn() async throws {
96 try await savedIdentity()
97 let sheets = SheetsOficinaSession(model: model("sheets", "Sheets"))
98 let calls = service.calls.count
99 await sheets.start(serverRoute: true)
100 XCTAssertNil(sheets.mounted)
101 XCTAssertEqual(sheets.model.step, .welcome)
102 XCTAssertEqual(service.calls.count, calls, "no network while the app's own sign-in is the route")
103 await sheets.model.resumeStraightIn()
104 XCTAssertEqual(sheets.mounted?.origin, Self.sheetsOrigin)
105 }
106
107 /// The route flipping to Oficina ID on its own (the last server account
108 /// signed out) resumes straight in; flipping back to the app's own
109 /// sign-in while signed in disturbs nothing (Fable, sheets ded0f68).
110 func testTheRouteAloneDecidesTheSuspension() async throws {
111 try await savedIdentity()
112 let sheets = SheetsOficinaSession(model: model("sheets", "Sheets"))
113 await sheets.start(serverRoute: true)
114 XCTAssertTrue(sheets.model.straightInSuspended)
115 XCTAssertNil(sheets.mounted)
116 await sheets.routeChanged(to: .oficinaID)
117 XCTAssertFalse(sheets.model.straightInSuspended)
118 let mounted = try XCTUnwrap(sheets.mounted, "straight in once the route is Oficina ID")
119 await sheets.routeChanged(to: .server)
120 XCTAssertTrue(sheets.model.straightInSuspended)
121 XCTAssertEqual(sheets.mounted, mounted, "signed in, suspending changes nothing")
122 }
123
124 /// Sign-out and "Use another" are refused while a document window of the
125 /// identity is open, and "Use another" while the team is unreachable.
126 func testLeavingIsRefusedWithAnOpenDocumentOrOverAnOutage() async throws {
127 let paulca = try await savedIdentity()
128 let sheets = SheetsOficinaSession(model: model("sheets", "Sheets"))
129 await sheets.start()
130 let state = try XCTUnwrap(sheets.mounted)
131 XCTAssertFalse(sheets.useAnother(identity: state.identity.id, canLeave: false))
132 XCTAssertFalse(sheets.model.confirmingReplace)
133 XCTAssertFalse(sheets.signOut(identity: state.identity.id, canLeave: false))
134 XCTAssertEqual(sheets.mounted, state)
135 XCTAssertEqual(try sheets.model.store.identities().map(\.id), ["id-1"])
136
137 // Over an outage the team stays mounted, but there is no dialog to ask
138 // "Use another" with.
139 service.expire(session: state.session)
140 service.failNext("exchange", at: Self.sheetsOrigin.absoluteString, with: .offline)
141 await sheets.rejected(SheetsOficinaSession.accountID(state))
142 XCTAssertEqual(sheets.model.step, .unavailable(paulca))
143 XCTAssertNotNil(sheets.mounted)
144 XCTAssertFalse(sheets.useAnother(identity: state.identity.id, canLeave: true))
145 XCTAssertFalse(sheets.model.confirmingReplace)
146
147 await sheets.model.retry()
148 XCTAssertTrue(sheets.useAnother(identity: state.identity.id, canLeave: true))
149 XCTAssertTrue(sheets.model.confirmingReplace)
150 sheets.model.cancelReplace()
151 XCTAssertTrue(sheets.signOut(identity: state.identity.id, canLeave: true))
152 XCTAssertNil(sheets.mounted)
153 }
154
155 // MARK: Transport
156
157 /// The workspace's transport reads the latest session: a 401 re-mints
158 /// silently and the next request carries the new one.
159 func testTheTransportFollowsARemintedSession() async throws {
160 try await savedIdentity()
161 let sheets = SheetsOficinaSession(model: model("sheets", "Sheets"))
162 await sheets.start()
163 let before = try XCTUnwrap(sheets.mounted)
164 let account = SheetsOficinaSession.accountID(before)
165 service.expire(session: before.session)
166 await sheets.rejected(account)
167 let after = try XCTUnwrap(sheets.mounted)
168 XCTAssertNotEqual(after.session, before.session)
169 XCTAssertTrue(service.isLive(session: after.session))
170 // At most once a minute per account: a refusing instance cannot loop.
171 let asserts = service.calls.filter { $0.hasPrefix("assert") }.count
172 await sheets.rejected(account)
173 XCTAssertEqual(service.calls.filter { $0.hasPrefix("assert") }.count, asserts)
174 }
175
176 /// After sign-out the transport has no session to send: unauthorized,
177 /// never the old cookie.
178 func testAfterSignOutTheTransportRefusesToSend() async throws {
179 try await savedIdentity()
180 let sheets = SheetsOficinaSession(model: model("sheets", "Sheets"))
181 await sheets.start()
182 let state = try XCTUnwrap(sheets.mounted)
183 let transport = sheets.transport(for: SheetsOficinaSession.accountID(state), origin: state.origin)
184 sheets.model.signOut()
185 XCTAssertNil(sheets.mounted)
186 XCTAssertEqual(sheets.model.step, .welcome)
187 do {
188 _ = try await transport.responseDetails("/sheets", method: "GET", body: nil, contentType: "application/json", maxBytes: 1024)
189 XCTFail("sent after sign-out")
190 } catch NativeClientError.unauthorized {}
191 }
192
193 /// A non-GET request with an ended session gets 403 "Sign in first."
194 /// from Sheets' guards: that is the session, not the request, so it
195 /// re-mints and reads as unauthorized. Any other 403 stays a refusal.
196 func testASignInFirst403IsAnEndedSession() async throws {
197 final class Counts: @unchecked Sendable { var rejected = 0; var refused = 0 }
198 let counts = Counts()
199 let server = ScriptedTransport(origin: Self.sheetsOrigin, [
200 .respond(status: 403, body: Data("Sign in first.\n".utf8)),
201 .respond(status: 403, body: Data(#"{"error":"not yours"}"#.utf8)),
202 ])
203 let transport = SheetsOficinaTransport(origin: Self.sheetsOrigin, current: { server },
204 rejected: { counts.rejected += 1 }, refused: { counts.refused += 1 })
205 let ended = try await transport.responseDetails("/sheets/1/cells", method: "POST", body: Data("{}".utf8),
206 contentType: "application/json", maxBytes: 1024)
207 XCTAssertEqual(ended.status, 401)
208 XCTAssertEqual(counts.rejected, 1)
209 XCTAssertEqual(counts.refused, 0)
210 let refusal = try await transport.responseDetails("/sheets/1/cells", method: "POST", body: Data("{}".utf8),
211 contentType: "application/json", maxBytes: 1024)
212 XCTAssertEqual(refusal.status, 403)
213 XCTAssertEqual(counts.rejected, 1)
214 XCTAssertEqual(counts.refused, 1)
215 }
216
217 // MARK: "Use another Oficina ID" in the account menu
218
219 func testUseAnotherFromTheMenuAsksThenReplaces() async throws {
220 try await savedIdentity()
221 let sheets = SheetsOficinaSession(model: model("sheets", "Sheets"))
222 await sheets.start()
223 let state = try XCTUnwrap(sheets.mounted)
224 sheets.model.useAnother()
225 XCTAssertTrue(sheets.model.confirmingReplace)
226 sheets.model.cancelReplace()
227 XCTAssertEqual(sheets.mounted, state, "cancelling changes nothing")
228 sheets.model.useAnother()
229 sheets.model.confirmReplace()
230 XCTAssertNil(sheets.mounted)
231 XCTAssertEqual(sheets.model.step, .email)
232 XCTAssertEqual(try sheets.model.store.identities(), [])
233 }
234
235 // MARK: Accounts and teams
236
237 func testAccountIDsArePerIdentityAndTeam() {
238 let id = SheetsOficinaSession.accountID(identity: "id-1", team: "t1")
239 XCTAssertEqual(id, "oficina-id.id-1.t1")
240 XCTAssertTrue(SheetsOficinaSession.account(id, belongsTo: "id-1"))
241 XCTAssertFalse(SheetsOficinaSession.account(id, belongsTo: "id-10"))
242 let odd = SheetsOficinaSession.accountID(identity: "a.b", team: "t/1")
243 XCTAssertFalse(odd.dropFirst(SheetsOficinaSession.prefix.count).contains("/"))
244 XCTAssertTrue(SheetsOficinaSession.account(odd, belongsTo: "a.b"))
245 XCTAssertFalse(SheetsOficinaSession.account(odd, belongsTo: "a"))
246 }
247
248 func testThePickerListsOnlyTeamsWithSheets() {
249 let current = OficinaTeam(sqid: "t1", label: "paulca", name: "Paul", role: "member",
250 apps: [OficinaTeamApp(app: "sheets", origin: Self.sheetsOrigin.absoluteString, consumerID: "c")])
251 let docsOnly = OficinaTeam(sqid: "t2", label: "docs", name: "Another", role: "member",
252 apps: [OficinaTeamApp(app: "docs", origin: Self.docsOrigin.absoluteString, consumerID: "d")])
253 XCTAssertEqual(SheetsTeamPicker.teams([docsOnly], current: current).map(\.sqid), ["t1"])
254 }
255
256 func testTheRouteKeepsServerAccountsUntilOficinaIDIsChosen() {
257 XCTAssertEqual(SheetsSignInRoute.resolve(stored: "", hasServerAccounts: false), .oficinaID)
258 XCTAssertEqual(SheetsSignInRoute.resolve(stored: "", hasServerAccounts: true), .server)
259 XCTAssertEqual(SheetsSignInRoute.resolve(stored: "oficina-id", hasServerAccounts: true), .oficinaID)
260 XCTAssertEqual(SheetsSignInRoute.resolve(stored: "server", hasServerAccounts: false), .server)
261 }
262
263 // MARK: Launch with a saved account (the Docs 0.1.7/0.1.8 lesson, docs 84d1008)
264
265 /// What the signed-in window's body builds, built under observation as a
266 /// body is: the transport and the workspace. Neither may change anything
267 /// a view watches, or each body pass would invalidate the next.
268 func testBuildingTheSignedInWorkspaceChangesNothingAViewWatches() async throws {
269 try await savedIdentity()
270 let sheets = SheetsOficinaSession(model: model("sheets", "Sheets"))
271 await sheets.start()
272 let state = try XCTUnwrap(sheets.mounted)
273 let account = SheetsOficinaSession.accountID(state)
274 let connectivity = NativeConnectivity.shared
275 var published = 0
276 let watches = [sheets.objectWillChange.sink { published += 1 }, sheets.model.objectWillChange.sink { published += 1 }]
277 let changed = Mutex(false)
278 withObservationTracking {
279 _ = connectivity.path
280 _ = connectivity.serverReachable
281 let transport = sheets.transport(for: account, origin: state.origin)
282 _ = SheetsWorkspace(client: transport, signOut: {}, useAnother: {}, accountsLabel: "Teams", signOutLabel: "Sign out")
283 _ = sheets.mounted
284 _ = sheets.model.step
285 } onChange: { changed.withLock { $0 = true } }
286 for _ in 0..<3 {
287 _ = SheetsWorkspace(client: sheets.transport(for: account, origin: state.origin), signOut: {})
288 }
289 watches.forEach { $0.cancel() }
290 XCTAssertFalse(changed.withLock { $0 }, "building the signed-in workspace must not invalidate its window")
291 XCTAssertEqual(published, 0, "nor publish from the session or the model")
292 }
293}
294