提交 ed82371e 编写于 作者: C Christian Noon

Merge pull request #489 from Alamofire/test/given_when_then

Switch test suite to use Given | When | Then structure
......@@ -7,6 +7,8 @@
objects = {
/* Begin PBXBuildFile section */
4C256A531B096C770065714F /* BaseTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C256A501B096C2C0065714F /* BaseTestCase.swift */; };
4C256A541B096C770065714F /* BaseTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C256A501B096C2C0065714F /* BaseTestCase.swift */; };
4CDE2C371AF8932A00BABAE5 /* Manager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4CDE2C361AF8932A00BABAE5 /* Manager.swift */; };
4CDE2C381AF8932A00BABAE5 /* Manager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4CDE2C361AF8932A00BABAE5 /* Manager.swift */; };
4CDE2C3A1AF899EC00BABAE5 /* Request.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4CDE2C391AF899EC00BABAE5 /* Request.swift */; };
......@@ -64,6 +66,7 @@
/* End PBXContainerItemProxy section */
/* Begin PBXFileReference section */
4C256A501B096C2C0065714F /* BaseTestCase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BaseTestCase.swift; sourceTree = "<group>"; };
4CDE2C361AF8932A00BABAE5 /* Manager.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Manager.swift; sourceTree = "<group>"; };
4CDE2C391AF899EC00BABAE5 /* Request.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Request.swift; sourceTree = "<group>"; };
4CDE2C3C1AF89D4900BABAE5 /* Download.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Download.swift; sourceTree = "<group>"; };
......@@ -123,6 +126,29 @@
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
4C256A4E1B09656A0065714F /* Core */ = {
isa = PBXGroup;
children = (
F8E6024419CB46A800A3E7F1 /* AuthenticationTests.swift */,
F8D1C6F419D52968002E74FE /* ManagerTests.swift */,
F8111E5C19A9674D0040E7D1 /* ParameterEncodingTests.swift */,
F8111E5D19A9674D0040E7D1 /* RequestTests.swift */,
F8111E5E19A9674D0040E7D1 /* ResponseTests.swift */,
);
name = Core;
sourceTree = "<group>";
};
4C256A4F1B09656E0065714F /* Features */ = {
isa = PBXGroup;
children = (
F8111E5B19A9674D0040E7D1 /* DownloadTests.swift */,
F86AEFE51AE6A282007D9C76 /* TLSEvaluationTests.swift */,
F8111E5F19A9674D0040E7D1 /* UploadTests.swift */,
F8AE910119D28DCC0078C7B2 /* ValidationTests.swift */,
);
name = Features;
sourceTree = "<group>";
};
4CDE2C481AF8A14A00BABAE5 /* Core */ = {
isa = PBXGroup;
children = (
......@@ -187,15 +213,9 @@
F8111E3F19A95C8B0040E7D1 /* Tests */ = {
isa = PBXGroup;
children = (
F8111E5C19A9674D0040E7D1 /* ParameterEncodingTests.swift */,
F8111E5D19A9674D0040E7D1 /* RequestTests.swift */,
F8D1C6F419D52968002E74FE /* ManagerTests.swift */,
F8111E5E19A9674D0040E7D1 /* ResponseTests.swift */,
F8111E5F19A9674D0040E7D1 /* UploadTests.swift */,
F8111E5B19A9674D0040E7D1 /* DownloadTests.swift */,
F8E6024419CB46A800A3E7F1 /* AuthenticationTests.swift */,
F8AE910119D28DCC0078C7B2 /* ValidationTests.swift */,
F86AEFE51AE6A282007D9C76 /* TLSEvaluationTests.swift */,
4C256A501B096C2C0065714F /* BaseTestCase.swift */,
4C256A4E1B09656A0065714F /* Core */,
4C256A4F1B09656E0065714F /* Features */,
F8111E4019A95C8B0040E7D1 /* Supporting Files */,
);
path = Tests;
......@@ -414,6 +434,7 @@
files = (
F86AEFE71AE6A312007D9C76 /* TLSEvaluationTests.swift in Sources */,
F8858DDD19A96B4300F55F93 /* RequestTests.swift in Sources */,
4C256A531B096C770065714F /* BaseTestCase.swift in Sources */,
F8E6024519CB46A800A3E7F1 /* AuthenticationTests.swift in Sources */,
F8858DDE19A96B4400F55F93 /* ResponseTests.swift in Sources */,
F8D1C6F519D52968002E74FE /* ManagerTests.swift in Sources */,
......@@ -430,6 +451,7 @@
files = (
F829C6BE1A7A950600A2CD59 /* ParameterEncodingTests.swift in Sources */,
F829C6BF1A7A950600A2CD59 /* RequestTests.swift in Sources */,
4C256A541B096C770065714F /* BaseTestCase.swift in Sources */,
F829C6C01A7A950600A2CD59 /* ManagerTests.swift in Sources */,
F829C6C11A7A950600A2CD59 /* ResponseTests.swift in Sources */,
F829C6C21A7A950600A2CD59 /* UploadTests.swift in Sources */,
......
......@@ -20,81 +20,185 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import Alamofire
import Foundation
import XCTest
class AlamofireAuthenticationTestCase: XCTestCase {
func testHTTPBasicAuthentication() {
let user = "user"
let password = "password"
let URL = "http://httpbin.org/basic-auth/\(user)/\(password)"
class AuthenticationTestCase: BaseTestCase {
// MARK: Properties
let invalidCredentialsExpectation = expectationWithDescription("\(URL) 401")
let user = "user"
let password = "password"
var URLString = ""
Alamofire.request(.GET, URL)
.authenticate(user: "invalid", password: "credentials")
.response { request, response, _, error in
XCTAssertNotNil(request, "request should not be nil")
XCTAssertNil(response, "response should be nil")
XCTAssertNotNil(error, "error should not be nil")
XCTAssert(error?.code == -999, "error should be NSURLErrorDomain Code -999 'cancelled'")
// MARK: Setup and Teardown
override func tearDown() {
super.tearDown()
invalidCredentialsExpectation.fulfill()
let credentialStorage = NSURLCredentialStorage.sharedCredentialStorage()
let allCredentials = credentialStorage.allCredentials as! [NSURLProtectionSpace: AnyObject]
for (protectionSpace, credentials) in allCredentials {
if let credentials = credentials as? [String: NSURLCredential] {
for (user, credential) in credentials {
credentialStorage.removeCredential(credential, forProtectionSpace: protectionSpace)
}
}
}
}
}
let validCredentialsExpectation = expectationWithDescription("\(URL) 200")
// MARK: -
Alamofire.request(.GET, URL)
.authenticate(user: user, password: password)
.response { request, response, _, error in
XCTAssertNotNil(request, "request should not be nil")
XCTAssertNotNil(response, "response should not be nil")
XCTAssert(response?.statusCode == 200, "response status code should be 200")
XCTAssertNil(error, "error should be nil")
class BasicAuthenticationTestCase: AuthenticationTestCase {
// MARK: Setup and Teardown
validCredentialsExpectation.fulfill()
override func setUp() {
super.setUp()
self.URLString = "http://httpbin.org/basic-auth/\(user)/\(password)"
}
// MARK: Tests
func testHTTPBasicAuthenticationWithInvalidCredentials() {
// Given
let expectation = expectationWithDescription("\(self.URLString) 401")
var request: NSURLRequest?
var response: NSHTTPURLResponse?
var data: AnyObject?
var error: NSError?
// When
Alamofire.request(.GET, self.URLString)
.authenticate(user: "invalid", password: "credentials")
.response { responseRequest, responseResponse, responseData, responseError in
request = responseRequest
response = responseResponse
data = responseData
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(10) { error in
XCTAssertNil(error, "\(error)")
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(request, "request should not be nil")
XCTAssertNil(response, "response should be nil")
XCTAssertNotNil(data, "data should not be nil")
XCTAssertNotNil(error, "error should not be nil")
XCTAssertEqual(error?.code ?? 0, -999, "error should be NSURLErrorDomain Code -999 'cancelled'")
}
func testHTTPBasicAuthenticationWithValidCredentials() {
// Given
let expectation = expectationWithDescription("\(self.URLString) 200")
var request: NSURLRequest?
var response: NSHTTPURLResponse?
var data: AnyObject?
var error: NSError?
// When
Alamofire.request(.GET, self.URLString)
.authenticate(user: self.user, password: self.password)
.response { responseRequest, responseResponse, responseData, responseError in
request = responseRequest
response = responseResponse
data = responseData
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(request, "request should not be nil")
XCTAssertNotNil(response, "response should not be nil")
XCTAssertEqual(response?.statusCode ?? 0, 200, "response status code should be 200")
XCTAssertNotNil(data, "data should not be nil")
XCTAssertNil(error, "error should be nil")
}
}
// MARK: -
func testHTTPDigestAuthentication() {
let qop = "auth"
let user = "user"
let password = "password"
let URL = "http://httpbin.org/digest-auth/\(qop)/\(user)/\(password)"
class HTTPDigestAuthenticationTestCase: AuthenticationTestCase {
// MARK: Properties
let invalidCredentialsExpectation = expectationWithDescription("\(URL) 401")
let qop = "auth"
Alamofire.request(.GET, URL)
// MARK: Setup and Teardown
override func setUp() {
super.setUp()
self.URLString = "http://httpbin.org/digest-auth/\(qop)/\(user)/\(password)"
}
// MARK: Tests
func testHTTPDigestAuthenticationWithInvalidCredentials() {
// Given
let expectation = expectationWithDescription("\(self.URLString) 401")
var request: NSURLRequest?
var response: NSHTTPURLResponse?
var data: AnyObject?
var error: NSError?
// When
Alamofire.request(.GET, self.URLString)
.authenticate(user: "invalid", password: "credentials")
.response { request, response, _, error in
XCTAssertNotNil(request, "request should not be nil")
XCTAssertNil(response, "response should be nil")
XCTAssertNotNil(error, "error should not be nil")
XCTAssert(error?.code == -999, "error should be NSURLErrorDomain Code -999 'cancelled'")
.response { responseRequest, responseResponse, responseData, responseError in
request = responseRequest
response = responseResponse
data = responseData
error = responseError
invalidCredentialsExpectation.fulfill()
expectation.fulfill()
}
let validCredentialsExpectation = expectationWithDescription("\(URL) 200")
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
Alamofire.request(.GET, URL)
.authenticate(user: user, password: password)
.response { request, response, _, error in
XCTAssertNotNil(request, "request should not be nil")
XCTAssertNotNil(response, "response should not be nil")
XCTAssert(response?.statusCode == 200, "response status code should be 200")
XCTAssertNil(error, "error should be nil")
// Then
XCTAssertNotNil(request, "request should not be nil")
XCTAssertNil(response, "response should be nil")
XCTAssertNotNil(data, "data should not be nil")
XCTAssertNotNil(error, "error should not be nil")
XCTAssertEqual(error?.code ?? 0, -999, "error should be NSURLErrorDomain Code -999 'cancelled'")
}
validCredentialsExpectation.fulfill()
func testHTTPDigestAuthenticationWithValidCredentials() {
// Given
let expectation = expectationWithDescription("\(self.URLString) 200")
var request: NSURLRequest?
var response: NSHTTPURLResponse?
var data: AnyObject?
var error: NSError?
// When
Alamofire.request(.GET, self.URLString)
.authenticate(user: self.user, password: self.password)
.response { responseRequest, responseResponse, responseData, responseError in
request = responseRequest
response = responseResponse
data = responseData
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(10) { error in
XCTAssertNil(error, "\(error)")
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(request, "request should not be nil")
XCTAssertNotNil(response, "response should not be nil")
XCTAssertEqual(response?.statusCode ?? 0, 200, "response status code should be 200")
XCTAssertNotNil(data, "data should not be nil")
XCTAssertNil(error, "error should be nil")
}
}
// DownloadTests.swift
//
// Copyright (c) 2014–2015 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
class BaseTestCase: XCTestCase {
let defaultTimeout: NSTimeInterval = 10
}
......@@ -20,50 +20,67 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import Alamofire
import Foundation
import XCTest
class AlamofireDownloadResponseTestCase: XCTestCase {
let searchPathDirectory: NSSearchPathDirectory = .DocumentDirectory
class DownloadResponseTestCase: BaseTestCase {
// MARK: - Properties
let searchPathDirectory: NSSearchPathDirectory = .CachesDirectory
let searchPathDomain: NSSearchPathDomainMask = .UserDomainMask
// MARK: -
// MARK: - Tests
func testDownloadRequest() {
// Given
let numberOfLines = 100
let URL = "http://httpbin.org/stream/\(numberOfLines)"
let destination = Alamofire.Request.suggestedDownloadDestination(directory: searchPathDirectory, domain: searchPathDomain)
let expectation = expectationWithDescription(URL)
let destination = Alamofire.Request.suggestedDownloadDestination(directory: searchPathDirectory, domain: searchPathDomain)
var request: NSURLRequest?
var response: NSHTTPURLResponse?
var error: NSError?
// When
Alamofire.download(.GET, URL, destination)
.response { request, response, _, error in
XCTAssertNotNil(request, "request should not be nil")
XCTAssertNotNil(response, "response should not be nil")
.response { responseRequest, responseResponse, _, responseError in
request = responseRequest
response = responseResponse
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
XCTAssertNil(error, "error should be nil")
// Then
XCTAssertNotNil(request, "request should not be nil")
XCTAssertNotNil(response, "response should not be nil")
XCTAssertNil(error, "error should be nil")
let fileManager = NSFileManager.defaultManager()
let directory = fileManager.URLsForDirectory(self.searchPathDirectory, inDomains: self.searchPathDomain)[0] as! NSURL
let fileManager = NSFileManager.defaultManager()
let directory = fileManager.URLsForDirectory(self.searchPathDirectory, inDomains: self.searchPathDomain)[0] as! NSURL
var fileManagerError: NSError?
let contents = fileManager.contentsOfDirectoryAtURL(directory, includingPropertiesForKeys: nil, options: NSDirectoryEnumerationOptions.SkipsHiddenFiles, error: &fileManagerError)!
XCTAssertNil(fileManagerError, "fileManagerError should be nil")
var fileManagerError: NSError?
if let contents = fileManager.contentsOfDirectoryAtURL(directory, includingPropertiesForKeys: nil, options: .SkipsHiddenFiles, error: &fileManagerError) {
XCTAssertNil(fileManagerError, "fileManagerError should be nil")
#if os(iOS)
let suggestedFilename = "\(numberOfLines)"
#elseif os(OSX)
let suggestedFilename = "\(numberOfLines).json"
#endif
#if os(iOS)
let suggestedFilename = "\(numberOfLines)"
#elseif os(OSX)
let suggestedFilename = "\(numberOfLines).json"
#endif
let predicate = NSPredicate(format: "lastPathComponent = '\(suggestedFilename)'")
let filteredContents = (contents as NSArray).filteredArrayUsingPredicate(predicate)
XCTAssertEqual(filteredContents.count, 1, "should have one file in Documents")
let predicate = NSPredicate(format: "lastPathComponent = '\(suggestedFilename)'")
let filteredContents = (contents as NSArray).filteredArrayUsingPredicate(predicate)
XCTAssertEqual(filteredContents.count, 1, "should have one file in Documents")
let file = filteredContents.first as! NSURL
XCTAssertEqual(file.lastPathComponent!, "\(suggestedFilename)", "filename should be \(suggestedFilename)")
if let file = filteredContents.first as? NSURL {
XCTAssertEqual(file.lastPathComponent ?? "", "\(suggestedFilename)", "filename should be \(suggestedFilename)")
if let data = NSData(contentsOfURL: file) {
XCTAssertGreaterThan(data.length, 0, "data length should be non-zero")
......@@ -72,36 +89,44 @@ class AlamofireDownloadResponseTestCase: XCTestCase {
}
fileManager.removeItemAtURL(file, error: nil)
expectation.fulfill()
}
waitForExpectationsWithTimeout(10) { error in
XCTAssertNil(error, "\(error)")
} else {
XCTFail("file should not be nil")
}
} else {
XCTFail("contents should not be nil")
}
}
func testDownloadRequestWithProgress() {
// Given
let numberOfLines = 100
let URL = "http://httpbin.org/stream/\(numberOfLines)"
let destination = Alamofire.Request.suggestedDownloadDestination(directory: searchPathDirectory, domain: searchPathDomain)
let expectation = expectationWithDescription(URL)
let destination = Alamofire.Request.suggestedDownloadDestination(directory: searchPathDirectory, domain: searchPathDomain)
var bytesRead: Int64?
var totalBytesRead: Int64?
var totalBytesExpectedToRead: Int64?
// When
let download = Alamofire.download(.GET, URL, destination)
download.progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in
XCTAssert(bytesRead > 0, "bytesRead should be > 0")
XCTAssert(totalBytesRead > 0, "totalBytesRead should be > 0")
XCTAssert(totalBytesExpectedToRead == -1, "totalBytesExpectedToRead should be -1")
download.progress { progressBytesRead, progressTotalBytesRead, progressTotalBytesExpectedToRead in
bytesRead = progressBytesRead
totalBytesRead = progressTotalBytesRead
totalBytesExpectedToRead = progressTotalBytesExpectedToRead
download.cancel()
expectation.fulfill()
}
waitForExpectationsWithTimeout(10) { error in
XCTAssertNil(error, "\(error)")
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertGreaterThan(bytesRead ?? 0, 0, "bytesRead should be > 0")
XCTAssertGreaterThan(totalBytesRead ?? 0, 0, "totalBytesRead should be > 0")
XCTAssertEqual(totalBytesExpectedToRead ?? 0, -1, "totalBytesExpectedToRead should be -1")
}
}
......@@ -20,12 +20,13 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import Alamofire
import Foundation
import XCTest
class AlamofireManagerTestCase: XCTestCase {
class ManagerTestCase: BaseTestCase {
func testSetStartRequestsImmediatelyToFalseAndResumeRequest() {
// Given
let manager = Alamofire.Manager()
manager.startRequestsImmediately = false
......@@ -34,43 +35,55 @@ class AlamofireManagerTestCase: XCTestCase {
let expectation = expectationWithDescription("\(URL)")
var response: NSHTTPURLResponse?
// When
manager.request(URLRequest)
.response { _, _, _, _ in expectation.fulfill() }
.response { _, responseResponse, _, _ in
response = responseResponse
expectation.fulfill()
}
.resume()
waitForExpectationsWithTimeout(10) { error in
XCTAssertNil(error, "\(error)")
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(response, "response should not be nil")
XCTAssertTrue(response?.statusCode == 200, "response status code should be 200")
}
func testReleasingManagerWithPendingRequestDeinitializesSuccessfully() {
// Given
var manager: Manager? = Alamofire.Manager()
manager!.startRequestsImmediately = false
manager?.startRequestsImmediately = false
let URL = NSURL(string: "http://httpbin.org/get")!
let URLRequest = NSURLRequest(URL: URL)
let request = manager!.request(URLRequest)
// When
let request = manager?.request(URLRequest)
manager = nil
XCTAssert(request.task.state == .Suspended)
XCTAssertNil(manager)
// Then
XCTAssertTrue(request?.task.state == .Suspended, "request task state should be '.Suspended'")
XCTAssertNil(manager, "manager should be nil")
}
func testReleasingManagerWithPendingCanceledRequestDeinitializesSuccessfully() {
// Given
var manager: Manager? = Alamofire.Manager()
manager!.startRequestsImmediately = false
manager?.startRequestsImmediately = false
let URL = NSURL(string: "http://httpbin.org/get")!
let URLRequest = NSURLRequest(URL: URL)
let request = manager!.request(URLRequest)
request.cancel()
// When
let request = manager?.request(URLRequest)
request?.cancel()
manager = nil
XCTAssert(request.task.state == .Canceling)
XCTAssertNil(manager)
// Then
XCTAssert(request?.task.state == .Canceling, "request task state should be '.Canceling'")
XCTAssertNil(manager, "manager should be nil")
}
}
此差异已折叠。
......@@ -20,120 +20,164 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import Alamofire
import Foundation
import XCTest
class AlamofireRequestInitializationTestCase: XCTestCase {
class RequestInitializationTestCase: BaseTestCase {
func testRequestClassMethodWithMethodAndURL() {
// Given
let URL = "http://httpbin.org/"
// When
let request = Alamofire.request(.GET, URL)
// Then
XCTAssertNotNil(request.request, "request should not be nil")
XCTAssertEqual(request.request.URL!, NSURL(string: URL)!, "request URL should be equal")
XCTAssertNil(request.response, "response should be nil")
}
func testRequestClassMethodWithMethodAndURLAndParameters() {
// Given
let URL = "http://httpbin.org/get"
// When
let request = Alamofire.request(.GET, URL, parameters: ["foo": "bar"])
// Then
XCTAssertNotNil(request.request, "request should not be nil")
XCTAssertNotEqual(request.request.URL!, NSURL(string: URL)!, "request URL should be equal")
XCTAssertEqual(request.request.URL!.query!, "foo=bar", "query is incorrect")
XCTAssertEqual(request.request.URL?.query ?? "", "foo=bar", "query is incorrect")
XCTAssertNil(request.response, "response should be nil")
}
}
class AlamofireRequestResponseTestCase: XCTestCase {
// MARK: -
class RequestResponseTestCase: BaseTestCase {
func testRequestResponse() {
// Given
let URL = "http://httpbin.org/get"
let serializer = Alamofire.Request.stringResponseSerializer(encoding: NSUTF8StringEncoding)
let expectation = expectationWithDescription("\(URL)")
var request: NSURLRequest?
var response: NSHTTPURLResponse?
var string: AnyObject?
var error: NSError?
// When
Alamofire.request(.GET, URL, parameters: ["foo": "bar"])
.response(serializer: serializer){ (request, response, string, error) in
XCTAssertNotNil(request, "request should not be nil")
XCTAssertNotNil(response, "response should not be nil")
XCTAssertNotNil(string, "string should not be nil")
XCTAssertNil(error, "error should be nil")
.response(serializer: serializer) { responseRequest, responseResponse, responseString, responseError in
request = responseRequest
response = responseResponse
string = responseString
error = responseError
expectation.fulfill()
expectation.fulfill()
}
waitForExpectationsWithTimeout(10) { error in
XCTAssertNil(error, "\(error)")
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(request, "request should not be nil")
XCTAssertNotNil(response, "response should not be nil")
XCTAssertNotNil(string, "string should not be nil")
XCTAssertNil(error, "error should be nil")
}
}
class AlamofireRequestDescriptionTestCase: XCTestCase {
// MARK: -
class RequestDescriptionTestCase: BaseTestCase {
func testRequestDescription() {
// Given
let URL = "http://httpbin.org/get"
let request = Alamofire.request(.GET, URL)
XCTAssertEqual(request.description, "GET http://httpbin.org/get", "incorrect request description")
let initialRequestDescription = request.description
let expectation = expectationWithDescription("\(URL)")
request.response { _, response, _, _ in
XCTAssertEqual(request.description, "GET http://httpbin.org/get (\(response!.statusCode))", "incorrect request description")
var finalRequestDescription: String?
var response: NSHTTPURLResponse?
// When
request.response { _, responseResponse, _, _ in
finalRequestDescription = request.description
response = responseResponse
expectation.fulfill()
}
waitForExpectationsWithTimeout(10) { error in
XCTAssertNil(error, "\(error)")
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertEqual(initialRequestDescription, "GET http://httpbin.org/get", "incorrect request description")
XCTAssertEqual(finalRequestDescription ?? "", "GET http://httpbin.org/get (\(response?.statusCode ?? -1))", "incorrect request description")
}
}
class AlamofireRequestDebugDescriptionTestCase: XCTestCase {
// MARK: -
class RequestDebugDescriptionTestCase: BaseTestCase {
// MARK: Properties
let manager: Alamofire.Manager = {
let manager = Alamofire.Manager(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
manager.startRequestsImmediately = false
return manager
}()
// MARK: -
// MARK: Tests
func testGETRequestDebugDescription() {
// Given
let URL = "http://httpbin.org/get"
// When
let request = manager.request(.GET, URL)
let components = cURLCommandComponents(request)
XCTAssert(components[0..<3] == ["$", "curl", "-i"], "components should be equal")
XCTAssert(!contains(components, "-X"), "command should not contain explicit -X flag")
XCTAssert(components.last! == "\"\(URL)\"", "URL component should be equal")
// Then
XCTAssertEqual(components[0..<3], ["$", "curl", "-i"], "components should be equal")
XCTAssertFalse(contains(components, "-X"), "command should not contain explicit -X flag")
XCTAssertEqual(components.last ?? "", "\"\(URL)\"", "URL component should be equal")
}
func testPOSTRequestDebugDescription() {
// Given
let URL = "http://httpbin.org/post"
// When
let request = manager.request(.POST, URL)
let components = cURLCommandComponents(request)
XCTAssert(components[0..<3] == ["$", "curl", "-i"], "components should be equal")
XCTAssert(components[3..<5] == ["-X", "POST"], "command should contain explicit -X flag")
XCTAssert(components.last! == "\"\(URL)\"", "URL component should be equal")
// Then
XCTAssertEqual(components[0..<3], ["$", "curl", "-i"], "components should be equal")
XCTAssertEqual(components[3..<5], ["-X", "POST"], "command should contain explicit -X flag")
XCTAssertEqual(components.last ?? "", "\"\(URL)\"", "URL component should be equal")
}
func testPOSTRequestWithJSONParametersDebugDescription() {
// Given
let URL = "http://httpbin.org/post"
// When
let request = manager.request(.POST, URL, parameters: ["foo": "bar"], encoding: .JSON)
let components = cURLCommandComponents(request)
XCTAssert(components[0..<3] == ["$", "curl", "-i"], "components should be equal")
XCTAssert(components[3..<5] == ["-X", "POST"], "command should contain explicit -X flag")
XCTAssert(request.debugDescription.rangeOfString("-H \"Content-Type: application/json\"") != nil)
XCTAssert(request.debugDescription.rangeOfString("-d \"{\\\"foo\\\":\\\"bar\\\"}\"") != nil)
XCTAssert(components.last! == "\"\(URL)\"", "URL component should be equal")
// Then
XCTAssertEqual(components[0..<3], ["$", "curl", "-i"], "components should be equal")
XCTAssertEqual(components[3..<5], ["-X", "POST"], "command should contain explicit -X flag")
XCTAssertTrue(request.debugDescription.rangeOfString("-H \"Content-Type: application/json\"") != nil, "command should contain 'application/json' Content-Type")
XCTAssertTrue(request.debugDescription.rangeOfString("-d \"{\\\"foo\\\":\\\"bar\\\"}\"") != nil, "command data should contain JSON encoded parameters")
XCTAssertEqual(components.last ?? "", "\"\(URL)\"", "URL component should be equal")
}
// Temporarily disabled on OS X due to build failure for CocoaPods
// See https://github.com/CocoaPods/swift/issues/24
#if !os(OSX)
func testPOSTRequestWithCookieDebugDescription() {
// Given
let URL = "http://httpbin.org/post"
let properties = [
......@@ -145,17 +189,21 @@ class AlamofireRequestDebugDescriptionTestCase: XCTestCase {
let cookie = NSHTTPCookie(properties: properties)!
manager.session.configuration.HTTPCookieStorage?.setCookie(cookie)
// When
let request = manager.request(.POST, URL)
let components = cURLCommandComponents(request)
XCTAssert(components[0..<3] == ["$", "curl", "-i"], "components should be equal")
XCTAssert(components[3..<5] == ["-X", "POST"], "command should contain explicit -X flag")
XCTAssert(components[5..<6] == ["-b"], "command should contain -b flag")
XCTAssert(components.last! == "\"\(URL)\"", "URL component should be equal")
// Then
XCTAssertEqual(components[0..<3], ["$", "curl", "-i"], "components should be equal")
XCTAssertEqual(components[3..<5], ["-X", "POST"], "command should contain explicit -X flag")
XCTAssertEqual(components.last ?? "", "\"\(URL)\"", "URL component should be equal")
#if !os(OSX)
XCTAssertEqual(components[5..<6], ["-b"], "command should contain -b flag")
#endif
}
#endif
// MARK: -
// MARK: Test Helper Methods
private func cURLCommandComponents(request: Request) -> [String] {
return request.debugDescription.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).filter { $0 != "" && $0 != "\\" }
......
......@@ -20,59 +20,90 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import Alamofire
import Foundation
import XCTest
class AlamofireJSONResponseTestCase: XCTestCase {
class JSONResponseTestCase: BaseTestCase {
func testGETRequestJSONResponse() {
// Given
let URL = "http://httpbin.org/get"
let expectation = expectationWithDescription("\(URL)")
Alamofire.request(.GET, URL, parameters: ["foo": "bar"])
.responseJSON { request, response, JSON, error in
XCTAssertNotNil(request, "request should not be nil")
XCTAssertNotNil(response, "response should not be nil")
XCTAssertNotNil(JSON, "JSON should not be nil")
XCTAssertNil(error, "error should be nil")
var request: NSURLRequest?
var response: NSHTTPURLResponse?
var JSON: AnyObject?
var error: NSError?
XCTAssertEqual(JSON!["args"] as! NSObject, ["foo": "bar"], "args should be equal")
// When
Alamofire.request(.GET, URL, parameters: ["foo": "bar"])
.responseJSON { responseRequest, responseResponse, responseJSON, responseError in
request = responseRequest
response = responseResponse
JSON = responseJSON
error = responseError
expectation.fulfill()
expectation.fulfill()
}
waitForExpectationsWithTimeout(10) { error in
XCTAssertNil(error, "\(error)")
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(request, "request should not be nil")
XCTAssertNotNil(response, "response should not be nil")
XCTAssertNotNil(JSON, "JSON should not be nil")
XCTAssertNil(error, "error should be nil")
if let args = JSON?["args"] as? NSObject {
XCTAssertEqual(args, ["foo": "bar"], "args should match parameters")
} else {
XCTFail("args should not be nil")
}
}
func testPOSTRequestJSONResponse() {
// Given
let URL = "http://httpbin.org/post"
let expectation = expectationWithDescription("\(URL)")
Alamofire.request(.POST, URL, parameters: ["foo": "bar"])
.responseJSON { request, response, JSON, error in
XCTAssertNotNil(request, "request should not be nil")
XCTAssertNotNil(response, "response should not be nil")
XCTAssertNotNil(JSON, "JSON should not be nil")
XCTAssertNil(error, "error should be nil")
var request: NSURLRequest?
var response: NSHTTPURLResponse?
var JSON: AnyObject?
var error: NSError?
XCTAssertEqual(JSON!["form"] as! NSObject, ["foo": "bar"], "args should be equal")
// When
Alamofire.request(.POST, URL, parameters: ["foo": "bar"])
.responseJSON { responseRequest, responseResponse, responseJSON, responseError in
request = responseRequest
response = responseResponse
JSON = responseJSON
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(10) { error in
XCTAssertNil(error, "\(error)")
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(request, "request should not be nil")
XCTAssertNotNil(response, "response should not be nil")
XCTAssertNotNil(JSON, "JSON should not be nil")
XCTAssertNil(error, "error should be nil")
if let form = JSON?["form"] as? NSObject {
XCTAssertEqual(form, ["foo": "bar"], "form should match parameters")
} else {
XCTFail("form should not be nil")
}
}
}
class AlamofireRedirectResponseTestCase: XCTestCase {
func testGETRequestRedirectResponse() {
let URL = "http://google.com"
let expectation = expectationWithDescription("\(URL)")
// MARK: -
class RedirectResponseTestCase: BaseTestCase {
func testGETRequestRedirectResponse() {
// Given
let URLString = "http://google.com"
let delegate: Alamofire.Manager.SessionDelegate = Alamofire.Manager.sharedInstance.delegate
delegate.taskWillPerformHTTPRedirection = { session, task, response, request in
......@@ -80,52 +111,75 @@ class AlamofireRedirectResponseTestCase: XCTestCase {
return request
}
Alamofire.request(.GET, URL)
.response { request, response, data, error in
XCTAssertNotNil(request, "request should not be nil")
XCTAssertNotNil(response, "response should not be nil")
XCTAssertNotNil(data, "data should not be nil")
XCTAssertNil(error, "error should be nil")
let expectation = expectationWithDescription("\(URLString)")
var request: NSURLRequest?
var response: NSHTTPURLResponse?
var data: AnyObject?
var error: NSError?
XCTAssertEqual(response!.URL!, NSURL(string: "http://www.google.com/")!, "request should have followed a redirect")
XCTAssertEqual(response!.statusCode, 200, "response should have a 200 status code")
// When
Alamofire.request(.GET, URLString)
.response { responseRequest, responseResponse, responseData, responseError in
request = responseRequest
response = responseResponse
data = responseData
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(10) { error in
XCTAssertNil(error, "\(error)")
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(request, "request should not be nil")
XCTAssertNotNil(response, "response should not be nil")
XCTAssertNotNil(data, "data should not be nil")
XCTAssertNil(error, "error should be nil")
XCTAssertEqual(response?.URL ?? NSURL(), NSURL(string: "http://www.google.com/")!, "request should have followed a redirect")
XCTAssertEqual(response?.statusCode ?? -1, 200, "response should have a 200 status code")
}
func testGETRequestDisallowRedirectResponse() {
let URL = "http://google.com/"
let expectation = expectationWithDescription("\(URL)")
// Given
let URLString = "http://google.com/"
let delegate: Alamofire.Manager.SessionDelegate = Alamofire.Manager.sharedInstance.delegate
delegate.taskWillPerformHTTPRedirection = { session, task, response, request in
// Disallow redirects by returning nil.
// TODO: NSURLSessionDelegate's URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:
// suggests that returning nil should refuse the redirect, but this causes a deadlock/timeout
return NSURLRequest(URL: NSURL(string: URL)!)
// NOTE: NSURLSessionDelegate's `URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:`
// suggests that returning nil should refuse the redirect, but this causes a deadlock/timeout.
return NSURLRequest(URL: NSURL(string: URLString)!)
}
Alamofire.request(.GET, URL)
.response { request, response, data, error in
XCTAssertNotNil(request, "request should not be nil")
XCTAssertNotNil(response, "response should not be nil")
XCTAssertNotNil(data, "data should not be nil")
XCTAssertNil(error, "error should be nil")
let expectation = expectationWithDescription("\(URLString)")
var request: NSURLRequest?
var response: NSHTTPURLResponse?
var data: AnyObject?
var error: NSError?
XCTAssertEqual(response!.URL!, NSURL(string: URL)!, "request should not have followed a redirect")
XCTAssertEqual(response!.statusCode, 301, "response should have a 301 status code")
// When
Alamofire.request(.GET, URLString)
.response { responseRequest, responseResponse, responseData, responseError in
request = responseRequest
response = responseResponse
data = responseData
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(10) { error in
XCTAssertNil(error, "\(error)")
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(request, "request should not be nil")
XCTAssertNotNil(response, "response should not be nil")
XCTAssertNotNil(data, "data should not be nil")
XCTAssertNil(error, "error should be nil")
XCTAssertEqual(response?.URL ?? NSURL(string: "")!, NSURL(string: URLString)!, "request should not have followed a redirect")
XCTAssertEqual(response?.statusCode ?? -1, 301, "response should have a 301 status code")
}
}
......@@ -20,26 +20,29 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import Alamofire
import Foundation
import XCTest
class AlamofireTLSEvaluationTestCase: XCTestCase {
func testSSLCertificateCommonNameValidation() {
class TLSEvaluationTestCase: BaseTestCase {
func testThatExpiredSSLCertificateFailsEvaluation() {
// Given
let URL = "https://testssl-expire.disig.sk/"
let expectation = expectationWithDescription("\(URL)")
Alamofire.request(.GET, URL)
.response { _, _, _, error in
XCTAssertNotNil(error, "error should not be nil")
XCTAssert(error?.code == NSURLErrorServerCertificateUntrusted, "error should be NSURLErrorServerCertificateUntrusted")
var error: NSError?
// When
Alamofire.request(.GET, URL)
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(10) { error in
XCTAssertNil(error, "\(error)")
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(error, "error should not be nil")
XCTAssertEqual(error?.code ?? -1, NSURLErrorServerCertificateUntrusted, "error should be NSURLErrorServerCertificateUntrusted")
}
}
......@@ -20,50 +20,68 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import Alamofire
import Foundation
import XCTest
class UploadResponseTestCase: XCTestCase {
class UploadResponseTestCase: BaseTestCase {
func testUploadRequest() {
// Given
let URL = "http://httpbin.org/post"
let data = "Lorem ipsum dolor sit amet".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
let data = "Lorem ipsum dolor sit amet".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
let expectation = expectationWithDescription(URL)
Alamofire.upload(.POST, URL, data!)
.response { request, response, _, error in
XCTAssertNotNil(request, "request should not be nil")
XCTAssertNotNil(response, "response should not be nil")
XCTAssertNil(error, "error should be nil")
var request: NSURLRequest?
var response: NSHTTPURLResponse?
var error: NSError?
expectation.fulfill()
}
// When
Alamofire.upload(.POST, URL, data)
.response { responseRequest, responseResponse, _, responseError in
request = responseRequest
response = responseResponse
error = responseError
waitForExpectationsWithTimeout(10) { error in
XCTAssertNil(error, "\(error)")
expectation.fulfill()
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(request, "request should not be nil")
XCTAssertNotNil(response, "response should not be nil")
XCTAssertNil(error, "error should be nil")
}
func testUploadRequestWithProgress() {
// Given
let URL = "http://httpbin.org/post"
let data = "Lorem ipsum dolor sit amet".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
let data = "Lorem ipsum dolor sit amet".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
let expectation = expectationWithDescription(URL)
let upload = Alamofire.upload(.POST, URL, data!)
upload.progress { bytesWritten, totalBytesWritten, totalBytesExpectedToWrite in
XCTAssert(bytesWritten > 0, "bytesWritten should be > 0")
XCTAssert(totalBytesWritten > 0, "totalBytesWritten should be > 0")
XCTAssert(totalBytesExpectedToWrite > 0, "totalBytesExpectedToWrite should be > 0")
var bytesWritten: Int64?
var totalBytesWritten: Int64?
var totalBytesExpectedToWrite: Int64?
// When
let upload = Alamofire.upload(.POST, URL, data)
upload.progress { progressBytesWritten, progressTotalBytesWritten, progressTotalBytesExpectedToWrite in
bytesWritten = progressBytesWritten
totalBytesWritten = progressTotalBytesWritten
totalBytesExpectedToWrite = progressTotalBytesExpectedToWrite
upload.cancel()
expectation.fulfill()
}
waitForExpectationsWithTimeout(10) { error in
XCTAssertNil(error, "\(error)")
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertGreaterThan(bytesWritten ?? 0, 0, "bytesWritten should be > 0")
XCTAssertGreaterThan(totalBytesWritten ?? 0, 0, "totalBytesWritten should be > 0")
XCTAssertGreaterThan(totalBytesExpectedToWrite ?? 0, 0, "totalBytesExpectedToWrite should be > 0")
}
}
......@@ -20,285 +20,336 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import Alamofire
import Foundation
import XCTest
class AlamofireStatusCodeValidationTestCase: XCTestCase {
class StatusCodeValidationTestCase: BaseTestCase {
func testValidationForRequestWithAcceptableStatusCodeResponse() {
// Given
let URL = "http://httpbin.org/status/200"
let expectation = expectationWithDescription("\(URL)")
var error: NSError?
// When
Alamofire.request(.GET, URL)
.validate(statusCode: 200..<300)
.response { _, _, _, error in
XCTAssertNil(error, "error should be nil")
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(10) { error in
XCTAssertNil(error, "\(error)")
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNil(error, "error should be nil")
}
func testValidationForRequestWithUnacceptableStatusCodeResponse() {
// Given
let URL = "http://httpbin.org/status/404"
let expectation = expectationWithDescription("\(URL)")
var error: NSError?
// When
Alamofire.request(.GET, URL)
.validate(statusCode: [200])
.response { _, _, _, error in
XCTAssertNotNil(error, "error should not be nil")
XCTAssertEqual(error!.domain, AlamofireErrorDomain, "error should be in Alamofire error domain")
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(10) { error in
XCTAssertNil(error, "\(error)")
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(error, "error should not be nil")
XCTAssertEqual(error?.domain ?? "", AlamofireErrorDomain, "error should be in Alamofire error domain")
}
func testValidationForRequestWithNoAcceptableStatusCodes() {
// Given
let URL = "http://httpbin.org/status/201"
let expectation = expectationWithDescription("\(URL)")
var error: NSError?
// When
Alamofire.request(.GET, URL)
.validate(statusCode: [])
.response { _, _, _, error in
XCTAssertNotNil(error, "error should not be nil")
XCTAssertEqual(error!.domain, AlamofireErrorDomain, "error should be in Alamofire error domain")
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(10) { error in
XCTAssertNil(error, "\(error)")
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(error, "error should not be nil")
XCTAssertEqual(error?.domain ?? "", AlamofireErrorDomain, "error should be in Alamofire error domain")
}
}
class AlamofireContentTypeValidationTestCase: XCTestCase {
// MARK: -
class ContentTypeValidationTestCase: BaseTestCase {
func testValidationForRequestWithAcceptableContentTypeResponse() {
// Given
let URL = "http://httpbin.org/ip"
let expectation = expectationWithDescription("\(URL)")
var error: NSError?
// When
Alamofire.request(.GET, URL)
.validate(contentType: ["application/json"])
.response { _, _, _, error in
XCTAssertNil(error, "error should be nil")
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(10) { error in
XCTAssertNil(error, "\(error)")
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNil(error, "error should be nil")
}
func testValidationForRequestWithAcceptableWildcardContentTypeResponse() {
// Given
let URL = "http://httpbin.org/ip"
let expectation = expectationWithDescription("\(URL)")
var error: NSError?
// When
Alamofire.request(.GET, URL)
.validate(contentType: ["*/*"])
.validate(contentType: ["application/*"])
.validate(contentType: ["*/json"])
.response { _, _, _, error in
XCTAssertNil(error, "error should be nil")
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(10) { error in
XCTAssertNil(error, "\(error)")
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNil(error, "error should be nil")
}
func testValidationForRequestWithUnacceptableContentTypeResponse() {
// Given
let URL = "http://httpbin.org/xml"
let expectation = expectationWithDescription("\(URL)")
var error: NSError?
// When
Alamofire.request(.GET, URL)
.validate(contentType: ["application/octet-stream"])
.response { _, _, _, error in
XCTAssertNotNil(error, "error should not be nil")
XCTAssertEqual(error!.domain, AlamofireErrorDomain, "error should be in Alamofire error domain")
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(10) { error in
XCTAssertNil(error, "\(error)")
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(error, "error should not be nil")
XCTAssertEqual(error?.domain ?? "", AlamofireErrorDomain, "error should be in Alamofire error domain")
}
func testValidationForRequestWithNoAcceptableContentTypeResponse() {
// Given
let URL = "http://httpbin.org/xml"
let expectation = expectationWithDescription("\(URL)")
var error: NSError?
// When
Alamofire.request(.GET, URL)
.validate(contentType: [])
.response { _, _, _, error in
XCTAssertNotNil(error, "error should not be nil")
XCTAssertEqual(error!.domain, AlamofireErrorDomain, "error should be in Alamofire error domain")
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(10) { error in
XCTAssertNil(error, "\(error)")
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(error, "error should not be nil")
XCTAssertEqual(error?.domain ?? "", AlamofireErrorDomain, "error should be in Alamofire error domain")
}
}
class AlamofireMultipleValidationTestCase: XCTestCase {
// MARK: -
class MultipleValidationTestCase: BaseTestCase {
func testValidationForRequestWithAcceptableStatusCodeAndContentTypeResponse() {
// Given
let URL = "http://httpbin.org/ip"
let expectation = expectationWithDescription("\(URL)")
var error: NSError?
// When
Alamofire.request(.GET, URL)
.validate(statusCode: 200..<300)
.validate(contentType: ["application/json"])
.response { _, _, _, error in
XCTAssertNil(error, "error should be nil")
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(10) { error in
XCTAssertNil(error, "\(error)")
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNil(error, "error should be nil")
}
func testValidationForRequestWithUnacceptableStatusCodeAndContentTypeResponse() {
// Given
let URL = "http://httpbin.org/xml"
let expectation = expectationWithDescription("\(URL)")
var error: NSError?
// When
Alamofire.request(.GET, URL)
.validate(statusCode: 400..<600)
.validate(contentType: ["application/octet-stream"])
.response { _, _, _, error in
XCTAssertNotNil(error, "error should not be nil")
XCTAssertEqual(error!.domain, AlamofireErrorDomain, "error should be in Alamofire error domain")
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(10) { error in
XCTAssertNil(error, "\(error)")
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(error, "error should not be nil")
XCTAssertEqual(error?.domain ?? "", AlamofireErrorDomain, "error should be in Alamofire error domain")
}
}
class AlamofireAutomaticValidationTestCase: XCTestCase {
// MARK: -
class AutomaticValidationTestCase: BaseTestCase {
func testValidationForRequestWithAcceptableStatusCodeAndContentTypeResponse() {
// Given
let URL = NSURL(string: "http://httpbin.org/ip")!
let mutableURLRequest = NSMutableURLRequest(URL: URL)
mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Accept")
let expectation = expectationWithDescription("\(URL)")
var error: NSError?
// When
Alamofire.request(.GET, URL)
.validate()
.response { _, _, _, error in
XCTAssertNil(error, "error should be nil")
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(10) { error in
XCTAssertNil(error, "\(error)")
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNil(error, "error should be nil")
}
func testValidationForRequestWithUnacceptableStatusCodeResponse() {
// Given
let URL = "http://httpbin.org/status/404"
let expectation = expectationWithDescription("\(URL)")
var error: NSError?
// When
Alamofire.request(.GET, URL)
.validate()
.response { _, _, _, error in
XCTAssertNotNil(error, "error should not be nil")
XCTAssertEqual(error!.domain, AlamofireErrorDomain, "error should be in Alamofire error domain")
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(10) { error in
XCTAssertNil(error, "\(error)")
}
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(error, "error should not be nil")
XCTAssertEqual(error!.domain, AlamofireErrorDomain, "error should be in Alamofire error domain")
}
func testValidationForRequestWithAcceptableWildcardContentTypeResponse() {
// Given
let URL = NSURL(string: "http://httpbin.org/ip")!
let mutableURLRequest = NSMutableURLRequest(URL: URL)
mutableURLRequest.setValue("application/*", forHTTPHeaderField: "Accept")
let expectation = expectationWithDescription("\(URL)")
var error: NSError?
// When
Alamofire.request(.GET, URL)
.validate()
.response { _, _, _, error in
XCTAssertNil(error, "error should be nil")
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(10) { error in
XCTAssertNil(error, "\(error)")
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNil(error, "error should be nil")
}
func testValidationForRequestWithAcceptableComplexContentTypeResponse() {
// Given
let URL = NSURL(string: "http://httpbin.org/xml")!
let mutableURLRequest = NSMutableURLRequest(URL: URL)
mutableURLRequest.setValue("text/xml, application/xml, application/xhtml+xml, text/html;q=0.9, text/plain;q=0.8,*/*;q=0.5", forHTTPHeaderField: "Accept")
let expectation = expectationWithDescription("\(URL)")
var error: NSError?
// When
Alamofire.request(.GET, URL)
.validate()
.response { _, _, _, error in
XCTAssertNil(error, "error should be nil")
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(10) { error in
XCTAssertNil(error, "\(error)")
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNil(error, "error should be nil")
}
func testValidationForRequestWithUnacceptableContentTypeResponse() {
// Given
let URL = NSURL(string: "http://httpbin.org/xml")!
let mutableURLRequest = NSMutableURLRequest(URL: URL)
mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Accept")
let expectation = expectationWithDescription("\(URL)")
var error: NSError?
// When
Alamofire.request(.GET, URL)
.validate()
.response { _, _, _, error in
XCTAssertNil(error, "error should be nil")
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(10) { error in
XCTAssertNil(error, "\(error)")
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNil(error, "error should be nil")
}
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册