This repository was archived by the owner on Sep 15, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathURLSessionHelperTests.swift
More file actions
420 lines (338 loc) · 16.3 KB
/
URLSessionHelperTests.swift
File metadata and controls
420 lines (338 loc) · 16.3 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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
import Foundation
import CryptoKit
import XCTest
import OHHTTPStubs
import OHHTTPStubsSwift
@testable import WordPressKit
class URLSessionHelperTests: XCTestCase {
var session: URLSession!
override func setUp() {
super.setUp()
session = .shared
}
override func tearDown() {
super.tearDown()
HTTPStubs.removeAllStubs()
XCTAssertEqual(session.debugNumberOfTaskData, 0)
}
func testConnectionError() async throws {
stub(condition: isPath("/hello")) { _ in
HTTPStubsResponse(error: URLError(.serverCertificateUntrusted))
}
let result = await session.perform(request: .init(url: URL(string: "https://wordpress.org/hello")!), errorType: TestError.self)
do {
_ = try result.get()
XCTFail("The above call should throw")
} catch let WordPressAPIError<TestError>.connection(error) {
XCTAssertEqual(error.code, URLError.Code.serverCertificateUntrusted)
} catch {
XCTFail("Unknown error: \(error)")
}
}
func test200() async throws {
stub(condition: isPath("/hello")) { _ in
HTTPStubsResponse(data: "success".data(using: .utf8)!, statusCode: 200, headers: nil)
}
let result = await session.perform(request: .init(url: URL(string: "https://wordpress.org/hello")!), errorType: TestError.self)
// The result is a successful result. This line should not throw
let response = try result.get()
XCTAssertEqual(String(data: response.body, encoding: .utf8), "success")
}
func testUnacceptable500() async {
stub(condition: isPath("/hello")) { _ in
HTTPStubsResponse(data: "Internal server error".data(using: .utf8)!, statusCode: 500, headers: nil)
}
let result = await session
.perform(request: .init(url: URL(string: "https://wordpress.org/hello")!), errorType: TestError.self)
switch result {
case let .failure(.unacceptableStatusCode(response, _)):
XCTAssertEqual(response.statusCode, 500)
default:
XCTFail("Got an unexpected result: \(result)")
}
}
func testAcceptable404() async throws {
stub(condition: isPath("/hello")) { _ in
HTTPStubsResponse(data: "Not found".data(using: .utf8)!, statusCode: 404, headers: nil)
}
let result = await session
.perform(
request: .init(url: URL(string: "https://wordpress.org/hello")!),
acceptableStatusCodes: [200...299, 400...499], errorType: TestError.self
)
// The result is a successful result. This line should not throw
let response = try result.get()
XCTAssertEqual(String(data: response.body, encoding: .utf8), "Not found")
}
func testParseError() async throws {
stub(condition: isPath("/hello")) { _ in
HTTPStubsResponse(data: "Not found".data(using: .utf8)!, statusCode: 404, headers: nil)
}
let result = await session
.perform(request: .init(url: URL(string: "https://wordpress.org/hello")!), errorType: TestError.self)
.mapUnacceptableStatusCodeError { response, _ in
XCTAssertEqual(response.statusCode, 404)
return .postNotFound
}
if case .failure(WordPressAPIError<TestError>.endpointError(.postNotFound)) = result {
// DO nothing
} else {
XCTFail("Unexpected result: \(result)")
}
}
func testParseSuccessAsJSON() async throws {
stub(condition: isPath("/hello")) { _ in
HTTPStubsResponse(jsonObject: ["title": "Hello Post"], statusCode: 200, headers: nil)
}
struct Post: Decodable {
var title: String
}
let result: WordPressAPIResult<Post, TestError> = await session
.perform(request: .init(url: URL(string: "https://wordpress.org/hello")!))
.decodeSuccess()
try XCTAssertEqual(result.get().title, "Hello Post")
}
func testProgressTracking() async throws {
stub(condition: isPath("/hello")) { _ in
HTTPStubsResponse(data: "success".data(using: .utf8)!, statusCode: 200, headers: nil)
}
let progress = Progress.discreteProgress(totalUnitCount: 20)
XCTAssertEqual(progress.completedUnitCount, 0)
XCTAssertEqual(progress.fractionCompleted, 0)
let _ = await session.perform(request: .init(url: URL(string: "https://wordpress.org/hello")!), fulfilling: progress, errorType: TestError.self)
XCTAssertEqual(progress.completedUnitCount, 20)
XCTAssertEqual(progress.fractionCompleted, 1)
}
func testProgressUpdateOnMainThread() async throws {
stub(condition: isPath("/hello")) { _ in
HTTPStubsResponse(data: "success".data(using: .utf8)!, statusCode: 200, headers: nil)
}
let progressReported = expectation(description: "Progress has been updated")
progressReported.assertForOverFulfill = false
let progress = Progress.discreteProgress(totalUnitCount: 20)
let observer = progress.observe(\.fractionCompleted, options: .new) { _, _ in
XCTAssertTrue(Thread.isMainThread)
progressReported.fulfill()
}
let _ = await session.perform(request: .init(url: URL(string: "https://wordpress.org/hello")!), fulfilling: progress, errorType: TestError.self)
await fulfillment(of: [progressReported], timeout: 0.3)
observer.invalidate()
}
func testCancellation() async throws {
// Give a slow HTTP request that takes 0.5 second to complete
stub(condition: isPath("/hello")) { _ in
let response = HTTPStubsResponse(data: "success".data(using: .utf8)!, statusCode: 200, headers: nil)
response.responseTime = 0.5
return response
}
// and cancelling it (in 0.1 second) before it completes
let progress = Progress.discreteProgress(totalUnitCount: 20)
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(100)) {
progress.cancel()
}
// The result should be an cancellation result
let result = await session.perform(request: .init(url: URL(string: "https://wordpress.org/hello")!), fulfilling: progress, errorType: TestError.self)
if case let .failure(.connection(urlError)) = result, urlError.code == .cancelled {
// Do nothing
} else {
XCTFail("Unexpected result: \(result)")
}
}
func testTaskCancellation() async throws {
// Give a slow HTTP request that takes 0.5 second to complete
stub(condition: isPath("/hello")) { _ in
let response = HTTPStubsResponse(data: "success".data(using: .utf8)!, statusCode: 200, headers: nil)
response.responseTime = 0.5
return response
}
let task = Task {
await session.perform(request: .init(url: URL(string: "https://wordpress.org/hello")!), errorType: TestError.self)
}
// and cancelling it (in 0.1 second) before it completes
try await Task.sleep(nanoseconds: 100_000_000)
task.cancel()
// The result should be an cancellation result
let result = await task.value
if case let .failure(.connection(urlError)) = result, urlError.code == .cancelled {
// Do nothing
} else {
XCTFail("Unexpected result: \(result)")
}
}
func testEncodingError() async {
let underlyingError = NSError(domain: "test", code: 123)
let builder = HTTPRequestBuilder(url: URL(string: "https://wordpress.org")!)
.method(.post)
.body(json: { throw underlyingError })
let result = await session.perform(request: builder, errorType: TestError.self)
if case let .failure(.requestEncodingFailure(underlyingError: error)) = result {
XCTAssertEqual(error as NSError, underlyingError)
} else {
XCTFail("Unexpected result: \(result)")
}
}
func testParsingError() async {
struct Model: Decodable {
var success: Bool
}
stub(condition: isPath("/hello")) { _ in
HTTPStubsResponse(data: "success".data(using: .utf8)!, statusCode: 200, headers: nil)
}
let result: WordPressAPIResult<Model, TestError> = await session
.perform(request: .init(url: URL(string: "https://wordpress.org/hello")!))
.decodeSuccess()
if case let .failure(.unparsableResponse(_, _, error)) = result {
XCTAssertTrue(error is DecodingError)
} else {
XCTFail("Unexpected result: \(result)")
}
}
func testMultipartForm() async throws {
var req: URLRequest?
stub(condition: isPath("/hello")) {
req = $0
return HTTPStubsResponse(data: "success".data(using: .utf8)!, statusCode: 200, headers: nil)
}
let builder = HTTPRequestBuilder(url: URL(string: "https://wordpress.org/hello")!)
.method(.post)
.body(form: [MultipartFormField(text: "value", name: "name", filename: nil)])
let _ = await session.perform(request: builder, errorType: TestError.self)
let request = try XCTUnwrap(req)
let boundary = try XCTUnwrap(
request
.value(forHTTPHeaderField: "Content-Type")?.split(separator: ";")
.map { $0.trimmingCharacters(in: .whitespaces) }
.reduce(into: [String: String]()) {
let pair = $1.split(separator: "=")
if pair.count == 2 {
$0[String(pair[0])] = String(pair[1])
}
}["boundary"]
)
let requestBody = try XCTUnwrap(request.httpBody ?? request.httpBodyStream?.readToEnd())
let expectedBody = "--\(boundary)\r\nContent-Disposition: form-data; name=\"name\"\r\n\r\nvalue\r\n--\(boundary)--\r\n"
XCTAssertEqual(String(data: requestBody, encoding: .utf8), expectedBody)
}
func testGetLargeData() async throws {
let file = try self.createLargeFile(megaBytes: 100)
defer {
try? FileManager.default.removeItem(at: file)
}
stub(condition: isPath("/hello")) { _ in
HTTPStubsResponse(fileURL: file, statusCode: 200, headers: nil)
}
let builder = HTTPRequestBuilder(url: URL(string: "https://wordpress.org/hello")!)
let response = try await session.perform(request: builder, errorType: TestError.self).get()
try XCTAssertEqual(
sha256(XCTUnwrap(InputStream(url: file))),
sha256(InputStream(data: response.body))
)
}
func testTempFileRemovedAfterMultipartUpload() async throws {
stub(condition: isPath("/upload")) { _ in
HTTPStubsResponse(data: "success".data(using: .utf8)!, statusCode: 200, headers: nil)
}
// Create a large file which will be uploaded. The file size needs to be larger than the hardcoded threshold of
// creating a temporary file for upload.
let file = try self.createLargeFile(megaBytes: 30)
defer {
try? FileManager.default.removeItem(at: file)
}
// Capture a list of files in temp dirs, before calling the upload function.
let tempFilesBeforeUpload = try existingMultipartFormTempFiles()
// Perform upload HTTP request
let builder = try HTTPRequestBuilder(url: URL(string: "https://wordpress.org/upload")!)
.method(.post)
.body(form: [MultipartFormField(fileAtPath: file.path, name: "file", filename: "file.txt", mimeType: "text/plain")])
let _ = await session.perform(request: builder, errorType: TestError.self)
// Capture a list of files in the temp dirs, after calling the upload function.
let tempFilesAfterUpload = try existingMultipartFormTempFiles()
// There should be no new files after the HTTP request returns. This assertion relies on an implementation detail
// where the multipart form content is put into a file in temp dirs.
let newFiles = tempFilesAfterUpload.subtracting(tempFilesBeforeUpload)
XCTAssertEqual(newFiles.count, 0)
}
func testTempFileRemovedAfterMultipartUploadError() async throws {
stub(condition: isPath("/upload")) { _ in
HTTPStubsResponse(error: URLError(.networkConnectionLost))
}
// Create a large file which will be uploaded. The file size needs to be larger than the hardcoded threshold of
// creating a temporary file for upload.
let file = try self.createLargeFile(megaBytes: 30)
defer {
try? FileManager.default.removeItem(at: file)
}
// Capture a list of files in temp dirs, before calling the upload function.
let tempFilesBeforeUpload = try existingMultipartFormTempFiles()
// Perform upload HTTP request
let builder = try HTTPRequestBuilder(url: URL(string: "https://wordpress.org/upload")!)
.method(.post)
.body(form: [MultipartFormField(fileAtPath: file.path, name: "file", filename: "file.txt", mimeType: "text/plain")])
let _ = await session.perform(request: builder, errorType: TestError.self)
// Capture a list of files in the temp dirs, after calling the upload function.
let tempFilesAfterUpload = try existingMultipartFormTempFiles()
// There should be no new files after the HTTP request returns. This assertion relies on an implementation detail
// where the multipart form content is put into a file in temp dirs.
let newFiles = tempFilesAfterUpload.subtracting(tempFilesBeforeUpload)
XCTAssertEqual(newFiles.count, 0)
}
// This functions finds temp files that are used for uploading multipart form.
// The implementation relies on an internal implementation detail of building multipart form content.
private func existingMultipartFormTempFiles() throws -> Set<String> {
let fm = FileManager.default
let files = try fm.contentsOfDirectory(atPath: fm.temporaryDirectory.path)
.filter { UUID(uuidString: $0) != nil }
return Set(files)
}
private func createLargeFile(megaBytes: Int) throws -> URL {
let file = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
.appendingPathComponent("large-file-\(UUID().uuidString).txt")
try Data(repeating: 46, count: 1024 * 1000 * megaBytes).write(to: file)
return file
}
private func sha256(_ stream: InputStream) -> SHA256Digest {
stream.open()
defer { stream.close() }
var hash = SHA256()
let maxLength = 50 * 1024
var buffer = [UInt8](repeating: 0, count: maxLength)
while stream.hasBytesAvailable {
let bytes = stream.read(&buffer, maxLength: maxLength)
let data = Data(bytesNoCopy: &buffer, count: bytes, deallocator: .none)
hash.update(data: data)
}
return hash.finalize()
}
}
class BackgroundURLSessionHelperTests: URLSessionHelperTests {
// swiftlint:disable weak_delegate
private var delegate: TestBackgroundURLSessionDelegate!
// swiftlint:enable weak_delegate
override func setUp() {
super.setUp()
delegate = TestBackgroundURLSessionDelegate()
session = URLSession(configuration: .default, delegate: delegate, delegateQueue: nil)
}
override func tearDown() {
super.tearDown()
if delegate.startedReceivingResponse {
XCTAssertTrue(delegate.completionCalled)
}
}
}
private class TestBackgroundURLSessionDelegate: BackgroundURLSessionDelegate {
var startedReceivingResponse = false
var completionCalled = false
override func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
startedReceivingResponse = true
super.urlSession(session, dataTask: dataTask, didReceive: data)
}
override func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
completionCalled = true
super.urlSession(session, task: task, didCompleteWithError: error)
}
}
private enum TestError: LocalizedError, Equatable {
case postNotFound
case serverFailure
}