gitbayTests/DashboardViewModelTests.swift
80 lines · 2950 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 let dashboardJSON = """
16 {"protocol_version":1,"data":{\
17 "pinned":[{"path":"krz/gitbay","visibility":"public","description":"a CLI-first git forge"}],\
18 "open_mrs":[{"repo":"krz/gitbay-ios","number":3,"title":"adopt aggregate","author":"cmc",\
19 "state":"open","updated_at":"2026-08-27T10:00:00.000Z"}],\
20 "assigned_issues":[{"repo":"krz/gitbay","number":11,"title":"iOS app","author":"krz",\
21 "state":"open","updated_at":"2026-08-26T10:00:00.000Z"}],\
22 "builds":[{"repo":"krz/gitbay","number":9,"job":"ci","status":"success",\
23 "sha":"65ba14e0000000000000","ref":"refs/heads/main",\
24 "created_at":"2026-08-27T09:00:00.000Z","finished_at":"2026-08-27T09:05:00.000Z"}]},\
25 "exit_code":0}
26 """
27
28private let emptyDashboardJSON = """
29 {"protocol_version":1,"data":{"pinned":[],"open_mrs":[],"assigned_issues":[],"builds":[]},\
30 "exit_code":0}
31 """
32
33@MainActor
34struct DashboardViewModelTests {
35
36 @Test func oneReadFillsEverySection() async throws {
37 let (client, stub) = try makeClient()
38 stub.enqueue(.init(status: 200, json: dashboardJSON))
39 let model = DashboardViewModel(client: client)
40
41 await model.load()
42
43 let data = try #require(model.state.value)
44 #expect(data.pinned.map(\.path) == ["krz/gitbay"])
45 #expect(data.openMRs.map(\.id) == ["krz/gitbay-ios#3"])
46 #expect(data.assignedIssues.first?.number == 11)
47 #expect(data.builds.first?.status == "success")
48 // The whole screen cost exactly one request.
49 #expect(stub.seen.count == 1)
50 #expect(stub.seen.first?.url.query() == "argv=dashboard")
51 }
52
53 @Test func emptyAggregateStillLoads() async throws {
54 let (client, stub) = try makeClient()
55 stub.enqueue(.init(status: 200, json: emptyDashboardJSON))
56 let model = DashboardViewModel(client: client)
57
58 await model.load()
59
60 let data = try #require(model.state.value)
61 #expect(data.pinned.isEmpty)
62 #expect(data.openMRs.isEmpty)
63 }
64
65 @Test func aFailureIsTheScreensState() async throws {
66 let (client, stub) = try makeClient()
67 stub.enqueue(.init(status: 500, json:
68 #"{"protocol_version":1,"error":"boom","exit_code":1}"#))
69 stub.enqueue(.init(status: 500, json:
70 #"{"protocol_version":1,"error":"boom","exit_code":1}"#))
71 let model = DashboardViewModel(client: client)
72
73 await model.load()
74
75 guard case .failed = model.state else {
76 Issue.record("expected .failed, got \(model.state)")
77 return
78 }
79 }
80}