diff options
Diffstat (limited to 'platform/ios/test/OHHTTPStubs/OHHTTPStubs/UnitTests/Test Suites')
9 files changed, 0 insertions, 1874 deletions
diff --git a/platform/ios/test/OHHTTPStubs/OHHTTPStubs/UnitTests/Test Suites/AFNetworkingTests.m b/platform/ios/test/OHHTTPStubs/OHHTTPStubs/UnitTests/Test Suites/AFNetworkingTests.m deleted file mode 100644 index a4ee670a6e..0000000000 --- a/platform/ios/test/OHHTTPStubs/OHHTTPStubs/UnitTests/Test Suites/AFNetworkingTests.m +++ /dev/null @@ -1,225 +0,0 @@ -/*********************************************************************************** - * - * Copyright (c) 2012 Olivier Halligon - * - * 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 <XCTest/XCTest.h> -#import <OHHTTPStubs/OHHTTPStubs.h> - -#import "AFHTTPRequestOperation.h" - -static const NSTimeInterval kResponseTimeTolerence = 1.0; - -@interface AFNetworkingTests : XCTestCase @end - -@implementation AFNetworkingTests - --(void)setUp -{ - [super setUp]; - [OHHTTPStubs removeAllStubs]; -} - --(void)test_AFHTTPRequestOperation_success -{ - static const NSTimeInterval kRequestTime = 0.05; - static const NSTimeInterval kResponseTime = 0.1; - NSData* expectedResponse = [NSStringFromSelector(_cmd) dataUsingEncoding:NSUTF8StringEncoding]; - [OHHTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) { - return YES; - } withStubResponse:^OHHTTPStubsResponse *(NSURLRequest *request) { - return [[OHHTTPStubsResponse responseWithData:expectedResponse statusCode:200 headers:nil] - requestTime:kRequestTime responseTime:kResponseTime]; - }]; - - XCTestExpectation* expectation = [self expectationWithDescription:@"AFHTTPRequestOperation request finished"]; - - NSURLRequest* req = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.iana.org/domains/example/"]]; - AFHTTPRequestOperation* op = [[AFHTTPRequestOperation alloc] initWithRequest:req]; - [op setResponseSerializer:[AFHTTPResponseSerializer serializer]]; - __block __strong id response = nil; - [op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { - response = responseObject; // keep strong reference - [expectation fulfill]; - } failure:^(AFHTTPRequestOperation *operation, NSError *error) { - XCTFail(@"Unexpected network failure"); - [expectation fulfill]; - }]; - [op start]; - - [self waitForExpectationsWithTimeout:kRequestTime+kResponseTime+kResponseTimeTolerence handler:nil]; - - XCTAssertEqualObjects(response, expectedResponse, @"Unexpected data received"); -} - --(void)test_AFHTTPRequestOperation_multiple_choices -{ - static const NSTimeInterval kRequestTime = 0.05; - static const NSTimeInterval kResponseTime = 0.1; - NSData* expectedResponse = [NSStringFromSelector(_cmd) dataUsingEncoding:NSUTF8StringEncoding]; - [OHHTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) { - return YES; - } withStubResponse:^OHHTTPStubsResponse *(NSURLRequest *request) { - return [[OHHTTPStubsResponse responseWithData:expectedResponse statusCode:300 headers:@{@"Location":@"http://www.iana.org/domains/another/example"}] - requestTime:kRequestTime responseTime:kResponseTime]; - }]; - - XCTestExpectation* expectation = [self expectationWithDescription:@"AFHTTPRequestOperation request finished"]; - - NSURLRequest* req = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.iana.org/domains/example/"]]; - AFHTTPRequestOperation* op = [[AFHTTPRequestOperation alloc] initWithRequest:req]; - AFHTTPResponseSerializer* serializer = [AFHTTPResponseSerializer serializer]; - [serializer setAcceptableStatusCodes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(200, 101)]]; - [op setResponseSerializer:serializer]; - - __block __strong id response = nil; - [op setRedirectResponseBlock:^NSURLRequest *(NSURLConnection *connection, NSURLRequest *request, NSURLResponse *redirectResponse) { - if (redirectResponse == nil) { - return request; - } - XCTFail(@"Unexpected redirect"); - return nil; - }]; - - [op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { - response = responseObject; // keep strong reference - [expectation fulfill]; - } failure:^(AFHTTPRequestOperation *operation, NSError *error) { - XCTFail(@"Unexpected network failure"); - [expectation fulfill]; - }]; - [op start]; - - [self waitForExpectationsWithTimeout:kRequestTime+kResponseTime+kResponseTimeTolerence handler:nil]; - - XCTAssertEqualObjects(response, expectedResponse, @"Unexpected data received"); -} - --(void)test_AFHTTPRequestOperation_redirect -{ - static const NSTimeInterval kRequestTime = 0.05; - static const NSTimeInterval kResponseTime = 0.1; - - NSURL* redirectURL = [NSURL URLWithString:@"http://www.iana.org/domains/another/example"]; - [OHHTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) { - return YES; - } withStubResponse:^OHHTTPStubsResponse *(NSURLRequest *request) { - return [[OHHTTPStubsResponse responseWithData:[NSData data] statusCode:311 headers:@{@"Location":redirectURL.absoluteString}] - requestTime:kRequestTime responseTime:kResponseTime]; - }]; - - XCTestExpectation* expectation = [self expectationWithDescription:@"AFHTTPRequestOperation request finished"]; - - NSURLRequest* req = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.iana.org/domains/example/"]]; - AFHTTPRequestOperation* op = [[AFHTTPRequestOperation alloc] initWithRequest:req]; - [op setResponseSerializer:[AFHTTPResponseSerializer serializer]]; - - __block __strong NSURL* url = nil; - [op setRedirectResponseBlock:^NSURLRequest *(NSURLConnection *connection, NSURLRequest *request, NSURLResponse *redirectResponse) { - if (redirectResponse == nil) { - return request; - } - url = request.URL; - [expectation fulfill]; - return nil; - }]; - - [op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { - XCTFail(@"Unexpected response"); - [expectation fulfill]; - } failure:^(AFHTTPRequestOperation *operation, NSError *error) { - XCTFail(@"Unexpected network failure"); - [expectation fulfill]; - }]; - [op start]; - - [self waitForExpectationsWithTimeout:kRequestTime+kResponseTime+kResponseTimeTolerence handler:nil]; - - XCTAssertEqualObjects(url, redirectURL, @"Unexpected data received"); -} - -@end - - - -#pragma mark - NSURLSession / AFHTTPURLSession support - -// Compile this only if SDK version (…MAX_ALLOWED) is iOS7+/10.9+ because NSURLSession is a class only known starting these SDKs -// (this code won't compile if we use an eariler SDKs, like when building with Xcode4) -#if (defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000) \ - || (defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && __MAC_OS_X_VERSION_MAX_ALLOWED >= 1090) - -#import "AFHTTPSessionManager.h" - -@interface AFNetworkingTests (NSURLSession) @end -@implementation AFNetworkingTests (NSURLSession) - -- (void)test_AFHTTPURLSessionCustom -{ - if ([NSURLSession class] && [NSURLSessionConfiguration class]) - { - static const NSTimeInterval kRequestTime = 0.1; - static const NSTimeInterval kResponseTime = 0.2; - NSDictionary *expectedResponseDict = @{@"Success" : @"Yes"}; - - [OHHTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) { - return [request.URL.scheme isEqualToString:@"stubs"]; - } withStubResponse:^OHHTTPStubsResponse *(NSURLRequest *request) { - return [[OHHTTPStubsResponse responseWithJSONObject:expectedResponseDict statusCode:200 headers:nil] - requestTime:kRequestTime responseTime:kResponseTime]; - }]; - - XCTestExpectation* expectation = [self expectationWithDescription:@"AFHTTPSessionManager request finished"]; - - NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration]; - NSURL* baseURL = [NSURL URLWithString:@"stubs://stubs/"]; - AFHTTPSessionManager *sessionManager = [[AFHTTPSessionManager alloc] initWithBaseURL:baseURL - sessionConfiguration:sessionConfig]; - - __block __strong id response = nil; - [sessionManager GET:@"foo" - parameters:nil - success:^(NSURLSessionDataTask *task, id responseObject) { - response = responseObject; // keep strong reference - [expectation fulfill]; - } - failure:^(NSURLSessionDataTask *task, NSError *error) { - XCTFail(@"Unexpected network failure"); - [expectation fulfill]; - }]; - - [self waitForExpectationsWithTimeout:kRequestTime+kResponseTime+kResponseTimeTolerence handler:nil]; - - XCTAssertEqualObjects(response, expectedResponseDict, @"Unexpected data received"); - } - else - { - NSLog(@"/!\\ Test skipped because the NSURLSession class is not available on this OS version. Run the tests a target with a more recent OS.\n"); - } -} - -@end - -#else -#warning Unit Tests using NSURLSession were not compiled nor executed, because NSURLSession is only available since iOS7/OSX10.9 SDK. \ --------- Compile using iOS7 or OSX10.9 SDK then launch the tests on the iOS7 simulator or an OSX10.9 target for them to be executed. -#endif diff --git a/platform/ios/test/OHHTTPStubs/OHHTTPStubs/UnitTests/Test Suites/MocktailTests.m b/platform/ios/test/OHHTTPStubs/OHHTTPStubs/UnitTests/Test Suites/MocktailTests.m deleted file mode 100644 index db7725703c..0000000000 --- a/platform/ios/test/OHHTTPStubs/OHHTTPStubs/UnitTests/Test Suites/MocktailTests.m +++ /dev/null @@ -1,147 +0,0 @@ -/*********************************************************************************** - * - * Copyright (c) 2015 Jinlian (Sunny) Wang - * - * 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 <XCTest/XCTest.h> -#import <OHHTTPStubs/OHHTTPStubs.h> - -@interface MocktailTests : XCTestCase -@property(nonatomic, strong) NSURLSession *session; -@end - -@implementation MocktailTests - -- (void)setUp -{ - [super setUp]; - [OHHTTPStubs removeAllStubs]; - - NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; - self.session = [NSURLSession sessionWithConfiguration:configuration delegate:nil delegateQueue:nil]; -} - -- (void)tearDown -{ - [super tearDown]; - self.session = nil; -} - -- (void)testMoctTailLoginSuccess -{ - NSError *error = nil; - NSBundle *bundle = [NSBundle bundleForClass:self.class]; - [OHHTTPStubs stubRequestsUsingMocktailNamed:@"login" inBundle:bundle error: &error]; - XCTAssertNil(error, @"Error while stubbing 'login.tail':%@", [error localizedDescription]); - [self runLogin]; -} - -- (void)testMocktailsAtFolder -{ - NSError *error = nil; - NSBundle *bundle = [NSBundle bundleForClass:self.class]; - [OHHTTPStubs stubRequestsUsingMocktailsAtPath:@"MocktailFolder" inBundle:bundle error:&error]; - XCTAssertNil(error, @"Error while stubbing Mocktails at folder 'MocktailFolder': %@", [error localizedDescription]); - [self runLogin]; - [self runGetCards]; -} - -- (void)runLogin -{ - NSURL *url = [NSURL URLWithString:@"http://happywebservice.com/users"]; - NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url - cachePolicy:NSURLRequestUseProtocolCachePolicy - timeoutInterval:60.0]; - - [request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; - [request addValue:@"application/json" forHTTPHeaderField:@"Accept"]; - - request.HTTPMethod = @"POST"; - NSDictionary *mapData = @{@"iloveit": @"happyuser1", - @"password": @"username"}; - NSData *postData = [NSJSONSerialization dataWithJSONObject:mapData options:0 error:NULL]; - request.HTTPBody = postData; - - XCTestExpectation* expectation = [self expectationWithDescription:@"NSURLSessionDataTask completed"]; - - NSURLSessionDataTask *postDataTask = [self.session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { - - XCTAssertNil(error, @"Error while logging in."); - - NSDictionary *json = nil; - if(!error && [@"application/json" isEqual:response.MIMEType]) - { - json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error]; - } - - XCTAssertNotNil(json, @"The response is not a json object"); - XCTAssertEqualObjects(json[@"status"], @"SUCCESS", @"The response does to return a successful status"); - XCTAssertNotNil(json[@"user_token"], @"The response does not contain a user token"); - - [expectation fulfill]; - }]; - - [postDataTask resume]; - - [self waitForExpectationsWithTimeout:10 handler:nil]; -} - -- (void)runGetCards -{ - NSURL *url = [NSURL URLWithString:@"http://happywebservice.com/cards"]; - NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url - cachePolicy:NSURLRequestUseProtocolCachePolicy - timeoutInterval:60.0]; - - [request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; - [request addValue:@"application/json" forHTTPHeaderField:@"Accept"]; - - request.HTTPMethod = @"GET"; - - XCTestExpectation* expectation = [self expectationWithDescription:@"NSURLSessionDataTask completed"]; - - NSURLSessionDataTask *getDataTask = [self.session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { - - XCTAssertNil(error, @"Error while getting cards."); - - NSArray *json = nil; - if(!error && [@"application/json" isEqual:response.MIMEType]) - { - json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error]; - } - - XCTAssertNotNil(json, @"The response is not a json object"); - XCTAssertEqual(json.count, 2, @"The response does not contain 2 cards"); - XCTAssertEqualObjects([json firstObject][@"amount"], @"$25.28", @"The first card amount does not match"); - - [expectation fulfill]; - }]; - - [getDataTask resume]; - - [self waitForExpectationsWithTimeout:10 handler:nil]; -} - -@end diff --git a/platform/ios/test/OHHTTPStubs/OHHTTPStubs/UnitTests/Test Suites/NSURLConnectionDelegateTests.m b/platform/ios/test/OHHTTPStubs/OHHTTPStubs/UnitTests/Test Suites/NSURLConnectionDelegateTests.m deleted file mode 100644 index 1321854169..0000000000 --- a/platform/ios/test/OHHTTPStubs/OHHTTPStubs/UnitTests/Test Suites/NSURLConnectionDelegateTests.m +++ /dev/null @@ -1,394 +0,0 @@ -/*********************************************************************************** - * - * Copyright (c) 2012 Olivier Halligon - * - * 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 <XCTest/XCTest.h> -#import <OHHTTPStubs/OHHTTPStubs.h> - -@interface NSURLConnectionDelegateTests : XCTestCase <NSURLConnectionDataDelegate> @end - -static const NSTimeInterval kResponseTimeTolerence = 0.2; - -@implementation NSURLConnectionDelegateTests -{ - NSMutableData* _data; - NSError* _error; - - NSURL* _redirectRequestURL; - NSInteger _redirectResponseStatusCode; - - XCTestExpectation* _connectionFinishedExpectation; -} - -/////////////////////////////////////////////////////////////////////////////////// -#pragma mark Global Setup + NSURLConnectionDelegate implementation -/////////////////////////////////////////////////////////////////////////////////// - --(void)setUp -{ - [super setUp]; - _data = [[NSMutableData alloc] init]; - [OHHTTPStubs removeAllStubs]; -} - --(void)tearDown -{ - // in case the test timed out and finished before a running NSURLConnection ended, - // we may continue receive delegate messages anyway if we forgot to cancel. - // So avoid sending messages to deallocated object in this case by ensuring we reset it to nil - _data = nil; - _error = nil; - _connectionFinishedExpectation = nil; - [super tearDown]; -} - -- (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response -{ - _redirectRequestURL = request.URL; - if (response) - { - if ([response isKindOfClass:NSHTTPURLResponse.class]) - { - _redirectResponseStatusCode = ((NSHTTPURLResponse *) response).statusCode; - } - else - { - _redirectResponseStatusCode = 0; - } - } - else - { - // we get a nil response when NSURLConnection canonicalizes the URL, we don't care about that. - } - return request; -} - --(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response -{ - _data.length = 0U; -} - --(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data -{ - [_data appendData:data]; -} - --(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error -{ - _error = error; // keep strong reference - [_connectionFinishedExpectation fulfill]; -} - --(void)connectionDidFinishLoading:(NSURLConnection *)connection -{ - [_connectionFinishedExpectation fulfill]; -} - - - -/////////////////////////////////////////////////////////////////////////////////// -#pragma mark NSURLConnection + Delegate -/////////////////////////////////////////////////////////////////////////////////// - --(void)test_NSURLConnectionDelegate_success -{ - static const NSTimeInterval kRequestTime = 0.1; - static const NSTimeInterval kResponseTime = 0.5; - NSData* testData = [NSStringFromSelector(_cmd) dataUsingEncoding:NSUTF8StringEncoding]; - - [OHHTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) { - return YES; - } withStubResponse:^OHHTTPStubsResponse *(NSURLRequest *request) { - return [[OHHTTPStubsResponse responseWithData:testData - statusCode:200 - headers:nil] - requestTime:kRequestTime responseTime:kResponseTime]; - }]; - - _connectionFinishedExpectation = [self expectationWithDescription:@"NSURLConnection did finish (with error or success)"]; - - NSURLRequest* req = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.iana.org/domains/example/"]]; - NSDate* startDate = [NSDate date]; - - NSURLConnection* cxn = [NSURLConnection connectionWithRequest:req delegate:self]; - - [self waitForExpectationsWithTimeout:kRequestTime+kResponseTime+kResponseTimeTolerence handler:nil]; - - XCTAssertEqualObjects(_data, testData, @"Invalid data response"); - XCTAssertNil(_error, @"Received unexpected network error %@", _error); - XCTAssertEqualWithAccuracy(-[startDate timeIntervalSinceNow], kRequestTime+kResponseTime, kResponseTimeTolerence, @"Invalid response time"); - - // in case we timed out before the end of the request (test failed), cancel the request to avoid further delegate method calls - [cxn cancel]; -} - --(void)test_NSURLConnectionDelegate_multiple_choices -{ - static const NSTimeInterval kRequestTime = 0.1; - static const NSTimeInterval kResponseTime = 0.5; - NSData* testData = [NSStringFromSelector(_cmd) dataUsingEncoding:NSUTF8StringEncoding]; - - [OHHTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) { - return YES; - } withStubResponse:^OHHTTPStubsResponse *(NSURLRequest *request) { - return [[OHHTTPStubsResponse responseWithData:testData - statusCode:300 - headers:@{@"Location":@"http://www.iana.org/domains/another/example"}] - requestTime:kRequestTime responseTime:kResponseTime]; - }]; - - _connectionFinishedExpectation = [self expectationWithDescription:@"NSURLConnection did finish (with error or success)"]; - - NSURLRequest* req = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.iana.org/domains/example/"]]; - NSDate* startDate = [NSDate date]; - - NSURLConnection* cxn = [NSURLConnection connectionWithRequest:req delegate:self]; - - [self waitForExpectationsWithTimeout:kRequestTime+kResponseTime+kResponseTimeTolerence handler:nil]; - - XCTAssertEqualObjects(_data, testData, @"Invalid data response"); - XCTAssertNil(_error, @"Received unexpected network error %@", _error); - XCTAssertEqualWithAccuracy(-[startDate timeIntervalSinceNow], kRequestTime+kResponseTime, kResponseTimeTolerence, @"Invalid response time"); - - // in case we timed out before the end of the request (test failed), cancel the request to avoid further delegate method calls - [cxn cancel]; -} - --(void)test_NSURLConnectionDelegate_error -{ - static const NSTimeInterval kResponseTime = 0.5; - NSError* expectedError = [NSError errorWithDomain:NSURLErrorDomain code:404 userInfo:nil]; - - [OHHTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) { - return YES; - } withStubResponse:^OHHTTPStubsResponse *(NSURLRequest *request) { - OHHTTPStubsResponse* resp = [OHHTTPStubsResponse responseWithError:expectedError]; - resp.responseTime = kResponseTime; - return resp; - }]; - - _connectionFinishedExpectation = [self expectationWithDescription:@"NSURLConnection did finish (with error or success)"]; - - NSURLRequest* req = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.iana.org/domains/example/"]]; - NSDate* startDate = [NSDate date]; - - NSURLConnection* cxn = [NSURLConnection connectionWithRequest:req delegate:self]; - - [self waitForExpectationsWithTimeout:kResponseTime+kResponseTimeTolerence handler:nil]; - - XCTAssertEqual(_data.length, (NSUInteger)0, @"Received unexpected network data %@", _data); - XCTAssertEqualObjects(_error.domain, expectedError.domain, @"Invalid error response domain"); - XCTAssertEqual(_error.code, expectedError.code, @"Invalid error response code"); - XCTAssertEqualWithAccuracy(-[startDate timeIntervalSinceNow], kResponseTime, kResponseTimeTolerence, @"Invalid response time"); - - // in case we timed out before the end of the request (test failed), cancel the request to avoid further delegate method calls - [cxn cancel]; -} - - -/////////////////////////////////////////////////////////////////////////////////// -#pragma mark Cancelling requests -/////////////////////////////////////////////////////////////////////////////////// - --(void)test_NSURLConnection_cancel -{ - [OHHTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) { - return YES; - } withStubResponse:^OHHTTPStubsResponse *(NSURLRequest *request) { - return [[OHHTTPStubsResponse responseWithData:[@"<this data should never have time to arrive>" dataUsingEncoding:NSUTF8StringEncoding] - statusCode:500 - headers:nil] - requestTime:0.0 responseTime:1.5]; - }]; - - NSURLRequest* req = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.iana.org/domains/example/"]]; - NSURLConnection* cxn = [NSURLConnection connectionWithRequest:req delegate:self]; - - XCTestExpectation* waitExpectation = [self expectationWithDescription:@"Waiting 2s, after cancelling in the middle"]; - dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ - [cxn cancel]; - dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ - [waitExpectation fulfill]; - }); - }); - - [self waitForExpectationsWithTimeout:5 handler:^(NSError *error) { - // in case we timed out before the end of the request (test failed), cancel the request to avoid further delegate method calls - [cxn cancel]; - }]; - - XCTAssertEqual(_data.length, (NSUInteger)0, @"Received unexpected data but the request should have been cancelled"); - XCTAssertNil(_error, @"Received unexpected network error but the request should have been cancelled"); - -} - - -/////////////////////////////////////////////////////////////////////////////////// -#pragma mark Cancelling requests -/////////////////////////////////////////////////////////////////////////////////// - --(void)test_NSURLConnection_cookies -{ - NSString* const cookieName = @"SESSIONID"; - NSString* const cookieValue = [NSProcessInfo.processInfo globallyUniqueString]; - [OHHTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) { - return YES; - } withStubResponse:^OHHTTPStubsResponse *(NSURLRequest *request) { - NSString* cookie = [NSString stringWithFormat:@"%@=%@;", cookieName, cookieValue]; - NSDictionary* headers = @{@"Set-Cookie": cookie}; - return [[OHHTTPStubsResponse responseWithData:[@"Yummy cookies" dataUsingEncoding:NSUTF8StringEncoding] - statusCode:200 - headers:headers] - requestTime:0.0 responseTime:0.1]; - }]; - - _connectionFinishedExpectation = [self expectationWithDescription:@"NSURLConnection did finish (with error or success)"]; - - // Set the cookie accept policy to accept all cookies from the main document domain - // (especially in case the previous policy was "NSHTTPCookieAcceptPolicyNever") - NSHTTPCookieStorage* cookieStorage = NSHTTPCookieStorage.sharedHTTPCookieStorage; - NSHTTPCookieAcceptPolicy previousAcceptPolicy = cookieStorage.cookieAcceptPolicy; // keep it to restore later - cookieStorage.cookieAcceptPolicy = NSHTTPCookieAcceptPolicyOnlyFromMainDocumentDomain; - - // Send the request and wait for the response containing the Set-Cookie headers - NSURLRequest* req = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.iana.org/domains/example/"]]; - NSURLConnection* cxn = [NSURLConnection connectionWithRequest:req delegate:self]; - [self waitForExpectationsWithTimeout:kResponseTimeTolerence handler:^(NSError *error) { - [cxn cancel]; // In case we timed out (test failed), cancel the request to avoid further delegate method calls - }]; - - /* Check that the cookie has been properly stored */ - NSArray* cookies = [cookieStorage cookiesForURL:req.URL]; - BOOL cookieFound = NO; - for (NSHTTPCookie* cookie in cookies) - { - if ([cookie.name isEqualToString:cookieName]) - { - cookieFound = YES; - XCTAssertEqualObjects(cookie.value, cookieValue, @"The cookie does not have the expected value"); - } - } - XCTAssertTrue(cookieFound, @"The cookie was not stored as expected"); - - - // As a courtesy, restore previous policy before leaving - cookieStorage.cookieAcceptPolicy = previousAcceptPolicy; - -} - - -/////////////////////////////////////////////////////////////////////////////////// -#pragma mark Redirected requests -/////////////////////////////////////////////////////////////////////////////////// - -- (void)test_NSURLConnection_redirected -{ - static const NSTimeInterval kRequestTime = 0.1; - static const NSTimeInterval kResponseTime = 0.5; - NSData* redirectData = [[NSString stringWithFormat:@"%@ - redirect", NSStringFromSelector(_cmd)] dataUsingEncoding:NSUTF8StringEncoding]; - NSData* testData = [NSStringFromSelector(_cmd) dataUsingEncoding:NSUTF8StringEncoding]; - NSURL* redirectURL = [NSURL URLWithString:@"http://www.yahoo.com/"]; - NSString* redirectCookieName = @"yahooCookie"; - NSString* redirectCookieValue = [NSProcessInfo.processInfo globallyUniqueString]; - - // Set the cookie accept policy to accept all cookies from the main document domain - // (especially in case the previous policy was "NSHTTPCookieAcceptPolicyNever") - NSHTTPCookieStorage* cookieStorage = NSHTTPCookieStorage.sharedHTTPCookieStorage; - NSHTTPCookieAcceptPolicy previousAcceptPolicy = cookieStorage.cookieAcceptPolicy; // keep it to restore later - cookieStorage.cookieAcceptPolicy = NSHTTPCookieAcceptPolicyOnlyFromMainDocumentDomain; - - NSString* endCookieName = @"googleCookie"; - NSString* endCookieValue = [NSProcessInfo.processInfo globallyUniqueString]; - NSURL *endURL = [NSURL URLWithString:@"http://www.google.com/"]; - - [OHHTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) { - return YES; - } withStubResponse:^OHHTTPStubsResponse *(NSURLRequest *request) { - if ([request.URL isEqual:redirectURL]) { - NSString* redirectCookie = [NSString stringWithFormat:@"%@=%@;", redirectCookieName, redirectCookieValue]; - NSDictionary* headers = @{ @"Location": endURL.absoluteString, - @"Set-Cookie": redirectCookie }; - return [[OHHTTPStubsResponse responseWithData:redirectData - statusCode:311 // any 300-level request will do - headers:headers] - requestTime:kRequestTime responseTime:kResponseTime]; - } else { - NSString* endCookie = [NSString stringWithFormat:@"%@=%@;", endCookieName, endCookieValue]; - NSDictionary* headers = @{ @"Set-Cookie": endCookie }; - return [[OHHTTPStubsResponse responseWithData:testData - statusCode:200 - headers:headers] - requestTime:kRequestTime responseTime:kResponseTime]; - } - }]; - - _connectionFinishedExpectation = [self expectationWithDescription:@"NSURLConnection did finish (with error or success)"]; - - NSURLRequest* req = [NSURLRequest requestWithURL:redirectURL]; - NSDate* startDate = [NSDate date]; - - NSURLConnection* cxn = [NSURLConnection connectionWithRequest:req delegate:self]; - - [self waitForExpectationsWithTimeout:2 * (kRequestTime+kResponseTime+kResponseTimeTolerence) handler:^(NSError *error) { - // in case we timed out before the end of the request (test failed), cancel the request to avoid further delegate method calls - [cxn cancel]; - }]; - - XCTAssertEqualObjects(_redirectRequestURL, endURL, @"Invalid redirect request URL"); - XCTAssertEqual(_redirectResponseStatusCode, (NSInteger)311, @"Invalid redirect response status code"); - XCTAssertEqualObjects(_data, testData, @"Invalid data response"); - XCTAssertNil(_error, @"Received unexpected network error %@", _error); - XCTAssertEqualWithAccuracy(-[startDate timeIntervalSinceNow], (2 * kRequestTime) + kResponseTime, 2 * kResponseTimeTolerence, @"Invalid response time"); - - /* Check that the redirect cookie has been properly stored */ - NSArray* redirectCookies = [cookieStorage cookiesForURL:req.URL]; - BOOL redirectCookieFound = NO; - for (NSHTTPCookie* cookie in redirectCookies) - { - if ([cookie.name isEqualToString:redirectCookieName]) - { - redirectCookieFound = YES; - XCTAssertEqualObjects(cookie.value, redirectCookieValue, @"The redirect cookie does not have the expected value"); - } - } - XCTAssertTrue(redirectCookieFound, @"The redirect cookie was not stored as expected"); - - /* Check that the end cookie has been properly stored */ - NSArray* endCookies = [cookieStorage cookiesForURL:endURL]; - BOOL endCookieFound = NO; - for (NSHTTPCookie* cookie in endCookies) - { - if ([cookie.name isEqualToString:endCookieName]) - { - endCookieFound = YES; - XCTAssertEqualObjects(cookie.value, endCookieValue, @"The end cookie does not have the expected value"); - } - } - XCTAssertTrue(endCookieFound, @"The end cookie was not stored as expected"); - - - // As a courtesy, restore previous policy before leaving - cookieStorage.cookieAcceptPolicy = previousAcceptPolicy; -} - -@end diff --git a/platform/ios/test/OHHTTPStubs/OHHTTPStubs/UnitTests/Test Suites/NSURLConnectionTests.m b/platform/ios/test/OHHTTPStubs/OHHTTPStubs/UnitTests/Test Suites/NSURLConnectionTests.m deleted file mode 100644 index 1fe6c91e87..0000000000 --- a/platform/ios/test/OHHTTPStubs/OHHTTPStubs/UnitTests/Test Suites/NSURLConnectionTests.m +++ /dev/null @@ -1,187 +0,0 @@ -/*********************************************************************************** - * - * Copyright (c) 2012 Olivier Halligon - * - * 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 <XCTest/XCTest.h> -#import <OHHTTPStubs/OHHTTPStubs.h> - -@interface NSURLConnectionTests : XCTestCase @end - -static const NSTimeInterval kResponseTimeTolerence = 0.3; - -@implementation NSURLConnectionTests - --(void)setUp -{ - [super setUp]; - [OHHTTPStubs removeAllStubs]; -} - -static const NSTimeInterval kRequestTime = 0.1; -static const NSTimeInterval kResponseTime = 0.5; - -/////////////////////////////////////////////////////////////////////////////////// -#pragma mark [NSURLConnection sendSynchronousRequest:returningResponse:error:] -/////////////////////////////////////////////////////////////////////////////////// - --(void)test_NSURLConnection_sendSyncronousRequest_mainQueue -{ - NSData* testData = [NSStringFromSelector(_cmd) dataUsingEncoding:NSUTF8StringEncoding]; - - [OHHTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) { - return YES; - } withStubResponse:^OHHTTPStubsResponse *(NSURLRequest *request) { - return [[OHHTTPStubsResponse responseWithData:testData - statusCode:200 - headers:nil] - requestTime:kRequestTime responseTime:kResponseTime]; - }]; - - NSURLRequest* req = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.iana.org/domains/example/"]]; - NSDate* startDate = [NSDate date]; - - NSData* data = [NSURLConnection sendSynchronousRequest:req returningResponse:NULL error:NULL]; - - XCTAssertEqualObjects(data, testData, @"Invalid data response"); - XCTAssertEqualWithAccuracy(-[startDate timeIntervalSinceNow], kRequestTime+kResponseTime, kResponseTimeTolerence, @"Invalid response time"); -} - --(void)test_NSURLConnection_sendSyncronousRequest_parallelQueue -{ - XCTestExpectation* expectation = [self expectationWithDescription:@"Synchronous request completed"]; - [[NSOperationQueue new] addOperationWithBlock:^{ - [self test_NSURLConnection_sendSyncronousRequest_mainQueue]; - [expectation fulfill]; - }]; - [self waitForExpectationsWithTimeout:kRequestTime+kResponseTime+kResponseTimeTolerence handler:nil]; -} - -/////////////////////////////////////////////////////////////////////////////////// -#pragma mark Single [NSURLConnection sendAsynchronousRequest:queue:completionHandler:] -/////////////////////////////////////////////////////////////////////////////////// - --(void)_test_NSURLConnection_sendAsyncronousRequest_onOperationQueue:(NSOperationQueue*)queue -{ - NSData* testData = [NSStringFromSelector(_cmd) dataUsingEncoding:NSUTF8StringEncoding]; - - [OHHTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) { - return YES; - } withStubResponse:^OHHTTPStubsResponse *(NSURLRequest *request) { - return [[OHHTTPStubsResponse responseWithData:testData - statusCode:200 - headers:nil] - requestTime:kRequestTime responseTime:kResponseTime]; - }]; - - XCTestExpectation* expectation = [self expectationWithDescription:@"Asynchronous request finished"]; - - NSURLRequest* req = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.iana.org/domains/example/"]]; - NSDate* startDate = [NSDate date]; - - [NSURLConnection sendAsynchronousRequest:req queue:queue completionHandler:^(NSURLResponse* resp, NSData* data, NSError* error) - { - XCTAssertEqualObjects(data, testData, @"Invalid data response"); - XCTAssertEqualWithAccuracy(-[startDate timeIntervalSinceNow], kRequestTime+kResponseTime, kResponseTimeTolerence, @"Invalid response time"); - - [expectation fulfill]; - }]; - - [self waitForExpectationsWithTimeout:kRequestTime+kResponseTime+kResponseTimeTolerence handler:nil]; -} - - --(void)test_NSURLConnection_sendAsyncronousRequest_mainQueue -{ - [self _test_NSURLConnection_sendAsyncronousRequest_onOperationQueue:NSOperationQueue.mainQueue]; -} - - --(void)test_NSURLConnection_sendAsyncronousRequest_parallelQueue -{ - [self _test_NSURLConnection_sendAsyncronousRequest_onOperationQueue:[NSOperationQueue new]]; -} - - -/////////////////////////////////////////////////////////////////////////////////// -#pragma mark Multiple Parallel [NSURLConnection sendAsynchronousRequest:queue:completionHandler:] -/////////////////////////////////////////////////////////////////////////////////// - --(void)_test_NSURLConnection_sendMultipleAsyncronousRequestsOnOperationQueue:(NSOperationQueue*)queue -{ - __block BOOL testFinished = NO; - NSData* (^dataForRequest)(NSURLRequest*) = ^(NSURLRequest* req) { - return [[NSString stringWithFormat:@"<Response for URL %@>",req.URL.absoluteString] dataUsingEncoding:NSUTF8StringEncoding]; - }; - - [OHHTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) { - return YES; - } withStubResponse:^OHHTTPStubsResponse *(NSURLRequest *request) { - NSData* retData = dataForRequest(request); - NSTimeInterval responseTime = [request.URL.lastPathComponent doubleValue]; - return [[OHHTTPStubsResponse responseWithData:retData - statusCode:200 - headers:nil] - requestTime:responseTime*.1 responseTime:responseTime]; - }]; - - // Reusable code to send a request that will respond in the given response time - void (^sendAsyncRequest)(NSTimeInterval) = ^(NSTimeInterval responseTime) - { - NSString* desc = [NSString stringWithFormat:@"Asynchronous request with response time %.f finished", responseTime]; - XCTestExpectation* expectation = [self expectationWithDescription:desc]; - - NSString* urlString = [NSString stringWithFormat:@"http://dummyrequest/concurrent/time/%f",responseTime]; - NSURLRequest* req = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]]; -// [SenTestLog testLogWithFormat:@"== Sending request %@\n", req]; - NSDate* startDate = [NSDate date]; - [NSURLConnection sendAsynchronousRequest:req queue:queue completionHandler:^(NSURLResponse* resp, NSData* data, NSError* error) - { -// [SenTestLog testLogWithFormat:@"== Received response for request %@\n", req]; - XCTAssertEqualObjects(data, dataForRequest(req), @"Invalid data response"); - XCTAssertEqualWithAccuracy(-[startDate timeIntervalSinceNow], (responseTime*.1)+responseTime, kResponseTimeTolerence, @"Invalid response time"); - - if (!testFinished) [expectation fulfill]; - }]; - }; - - static NSTimeInterval time3 = 1.5, time2 = 1.0, time1 = 0.5; - sendAsyncRequest(time3); // send this one first, should receive last - sendAsyncRequest(time2); // send this one next, shoud receive 2nd - sendAsyncRequest(time1); // send this one last, should receive first - - [self waitForExpectationsWithTimeout:MAX(time1,MAX(time2,time3))+kResponseTimeTolerence handler:nil]; - testFinished = YES; -} - --(void)test_NSURLConnection_sendMultipleAsyncronousRequests_mainQueue -{ - [self _test_NSURLConnection_sendMultipleAsyncronousRequestsOnOperationQueue:NSOperationQueue.mainQueue]; -} - --(void)test_NSURLConnection_sendMultipleAsyncronousRequests_parallelQueue -{ - [self _test_NSURLConnection_sendMultipleAsyncronousRequestsOnOperationQueue:[NSOperationQueue new]]; -} - - -@end diff --git a/platform/ios/test/OHHTTPStubs/OHHTTPStubs/UnitTests/Test Suites/NSURLSessionTests.m b/platform/ios/test/OHHTTPStubs/OHHTTPStubs/UnitTests/Test Suites/NSURLSessionTests.m deleted file mode 100644 index 2e829ca432..0000000000 --- a/platform/ios/test/OHHTTPStubs/OHHTTPStubs/UnitTests/Test Suites/NSURLSessionTests.m +++ /dev/null @@ -1,227 +0,0 @@ -/*********************************************************************************** - * - * Copyright (c) 2012 Olivier Halligon - * - * 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. - * - ***********************************************************************************/ - - -// Compile this only if SDK version (…MAX_ALLOWED) is iOS7+/10.9+ because NSURLSession is a class only known starting these SDKs -// (this code won't compile if we use an eariler SDKs, like when building with Xcode4) -#if (defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000) \ - || (defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && __MAC_OS_X_VERSION_MAX_ALLOWED >= 1090) - -#import <XCTest/XCTest.h> -#import <OHHTTPStubs/OHHTTPStubs.h> - -@interface NSURLSessionTests : XCTestCase <NSURLSessionDataDelegate> @end - -@implementation NSURLSessionTests -{ - NSMutableData* _receivedData; - XCTestExpectation* _taskDidCompleteExpectation; -} - -- (void)setUp -{ - [super setUp]; - [OHHTTPStubs removeAllStubs]; - _receivedData = nil; -} - -- (void)_test_NSURLSession:(NSURLSession*)session - jsonForStub:(id)json - completion:(void(^)(NSError* errorResponse,id jsonResponse))completion -{ - if ([NSURLSession class]) - { - static const NSTimeInterval kRequestTime = 0.0; - static const NSTimeInterval kResponseTime = 0.2; - - [OHHTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) { - return YES; - } withStubResponse:^OHHTTPStubsResponse *(NSURLRequest *request) { - return [[OHHTTPStubsResponse responseWithJSONObject:json statusCode:200 headers:nil] - requestTime:kRequestTime responseTime:kResponseTime]; - }]; - - XCTestExpectation* expectation = [self expectationWithDescription:@"NSURLSessionDataTask completed"]; - - __block __strong id dataResponse = nil; - __block __strong NSError* errorResponse = nil; - NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"foo://unknownhost:666"]]; - request.HTTPMethod = @"GET"; - [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; - [request setValue:@"application/json" forHTTPHeaderField:@"Accept"]; - - NSURLSessionDataTask *task = [session dataTaskWithRequest:request - completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) - { - errorResponse = error; - if (!error) - { - NSError *jsonError = nil; - NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonError]; - XCTAssertNil(jsonError, @"Unexpected error deserializing JSON response"); - dataResponse = jsonObject; - } - [expectation fulfill]; - }]; - - [task resume]; - - [self waitForExpectationsWithTimeout:kRequestTime+kResponseTime+0.5 handler:nil]; - - completion(errorResponse, dataResponse); - } -} - -// The shared session use the same mechanism as NSURLConnection -// (based on protocols registered via +[NSURLProtocol registerClass:] and all) -// and no NSURLSessionConfiguration -- (void)test_SharedNSURLSession -{ - if ([NSURLSession class]) - { - NSURLSession *session = [NSURLSession sharedSession]; - - NSDictionary* json = @{@"Success": @"Yes"}; - [self _test_NSURLSession:session jsonForStub:json completion:^(NSError *errorResponse, id jsonResponse) { - XCTAssertNil(errorResponse, @"Unexpected error"); - XCTAssertEqualObjects(jsonResponse, json, @"Unexpected data received"); - }]; - } - else - { - NSLog(@"/!\\ Test skipped because the NSURLSession class is not available on this OS version. Run the tests a target with a more recent OS.\n"); - } -} - -- (void)test_NSURLSessionDefaultConfig -{ - if ([NSURLSessionConfiguration class] && [NSURLSession class]) - { - NSURLSessionConfiguration* config = [NSURLSessionConfiguration defaultSessionConfiguration]; - NSURLSession *session = [NSURLSession sessionWithConfiguration:config]; - - NSDictionary* json = @{@"Success": @"Yes"}; - [self _test_NSURLSession:session jsonForStub:json completion:^(NSError *errorResponse, id jsonResponse) { - XCTAssertNil(errorResponse, @"Unexpected error"); - XCTAssertEqualObjects(jsonResponse, json, @"Unexpected data received"); - }]; - } - else - { - NSLog(@"/!\\ Test skipped because the NSURLSession class is not available on this OS version. Run the tests a target with a more recent OS.\n"); - } -} - -- (void)test_NSURLSessionEphemeralConfig -{ - if ([NSURLSessionConfiguration class] && [NSURLSession class]) - { - NSURLSessionConfiguration* config = [NSURLSessionConfiguration ephemeralSessionConfiguration]; - NSURLSession *session = [NSURLSession sessionWithConfiguration:config]; - - NSDictionary* json = @{@"Success": @"Yes"}; - [self _test_NSURLSession:session jsonForStub:json completion:^(NSError *errorResponse, id jsonResponse) { - XCTAssertNil(errorResponse, @"Unexpected error"); - XCTAssertEqualObjects(jsonResponse, json, @"Unexpected data received"); - }]; - } - else - { - NSLog(@"/!\\ Test skipped because the NSURLSession class is not available on this OS version. Run the tests a target with a more recent OS.\n"); - } -} - -- (void)test_NSURLSessionDefaultConfig_Disabled -{ - if ([NSURLSessionConfiguration class] && [NSURLSession class]) - { - NSURLSessionConfiguration* config = [NSURLSessionConfiguration ephemeralSessionConfiguration]; - [OHHTTPStubs setEnabled:NO forSessionConfiguration:config]; // Disable stubs for this session - NSURLSession *session = [NSURLSession sessionWithConfiguration:config]; - - NSDictionary* json = @{@"Success": @"Yes"}; - [self _test_NSURLSession:session jsonForStub:json completion:^(NSError *errorResponse, id jsonResponse) { - // Stubs were disable for this session, so we should get an error instead of the stubs data - XCTAssertNotNil(errorResponse, @"Expected error but none found"); - XCTAssertNil(jsonResponse, @"Data should not have been received as stubs should be disabled"); - }]; - } - else - { - NSLog(@"/!\\ Test skipped because the NSURLSession class is not available on this OS version. Run the tests a target with a more recent OS.\n"); - } -} - -- (void)test_NSURLSession_DataTask_DelegateMethods -{ - if ([NSURLSessionConfiguration class] && [NSURLSession class]) - { - NSData* expectedResponse = [NSStringFromSelector(_cmd) dataUsingEncoding:NSUTF8StringEncoding]; - [OHHTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) { - return [request.URL.scheme isEqualToString:@"stub"]; - } withStubResponse:^OHHTTPStubsResponse *(NSURLRequest *request) { - return [[OHHTTPStubsResponse responseWithData:expectedResponse statusCode:200 headers:nil] - responseTime:0.5]; - }]; - - _taskDidCompleteExpectation = [self expectationWithDescription:@"NSURLSessionDataTask completion delegate method called"]; - - NSURLSessionConfiguration* config = [NSURLSessionConfiguration defaultSessionConfiguration]; - NSURLSession* session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil]; - - [[session dataTaskWithURL:[NSURL URLWithString:@"stub://foo"]] resume]; - - [self waitForExpectationsWithTimeout:5 handler:nil]; - - XCTAssertEqualObjects(_receivedData, expectedResponse, @"Unexpected response"); - } - else - { - NSLog(@"/!\\ Test skipped because the NSURLSession class is not available on this OS version. Run the tests a target with a more recent OS.\n"); - } -} - -//--------------------------------------------------------------- -#pragma mark - Delegate Methods - -- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler -{ - _receivedData = [NSMutableData new]; - completionHandler(NSURLSessionResponseAllow); -} -- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data -{ - [_receivedData appendData:data]; -} -- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error -{ - [_taskDidCompleteExpectation fulfill]; -} - -@end - -#else -#warning Unit Tests using NSURLSession were not compiled nor executed, because NSURLSession is only available since iOS7/OSX10.9 SDK. \ --------- Compile using iOS7 or OSX10.9 SDK then launch the tests on the iOS7 simulator or an OSX10.9 target for them to be executed. -#endif diff --git a/platform/ios/test/OHHTTPStubs/OHHTTPStubs/UnitTests/Test Suites/NilValuesTests.m b/platform/ios/test/OHHTTPStubs/OHHTTPStubs/UnitTests/Test Suites/NilValuesTests.m deleted file mode 100644 index ec263d543f..0000000000 --- a/platform/ios/test/OHHTTPStubs/OHHTTPStubs/UnitTests/Test Suites/NilValuesTests.m +++ /dev/null @@ -1,216 +0,0 @@ -/*********************************************************************************** - * - * Copyright (c) 2012 Olivier Halligon - * - * 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 <XCTest/XCTest.h> -#import <OHHTTPStubs/OHHTTPStubs.h> - -static const NSTimeInterval kResponseTimeTolerence = 0.3; - -@interface NilValuesTests : XCTestCase @end - -@implementation NilValuesTests - --(void)setUp -{ - [super setUp]; - [OHHTTPStubs removeAllStubs]; -} - -- (void)test_NilData -{ - [OHHTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) { - return YES; - } withStubResponse:^OHHTTPStubsResponse *(NSURLRequest *request) { -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wnonnull" - return [OHHTTPStubsResponse responseWithData:nil statusCode:400 headers:nil]; -#pragma clang diagnostic pop - }]; - - XCTestExpectation* expectation = [self expectationWithDescription:@"Network request's completionHandler called"]; - - NSURLRequest* req = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.iana.org/domains/example/"]]; - - [NSURLConnection sendAsynchronousRequest:req - queue:[NSOperationQueue mainQueue] - completionHandler:^(NSURLResponse* resp, NSData* data, NSError* error) - { - XCTAssertEqual(data.length, (NSUInteger)0, @"Data should be empty"); - - [expectation fulfill]; - }]; - - [self waitForExpectationsWithTimeout:kResponseTimeTolerence handler:nil]; -} - -- (void)test_EmptyData -{ - [OHHTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) { - return YES; - } withStubResponse:^OHHTTPStubsResponse *(NSURLRequest *request) { - return [[OHHTTPStubsResponse responseWithData:[NSData data] statusCode:400 headers:nil] - requestTime:0.01 responseTime:0.01]; - }]; - - XCTestExpectation* expectation = [self expectationWithDescription:@"Network request's completionHandler called"]; - - NSURLRequest* req = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.iana.org/domains/example/"]]; - - [NSURLConnection sendAsynchronousRequest:req - queue:[NSOperationQueue mainQueue] - completionHandler:^(NSURLResponse* resp, NSData* data, NSError* error) - { - XCTAssertEqual(data.length, (NSUInteger)0, @"Data should be empty"); - - [expectation fulfill]; - }]; - - [self waitForExpectationsWithTimeout:kResponseTimeTolerence handler:nil]; -} - -- (void)test_NilPath -{ - [OHHTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) { - return YES; - } withStubResponse:^OHHTTPStubsResponse *(NSURLRequest *request) { -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wnonnull" - return [[OHHTTPStubsResponse responseWithFileAtPath:nil statusCode:501 headers:nil] - requestTime:0.01 responseTime:0.01]; -#pragma clang diagnostic pop - }]; - - XCTestExpectation* expectation = [self expectationWithDescription:@"Network request's completionHandler called"]; - - NSURLRequest* req = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.iana.org/domains/example/"]]; - - [NSURLConnection sendAsynchronousRequest:req - queue:[NSOperationQueue mainQueue] - completionHandler:^(NSURLResponse* resp, NSData* data, NSError* error) - { - XCTAssertEqual(data.length, (NSUInteger)0, @"Data should be empty"); - - [expectation fulfill]; - }]; - - [self waitForExpectationsWithTimeout:kResponseTimeTolerence handler:nil]; -} - -- (void)test_InvalidPath -{ - [OHHTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) { - return YES; - } withStubResponse:^OHHTTPStubsResponse *(NSURLRequest *request) { - return [[OHHTTPStubsResponse responseWithFileAtPath:@"-invalid-path-" statusCode:500 headers:nil] - requestTime:0.01 responseTime:0.01]; - }]; - - XCTestExpectation* expectation = [self expectationWithDescription:@"Network request's completionHandler called"]; - - NSURLRequest* req = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.iana.org/domains/example/"]]; - - [NSURLConnection sendAsynchronousRequest:req - queue:[NSOperationQueue mainQueue] - completionHandler:^(NSURLResponse* resp, NSData* data, NSError* error) - { - XCTAssertEqual(data.length, (NSUInteger)0, @"Data should be empty"); - - [expectation fulfill]; - }]; - - [self waitForExpectationsWithTimeout:kResponseTimeTolerence handler:nil]; -} - -- (void)test_EmptyFile -{ - [OHHTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) { - return YES; - } withStubResponse:^OHHTTPStubsResponse *(NSURLRequest *request) { - NSString* emptyFile = OHPathForFile(@"emptyfile.json", self.class); - return [[OHHTTPStubsResponse responseWithFileAtPath:emptyFile statusCode:500 headers:nil] - requestTime:0.01 responseTime:0.01]; - }]; - - XCTestExpectation* expectation = [self expectationWithDescription:@"Network request's completionHandler called"]; - - NSURLRequest* req = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.iana.org/domains/example/"]]; - - [NSURLConnection sendAsynchronousRequest:req - queue:[NSOperationQueue mainQueue] - completionHandler:^(NSURLResponse* resp, NSData* data, NSError* error) - { - XCTAssertEqual(data.length, (NSUInteger)0, @"Data should be empty"); - - [expectation fulfill]; - }]; - - [self waitForExpectationsWithTimeout:kResponseTimeTolerence handler:nil]; -} - -- (void)_test_NilURLAndCookieHandlingEnabled:(BOOL)handleCookiesEnabled -{ - NSData* expectedResponse = [NSStringFromSelector(_cmd) dataUsingEncoding:NSUTF8StringEncoding]; - - [OHHTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) { - return YES; - } withStubResponse:^OHHTTPStubsResponse *(NSURLRequest *request) { - return [OHHTTPStubsResponse responseWithData:expectedResponse - statusCode:200 - headers:nil]; - }]; - - XCTestExpectation* expectation = [self expectationWithDescription:@"Network request's completionHandler called"]; - -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wnonnull" - NSMutableURLRequest* req = [NSMutableURLRequest requestWithURL:nil]; -#pragma clang diagnostic pop - req.HTTPShouldHandleCookies = handleCookiesEnabled; - - __block NSData* response = nil; - - [NSURLConnection sendAsynchronousRequest:req - queue:[NSOperationQueue mainQueue] - completionHandler:^(NSURLResponse* resp, NSData* data, NSError* error) - { - response = data; - [expectation fulfill]; - }]; - - [self waitForExpectationsWithTimeout:kResponseTimeTolerence handler:nil]; - - XCTAssertEqualObjects(response, expectedResponse, @"Unexpected data received"); -} - -- (void)test_NilURLAndCookieHandlingEnabled -{ - [self _test_NilURLAndCookieHandlingEnabled:YES]; -} - -- (void)test_NilURLAndCookieHandlingDisabled -{ - [self _test_NilURLAndCookieHandlingEnabled:NO]; -} - -@end diff --git a/platform/ios/test/OHHTTPStubs/OHHTTPStubs/UnitTests/Test Suites/SwiftHelpersTests.swift b/platform/ios/test/OHHTTPStubs/OHHTTPStubs/UnitTests/Test Suites/SwiftHelpersTests.swift deleted file mode 100644 index 3d2f1c3577..0000000000 --- a/platform/ios/test/OHHTTPStubs/OHHTTPStubs/UnitTests/Test Suites/SwiftHelpersTests.swift +++ /dev/null @@ -1,200 +0,0 @@ -// -// SwiftHelpersTests.swift -// OHHTTPStubs -// -// Created by Olivier Halligon on 20/09/2015. -// Copyright © 2015 AliSoftware. All rights reserved. -// - -import Foundation -import XCTest -import OHHTTPStubs - -class SwiftHelpersTests : XCTestCase { - - func testIsScheme() { - let matcher = isScheme("foo") - - let urls = [ - "foo:": true, - "foo://": true, - "foo://bar/baz": true, - "bar://": false, - "bar://foo/": false, - "foobar://": false - ] - - for (url, result) in urls { - let req = NSURLRequest(URL: NSURL(string: url)!) - XCTAssert(matcher(req) == result, "isScheme(\"foo\") matcher failed when testing url \(url)") - } - } - - func testIsHost() { - let matcher = isHost("foo") - - let urls = [ - "foo:": false, - "foo://": false, - "foo://bar/baz": false, - "bar://foo": true, - "bar://foo/baz": true, - ] - - for (url, result) in urls { - let req = NSURLRequest(URL: NSURL(string: url)!) - XCTAssert(matcher(req) == result, "isHost(\"foo\") matcher failed when testing url \(url)") - } - } - - func testIsPath_absoluteURL() { - testIsPath("/foo/bar/baz", isAbsoluteMatcher: true) - } - - func testIsPath_relativeURL() { - testIsPath("foo/bar/baz", isAbsoluteMatcher: false) - } - - func testIsPath(path: String, isAbsoluteMatcher: Bool) { - let matcher = isPath(path) - - let urls = [ - // Absolute URLs - "scheme:": false, - "scheme://": false, - "scheme://foo/bar/baz": false, - "scheme://host/foo/bar": false, - "scheme://host/foo/bar/baz": isAbsoluteMatcher, - "scheme://host/foo/bar/baz?q=1": isAbsoluteMatcher, - "scheme://host/foo/bar/baz#anchor": isAbsoluteMatcher, - "scheme://host/foo/bar/baz;param": isAbsoluteMatcher, - "scheme://host/foo/bar/baz/wizz": false, - "scheme://host/path#/foo/bar/baz": false, - "scheme://host/path?/foo/bar/baz": false, - "scheme://host/path;/foo/bar/baz": false, - // Relative URLs - "foo/bar/baz": !isAbsoluteMatcher, - "foo/bar/baz?q=1": !isAbsoluteMatcher, - "foo/bar/baz#anchor": !isAbsoluteMatcher, - "foo/bar/baz;param": !isAbsoluteMatcher, - "foo/bar/baz/wizz": false, - "path#/foo/bar/baz": false, - "path?/foo/bar/baz": false, - "path;/foo/bar/baz": false, - ] - - for (url, result) in urls { - let req = NSURLRequest(URL: NSURL(string: url)!) - let p = req.URL?.path - print("URL: \(url) -> Path: \(p)") - XCTAssert(matcher(req) == result, "isPath(\"\(path)\" matcher failed when testing url \(url)") - } - } - - func testIsExtension() { - let matcher = isExtension("txt") - - let urls = [ - "txt:": false, - "txt://": false, - "txt://txt/txt/txt": false, - "scheme://host/foo/bar.png": false, - "scheme://host/foo/bar.txt": true, - "scheme://host/foo/bar.txt?q=1": true, - "scheme://host/foo/bar.baz?q=wizz.txt": false, - ] - - for (url, result) in urls { - let req = NSURLRequest(URL: NSURL(string: url)!) - XCTAssert(matcher(req) == result, "isExtension(\"txt\") matcher failed when testing url \(url)") - } - - } - - func testContainsQueryParams() { - let params: [String: String?] = ["q":"test", "lang":"en", "empty":"", "flag":nil] - let matcher = containsQueryParams(params) - - let urls = [ - "foo://bar": false, - "foo://bar?q=test": false, - "foo://bar?lang=en": false, - "foo://bar#q=test&lang=en&empty=&flag": false, - "foo://bar#lang=en&empty=&flag&q=test": false, - "foo://bar;q=test&lang=en&empty=&flag": false, - "foo://bar;lang=en&empty=&flag&q=test": false, - - "foo://bar?q=test&lang=en&empty=&flag": true, - "foo://bar?lang=en&flag&empty=&q=test": true, - "foo://bar?q=test&lang=en&empty=&flag#anchor": true, - "foo://bar?q=test&lang=en&empty&flag": false, // key "empty" with no value is matched against nil, not "" - "foo://bar?q=test&lang=en&empty=&flag=": false, // key "flag" with empty value is matched against "", not nil - "foo://bar?q=en&lang=test&empty=&flag": false, // param keys and values mismatch - "foo://bar?q=test&lang=en&empty=&flag&&wizz=fuzz": true, - "foo://bar?wizz=fuzz&empty=&lang=en&flag&&q=test": true, - "?q=test&lang=en&empty=&flag": true, - "?lang=en&flag&empty=&q=test": true, - ] - - for (url, result) in urls { - let req = NSURLRequest(URL: NSURL(string: url)!) - XCTAssert(matcher(req) == result, "containsQueryParams(\"\(params)\") matcher failed when testing url \(url)") - } - } - - let sampleURLs = [ - // Absolute URLs - "scheme:", - "scheme://", - "scheme://foo/bar/baz", - "scheme://host/foo/bar", - "scheme://host/foo/bar/baz", - "scheme://host/foo/bar/baz?q=1", - "scheme://host/foo/bar/baz#anchor", - "scheme://host/foo/bar/baz;param", - "scheme://host/foo/bar/baz/wizz", - "scheme://host/path#/foo/bar/baz", - "scheme://host/path?/foo/bar/baz", - "scheme://host/path;/foo/bar/baz", - // Relative URLs - "foo/bar/baz", - "foo/bar/baz?q=1", - "foo/bar/baz#anchor", - "foo/bar/baz;param", - "foo/bar/baz/wizz", - "path#/foo/bar/baz", - "path?/foo/bar/baz", - "path;/foo/bar/baz" - ] - - let trueMatcher: OHHTTPStubsTestBlock = { _ in return true } - let falseMatcher: OHHTTPStubsTestBlock = { _ in return false } - - func testOrOperator() { - for url in sampleURLs { - let req = NSURLRequest(URL: NSURL(string: url)!) - XCTAssert((trueMatcher || trueMatcher)(req) == true, "trueMatcher || trueMatcher should result in a trueMatcher") - XCTAssert((trueMatcher || falseMatcher)(req) == true, "trueMatcher || falseMatcher should result in a trueMatcher") - XCTAssert((falseMatcher || trueMatcher)(req) == true, "falseMatcher || trueMatcher should result in a trueMatcher") - XCTAssert((falseMatcher || falseMatcher)(req) == false, "falseMatcher || falseMatcher should result in a falseMatcher") - } - } - - func testAndOperator() { - for url in sampleURLs { - let req = NSURLRequest(URL: NSURL(string: url)!) - XCTAssert((trueMatcher && trueMatcher)(req) == true, "trueMatcher && trueMatcher should result in a trueMatcher") - XCTAssert((trueMatcher && falseMatcher)(req) == false, "trueMatcher && falseMatcher should result in a falseMatcher") - XCTAssert((falseMatcher && trueMatcher)(req) == false, "falseMatcher && trueMatcher should result in a falseMatcher") - XCTAssert((falseMatcher && falseMatcher)(req) == false, "falseMatcher && falseMatcher should result in a falseMatcher") - } - } - - func testNotOperator() { - for url in sampleURLs { - let req = NSURLRequest(URL: NSURL(string: url)!) - XCTAssert((!trueMatcher)(req) == false, "!trueMatcher should result in a falseMatcher") - XCTAssert((!falseMatcher)(req) == true, "!falseMatcher should result in a trueMatcher") - } - } -} diff --git a/platform/ios/test/OHHTTPStubs/OHHTTPStubs/UnitTests/Test Suites/TimingTests.m b/platform/ios/test/OHHTTPStubs/OHHTTPStubs/UnitTests/Test Suites/TimingTests.m deleted file mode 100644 index b2e820f80f..0000000000 --- a/platform/ios/test/OHHTTPStubs/OHHTTPStubs/UnitTests/Test Suites/TimingTests.m +++ /dev/null @@ -1,162 +0,0 @@ -/*********************************************************************************** - * - * Copyright (c) 2012 Olivier Halligon - * - * 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 <XCTest/XCTest.h> -#import <OHHTTPStubs/OHHTTPStubs.h> - -@interface TimingTests : XCTestCase -{ - NSMutableData* _data; - NSError* _error; - XCTestExpectation* _connectionFinishedExpectation; - -// NSDate* _didReceiveResponseTS; - NSDate* _didFinishLoadingTS; -} -@end - -@implementation TimingTests - --(void)setUp -{ - [super setUp]; - - _data = [NSMutableData new]; - _error = nil; -// _didReceiveResponseTS = nil; - _didFinishLoadingTS = nil; - [OHHTTPStubs removeAllStubs]; -} --(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response -{ - _data.length = 0U; - // NOTE: This timing info is not reliable as Cocoa always calls the connection:didReceiveResponse: delegate method just before - // calling the first "connection:didReceiveData:", even if the [id<NSURLProtocolClient> URLProtocol:didReceiveResponse:…] method was called way before. So we are not testing this -// _didReceiveResponseTS = [NSDate date]; -} - --(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data -{ - [_data appendData:data]; -} - --(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error -{ - _error = error; // keep strong reference - _didFinishLoadingTS = [NSDate date]; - [_connectionFinishedExpectation fulfill]; -} - --(void)connectionDidFinishLoading:(NSURLConnection *)connection -{ - _didFinishLoadingTS = [NSDate date]; - [_connectionFinishedExpectation fulfill]; -} - - -/////////////////////////////////////////////////////////////////////////////////////// - -static NSTimeInterval const kResponseTimeTolerence = 0.8; -static NSTimeInterval const kSecurityTimeout = 5.0; - --(void)_testWithData:(NSData*)stubData requestTime:(NSTimeInterval)requestTime responseTime:(NSTimeInterval)responseTime -{ - [OHHTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) { - return YES; - } withStubResponse:^OHHTTPStubsResponse *(NSURLRequest *request) { - return [[OHHTTPStubsResponse responseWithData:stubData - statusCode:200 - headers:nil] - requestTime:requestTime responseTime:responseTime]; - }]; - - _connectionFinishedExpectation = [self expectationWithDescription:@"NSURLConnection did finish (with error or success)"]; - - NSURLRequest* req = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.iana.org/domains/example/"]]; - NSDate* startTS = [NSDate date]; - - [NSURLConnection connectionWithRequest:req delegate:self]; - - [self waitForExpectationsWithTimeout:requestTime+responseTime+kResponseTimeTolerence+kSecurityTimeout handler:nil]; - - XCTAssertEqualObjects(_data, stubData, @"Invalid data response"); - -// XCTAssertEqualWithAccuracy([_didReceiveResponseTS timeIntervalSinceDate:startTS], requestTime, -// kResponseTimeTolerence, @"Invalid request time"); - XCTAssertEqualWithAccuracy([_didFinishLoadingTS timeIntervalSinceDate:startTS], requestTime + responseTime, - kResponseTimeTolerence, @"Invalid response time"); - - [NSThread sleepForTimeInterval:0.01]; // Time for the test to wrap it all (otherwise we may have "Test did not finish" warning) -} - - - - - - --(void)test_RequestTime0_ResponseTime0 -{ - NSData* testData = [NSStringFromSelector(_cmd) dataUsingEncoding:NSUTF8StringEncoding]; - [self _testWithData:testData requestTime:0 responseTime:0]; -} - --(void)test_SmallDataLargeTime_CumulativeAlgorithm -{ - NSData* testData = [NSStringFromSelector(_cmd) dataUsingEncoding:NSUTF8StringEncoding]; - // 21 bytes in 23/4 of a second = 0.913042 byte per slot: we need to check that the cumulative algorithm works - [self _testWithData:testData requestTime:0 responseTime:5.75]; -} - --(void)test_RequestTime1_ResponseTime0 -{ - NSData* testData = [NSStringFromSelector(_cmd) dataUsingEncoding:NSUTF8StringEncoding]; - [self _testWithData:testData requestTime:1 responseTime:0]; -} - --(void)test_LongData_RequestTime1_ResponseTime5 -{ - static NSUInteger const kDataLength = 1024; - NSMutableData* testData = [NSMutableData dataWithCapacity:kDataLength]; - NSData* chunk = [[NSProcessInfo.processInfo globallyUniqueString] dataUsingEncoding:NSUTF8StringEncoding]; - while(testData.length<kDataLength) - { - [testData appendData:chunk]; - } - [self _testWithData:testData requestTime:1 responseTime:5]; -} - --(void)test_VeryLongData_RequestTime1_ResponseTime0 -{ - static NSUInteger const kDataLength = 609792; - NSMutableData* testData = [NSMutableData dataWithCapacity:kDataLength]; - NSData* chunk = [[NSProcessInfo.processInfo globallyUniqueString] dataUsingEncoding:NSUTF8StringEncoding]; - while(testData.length<kDataLength) - { - [testData appendData:chunk]; - } - [self _testWithData:testData requestTime:1 responseTime:0]; -} - -@end diff --git a/platform/ios/test/OHHTTPStubs/OHHTTPStubs/UnitTests/Test Suites/WithContentsOfURLTests.m b/platform/ios/test/OHHTTPStubs/OHHTTPStubs/UnitTests/Test Suites/WithContentsOfURLTests.m deleted file mode 100644 index 0e34aea54f..0000000000 --- a/platform/ios/test/OHHTTPStubs/OHHTTPStubs/UnitTests/Test Suites/WithContentsOfURLTests.m +++ /dev/null @@ -1,116 +0,0 @@ -/*********************************************************************************** - * - * Copyright (c) 2012 Olivier Halligon - * - * 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 <XCTest/XCTest.h> -#import <OHHTTPStubs/OHHTTPStubs.h> - -@interface WithContentsOfURLTests : XCTestCase @end - -static const NSTimeInterval kResponseTimeTolerence = 0.2; - -@implementation WithContentsOfURLTests - --(void)setUp -{ - [super setUp]; - [OHHTTPStubs removeAllStubs]; -} - -static const NSTimeInterval kRequestTime = 0.1; -static const NSTimeInterval kResponseTime = 0.5; - -/////////////////////////////////////////////////////////////////////////////////// -#pragma mark [NSString stringWithContentsOfURL:encoding:error:] -/////////////////////////////////////////////////////////////////////////////////// - --(void)test_NSString_stringWithContentsOfURL_mainQueue -{ - NSString* testString = NSStringFromSelector(_cmd); - - [OHHTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) { - return YES; - } withStubResponse:^OHHTTPStubsResponse *(NSURLRequest *request) { - return [[OHHTTPStubsResponse responseWithData:[testString dataUsingEncoding:NSUTF8StringEncoding] - statusCode:200 - headers:nil] - requestTime:kRequestTime responseTime:kResponseTime]; - }]; - - NSDate* startDate = [NSDate date]; - - NSString* string = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.iana.org/domains/example/"] - encoding:NSUTF8StringEncoding - error:NULL]; - - XCTAssertEqualObjects(string, testString, @"Invalid returned string"); - XCTAssertEqualWithAccuracy(-[startDate timeIntervalSinceNow], kResponseTime+kRequestTime, kResponseTimeTolerence, @"Invalid response time"); -} - --(void)test_NSString_stringWithContentsOfURL_parallelQueue -{ - XCTestExpectation* expectation = [self expectationWithDescription:@"Synchronous download finished"]; - [[NSOperationQueue new] addOperationWithBlock:^{ - [self test_NSString_stringWithContentsOfURL_mainQueue]; - [expectation fulfill]; - }]; - [self waitForExpectationsWithTimeout:kRequestTime+kResponseTime+kResponseTimeTolerence handler:nil]; -} - -/////////////////////////////////////////////////////////////////////////////////// -#pragma mark [NSData dataWithContentsOfURL:] -/////////////////////////////////////////////////////////////////////////////////// - --(void)test_NSData_dataWithContentsOfURL_mainQueue -{ - NSData* testData = [NSStringFromSelector(_cmd) dataUsingEncoding:NSUTF8StringEncoding]; - - [OHHTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) { - return YES; - } withStubResponse:^OHHTTPStubsResponse *(NSURLRequest *request) { - return [[OHHTTPStubsResponse responseWithData:testData - statusCode:200 - headers:nil] - requestTime:kRequestTime responseTime:kResponseTime]; - }]; - - NSDate* startDate = [NSDate date]; - - NSData* data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://www.iana.org/domains/example/"]]; - - XCTAssertEqualObjects(data, testData, @"Invalid returned string"); - XCTAssertEqualWithAccuracy(-[startDate timeIntervalSinceNow], kRequestTime+kResponseTime, kResponseTimeTolerence, @"Invalid response time"); -} - --(void)test_NSData_dataWithContentsOfURL_parallelQueue -{ - XCTestExpectation* expectation = [self expectationWithDescription:@"Synchronous download finished"]; - [[NSOperationQueue new] addOperationWithBlock:^{ - [self test_NSData_dataWithContentsOfURL_mainQueue]; - [expectation fulfill]; - }]; - [self waitForExpectationsWithTimeout:kRequestTime+kResponseTime+kResponseTimeTolerence handler:nil]; -} - -@end |