-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathURLSessionHTTPClientTests.swift
More file actions
640 lines (544 loc) · 21.6 KB
/
URLSessionHTTPClientTests.swift
File metadata and controls
640 lines (544 loc) · 21.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
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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
import Foundation
#if canImport(FoundationNetworking)
import FoundationNetworking
#endif
import Testing
import HTTPTypes
@testable import Simplicity
// MARK: - Tests
@Suite("URLSessionClient Tests")
struct URLSessionClientTests {
let baseURL = URL(string: "https://example.com/api")!
@Test
func testSuccessDecoding_returnsModel() async throws {
// Arrange
let expected = SuccessModel(value: "ok")
let client = makeClient(baseURL: baseURL) { _, _ in
let data = try JSONEncoder().encode(expected)
return (data, HTTPResponse(status: .ok, headerFields: [.contentType: "application/json"]))
}
// Act
let response = try await client.send(GetSuccessRequest())
// Assert
let model = try JSONDecoder().decode(SuccessModel.self, from: response.body)
#expect(model == expected)
}
@Test
func testFailureDecoding_returnsErrorPayload() async throws {
// Arrange
let expected = ErrorModel(message: "bad")
let client = makeClient(baseURL: baseURL) { _, _ in
let data = try JSONEncoder().encode(expected)
return (data, HTTPResponse(status: .badRequest, headerFields: [.contentType: "application/json"]))
}
// Act
let response = try await client.send(GetSuccessRequest())
// Assert
let err = try JSONDecoder().decode(ErrorModel.self, from: response.body)
#expect(err == expected)
}
@Test
func testRequestBodyNoneWhenRequestBodyIsNever() async throws {
// Arrange
let client = makeClient(baseURL: baseURL) { _, body in
#expect(body == nil)
return (Data(), HTTPResponse(status: .ok))
}
// Act
_ = try await client.send(GetSuccessRequest())
}
@Test
func testBaseURLComposition_usesClientBaseURLAndPath() async throws {
// Arrange
let client = makeClient(baseURL: baseURL) { request, _ in
let url = reconstructURL(from: request)
#expect(url == "https://example.com/api/test/success")
return (Data(), HTTPResponse(status: .ok))
}
// Act
_ = try await client.send(GetSuccessRequest())
}
@Test
func testSpecialization_FailureIsNever_allowsSuccessOnly() async throws {
// Arrange
let expected = SuccessModel(value: "ok")
let client = makeClient(baseURL: baseURL) { _, _ in
let data = try JSONEncoder().encode(expected)
return (data, HTTPResponse(status: .ok))
}
// Act
let response = try await client.send(SuccessOnlyRequest())
let model = try response.decodeSuccessBody()
// Assert
#expect(model == expected)
}
@Test
func testSpecialization_SuccessIsNever_allowsFailureOnly() async throws {
// Arrange
let expected = ErrorModel(message: "nope")
let client = makeClient(baseURL: baseURL) { _, _ in
let data = try JSONEncoder().encode(expected)
return (data, HTTPResponse(status: .badRequest))
}
// Act
let response = try await client.send(FailureOnlyRequest())
let err = try response.decodeFailureBody()
// Assert
#expect(err == expected)
}
@Test
func testMiddlewareNonClientError_isWrappedAsMiddlewareAndNotNested() async throws {
// Arrange
enum DummyError: Error, Equatable { case boom }
let throwingMiddleware = MiddlewareSpy(thrownError: DummyError.boom)
let client = makeClient(baseURL: baseURL, middlewares: [throwingMiddleware]) { _, _ in
Issue.record("Handler should not be called when middleware throws")
return (Data(), HTTPResponse(status: .ok))
}
// Act
do {
_ = try await client.send(GetSuccessRequest())
Issue.record("Expected to throw, but succeeded")
} catch {
// Assert: should be wrapped as .middleware with underlying DummyError
switch error {
case .middleware(let mw, let underlyingError):
#expect((mw as? MiddlewareSpy) === throwingMiddleware)
#expect((underlyingError as? DummyError) == .boom)
assertNoNestedClientError(error)
default:
Issue.record("Expected ClientError.middleware, got: \(error)")
}
}
}
@Test
func testMiddlewareClientError_isNotWrapped() async throws {
// Arrange
let middleware = MiddlewareSpy(thrownError: ClientError.invalidResponse("forced"))
let client = makeClient(baseURL: baseURL, middlewares: [middleware]) { _, _ in
Issue.record("Handler should not be called when middleware throws")
return (Data(), HTTPResponse(status: .ok))
}
// Act
do {
_ = try await client.send(GetSuccessRequest())
Issue.record("Expected to throw, but succeeded")
} catch {
// Assert: should be the exact same ClientError, not wrapped
switch error {
case .invalidResponse(let message):
#expect(message == "forced")
assertNoNestedClientError(error)
default:
Issue.record("Expected ClientError.invalidResponse, got: \(error)")
}
}
}
@Test
func testURLSessionURLError_isWrappedAsTransport() async throws {
// Arrange
let client = makeClient(baseURL: baseURL) { _, _ in
throw URLError(.badServerResponse)
}
// Act
do {
_ = try await client.send(GetSuccessRequest())
Issue.record("Expected to throw, but succeeded")
} catch {
// Assert
switch error {
case .transport(let urlError):
#expect(urlError.code == .badServerResponse)
assertNoNestedClientError(error)
default:
Issue.record("Expected ClientError.transport, got: \(error)")
}
}
}
@Test
func testUnusualStatusCode_returnsResponseWithInvalidKind() async throws {
// Arrange
let client = makeClient(baseURL: baseURL) { _, _ in
(Data(), HTTPResponse(status: HTTPResponse.Status(code: 999)))
}
// Act — with Apple's HTTPResponse.Status, any status code is valid
let response = try await client.send(GetSuccessRequest())
// Assert — status code 999 has kind .invalid
#expect(response.status.code == 999)
#expect(response.status.kind == .invalid)
}
// MARK: - Assertions
private func assertNoNestedClientError(
_ error: ClientError,
sourceLocation: SourceLocation = SourceLocation(
fileID: #fileID,
filePath: #filePath,
line: #line,
column: #column
)
) {
switch error {
case .middleware(_, let underlying):
#expect(!(underlying is ClientError), "ClientError.middleware should not wrap a ClientError")
case .encodingError(_, let underlying):
#expect(
!(underlying is ClientError),
"ClientError.encodingError should not wrap a ClientError",
sourceLocation: sourceLocation
)
case .unknown(_, let underlying):
#expect(
!(underlying is ClientError),
"ClientError.unknown should not wrap a ClientError",
sourceLocation: sourceLocation
)
default:
break
}
}
}
// MARK: - Helpers
private func makeClient(
baseURL: URL,
middlewares: [any Middleware] = [],
handler: @escaping @Sendable (HTTPRequest, Data?) async throws -> (Data, HTTPResponse)
) -> URLSessionClient {
URLSessionClient(
transport: MockTransport(handler: handler),
baseURL: baseURL,
middlewares: middlewares
)
}
/// Reconstructs a URL string from an HTTPRequest's components for test assertions.
private func reconstructURL(from request: HTTPRequest) -> String {
var string = ""
if let scheme = request.scheme {
string += scheme + "://"
}
if let authority = request.authority {
string += authority
}
if let path = request.path {
string += path
}
return string
}
// MARK: - Test Requests
private struct SuccessModel: Codable, Sendable, Equatable { let value: String }
private struct ErrorModel: Codable, Sendable, Equatable { let message: String }
private struct GetSuccessRequest: Request {
typealias RequestBody = Never
typealias SuccessResponseBody = SuccessModel
typealias FailureResponseBody = ErrorModel
static var operationID: String { "success" }
var method: HTTPRequest.Method { .get }
var path: String { "/test/success" }
var headerFields: HTTPFields { HTTPFields() }
var queryItems: [URLQueryItem] { [] }
func decodeSuccessBody(from data: Data) throws -> SuccessModel {
try JSONDecoder().decode(SuccessModel.self, from: data)
}
func decodeFailureBody(from data: Data) throws -> ErrorModel {
try JSONDecoder().decode(ErrorModel.self, from: data)
}
}
private struct PostWithBodyRequest: Request {
typealias RequestBody = SuccessModel
typealias SuccessResponseBody = SuccessModel
typealias FailureResponseBody = ErrorModel
static var operationID: String { "body" }
var method: HTTPRequest.Method { .post }
var path: String { "/test/body" }
var headerFields: HTTPFields { [.contentType: "application/json"] }
var queryItems: [URLQueryItem] { [] }
var body: SuccessModel
func encodeBody() throws -> Data? {
try JSONEncoder().encode(body)
}
func decodeSuccessBody(from data: Data) throws -> SuccessModel {
try JSONDecoder().decode(SuccessModel.self, from: data)
}
func decodeFailureBody(from data: Data) throws -> ErrorModel {
try JSONDecoder().decode(ErrorModel.self, from: data)
}
}
private struct FailureOnlyRequest: Request {
typealias RequestBody = Never
typealias SuccessResponseBody = Never
typealias FailureResponseBody = ErrorModel
static var operationID: String { "failure" }
var method: HTTPRequest.Method { .get }
var path: String { "/test/failure-only" }
var headerFields: HTTPFields { HTTPFields() }
var queryItems: [URLQueryItem] { [] }
func encodeBody() throws -> Data? { nil }
func decodeSuccessBody(from data: Data) throws -> Never {
fatalError("should not decode success for FailureOnlyRequest")
}
func decodeFailureBody(from data: Data) throws -> ErrorModel {
try JSONDecoder().decode(ErrorModel.self, from: data)
}
}
private struct SuccessOnlyRequest: Request {
typealias RequestBody = Never
typealias SuccessResponseBody = SuccessModel
typealias FailureResponseBody = Never
static var operationID: String { "success-only" }
var method: HTTPRequest.Method { .get }
var path: String { "/test/success-only" }
var headerFields: HTTPFields { HTTPFields() }
var queryItems: [URLQueryItem] { [] }
func encodeBody() throws -> Data? { nil }
func decodeSuccessBody(from data: Data) throws -> SuccessModel {
try JSONDecoder().decode(SuccessModel.self, from: data)
}
func decodeFailureBody(from data: Data) throws -> Never {
fatalError("should not decode failure for SuccessOnlyRequest")
}
}
// MARK: - Decoding Error Tests
@Suite("Response Decoding Error Tests")
struct ResponseDecodingErrorTests {
@Test
func testDecodeSuccessBody_throwsDecodingError_withResponseBody() throws {
// Arrange — response body is valid JSON but wrong shape for SuccessModel
let mismatchedBody = Data("{\"unexpected\":\"field\"}".utf8)
let response = Response<SuccessModel, ErrorModel>(
httpResponse: HTTPResponse(status: .ok),
url: URL(string: "https://example.com/test")!,
body: mismatchedBody,
successBodyDecoder: { data in
try JSONDecoder().decode(SuccessModel.self, from: data)
},
failureBodyDecoder: { data in
try JSONDecoder().decode(ErrorModel.self, from: data)
}
)
// Act & Assert
do {
_ = try response.decodeSuccessBody()
Issue.record("Expected decodingError to be thrown")
} catch let error as ClientError {
guard case let .decodingError(type, responseBody, underlyingError) = error else {
Issue.record("Expected ClientError.decodingError, got: \(error)")
return
}
#expect(type == "SuccessModel")
#expect(responseBody == mismatchedBody)
#expect(underlyingError is DecodingError)
}
}
@Test
func testDecodeFailureBody_throwsDecodingError_withResponseBody() throws {
// Arrange — response body is not valid JSON at all
let invalidBody = Data("not json".utf8)
let response = Response<SuccessModel, ErrorModel>(
httpResponse: HTTPResponse(status: .badRequest),
url: URL(string: "https://example.com/test")!,
body: invalidBody,
successBodyDecoder: { data in
try JSONDecoder().decode(SuccessModel.self, from: data)
},
failureBodyDecoder: { data in
try JSONDecoder().decode(ErrorModel.self, from: data)
}
)
// Act & Assert
do {
_ = try response.decodeFailureBody()
Issue.record("Expected decodingError to be thrown")
} catch let error as ClientError {
guard case let .decodingError(type, responseBody, underlyingError) = error else {
Issue.record("Expected ClientError.decodingError, got: \(error)")
return
}
#expect(type == "ErrorModel")
#expect(responseBody == invalidBody)
#expect(underlyingError is DecodingError)
}
}
@Test
func testDecodingError_errorDescription_includesResponseBody() throws {
let body = Data("{\"wrong\":true}".utf8)
let error = ClientError.decodingError(
type: "SuccessModel",
responseBody: body,
underlyingError: DecodingError.keyNotFound(
AnyCodingKey(stringValue: "value"),
.init(codingPath: [], debugDescription: "No value for key 'value'")
)
)
let description = error.errorDescription ?? ""
#expect(description.contains("Failed to decode SuccessModel"))
#expect(description.contains("{\"wrong\":true}"))
}
}
/// A type-erased CodingKey for test assertions.
private struct AnyCodingKey: CodingKey {
var stringValue: String
var intValue: Int?
init(stringValue: String) { self.stringValue = stringValue; self.intValue = nil }
init?(intValue: Int) { self.stringValue = "\(intValue)"; self.intValue = intValue }
}
// MARK: - Cache Tests
@Suite("URLSessionClient Cache Tests")
struct URLSessionClientCacheTests {
let baseURL = URL(string: "https://example.com/api")!
@Test
func testSetCachedResponse_storesInCache() async throws {
// Arrange
let client = makeCacheableClient(baseURL: baseURL)
let expected = CacheableModel(id: 1, name: "cached")
// Act
try await client.setCachedResponse(expected, for: CacheableRequest())
// Assert - retrieve and verify
let cached = try await client.cachedResponse(for: CacheableRequest())
let decoded = try cached.decodeSuccessBody()
#expect(decoded == expected)
}
@Test
func testCachedResponse_throwsCacheMiss_whenNotCached() async throws {
// Arrange
let client = makeCacheableClient(baseURL: baseURL)
// Act & Assert
do {
_ = try await client.cachedResponse(for: CacheableRequest())
Issue.record("Expected cacheMiss error")
} catch {
guard case .cacheMiss = error else {
Issue.record("Expected cacheMiss, got: \(error)")
return
}
}
}
@Test
func testRemoveCachedResponse_clearsCache() async throws {
// Arrange
let client = makeCacheableClient(baseURL: baseURL)
let model = CacheableModel(id: 2, name: "to-remove")
try await client.setCachedResponse(model, for: CacheableRequest())
// Verify it's cached
_ = try await client.cachedResponse(for: CacheableRequest())
// Act
await client.removeCachedResponse(for: CacheableRequest())
// Assert - should now throw cacheMiss
do {
_ = try await client.cachedResponse(for: CacheableRequest())
Issue.record("Expected cacheMiss error after removal")
} catch {
guard case .cacheMiss = error else {
Issue.record("Expected cacheMiss, got: \(error)")
return
}
}
}
@Test
func testCachedResponse_preservesStatusCode() async throws {
// Arrange
let client = makeCacheableClient(baseURL: baseURL)
let model = CacheableModel(id: 3, name: "with-status")
// Act
try await client.setCachedResponse(model, for: CacheableRequest(), status: .created)
let cached = try await client.cachedResponse(for: CacheableRequest())
// Assert
#expect(cached.status == .created)
}
@Test
func testCachedResponse_preservesHeaders() async throws {
// Arrange
let client = makeCacheableClient(baseURL: baseURL)
let model = CacheableModel(id: 4, name: "with-headers")
var headerFields = HTTPFields()
headerFields[.contentType] = "application/json"
headerFields[HTTPField.Name("X-Custom")!] = "value"
// Act
try await client.setCachedResponse(model, for: CacheableRequest(), headerFields: headerFields)
let cached = try await client.cachedResponse(for: CacheableRequest())
// Assert
#expect(cached.headerFields[HTTPField.Name("X-Custom")!] == "value")
}
@Test
func testCachedResponse_differentQueryParams_differentCacheEntries() async throws {
// Arrange
let client = makeCacheableClient(baseURL: baseURL)
let model1 = CacheableModel(id: 10, name: "query1")
let model2 = CacheableModel(id: 20, name: "query2")
// Act - cache with different query params
try await client.setCachedResponse(model1, for: CacheableRequestWithQuery(filter: "a"))
try await client.setCachedResponse(model2, for: CacheableRequestWithQuery(filter: "b"))
// Assert - each query should have its own cache entry
let cached1 = try await client.cachedResponse(for: CacheableRequestWithQuery(filter: "a"))
let cached2 = try await client.cachedResponse(for: CacheableRequestWithQuery(filter: "b"))
#expect(try cached1.decodeSuccessBody() == model1)
#expect(try cached2.decodeSuccessBody() == model2)
}
@Test
func testClearNetworkCache_clearsAllCachedResponses() async throws {
// Arrange
let client = makeCacheableClient(baseURL: baseURL)
let model = CacheableModel(id: 5, name: "to-clear")
try await client.setCachedResponse(model, for: CacheableRequest())
// Act
await client.clearNetworkCache()
// Assert - should now throw cacheMiss
do {
_ = try await client.cachedResponse(for: CacheableRequest())
Issue.record("Expected cacheMiss error after clear")
} catch {
guard case .cacheMiss = error else {
Issue.record("Expected cacheMiss, got: \(error)")
return
}
}
}
}
// MARK: - Cache Test Helpers
private func makeCacheableClient(baseURL: URL) -> URLSessionClient {
#if canImport(FoundationNetworking)
let cache = URLCache(memoryCapacity: 10_000_000, diskCapacity: 0, diskPath: nil)
#else
let cache = URLCache(memoryCapacity: 10_000_000, diskCapacity: 0)
#endif
return URLSessionClient(
urlCache: cache,
baseURL: baseURL,
middlewares: []
)
}
private struct CacheableModel: Codable, Sendable, Equatable {
let id: Int
let name: String
}
private struct CacheableRequest: Request {
typealias RequestBody = Never
typealias SuccessResponseBody = CacheableModel
typealias FailureResponseBody = ErrorModel
static var operationID: String { "cacheable" }
var method: HTTPRequest.Method { .get }
var path: String { "/test/cacheable" }
var headerFields: HTTPFields { HTTPFields() }
var queryItems: [URLQueryItem] { [] }
func decodeSuccessBody(from data: Data) throws -> CacheableModel {
try JSONDecoder().decode(CacheableModel.self, from: data)
}
func decodeFailureBody(from data: Data) throws -> ErrorModel {
try JSONDecoder().decode(ErrorModel.self, from: data)
}
}
private struct CacheableRequestWithQuery: Request {
typealias RequestBody = Never
typealias SuccessResponseBody = CacheableModel
typealias FailureResponseBody = ErrorModel
let filter: String
static var operationID: String { "cacheable-query" }
var method: HTTPRequest.Method { .get }
var path: String { "/test/cacheable" }
var headerFields: HTTPFields { HTTPFields() }
var queryItems: [URLQueryItem] { [URLQueryItem(name: "filter", value: filter)] }
func decodeSuccessBody(from data: Data) throws -> CacheableModel {
try JSONDecoder().decode(CacheableModel.self, from: data)
}
func decodeFailureBody(from data: Data) throws -> ErrorModel {
try JSONDecoder().decode(ErrorModel.self, from: data)
}
}