-
-
Notifications
You must be signed in to change notification settings - Fork 7.5k
/
RequestTests.swift
1361 lines (1083 loc) · 51.1 KB
/
RequestTests.swift
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
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// RequestTests.swift
//
// Copyright (c) 2014-2020 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Alamofire
import Foundation
import XCTest
final class RequestResponseTestCase: BaseTestCase {
func testRequestResponse() {
// Given
let url = Endpoint.get.url
let expectation = expectation(description: "GET request should succeed: \(url)")
var response: DataResponse<Data?, AFError>?
// When
AF.request(url, parameters: ["foo": "bar"])
.response { resp in
response = resp
expectation.fulfill()
}
waitForExpectations(timeout: timeout)
// Then
XCTAssertNotNil(response?.request)
XCTAssertNotNil(response?.response)
XCTAssertNotNil(response?.data)
XCTAssertNil(response?.error)
}
func testRequestResponseWithProgress() {
// Given
let byteCount = 50 * 1024
let url = Endpoint.bytes(byteCount).url
let expectation = expectation(description: "Bytes download progress should be reported: \(url)")
var progressValues: [Double] = []
var response: DataResponse<Data?, AFError>?
// When
AF.request(url)
.downloadProgress { progress in
progressValues.append(progress.fractionCompleted)
}
.response { resp in
response = resp
expectation.fulfill()
}
waitForExpectations(timeout: timeout)
// Then
XCTAssertNotNil(response?.request)
XCTAssertNotNil(response?.response)
XCTAssertNotNil(response?.data)
XCTAssertNil(response?.error)
var previousProgress: Double = progressValues.first ?? 0.0
for progress in progressValues {
XCTAssertGreaterThanOrEqual(progress, previousProgress)
previousProgress = progress
}
if let lastProgressValue = progressValues.last {
XCTAssertEqual(lastProgressValue, 1.0)
} else {
XCTFail("last item in progressValues should not be nil")
}
}
func testPOSTRequestWithUnicodeParameters() {
// Given
let parameters = ["french": "français",
"japanese": "日本語",
"arabic": "العربية",
"emoji": "😃"]
let expectation = expectation(description: "request should succeed")
var response: DataResponse<TestResponse, AFError>?
// When
AF.request(.method(.post), parameters: parameters)
.responseDecodable(of: TestResponse.self) { closureResponse in
response = closureResponse
expectation.fulfill()
}
waitForExpectations(timeout: timeout)
// Then
XCTAssertNotNil(response?.request)
XCTAssertNotNil(response?.response)
XCTAssertNotNil(response?.data)
if let form = response?.result.success?.form {
XCTAssertEqual(form["french"], parameters["french"])
XCTAssertEqual(form["japanese"], parameters["japanese"])
XCTAssertEqual(form["arabic"], parameters["arabic"])
XCTAssertEqual(form["emoji"], parameters["emoji"])
} else {
XCTFail("form parameter in JSON should not be nil")
}
}
func testPOSTRequestWithBase64EncodedImages() {
// Given
let pngBase64EncodedString: String = {
let fileURL = url(forResource: "unicorn", withExtension: "png")
let data = try! Data(contentsOf: fileURL)
return data.base64EncodedString(options: .lineLength64Characters)
}()
let jpegBase64EncodedString: String = {
let fileURL = url(forResource: "rainbow", withExtension: "jpg")
let data = try! Data(contentsOf: fileURL)
return data.base64EncodedString(options: .lineLength64Characters)
}()
let parameters = ["email": "user@alamofire.org",
"png_image": pngBase64EncodedString,
"jpeg_image": jpegBase64EncodedString]
let expectation = expectation(description: "request should succeed")
var response: DataResponse<TestResponse, AFError>?
// When
AF.request(Endpoint.method(.post), method: .post, parameters: parameters)
.responseDecodable(of: TestResponse.self) { closureResponse in
response = closureResponse
expectation.fulfill()
}
waitForExpectations(timeout: timeout)
// Then
XCTAssertNotNil(response?.request)
XCTAssertNotNil(response?.response)
XCTAssertNotNil(response?.data)
XCTAssertEqual(response?.result.isSuccess, true)
if let form = response?.result.success?.form {
XCTAssertEqual(form["email"], parameters["email"])
XCTAssertEqual(form["png_image"], parameters["png_image"])
XCTAssertEqual(form["jpeg_image"], parameters["jpeg_image"])
} else {
XCTFail("form parameter in JSON should not be nil")
}
}
// MARK: Queues
func testThatResponseSerializationWorksWithSerializationQueue() {
// Given
let queue = DispatchQueue(label: "org.alamofire.testSerializationQueue")
let manager = Session(serializationQueue: queue)
let expectation = expectation(description: "request should complete")
var response: DataResponse<TestResponse, AFError>?
// When
manager.request(.get).responseDecodable(of: TestResponse.self) { resp in
response = resp
expectation.fulfill()
}
waitForExpectations(timeout: timeout)
// Then
XCTAssertEqual(response?.result.isSuccess, true)
}
func testThatRequestsWorksWithRequestAndSerializationQueues() {
// Given
let requestQueue = DispatchQueue(label: "org.alamofire.testRequestQueue")
let serializationQueue = DispatchQueue(label: "org.alamofire.testSerializationQueue")
let manager = Session(requestQueue: requestQueue, serializationQueue: serializationQueue)
let expectation = expectation(description: "request should complete")
var response: DataResponse<TestResponse, AFError>?
// When
manager.request(.get).responseDecodable(of: TestResponse.self) { resp in
response = resp
expectation.fulfill()
}
waitForExpectations(timeout: timeout)
// Then
XCTAssertEqual(response?.result.isSuccess, true)
}
func testThatRequestsWorksWithConcurrentRequestAndSerializationQueues() {
// Given
let requestQueue = DispatchQueue(label: "org.alamofire.testRequestQueue", attributes: .concurrent)
let serializationQueue = DispatchQueue(label: "org.alamofire.testSerializationQueue", attributes: .concurrent)
let session = Session(requestQueue: requestQueue, serializationQueue: serializationQueue)
let count = 10
let expectation = expectation(description: "request should complete")
expectation.expectedFulfillmentCount = count
var responses: [DataResponse<TestResponse, AFError>] = []
// When
DispatchQueue.concurrentPerform(iterations: count) { _ in
session.request(.default).responseDecodable(of: TestResponse.self) { resp in
responses.append(resp)
expectation.fulfill()
}
}
waitForExpectations(timeout: timeout, handler: nil)
// Then
XCTAssertEqual(responses.count, count)
XCTAssertTrue(responses.allSatisfy(\.result.isSuccess))
}
// MARK: Encodable Parameters
func testThatRequestsCanPassEncodableParametersAsJSONBodyData() {
// Given
let parameters = TestParameters(property: "one")
let expect = expectation(description: "request should complete")
var receivedResponse: DataResponse<TestResponse, AFError>?
// When
AF.request(.method(.post), parameters: parameters, encoder: JSONParameterEncoder.default)
.responseDecodable(of: TestResponse.self) { response in
receivedResponse = response
expect.fulfill()
}
waitForExpectations(timeout: timeout)
// Then
XCTAssertEqual(receivedResponse?.result.success?.data, "{\"property\":\"one\"}")
}
func testThatRequestsCanPassEncodableParametersAsAURLQuery() {
// Given
let parameters = TestParameters(property: "one")
let expect = expectation(description: "request should complete")
var receivedResponse: DataResponse<TestResponse, AFError>?
// When
AF.request(.method(.get), parameters: parameters)
.responseDecodable(of: TestResponse.self) { response in
receivedResponse = response
expect.fulfill()
}
waitForExpectations(timeout: timeout)
// Then
XCTAssertEqual(receivedResponse?.result.success?.args, ["property": "one"])
}
func testThatRequestsCanPassEncodableParametersAsURLEncodedBodyData() {
// Given
let parameters = TestParameters(property: "one")
let expect = expectation(description: "request should complete")
var receivedResponse: DataResponse<TestResponse, AFError>?
// When
AF.request(.method(.post), parameters: parameters)
.responseDecodable(of: TestResponse.self) { response in
receivedResponse = response
expect.fulfill()
}
waitForExpectations(timeout: timeout)
// Then
XCTAssertEqual(receivedResponse?.result.success?.form, ["property": "one"])
}
// MARK: Lifetime Events
func testThatAutomaticallyResumedRequestReceivesAppropriateLifetimeEvents() {
// Given
let eventMonitor = ClosureEventMonitor()
let session = Session(eventMonitors: [eventMonitor])
let expect = expectation(description: "request should receive appropriate lifetime events")
expect.expectedFulfillmentCount = 4
eventMonitor.requestDidResumeTask = { _, _ in expect.fulfill() }
eventMonitor.requestDidResume = { _ in expect.fulfill() }
eventMonitor.requestDidFinish = { _ in expect.fulfill() }
// Fulfill other events that would exceed the expected count. Inverted expectations require the full timeout.
eventMonitor.requestDidSuspend = { _ in expect.fulfill() }
eventMonitor.requestDidSuspendTask = { _, _ in expect.fulfill() }
eventMonitor.requestDidCancel = { _ in expect.fulfill() }
eventMonitor.requestDidCancelTask = { _, _ in expect.fulfill() }
// When
let request = session.request(.default).response { _ in expect.fulfill() }
waitForExpectations(timeout: timeout)
// Then
XCTAssertEqual(request.state, .finished)
}
func testThatAutomaticallyAndManuallyResumedRequestReceivesAppropriateLifetimeEvents() {
// Given
let eventMonitor = ClosureEventMonitor()
let session = Session(eventMonitors: [eventMonitor])
let expect = expectation(description: "request should receive appropriate lifetime events")
expect.expectedFulfillmentCount = 4
eventMonitor.requestDidResumeTask = { _, _ in expect.fulfill() }
eventMonitor.requestDidResume = { _ in expect.fulfill() }
eventMonitor.requestDidFinish = { _ in expect.fulfill() }
// Fulfill other events that would exceed the expected count. Inverted expectations require the full timeout.
eventMonitor.requestDidSuspend = { _ in expect.fulfill() }
eventMonitor.requestDidSuspendTask = { _, _ in expect.fulfill() }
eventMonitor.requestDidCancel = { _ in expect.fulfill() }
eventMonitor.requestDidCancelTask = { _, _ in expect.fulfill() }
// When
let request = session.request(.default).response { _ in expect.fulfill() }
for _ in 0..<100 {
request.resume()
}
waitForExpectations(timeout: timeout)
// Then
XCTAssertEqual(request.state, .finished)
}
func testThatManuallyResumedRequestReceivesAppropriateLifetimeEvents() {
// Given
let eventMonitor = ClosureEventMonitor()
let session = Session(startRequestsImmediately: false, eventMonitors: [eventMonitor])
let expect = expectation(description: "request should receive appropriate lifetime events")
expect.expectedFulfillmentCount = 3
eventMonitor.requestDidResumeTask = { _, _ in expect.fulfill() }
eventMonitor.requestDidResume = { _ in expect.fulfill() }
eventMonitor.requestDidFinish = { _ in expect.fulfill() }
// Fulfill other events that would exceed the expected count. Inverted expectations require the full timeout.
eventMonitor.requestDidSuspend = { _ in expect.fulfill() }
eventMonitor.requestDidSuspendTask = { _, _ in expect.fulfill() }
eventMonitor.requestDidCancel = { _ in expect.fulfill() }
eventMonitor.requestDidCancelTask = { _, _ in expect.fulfill() }
// When
let request = session.request(.default)
for _ in 0..<100 {
request.resume()
}
waitForExpectations(timeout: timeout)
// Then
XCTAssertEqual(request.state, .finished)
}
func testThatRequestManuallyResumedManyTimesOnlyReceivesAppropriateLifetimeEvents() {
// Given
let eventMonitor = ClosureEventMonitor()
let session = Session(startRequestsImmediately: false, eventMonitors: [eventMonitor])
let expect = expectation(description: "request should receive appropriate lifetime events")
expect.expectedFulfillmentCount = 4
eventMonitor.requestDidResumeTask = { _, _ in expect.fulfill() }
eventMonitor.requestDidResume = { _ in expect.fulfill() }
eventMonitor.requestDidFinish = { _ in expect.fulfill() }
// Fulfill other events that would exceed the expected count. Inverted expectations require the full timeout.
eventMonitor.requestDidSuspend = { _ in expect.fulfill() }
eventMonitor.requestDidSuspendTask = { _, _ in expect.fulfill() }
eventMonitor.requestDidCancel = { _ in expect.fulfill() }
eventMonitor.requestDidCancelTask = { _, _ in expect.fulfill() }
// When
let request = session.request(.default).response { _ in expect.fulfill() }
for _ in 0..<100 {
request.resume()
}
waitForExpectations(timeout: timeout)
// Then
XCTAssertEqual(request.state, .finished)
}
func testThatRequestManuallySuspendedManyTimesAfterAutomaticResumeOnlyReceivesAppropriateLifetimeEvents() {
// Given
let eventMonitor = ClosureEventMonitor()
let session = Session(startRequestsImmediately: false, eventMonitors: [eventMonitor])
let expect = expectation(description: "request should receive appropriate lifetime events")
expect.expectedFulfillmentCount = 2
eventMonitor.requestDidSuspendTask = { _, _ in expect.fulfill() }
eventMonitor.requestDidSuspend = { _ in expect.fulfill() }
// Fulfill other events that would exceed the expected count. Inverted expectations require the full timeout.
eventMonitor.requestDidCancel = { _ in expect.fulfill() }
eventMonitor.requestDidCancelTask = { _, _ in expect.fulfill() }
// When
let request = session.request(.default)
for _ in 0..<100 {
request.suspend()
}
waitForExpectations(timeout: timeout)
// Then
XCTAssertEqual(request.state, .suspended)
}
func testThatRequestManuallySuspendedManyTimesOnlyReceivesAppropriateLifetimeEvents() {
// Given
let eventMonitor = ClosureEventMonitor()
let session = Session(startRequestsImmediately: false, eventMonitors: [eventMonitor])
let expect = expectation(description: "request should receive appropriate lifetime events")
expect.expectedFulfillmentCount = 2
eventMonitor.requestDidSuspendTask = { _, _ in expect.fulfill() }
eventMonitor.requestDidSuspend = { _ in expect.fulfill() }
// Fulfill other events that would exceed the expected count. Inverted expectations require the full timeout.
eventMonitor.requestDidResume = { _ in expect.fulfill() }
eventMonitor.requestDidResumeTask = { _, _ in expect.fulfill() }
eventMonitor.requestDidCancel = { _ in expect.fulfill() }
eventMonitor.requestDidCancelTask = { _, _ in expect.fulfill() }
// When
let request = session.request(.default)
for _ in 0..<100 {
request.suspend()
}
waitForExpectations(timeout: timeout)
// Then
XCTAssertEqual(request.state, .suspended)
}
func testThatRequestManuallyCancelledManyTimesAfterAutomaticResumeOnlyReceivesAppropriateLifetimeEvents() {
// Given
let eventMonitor = ClosureEventMonitor()
let session = Session(eventMonitors: [eventMonitor])
let expect = expectation(description: "request should receive appropriate lifetime events")
expect.expectedFulfillmentCount = 2
eventMonitor.requestDidCancelTask = { _, _ in expect.fulfill() }
eventMonitor.requestDidCancel = { _ in expect.fulfill() }
// Fulfill other events that would exceed the expected count. Inverted expectations require the full timeout.
eventMonitor.requestDidSuspend = { _ in expect.fulfill() }
eventMonitor.requestDidSuspendTask = { _, _ in expect.fulfill() }
// When
let request = session.request(.default)
// Cancellation stops task creation, so don't cancel the request until the task has been created.
eventMonitor.requestDidCreateTask = { [unowned request] _, _ in
for _ in 0..<100 {
request.cancel()
}
}
waitForExpectations(timeout: timeout)
// Then
XCTAssertEqual(request.state, .cancelled)
}
func testThatRequestManuallyCancelledManyTimesOnlyReceivesAppropriateLifetimeEvents() {
// Given
let eventMonitor = ClosureEventMonitor()
let session = Session(startRequestsImmediately: false, eventMonitors: [eventMonitor])
let expect = expectation(description: "request should receive appropriate lifetime events")
expect.expectedFulfillmentCount = 2
eventMonitor.requestDidCancelTask = { _, _ in expect.fulfill() }
eventMonitor.requestDidCancel = { _ in expect.fulfill() }
// Fulfill other events that would exceed the expected count. Inverted expectations require the full timeout.
eventMonitor.requestDidResume = { _ in expect.fulfill() }
eventMonitor.requestDidResumeTask = { _, _ in expect.fulfill() }
eventMonitor.requestDidSuspend = { _ in expect.fulfill() }
eventMonitor.requestDidSuspendTask = { _, _ in expect.fulfill() }
// When
let request = session.request(.default)
// Cancellation stops task creation, so don't cancel the request until the task has been created.
eventMonitor.requestDidCreateTask = { [unowned request] _, _ in
for _ in 0..<100 {
request.cancel()
}
}
waitForExpectations(timeout: timeout)
// Then
XCTAssertEqual(request.state, .cancelled)
}
func testThatRequestManuallyCancelledManyTimesOnManyQueuesOnlyReceivesAppropriateLifetimeEvents() {
// Given
let eventMonitor = ClosureEventMonitor()
let session = Session(eventMonitors: [eventMonitor])
let expect = expectation(description: "request should receive appropriate lifetime events")
expect.expectedFulfillmentCount = 6
eventMonitor.requestDidCancelTask = { _, _ in expect.fulfill() }
eventMonitor.requestDidCancel = { _ in expect.fulfill() }
eventMonitor.requestDidResume = { _ in expect.fulfill() }
eventMonitor.requestDidResumeTask = { _, _ in expect.fulfill() }
// Fulfill other events that would exceed the expected count. Inverted expectations require the full timeout.
eventMonitor.requestDidSuspend = { _ in expect.fulfill() }
eventMonitor.requestDidSuspendTask = { _, _ in expect.fulfill() }
// When
let request = session.request(.delay(5)).response { _ in expect.fulfill() }
// Cancellation stops task creation, so don't cancel the request until the task has been created.
eventMonitor.requestDidCreateTask = { [unowned request] _, _ in
DispatchQueue.concurrentPerform(iterations: 100) { i in
request.cancel()
if i == 99 { expect.fulfill() }
}
}
waitForExpectations(timeout: timeout)
// Then
XCTAssertEqual(request.state, .cancelled)
}
func testThatRequestTriggersAllAppropriateLifetimeEvents() {
// Given
let eventMonitor = ClosureEventMonitor()
let session = Session(eventMonitors: [eventMonitor])
// Disable event test until Firewalk support HTTPS.
// let didReceiveChallenge = expectation(description: "didReceiveChallenge should fire")
let taskDidFinishCollecting = expectation(description: "taskDidFinishCollecting should fire")
let didReceiveData = expectation(description: "didReceiveData should fire")
let willCacheResponse = expectation(description: "willCacheResponse should fire")
let didCreateURLRequest = expectation(description: "didCreateInitialURLRequest should fire")
let didCreateTask = expectation(description: "didCreateTask should fire")
let didGatherMetrics = expectation(description: "didGatherMetrics should fire")
let didComplete = expectation(description: "didComplete should fire")
let didFinish = expectation(description: "didFinish should fire")
let didResume = expectation(description: "didResume should fire")
let didResumeTask = expectation(description: "didResumeTask should fire")
let didParseResponse = expectation(description: "didParseResponse should fire")
let responseHandler = expectation(description: "responseHandler should fire")
var dataReceived = false
// Disable event test until Firewalk supports HTTPS.
// eventMonitor.taskDidReceiveChallenge = { _, _, _ in didReceiveChallenge.fulfill() }
eventMonitor.taskDidFinishCollectingMetrics = { _, _, _ in taskDidFinishCollecting.fulfill() }
eventMonitor.dataTaskDidReceiveData = { _, _, _ in
guard !dataReceived else { return }
// Data may be received many times, fulfill only once.
dataReceived = true
didReceiveData.fulfill()
}
eventMonitor.dataTaskWillCacheResponse = { _, _, _ in willCacheResponse.fulfill() }
eventMonitor.requestDidCreateInitialURLRequest = { _, _ in didCreateURLRequest.fulfill() }
eventMonitor.requestDidCreateTask = { _, _ in didCreateTask.fulfill() }
eventMonitor.requestDidGatherMetrics = { _, _ in didGatherMetrics.fulfill() }
eventMonitor.requestDidCompleteTaskWithError = { _, _, _ in didComplete.fulfill() }
eventMonitor.requestDidFinish = { _ in didFinish.fulfill() }
eventMonitor.requestDidResume = { _ in didResume.fulfill() }
eventMonitor.requestDidResumeTask = { _, _ in didResumeTask.fulfill() }
eventMonitor.requestDidParseResponse = { _, _ in didParseResponse.fulfill() }
// When
let request = session.request(.default).response { _ in
responseHandler.fulfill()
}
waitForExpectations(timeout: timeout)
// Then
XCTAssertEqual(request.state, .finished)
}
func testThatCancelledRequestTriggersAllAppropriateLifetimeEvents() {
// Given
let eventMonitor = ClosureEventMonitor()
let session = Session(startRequestsImmediately: false, eventMonitors: [eventMonitor])
let taskDidFinishCollecting = expectation(description: "taskDidFinishCollecting should fire")
let didCreateURLRequest = expectation(description: "didCreateInitialURLRequest should fire")
let didCreateTask = expectation(description: "didCreateTask should fire")
let didGatherMetrics = expectation(description: "didGatherMetrics should fire")
let didComplete = expectation(description: "didComplete should fire")
let didFinish = expectation(description: "didFinish should fire")
let didResume = expectation(description: "didResume should fire")
let didResumeTask = expectation(description: "didResumeTask should fire")
let didParseResponse = expectation(description: "didParseResponse should fire")
let didCancel = expectation(description: "didCancel should fire")
let didCancelTask = expectation(description: "didCancelTask should fire")
let responseHandler = expectation(description: "responseHandler should fire")
eventMonitor.taskDidFinishCollectingMetrics = { _, _, _ in taskDidFinishCollecting.fulfill() }
eventMonitor.requestDidCreateInitialURLRequest = { _, _ in didCreateURLRequest.fulfill() }
eventMonitor.requestDidCreateTask = { _, _ in didCreateTask.fulfill() }
eventMonitor.requestDidGatherMetrics = { _, _ in didGatherMetrics.fulfill() }
eventMonitor.requestDidCompleteTaskWithError = { _, _, _ in didComplete.fulfill() }
eventMonitor.requestDidFinish = { _ in didFinish.fulfill() }
eventMonitor.requestDidResume = { _ in didResume.fulfill() }
eventMonitor.requestDidParseResponse = { _, _ in didParseResponse.fulfill() }
eventMonitor.requestDidCancel = { _ in didCancel.fulfill() }
eventMonitor.requestDidCancelTask = { _, _ in didCancelTask.fulfill() }
// When
let request = session.request(.delay(5)).response { _ in
responseHandler.fulfill()
}
eventMonitor.requestDidResumeTask = { [unowned request] _, _ in
request.cancel()
didResumeTask.fulfill()
}
request.resume()
waitForExpectations(timeout: timeout)
// Then
XCTAssertEqual(request.state, .cancelled)
}
func testThatAppendingResponseSerializerToCancelledRequestCallsCompletion() {
// Given
let session = Session()
var response1: DataResponse<TestResponse, AFError>?
var response2: DataResponse<TestResponse, AFError>?
let expect = expectation(description: "both response serializer completions should be called")
expect.expectedFulfillmentCount = 2
// When
let request = session.request(.default)
request.responseDecodable(of: TestResponse.self) { resp in
response1 = resp
expect.fulfill()
request.responseDecodable(of: TestResponse.self) { resp in
response2 = resp
expect.fulfill()
}
}
request.cancel()
waitForExpectations(timeout: timeout)
// Then
XCTAssertEqual(response1?.error?.isExplicitlyCancelledError, true)
XCTAssertEqual(response2?.error?.isExplicitlyCancelledError, true)
}
func testThatAppendingResponseSerializerToCompletedRequestInsideCompletionResumesRequest() {
// Given
let session = Session()
var response1: DataResponse<TestResponse, AFError>?
var response2: DataResponse<TestResponse, AFError>?
var response3: DataResponse<TestResponse, AFError>?
let expect = expectation(description: "all response serializer completions should be called")
expect.expectedFulfillmentCount = 3
// When
let request = session.request(.default)
request.responseDecodable(of: TestResponse.self) { resp in
response1 = resp
expect.fulfill()
request.responseDecodable(of: TestResponse.self) { resp in
response2 = resp
expect.fulfill()
request.responseDecodable(of: TestResponse.self) { resp in
response3 = resp
expect.fulfill()
}
}
}
waitForExpectations(timeout: timeout)
// Then
XCTAssertNotNil(response1?.value)
XCTAssertNotNil(response2?.value)
XCTAssertNotNil(response3?.value)
}
func testThatAppendingResponseSerializerToCompletedRequestOutsideCompletionResumesRequest() {
// Given
let session = Session()
let request = session.request(.default)
var response1: DataResponse<TestResponse, AFError>?
var response2: DataResponse<TestResponse, AFError>?
var response3: DataResponse<TestResponse, AFError>?
// When
let expect1 = expectation(description: "response serializer 1 completion should be called")
request.responseDecodable(of: TestResponse.self) { response1 = $0; expect1.fulfill() }
waitForExpectations(timeout: timeout)
let expect2 = expectation(description: "response serializer 2 completion should be called")
request.responseDecodable(of: TestResponse.self) { response2 = $0; expect2.fulfill() }
waitForExpectations(timeout: timeout)
let expect3 = expectation(description: "response serializer 3 completion should be called")
request.responseDecodable(of: TestResponse.self) { response3 = $0; expect3.fulfill() }
waitForExpectations(timeout: timeout)
// Then
XCTAssertNotNil(response1?.value)
XCTAssertNotNil(response2?.value)
XCTAssertNotNil(response3?.value)
}
}
// MARK: -
final class RequestDescriptionTestCase: BaseTestCase {
func testRequestDescription() {
// Given
let url = Endpoint().url
let manager = Session(startRequestsImmediately: false)
let request = manager.request(url)
let expectation = expectation(description: "Request description should update: \(url)")
var response: HTTPURLResponse?
// When
request.response { resp in
response = resp.response
expectation.fulfill()
}.resume()
waitForExpectations(timeout: timeout)
// Then
XCTAssertEqual(request.description, "GET \(url) (\(response?.statusCode ?? -1))")
}
}
// MARK: -
final class RequestCURLDescriptionTestCase: BaseTestCase {
// MARK: Properties
let session: Session = {
let manager = Session()
return manager
}()
let sessionWithAcceptLanguageHeader: Session = {
var headers = HTTPHeaders.default
headers["Accept-Language"] = "en-US"
let configuration = URLSessionConfiguration.af.default
configuration.headers = headers
let manager = Session(configuration: configuration)
return manager
}()
let sessionWithContentTypeHeader: Session = {
var headers = HTTPHeaders.default
headers["Content-Type"] = "application/json"
let configuration = URLSessionConfiguration.af.default
configuration.headers = headers
let manager = Session(configuration: configuration)
return manager
}()
func sessionWithCookie(_ cookie: HTTPCookie) -> Session {
let configuration = URLSessionConfiguration.af.default
configuration.httpCookieStorage?.setCookie(cookie)
return Session(configuration: configuration)
}
let sessionDisallowingCookies: Session = {
let configuration = URLSessionConfiguration.af.default
configuration.httpShouldSetCookies = false
let manager = Session(configuration: configuration)
return manager
}()
// MARK: Tests
func testGETRequestCURLDescription() {
// Given
let url = Endpoint().url
let expectation = expectation(description: "request should complete")
var components: [String]?
// When
session.request(url).cURLDescription {
components = self.cURLCommandComponents(from: $0)
expectation.fulfill()
}
waitForExpectations(timeout: timeout)
// Then
XCTAssertEqual(components?[0..<3], ["$", "curl", "-v"])
XCTAssertTrue(components?.contains("-X") == true)
XCTAssertEqual(components?.last, "\"\(url)\"")
}
func testGETRequestCURLDescriptionOnMainQueue() {
// Given
let url = Endpoint().url
let expectation = expectation(description: "request should complete")
var isMainThread = false
var components: [String]?
// When
session.request(url).cURLDescription(on: .main) {
components = self.cURLCommandComponents(from: $0)
isMainThread = Thread.isMainThread
expectation.fulfill()
}
waitForExpectations(timeout: timeout, handler: nil)
// Then
XCTAssertTrue(isMainThread)
XCTAssertEqual(components?[0..<3], ["$", "curl", "-v"])
XCTAssertTrue(components?.contains("-X") == true)
XCTAssertEqual(components?.last, "\"\(url)\"")
}
func testGETRequestCURLDescriptionSynchronous() {
// Given
let url = Endpoint().url
let expectation = expectation(description: "request should complete")
var components: [String]?
var syncComponents: [String]?
// When
let request = session.request(url)
request.cURLDescription {
components = self.cURLCommandComponents(from: $0)
syncComponents = self.cURLCommandComponents(from: request.cURLDescription())
expectation.fulfill()
}
waitForExpectations(timeout: timeout)
// Then
XCTAssertEqual(components?[0..<3], ["$", "curl", "-v"])
XCTAssertTrue(components?.contains("-X") == true)
XCTAssertEqual(components?.last, "\"\(url)\"")
XCTAssertEqual(components?.sorted(), syncComponents?.sorted())
}
func testGETRequestCURLDescriptionCanBeRequestedManyTimes() {
// Given
let url = Endpoint().url
let expectation = expectation(description: "request should complete")
var components: [String]?
var secondComponents: [String]?
// When
let request = session.request(url)
request.cURLDescription {
components = self.cURLCommandComponents(from: $0)
request.cURLDescription {
secondComponents = self.cURLCommandComponents(from: $0)
expectation.fulfill()
}
}
waitForExpectations(timeout: timeout)
// Then
XCTAssertEqual(components?[0..<3], ["$", "curl", "-v"])
XCTAssertTrue(components?.contains("-X") == true)
XCTAssertEqual(components?.last, "\"\(url)\"")
XCTAssertEqual(components?.sorted(), secondComponents?.sorted())
}
func testGETRequestWithCustomHeaderCURLDescription() {
// Given
let url = Endpoint().url
let expectation = expectation(description: "request should complete")
var cURLDescription: String?
// When
let headers: HTTPHeaders = ["X-Custom-Header": "{\"key\": \"value\"}"]
session.request(url, headers: headers).cURLDescription {
cURLDescription = $0
expectation.fulfill()
}
waitForExpectations(timeout: timeout)
// Then
XCTAssertNotNil(cURLDescription?.range(of: "-H \"X-Custom-Header: {\\\"key\\\": \\\"value\\\"}\""))
}
func testGETRequestWithDuplicateHeadersDebugDescription() {
// Given
let url = Endpoint().url
let expectation = expectation(description: "request should complete")
var cURLDescription: String?
var components: [String]?
// When
let headers: HTTPHeaders = ["Accept-Language": "en-GB"]
sessionWithAcceptLanguageHeader.request(url, headers: headers).cURLDescription {
components = self.cURLCommandComponents(from: $0)
cURLDescription = $0
expectation.fulfill()
}
waitForExpectations(timeout: timeout)
// Then
XCTAssertEqual(components?[0..<3], ["$", "curl", "-v"])
XCTAssertTrue(components?.contains("-X") == true)
XCTAssertEqual(components?.last, "\"\(url)\"")
let acceptLanguageCount = components?.filter { $0.contains("Accept-Language") }.count
XCTAssertEqual(acceptLanguageCount, 1, "command should contain a single Accept-Language header")
XCTAssertNotNil(cURLDescription?.range(of: "-H \"Accept-Language: en-GB\""))
}
func testPOSTRequestCURLDescription() {
// Given
let url = Endpoint.method(.post).url
let expectation = expectation(description: "request should complete")
var components: [String]?
// When
session.request(url, method: .post).cURLDescription {
components = self.cURLCommandComponents(from: $0)
expectation.fulfill()
}
waitForExpectations(timeout: timeout)
// Then
XCTAssertEqual(components?[0..<3], ["$", "curl", "-v"])
XCTAssertEqual(components?[3..<5], ["-X", "POST"])
XCTAssertEqual(components?.last, "\"\(url)\"")
}