| 1 | import Foundation |
| 2 | import Testing |
| 3 | #if os(macOS) |
| 4 | import AppKit |
| 5 | #endif |
| 6 | @testable import EquipoKit |
| 7 | |
| 8 | @MainActor @Suite struct ChangeDiffTests { |
| 9 | static let sha = String(repeating: "b", count: 40) |
| 10 | static let base = String(repeating: "a", count: 40) |
| 11 | static func value() -> ChangeDiff { |
| 12 | .init(taskId: "tk1", stepId: "s1", attempt: 1, base: base, candidateSha: sha, |
| 13 | status: "modified", path: "dir/space 日本語.txt", patch: "@@ -1 +1 @@\n-old\n+new\n", truncated: false) |
| 14 | } |
| 15 | @Test func responseBindingsBoundsAndPlainLineStyles() async throws { |
| 16 | let server = ScriptedTransport(), good = Self.value() |
| 17 | let key = "GET /tasks/tk1/changes/diff" |
| 18 | server.on(key, .success(APIResponse(status: 200, data: try EquipoJSON.encoder.encode(good)))) |
| 19 | let client = EquipoClient(transport: server, token: "device-bearer") |
| 20 | let read = try await client.changeDiff(task: "tk1", candidate: Self.sha, path: good.path) |
| 21 | #expect(read == good) |
| 22 | let request = try #require(server.sent(key).first) |
| 23 | #expect(request.bearer == "device-bearer") |
| 24 | #expect(request.maximumResponseBytes == 128 * 1024) |
| 25 | #expect(request.query == [URLQueryItem(name: "candidate_sha", value: Self.sha), URLQueryItem(name: "path", value: good.path)]) |
| 26 | #expect(read.lines.map(\.kind) == [.context, .removed, .added]) |
| 27 | var oversized = Data(repeating: 32, count: 128 * 1024) |
| 28 | oversized.append(try EquipoJSON.encoder.encode(good)) |
| 29 | server.replace(key, with: .success(APIResponse(status: 200, data: oversized))) |
| 30 | await #expect(throws: (any Error).self) { try await client.changeDiff(task: "tk1", candidate: Self.sha, path: good.path) } |
| 31 | |
| 32 | for mutation in ["task", "candidate", "path", "bytes", "lines", "reason", "withheld", "old"] { |
| 33 | var bad = good |
| 34 | switch mutation { |
| 35 | case "task": bad.taskId = "other" |
| 36 | case "candidate": bad.candidateSha = Self.base |
| 37 | case "path": bad.path = "other" |
| 38 | case "bytes": bad.patch = String(repeating: "x", count: 65536) + "\n" |
| 39 | case "lines": bad.patch = String(repeating: "+\n", count: 2001) |
| 40 | case "reason": bad.reason = "unknown" |
| 41 | case "withheld": bad.reason = "withheld" |
| 42 | default: bad.oldPath = "../bad" |
| 43 | } |
| 44 | server.replace(key, with: .success(APIResponse(status: 200, data: try EquipoJSON.encoder.encode(bad)))) |
| 45 | await #expect(throws: (any Error).self) { try await client.changeDiff(task: "tk1", candidate: Self.sha, path: good.path) } |
| 46 | } |
| 47 | } |
| 48 | @Test func hiddenCharactersAreVisibleAndNotStripped() throws { |
| 49 | var diff = Self.value() |
| 50 | diff.patch = "+safe\u{202E}hidden\u{200D}code\n" |
| 51 | #expect(diff.hiddenCharactersNotice == EquipoStrings.text("native.diff.hidden_characters")) |
| 52 | let segments = try #require(diff.lines.first).displaySegments() |
| 53 | #expect(segments.map(\.text).joined() == "+safe⟨U+202E⟩hidden⟨U+200D⟩code") |
| 54 | #expect(segments.filter(\.marker).map(\.text) == ["⟨U+202E⟩", "⟨U+200D⟩"]) |
| 55 | #expect(diff.patch == "+safe\u{202E}hidden\u{200D}code\n") |
| 56 | for scalar in [0x202A,0x202B,0x202C,0x202D,0x202E,0x2066,0x2067,0x2068,0x2069,0x200E,0x200F,0x061C,0x200B,0x200C,0x200D,0x2060,0xFEFF,0x00AD] { |
| 57 | diff.patch = "+" + String(Unicode.Scalar(scalar)!) + "\n" |
| 58 | #expect(diff.hasHiddenCharacters) |
| 59 | #expect(diff.lines[0].displaySegments().contains { $0.marker }) |
| 60 | } |
| 61 | diff.patch = "+日本語 café 🙂\n" |
| 62 | #expect(diff.hiddenCharactersNotice == nil) |
| 63 | diff.hiddenCharacters = true |
| 64 | #expect(diff.hiddenCharactersNotice != nil) |
| 65 | } |
| 66 | @Test func sharedHiddenCodepointsAndDisplayedCopy() throws { |
| 67 | struct Case: Decodable { let first: String; let last: String; let kind: String; let hidden: Bool; let prefix: String?; let suffix: String? } |
| 68 | var root = URL(fileURLWithPath: #filePath) |
| 69 | for _ in 0..<5 { root.deleteLastPathComponent() } |
| 70 | let cases = try JSONDecoder().decode([Case].self, from: Data(contentsOf: root.appendingPathComponent("internal/wire/testdata/hidden-codepoints.json"))) |
| 71 | for item in cases { |
| 72 | for value in UInt32(item.first, radix: 16)!...UInt32(item.last, radix: 16)! { |
| 73 | let scalar = Unicode.Scalar(value)! |
| 74 | let prefix = item.prefix ?? "", suffix = item.suffix ?? "" |
| 75 | let input = prefix + String(scalar) + suffix |
| 76 | var diff = Self.value(); diff.patch = input |
| 77 | #expect(diff.hasHiddenCharacters == item.hidden, "\(item.kind) U+\(item.first)") |
| 78 | let displayed = ChangeDiff.Line(id: 0, text: input).displaySegments() |
| 79 | let expected = prefix + (item.hidden ? String(format: "⟨U+%04X⟩", value) : String(scalar)) + suffix |
| 80 | #expect(displayed.map(\.text).joined() == expected) |
| 81 | #expect(displayed.contains(where: \.marker) == item.hidden) |
| 82 | #expect(diff.copyText == expected) |
| 83 | } |
| 84 | } |
| 85 | var diff = Self.value(); diff.patch = "+safe\u{202E}evil()\r\n" |
| 86 | #expect(diff.copyText == "+safe⟨U+202E⟩evil()⟨U+000D⟩\n") |
| 87 | } |
| 88 | @Test func crlfIsVisibleAndObeysTheSameLineBound() { |
| 89 | var diff = Self.value(); diff.patch = "+windows\r\n" |
| 90 | #expect(diff.isValid) |
| 91 | #expect(diff.hiddenCharactersNotice != nil) |
| 92 | #expect(DiffAttributedText.make(diff).string == "+windows⟨U+000D⟩\n") |
| 93 | #expect(DiffAttributedText.make(diff).string == diff.copyText) |
| 94 | diff.patch = String(repeating: "+x\r\n", count: 2001) |
| 95 | #expect(!diff.isValid) |
| 96 | } |
| 97 | @Test func longLineKeepsTrailingCode() throws { |
| 98 | var diff = Self.value() |
| 99 | diff.patch = "+" + String(repeating: " ", count: 2000) + "evil()\n" |
| 100 | let shown = try #require(diff.lines.first).displaySegments().map(\.text).joined() |
| 101 | #expect(shown.hasSuffix("evil()")) |
| 102 | #expect(shown == String(diff.patch!.dropLast())) |
| 103 | diff.patch = "+" + String(repeating: "x", count: 60_000) + "evil()\n" |
| 104 | #expect(diff.lines[0].displaySegments().map(\.text).joined().hasSuffix("evil()")) |
| 105 | } |
| 106 | @Test func fileNamesAndRenameSourcesShowCodesWithoutChangingPaths() throws { |
| 107 | var file = ChangeFilesTests.facts().entries[0] |
| 108 | file.path = "dir/a\u{3164}b\u{200D}.swift" |
| 109 | file.status = "renamed"; file.oldPath = "dir/old\u{034F}.swift" |
| 110 | #expect(ThinChangeFiles.path(file.path)) |
| 111 | #expect(ChangedFilesPresentation.displayPath(file) == "dir/a⟨U+3164⟩b⟨U+200D⟩.swift") |
| 112 | #expect(ChangedFilesPresentation.renamedFrom(file) == "Renamed from dir/old⟨U+034F⟩.swift") |
| 113 | var task = try TaskDetailTests.task(); task.repo = "oficina/equipo" |
| 114 | let url = try #require(ChangedFilesPresentation.fileURL(task: task, facts: ChangeFilesTests.facts(), file: file)) |
| 115 | #expect(URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems?.first(where: { $0.name == "path" })?.value == file.path) |
| 116 | } |
| 117 | #if os(macOS) |
| 118 | @Test func macCharacterWrappingLaysOutTrailingCodeAndCopiesDisplayedFile() throws { |
| 119 | var diff = Self.value() |
| 120 | diff.patch = "+" + String(repeating: " ", count: 2000) + "evil()\r\n+\u{3164}\u{202E}end\n" |
| 121 | let view = WrappingDiffText.makeTextView() |
| 122 | let attributed = DiffAttributedText.make(diff) |
| 123 | view.textStorage?.setAttributedString(attributed) |
| 124 | #expect(view.isSelectable && !view.isEditable) |
| 125 | #expect(view.textContainer?.lineBreakMode == .byCharWrapping) |
| 126 | #expect(attributed.string == diff.copyText) |
| 127 | #expect(attributed.string.contains("evil()⟨U+000D⟩\n+⟨U+3164⟩⟨U+202E⟩end")) |
| 128 | for width: CGFloat in [240, 560, 800] { |
| 129 | let size = WrappingDiffText.measure(view, width: width) |
| 130 | view.frame = CGRect(origin: .zero, size: size) |
| 131 | let layout = try #require(view.layoutManager) |
| 132 | let container = try #require(view.textContainer) |
| 133 | let chars = (attributed.string as NSString).range(of: "evil()") |
| 134 | let glyphs = layout.glyphRange(forCharacterRange: chars, actualCharacterRange: nil) |
| 135 | let rect = layout.boundingRect(forGlyphRange: glyphs, in: container) |
| 136 | #expect(rect.width > 0 && rect.height > 0) |
| 137 | #expect(rect.minX >= 20 && rect.maxX <= width + 1) |
| 138 | let plusGlyphs = layout.glyphRange(forCharacterRange: NSRange(location: 0, length: 1), actualCharacterRange: nil) |
| 139 | let plusRect = layout.boundingRect(forGlyphRange: plusGlyphs, in: container) |
| 140 | #expect(plusRect.minX < rect.minX) |
| 141 | #expect(plusRect.minY < rect.minY) |
| 142 | #expect(rect.minY >= 0 && rect.maxY <= size.height) |
| 143 | #expect(layout.glyphRange(for: container).length == layout.numberOfGlyphs) |
| 144 | } |
| 145 | // The whole-file Copy button and selected native text expose the same codes. |
| 146 | let marker = (attributed.string as NSString).range(of: "⟨U+202E⟩") |
| 147 | #expect(attributed.attribute(.backgroundColor, at: marker.location, effectiveRange: nil) != nil) |
| 148 | } |
| 149 | #endif |
| 150 | @Test func selectionChangeDropsLateResponse() async throws { |
| 151 | let server = ScriptedTransport() |
| 152 | let gate = DiffReadGate(base: server) |
| 153 | server.on("GET /tasks/tk1/changes/diff", .success(APIResponse(status: 200, data: try EquipoJSON.encoder.encode(Self.value())))) |
| 154 | let model = ChangeDiffModel() |
| 155 | let job = Task { await model.load(client: EquipoClient(transport: gate, token: "device"), task: "tk1", candidate: Self.sha, path: Self.value().path) } |
| 156 | await gate.waitUntilHeld() |
| 157 | model.clear() |
| 158 | await gate.release() |
| 159 | await job.value |
| 160 | #expect(model.diff == nil) |
| 161 | } |
| 162 | } |
| 163 | |
| 164 | private actor DiffReadGate: EquipoTransport { |
| 165 | nonisolated let origin = URL(string: "https://oficina.example.test")! |
| 166 | nonisolated let base: ScriptedTransport |
| 167 | init(base: ScriptedTransport) {self.base=base} |
| 168 | var held=false |
| 169 | var continuation: CheckedContinuation<Void,Never>? |
| 170 | func waitUntilHeld() async {while !held {await Task.yield()}} |
| 171 | func release(){continuation?.resume();continuation=nil} |
| 172 | func send(_ request: APIRequest) async throws -> APIResponse { |
| 173 | held=true;await withCheckedContinuation {continuation=$0} |
| 174 | return try await base.send(request) |
| 175 | } |
| 176 | func lines(_ request: APIRequest) async throws -> AsyncThrowingStream<String,Error> {try await base.lines(request)} |
| 177 | } |
| 178 | |