A helper function to stub network requests with OHHTTPStubs using raw response recorded with curl -is
.
Inspired by the feature of Nocilla to stub raw responses recorded with curl -is
and this gist by Denis Lebedev.
A helper function to stub network requests with OHHTTPStubs using raw response recorded with curl -is
.
Inspired by the feature of Nocilla to stub raw responses recorded with curl -is
and this gist by Denis Lebedev.
/// File at `rawResponseFilePath` contains a response recorded using `curl -is` | |
/// so we could read response headers and body from it. | |
void StubNetworkRequest(NSString *httpMethod, NSString *httpPath, NSString *rawResponseFilePath) | |
{ | |
NSData *rawResponseData = [NSData dataWithContentsOfFile:rawResponseFilePath]; | |
__block NSInteger statusCode = 0; | |
__block NSDictionary *headers; | |
__block NSData *body; | |
CFHTTPMessageRef httpMessage = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, FALSE); | |
if (httpMessage) { | |
CFHTTPMessageAppendBytes(httpMessage, [rawResponseData bytes], [rawResponseData length]); | |
if (CFHTTPMessageIsHeaderComplete(httpMessage)) { | |
statusCode = (NSInteger)CFHTTPMessageGetResponseStatusCode(httpMessage); | |
headers = (__bridge_transfer NSDictionary *)CFHTTPMessageCopyAllHeaderFields(httpMessage); | |
body = (__bridge_transfer NSData *)CFHTTPMessageCopyBody(httpMessage); | |
} | |
CFRelease(httpMessage); | |
} | |
[OHHTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) { | |
return ([request.URL.path isEqualToString:httpPath] && [request.HTTPMethod isEqualToString:httpMethod]); | |
} withStubResponse:^OHHTTPStubsResponse *(NSURLRequest *request) { | |
return [OHHTTPStubsResponse responseWithData:body statusCode:statusCode headers:headers]; | |
}]; | |
} |