gitbayTests/MRViewModelTests.swift
390 lines · 16224 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 mrListJSON = """
16 {"protocol_version":1,"data":{"items":[\
17 {"number":7,"title":"client: envelope decoding","state":"open","author":"cmc",\
18 "source":"client-envelope","target_ref":"main","head_sha":"aabbcc",\
19 "created_at":"2026-08-20T10:00:00.000Z"},\
20 {"number":9,"title":"auth: keychain","state":"open","author":"cmc",\
21 "source":"krz/fork:auth","target_ref":"main","head_sha":"ddeeff",\
22 "created_at":"2026-08-21T10:00:00.000Z"}\
23 ]},"exit_code":0}
24 """
25
26private let mrShowJSON = """
27 {"protocol_version":1,"data":{"number":7,"title":"client: envelope decoding",\
28 "state":"open","author":"cmc","source":"client-envelope","target_ref":"main",\
29 "head_sha":"aabbcc","body":"Speaks both surfaces.","created_at":"2026-08-20T10:00:00.000Z",\
30 "checks":[{"context":"ci/build","state":"success","updated_at":"2026-08-20T10:05:00.000Z",\
31 "duration":"1m12s"},{"context":"external/lint","state":"success",\
32 "updated_at":"2026-08-20T10:06:00.000Z"}],"checks_combined":"success",\
33 "unresolved_threads":1,\
34 "commits":[{"sha":"aabbcc00000000000000","subject":"client: envelope"}],\
35 "comments":[{"author":"krz","body":"looks right","created_at":"2026-08-20T11:00:00.000Z"}],\
36 "reviews":[{"reviewer":"krz","verdict":"approve","stale":false,\
37 "created_at":"2026-08-20T10:30:00.000Z"}]},"exit_code":0}
38 """
39
40private let mrMergedJSON = """
41 {"protocol_version":1,"data":{"number":7,"title":"client: envelope decoding",\
42 "state":"merged","author":"cmc","source":"client-envelope","target_ref":"main",\
43 "head_sha":"aabbcc","created_at":"2026-08-20T10:00:00.000Z",\
44 "merged_at":"2026-08-21T09:15:00.000Z","merged_by":"cmc"},"exit_code":0}
45 """
46
47private let threadsJSON = """
48 {"protocol_version":1,"data":[\
49 {"id":3,"path":"gitbay/Client.swift","side":"new","line":42,"stale":false,\
50 "comments":[{"id":3,"author":"krz","body":"why retry twice?","created_at":"2026-08-20T10:30:00.000Z"}]},\
51 {"id":5,"path":"gitbay/Client.swift","side":"new","line":90,"stale":true,"resolved_by":"cmc",\
52 "comments":[{"id":5,"author":"krz","body":"naming","created_at":"2026-08-20T10:31:00.000Z"},\
53 {"id":6,"author":"cmc","body":"renamed","created_at":"2026-08-20T10:35:00.000Z"}]}\
54 ],"exit_code":0}
55 """
56
57private let diffText = """
58 diff --git a/main.go b/main.go
59 index 1234567..89abcde 100644
60 --- a/main.go
61 +++ b/main.go
62 @@ -1,4 +1,5 @@
63 package main
64 -import "fmt"
65 +import (
66 +\t"fmt"
67 +)
68
69 -func main() {}
70 @@ -10,2 +11,3 @@ func helper() {
71 \tx := 1
72 +\ty := 2
73 \t_ = x
74 diff --git a/new.txt b/new.txt
75 new file mode 100644
76 --- /dev/null
77 +++ b/new.txt
78 @@ -0,0 +1,2 @@
79 +hello
80 +world
81 """
82
83private func diffEnvelope() -> String {
84 let escaped = diffText
85 .replacingOccurrences(of: "\\", with: "\\\\")
86 .replacingOccurrences(of: "\"", with: "\\\"")
87 .replacingOccurrences(of: "\n", with: "\\n")
88 .replacingOccurrences(of: "\t", with: "\\t")
89 return "{\"protocol_version\":1,\"output\":\"\(escaped)\",\"exit_code\":0}"
90}
91
92struct UnifiedDiffParserTests {
93
94 @Test func parsesFilesHunksAndLineNumbers() {
95 let diff = UnifiedDiff.parse(diffText)
96
97 #expect(diff.files.count == 2)
98 let first = diff.files[0]
99 #expect(first.displayPath == "main.go")
100 #expect(first.hunks.count == 2)
101 #expect(first.additions == 4)
102 #expect(first.deletions == 2)
103
104 // Line numbering advances per side.
105 let lines = first.hunks[0].lines
106 #expect(lines[0].kind == .context)
107 #expect(lines[0].oldNumber == 1)
108 #expect(lines[0].newNumber == 1)
109 #expect(lines[1].kind == .deletion)
110 #expect(lines[1].oldNumber == 2)
111 #expect(lines[1].newNumber == nil)
112 #expect(lines[2].kind == .addition)
113 #expect(lines[2].oldNumber == nil)
114 #expect(lines[2].newNumber == 2)
115
116 // Second hunk restarts numbering from its header.
117 #expect(first.hunks[1].lines[0].oldNumber == 10)
118 #expect(first.hunks[1].lines[0].newNumber == 11)
119 }
120
121 @Test func newFilesAreMarked() {
122 let diff = UnifiedDiff.parse(diffText)
123 let added = diff.files[1]
124 #expect(added.isNew)
125 #expect(!added.isDeleted)
126 #expect(added.displayPath == "new.txt")
127 #expect(added.additions == 2)
128 }
129
130 @Test func totalsSumAcrossFiles() {
131 let diff = UnifiedDiff.parse(diffText)
132 #expect(diff.additions == 6)
133 #expect(diff.deletions == 2)
134 }
135
136 @Test func binaryFilesAreRecognised() {
137 let diff = UnifiedDiff.parse("""
138 diff --git a/logo.png b/logo.png
139 Binary files a/logo.png and b/logo.png differ
140 """)
141 #expect(diff.files.count == 1)
142 #expect(diff.files[0].isBinary)
143 }
144
145 @Test func emptyDiffParsesToNoFiles() {
146 #expect(UnifiedDiff.parse("").files.isEmpty)
147 }
148}
149
150@MainActor
151struct MRListViewModelTests {
152
153 @Test func listsInServerOrderWithPagingFlags() async throws {
154 let (client, stub) = try makeClient()
155 stub.enqueue(.init(status: 200, json: mrListJSON))
156 let model = MRListViewModel(client: client, repoPath: "krz/gitbay")
157
158 await model.load()
159
160 let mrs = try #require(model.state.value)
161 #expect(mrs.map(\.number) == [7, 9])
162 let seen = try #require(stub.seen.first)
163 #expect(seen.url.query() ==
164 "argv=mr&argv=list&argv=krz/gitbay&argv=--state&argv=open&argv=--limit&argv=50")
165 }
166
167 @Test func changingTheFilterReloadsWithThatState() async throws {
168 let (client, stub) = try makeClient()
169 stub.enqueue(.init(status: 200, json: mrListJSON))
170 stub.enqueue(.init(status: 200, json: #"{"protocol_version":1,"data":{"items":[]},"exit_code":0}"#))
171 let model = MRListViewModel(client: client, repoPath: "krz/gitbay")
172 await model.load()
173
174 model.filter = .merged
175 // The reload happens in a spawned task; give it a beat.
176 try await Task.sleep(for: .milliseconds(300))
177
178 #expect(stub.seen.count == 2)
179 #expect(stub.seen[1].url.query()?.contains("argv=merged") == true)
180 guard case .empty = model.state else {
181 Issue.record("expected .empty after filtering, got \(model.state)")
182 return
183 }
184 }
185}
186
187@MainActor
188struct MRDetailViewModelTests {
189
190 private func loadedModel() async throws -> (MRDetailViewModel, StubProtocol.Box) {
191 let (client, stub) = try makeClient()
192 stub.enqueue(.init(status: 200, json: mrShowJSON, match: "argv=show"))
193 stub.enqueue(.init(status: 200, json: diffEnvelope(), match: "argv=diff"))
194 stub.enqueue(.init(status: 200, json: threadsJSON, match: "argv=threads"))
195 let model = MRDetailViewModel(client: client, repoPath: "krz/gitbay", number: 7)
196 await model.load()
197 return (model, stub)
198 }
199
200 @Test func loadsHeaderDiffAndThreads() async throws {
201 let (model, _) = try await loadedModel()
202
203 let mr = try #require(model.state.value)
204 #expect(mr.title == "client: envelope decoding")
205 #expect(mr.checksCombined == "success")
206 #expect(mr.reviews?.first?.verdict == "approve")
207 #expect(mr.reviews?.first?.createdAt != nil)
208 #expect(model.diff?.files.count == 2)
209 #expect(model.threads.count == 2)
210 #expect(model.unresolvedCount == 1)
211 }
212
213 /// A CI check reports how long its build ran; anything else reports
214 /// only when it last changed. Neither may borrow the other's timing.
215 @Test func checksCarryTheirTiming() async throws {
216 let (model, _) = try await loadedModel()
217
218 let checks = try #require(model.state.value?.checks)
219 let ci = try #require(checks.first { $0.context == "ci/build" })
220 #expect(ci.duration == "1m12s")
221 #expect(ci.updatedAt != nil)
222 let external = try #require(checks.first { $0.context == "external/lint" })
223 #expect(external.duration == nil)
224 #expect(external.updatedAt != nil)
225 }
226
227 /// A merged MR says who merged it and when. An open one has no stamp
228 /// to show, and must not invent one.
229 @Test func resolutionStampsDecode() async throws {
230 let (client, stub) = try makeClient()
231 stub.enqueue(.init(status: 200, json: mrShowJSON, match: "argv=show"))
232 stub.enqueue(.init(status: 200, json: diffEnvelope(), match: "argv=diff"))
233 stub.enqueue(.init(status: 200, json: threadsJSON, match: "argv=threads"))
234 let open = MRDetailViewModel(client: client, repoPath: "krz/gitbay", number: 7)
235 await open.load()
236 #expect(open.state.value?.mergedAt == nil)
237 #expect(open.state.value?.closedAt == nil)
238
239 let (mergedClient, mergedStub) = try makeClient()
240 mergedStub.enqueue(.init(status: 200, json: mrMergedJSON, match: "argv=show"))
241 mergedStub.enqueue(.init(status: 200, json: diffEnvelope(), match: "argv=diff"))
242 mergedStub.enqueue(.init(status: 200, json: threadsJSON, match: "argv=threads"))
243 let merged = MRDetailViewModel(client: mergedClient, repoPath: "krz/gitbay", number: 7)
244 await merged.load()
245 #expect(merged.state.value?.mergedBy == "cmc")
246 #expect(merged.state.value?.mergedAt != nil)
247 }
248
249 @Test func approveSendsTheWriteThenReloads() async throws {
250 let (model, stub) = try await loadedModel()
251 stub.enqueue(.init(status: 200, json: #"{"protocol_version":1,"data":{},"exit_code":0}"#))
252 stub.enqueue(.init(status: 200, json: mrShowJSON, match: "argv=show"))
253 stub.enqueue(.init(status: 200, json: diffEnvelope(), match: "argv=diff"))
254 stub.enqueue(.init(status: 200, json: threadsJSON, match: "argv=threads"))
255
256 await model.review(.approve)
257
258 let write = stub.seen[3]
259 #expect(write.method == "POST")
260 #expect(write.url.path() == "/api/v1/cmd")
261 let body = try #require(try JSONSerialization.jsonObject(with: write.body) as? [String: Any])
262 #expect(body["argv"] as? [String] ==
263 ["mr", "review", "krz/gitbay", "7", "--approve"])
264 #expect(model.actionError == nil)
265 }
266
267 @Test func commentGoesThroughStdinNotArgv() async throws {
268 let (model, stub) = try await loadedModel()
269 stub.enqueue(.init(status: 200, json: #"{"protocol_version":1,"data":{},"exit_code":0}"#))
270 stub.enqueue(.init(status: 200, json: mrShowJSON, match: "argv=show"))
271 stub.enqueue(.init(status: 200, json: diffEnvelope(), match: "argv=diff"))
272 stub.enqueue(.init(status: 200, json: threadsJSON, match: "argv=threads"))
273
274 await model.comment("long review text\nwith lines")
275
276 let write = stub.seen[3]
277 let body = try #require(try JSONSerialization.jsonObject(with: write.body) as? [String: Any])
278 #expect(body["argv"] as? [String] == ["mr", "comment", "krz/gitbay", "7", "--file", "-"])
279 #expect(body["stdin"] as? String == "long review text\nwith lines")
280 }
281
282 @Test func aMergeRefusalSurfacesTheServersRuleVerbatim() async throws {
283 let (model, stub) = try await loadedModel()
284 stub.enqueue(.init(status: 403, json:
285 #"{"protocol_version":1,"error":"merge blocked: 1 review thread unresolved","exit_code":4}"#))
286
287 await model.merge()
288
289 #expect(model.actionError == "merge blocked: 1 review thread unresolved")
290 // The refusal did not wipe the loaded screen.
291 #expect(model.state.value != nil)
292 #expect(stub.seen.count == 4)
293 }
294
295 @Test func resolveTargetsTheThreadID() async throws {
296 let (model, stub) = try await loadedModel()
297 stub.enqueue(.init(status: 200, json: #"{"protocol_version":1,"data":{},"exit_code":0}"#))
298 stub.enqueue(.init(status: 200, json: mrShowJSON, match: "argv=show"))
299 stub.enqueue(.init(status: 200, json: diffEnvelope(), match: "argv=diff"))
300 stub.enqueue(.init(status: 200, json: threadsJSON, match: "argv=threads"))
301 let thread = try #require(model.threads.first { !$0.isResolved })
302
303 await model.setResolved(thread, true)
304
305 let write = stub.seen[3]
306 let body = try #require(try JSONSerialization.jsonObject(with: write.body) as? [String: Any])
307 #expect(body["argv"] as? [String] == ["mr", "resolve", "krz/gitbay", "7", "3"])
308 }
309
310 @Test func replyUsesDiffCommentWithReplyFlag() async throws {
311 let (model, stub) = try await loadedModel()
312 stub.enqueue(.init(status: 200, json: #"{"protocol_version":1,"data":{"id":9,"thread":3},"exit_code":0}"#))
313 stub.enqueue(.init(status: 200, json: mrShowJSON, match: "argv=show"))
314 stub.enqueue(.init(status: 200, json: diffEnvelope(), match: "argv=diff"))
315 stub.enqueue(.init(status: 200, json: threadsJSON, match: "argv=threads"))
316 let thread = try #require(model.threads.first { !$0.isResolved })
317
318 await model.reply(to: thread, "because 5xx is transient")
319
320 let write = stub.seen[3]
321 let body = try #require(try JSONSerialization.jsonObject(with: write.body) as? [String: Any])
322 #expect(body["argv"] as? [String] ==
323 ["mr", "diff-comment", "krz/gitbay", "7", "--reply", "3", "--file", "-"])
324 #expect(body["stdin"] as? String == "because 5xx is transient")
325 }
326}
327
328/// Where a review thread hangs in the diff. Threads the diff has moved
329/// past must not vanish — they render in their own section.
330struct ThreadAnchoringTests {
331
332 private func thread(
333 path: String, line: Int64, side: String = "new", stale: Bool = false
334 ) throws -> ReviewThread {
335 let json = """
336 {"id":1,"path":"\(path)","side":"\(side)","line":\(line),"stale":\(stale),\
337 "comments":[{"id":1,"author":"krz","body":"why?",\
338 "created_at":"2026-08-20T10:30:00.000Z"}]}
339 """
340 let decoder = JSONDecoder()
341 decoder.dateDecodingStrategy = .iso8601
342 return try decoder.decode(ReviewThread.self, from: Data(json.utf8))
343 }
344
345 private let diff = UnifiedDiff.parse("""
346 diff --git a/main.go b/main.go
347 --- a/main.go
348 +++ b/main.go
349 @@ -1,4 +1,5 @@
350 package main
351 -import "fmt"
352 +import (
353 +\t"fmt"
354 +)
355 """)
356
357 @Test func aThreadAnchorsToItsLineOnTheNewSide() throws {
358 // "+import (" is new line 2.
359 let subject = try thread(path: "main.go", line: 2)
360 #expect(diff.anchors(subject))
361
362 let file = try #require(diff.files.first)
363 let line = try #require(file.hunks.first?.lines.first { $0.newNumber == 2 })
364 #expect(line.anchors(subject, in: file))
365 }
366
367 @Test func anOldSideThreadAnchorsToTheDeletedLine() throws {
368 // `-import "fmt"` is old line 2 and has no new number.
369 let subject = try thread(path: "main.go", line: 2, side: "old")
370 #expect(diff.anchors(subject))
371
372 let file = try #require(diff.files.first)
373 let deletion = try #require(file.hunks.first?.lines.first { $0.kind == .deletion })
374 #expect(deletion.anchors(subject, in: file))
375 // The same line number on the other side is a different anchor.
376 let addition = try #require(file.hunks.first?.lines.first { $0.newNumber == 2 })
377 #expect(!addition.anchors(subject, in: file))
378 }
379
380 @Test func aStaleThreadAnchorsNowhere() throws {
381 // Its head is gone, so the line numbers cannot be trusted.
382 let subject = try thread(path: "main.go", line: 2, stale: true)
383 #expect(!diff.anchors(subject))
384 }
385
386 @Test func aThreadOnAnotherFileOrLineDoesNotAnchor() throws {
387 #expect(!diff.anchors(try thread(path: "other.go", line: 2)))
388 #expect(!diff.anchors(try thread(path: "main.go", line: 999)))
389 }
390}