Skip to content

Instantly share code, notes, and snippets.

@akisute
Last active October 6, 2015 17:53
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save akisute/2f87b20272e0c8366694 to your computer and use it in GitHub Desktop.
Save akisute/2f87b20272e0c8366694 to your computer and use it in GitHub Desktop.
Example of APIClient and TestCase in Swift, using AFNetworking/Bolts
import UIKit
// How to make singleton classes in Swift: http://stackoverflow.com/questions/24024549/dispatch-once-singleton-model-in-swift
// Basically using global constants is the most easy and safe way to go
class APIClient: NSObject {
let functionSessionManager:AFHTTPSessionManager
class var sharedInstance:APIClient {
get {
return APIClientSharedInstance;
}
}
init() {
let configuration = NSURLSessionConfiguration.ephemeralSessionConfiguration()
configuration.HTTPAdditionalHeaders = [
"X-Parse-Application-Id": "bSd79gbuQxsyvL1mEF16i9EB58fxr9wQJmLleSG5",
"X-Parse-REST-API-Key": "YrmzQ8SmBwmrwlf4nRzOMeJnHkSXjbmNHb108Ds5",
"Content-Type": "application/json"
]
self.functionSessionManager = AFHTTPSessionManager(baseURL:NSURL(string:"https://api.parse.com/1/functions/"), sessionConfiguration:configuration)
self.functionSessionManager.requestSerializer = AFJSONRequestSerializer(writingOptions:nil)
self.functionSessionManager.responseSerializer = AFJSONResponseSerializer(readingOptions:nil)
}
func getNewWeaponAsync() -> BFTask {
let deferred = BFTaskCompletionSource()
self.functionSessionManager.POST("get_new_weapon", parameters:[:],
success:{task, responseObject in
deferred.setResult(responseObject)
},
failure:{task, error in
deferred.setError(error)
})
return deferred.task
}
}
let APIClientSharedInstance = APIClient()
import XCTest
import HelloSwift
class HelloSwiftTests: XCTestCase {
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
func testExample() {
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
self.measureBlock() {
}
}
/*!
* @const XCTPerformanceMetric_WallClockTime
* Records wall clock time in seconds between startMeasuring/stopMeasuring.
*/
/*!
* @const XCTPerformanceMetric_TotalHeapAllocationsKilobytes
* Records number of kilobytes allocated in heap across all threads in the process (between startMeasuring/stopMeasuring)
*/
/*!
* @const XCTPerformanceMetric_PersistentHeapAllocationsKilobytes
* Records number of kilobytes allocated in heap but not freed across all threads in the process (between startMeasuring/stopMeasuring)
*/
/*!
* @method +defaultPerformanceMetrics
* The names of the performance metrics to measure when invoking -measureBlock:. Returns XCTPerformanceMetric_WallClockTime, XCTPerformanceMetric_TotalHeapAllocationsKilobytes, and XCTPerformanceMetric_PersistentHeapAllocationsKilobytes by default. Subclasses can override this to change the behavior of -measureBlock:
*/
func testPerformanceExample2() {
self.measureMetrics(self.dynamicType.defaultPerformanceMetrics(), automaticallyStartMeasuring:false, forBlock:{
self.startMeasuring()
self.stopMeasuring()
});
}
func testPerformanceExample3() {
self.measureMetrics([XCTPerformanceMetric_WallClockTime, XCTPerformanceMetric_TotalHeapAllocationsKilobytes, XCTPerformanceMetric_PersistentHeapAllocationsKilobytes], automaticallyStartMeasuring:false, forBlock:{
self.startMeasuring()
self.stopMeasuring()
});
}
func testAsynchronousExample() {
let expectation1 = self.expectationWithDescription("Expectation1")
// call expectation1.fulfill() when asynchronous task is succeeded
// call XCTFail() when asynchronous task is failed
APIClient.sharedInstance.getNewWeaponAsync().continueWithExecutor(BFExecutor.mainThreadExecutor(), withBlock:{task in
if let e = task.error() {
XCTFail("Error: \(e)")
}
if let result:AnyObject = task.result() {
NSLog("Result (1st attempt): \(result)")
}
return APIClient.sharedInstance.getNewWeaponAsync()
}).continueWithExecutor(BFExecutor.mainThreadExecutor(), withBlock:{task in
if let e = task.error() {
XCTFail("Error: \(e)")
}
if let result:AnyObject = task.result() {
NSLog("Result (2nd attempt): \(result)")
}
expectation1.fulfill()
return nil
})
self.waitForExpectationsWithTimeout(10.0, handler:{(error:NSError!) -> Void in
// When this handler is called, the asynchronous task is already timed out, or XCTFail() is called
// You may not call XCTFail() here because the test is already failed!
// You can tear down any resources used, or log something in here
if let e = error {
println("Error: \(e)")
}
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment