gitbayTests/KeyExpiryTests.swift
56 lines · 2156 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 posted(_ stub: StubProtocol.Box) throws -> [[String]] {
16 try stub.seen.filter { $0.method == "POST" }.map { seen in
17 let body = try #require(try JSONSerialization.jsonObject(with: seen.body) as? [String: Any])
18 return try #require(body["argv"] as? [String])
19 }
20}
21
22struct KeyExpiryTests {
23
24 @Test func keysCarryLastUseExpiryAndWhoCreatedThem() throws {
25 let json = """
26 [{"fingerprint":"SHA256:a","algo":"ssh-ed25519","scope":"full","label":"laptop",\
27 "last_used_at":"2026-10-14T07:32:16.789Z"},\
28 {"fingerprint":"SHA256:b","algo":"ssh-ed25519","scope":"git","label":"ci",\
29 "created_by":"phone","expires_at":"2026-01-01T00:00:00Z"},\
30 {"fingerprint":"SHA256:c","algo":"ssh-ed25519","scope":"full","label":""}]
31 """
32 let keys = try GitbayClient.decoder().decode([AccountViewModel.SSHKey].self, from: Data(json.utf8))
33 let now = try Date("2026-10-15T00:00:00Z", strategy: .iso8601)
34
35 #expect(keys[0].lastUsedAt != nil)
36 #expect(keys[0].expiresAt == nil)
37 #expect(!keys[0].isExpired(at: now))
38 #expect(keys[1].createdBy == "phone")
39 #expect(keys[1].isExpired(at: now))
40 #expect(keys[2].lastUsedAt == nil)
41 }
42}
43
44@MainActor
45struct KeyTTLTests {
46
47 @Test func anExpiringKeyIsAddedWithItsTTL() async throws {
48 let (client, stub) = try makeClient()
49 stub.enqueue(.init(status: 200, json: #"{"protocol_version":1,"data":{},"exit_code":0}"#, match: "cmd"))
50 let model = AccountViewModel(client: client)
51
52 await model.addSSHKey("ssh-ed25519 AAAA phone", scope: "full", label: "phone", ttl: "90d")
53
54 #expect(try posted(stub) == [["keys", "add", "--scope", "full", "--label", "phone", "--ttl", "90d"]])
55 }
56}