Skip to content

Commit 7165d15

Browse files
authored
Merge pull request #2527 from drodriguez/tests-rewrite-cookie-tests
[test] Rewrite URLSession cookie tests to be independent.
2 parents 7028b09 + 341872b commit 7165d15

File tree

2 files changed

+116
-57
lines changed

2 files changed

+116
-57
lines changed

TestFoundation/HTTPServer.swift

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -588,17 +588,16 @@ public class TestURLSessionServer {
588588
}
589589

590590
if uri == "/requestCookies" {
591-
let text = request.getCommaSeparatedHeaders()
592-
return _HTTPResponse(response: .OK, headers: "Content-Length: \(text.data(using: .utf8)!.count)\r\nSet-Cookie: fr=anjd&232; Max-Age=7776000; path=/\r\nSet-Cookie: nm=sddf&232; Max-Age=7776000; path=/; domain=.swift.org; secure; httponly\r\n", body: text)
591+
return _HTTPResponse(response: .OK, headers: "Set-Cookie: fr=anjd&232; Max-Age=7776000; path=/\r\nSet-Cookie: nm=sddf&232; Max-Age=7776000; path=/; domain=.swift.org; secure; httponly\r\n", body: "")
593592
}
594593

595-
if uri == "/setCookies" {
594+
if uri == "/echoHeaders" {
596595
let text = request.getCommaSeparatedHeaders()
597596
return _HTTPResponse(response: .OK, headers: "Content-Length: \(text.data(using: .utf8)!.count)", body: text)
598597
}
599598

600-
if uri == "/redirectSetCookies" {
601-
return _HTTPResponse(response: .REDIRECT, headers: "Location: /setCookies\r\nSet-Cookie: redirect=true; Max-Age=7776000; path=/", body: "")
599+
if uri == "/redirectToEchoHeaders" {
600+
return _HTTPResponse(response: .REDIRECT, headers: "Location: /echoHeaders\r\nSet-Cookie: redirect=true; Max-Age=7776000; path=/", body: "")
602601
}
603602

604603
if uri == "/UnitedStates" {

TestFoundation/TestURLSession.swift

Lines changed: 112 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -283,7 +283,7 @@ class TestURLSession : LoopbackServerTest {
283283
let headers = ["header1": "value1"]
284284
req.httpMethod = "POST"
285285
req.allHTTPHeaderFields = headers
286-
var task = session.dataTask(with: req) { (data, _, error) -> Void in
286+
let task = session.dataTask(with: req) { (data, _, error) -> Void in
287287
defer { expect.fulfill() }
288288
XCTAssertNotNil(data)
289289
XCTAssertNil(error as? URLError, "error = \(error as! URLError)")
@@ -310,7 +310,7 @@ class TestURLSession : LoopbackServerTest {
310310
let headers = ["header1": "rvalue1", "header2": "rvalue2", "Header4": "rvalue4"]
311311
req.httpMethod = "POST"
312312
req.allHTTPHeaderFields = headers
313-
var task = session.dataTask(with: req) { (data, _, error) -> Void in
313+
let task = session.dataTask(with: req) { (data, _, error) -> Void in
314314
defer { expect.fulfill() }
315315
XCTAssertNotNil(data)
316316
XCTAssertNil(error as? URLError, "error = \(error as! URLError)")
@@ -334,7 +334,7 @@ class TestURLSession : LoopbackServerTest {
334334
let session = URLSession(configuration: config, delegate: nil, delegateQueue: nil)
335335
var expect = expectation(description: "GET \(urlString): no timeout")
336336
let req = URLRequest(url: URL(string: urlString)!)
337-
var task = session.dataTask(with: req) { (data, _, error) -> Void in
337+
let task = session.dataTask(with: req) { (data, _, error) -> Void in
338338
defer { expect.fulfill() }
339339
XCTAssertNil(error as? URLError, "error = \(error as! URLError)")
340340
}
@@ -351,7 +351,7 @@ class TestURLSession : LoopbackServerTest {
351351
var expect = expectation(description: "GET \(urlString): will timeout")
352352
var req = URLRequest(url: URL(string: "http://127.0.0.1:-1/Peru")!)
353353
req.timeoutInterval = 1
354-
var task = session.dataTask(with: req) { (data, _, error) -> Void in
354+
let task = session.dataTask(with: req) { (data, _, error) -> Void in
355355
defer { expect.fulfill() }
356356
XCTAssertNotNil(error)
357357
}
@@ -414,7 +414,6 @@ class TestURLSession : LoopbackServerTest {
414414
config.timeoutIntervalForRequest = 8
415415
let session = URLSession(configuration: config, delegate: nil, delegateQueue: nil)
416416
let expect = expectation(description: "GET \(urlString): simple HTTP/0.9 response")
417-
var expectedResult = "unknown"
418417
let task = session.dataTask(with: url) { data, response, error in
419418
XCTAssertNotNil(data)
420419
XCTAssertNotNil(response)
@@ -564,25 +563,34 @@ class TestURLSession : LoopbackServerTest {
564563
}
565564
}
566565

567-
func test_disableCookiesStorage() {
568-
let config = URLSessionConfiguration.default
569-
config.timeoutIntervalForRequest = 5
570-
config.httpCookieAcceptPolicy = HTTPCookie.AcceptPolicy.never
571-
if let storage = config.httpCookieStorage, let cookies = storage.cookies {
566+
func emptyCookieStorage(storage: HTTPCookieStorage?) {
567+
if let storage = storage, let cookies = storage.cookies {
572568
for cookie in cookies {
573569
storage.deleteCookie(cookie)
574570
}
575571
}
572+
}
573+
574+
func test_disableCookiesStorage() {
575+
let config = URLSessionConfiguration.default
576+
config.timeoutIntervalForRequest = 5
577+
config.httpCookieAcceptPolicy = HTTPCookie.AcceptPolicy.never
578+
emptyCookieStorage(storage: config.httpCookieStorage)
576579
XCTAssertEqual(config.httpCookieStorage?.cookies?.count, 0)
577580
let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/requestCookies"
578581
let session = URLSession(configuration: config, delegate: nil, delegateQueue: nil)
579582
var expect = expectation(description: "POST \(urlString)")
580583
var req = URLRequest(url: URL(string: urlString)!)
581584
req.httpMethod = "POST"
582-
var task = session.dataTask(with: req) { (data, _, error) -> Void in
585+
let task = session.dataTask(with: req) { (data, response, error) -> Void in
583586
defer { expect.fulfill() }
584587
XCTAssertNotNil(data)
585588
XCTAssertNil(error as? URLError, "error = \(error as! URLError)")
589+
guard let httpResponse = try? XCTUnwrap(response as? HTTPURLResponse) else {
590+
XCTFail("response should be a non-nil HTTPURLResponse")
591+
return
592+
}
593+
XCTAssertNotNil(httpResponse.allHeaderFields["Set-Cookie"])
586594
}
587595
task.resume()
588596
waitForExpectations(timeout: 30)
@@ -593,15 +601,21 @@ class TestURLSession : LoopbackServerTest {
593601
func test_cookiesStorage() {
594602
let config = URLSessionConfiguration.default
595603
config.timeoutIntervalForRequest = 5
604+
emptyCookieStorage(storage: config.httpCookieStorage)
596605
let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/requestCookies"
597606
let session = URLSession(configuration: config, delegate: nil, delegateQueue: nil)
598607
var expect = expectation(description: "POST \(urlString)")
599608
var req = URLRequest(url: URL(string: urlString)!)
600609
req.httpMethod = "POST"
601-
var task = session.dataTask(with: req) { (data, _, error) -> Void in
610+
let task = session.dataTask(with: req) { (data, response, error) -> Void in
602611
defer { expect.fulfill() }
603612
XCTAssertNotNil(data)
604613
XCTAssertNil(error as? URLError, "error = \(error as! URLError)")
614+
guard let httpResponse = try? XCTUnwrap(response as? HTTPURLResponse) else {
615+
XCTFail("response should be a non-nil HTTPURLResponse")
616+
return
617+
}
618+
XCTAssertNotNil(httpResponse.allHeaderFields["Set-Cookie"])
605619
}
606620
task.resume()
607621
waitForExpectations(timeout: 30)
@@ -612,57 +626,81 @@ class TestURLSession : LoopbackServerTest {
612626
func test_redirectionWithSetCookies() {
613627
let config = URLSessionConfiguration.default
614628
config.timeoutIntervalForRequest = 5
615-
if let storage = config.httpCookieStorage, let cookies = storage.cookies {
616-
for cookie in cookies {
617-
storage.deleteCookie(cookie)
618-
}
619-
}
620-
let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/redirectSetCookies"
629+
emptyCookieStorage(storage: config.httpCookieStorage)
630+
let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/redirectToEchoHeaders"
621631
let session = URLSession(configuration: config, delegate: nil, delegateQueue: nil)
622632
var expect = expectation(description: "POST \(urlString)")
623-
var req = URLRequest(url: URL(string: urlString)!)
624-
var task = session.dataTask(with: req) { (data, _, error) -> Void in
633+
let req = URLRequest(url: URL(string: urlString)!)
634+
let task = session.dataTask(with: req) { (data, _, error) -> Void in
625635
defer { expect.fulfill() }
626-
XCTAssertNotNil(data)
636+
// Because /redirectToEchoHeaders is a redirection, this is the
637+
// final result of the redirection, not the redirection itself.
638+
guard let data = try? XCTUnwrap(data) else {
639+
XCTFail("data should not be nil")
640+
return
641+
}
627642
XCTAssertNil(error as? URLError, "error = \(error as! URLError)")
628-
guard let data = data else { return }
629643
let headers = String(data: data, encoding: String.Encoding.utf8) ?? ""
630-
print("headers here = \(headers)")
631644
XCTAssertNotNil(headers.range(of: "Cookie: redirect=true"))
632645
}
633646
task.resume()
634647
waitForExpectations(timeout: 30)
635648
}
636649

637-
func test_setCookies() {
650+
func test_previouslySetCookiesAreSentInLaterRequests() {
638651
let config = URLSessionConfiguration.default
639652
config.timeoutIntervalForRequest = 5
640-
let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/setCookies"
653+
emptyCookieStorage(storage: config.httpCookieStorage)
641654
let session = URLSession(configuration: config, delegate: nil, delegateQueue: nil)
642-
var expect = expectation(description: "POST \(urlString)")
643-
var req = URLRequest(url: URL(string: urlString)!)
644-
req.httpMethod = "POST"
645-
var task = session.dataTask(with: req) { (data, _, error) -> Void in
646-
defer { expect.fulfill() }
655+
656+
let urlString1 = "http://127.0.0.1:\(TestURLSession.serverPort)/requestCookies"
657+
var expect1 = expectation(description: "POST \(urlString1)")
658+
var req1 = URLRequest(url: URL(string: urlString1)!)
659+
req1.httpMethod = "POST"
660+
661+
let urlString2 = "http://127.0.0.1:\(TestURLSession.serverPort)/echoHeaders"
662+
var expect2 = expectation(description: "POST \(urlString2)")
663+
var req2 = URLRequest(url: URL(string: urlString2)!)
664+
req2.httpMethod = "POST"
665+
666+
let task1 = session.dataTask(with: req1) { (data, response, error) -> Void in
667+
defer { expect1.fulfill() }
647668
XCTAssertNotNil(data)
648669
XCTAssertNil(error as? URLError, "error = \(error as! URLError)")
649-
guard let data = data else { return }
650-
let headers = String(data: data, encoding: String.Encoding.utf8) ?? ""
651-
XCTAssertNotNil(headers.range(of: "Cookie: fr=anjd&232"))
670+
guard let httpResponse = try? XCTUnwrap(response as? HTTPURLResponse) else {
671+
XCTFail("response should be a non-nil HTTPURLResponse")
672+
return
673+
}
674+
XCTAssertNotNil(httpResponse.allHeaderFields["Set-Cookie"])
675+
676+
let task2 = session.dataTask(with: req2) { (data, _, error) -> Void in
677+
defer { expect2.fulfill() }
678+
guard let data = try? XCTUnwrap(data) else {
679+
XCTFail("data should not be nil")
680+
return
681+
}
682+
XCTAssertNil(error as? URLError, "error = \(error as! URLError)")
683+
let headers = String(data: data, encoding: String.Encoding.utf8) ?? ""
684+
XCTAssertNotNil(headers.range(of: "Cookie: fr=anjd&232"))
685+
}
686+
task2.resume()
652687
}
653-
task.resume()
688+
task1.resume()
689+
654690
waitForExpectations(timeout: 30)
655691
}
656692

657-
func test_cookieStorageForEphmeralConfiguration() {
693+
func test_cookieStorageForEphemeralConfiguration() {
658694
let config = URLSessionConfiguration.ephemeral
659695
config.timeoutIntervalForRequest = 5
696+
emptyCookieStorage(storage: config.httpCookieStorage)
697+
660698
let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/requestCookies"
661699
let session = URLSession(configuration: config, delegate: nil, delegateQueue: nil)
662700
var expect = expectation(description: "POST \(urlString)")
663701
var req = URLRequest(url: URL(string: urlString)!)
664702
req.httpMethod = "POST"
665-
var task = session.dataTask(with: req) { (data, _, error) -> Void in
703+
let task = session.dataTask(with: req) { (data, _, error) -> Void in
666704
defer { expect.fulfill() }
667705
XCTAssertNotNil(data)
668706
XCTAssertNil(error as? URLError, "error = \(error as! URLError)")
@@ -677,24 +715,47 @@ class TestURLSession : LoopbackServerTest {
677715
XCTAssertEqual(cookies2?.count, 0)
678716
}
679717

680-
func test_dontSetCookies() {
718+
func test_setCookieHeadersCanBeIgnored() {
681719
let config = URLSessionConfiguration.default
682720
config.timeoutIntervalForRequest = 5
683721
config.httpShouldSetCookies = false
684-
let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/setCookies"
722+
emptyCookieStorage(storage: config.httpCookieStorage)
685723
let session = URLSession(configuration: config, delegate: nil, delegateQueue: nil)
686-
var expect = expectation(description: "POST \(urlString)")
687-
var req = URLRequest(url: URL(string: urlString)!)
688-
req.httpMethod = "POST"
689-
var task = session.dataTask(with: req) { (data, _, error) -> Void in
690-
defer { expect.fulfill() }
724+
725+
let urlString1 = "http://127.0.0.1:\(TestURLSession.serverPort)/requestCookies"
726+
var expect1 = expectation(description: "POST \(urlString1)")
727+
var req1 = URLRequest(url: URL(string: urlString1)!)
728+
req1.httpMethod = "POST"
729+
730+
let urlString2 = "http://127.0.0.1:\(TestURLSession.serverPort)/echoHeaders"
731+
var expect2 = expectation(description: "POST \(urlString2)")
732+
var req2 = URLRequest(url: URL(string: urlString2)!)
733+
req2.httpMethod = "POST"
734+
735+
let task1 = session.dataTask(with: req1) { (data, response, error) -> Void in
736+
defer { expect1.fulfill() }
691737
XCTAssertNotNil(data)
692738
XCTAssertNil(error as? URLError, "error = \(error as! URLError)")
693-
guard let data = data else { return }
694-
let headers = String(data: data, encoding: String.Encoding.utf8) ?? ""
695-
XCTAssertNil(headers.range(of: "Cookie: fr=anjd&232"))
739+
guard let httpResponse = try? XCTUnwrap(response as? HTTPURLResponse) else {
740+
XCTFail("response should be a non-nil HTTPURLResponse")
741+
return
742+
}
743+
XCTAssertNotNil(httpResponse.allHeaderFields["Set-Cookie"])
744+
745+
let task2 = session.dataTask(with: req2) { (data, _, error) -> Void in
746+
defer { expect2.fulfill() }
747+
guard let data = try? XCTUnwrap(data) else {
748+
XCTFail("data should not be nil")
749+
return
750+
}
751+
XCTAssertNil(error as? URLError, "error = \(error as! URLError)")
752+
let headers = String(data: data, encoding: String.Encoding.utf8) ?? ""
753+
XCTAssertNil(headers.range(of: "Cookie: fr=anjd&232"))
754+
}
755+
task2.resume()
696756
}
697-
task.resume()
757+
task1.resume()
758+
698759
waitForExpectations(timeout: 30)
699760
}
700761

@@ -749,7 +810,7 @@ class TestURLSession : LoopbackServerTest {
749810
var expect = expectation(description: "POST \(urlString): post with empty body")
750811
var req = URLRequest(url: URL(string: urlString)!)
751812
req.httpMethod = "POST"
752-
var task = session.dataTask(with: req) { (_, response, error) -> Void in
813+
let task = session.dataTask(with: req) { (_, response, error) -> Void in
753814
defer { expect.fulfill() }
754815
XCTAssertNil(error as? URLError, "error = \(error as! URLError)")
755816
guard let httpresponse = response as? HTTPURLResponse else { fatalError() }
@@ -763,7 +824,6 @@ class TestURLSession : LoopbackServerTest {
763824
let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/unauthorized"
764825
let url = URL(string: urlString)!
765826
let expect = expectation(description: "GET \(urlString): with a completion handler")
766-
var expectedResult = "unknown"
767827
let session = URLSession(configuration: URLSessionConfiguration.default)
768828
let task = session.dataTask(with: url) { _, response, error in
769829
defer { expect.fulfill() }
@@ -1052,9 +1112,9 @@ class TestURLSession : LoopbackServerTest {
10521112
("test_concurrentRequests", test_concurrentRequests),
10531113
("test_disableCookiesStorage", test_disableCookiesStorage),
10541114
("test_cookiesStorage", test_cookiesStorage),
1055-
("test_cookieStorageForEphmeralConfiguration", test_cookieStorageForEphmeralConfiguration),
1056-
("test_setCookies", test_setCookies),
1057-
("test_dontSetCookies", test_dontSetCookies),
1115+
("test_cookieStorageForEphemeralConfiguration", test_cookieStorageForEphemeralConfiguration),
1116+
("test_previouslySetCookiesAreSentInLaterRequests", test_previouslySetCookiesAreSentInLaterRequests),
1117+
("test_setCookieHeadersCanBeIgnored", test_setCookieHeadersCanBeIgnored),
10581118
("test_initURLSessionConfiguration", test_initURLSessionConfiguration),
10591119
("test_basicAuthRequest", test_basicAuthRequest),
10601120
("test_redirectionWithSetCookies", test_redirectionWithSetCookies),

0 commit comments

Comments
 (0)