| 1 | @testable import EquipoShareCore |
| 2 | #if os(macOS) |
| 3 | import Foundation |
| 4 | import Synchronization |
| 5 | import Testing |
| 6 | @testable import EquipoKit |
| 7 | |
| 8 | /// A loopback fake server exercises URLSession's raw upload and progress |
| 9 | /// delegate, then resolves message attachment ids to the coordinator's bytes. |
| 10 | @Suite struct AttachmentHTTPTests { |
| 11 | @Test func imageReachesCoordinatorOverHTTP() async throws { |
| 12 | let process = Process(), output = Pipe() |
| 13 | process.executableURL = URL(fileURLWithPath: "/usr/bin/python3") |
| 14 | process.standardOutput = output |
| 15 | let sent: Sent = try Fixture.decode("thin/sent") |
| 16 | let encoder = EquipoJSON.encoder; encoder.dateEncodingStrategy = .iso8601 |
| 17 | process.arguments = ["-u", "-c", Self.server, |
| 18 | AttachmentServer.attachment, |
| 19 | String(decoding: try encoder.encode(sent), as: UTF8.self)] |
| 20 | try process.run() |
| 21 | defer { process.terminate(); process.waitUntilExit() } |
| 22 | var port = Data() |
| 23 | while let byte = try output.fileHandleForReading.read(upToCount: 1), !byte.isEmpty { |
| 24 | if byte == Data([10]) { break }; port.append(byte) |
| 25 | } |
| 26 | let origin = try #require(URL(string: "http://127.0.0.1:" + String(decoding: port, as: UTF8.self))) |
| 27 | let client = EquipoClient(transport: URLSessionTransport(origin: origin, observe: { _ in }), token: "fixture-http") |
| 28 | let file = try AttachmentFile.prepare(AttachmentTests.image(width: 512, height: 512), name: "screen.png") |
| 29 | let progress = Mutex<[Double]>([]) |
| 30 | let attachment = try await client.upload(file) { value in progress.withLock { $0.append(value) } } |
| 31 | let response = try await client.send(EquipoClient.message("", attachments: [attachment.id])) |
| 32 | #expect(response.message.attachments?.first?.id == attachment.id) |
| 33 | #expect(try await client.attachmentData(attachment.id) == file.data) |
| 34 | var capped = APIRequest("GET", "/attachments/" + attachment.id, bearer: "fixture-http") |
| 35 | capped.maximumResponseBytes = 1 |
| 36 | await #expect(throws: EquipoAPIError.tooLarge) { try await URLSessionTransport(origin: origin, observe: { _ in }).send(capped) } |
| 37 | var redirect = APIRequest("POST", "/redirect", body: file.data, bearer: "fixture-http") |
| 38 | redirect.uploadProgress = UploadProgress { _ in } |
| 39 | let refused = try await URLSessionTransport(origin: origin, observe: { _ in }).send(redirect) |
| 40 | #expect(refused.status == 307) |
| 41 | #expect(progress.withLock { $0.contains { $0 > 0 && $0 <= 1 } }) |
| 42 | } |
| 43 | |
| 44 | static let server = #""" |
| 45 | import http.server,json,sys |
| 46 | attachment=json.loads(sys.argv[1]); sent=json.loads(sys.argv[2]) |
| 47 | uploaded=b''; delivered=b'' |
| 48 | class Handler(http.server.BaseHTTPRequestHandler): |
| 49 | def log_message(self,*args): pass |
| 50 | def answer(self,status,data,kind='application/json'): |
| 51 | self.send_response(status); self.send_header('Content-Type',kind) |
| 52 | self.send_header('Content-Length',str(len(data))); self.end_headers(); self.wfile.write(data) |
| 53 | def do_POST(self): |
| 54 | global uploaded,delivered |
| 55 | body=self.rfile.read(int(self.headers.get('Content-Length','0'))) |
| 56 | if self.headers.get('Authorization')!='Bearer fixture-http' or self.headers.get('Cookie'): |
| 57 | return self.answer(403,b'{}') |
| 58 | if self.path=='/api/v1/redirect': |
| 59 | self.send_response(307); self.send_header('Location','/api/v1/attachments'); self.send_header('Content-Length','0'); self.end_headers(); return |
| 60 | if self.path=='/api/v1/attachments': |
| 61 | if self.headers.get('Content-Type')!='image/png' or not body.startswith(bytes([137])+b'PNG'): |
| 62 | return self.answer(415,b'{}') |
| 63 | uploaded=body |
| 64 | return self.answer(201,json.dumps(attachment).encode()) |
| 65 | if self.path=='/api/v1/messages': |
| 66 | message=json.loads(body) |
| 67 | if message.get('attachments')!=[attachment['id']] or not uploaded: |
| 68 | return self.answer(422,b'{}') |
| 69 | delivered=uploaded |
| 70 | sent['message']['attachments']=[attachment] |
| 71 | return self.answer(201,json.dumps(sent).encode()) |
| 72 | self.answer(404,b'{}') |
| 73 | def do_GET(self): |
| 74 | if self.headers.get('Authorization')!='Bearer fixture-http': |
| 75 | return self.answer(403,b'{}') |
| 76 | if self.path=='/api/v1/attachments/'+attachment['id']: |
| 77 | return self.answer(200,delivered,'image/png') |
| 78 | self.answer(404,b'{}') |
| 79 | server=http.server.HTTPServer(('127.0.0.1',0),Handler) |
| 80 | print(server.server_address[1],flush=True) |
| 81 | server.serve_forever() |
| 82 | """# |
| 83 | } |
| 84 | #endif |
| 85 | |