forked from swiftlang/swift-corelibs-foundation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTestURLSession.swift
1450 lines (1275 loc) · 64.2 KB
/
TestURLSession.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
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
class TestURLSession : LoopbackServerTest {
func test_dataTaskWithURL() {
let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/Nepal"
let url = URL(string: urlString)!
let d = DataTask(with: expectation(description: "GET \(urlString): with a delegate"))
d.run(with: url)
waitForExpectations(timeout: 12)
if !d.error {
XCTAssertEqual(d.capital, "Kathmandu", "test_dataTaskWithURLRequest returned an unexpected result")
}
}
func test_dataTaskWithURLCompletionHandler() {
//shared session
dataTaskWithURLCompletionHandler(with: URLSession.shared)
//new session
let config = URLSessionConfiguration.default
config.timeoutIntervalForRequest = 8
let session = URLSession(configuration: config, delegate: nil, delegateQueue: nil)
dataTaskWithURLCompletionHandler(with: session)
}
func dataTaskWithURLCompletionHandler(with session: URLSession) {
let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/USA"
let url = URL(string: urlString)!
let expect = expectation(description: "GET \(urlString): with a completion handler")
var expectedResult = "unknown"
let task = session.dataTask(with: url) { data, response, error in
defer { expect.fulfill() }
XCTAssertNil(error as? URLError, "error = \(error as! URLError)")
XCTAssertNotNil(response)
XCTAssertNotNil(data)
guard let httpResponse = response as? HTTPURLResponse, let data = data else { return }
XCTAssertEqual(200, httpResponse.statusCode, "HTTP response code is not 200")
expectedResult = String(data: data, encoding: .utf8) ?? ""
XCTAssertEqual("Washington, D.C.", expectedResult, "Did not receive expected value")
}
task.resume()
waitForExpectations(timeout: 12)
}
func test_dataTaskWithURLRequest() {
let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/Peru"
let urlRequest = URLRequest(url: URL(string: urlString)!)
let d = DataTask(with: expectation(description: "GET \(urlString): with a delegate"))
d.run(with: urlRequest)
waitForExpectations(timeout: 12)
if !d.error {
XCTAssertEqual(d.capital, "Lima", "test_dataTaskWithURLRequest returned an unexpected result")
}
}
func test_dataTaskWithURLRequestCompletionHandler() {
let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/Italy"
let urlRequest = URLRequest(url: URL(string: urlString)!)
let config = URLSessionConfiguration.default
config.timeoutIntervalForRequest = 8
let session = URLSession(configuration: config, delegate: nil, delegateQueue: nil)
let expect = expectation(description: "GET \(urlString): with a completion handler")
var expectedResult = "unknown"
let task = session.dataTask(with: urlRequest) { data, response, error in
defer { expect.fulfill() }
XCTAssertNotNil(data)
XCTAssertNotNil(response)
XCTAssertNil(error as? URLError, "error = \(error as! URLError)")
guard let httpResponse = response as? HTTPURLResponse, let data = data else { return }
XCTAssertEqual(200, httpResponse.statusCode, "HTTP response code is not 200")
expectedResult = String(data: data, encoding: .utf8) ?? ""
XCTAssertEqual("Rome", expectedResult, "Did not receive expected value")
}
task.resume()
waitForExpectations(timeout: 12)
}
func test_dataTaskWithHttpInputStream() {
let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/echo"
let dataString = """
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras congue laoreet facilisis. Sed porta tristique orci. Fusce ut nisl dignissim, tempor tortor id, molestie neque. Nam non tincidunt mi. Integer ac diam quis leo aliquam congue et non magna. In porta mauris suscipit erat pulvinar, sed fringilla quam ornare. Nulla vulputate et ligula vitae sollicitudin. Nulla vel vehicula risus. Quisque eu urna ullamcorper, tincidunt ante vitae, aliquet sem. Suspendisse nec turpis placerat, porttitor ex vel, tristique orci. Maecenas pretium, augue non elementum imperdiet, diam ex vestibulum tortor, non ultrices ante enim iaculis ex.
Suspendisse ante eros, scelerisque ut molestie vitae, lacinia nec metus. Sed in feugiat sem. Nullam sed congue nulla, id vehicula mauris. Aliquam ultrices ultricies pellentesque. Etiam blandit ultrices quam in egestas. Donec a vulputate est, ut ultricies dui. In non maximus velit.
Vivamus vehicula faucibus odio vel maximus. Vivamus elementum, quam at accumsan rhoncus, ex ligula maximus sem, sed pretium urna enim ut urna. Donec semper porta augue at faucibus. Quisque vel congue purus. Morbi vitae elit pellentesque, finibus lectus quis, laoreet nulla. Praesent in fermentum felis. Aenean vestibulum dictum lorem quis egestas. Sed dictum elementum est laoreet volutpat.
"""
let url = URL(string: urlString)!
let urlSession = URLSession(configuration: URLSessionConfiguration.default)
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = "POST"
guard let data = dataString.data(using: .utf8) else {
XCTFail()
return
}
let inputStream = InputStream(data: data)
inputStream.open()
urlRequest.httpBodyStream = inputStream
urlRequest.setValue("en-us", forHTTPHeaderField: "Accept-Language")
urlRequest.setValue("text/xml; charset=utf-8", forHTTPHeaderField: "Content-Type")
urlRequest.setValue("chunked", forHTTPHeaderField: "Transfer-Encoding")
let expect = expectation(description: "POST \(urlString): with HTTP Body as InputStream")
let task = urlSession.dataTask(with: urlRequest) { respData, response, error in
XCTAssertNotNil(respData)
XCTAssertNotNil(response)
XCTAssertNil(error)
defer { expect.fulfill() }
guard let httpResponse = response as? HTTPURLResponse else {
XCTFail("response (\(response.debugDescription)) invalid")
return
}
XCTAssertEqual(data, respData!, "Response Data and Data is not equal")
XCTAssertEqual(200, httpResponse.statusCode, "HTTP response code is not 200")
}
task.resume()
waitForExpectations(timeout: 12)
}
func test_gzippedDataTask() {
let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/gzipped-response"
let url = URL(string: urlString)!
let d = DataTask(with: expectation(description: "GET \(urlString): gzipped response"))
d.run(with: url)
waitForExpectations(timeout: 12)
if !d.error {
XCTAssertEqual(d.capital, "Hello World!")
}
}
func test_downloadTaskWithURL() {
let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/country.txt"
let url = URL(string: urlString)!
let d = DownloadTask(testCase: self, description: "Download GET \(urlString): with a delegate")
d.run(with: url)
waitForExpectations(timeout: 12)
}
func test_downloadTaskWithURLRequest() {
let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/country.txt"
let urlRequest = URLRequest(url: URL(string: urlString)!)
let d = DownloadTask(testCase: self, description: "Download GET \(urlString): with a delegate")
d.run(with: urlRequest)
waitForExpectations(timeout: 12)
}
func test_downloadTaskWithRequestAndHandler() {
//shared session
downloadTaskWithRequestAndHandler(with: URLSession.shared)
//newly created session
let config = URLSessionConfiguration.default
config.timeoutIntervalForRequest = 8
let session = URLSession(configuration: config, delegate: nil, delegateQueue: nil)
downloadTaskWithRequestAndHandler(with: session)
}
func downloadTaskWithRequestAndHandler(with session: URLSession) {
let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/country.txt"
let expect = expectation(description: "Download GET \(urlString): with a completion handler")
let req = URLRequest(url: URL(string: urlString)!)
let task = session.downloadTask(with: req) { (_, _, error) -> Void in
XCTAssertNil(error as? URLError, "error = \(error as! URLError)")
expect.fulfill()
}
task.resume()
waitForExpectations(timeout: 12)
}
func test_downloadTaskWithURLAndHandler() {
let config = URLSessionConfiguration.default
config.timeoutIntervalForRequest = 8
let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/country.txt"
let session = URLSession(configuration: config, delegate: nil, delegateQueue: nil)
let expect = expectation(description: "Download GET \(urlString): with a completion handler")
let req = URLRequest(url: URL(string: urlString)!)
let task = session.downloadTask(with: req) { (_, _, error) -> Void in
if let e = error as? URLError {
XCTAssertEqual(e.code, .timedOut, "Unexpected error code")
}
expect.fulfill()
}
task.resume()
waitForExpectations(timeout: 12)
}
func test_gzippedDownloadTask() {
let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/gzipped-response"
let url = URL(string: urlString)!
let d = DownloadTask(testCase: self, description: "GET \(urlString): gzipped response")
d.run(with: url)
waitForExpectations(timeout: 12)
if d.totalBytesWritten != "Hello World!".utf8.count {
XCTFail("Expected the gzipped-response to be the length of Hello World!")
}
}
func test_finishTasksAndInvalidate() {
let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/Nepal"
let invalidateExpectation = expectation(description: "Session invalidation")
let delegate = SessionDelegate(invalidateExpectation: invalidateExpectation)
let url = URL(string: urlString)!
let session = URLSession(configuration: URLSessionConfiguration.default,
delegate: delegate, delegateQueue: nil)
let completionExpectation = expectation(description: "GET \(urlString): task completion before session invalidation")
let task = session.dataTask(with: url) { (_, _, _) in
completionExpectation.fulfill()
}
task.resume()
session.finishTasksAndInvalidate()
waitForExpectations(timeout: 12)
}
func test_taskError() {
let urlString = "http://127.0.0.1:-1/Nepal"
let url = URL(string: urlString)!
let session = URLSession(configuration: URLSessionConfiguration.default,
delegate: nil,
delegateQueue: nil)
let completionExpectation = expectation(description: "GET \(urlString): Bad URL error")
let task = session.dataTask(with: url) { (_, _, result) in
let error = result as? URLError
XCTAssertNotNil(error)
XCTAssertEqual(error?.code, .badURL)
completionExpectation.fulfill()
}
//should result in Bad URL error
task.resume()
waitForExpectations(timeout: 5) { error in
XCTAssertNil(error)
XCTAssertNotNil(task.error)
XCTAssertEqual((task.error as? URLError)?.code, .badURL)
}
}
func test_taskCopy() {
let url = URL(string: "http://127.0.0.1:\(TestURLSession.serverPort)/Nepal")!
let session = URLSession(configuration: URLSessionConfiguration.default,
delegate: nil,
delegateQueue: nil)
let task = session.dataTask(with: url)
XCTAssert(task.isEqual(task.copy()))
}
// This test is buggy becuase the server could respond before the task is cancelled.
func test_cancelTask() {
let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/Peru"
var urlRequest = URLRequest(url: URL(string: urlString)!)
urlRequest.setValue("2.0", forHTTPHeaderField: "X-Pause")
let d = DataTask(with: expectation(description: "GET \(urlString): task cancelation"))
d.cancelExpectation = expectation(description: "GET \(urlString): task canceled")
d.run(with: urlRequest)
d.cancel()
waitForExpectations(timeout: 12)
}
func test_verifyRequestHeaders() {
let config = URLSessionConfiguration.default
config.timeoutIntervalForRequest = 5
let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/requestHeaders"
let session = URLSession(configuration: config, delegate: nil, delegateQueue: nil)
var expect = expectation(description: "POST \(urlString): get request headers")
var req = URLRequest(url: URL(string: urlString)!)
let headers = ["header1": "value1"]
req.httpMethod = "POST"
req.allHTTPHeaderFields = headers
var task = session.dataTask(with: req) { (data, _, error) -> Void in
defer { expect.fulfill() }
XCTAssertNotNil(data)
XCTAssertNil(error as? URLError, "error = \(error as! URLError)")
guard let data = data else { return }
let headers = String(data: data, encoding: .utf8) ?? ""
XCTAssertNotNil(headers.range(of: "header1: value1"))
}
task.resume()
req.allHTTPHeaderFields = nil
waitForExpectations(timeout: 30)
}
// Verify httpAdditionalHeaders from session configuration are added to the request
// and whether it is overriden by Request.allHTTPHeaderFields.
func test_verifyHttpAdditionalHeaders() {
let config = URLSessionConfiguration.default
config.timeoutIntervalForRequest = 5
config.httpAdditionalHeaders = ["header2": "svalue2", "header3": "svalue3", "header4": "svalue4"]
let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/requestHeaders"
let session = URLSession(configuration: config, delegate: nil, delegateQueue: nil)
var expect = expectation(description: "POST \(urlString) with additional headers")
var req = URLRequest(url: URL(string: urlString)!)
let headers = ["header1": "rvalue1", "header2": "rvalue2", "Header4": "rvalue4"]
req.httpMethod = "POST"
req.allHTTPHeaderFields = headers
var task = session.dataTask(with: req) { (data, _, error) -> Void in
defer { expect.fulfill() }
XCTAssertNotNil(data)
XCTAssertNil(error as? URLError, "error = \(error as! URLError)")
guard let data = data else { return }
let headers = String(data: data, encoding: .utf8) ?? ""
XCTAssertNotNil(headers.range(of: "header1: rvalue1"))
XCTAssertNotNil(headers.range(of: "header2: rvalue2"))
XCTAssertNotNil(headers.range(of: "header3: svalue3"))
XCTAssertNotNil(headers.range(of: "Header4: rvalue4"))
XCTAssertNil(headers.range(of: "header4: svalue"))
}
task.resume()
waitForExpectations(timeout: 30)
}
func test_taskTimeout() {
let config = URLSessionConfiguration.default
config.timeoutIntervalForRequest = 5
let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/Peru"
let session = URLSession(configuration: config, delegate: nil, delegateQueue: nil)
var expect = expectation(description: "GET \(urlString): no timeout")
let req = URLRequest(url: URL(string: urlString)!)
var task = session.dataTask(with: req) { (data, _, error) -> Void in
defer { expect.fulfill() }
XCTAssertNil(error as? URLError, "error = \(error as! URLError)")
}
task.resume()
waitForExpectations(timeout: 30)
}
func test_timeoutInterval() {
let config = URLSessionConfiguration.default
config.timeoutIntervalForRequest = 10
let urlString = "http://127.0.0.1:-1/Peru"
let session = URLSession(configuration: config, delegate: nil, delegateQueue: nil)
var expect = expectation(description: "GET \(urlString): will timeout")
var req = URLRequest(url: URL(string: "http://127.0.0.1:-1/Peru")!)
req.timeoutInterval = 1
var task = session.dataTask(with: req) { (data, _, error) -> Void in
defer { expect.fulfill() }
XCTAssertNotNil(error)
}
task.resume()
waitForExpectations(timeout: 30)
}
func test_httpRedirectionWithCompleteRelativePath() {
let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/UnitedStates"
let url = URL(string: urlString)!
let d = HTTPRedirectionDataTask(with: expectation(description: "GET \(urlString): with HTTP redirection"))
d.run(with: url)
waitForExpectations(timeout: 12)
}
func test_httpRedirectionWithInCompleteRelativePath() {
let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/UnitedKingdom"
let url = URL(string: urlString)!
let d = HTTPRedirectionDataTask(with: expectation(description: "GET \(urlString): with HTTP redirection"))
d.run(with: url)
waitForExpectations(timeout: 12)
}
func test_httpRedirectionWithDefaultPort() {
let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/redirect-with-default-port"
let url = URL(string: urlString)!
let d = HTTPRedirectionDataTask(with: expectation(description: "GET \(urlString): with HTTP redirection"))
d.run(with: url)
waitForExpectations(timeout: 12)
}
// temporarily disabled (https://bugs.swift.org/browse/SR-5751)
func test_httpRedirectionTimeout() {
let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/UnitedStates"
var req = URLRequest(url: URL(string: urlString)!)
req.timeoutInterval = 3
let config = URLSessionConfiguration.default
var expect = expectation(description: "GET \(urlString): timeout with redirection ")
let session = URLSession(configuration: config, delegate: nil, delegateQueue: nil)
let task = session.dataTask(with: req) { data, response, error in
defer { expect.fulfill() }
if let e = error as? URLError {
XCTAssertEqual(e.code, .cannotConnectToHost, "Unexpected error code")
return
} else {
XCTFail("test unexpectedly succeeded (response=\(response.debugDescription))")
}
}
task.resume()
waitForExpectations(timeout: 12)
}
func test_http0_9SimpleResponses() {
for brokenCity in ["Pompeii", "Sodom"] {
let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/LandOfTheLostCities/\(brokenCity)"
let url = URL(string: urlString)!
let config = URLSessionConfiguration.default
config.timeoutIntervalForRequest = 8
let session = URLSession(configuration: config, delegate: nil, delegateQueue: nil)
let expect = expectation(description: "GET \(urlString): simple HTTP/0.9 response")
var expectedResult = "unknown"
let task = session.dataTask(with: url) { data, response, error in
XCTAssertNotNil(data)
XCTAssertNotNil(response)
XCTAssertNil(error)
defer { expect.fulfill() }
guard let httpResponse = response as? HTTPURLResponse else {
XCTFail("response (\(response.debugDescription)) invalid")
return
}
XCTAssertEqual(200, httpResponse.statusCode, "HTTP response code is not 200")
}
task.resume()
waitForExpectations(timeout: 12)
}
}
func test_outOfRangeButCorrectlyFormattedHTTPCode() {
let brokenCity = "Kameiros"
let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/LandOfTheLostCities/\(brokenCity)"
let url = URL(string: urlString)!
let config = URLSessionConfiguration.default
config.timeoutIntervalForRequest = 8
let session = URLSession(configuration: config, delegate: nil, delegateQueue: nil)
let expect = expectation(description: "GET \(urlString): out of range HTTP code")
let task = session.dataTask(with: url) { data, response, error in
XCTAssertNotNil(data)
XCTAssertNotNil(response)
XCTAssertNil(error)
defer { expect.fulfill() }
guard let httpResponse = response as? HTTPURLResponse else {
XCTFail("response (\(response.debugDescription)) invalid")
return
}
XCTAssertEqual(999, httpResponse.statusCode, "HTTP response code is not 999")
}
task.resume()
waitForExpectations(timeout: 12)
}
func test_missingContentLengthButStillABody() {
let brokenCity = "Myndus"
let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/LandOfTheLostCities/\(brokenCity)"
let url = URL(string: urlString)!
let config = URLSessionConfiguration.default
config.timeoutIntervalForRequest = 8
let session = URLSession(configuration: config, delegate: nil, delegateQueue: nil)
let expect = expectation(description: "GET \(urlString): missing content length")
let task = session.dataTask(with: url) { data, response, error in
XCTAssertNotNil(data)
XCTAssertNotNil(response)
XCTAssertNil(error)
defer { expect.fulfill() }
guard let httpResponse = response as? HTTPURLResponse else {
XCTFail("response (\(response.debugDescription)) invalid")
return
}
XCTAssertEqual(200, httpResponse.statusCode, "HTTP response code is not 200")
}
task.resume()
waitForExpectations(timeout: 12)
}
func test_illegalHTTPServerResponses() {
for brokenCity in ["Gomorrah", "Dinavar", "Kuhikugu"] {
let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/LandOfTheLostCities/\(brokenCity)"
let url = URL(string: urlString)!
let config = URLSessionConfiguration.default
config.timeoutIntervalForRequest = 8
let session = URLSession(configuration: config, delegate: nil, delegateQueue: nil)
let expect = expectation(description: "GET \(urlString): illegal response")
let task = session.dataTask(with: url) { data, response, error in
XCTAssertNil(data)
XCTAssertNil(response)
XCTAssertNotNil(error)
expect.fulfill()
}
task.resume()
waitForExpectations(timeout: 12)
}
}
func test_dataTaskWithSharedDelegate() {
let sharedDelegate = SharedDelegate()
let urlString0 = "http://127.0.0.1:\(TestURLSession.serverPort)/Nepal"
let session = URLSession(configuration: .default, delegate: sharedDelegate, delegateQueue: nil)
let dataRequest = URLRequest(url: URL(string: urlString0)!)
let dataTask = session.dataTask(with: dataRequest)
sharedDelegate.dataCompletionExpectation = expectation(description: "GET \(urlString0)")
dataTask.resume()
waitForExpectations(timeout: 20)
}
func test_simpleUploadWithDelegate() {
let delegate = HTTPUploadDelegate()
let session = URLSession(configuration: .default, delegate: delegate, delegateQueue: nil)
let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/upload"
var request = URLRequest(url: URL(string: urlString)!)
request.httpMethod = "PUT"
delegate.uploadCompletedExpectation = expectation(description: "PUT \(urlString): Upload data")
let fileData = Data(count: 16*1024)
let task = session.uploadTask(with: request, from: fileData)
task.resume()
waitForExpectations(timeout: 20)
}
func test_concurrentRequests() {
// "10 tasks ought to be enough for anybody"
let tasks = 10
let syncQ = dispatchQueueMake("test_dataTaskWithURL.syncQ")
var dataTasks: [DataTask] = []
let g = dispatchGroupMake()
for f in 0..<tasks {
g.enter()
let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/Nepal"
let expectation = self.expectation(description: "GET \(urlString) [\(f)]: with a delegate")
globalDispatchQueue.async {
let url = URL(string: urlString)!
let d = DataTask(with: expectation)
d.run(with: url)
syncQ.async {
dataTasks.append(d)
g.leave()
}
}
}
waitForExpectations(timeout: 12)
g.wait()
for d in syncQ.sync(execute: {dataTasks}) {
if !d.error {
XCTAssertEqual(d.capital, "Kathmandu", "test_dataTaskWithURLRequest returned an unexpected result")
}
}
}
func test_disableCookiesStorage() {
let config = URLSessionConfiguration.default
config.timeoutIntervalForRequest = 5
config.httpCookieAcceptPolicy = HTTPCookie.AcceptPolicy.never
if let storage = config.httpCookieStorage, let cookies = storage.cookies {
for cookie in cookies {
storage.deleteCookie(cookie)
}
}
XCTAssertEqual(config.httpCookieStorage?.cookies?.count, 0)
let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/requestCookies"
let session = URLSession(configuration: config, delegate: nil, delegateQueue: nil)
var expect = expectation(description: "POST \(urlString)")
var req = URLRequest(url: URL(string: urlString)!)
req.httpMethod = "POST"
var task = session.dataTask(with: req) { (data, _, error) -> Void in
defer { expect.fulfill() }
XCTAssertNotNil(data)
XCTAssertNil(error as? URLError, "error = \(error as! URLError)")
}
task.resume()
waitForExpectations(timeout: 30)
let cookies = HTTPCookieStorage.shared.cookies
XCTAssertEqual(cookies?.count, 0)
}
func test_cookiesStorage() {
let config = URLSessionConfiguration.default
config.timeoutIntervalForRequest = 5
let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/requestCookies"
let session = URLSession(configuration: config, delegate: nil, delegateQueue: nil)
var expect = expectation(description: "POST \(urlString)")
var req = URLRequest(url: URL(string: urlString)!)
req.httpMethod = "POST"
var task = session.dataTask(with: req) { (data, _, error) -> Void in
defer { expect.fulfill() }
XCTAssertNotNil(data)
XCTAssertNil(error as? URLError, "error = \(error as! URLError)")
}
task.resume()
waitForExpectations(timeout: 30)
let cookies = HTTPCookieStorage.shared.cookies
XCTAssertEqual(cookies?.count, 1)
}
func test_redirectionWithSetCookies() {
let config = URLSessionConfiguration.default
config.timeoutIntervalForRequest = 5
if let storage = config.httpCookieStorage, let cookies = storage.cookies {
for cookie in cookies {
storage.deleteCookie(cookie)
}
}
let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/redirectSetCookies"
let session = URLSession(configuration: config, delegate: nil, delegateQueue: nil)
var expect = expectation(description: "POST \(urlString)")
var req = URLRequest(url: URL(string: urlString)!)
var task = session.dataTask(with: req) { (data, _, error) -> Void in
defer { expect.fulfill() }
XCTAssertNotNil(data)
XCTAssertNil(error as? URLError, "error = \(error as! URLError)")
guard let data = data else { return }
let headers = String(data: data, encoding: String.Encoding.utf8) ?? ""
print("headers here = \(headers)")
XCTAssertNotNil(headers.range(of: "Cookie: redirect=true"))
}
task.resume()
waitForExpectations(timeout: 30)
}
func test_setCookies() {
let config = URLSessionConfiguration.default
config.timeoutIntervalForRequest = 5
let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/setCookies"
let session = URLSession(configuration: config, delegate: nil, delegateQueue: nil)
var expect = expectation(description: "POST \(urlString)")
var req = URLRequest(url: URL(string: urlString)!)
req.httpMethod = "POST"
var task = session.dataTask(with: req) { (data, _, error) -> Void in
defer { expect.fulfill() }
XCTAssertNotNil(data)
XCTAssertNil(error as? URLError, "error = \(error as! URLError)")
guard let data = data else { return }
let headers = String(data: data, encoding: String.Encoding.utf8) ?? ""
XCTAssertNotNil(headers.range(of: "Cookie: fr=anjd&232"))
}
task.resume()
waitForExpectations(timeout: 30)
}
func test_cookieStorageForEphmeralConfiguration() {
let config = URLSessionConfiguration.ephemeral
config.timeoutIntervalForRequest = 5
let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/requestCookies"
let session = URLSession(configuration: config, delegate: nil, delegateQueue: nil)
var expect = expectation(description: "POST \(urlString)")
var req = URLRequest(url: URL(string: urlString)!)
req.httpMethod = "POST"
var task = session.dataTask(with: req) { (data, _, error) -> Void in
defer { expect.fulfill() }
XCTAssertNotNil(data)
XCTAssertNil(error as? URLError, "error = \(error as! URLError)")
}
task.resume()
waitForExpectations(timeout: 30)
let cookies = config.httpCookieStorage?.cookies
XCTAssertEqual(cookies?.count, 1)
let config2 = URLSessionConfiguration.ephemeral
let cookies2 = config2.httpCookieStorage?.cookies
XCTAssertEqual(cookies2?.count, 0)
}
func test_dontSetCookies() {
let config = URLSessionConfiguration.default
config.timeoutIntervalForRequest = 5
config.httpShouldSetCookies = false
let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/setCookies"
let session = URLSession(configuration: config, delegate: nil, delegateQueue: nil)
var expect = expectation(description: "POST \(urlString)")
var req = URLRequest(url: URL(string: urlString)!)
req.httpMethod = "POST"
var task = session.dataTask(with: req) { (data, _, error) -> Void in
defer { expect.fulfill() }
XCTAssertNotNil(data)
XCTAssertNil(error as? URLError, "error = \(error as! URLError)")
guard let data = data else { return }
let headers = String(data: data, encoding: String.Encoding.utf8) ?? ""
XCTAssertNil(headers.range(of: "Cookie: fr=anjd&232"))
}
task.resume()
waitForExpectations(timeout: 30)
}
// Validate that the properties are correctly set
func test_initURLSessionConfiguration() {
let config = URLSessionConfiguration.default
config.requestCachePolicy = .useProtocolCachePolicy
config.timeoutIntervalForRequest = 30
config.timeoutIntervalForResource = 604800
config.networkServiceType = .default
config.allowsCellularAccess = false
config.isDiscretionary = true
config.httpShouldUsePipelining = true
config.httpShouldSetCookies = true
config.httpCookieAcceptPolicy = .always
config.httpMaximumConnectionsPerHost = 2
config.httpCookieStorage = HTTPCookieStorage.shared
config.urlCredentialStorage = nil
config.urlCache = nil
config.shouldUseExtendedBackgroundIdleMode = true
XCTAssertEqual(config.requestCachePolicy, NSURLRequest.CachePolicy.useProtocolCachePolicy)
XCTAssertEqual(config.timeoutIntervalForRequest, 30)
XCTAssertEqual(config.timeoutIntervalForResource, 604800)
XCTAssertEqual(config.networkServiceType, NSURLRequest.NetworkServiceType.default)
XCTAssertEqual(config.allowsCellularAccess, false)
XCTAssertEqual(config.isDiscretionary, true)
XCTAssertEqual(config.httpShouldUsePipelining, true)
XCTAssertEqual(config.httpShouldSetCookies, true)
XCTAssertEqual(config.httpCookieAcceptPolicy, HTTPCookie.AcceptPolicy.always)
XCTAssertEqual(config.httpMaximumConnectionsPerHost, 2)
XCTAssertEqual(config.httpCookieStorage, HTTPCookieStorage.shared)
XCTAssertEqual(config.urlCredentialStorage, nil)
XCTAssertEqual(config.urlCache, nil)
XCTAssertEqual(config.shouldUseExtendedBackgroundIdleMode, true)
}
func test_basicAuthRequest() {
let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/auth/basic"
let url = URL(string: urlString)!
let d = DataTask(with: expectation(description: "GET \(urlString): with a delegate"))
d.run(with: url)
waitForExpectations(timeout: 60)
}
/* Test for SR-8970 to verify that content-type header is not added to post with empty body */
func test_postWithEmptyBody() {
let config = URLSessionConfiguration.default
config.timeoutIntervalForRequest = 5
let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/emptyPost"
let session = URLSession(configuration: config, delegate: nil, delegateQueue: nil)
var expect = expectation(description: "POST \(urlString): post with empty body")
var req = URLRequest(url: URL(string: urlString)!)
req.httpMethod = "POST"
var task = session.dataTask(with: req) { (_, response, error) -> Void in
defer { expect.fulfill() }
XCTAssertNil(error as? URLError, "error = \(error as! URLError)")
guard let httpresponse = response as? HTTPURLResponse else { fatalError() }
XCTAssertEqual(200, httpresponse.statusCode, "HTTP response code is not 200")
}
task.resume()
waitForExpectations(timeout: 30)
}
func test_basicAuthWithUnauthorizedHeader() {
let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/unauthorized"
let url = URL(string: urlString)!
let expect = expectation(description: "GET \(urlString): with a completion handler")
var expectedResult = "unknown"
let session = URLSession(configuration: URLSessionConfiguration.default)
let task = session.dataTask(with: url) { _, response, error in
defer { expect.fulfill() }
XCTAssertNotNil(response)
XCTAssertNil(error)
}
task.resume()
waitForExpectations(timeout: 12, handler: nil)
}
func test_checkErrorTypeAfterInvalidateAndCancel() throws {
let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/country.txt"
let url = try XCTUnwrap(URL(string: urlString))
var urlRequest = URLRequest(url: url)
urlRequest.addValue("5", forHTTPHeaderField: "X-Pause")
let expect = expectation(description: "Check error code of tasks after invalidateAndCancel")
let delegate = SessionDelegate()
let session = URLSession(configuration: .default, delegate: delegate, delegateQueue: nil)
let task = session.dataTask(with: urlRequest) { (_, _, error) in
XCTAssertNotNil(error as? URLError)
if let urlError = error as? URLError {
XCTAssertEqual(urlError._nsError.code, NSURLErrorCancelled)
}
expect.fulfill()
}
task.resume()
session.invalidateAndCancel()
waitForExpectations(timeout: 5)
}
func test_taskCountAfterInvalidateAndCancel() throws {
let expect = expectation(description: "Check task count after invalidateAndCancel")
let session = URLSession(configuration: .default)
var request = URLRequest(url: try XCTUnwrap(URL(string: "http://127.0.0.1:\(TestURLSession.serverPort)/country.txt")))
request.addValue("5", forHTTPHeaderField: "X-Pause")
let task1 = session.dataTask(with: request)
request.url = try XCTUnwrap(URL(string: "http://127.0.0.1:\(TestURLSession.serverPort)/requestHeaders"))
let task2 = session.dataTask(with: request)
request.url = try XCTUnwrap(URL(string: "http://127.0.0.1:\(TestURLSession.serverPort)/emptyPost"))
let task3 = session.dataTask(with: request)
task1.resume()
task2.resume()
session.invalidateAndCancel()
session.getAllTasks { tasksBeforeResume in
XCTAssertEqual(tasksBeforeResume.count, 0)
// Resume a task after invalidating a session shouldn't change the task's status
task3.resume()
session.getAllTasks { tasksAfterResume in
XCTAssertEqual(tasksAfterResume.count, 0)
expect.fulfill()
}
}
waitForExpectations(timeout: 5)
}
func test_sessionDelegateAfterInvalidateAndCancel() {
let delegate = SessionDelegate()
let session = URLSession(configuration: .default, delegate: delegate, delegateQueue: nil)
session.invalidateAndCancel()
Thread.sleep(forTimeInterval: 2)
XCTAssertNil(session.delegate)
}
func test_getAllTasks() throws {
let expect = expectation(description: "Tasks URLSession.getAllTasks")
let session = URLSession(configuration: .default)
var request = URLRequest(url: try XCTUnwrap(URL(string: "http://127.0.0.1:\(TestURLSession.serverPort)/country.txt")))
request.addValue("5", forHTTPHeaderField: "X-Pause")
let dataTask1 = session.dataTask(with: request)
request.url = try XCTUnwrap(URL(string: "http://127.0.0.1:\(TestURLSession.serverPort)/requestHeaders"))
let dataTask2 = session.dataTask(with: request)
request.url = try XCTUnwrap(URL(string: "http://127.0.0.1:\(TestURLSession.serverPort)/emptyPost"))
let dataTask3 = session.dataTask(with: request)
session.getAllTasks { (tasksBeforeResume) in
XCTAssertEqual(tasksBeforeResume.count, 0)
dataTask1.cancel()
dataTask2.resume()
dataTask2.suspend()
// dataTask3 is suspended even before it was resumed, so the next call to `getAllTasks` should not include this tasks
dataTask3.suspend()
session.getAllTasks { (tasksAfterCancel) in
// tasksAfterCancel should only contain dataTask2
XCTAssertEqual(tasksAfterCancel.count, 1)
// A task will in be in suspended state when it was created.
// Given that, dataTask3 was suspended once again earlier above, so it should receive `resume()` twice in order to be executed
// Calling `getAllTasks` next time should not include dataTask3
dataTask3.resume()
session.getAllTasks { (tasksAfterFirstResume) in
// tasksAfterFirstResume should only contain dataTask2
XCTAssertEqual(tasksAfterFirstResume.count, 1)
// Now dataTask3 received `resume()` twice, this time `getAllTasks` should include
dataTask3.resume()
session.getAllTasks { (tasksAfterSecondResume) in
// tasksAfterSecondResume should contain dataTask2 and dataTask2 this time
XCTAssertEqual(tasksAfterSecondResume.count, 2)
expect.fulfill()
}
}
}
}
waitForExpectations(timeout: 20)
}
func test_getTasksWithCompletion() throws {
let expect = expectation(description: "Test URLSession.getTasksWithCompletion")
let session = URLSession(configuration: .default)
var request = URLRequest(url: try XCTUnwrap(URL(string: "http://127.0.0.1:\(TestURLSession.serverPort)/country.txt")))
request.addValue("5", forHTTPHeaderField: "X-Pause")
let dataTask1 = session.dataTask(with: request)
request.url = try XCTUnwrap(URL(string: "http://127.0.0.1:\(TestURLSession.serverPort)/requestHeaders"))
let dataTask2 = session.dataTask(with: request)
request.url = try XCTUnwrap(URL(string: "http://127.0.0.1:\(TestURLSession.serverPort)/emptyPost"))
let dataTask3 = session.dataTask(with: request)
request.url = try XCTUnwrap(URL(string: "http://127.0.0.1:\(TestURLSession.serverPort)/upload"))
let uploadTask1 = session.uploadTask(with: request, from: Data())
request.url = try XCTUnwrap(URL(string: "http://127.0.0.1:\(TestURLSession.serverPort)/echo"))
let uploadTask2 = session.uploadTask(with: request, from: Data())
request.url = try XCTUnwrap(URL(string: "http://127.0.0.1:\(TestURLSession.serverPort)/DTDs/PropertyList-1.0.dtd"))
let downloadTask1 = session.downloadTask(with: request)
session.getTasksWithCompletionHandler { (dataTasksBeforeCancel, uploadTasksBeforeCancel, downloadTasksBeforeCancel) in
XCTAssertEqual(dataTasksBeforeCancel.count, 0)
XCTAssertEqual(uploadTasksBeforeCancel.count, 0)
XCTAssertEqual(downloadTasksBeforeCancel.count, 0)
dataTask1.cancel()
dataTask2.resume()
// dataTask3 is resumed and suspended, so this task should be a part of `getTasksWithCompletionHandler` response
dataTask3.resume()
dataTask3.suspend()
// uploadTask1 suspended even before it was resumed, so this task shouldn't be a part of `getTasksWithCompletionHandler` response
uploadTask1.suspend()
uploadTask2.resume()
downloadTask1.cancel()
session.getTasksWithCompletionHandler{ (dataTasksAfterCancel, uploadTasksAfterCancel, downloadTasksAfterCancel) in
XCTAssertEqual(dataTasksAfterCancel.count, 2)
XCTAssertEqual(uploadTasksAfterCancel.count, 1)
XCTAssertEqual(downloadTasksAfterCancel.count, 0)
expect.fulfill()
}
}
waitForExpectations(timeout: 20)
}
func test_noDoubleCallbackWhenCancellingAndProtocolFailsFast() throws {
let urlString = "failfast://bogus"
var callbackCount = 0
let callback1 = expectation(description: "Callback call #1")
let callback2 = expectation(description: "Callback call #2")
callback2.isInverted = true
let delegate = SessionDelegate()
let url = try XCTUnwrap(URL(string: urlString))
let configuration = URLSessionConfiguration.default
configuration.protocolClasses = [FailFastProtocol.self]
let session = URLSession(configuration: configuration, delegate: delegate, delegateQueue: nil)
let task = session.dataTask(with: url) { (_, _, error) in
callbackCount += 1
XCTAssertNotNil(error)
if let urlError = error as? URLError {
XCTAssertNotEqual(urlError._nsError.code, NSURLErrorCancelled)
}
if callbackCount == 1 {
callback1.fulfill()
} else {
callback2.fulfill()
}
}
task.resume()
session.invalidateAndCancel()
waitForExpectations(timeout: 1)
}
func test_cancelledTasksCannotBeResumed() throws {
let url = try XCTUnwrap(URL(string: "http://127.0.0.1:\(TestURLSession.serverPort)/Nepal"))
let session = URLSession(configuration: .default, delegate: nil, delegateQueue: nil)
let task = session.dataTask(with: url)
task.cancel() // should set .cancelling and eventually .completed
task.resume() // should not change the task to .running
let e = expectation(description: "getAllTasks callback called")
session.getAllTasks { tasks in
XCTAssertEqual(tasks.count, 0)
e.fulfill()
}
waitForExpectations(timeout: 1)
}
func test_invalidResumeDataForDownloadTask() {
let done = expectation(description: "Invalid resume data for download task (with completion block)")
URLSession.shared.downloadTask(withResumeData: Data()) { (url, response, error) in
XCTAssertNil(url)
XCTAssertNil(response)
XCTAssert(error is URLError)
XCTAssertEqual((error as? URLError)?.errorCode, URLError.unsupportedURL.rawValue)
done.fulfill()
}.resume()
waitForExpectations(timeout: 20)
let d = DownloadTask(testCase: self, description: "Invalid resume data for download task")
d.run { (session) -> DownloadTask.Configuration in
return DownloadTask.Configuration(task: session.downloadTask(withResumeData: Data()),
errorExpectation:
{ (error) in
XCTAssert(error is URLError)
XCTAssertEqual((error as? URLError)?.errorCode, URLError.unsupportedURL.rawValue)
})
}
waitForExpectations(timeout: 20)
}