Modern Apps git

xtool.git

Public
git clone https://git.maproj.org/xtool.git
main ▾

xtool.git / Tests / XToolTests / DispatchInputTests.swift

DispatchInputTests.swift193 lines · 8.0 KiBRaw
1@testable import XUtils
2import XCLIUtils
3import CustomDump
4import Foundation
5import Testing
6
7@Suite(.timeLimit(.minutes(1)))
8struct DispatchInputTests {
9 @Test
10 func commandInputReadsLinesAcrossDispatchBatches() async throws {
11 let pipe = Pipe()
12 let descriptor = FileDescriptor(rawValue: pipe.fileHandleForReading.fileDescriptor)
13 try pipe.fileHandleForWriting.write(contentsOf: Data("abfirst\r\n\nlast".utf8))
14 try pipe.fileHandleForWriting.close()
15 try await withReader(descriptor: descriptor, chunkSize: 2) { reader async throws in
16 let input = CommandInput(read: { try await reader.read(upTo: $0) })
17 #expect(try await input.read(upTo: .bytes(2)) == Data("ab".utf8))
18 #expect(try await input.readLine() == "first")
19 #expect(try await input.readLine() == "")
20 #expect(try await input.readLine() == "last")
21 #expect(try await input.read() == nil)
22 }
23 }
24
25 @Test
26 func pipeDeliversShortChunksBeforeEOF() async throws {
27 let pipe = Pipe()
28 let descriptor = FileDescriptor(rawValue: pipe.fileHandleForReading.fileDescriptor)
29 let flags = fcntl(descriptor.rawValue, F_GETFL)
30 try await withReader(descriptor: descriptor) { reader in
31 for bytes in [Data("first\n".utf8), Data([0, 255, 128])] {
32 try pipe.fileHandleForWriting.write(contentsOf: bytes)
33 let chunk = try await reader.read()
34 expectNoDifference(chunk, bytes)
35 }
36 try pipe.fileHandleForWriting.close()
37 #expect(try await reader.read() == nil)
38 #expect(try await reader.read() == nil)
39 }
40 #expect(fcntl(descriptor.rawValue, F_GETFL) == flags)
41 }
42
43 @Test
44 func pipePreservesBytesAcrossBatches() async throws {
45 let pipe = Pipe()
46 let descriptor = FileDescriptor(rawValue: pipe.fileHandleForReading.fileDescriptor)
47 let bytes = Data((0..<1027).map { UInt8(truncatingIfNeeded: $0) })
48 try pipe.fileHandleForWriting.write(contentsOf: bytes)
49 try pipe.fileHandleForWriting.close()
50 try await withReader(descriptor: descriptor, chunkSize: 64) { reader in
51 var received = Data()
52 while let chunk = try await reader.read() {
53 #expect(!chunk.isEmpty)
54 #expect(chunk.count <= 64)
55 received.append(chunk)
56 }
57 expectNoDifference(received, bytes)
58 }
59 }
60
61 @Test(arguments: [false, true])
62 @available(anyAppleOS 26.0, *)
63 func closeFinishesBeforeOrDuringRead(pendingRead: Bool) async throws {
64 let pipe = Pipe()
65 let descriptor = FileDescriptor(rawValue: pipe.fileHandleForReading.fileDescriptor)
66 let flags = fcntl(descriptor.rawValue, F_GETFL)
67 try await withReader(descriptor: descriptor) { reader async throws in
68 if pendingRead {
69 let reading = Task.immediate { try await reader.read() }
70 defer { reading.cancel() }
71 await reader.close()
72 #expect(try await reading.value == nil)
73 } else {
74 await reader.close()
75 }
76 #expect(try await reader.read() == nil)
77 await reader.close()
78 }
79 #expect(fcntl(descriptor.rawValue, F_GETFL) == flags)
80 }
81
82 @Test
83 func nullInputClosesAfterEOF() async throws {
84 let descriptor = try FileDescriptor.open("/dev/null", .readOnly)
85 defer { try? descriptor.close() }
86 try await withReader(descriptor: descriptor) { reader async throws in
87 #expect(try await reader.read() == nil)
88 await reader.close()
89 #expect(try await reader.read() == nil)
90 }
91 #expect(fcntl(descriptor.rawValue, F_GETFL) != -1)
92 }
93
94 @Test
95 func readErrorSurvivesClose() async throws {
96 let descriptor = try FileDescriptor.open("/dev/null", .writeOnly)
97 defer { try? descriptor.close() }
98 try await withReader(descriptor: descriptor) { reader in
99 await #expect(throws: Errno.badFileDescriptor) { try await reader.read() }
100 await reader.close()
101 await #expect(throws: Errno.badFileDescriptor) { try await reader.read() }
102 }
103 }
104
105 @Test
106 func invalidDescriptorFailsDuringInitOrRead() async throws {
107 // DispatchIO can report initialization failure before or after init returns.
108 await #expect(throws: Errno.badFileDescriptor) {
109 try await withReader(descriptor: FileDescriptor(rawValue: -1)) { reader in
110 _ = try await reader.read()
111 }
112 }
113 }
114
115 @Test
116 func fileReadsAreBoundedAndPreserveAllBytes() async throws {
117 let path = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
118 defer { try? FileManager.default.removeItem(at: path) }
119 let bytes = Data((0..<10_003).map { UInt8(truncatingIfNeeded: $0) })
120 try bytes.write(to: path)
121 let descriptor = try FileDescriptor.open(FilePath(path.path), .readOnly)
122 defer { try? descriptor.close() }
123 try await withReader(descriptor: descriptor, chunkSize: 1024) { reader in
124 var received = Data()
125 while let chunk = try await reader.read() {
126 #expect(!chunk.isEmpty)
127 #expect(chunk.count <= 1024)
128 received.append(chunk)
129 }
130 expectNoDifference(received, bytes)
131 #expect(try await reader.read() == nil)
132 }
133 }
134
135 @Test
136 func idleConsumerDoesNotStartAnotherBatch() async throws {
137 let path = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
138 defer { try? FileManager.default.removeItem(at: path) }
139 try Data(repeating: 255, count: 16 * 1024).write(to: path)
140 let descriptor = try FileDescriptor.open(FilePath(path.path), .readOnly)
141 defer { try? descriptor.close() }
142 try await withReader(descriptor: descriptor, chunkSize: 1024) { reader in
143 #expect(try await reader.read() != nil)
144 // Allow any unintended read-ahead to run while the consumer is idle.
145 try await Task.sleep(for: .milliseconds(20))
146 await reader.close()
147 let offset = try descriptor.seek(offset: 0, from: .current)
148 #expect(offset > 0)
149 #expect(offset <= 1024)
150 }
151 }
152
153 @Test
154 func deinitClosesPendingIOAndRestoresDescriptor() async throws {
155 let pipe = Pipe()
156 let descriptor = FileDescriptor(rawValue: pipe.fileHandleForReading.fileDescriptor)
157 let flags = fcntl(descriptor.rawValue, F_GETFL)
158 weak var weakReader: DispatchInput?
159 do {
160 let reader: DispatchInput = try DispatchInput(fileDesciptor: descriptor)
161 weakReader = reader
162 try pipe.fileHandleForWriting.write(contentsOf: Data("a".utf8))
163 let chunk = try await withInputTestTimeout {
164 try await reader.read()
165 } cleanup: { [reader] in
166 await reader.close()
167 }
168 expectNoDifference(chunk, Data("a".utf8))
169 #expect(fcntl(descriptor.rawValue, F_GETFL) & O_NONBLOCK != 0)
170 }
171 #expect(weakReader == nil)
172 // poll for channel.close() to finish
173 let deadline = ContinuousClock.now + .seconds(2)
174 while fcntl(descriptor.rawValue, F_GETFL) != flags {
175 try #require(ContinuousClock.now < deadline, "Timed out waiting for input operation")
176 try await Task.sleep(for: .milliseconds(1))
177 }
178 }
179
180 private func withReader(
181 descriptor: FileDescriptor,
182 chunkSize: Int = DispatchInput.defaultChunkSize,
183 operation: (DispatchInput) async throws -> Void,
184 ) async throws {
185 let reader = try DispatchInput(fileDesciptor: descriptor, chunkSize: chunkSize)
186 defer { await reader.close() }
187 try await withInputTestTimeout {
188 try await operation(reader)
189 } cleanup: {
190 await reader.close()
191 }
192 }
193}