Skip to content

Commit

Permalink
Refactored all tests to follow Given / When / Then structure.
Browse files Browse the repository at this point in the history
Also reworked all tests to be crash safe and fixed the OS X tests.
  • Loading branch information
cnoon committed May 18, 2015
1 parent b328797 commit a967279
Show file tree
Hide file tree
Showing 9 changed files with 853 additions and 417 deletions.
206 changes: 155 additions & 51 deletions Tests/AuthenticationTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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")
}
}
101 changes: 63 additions & 38 deletions Tests/DownloadTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand All @@ -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")
}
}
Loading

0 comments on commit a967279

Please sign in to comment.