| 1 | @testable import EquipoShareCore |
| 2 | import Foundation |
| 3 | import ImageIO |
| 4 | import Testing |
| 5 | import UniformTypeIdentifiers |
| 6 | @testable import EquipoKit |
| 7 | |
| 8 | @Suite struct AttachmentReviewTests { |
| 9 | @Test func largeHEICAndWebPMatchWebSizing() throws { |
| 10 | let heic = try AttachmentTests.image(.heic, width: 8064, height: 6048) |
| 11 | let url = try #require(Bundle.module.url(forResource: "large", withExtension: "webp", subdirectory: "Fixtures/attachments")) |
| 12 | for (bytes, name, height) in [(heic, "photo.heic", 1920), (try Data(contentsOf: url), "large.webp", 1280)] { |
| 13 | let file = try AttachmentFile.prepare(bytes, name: name) |
| 14 | #expect(file.mediaType == "image/jpeg") |
| 15 | #expect(file.width == 2560 && file.height == height) |
| 16 | #expect(file.data.count <= AttachmentLimits.maxBytes) |
| 17 | } |
| 18 | } |
| 19 | |
| 20 | @Test func conversionStripsMetadataAndAppliesOrientation() throws { |
| 21 | let source = try #require(CGImageSourceCreateWithData(AttachmentTests.image() as CFData, nil)) |
| 22 | let image = try #require(CGImageSourceCreateImageAtIndex(source, 0, nil)) |
| 23 | let bytes = NSMutableData() |
| 24 | let dest = try #require(CGImageDestinationCreateWithData(bytes, UTType.heic.identifier as CFString, 1, nil)) |
| 25 | let metadata: [CFString: Any] = [kCGImagePropertyOrientation: 6, |
| 26 | kCGImagePropertyGPSDictionary: [kCGImagePropertyGPSLatitude: 53.3, kCGImagePropertyGPSLatitudeRef: "N", kCGImagePropertyGPSLongitude: 6.2, kCGImagePropertyGPSLongitudeRef: "W"], |
| 27 | kCGImagePropertyExifDictionary: [kCGImagePropertyExifUserComment: "private fixture metadata"]] |
| 28 | CGImageDestinationAddImage(dest, image, metadata as CFDictionary) |
| 29 | #expect(CGImageDestinationFinalize(dest)) |
| 30 | let file = try AttachmentFile.prepare(bytes as Data, name: "private.heic") |
| 31 | #expect(file.width == 8 && file.height == 12) |
| 32 | let converted = try #require(CGImageSourceCreateWithData(file.data as CFData, nil)) |
| 33 | let properties = try #require(CGImageSourceCopyPropertiesAtIndex(converted, 0, nil) as? [CFString: Any]) |
| 34 | #expect(properties[kCGImagePropertyGPSDictionary] == nil) |
| 35 | #expect((properties[kCGImagePropertyExifDictionary] as? [CFString: Any])?[kCGImagePropertyExifUserComment] == nil) |
| 36 | } |
| 37 | |
| 38 | @Test func convertedBytesAreCheckedAgain() throws { |
| 39 | let input = try AttachmentTests.image(.heic) |
| 40 | #expect(throws: AttachmentFailure.tooLarge) { try AttachmentFile.prepare(input, name: "photo.heic", maximumBytes: 1) } |
| 41 | } |
| 42 | |
| 43 | @Test func emptyAndBoundedFileReads() throws { |
| 44 | #expect(throws: AttachmentFailure.type) { try AttachmentFile.prepare(Data(), name: "empty.txt") } |
| 45 | let url = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) |
| 46 | defer { try? FileManager.default.removeItem(at: url) } |
| 47 | FileManager.default.createFile(atPath: url.path, contents: nil) |
| 48 | let handle = try FileHandle(forWritingTo: url) |
| 49 | try handle.truncate(atOffset: 128 * 1024 * 1024 + 1); try handle.close() |
| 50 | #expect(throws: AttachmentFailure.tooLarge) { try AttachmentFile.read(url) } |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | actor AttachmentReviewServer: EquipoTransport { |
| 55 | nonisolated let origin = URL(string: "https://review.invalid")! |
| 56 | var requests: [APIRequest] = [] |
| 57 | var callbacks: [UploadProgress] = [] |
| 58 | var code: String? |
| 59 | var hold = false |
| 60 | var lostProject = false |
| 61 | var cancelled = false |
| 62 | var pending: [CheckedContinuation<APIResponse, Error>] = [] |
| 63 | func configure(code: String? = nil, hold: Bool = false, lostProject: Bool = false) { self.code = code; self.hold = hold; self.lostProject = lostProject } |
| 64 | func send(_ request: APIRequest) async throws -> APIResponse { |
| 65 | requests.append(request) |
| 66 | if request.path == "/attachments" { |
| 67 | if let callback = request.uploadProgress { callbacks.append(callback) } |
| 68 | if let code { self.code = nil; return APIResponse(status: 422, data: Data("{\"code\":\"\(code)\",\"copy_key\":\"api.\(code)\",\"request_id\":\"fixture\"}".utf8)) } |
| 69 | if hold { return try await withCheckedThrowingContinuation { pending.append($0) } } |
| 70 | return APIResponse(status: 201, data: Data(AttachmentServer.attachment.utf8)) |
| 71 | } |
| 72 | if request.path == "/messages" { |
| 73 | if lostProject { lostProject = false; return APIResponse(status: 404, data: Data("{\"code\":\"not_found\",\"copy_key\":\"api.not_found\",\"request_id\":\"fixture\"}".utf8)) } |
| 74 | let sent: Sent = try Fixture.decode("thin/sent") |
| 75 | let encoder = EquipoJSON.encoder; encoder.dateEncodingStrategy = .iso8601 |
| 76 | return APIResponse(status: 201, data: try encoder.encode(sent)) |
| 77 | } |
| 78 | return APIResponse(status: 200, data: Data("{}".utf8)) |
| 79 | } |
| 80 | func emit(_ index: Int, _ value: Double) { callbacks[index].report(value) } |
| 81 | func finish() { for c in pending { c.resume(returning: APIResponse(status: 201, data: Data(AttachmentServer.attachment.utf8))) }; pending = [] } |
| 82 | func lines(_ request: APIRequest) async throws -> AsyncThrowingStream<String, Error> { AsyncThrowingStream { $0.finish() } } |
| 83 | } |
| 84 | |
| 85 | extension AttachmentReviewTests { |
| 86 | @MainActor @Test func failedDraftCannotSendAndThreadsRejectAttachments() async throws { |
| 87 | let server = AttachmentReviewServer(); await server.configure(code: "attachment_type") |
| 88 | let session = EquipoSession(account: .new(origin: server.origin, label: "Fixture"), accounts: DeviceAccounts(store: MemorySecretStore()), transport: server) |
| 89 | await session.attachments.add(data: try AttachmentTests.image(), name: "screen.png") |
| 90 | await session.sendFromComposer("note").value |
| 91 | #expect(await server.requests.filter { $0.path == "/messages" }.isEmpty) |
| 92 | #expect(session.attachments.items.count == 1) |
| 93 | let attachment = try EquipoJSON.decoder.decode(MessageAttachment.self, from: Data(AttachmentServer.attachment.utf8)) |
| 94 | await session.send("note", inThreadOf: "task", attachments: [attachment]) |
| 95 | #expect(await server.requests.filter { $0.path.contains("/thread") }.isEmpty) |
| 96 | } |
| 97 | |
| 98 | @MainActor @Test func lostProjectRetryKeepsAttachmentIDs() async throws { |
| 99 | let server = AttachmentReviewServer(); await server.configure(lostProject: true) |
| 100 | let session = EquipoSession(account: .new(origin: server.origin, label: "Fixture"), accounts: DeviceAccounts(store: MemorySecretStore()), transport: server) |
| 101 | let attachment = try EquipoJSON.decoder.decode(MessageAttachment.self, from: Data(AttachmentServer.attachment.utf8)) |
| 102 | await session.send("note", projectID: "lost", attachments: [attachment]) |
| 103 | let pending = try #require(session.outgoing.first) |
| 104 | #expect(pending.goneProject) |
| 105 | await session.retry(pending.id) |
| 106 | let requests = await server.requests.filter { $0.path == "/messages" } |
| 107 | #expect(requests.count == 2) |
| 108 | let bytes = try #require(requests.last?.body) |
| 109 | let body = try #require(try JSONSerialization.jsonObject(with: bytes) as? [String: Any]) |
| 110 | #expect(body["attachments"] as? [String] == [attachment.id]); #expect(body["project_id"] == nil) |
| 111 | } |
| 112 | |
| 113 | @MainActor @Test func retryIsSingleAndOldProgressCannotOverwriteNewOrReadyState() async throws { |
| 114 | let server = AttachmentReviewServer(); await server.configure(code: "attachment_type") |
| 115 | let draft = AttachmentDraft(client: EquipoClient(transport: server, token: "fixture")) |
| 116 | await draft.add(data: try AttachmentTests.image(), name: "screen.png") |
| 117 | let id = try #require(draft.items.first?.id) |
| 118 | await server.configure(hold: true) |
| 119 | let first = Task { await draft.retry(id) } |
| 120 | for _ in 0..<100 { if await server.callbacks.count >= 2 { break }; try await Task.sleep(for: .milliseconds(10)) } |
| 121 | let second = Task { await draft.retry(id) } |
| 122 | try await Task.sleep(for: .milliseconds(40)) |
| 123 | #expect(await server.callbacks.count == 2) |
| 124 | await server.emit(0, 0.99) |
| 125 | try await Task.sleep(for: .milliseconds(30)) |
| 126 | if case .uploading(let progress) = draft.items.first?.state { #expect(progress == 0) } else { Issue.record("Expected retry upload") } |
| 127 | await server.finish(); await first.value; await second.value |
| 128 | await server.emit(1, 0.2) |
| 129 | try await Task.sleep(for: .milliseconds(30)) |
| 130 | #expect(draft.readyAttachments.count == 1) |
| 131 | } |
| 132 | |
| 133 | @MainActor @Test(arguments: ["attachment_too_large", "attachment_pixels", "attachment_type", "attachment_heic", "attachment_limit"]) |
| 134 | func serverCodesUseReviewedWords(_ code: String) async throws { |
| 135 | let server = AttachmentReviewServer(); await server.configure(code: code) |
| 136 | let draft = AttachmentDraft(client: EquipoClient(transport: server, token: "fixture")) |
| 137 | await draft.add(data: try AttachmentTests.image(), name: "screen.png") |
| 138 | #expect(draft.items.first?.failure == EquipoStrings.text(String.LocalizationValue("api." + code))) |
| 139 | } |
| 140 | |
| 141 | @Test func readsCarryBearerAndRefuseOversizedResponses() async throws { |
| 142 | let server = AttachmentServer() |
| 143 | let client = EquipoClient(transport: server, token: "private-bearer") |
| 144 | _ = try await client.attachmentData("at_fixture") |
| 145 | _ = try await client.attachmentData("at_fixture", preview: true) |
| 146 | for request in await server.requests { #expect(request.bearer == "private-bearer"); #expect(request.maximumResponseBytes == AttachmentLimits.maxBytes) } |
| 147 | let huge = HugeAttachmentServer() |
| 148 | await #expect(throws: EquipoAPIError.tooLarge) { try await EquipoClient(transport: huge, token: "fixture").attachmentData("huge") } |
| 149 | } |
| 150 | |
| 151 | @Test func uploadDelegateRefusesRedirects() async throws { |
| 152 | let delegate = UploadDelegate(UploadProgress { _ in }) |
| 153 | let session = URLSession(configuration: .ephemeral) |
| 154 | defer { session.invalidateAndCancel() } |
| 155 | let target = URL(string: "https://other.invalid")! |
| 156 | let response = try #require(HTTPURLResponse(url: target, statusCode: 307, httpVersion: nil, headerFields: ["Location": target.absoluteString])) |
| 157 | let result = await delegate.urlSession(session, task: session.dataTask(with: target), willPerformHTTPRedirection: response, newRequest: URLRequest(url: target)) |
| 158 | #expect(result == nil) |
| 159 | } |
| 160 | |
| 161 | @MainActor @Test func removalCancelsTheActualUpload() async throws { |
| 162 | let server = CancellableAttachmentServer() |
| 163 | let draft = AttachmentDraft(client: EquipoClient(transport: server, token: "fixture")) |
| 164 | let adding = Task { await draft.add(data: try AttachmentTests.image(), name: "screen.png") } |
| 165 | for _ in 0..<100 { if await server.started { break }; try await Task.sleep(for: .milliseconds(10)) } |
| 166 | draft.remove(try #require(draft.items.first?.id)) |
| 167 | for _ in 0..<100 { if await server.cancelled { break }; try await Task.sleep(for: .milliseconds(10)) } |
| 168 | #expect(await server.cancelled) |
| 169 | adding.cancel() |
| 170 | try await adding.value |
| 171 | } |
| 172 | } |
| 173 | |
| 174 | private struct HugeAttachmentServer: EquipoTransport { |
| 175 | let origin = URL(string: "https://huge.invalid")! |
| 176 | func send(_ request: APIRequest) async throws -> APIResponse { APIResponse(status: 200, data: Data(repeating: 0, count: AttachmentLimits.maxBytes + 1)) } |
| 177 | func lines(_ request: APIRequest) async throws -> AsyncThrowingStream<String, Error> { AsyncThrowingStream { $0.finish() } } |
| 178 | } |
| 179 | private actor CancellableAttachmentServer: EquipoTransport { |
| 180 | nonisolated let origin = URL(string: "https://cancel.invalid")! |
| 181 | var started = false |
| 182 | var cancelled = false |
| 183 | func send(_ request: APIRequest) async throws -> APIResponse { |
| 184 | started = true |
| 185 | do { try await Task.sleep(for: .seconds(30)) } catch { cancelled = true; throw error } |
| 186 | return APIResponse(status: 201, data: Data(AttachmentServer.attachment.utf8)) |
| 187 | } |
| 188 | func lines(_ request: APIRequest) async throws -> AsyncThrowingStream<String, Error> { AsyncThrowingStream { $0.finish() } } |
| 189 | } |
| 190 | |