-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathDownloadDelegateTests.swift
More file actions
243 lines (197 loc) · 10.6 KB
/
DownloadDelegateTests.swift
File metadata and controls
243 lines (197 loc) · 10.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
import Foundation
import Logging
import Testing
@testable import xcodeinstall
#if canImport(FoundationNetworking)
import FoundationNetworking
#endif
// MARK: - DownloadDelegate Tests
@Suite("DownloadDelegate Tests", .serialized)
struct DownloadDelegateTests {
// MARK: - Test Environment
let log = Logger(label: "DownloadDelegateTests")
let fileManager = FileManager.default
/// Creates a DownloadDelegate backed by an AsyncThrowingStream, returning both.
/// The stream can be consumed to verify what the delegate yielded/threw.
func makeDelegate(
dstPath: URL,
fileHandler: FileHandlerProtocol = MockedFileHandler(),
totalBytes: Int64 = 1000,
startTime: Date = Date.now
) -> (DownloadDelegate, AsyncThrowingStream<DownloadProgress, Error>) {
var capturedContinuation: AsyncThrowingStream<DownloadProgress, Error>.Continuation!
let stream = AsyncThrowingStream<DownloadProgress, Error> { continuation in
capturedContinuation = continuation
}
let delegate = DownloadDelegate(
continuation: capturedContinuation,
totalBytes: totalBytes,
startTime: startTime,
dstPath: dstPath,
fileHandler: fileHandler,
log: log
)
return (delegate, stream)
}
}
// MARK: - didFinishDownloadingTo Tests
extension DownloadDelegateTests {
@Test("Successful file move via didFinishDownloadingTo")
func testDidFinishDownloadingTo_movesFile() async throws {
try await withTemporaryDirectory { tempDir in
// Given — a source file at a temp location and a destination path
let srcFile = tempDir.appendingPathComponent("source.xip")
let dstFile = tempDir.appendingPathComponent("destination.xip")
// Pad content to exceed 10_000 bytes so it doesn't trigger error page detection
let paddedContent = String(repeating: "x", count: 10_001)
try paddedContent.data(using: .utf8)!.write(to: srcFile)
let mockFileHandler = MockedFileHandler()
let (delegate, stream) = makeDelegate(dstPath: dstFile, fileHandler: mockFileHandler)
let session = URLSession(configuration: .ephemeral)
defer { session.invalidateAndCancel() }
// When — call didFinishDownloadingTo with the source file location
let dummyTask = session.downloadTask(with: URL(string: "https://example.com")!)
delegate.urlSession(session, downloadTask: dummyTask, didFinishDownloadingTo: srcFile)
// Then — the stream should finish without error
await #expect(throws: Never.self) {
for try await _ in stream {}
}
// Verify the file handler was asked to move from src to dst
#expect(mockFileHandler.moveSrc == srcFile)
#expect(mockFileHandler.moveDst == dstFile)
}
}
@Test("Error page detection with Error tag in small download")
func testDidFinishDownloadingTo_detectsErrorPage() async throws {
try await withTemporaryDirectory { tempDir in
// Given — a small file containing an error page marker
let srcFile = tempDir.appendingPathComponent("error_response.xml")
let errorContent = "<Error><Code>AccessDenied</Code></Error>"
try errorContent.data(using: .utf8)!.write(to: srcFile)
let dstFile = tempDir.appendingPathComponent("destination.xip")
let (delegate, stream) = makeDelegate(dstPath: dstFile)
let session = URLSession(configuration: .ephemeral)
defer { session.invalidateAndCancel() }
// When — call didFinishDownloadingTo with the error page file
let dummyTask = session.downloadTask(with: URL(string: "https://example.com")!)
delegate.urlSession(session, downloadTask: dummyTask, didFinishDownloadingTo: srcFile)
// Then — the stream should finish with authenticationRequired error
let error = await #expect(throws: DownloadError.self) {
for try await _ in stream {}
}
#expect(error == .authenticationRequired)
// The error page file should have been cleaned up
#expect(!fileManager.fileExists(atPath: srcFile.path))
}
}
@Test("AccessDenied string triggers error page detection")
func testDidFinishDownloadingTo_detectsAccessDenied() async throws {
try await withTemporaryDirectory { tempDir in
// Given — a small file containing "AccessDenied"
let srcFile = tempDir.appendingPathComponent("access_denied.txt")
let content = "AccessDenied"
try content.data(using: .utf8)!.write(to: srcFile)
let dstFile = tempDir.appendingPathComponent("destination.xip")
let (delegate, stream) = makeDelegate(dstPath: dstFile)
let session = URLSession(configuration: .ephemeral)
defer { session.invalidateAndCancel() }
// When
let dummyTask = session.downloadTask(with: URL(string: "https://example.com")!)
delegate.urlSession(session, downloadTask: dummyTask, didFinishDownloadingTo: srcFile)
// Then — should throw authenticationRequired
let error = await #expect(throws: DownloadError.self) {
for try await _ in stream {}
}
#expect(error == .authenticationRequired)
}
}
@Test("Sign in page triggers error page detection")
func testDidFinishDownloadingTo_detectsSignInPage() async throws {
try await withTemporaryDirectory { tempDir in
// Given — a small file containing Apple sign-in page marker
let srcFile = tempDir.appendingPathComponent("signin_page.html")
let content = "<html>Sign in to your Apple Account</html>"
try content.data(using: .utf8)!.write(to: srcFile)
let dstFile = tempDir.appendingPathComponent("destination.xip")
let (delegate, stream) = makeDelegate(dstPath: dstFile)
let session = URLSession(configuration: .ephemeral)
defer { session.invalidateAndCancel() }
// When
let dummyTask = session.downloadTask(with: URL(string: "https://example.com")!)
delegate.urlSession(session, downloadTask: dummyTask, didFinishDownloadingTo: srcFile)
// Then — should throw authenticationRequired
let error = await #expect(throws: DownloadError.self) {
for try await _ in stream {}
}
#expect(error == .authenticationRequired)
}
}
@Test("File move failure propagates error through stream")
func testDidFinishDownloadingTo_moveFailure() async throws {
try await withTemporaryDirectory { tempDir in
// Given — a source file and a file handler that will fail on move
let srcFile = tempDir.appendingPathComponent("source.xip")
let paddedContent = String(repeating: "x", count: 10_001)
try paddedContent.data(using: .utf8)!.write(to: srcFile)
let dstFile = tempDir.appendingPathComponent("destination.xip")
let mockFileHandler = MockedFileHandler()
let moveError = NSError(domain: "test", code: 42, userInfo: [NSLocalizedDescriptionKey: "disk full"])
mockFileHandler.nextMoveError = moveError
let (delegate, stream) = makeDelegate(dstPath: dstFile, fileHandler: mockFileHandler)
let session = URLSession(configuration: .ephemeral)
defer { session.invalidateAndCancel() }
// When — call didFinishDownloadingTo
let dummyTask = session.downloadTask(with: URL(string: "https://example.com")!)
delegate.urlSession(session, downloadTask: dummyTask, didFinishDownloadingTo: srcFile)
// Then — the stream should finish with the move error
let error = await #expect(throws: NSError.self) {
for try await _ in stream {}
}
#expect(error?.domain == "test")
#expect(error?.code == 42)
}
}
}
// MARK: - didCompleteWithError Tests
extension DownloadDelegateTests {
@Test("didCompleteWithError with error finishes stream with that error")
func testDidCompleteWithError_withError() async throws {
// Given
let dstFile = URL(fileURLWithPath: "/tmp/test_destination.xip")
let (delegate, stream) = makeDelegate(dstPath: dstFile)
let session = URLSession(configuration: .ephemeral)
defer { session.invalidateAndCancel() }
let downloadError = NSError(domain: NSURLErrorDomain, code: NSURLErrorTimedOut, userInfo: nil)
// When — call didCompleteWithError with an error
let dummyTask = session.downloadTask(with: URL(string: "https://example.com")!)
delegate.urlSession(session, task: dummyTask, didCompleteWithError: downloadError)
// Then — the stream should finish with that error
let error = await #expect(throws: NSError.self) {
for try await _ in stream {}
}
#expect(error?.domain == NSURLErrorDomain)
#expect(error?.code == NSURLErrorTimedOut)
}
@Test("didCompleteWithError with nil does not throw after successful download")
func testDidCompleteWithError_withNil() async throws {
try await withTemporaryDirectory { tempDir in
// Given — simulate the scenario where didFinishDownloadingTo already completed the stream
let srcFile = tempDir.appendingPathComponent("source.xip")
let paddedContent = String(repeating: "x", count: 10_001)
try paddedContent.data(using: .utf8)!.write(to: srcFile)
let dstFile = tempDir.appendingPathComponent("destination.xip")
let (delegate, stream) = makeDelegate(dstPath: dstFile)
let session = URLSession(configuration: .ephemeral)
defer { session.invalidateAndCancel() }
let dummyTask = session.downloadTask(with: URL(string: "https://example.com")!)
// When — first call didFinishDownloadingTo (which calls continuation.finish()),
// then call didCompleteWithError with nil (which should be a no-op)
delegate.urlSession(session, downloadTask: dummyTask, didFinishDownloadingTo: srcFile)
delegate.urlSession(session, task: dummyTask, didCompleteWithError: nil)
// Then — the stream should complete without error
await #expect(throws: Never.self) {
for try await _ in stream {}
}
}
}
}