import Foundation import Testing #if os(macOS) import AppKit #endif @testable import EquipoKit @MainActor @Suite struct ChangeDiffTests { static let sha = String(repeating: "b", count: 40) static let base = String(repeating: "a", count: 40) static func value() -> ChangeDiff { .init(taskId: "tk1", stepId: "s1", attempt: 1, base: base, candidateSha: sha, status: "modified", path: "dir/space 日本語.txt", patch: "@@ -1 +1 @@\n-old\n+new\n", truncated: false) } @Test func responseBindingsBoundsAndPlainLineStyles() async throws { let server = ScriptedTransport(), good = Self.value() let key = "GET /tasks/tk1/changes/diff" server.on(key, .success(APIResponse(status: 200, data: try EquipoJSON.encoder.encode(good)))) let client = EquipoClient(transport: server, token: "device-bearer") let read = try await client.changeDiff(task: "tk1", candidate: Self.sha, path: good.path) #expect(read == good) let request = try #require(server.sent(key).first) #expect(request.bearer == "device-bearer") #expect(request.maximumResponseBytes == 128 * 1024) #expect(request.query == [URLQueryItem(name: "candidate_sha", value: Self.sha), URLQueryItem(name: "path", value: good.path)]) #expect(read.lines.map(\.kind) == [.context, .removed, .added]) var oversized = Data(repeating: 32, count: 128 * 1024) oversized.append(try EquipoJSON.encoder.encode(good)) server.replace(key, with: .success(APIResponse(status: 200, data: oversized))) await #expect(throws: (any Error).self) { try await client.changeDiff(task: "tk1", candidate: Self.sha, path: good.path) } for mutation in ["task", "candidate", "path", "bytes", "lines", "reason", "withheld", "old"] { var bad = good switch mutation { case "task": bad.taskId = "other" case "candidate": bad.candidateSha = Self.base case "path": bad.path = "other" case "bytes": bad.patch = String(repeating: "x", count: 65536) + "\n" case "lines": bad.patch = String(repeating: "+\n", count: 2001) case "reason": bad.reason = "unknown" case "withheld": bad.reason = "withheld" default: bad.oldPath = "../bad" } server.replace(key, with: .success(APIResponse(status: 200, data: try EquipoJSON.encoder.encode(bad)))) await #expect(throws: (any Error).self) { try await client.changeDiff(task: "tk1", candidate: Self.sha, path: good.path) } } } @Test func hiddenCharactersAreVisibleAndNotStripped() throws { var diff = Self.value() diff.patch = "+safe\u{202E}hidden\u{200D}code\n" #expect(diff.hiddenCharactersNotice == EquipoStrings.text("native.diff.hidden_characters")) let segments = try #require(diff.lines.first).displaySegments() #expect(segments.map(\.text).joined() == "+safe⟨U+202E⟩hidden⟨U+200D⟩code") #expect(segments.filter(\.marker).map(\.text) == ["⟨U+202E⟩", "⟨U+200D⟩"]) #expect(diff.patch == "+safe\u{202E}hidden\u{200D}code\n") for scalar in [0x202A,0x202B,0x202C,0x202D,0x202E,0x2066,0x2067,0x2068,0x2069,0x200E,0x200F,0x061C,0x200B,0x200C,0x200D,0x2060,0xFEFF,0x00AD] { diff.patch = "+" + String(Unicode.Scalar(scalar)!) + "\n" #expect(diff.hasHiddenCharacters) #expect(diff.lines[0].displaySegments().contains { $0.marker }) } diff.patch = "+日本語 café 🙂\n" #expect(diff.hiddenCharactersNotice == nil) diff.hiddenCharacters = true #expect(diff.hiddenCharactersNotice != nil) } @Test func sharedHiddenCodepointsAndDisplayedCopy() throws { struct Case: Decodable { let first: String; let last: String; let kind: String; let hidden: Bool; let prefix: String?; let suffix: String? } var root = URL(fileURLWithPath: #filePath) for _ in 0..<5 { root.deleteLastPathComponent() } let cases = try JSONDecoder().decode([Case].self, from: Data(contentsOf: root.appendingPathComponent("internal/wire/testdata/hidden-codepoints.json"))) for item in cases { for value in UInt32(item.first, radix: 16)!...UInt32(item.last, radix: 16)! { let scalar = Unicode.Scalar(value)! let prefix = item.prefix ?? "", suffix = item.suffix ?? "" let input = prefix + String(scalar) + suffix var diff = Self.value(); diff.patch = input #expect(diff.hasHiddenCharacters == item.hidden, "\(item.kind) U+\(item.first)") let displayed = ChangeDiff.Line(id: 0, text: input).displaySegments() let expected = prefix + (item.hidden ? String(format: "⟨U+%04X⟩", value) : String(scalar)) + suffix #expect(displayed.map(\.text).joined() == expected) #expect(displayed.contains(where: \.marker) == item.hidden) #expect(diff.copyText == expected) } } var diff = Self.value(); diff.patch = "+safe\u{202E}evil()\r\n" #expect(diff.copyText == "+safe⟨U+202E⟩evil()⟨U+000D⟩\n") } @Test func crlfIsVisibleAndObeysTheSameLineBound() { var diff = Self.value(); diff.patch = "+windows\r\n" #expect(diff.isValid) #expect(diff.hiddenCharactersNotice != nil) #expect(DiffAttributedText.make(diff).string == "+windows⟨U+000D⟩\n") #expect(DiffAttributedText.make(diff).string == diff.copyText) diff.patch = String(repeating: "+x\r\n", count: 2001) #expect(!diff.isValid) } @Test func longLineKeepsTrailingCode() throws { var diff = Self.value() diff.patch = "+" + String(repeating: " ", count: 2000) + "evil()\n" let shown = try #require(diff.lines.first).displaySegments().map(\.text).joined() #expect(shown.hasSuffix("evil()")) #expect(shown == String(diff.patch!.dropLast())) diff.patch = "+" + String(repeating: "x", count: 60_000) + "evil()\n" #expect(diff.lines[0].displaySegments().map(\.text).joined().hasSuffix("evil()")) } @Test func fileNamesAndRenameSourcesShowCodesWithoutChangingPaths() throws { var file = ChangeFilesTests.facts().entries[0] file.path = "dir/a\u{3164}b\u{200D}.swift" file.status = "renamed"; file.oldPath = "dir/old\u{034F}.swift" #expect(ThinChangeFiles.path(file.path)) #expect(ChangedFilesPresentation.displayPath(file) == "dir/a⟨U+3164⟩b⟨U+200D⟩.swift") #expect(ChangedFilesPresentation.renamedFrom(file) == "Renamed from dir/old⟨U+034F⟩.swift") var task = try TaskDetailTests.task(); task.repo = "oficina/equipo" let url = try #require(ChangedFilesPresentation.fileURL(task: task, facts: ChangeFilesTests.facts(), file: file)) #expect(URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems?.first(where: { $0.name == "path" })?.value == file.path) } #if os(macOS) @Test func macCharacterWrappingLaysOutTrailingCodeAndCopiesDisplayedFile() throws { var diff = Self.value() diff.patch = "+" + String(repeating: " ", count: 2000) + "evil()\r\n+\u{3164}\u{202E}end\n" let view = WrappingDiffText.makeTextView() let attributed = DiffAttributedText.make(diff) view.textStorage?.setAttributedString(attributed) #expect(view.isSelectable && !view.isEditable) #expect(view.textContainer?.lineBreakMode == .byCharWrapping) #expect(attributed.string == diff.copyText) #expect(attributed.string.contains("evil()⟨U+000D⟩\n+⟨U+3164⟩⟨U+202E⟩end")) for width: CGFloat in [240, 560, 800] { let size = WrappingDiffText.measure(view, width: width) view.frame = CGRect(origin: .zero, size: size) let layout = try #require(view.layoutManager) let container = try #require(view.textContainer) let chars = (attributed.string as NSString).range(of: "evil()") let glyphs = layout.glyphRange(forCharacterRange: chars, actualCharacterRange: nil) let rect = layout.boundingRect(forGlyphRange: glyphs, in: container) #expect(rect.width > 0 && rect.height > 0) #expect(rect.minX >= 20 && rect.maxX <= width + 1) let plusGlyphs = layout.glyphRange(forCharacterRange: NSRange(location: 0, length: 1), actualCharacterRange: nil) let plusRect = layout.boundingRect(forGlyphRange: plusGlyphs, in: container) #expect(plusRect.minX < rect.minX) #expect(plusRect.minY < rect.minY) #expect(rect.minY >= 0 && rect.maxY <= size.height) #expect(layout.glyphRange(for: container).length == layout.numberOfGlyphs) } // The whole-file Copy button and selected native text expose the same codes. let marker = (attributed.string as NSString).range(of: "⟨U+202E⟩") #expect(attributed.attribute(.backgroundColor, at: marker.location, effectiveRange: nil) != nil) } #endif @Test func selectionChangeDropsLateResponse() async throws { let server = ScriptedTransport() let gate = DiffReadGate(base: server) server.on("GET /tasks/tk1/changes/diff", .success(APIResponse(status: 200, data: try EquipoJSON.encoder.encode(Self.value())))) let model = ChangeDiffModel() let job = Task { await model.load(client: EquipoClient(transport: gate, token: "device"), task: "tk1", candidate: Self.sha, path: Self.value().path) } await gate.waitUntilHeld() model.clear() await gate.release() await job.value #expect(model.diff == nil) } } private actor DiffReadGate: EquipoTransport { nonisolated let origin = URL(string: "https://oficina.example.test")! nonisolated let base: ScriptedTransport init(base: ScriptedTransport) {self.base=base} var held=false var continuation: CheckedContinuation? func waitUntilHeld() async {while !held {await Task.yield()}} func release(){continuation?.resume();continuation=nil} func send(_ request: APIRequest) async throws -> APIResponse { held=true;await withCheckedContinuation {continuation=$0} return try await base.send(request) } func lines(_ request: APIRequest) async throws -> AsyncThrowingStream {try await base.lines(request)} }