gitbayTests/AccountTests.swift

v1.1.0
gitbay-ios/gitbayTests/AccountTests.swift history · blame · raw

200 lines · 8988 bytes

  1import Foundation
  2import Testing
  3@testable import gitbay
  4
  5private func makeClient() throws -> (GitbayClient, StubProtocol.Box) {
  6    let box = StubProtocol.box()
  7    let client = GitbayClient(
  8        instance: try GitbayInstance(url: "https://gitbay.org"),
  9        token: "test-token",
 10        session: box.session()
 11    )
 12    return (client, box)
 13}
 14
 15private func argvOf(_ seen: StubProtocol.Seen) throws -> ([String], String?) {
 16    let body = try #require(try JSONSerialization.jsonObject(with: seen.body) as? [String: Any])
 17    return (try #require(body["argv"] as? [String]), body["stdin"] as? String)
 18}
 19
 20private let keysJSON = """
 21    {"protocol_version":1,"data":[\
 22    {"fingerprint":"SHA256:15jrWGl3s3BB1CeG0z9TfGnyf35l8lcBWoYfA0+IJbY","algo":"ssh-ed25519","scope":"full"}\
 23    ],"exit_code":0}
 24    """
 25private let pgpJSON = """
 26    {"protocol_version":1,"data":[\
 27    {"fingerprint":"3917973fb159bbb86194538569451a517ac0cb37",\
 28    "emails":"[\\"hello@cleberg.net\\"]"}],"exit_code":0}
 29    """
 30private let okJSON = #"{"protocol_version":1,"data":{},"exit_code":0}"#
 31private let orgListJSON = """
 32    {"protocol_version":1,"data":[{"org":"krz","role":"admin"}],"exit_code":0}
 33    """
 34
 35@MainActor
 36struct AccountViewModelTests {
 37
 38    private func loadedModel() async throws -> (AccountViewModel, StubProtocol.Box) {
 39        let (client, stub) = try makeClient()
 40        stub.enqueue(.init(status: 200, json: keysJSON, match: "argv=keys"))
 41        stub.enqueue(.init(status: 200, json: pgpJSON, match: "argv=pgp"))
 42        stub.enqueue(.init(status: 200, json: orgListJSON, match: "argv=org"))
 43        let model = AccountViewModel(client: client)
 44        await model.load()
 45        return (model, stub)
 46    }
 47
 48    /// v1.16.0: `notifications settings show` says whether activity mail
 49    /// is on; `notifications settings mail on|off` flips it. The read is
 50    /// separate from the keys, and an older server leaves it unknown.
 51    @Test func mailPreferenceLoadsAndFlips() async throws {
 52        let (model, stub) = try await loadedModel()
 53        stub.enqueue(.init(status: 200, json: #"{"protocol_version":1,"data":{"mail":true},"exit_code":0}"#, match: "argv=settings&argv=show"))
 54
 55        await model.loadMailPreference()
 56
 57        #expect(model.mailOn == true)
 58        stub.enqueue(.init(status: 200, json: okJSON, match: "cmd"))
 59        stub.enqueue(.init(status: 200, json: #"{"protocol_version":1,"data":{"mail":false},"exit_code":0}"#, match: "argv=settings&argv=show"))
 60
 61        await model.setMail(false)
 62
 63        let write = try #require(stub.seen.first { $0.method == "POST" })
 64        let (argv, _) = try argvOf(write)
 65        #expect(argv == ["notifications", "settings", "mail", "off"])
 66        #expect(model.mailOn == false)
 67    }
 68
 69    @Test func anOlderServerLeavesTheMailPreferenceUnknown() async throws {
 70        let (model, stub) = try await loadedModel()
 71        stub.enqueue(.init(status: 400, json: #"{"protocol_version":1,"error":"no command matches","exit_code":2}"#, match: "argv=settings&argv=show"))
 72
 73        await model.loadMailPreference()
 74
 75        #expect(model.mailOn == nil)
 76        #expect(model.actionError == nil)
 77    }
 78
 79    /// v1.16.0's `email list`, `email remove` and `email primary`. The
 80    /// list is its own read, and an older server leaves it nil.
 81    @Test func emailsLoadWithVerifiedAndPrimaryFlags() async throws {
 82        let (model, stub) = try await loadedModel()
 83        stub.enqueue(.init(status: 200, json: """
 84            {"protocol_version":1,"data":[\
 85            {"address":"hello@cleberg.net","verified":true,"verified_by":"code","primary":true},\
 86            {"address":"c@example.test","verified":false,"primary":false}],"exit_code":0}
 87            """, match: "argv=email&argv=list"))
 88
 89        await model.loadEmails()
 90
 91        let emails = try #require(model.emails)
 92        #expect(emails.map(\.address) == ["hello@cleberg.net", "c@example.test"])
 93        #expect(emails[0].verified && emails[0].primary)
 94        #expect(!emails[1].verified && !emails[1].primary)
 95    }
 96
 97    @Test func anOlderServerLeavesTheEmailListUnknown() async throws {
 98        let (model, stub) = try await loadedModel()
 99        stub.enqueue(.init(status: 400, json: #"{"protocol_version":1,"error":"no command matches","exit_code":2}"#, match: "argv=email&argv=list"))
100
101        await model.loadEmails()
102
103        #expect(model.emails == nil)
104        #expect(model.actionError == nil)
105    }
106
107    @Test func removeAndPrimarySendTheirCommandsThenReloadEmails() async throws {
108        let (model, stub) = try await loadedModel()
109        let listJSON = #"{"protocol_version":1,"data":[{"address":"hello@cleberg.net","verified":true,"primary":true}],"exit_code":0}"#
110        for _ in 0..<2 {
111            stub.enqueue(.init(status: 200, json: okJSON, match: "cmd"))
112            stub.enqueue(.init(status: 200, json: listJSON, match: "argv=email&argv=list"))
113        }
114
115        await model.removeEmail("c@example.test")
116        await model.setPrimaryEmail("hello@cleberg.net")
117
118        let writes = try stub.seen.filter { $0.method == "POST" }.map { try argvOf($0).0 }
119        #expect(writes == [
120            ["email", "remove", "c@example.test"],
121            ["email", "primary", "hello@cleberg.net"],
122        ])
123        #expect(stub.seen.filter { $0.url.query()?.contains("argv=email&argv=list") == true }.count == 2)
124    }
125
126    @Test func loadsBothKeyListsAndDecodesNestedEmails() async throws {
127        let (model, _) = try await loadedModel()
128
129        let loaded = try #require(model.state.value)
130        #expect(loaded.sshKeys.first?.algo == "ssh-ed25519")
131        // The UID list is JSON-encoded inside the JSON field.
132        #expect(loaded.pgpKeys.first?.emailList == ["hello@cleberg.net"])
133    }
134
135    @Test func sshKeyTravelsAsRawStdinWithScope() async throws {
136        let (model, stub) = try await loadedModel()
137        stub.enqueue(.init(status: 200, json: okJSON, match: "cmd"))
138        stub.enqueue(.init(status: 200, json: keysJSON, match: "argv=keys"))
139        stub.enqueue(.init(status: 200, json: pgpJSON, match: "argv=pgp"))
140        stub.enqueue(.init(status: 200, json: orgListJSON, match: "argv=org"))
141
142        await model.addSSHKey("ssh-ed25519 AAAAC3Nza phone\n", scope: "git")
143
144        let (argv, stdin) = try argvOf(try #require(stub.seen.first { $0.method == "POST" }))
145        // No --file - here: keys add reads bare stdin.
146        #expect(argv == ["keys", "add", "--scope", "git"])
147        #expect(stdin == "ssh-ed25519 AAAAC3Nza phone")
148    }
149
150    @Test func removalsTargetTheFingerprint() async throws {
151        let (model, stub) = try await loadedModel()
152        for _ in 0..<2 {
153            stub.enqueue(.init(status: 200, json: okJSON, match: "cmd"))
154            stub.enqueue(.init(status: 200, json: keysJSON, match: "argv=keys"))
155            stub.enqueue(.init(status: 200, json: pgpJSON, match: "argv=pgp"))
156            stub.enqueue(.init(status: 200, json: orgListJSON, match: "argv=org"))
157        }
158        let loaded = try #require(model.state.value)
159
160        await model.removeSSHKey(loaded.sshKeys[0])
161        await model.removePGPKey(loaded.pgpKeys[0])
162
163        let writes = try stub.seen.filter { $0.method == "POST" }.map { try argvOf($0).0 }
164        #expect(writes[0] == ["keys", "remove", "SHA256:15jrWGl3s3BB1CeG0z9TfGnyf35l8lcBWoYfA0+IJbY"])
165        #expect(writes[1] == ["pgp", "remove", "3917973fb159bbb86194538569451a517ac0cb37"])
166    }
167
168    @Test func emailAddAndVerifySendTheirCommands() async throws {
169        let (model, stub) = try await loadedModel()
170        for _ in 0..<2 {
171            stub.enqueue(.init(status: 200, json: okJSON, match: "cmd"))
172            stub.enqueue(.init(status: 200, json: keysJSON, match: "argv=keys"))
173            stub.enqueue(.init(status: 200, json: pgpJSON, match: "argv=pgp"))
174            stub.enqueue(.init(status: 200, json: orgListJSON, match: "argv=org"))
175        }
176
177        await model.addEmail(" claude@cleberg.net ")
178        #expect(model.notice?.contains("on its way") == true)
179        await model.verifyEmail(code: "123456")
180        #expect(model.notice == "Email verified.")
181
182        let writes = try stub.seen.filter { $0.method == "POST" }.map { try argvOf($0).0 }
183        #expect(writes[0] == ["email", "add", "claude@cleberg.net"])
184        #expect(writes[1] == ["email", "verify", "123456"])
185    }
186
187    @Test func contentValidationUsageErrorsSurfaceVerbatimHere() async throws {
188        let (model, stub) = try await loadedModel()
189        stub.enqueue(.init(status: 400, json:
190            #"{"protocol_version":1,"error":"not a valid public key in authorized_keys format: illegal base64","exit_code":2}"#,
191            match: "cmd"))
192
193        await model.addSSHKey("garbage", scope: "full")
194
195        // Exit 2 stays generic app-wide; on this screen it validates
196        // pasted content and the message is for the person.
197        #expect(model.actionError ==
198            "not a valid public key in authorized_keys format: illegal base64")
199    }
200}