Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

In Test cases, Fix potential memory leaks by use of NSURLSession #250

Merged
merged 4 commits into from
May 22, 2017
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
# OHHTTPStubs — CHANGELOG

## Master

* Fixed potential memory leaks with use of NSURLSession as detected by our devs.
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please add two spaces after the . (like you can see for other entries).

(This is a Markdown-specific stuff that makes the text on the next line actually be rendered in a new line in same paragraph instead of being joined on the same line)

[@mikelupo](https://github.com/mikelupo
[#249](https://github.com/AliSoftware/OHHTTPStubs/pull/249)
* Add precondition assertions in `isScheme` and `isHost` matchers and some documentation in `isHost`, `isScheme` and `isPath`.
[@Liquidsoul](https://github.com/Liquidsoul)
[#248](https://github.com/AliSoftware/OHHTTPStubs/pull/248)
Expand Down
41 changes: 21 additions & 20 deletions OHHTTPStubs/UnitTests/Test Suites/MocktailTests.m
Original file line number Diff line number Diff line change
Expand Up @@ -45,14 +45,15 @@ - (void)setUp
{
[super setUp];
[OHHTTPStubs removeAllStubs];

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would it be possible to get rid of those changes? 🙏 (by using the trick in the Xcode prefs I mentioned you in the last review or even manually of you don't want to change your prefs, that works too)

Basically all empty lines should really be empty and not contain indentation and spaces. I know it's nitpicking and a matter of taste, I don't care for one style or another but I care about consistency throughout the code base 😉

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
self.session = [NSURLSession sessionWithConfiguration:configuration delegate:nil delegateQueue:nil];
}

- (void)tearDown
{
[super tearDown];
[self.session invalidateAndCancel];
self.session = nil;
}

Expand Down Expand Up @@ -110,18 +111,18 @@ - (NSHTTPURLResponse *)runLogin
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

And if course that applies to everywhere it changed here

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@AliSoftware, Sorry I missed that. It's fixed now. My Xcode is already up as you mentioned, but I just didn't CTRL-i to repair the indentation on that one file. It's in the new commit of this PR now.

[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"];

__block NSHTTPURLResponse *capturedResponse;
NSURLSessionDataTask *postDataTask = [self.session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if ([response isKindOfClass:[NSHTTPURLResponse class]]) capturedResponse = (id)response;
Expand All @@ -131,18 +132,18 @@ - (NSHTTPURLResponse *)runLogin
{
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];

return capturedResponse;
}

Expand All @@ -152,36 +153,36 @@ - (NSHTTPURLResponse *)runGetCards
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"];

__block NSHTTPURLResponse *capturedResponse;
NSURLSessionDataTask *getDataTask = [self.session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if ([response isKindOfClass:[NSHTTPURLResponse class]]) capturedResponse = (id)response;
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];

return capturedResponse;
}

Expand Down
38 changes: 24 additions & 14 deletions OHHTTPStubs/UnitTests/Test Suites/NSURLSessionTests.m
Original file line number Diff line number Diff line change
Expand Up @@ -64,23 +64,23 @@ - (void)_test_NSURLSession:(NSURLSession*)session
{
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)
{
Expand All @@ -96,7 +96,7 @@ - (void)_test_NSURLSession:(NSURLSession*)session
}];

[task resume];

[self waitForExpectationsWithTimeout:kRequestTime+kResponseTime+0.5 handler:^(NSError * _Nullable error) {
completion(errorResponse, dataResponse);
}];
Expand Down Expand Up @@ -183,7 +183,7 @@ - (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");
Expand All @@ -195,6 +195,8 @@ - (void)test_SharedNSURLSession
XCTAssertNil(redirectResponse, @"Unexpected redirect response received");
XCTAssertEqualObjects(jsonResponse, json, @"Unexpected data received");
}];

[session finishTasksAndInvalidate];
}
else
{
Expand All @@ -208,7 +210,7 @@ - (void)test_NSURLSessionDefaultConfig
{
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");
Expand All @@ -220,6 +222,8 @@ - (void)test_NSURLSessionDefaultConfig
XCTAssertNil(redirectResponse, @"Unexpected redirect response received");
XCTAssertEqualObjects(jsonResponse, json, @"Unexpected data received");
}];

[session finishTasksAndInvalidate];
}
else
{
Expand All @@ -243,6 +247,7 @@ - (void)test_NSURLSessionDefaultConfig_notFollowingRedirects
XCTAssertEqual(301, [redirectResponse statusCode], @"Expected 301 redirect");
XCTAssertNil(jsonResponse, @"Unexpected data received");
}];
[session finishTasksAndInvalidate];
}
else
{
Expand All @@ -256,7 +261,7 @@ - (void)test_NSURLSessionEphemeralConfig
{
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");
Expand All @@ -268,6 +273,8 @@ - (void)test_NSURLSessionEphemeralConfig
XCTAssertNil(redirectResponse, @"Unexpected redirect response received");
XCTAssertEqualObjects(jsonResponse, json, @"Unexpected data received");
}];

[session finishTasksAndInvalidate];
}
else
{
Expand All @@ -282,7 +289,7 @@ - (void)test_NSURLSessionDefaultConfig_Disabled
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
Expand All @@ -296,6 +303,8 @@ - (void)test_NSURLSessionDefaultConfig_Disabled
XCTAssertNil(redirectResponse, @"Redirect response should not have been received as stubs should be disabled");
XCTAssertNil(jsonResponse, @"Data should not have been received as stubs should be disabled");
}];

[session finishTasksAndInvalidate];
}
else
{
Expand All @@ -314,16 +323,16 @@ - (void)test_NSURLSession_DataTask_DelegateMethods
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
Expand Down Expand Up @@ -366,6 +375,7 @@ - (void)test_NSURLSessionCustomHTTPBody

requestWithBody.HTTPBody = [@"somethingElse" dataUsingEncoding:NSUTF8StringEncoding];
[[session dataTaskWithRequest:requestWithBody] resume];
[session finishTasksAndInvalidate];
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you fix the indentation here? (use spaces so that we're sure it matches the rest of the code which already uses spaces too). Yeah, I know, that old war again 😄


[self waitForExpectationsWithTimeout:5 handler:nil];

Expand Down