gitbayTests/MRViewModelTests.swift
400 lines · 16883 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.state = .merged
175 // The reload happens in a spawned task; wait for it to settle
176 // rather than for a fixed interval to pass. Checking `model.state`
177 // alone is not enough: right after the assignment, before the
178 // spawned task has even run, the state is still the *previous*
179 // load's non-loading result, which would satisfy a bare
180 // "not loading" check before the reload ever started.
181 await until {
182 guard stub.seen.count == 2 else { return false }
183 if case .loading = model.state { return false }
184 return true
185 }
186
187 #expect(stub.seen.count == 2)
188 let second = try #require(stub.seen.dropFirst().first)
189 #expect(second.url.query()?.contains("argv=merged") == true)
190 guard case .empty = model.state else {
191 Issue.record("expected .empty after filtering, got \(model.state)")
192 return
193 }
194 }
195}
196
197@MainActor
198struct MRDetailViewModelTests {
199
200 private func loadedModel() async throws -> (MRDetailViewModel, StubProtocol.Box) {
201 let (client, stub) = try makeClient()
202 stub.enqueue(.init(status: 200, json: mrShowJSON, match: "argv=show"))
203 stub.enqueue(.init(status: 200, json: diffEnvelope(), match: "argv=diff"))
204 stub.enqueue(.init(status: 200, json: threadsJSON, match: "argv=threads"))
205 let model = MRDetailViewModel(client: client, repoPath: "krz/gitbay", number: 7)
206 await model.load()
207 return (model, stub)
208 }
209
210 @Test func loadsHeaderDiffAndThreads() async throws {
211 let (model, _) = try await loadedModel()
212
213 let mr = try #require(model.state.value)
214 #expect(mr.title == "client: envelope decoding")
215 #expect(mr.checksCombined == "success")
216 #expect(mr.reviews?.first?.verdict == "approve")
217 #expect(mr.reviews?.first?.createdAt != nil)
218 #expect(model.diff?.files.count == 2)
219 #expect(model.threads.count == 2)
220 #expect(model.unresolvedCount == 1)
221 }
222
223 /// A CI check reports how long its build ran; anything else reports
224 /// only when it last changed. Neither may borrow the other's timing.
225 @Test func checksCarryTheirTiming() async throws {
226 let (model, _) = try await loadedModel()
227
228 let checks = try #require(model.state.value?.checks)
229 let ci = try #require(checks.first { $0.context == "ci/build" })
230 #expect(ci.duration == "1m12s")
231 #expect(ci.updatedAt != nil)
232 let external = try #require(checks.first { $0.context == "external/lint" })
233 #expect(external.duration == nil)
234 #expect(external.updatedAt != nil)
235 }
236
237 /// A merged MR says who merged it and when. An open one has no stamp
238 /// to show, and must not invent one.
239 @Test func resolutionStampsDecode() async throws {
240 let (client, stub) = try makeClient()
241 stub.enqueue(.init(status: 200, json: mrShowJSON, match: "argv=show"))
242 stub.enqueue(.init(status: 200, json: diffEnvelope(), match: "argv=diff"))
243 stub.enqueue(.init(status: 200, json: threadsJSON, match: "argv=threads"))
244 let open = MRDetailViewModel(client: client, repoPath: "krz/gitbay", number: 7)
245 await open.load()
246 #expect(open.state.value?.mergedAt == nil)
247 #expect(open.state.value?.closedAt == nil)
248
249 let (mergedClient, mergedStub) = try makeClient()
250 mergedStub.enqueue(.init(status: 200, json: mrMergedJSON, match: "argv=show"))
251 mergedStub.enqueue(.init(status: 200, json: diffEnvelope(), match: "argv=diff"))
252 mergedStub.enqueue(.init(status: 200, json: threadsJSON, match: "argv=threads"))
253 let merged = MRDetailViewModel(client: mergedClient, repoPath: "krz/gitbay", number: 7)
254 await merged.load()
255 #expect(merged.state.value?.mergedBy == "cmc")
256 #expect(merged.state.value?.mergedAt != nil)
257 }
258
259 @Test func approveSendsTheWriteThenReloads() async throws {
260 let (model, stub) = try await loadedModel()
261 stub.enqueue(.init(status: 200, json: #"{"protocol_version":1,"data":{},"exit_code":0}"#))
262 stub.enqueue(.init(status: 200, json: mrShowJSON, match: "argv=show"))
263 stub.enqueue(.init(status: 200, json: diffEnvelope(), match: "argv=diff"))
264 stub.enqueue(.init(status: 200, json: threadsJSON, match: "argv=threads"))
265
266 await model.review(.approve)
267
268 let write = try #require(stub.seen.dropFirst(3).first)
269 #expect(write.method == "POST")
270 #expect(write.url.path() == "/api/v1/cmd")
271 let body = try #require(try JSONSerialization.jsonObject(with: write.body) as? [String: Any])
272 #expect(body["argv"] as? [String] ==
273 ["mr", "review", "krz/gitbay", "7", "--approve"])
274 #expect(model.actionError == nil)
275 }
276
277 @Test func commentGoesThroughStdinNotArgv() async throws {
278 let (model, stub) = try await loadedModel()
279 stub.enqueue(.init(status: 200, json: #"{"protocol_version":1,"data":{},"exit_code":0}"#))
280 stub.enqueue(.init(status: 200, json: mrShowJSON, match: "argv=show"))
281 stub.enqueue(.init(status: 200, json: diffEnvelope(), match: "argv=diff"))
282 stub.enqueue(.init(status: 200, json: threadsJSON, match: "argv=threads"))
283
284 await model.comment("long review text\nwith lines")
285
286 let write = try #require(stub.seen.dropFirst(3).first)
287 let body = try #require(try JSONSerialization.jsonObject(with: write.body) as? [String: Any])
288 #expect(body["argv"] as? [String] == ["mr", "comment", "krz/gitbay", "7", "--file", "-"])
289 #expect(body["stdin"] as? String == "long review text\nwith lines")
290 }
291
292 @Test func aMergeRefusalSurfacesTheServersRuleVerbatim() async throws {
293 let (model, stub) = try await loadedModel()
294 stub.enqueue(.init(status: 403, json:
295 #"{"protocol_version":1,"error":"merge blocked: 1 review thread unresolved","exit_code":4}"#))
296
297 await model.merge()
298
299 #expect(model.actionError == "merge blocked: 1 review thread unresolved")
300 // The refusal did not wipe the loaded screen.
301 #expect(model.state.value != nil)
302 #expect(stub.seen.count == 4)
303 }
304
305 @Test func resolveTargetsTheThreadID() async throws {
306 let (model, stub) = try await loadedModel()
307 stub.enqueue(.init(status: 200, json: #"{"protocol_version":1,"data":{},"exit_code":0}"#))
308 stub.enqueue(.init(status: 200, json: mrShowJSON, match: "argv=show"))
309 stub.enqueue(.init(status: 200, json: diffEnvelope(), match: "argv=diff"))
310 stub.enqueue(.init(status: 200, json: threadsJSON, match: "argv=threads"))
311 let thread = try #require(model.threads.first { !$0.isResolved })
312
313 await model.setResolved(thread, true)
314
315 let write = try #require(stub.seen.dropFirst(3).first)
316 let body = try #require(try JSONSerialization.jsonObject(with: write.body) as? [String: Any])
317 #expect(body["argv"] as? [String] == ["mr", "resolve", "krz/gitbay", "7", "3"])
318 }
319
320 @Test func replyUsesDiffCommentWithReplyFlag() async throws {
321 let (model, stub) = try await loadedModel()
322 stub.enqueue(.init(status: 200, json: #"{"protocol_version":1,"data":{"id":9,"thread":3},"exit_code":0}"#))
323 stub.enqueue(.init(status: 200, json: mrShowJSON, match: "argv=show"))
324 stub.enqueue(.init(status: 200, json: diffEnvelope(), match: "argv=diff"))
325 stub.enqueue(.init(status: 200, json: threadsJSON, match: "argv=threads"))
326 let thread = try #require(model.threads.first { !$0.isResolved })
327
328 await model.reply(to: thread, "because 5xx is transient")
329
330 let write = try #require(stub.seen.dropFirst(3).first)
331 let body = try #require(try JSONSerialization.jsonObject(with: write.body) as? [String: Any])
332 #expect(body["argv"] as? [String] ==
333 ["mr", "diff-comment", "krz/gitbay", "7", "--reply", "3", "--file", "-"])
334 #expect(body["stdin"] as? String == "because 5xx is transient")
335 }
336}
337
338/// Where a review thread hangs in the diff. Threads the diff has moved
339/// past must not vanish — they render in their own section.
340struct ThreadAnchoringTests {
341
342 private func thread(
343 path: String, line: Int64, side: String = "new", stale: Bool = false
344 ) throws -> ReviewThread {
345 let json = """
346 {"id":1,"path":"\(path)","side":"\(side)","line":\(line),"stale":\(stale),\
347 "comments":[{"id":1,"author":"krz","body":"why?",\
348 "created_at":"2026-08-20T10:30:00.000Z"}]}
349 """
350 let decoder = JSONDecoder()
351 decoder.dateDecodingStrategy = .iso8601
352 return try decoder.decode(ReviewThread.self, from: Data(json.utf8))
353 }
354
355 private let diff = UnifiedDiff.parse("""
356 diff --git a/main.go b/main.go
357 --- a/main.go
358 +++ b/main.go
359 @@ -1,4 +1,5 @@
360 package main
361 -import "fmt"
362 +import (
363 +\t"fmt"
364 +)
365 """)
366
367 @Test func aThreadAnchorsToItsLineOnTheNewSide() throws {
368 // "+import (" is new line 2.
369 let subject = try thread(path: "main.go", line: 2)
370 #expect(diff.anchors(subject))
371
372 let file = try #require(diff.files.first)
373 let line = try #require(file.hunks.first?.lines.first { $0.newNumber == 2 })
374 #expect(line.anchors(subject, in: file))
375 }
376
377 @Test func anOldSideThreadAnchorsToTheDeletedLine() throws {
378 // `-import "fmt"` is old line 2 and has no new number.
379 let subject = try thread(path: "main.go", line: 2, side: "old")
380 #expect(diff.anchors(subject))
381
382 let file = try #require(diff.files.first)
383 let deletion = try #require(file.hunks.first?.lines.first { $0.kind == .deletion })
384 #expect(deletion.anchors(subject, in: file))
385 // The same line number on the other side is a different anchor.
386 let addition = try #require(file.hunks.first?.lines.first { $0.newNumber == 2 })
387 #expect(!addition.anchors(subject, in: file))
388 }
389
390 @Test func aStaleThreadAnchorsNowhere() throws {
391 // Its head is gone, so the line numbers cannot be trusted.
392 let subject = try thread(path: "main.go", line: 2, stale: true)
393 #expect(!diff.anchors(subject))
394 }
395
396 @Test func aThreadOnAnotherFileOrLineDoesNotAnchor() throws {
397 #expect(!diff.anchors(try thread(path: "other.go", line: 2)))
398 #expect(!diff.anchors(try thread(path: "main.go", line: 999)))
399 }
400}