PageRenderTime 28ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/WebServiceDemo/Required_Libs/HTTPRequest/Classes/Tests/ASIHTTPRequestTests.m

https://gitlab.com/praveenvelanati/ios-demo
Objective C | 1152 lines | 852 code | 228 blank | 72 comment | 63 complexity | 0c64701ac82c817d9f2857a9f01f965e MD5 | raw file
  1. //
  2. // ASIHTTPRequestTests.m
  3. // Part of ASIHTTPRequest -> http://allseeing-i.com/ASIHTTPRequest
  4. //
  5. // Created by Ben Copsey on 01/08/2008.
  6. // Copyright 2008 All-Seeing Interactive. All rights reserved.
  7. //
  8. #import "ASIHTTPRequestTests.h"
  9. #import "ASIHTTPRequest.h"
  10. #import "ASINetworkQueue.h"
  11. #import "ASIFormDataRequest.h"
  12. #import <SystemConfiguration/SystemConfiguration.h>
  13. #import <unistd.h>
  14. // Used for subclass test
  15. @interface ASIHTTPRequestSubclass : ASIHTTPRequest {}
  16. @end
  17. @implementation ASIHTTPRequestSubclass;
  18. // For testing exceptions are caught
  19. - (void)startRequest
  20. {
  21. [[NSException exceptionWithName:@"Test Exception" reason:@"Test Reason" userInfo:nil] raise];
  22. }
  23. @end
  24. // Stop clang complaining about undeclared selectors
  25. @interface ASIHTTPRequestTests ()
  26. - (void)runCancelTest;
  27. - (void)performDelegateMethodsTest;
  28. - (void)requestStarted:(ASIHTTPRequest *)request;
  29. - (void)requestFinished:(ASIHTTPRequest *)request;
  30. - (void)requestFailed:(ASIHTTPRequest *)request;
  31. - (void)delegateTestStarted:(ASIHTTPRequest *)request;
  32. - (void)delegateTestResponseHeaders:(ASIHTTPRequest *)request;
  33. - (void)delegateTestFinished:(ASIHTTPRequest *)request;
  34. - (void)delegateTestFailed:(ASIHTTPRequest *)request;
  35. - (void)runRemoveUploadProgressTest;
  36. - (void)runRedirectedResume;
  37. - (void)performDownloadProgressTest;
  38. - (void)theTestRequest:(ASIHTTPRequest *)request didReceiveData:(NSData *)data;
  39. - (void)theTestRequestFinished:(ASIHTTPRequest *)request;
  40. - (void)performUploadProgressTest;
  41. - (void)performPostBodyStreamedFromDiskTest;
  42. - (void)performPartialFetchTest;
  43. - (void)asyncFail:(ASIHTTPRequest *)request;
  44. - (void)asyncSuccess:(ASIHTTPRequest *)request;
  45. - (void)request:(ASIHTTPRequest *)request isGoingToRedirectToURL:(NSURL *)url;
  46. - (void)redirectURLTestFailed:(ASIHTTPRequest *)request;
  47. - (void)redirectURLTestSucceeded:(ASIHTTPRequest *)request;
  48. @end
  49. @implementation ASIHTTPRequestTests
  50. - (void)testBasicDownload
  51. {
  52. NSURL *url = [NSURL URLWithString:@"http://allseeing-i.com"];
  53. ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
  54. [request startSynchronous];
  55. NSString *html = [request responseString];
  56. GHAssertNotNil(html,@"Basic synchronous request failed");
  57. // Check we're getting the correct response headers
  58. NSString *pingBackHeader = [[request responseHeaders] objectForKey:@"X-Pingback"];
  59. BOOL success = [pingBackHeader isEqualToString:@"http://allseeing-i.com/Ping-Back"];
  60. GHAssertTrue(success,@"Failed to populate response headers");
  61. // Check we're getting back the correct status code
  62. url = [[[NSURL alloc] initWithString:@"http://allseeing-i.com/a-page-that-does-not-exist"] autorelease];
  63. request = [[[ASIHTTPRequest alloc] initWithURL:url] autorelease];
  64. [request startSynchronous];
  65. success = ([request responseStatusCode] == 404);
  66. GHAssertTrue(success,@"Didn't get correct status code");
  67. // Check data is as expected
  68. NSRange notFound = NSMakeRange(NSNotFound, 0);
  69. success = !NSEqualRanges([html rangeOfString:@"All-Seeing Interactive"],notFound);
  70. GHAssertTrue(success,@"Failed to download the correct data");
  71. // Attempt to grab from bad url
  72. url = [[[NSURL alloc] initWithString:@""] autorelease];
  73. request = [[[ASIHTTPRequest alloc] initWithURL:url] autorelease];
  74. [request startSynchronous];
  75. success = [[request error] code] == ASIInternalErrorWhileBuildingRequestType;
  76. GHAssertTrue(success,@"Failed to generate an error for a bad host");
  77. request = [[[ASIHTTPRequest alloc] initWithURL:nil] autorelease];
  78. [request startSynchronous];
  79. success = [[request error] code] == ASIUnableToCreateRequestErrorType;
  80. GHAssertTrue(success,@"Failed to generate an error for a bad host");
  81. }
  82. - (void)testBase64Encode
  83. {
  84. NSData *data = [@"Hello, world" dataUsingEncoding:NSUTF8StringEncoding];
  85. NSString *base64 = [ASIHTTPRequest base64forData:data];
  86. BOOL success = [base64 isEqualToString:@"SGVsbG8sIHdvcmxk"];
  87. GHAssertTrue(success,@"Failed to encode data using base64 data correctly");
  88. }
  89. - (void)testCancel
  90. {
  91. // We run this test on the main thread because otherwise we can't depend on the delegate being notified before we need to test it's working
  92. [self performSelectorOnMainThread:@selector(runCancelTest) withObject:nil waitUntilDone:YES];
  93. }
  94. - (void)runCancelTest
  95. {
  96. ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:@"http://allseeing-i.com/ASIHTTPRequest/tests/the_great_american_novel_%28abridged%29.txt"]];
  97. [request startAsynchronous];
  98. [request cancel];
  99. [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:2.0]];
  100. GHAssertNotNil([request error],@"Failed to cancel the request");
  101. // Test cancelling a redirected request works
  102. // This test is probably unreliable on very slow or very fast connections, as it depends on being able to complete the first request (but not the second) in under 2 seconds
  103. request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:@"http://allseeing-i.com/ASIHTTPRequest/tests/cancel_redirect"]];
  104. [request startAsynchronous];
  105. [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:2.0]];
  106. [request cancel];
  107. [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:2.0]];
  108. BOOL success = ([[[request url] absoluteString] isEqualToString:@"http://allseeing-i.com/ASIHTTPRequest/tests/the_great_american_novel.txt"]);
  109. GHAssertTrue(success, @"Request did not redirect quickly enough, cannot proceed with test");
  110. GHAssertNotNil([request error],@"Failed to cancel the request");
  111. success = [request totalBytesRead] < 7900198;
  112. GHAssertTrue(success, @"Downloaded the whole of the response even though we should have cancelled by now");
  113. }
  114. - (void)testDelegateMethods
  115. {
  116. // We run this test on the main thread because otherwise we can't depend on the delegate being notified before we need to test it's working
  117. [self performSelectorOnMainThread:@selector(performDelegateMethodsTest) withObject:nil waitUntilDone:YES];
  118. }
  119. - (void)performDelegateMethodsTest
  120. {
  121. started = NO;
  122. finished = NO;
  123. failed = NO;
  124. // Test default delegate methods
  125. ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:@"http://allseeing-i.com"]];
  126. [request setDelegate:self];
  127. [request startSynchronous];
  128. GHAssertTrue(started,@"Failed to call the delegate method when the request started");
  129. GHAssertTrue(receivedResponseHeaders,@"Failed to call the delegate method when the request started");
  130. GHAssertTrue(finished,@"Failed to call the delegate method when the request finished");
  131. request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:@"http://allseeing-i.com/ASIHTTPRequest/tests/the_great_american_novel.txt"]];
  132. [request setDelegate:self];
  133. [request setTimeOutSeconds:0.01];
  134. [request startSynchronous];
  135. GHAssertTrue(failed,@"Failed to call the delegate method when the request failed");
  136. started = NO;
  137. finished = NO;
  138. failed = NO;
  139. receivedResponseHeaders = NO;
  140. // Test custom delegate methods
  141. request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:@"http://allseeing-i.com"]];
  142. [request setDelegate:self];
  143. [request setDidStartSelector:@selector(delegateTestStarted:)];
  144. [request setDidReceiveResponseHeadersSelector:@selector(delegateTestResponseHeaders:)];
  145. [request setDidFinishSelector:@selector(delegateTestFinished:)];
  146. [request startSynchronous];
  147. GHAssertTrue(started,@"Failed to call the delegate method when the request started");
  148. GHAssertTrue(finished,@"Failed to call the delegate method when the request finished");
  149. request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:@"http://allseeing-i.com/ASIHTTPRequest/tests/the_great_american_novel.txt"]];
  150. [request setDidFailSelector:@selector(delegateTestFailed:)];
  151. [request setDelegate:self];
  152. [request setTimeOutSeconds:0.01];
  153. [request startSynchronous];
  154. GHAssertTrue(failed,@"Failed to call the delegate method when the request failed");
  155. }
  156. - (void)requestStarted:(ASIHTTPRequest *)request
  157. {
  158. started = YES;
  159. }
  160. - (void)request:(ASIHTTPRequest *)request didReceiveResponseHeaders:(NSDictionary *)newResponseHeaders
  161. {
  162. GHAssertNotNil(newResponseHeaders,@"Called request:didReceiveResponseHeaders: when we have no headers");
  163. receivedResponseHeaders = YES;
  164. }
  165. - (void)requestFinished:(ASIHTTPRequest *)request
  166. {
  167. finished = YES;
  168. }
  169. - (void)requestFailed:(ASIHTTPRequest *)request
  170. {
  171. failed = YES;
  172. }
  173. - (void)delegateTestStarted:(ASIHTTPRequest *)request
  174. {
  175. started = YES;
  176. }
  177. - (void)delegateTestResponseHeaders:(ASIHTTPRequest *)request
  178. {
  179. GHAssertNotNil([request responseHeaders],@"Called delegateTestResponseHeaders: when we have no headers");
  180. receivedResponseHeaders = YES;
  181. }
  182. - (void)delegateTestFinished:(ASIHTTPRequest *)request
  183. {
  184. finished = YES;
  185. }
  186. - (void)delegateTestFailed:(ASIHTTPRequest *)request
  187. {
  188. failed = YES;
  189. }
  190. - (void)testConditionalGET
  191. {
  192. ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:@"http://allseeing-i.com/i/logo.png"]];
  193. [request startSynchronous];
  194. BOOL success = ([request responseStatusCode] == 200);
  195. GHAssertTrue(success, @"Failed to download file, cannot proceed with this test");
  196. success = ([[request responseData] length] > 0);
  197. GHAssertTrue(success, @"Response length is 0, this shouldn't happen");
  198. NSString *etag = [[request responseHeaders] objectForKey:@"Etag"];
  199. NSString *lastModified = [[request responseHeaders] objectForKey:@"Last-Modified"];
  200. GHAssertNotNil(etag, @"Response didn't return an etag");
  201. GHAssertNotNil(lastModified, @"Response didn't return a last modified date");
  202. request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:@"http://allseeing-i.com/i/logo.png"]];
  203. [request addRequestHeader:@"If-Modified-Since" value:lastModified];
  204. [request addRequestHeader:@"If-None-Match" value:etag];
  205. [request startSynchronous];
  206. success = ([request responseStatusCode] == 304);
  207. GHAssertTrue(success, @"Got wrong status code");
  208. success = ([[request responseData] length] == 0);
  209. GHAssertTrue(success, @"Response length is not 0, this shouldn't happen");
  210. }
  211. - (void)testException
  212. {
  213. ASIHTTPRequestSubclass *request = [ASIHTTPRequestSubclass requestWithURL:[NSURL URLWithString:@"http://allseeing-i.com"]];
  214. [request startSynchronous];
  215. NSError *error = [request error];
  216. GHAssertNotNil(error,@"Failed to generate an error for an exception");
  217. BOOL success = [[[error userInfo] objectForKey:NSLocalizedDescriptionKey] isEqualToString:@"Test Exception"];
  218. GHAssertTrue(success, @"Generated wrong error for exception");
  219. }
  220. - (void)testCharacterEncoding
  221. {
  222. NSArray *IANAEncodings = [NSArray arrayWithObjects:@"UTF-8",@"US-ASCII",@"ISO-8859-1",@"UTF-16",nil];
  223. NSUInteger NSStringEncodings[] = {NSUTF8StringEncoding,NSASCIIStringEncoding,NSISOLatin1StringEncoding,NSUnicodeStringEncoding};
  224. NSUInteger i;
  225. for (i=0; i<[IANAEncodings count]; i++) {
  226. NSURL *url = [[[NSURL alloc] initWithString:[NSString stringWithFormat:@"http://allseeing-i.com/ASIHTTPRequest/tests/Character-Encoding/%@",[IANAEncodings objectAtIndex:i]]] autorelease];
  227. ASIHTTPRequest *request = [[[ASIHTTPRequest alloc] initWithURL:url] autorelease];
  228. [request startSynchronous];
  229. BOOL success = [request responseEncoding] == NSStringEncodings[i];
  230. GHAssertTrue(success,[NSString stringWithFormat:@"Failed to use the correct text encoding for %@i",[IANAEncodings objectAtIndex:i]]);
  231. }
  232. NSURL *url = [[[NSURL alloc] initWithString:@"http://allseeing-i.com/ASIHTTPRequest/tests/Character-Encoding/Something-else"] autorelease];
  233. ASIHTTPRequest *request = [[[ASIHTTPRequest alloc] initWithURL:url] autorelease];
  234. [request setDefaultResponseEncoding:NSWindowsCP1251StringEncoding];
  235. [request startSynchronous];
  236. BOOL success = [request responseEncoding] == [request defaultResponseEncoding];
  237. GHAssertTrue(success,[NSString stringWithFormat:@"Failed to use the default string encoding"]);
  238. // Will return a Content-Type header with charset in the middle of the value (Fix contributed by Roman Busyghin)
  239. url = [[[NSURL alloc] initWithString:@"http://allseeing-i.com/ASIHTTPRequest/tests/Character-Encoding/utf-16-with-type-header"] autorelease];
  240. request = [[[ASIHTTPRequest alloc] initWithURL:url] autorelease];
  241. [request startSynchronous];
  242. success = [request responseEncoding] == NSUnicodeStringEncoding;
  243. GHAssertTrue(success,[NSString stringWithFormat:@"Failed to parse the content type header correctly"]);
  244. }
  245. - (void)testTimeOut
  246. {
  247. NSURL *url = [[[NSURL alloc] initWithString:@"http://allseeing-i.com/ASIHTTPRequest/tests/the_great_american_novel_%28abridged%29.txt"] autorelease];
  248. ASIHTTPRequest *request = [[[ASIHTTPRequest alloc] initWithURL:url] autorelease];
  249. [request setTimeOutSeconds:0.0001]; //It's pretty unlikely we will be able to grab the data this quickly, so the request should timeout
  250. [request startSynchronous];
  251. BOOL success = [[request error] code] == ASIRequestTimedOutErrorType;
  252. GHAssertTrue(success,@"Timeout didn't generate the correct error");
  253. [ASIHTTPRequest setDefaultTimeOutSeconds:0.0001];
  254. request = [[[ASIHTTPRequest alloc] initWithURL:url] autorelease];
  255. [request startSynchronous];
  256. success = [[request error] code] == ASIRequestTimedOutErrorType;
  257. GHAssertTrue(success,@"Failed to change the default timeout");
  258. [ASIHTTPRequest setDefaultTimeOutSeconds:10];
  259. }
  260. // Test fix for a bug that might have caused timeouts when posting data
  261. - (void)testTimeOutWithoutDownloadDelegate
  262. {
  263. ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:@"http://allseeing-i.com/ASIHTTPRequest/tests/the_great_american_novel_%28young_readers_edition%29.txt"]];
  264. [request setTimeOutSeconds:5];
  265. [request setShowAccurateProgress:NO];
  266. [request setPostBody:[NSMutableData dataWithData:[@"Small Body" dataUsingEncoding:NSUTF8StringEncoding]]];
  267. [request startSynchronous];
  268. GHAssertNil([request error],@"Generated an error (most likely a timeout) - this test might fail on high latency connections");
  269. }
  270. - (void)testRequestMethod
  271. {
  272. NSURL *url = [[[NSURL alloc] initWithString:@"http://allseeing-i.com/ASIHTTPRequest/tests/request-method"] autorelease];
  273. NSArray *methods = [[[NSArray alloc] initWithObjects:@"GET",@"POST",@"PUT",@"DELETE", nil] autorelease];
  274. for (NSString *method in methods) {
  275. ASIHTTPRequest *request = [[[ASIHTTPRequest alloc] initWithURL:url] autorelease];
  276. [request setRequestMethod:method];
  277. [request startSynchronous];
  278. BOOL success = [[request responseString] isEqualToString:method];
  279. GHAssertTrue(success,@"Failed to set the request method correctly");
  280. }
  281. // Test to ensure we don't change the request method when we have an unrecognised method already set
  282. ASIHTTPRequest *request = [[[ASIHTTPRequest alloc] initWithURL:url] autorelease];
  283. [request setRequestMethod:@"FINK"];
  284. [request appendPostData:[@"King" dataUsingEncoding:NSUTF8StringEncoding]];
  285. [request buildPostBody];
  286. BOOL success = [[request requestMethod] isEqualToString:@"FINK"];
  287. GHAssertTrue(success,@"Erroneously changed request method");
  288. }
  289. - (void)testHTTPVersion
  290. {
  291. NSURL *url = [[[NSURL alloc] initWithString:@"http://allseeing-i.com/ASIHTTPRequest/tests/http-version"] autorelease];
  292. ASIHTTPRequest *request = [[[ASIHTTPRequest alloc] initWithURL:url] autorelease];
  293. [request startSynchronous];
  294. BOOL success = [[request responseString] isEqualToString:@"HTTP/1.1"];
  295. GHAssertTrue(success,@"Wrong HTTP version used (May fail when using a proxy that changes the HTTP version!)");
  296. request = [[[ASIHTTPRequest alloc] initWithURL:url] autorelease];
  297. [request setUseHTTPVersionOne:YES];
  298. [request startSynchronous];
  299. success = [[request responseString] isEqualToString:@"HTTP/1.0"];
  300. GHAssertTrue(success,@"Wrong HTTP version used (May fail when using a proxy that changes the HTTP version!)");
  301. }
  302. - (void)testUserAgent
  303. {
  304. // defaultUserAgentString will be nil if we haven't set a Bundle Name or Bundle Display Name
  305. if ([ASIHTTPRequest defaultUserAgentString]) {
  306. // Returns the user agent it received in the response body
  307. ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:@"http://allseeing-i.com/ASIHTTPRequest/tests/user-agent"]];
  308. [request startSynchronous];
  309. BOOL success = [[request responseString] isEqualToString:[ASIHTTPRequest defaultUserAgentString]];
  310. GHAssertTrue(success,@"Failed to set the correct user agent");
  311. }
  312. NSString *customUserAgent = @"Ferdinand Fuzzworth's Magic Tent of Mystery";
  313. // Test specifying a custom user-agent for a single request
  314. ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:@"http://allseeing-i.com/ASIHTTPRequest/tests/user-agent"]];
  315. [request addRequestHeader:@"User-Agent" value:customUserAgent];
  316. [request startSynchronous];
  317. BOOL success = [[request responseString] isEqualToString:customUserAgent];
  318. GHAssertTrue(success,@"Failed to set the correct user-agent for a single request");
  319. // Test again using userAgent
  320. request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:@"http://allseeing-i.com/ASIHTTPRequest/tests/user-agent"]];
  321. [request setUserAgentString:customUserAgent];
  322. [request startSynchronous];
  323. success = [[request responseString] isEqualToString:customUserAgent];
  324. GHAssertTrue(success,@"Failed to set the correct user-agent for a single request");
  325. // Test again to ensure user-agent not reused
  326. request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:@"http://allseeing-i.com/ASIHTTPRequest/tests/user-agent"]];
  327. [request startSynchronous];
  328. success = ![[request responseString] isEqualToString:customUserAgent];
  329. GHAssertTrue(success,@"Re-used a user agent when we shouldn't have done so");
  330. // Test setting a custom default user-agent string
  331. [ASIHTTPRequest setDefaultUserAgentString:customUserAgent];
  332. request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:@"http://allseeing-i.com/ASIHTTPRequest/tests/user-agent"]];
  333. [request startSynchronous];
  334. success = [[request responseString] isEqualToString:customUserAgent];
  335. GHAssertTrue(success,@"Failed to set the correct user-agent when using a custom default");
  336. [ASIHTTPRequest setDefaultUserAgentString:nil];
  337. request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:@"http://allseeing-i.com/ASIHTTPRequest/tests/user-agent"]];
  338. [request startSynchronous];
  339. success = ![[request responseString] isEqualToString:customUserAgent];
  340. GHAssertTrue(success,@"Failed to clear a custom default user-agent");
  341. }
  342. - (void)testAutomaticRedirection
  343. {
  344. ASIHTTPRequest *request;
  345. ASIFormDataRequest *request2;
  346. BOOL success;
  347. unsigned int i;
  348. for (i=301; i<308; i++) {
  349. if (i > 304 && i < 307) {
  350. continue;
  351. }
  352. NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://allseeing-i.com/ASIHTTPRequest/tests/redirect/%hi",i]];
  353. request = [ASIHTTPRequest requestWithURL:url];
  354. [request setShouldRedirect:NO];
  355. [request startSynchronous];
  356. if (i == 304) { // 304s will not contain a body, as per rfc2616. Will test 304 handling in a future test when we have etag support
  357. continue;
  358. }
  359. success = [[request responseString] isEqualToString:[NSString stringWithFormat:@"Non-redirected content with %hi status code",i]];
  360. GHAssertTrue(success,[NSString stringWithFormat:@"Got the wrong content when not redirecting after a %hi",i]);
  361. request2 = [ASIFormDataRequest requestWithURL:url];
  362. [request2 setPostValue:@"Giant Monkey" forKey:@"lookbehindyou"];
  363. [request2 startSynchronous];
  364. NSString *method = @"GET";
  365. if (i>304) {
  366. method = @"POST";
  367. }
  368. NSString *expectedString = [NSString stringWithFormat:@"Redirected as %@ after a %hi status code",method,i];
  369. if (i>304) {
  370. expectedString = [NSString stringWithFormat:@"%@\r\nWatch out for the Giant Monkey!",expectedString];
  371. }
  372. success = [[request2 responseString] isEqualToString:expectedString];
  373. GHAssertTrue(success,[NSString stringWithFormat:@"Got the wrong content when redirecting after a %hi",i]);
  374. success = ([request2 responseStatusCode] == 200);
  375. GHAssertTrue(success,@"Got the wrong status code (expected 200)");
  376. }
  377. // Test RFC 2616 behaviour
  378. for (i=301; i<303; i++) {
  379. NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://allseeing-i.com/ASIHTTPRequest/tests/redirect/%hi",i]];
  380. request2 = [ASIFormDataRequest requestWithURL:url];
  381. [request2 setPostValue:@"Giant Monkey" forKey:@"lookbehindyou"];
  382. [request2 setShouldUseRFC2616RedirectBehaviour:YES];
  383. [request2 startSynchronous];
  384. success = ([request2 responseStatusCode] == 200);
  385. GHAssertTrue(success,@"Got the wrong status code (expected 200)");
  386. if (i == 303) {
  387. success = ([request2 postLength] == 0 && ![request2 postBody] && [[request2 requestMethod] isEqualToString:@"GET"]);
  388. GHAssertTrue(success,@"Failed to reset request to GET on 303 redirect");
  389. success = [[request2 responseString] isEqualToString:[NSString stringWithFormat:@"Redirected as GET after a %hi status code",i]];
  390. GHAssertTrue(success,@"Failed to dump the post body on 303 redirect");
  391. } else {
  392. success = ([request2 postLength] > 0 || ![request2 postBody] || ![[request2 requestMethod] isEqualToString:@"POST"]);
  393. GHAssertTrue(success,@"Failed to use the same request method and body for a redirect when using rfc2616 behaviour");
  394. success = ([[request2 responseString] isEqualToString:[NSString stringWithFormat:@"Redirected as POST after a %hi status code\r\nWatch out for the Giant Monkey!",i]]);
  395. GHAssertTrue(success,@"Failed to send the correct post body on redirect");
  396. }
  397. }
  398. // Ensure the file contains only the body of the last request (after redirects) when downloading to a file
  399. request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:@"http://allseeing-i.com/ASIHTTPRequest/tests/redirect/301"]];
  400. NSString *path = [[self filePathForTemporaryTestFiles] stringByAppendingPathComponent:@"test.txt"];
  401. [request setDownloadDestinationPath:path];
  402. [request startSynchronous];
  403. NSString *result = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
  404. success = [result isEqualToString:@"Redirected as GET after a 301 status code"];
  405. GHAssertTrue(success,@"Failed to store just the body of the file request on redirect");
  406. success = ([request originalURL] != [request url]);
  407. GHAssertTrue(success,@"Failed to update request url on redirection");
  408. success = ([[[request originalURL] absoluteString] isEqualToString:@"http://allseeing-i.com/ASIHTTPRequest/tests/redirect/301"]);
  409. GHAssertTrue(success,@"Failed to preserve original url");
  410. // Ensure user agent is preserved
  411. request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:@"http://allseeing-i.com/ASIHTTPRequest/tests/redirect/301"]];
  412. [request addRequestHeader:@"User-Agent" value:@"test"];
  413. [request startSynchronous];
  414. success = ([[[request requestHeaders] objectForKey:@"User-Agent"] isEqualToString:@"test"]);
  415. GHAssertTrue(success,@"Failed to preserve original user agent on redirect");
  416. }
  417. // Using a persistent connection for HTTP 305-307 would cause crashes on the redirect, not really sure why
  418. // Since 305 (use proxy) wasn't properly supported anyway, 306 is unused, and clients are supposed to confirm redirects for 307, I've simply removed automatic redirect for these codes
  419. - (void)test30xCrash
  420. {
  421. int i;
  422. for (i=305; i<308; i++) {
  423. ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://allseeing-i.com/ASIHTTPRequest/tests/redirect/%hi",i]]];
  424. [request setPostValue:@"foo" forKey:@"eep"];
  425. [request setShouldRedirect:NO];
  426. [request startSynchronous];
  427. request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://allseeing-i.com/ASIHTTPRequest/tests/redirect/%hi",i]]];
  428. [request setPostValue:@"foo" forKey:@"eep"];
  429. [request startSynchronous];
  430. }
  431. }
  432. - (void)testResumeChecksContentRangeHeader
  433. {
  434. NSURL *url = [NSURL URLWithString:@"http://allseeing-i.com/ASIHTTPRequest/tests/no_resume"];
  435. NSString *temporaryPath = [[self filePathForTemporaryTestFiles] stringByAppendingPathComponent:@"foo.temp"];
  436. [@"" writeToFile:temporaryPath atomically:NO encoding:NSUTF8StringEncoding error:NULL];
  437. NSString *downloadPath = [[self filePathForTemporaryTestFiles] stringByAppendingPathComponent:@"foo.txt"];
  438. // Download part of a large file that is returned after a redirect
  439. ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
  440. [request setTemporaryFileDownloadPath:temporaryPath];
  441. [request setDownloadDestinationPath:downloadPath];
  442. [request setAllowResumeForFileDownloads:YES];
  443. [request setAllowCompressedResponse:NO];
  444. [request setShouldAttemptPersistentConnection:NO];
  445. [request startAsynchronous];
  446. // Cancel the request as soon as it has downloaded 64KB
  447. while (1) {
  448. sleep(0.5);
  449. if ([request totalBytesRead] > 32*1024) {
  450. [request cancel];
  451. break;
  452. }
  453. }
  454. NSNumber *fileSize = [[[NSFileManager defaultManager] attributesOfItemAtPath:temporaryPath error:NULL] objectForKey:NSFileSize];
  455. unsigned long long partialFileSize = [fileSize unsignedLongLongValue];
  456. BOOL success = (partialFileSize < 1036935);
  457. GHAssertTrue(success,@"Downloaded whole file too quickly, cannot proceed with this test");
  458. // Resume the download
  459. request = [ASIHTTPRequest requestWithURL:url];
  460. [request setTemporaryFileDownloadPath:temporaryPath];
  461. [request setDownloadDestinationPath:downloadPath];
  462. [request setAllowResumeForFileDownloads:YES];
  463. [request setAllowCompressedResponse:NO];
  464. [request buildRequestHeaders];
  465. success = ([request partialDownloadSize] == partialFileSize);
  466. GHAssertTrue(success,@"Failed to obtain correct partial dowload size");
  467. [request startAsynchronous];
  468. while (1) {
  469. sleep(0.5);
  470. if ([request isFinished]) {
  471. break;
  472. }
  473. }
  474. GHAssertNil([request error],@"Request failed, cannot proceed with this test");
  475. success = (![[request responseHeaders] objectForKey:@"Content-Range"]);
  476. GHAssertTrue(success,@"Got range header back, cannot proceed with this test");
  477. NSDictionary *attributes = [[NSFileManager defaultManager] attributesOfItemAtPath:downloadPath error:NULL];
  478. fileSize = [attributes objectForKey:NSFileSize];
  479. success = ([fileSize intValue] == 1036935);
  480. GHAssertTrue(success,@"Downloaded file has wrong length");
  481. success = ([request partialDownloadSize] == 0);
  482. GHAssertTrue(success,@"Failed to reset download size");
  483. }
  484. - (void)testRedirectedResume
  485. {
  486. [self performSelectorOnMainThread:@selector(runRedirectedResume) withObject:nil waitUntilDone:YES];
  487. }
  488. - (void)runRedirectedResume
  489. {
  490. NSURL *url = [NSURL URLWithString:@"http://allseeing-i.com/ASIHTTPRequest/tests/redirect_resume"];
  491. NSString *temporaryPath = [[self filePathForTemporaryTestFiles] stringByAppendingPathComponent:@"foo.temp"];
  492. [@"" writeToFile:temporaryPath atomically:NO encoding:NSUTF8StringEncoding error:NULL];
  493. NSString *downloadPath = [[self filePathForTemporaryTestFiles] stringByAppendingPathComponent:@"foo.txt"];
  494. // Download part of a large file that is returned after a redirect
  495. ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
  496. [request setTemporaryFileDownloadPath:temporaryPath];
  497. [request setDownloadDestinationPath:downloadPath];
  498. [request setAllowResumeForFileDownloads:YES];
  499. [request setAllowCompressedResponse:NO];
  500. [request startAsynchronous];
  501. // Cancel the request as soon as it has downloaded 64KB
  502. while (1) {
  503. [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.5]];
  504. if ([request totalBytesRead] > 32*1024) {
  505. [request cancel];
  506. break;
  507. }
  508. }
  509. NSNumber *fileSize = [[[NSFileManager defaultManager] attributesOfItemAtPath:temporaryPath error:NULL] objectForKey:NSFileSize];
  510. unsigned long long partialFileSize = [fileSize unsignedLongLongValue];
  511. BOOL success = (partialFileSize < 1036935);
  512. GHAssertTrue(success,@"Downloaded whole file too quickly, cannot proceed with this test");
  513. // Resume the download synchronously
  514. request = [ASIHTTPRequest requestWithURL:url];
  515. [request setTemporaryFileDownloadPath:temporaryPath];
  516. [request setDownloadDestinationPath:downloadPath];
  517. [request setAllowResumeForFileDownloads:YES];
  518. [request setAllowCompressedResponse:NO];
  519. [request startSynchronous];
  520. fileSize = [[[NSFileManager defaultManager] attributesOfItemAtPath:downloadPath error:NULL] objectForKey:NSFileSize];
  521. success = ([fileSize intValue] == 1036935);
  522. GHAssertTrue(success,@"Downloaded file has wrong length");
  523. success = [[[request requestHeaders] objectForKey:@"Range"] isEqualToString:[NSString stringWithFormat:@"bytes=%llu-",partialFileSize]];
  524. GHAssertTrue(success,@"Restarted download when we should have resumed, or asked for the wrong segment of the file");
  525. }
  526. - (void)testUploadContentLength
  527. {
  528. //This url will return the contents of the Content-Length request header
  529. NSURL *url = [NSURL URLWithString:@"http://allseeing-i.com/ASIHTTPRequest/tests/content-length"];
  530. ASIHTTPRequest *request = [[[ASIHTTPRequest alloc] initWithURL:url] autorelease];
  531. [request setPostBody:[NSMutableData dataWithLength:1024*32]];
  532. [request startSynchronous];
  533. BOOL success = ([[request responseString] isEqualToString:[NSString stringWithFormat:@"%hu",(1024*32)]]);
  534. GHAssertTrue(success,@"Sent wrong content length");
  535. }
  536. - (void)testDownloadContentLength
  537. {
  538. NSURL *url = [[[NSURL alloc] initWithString:@"http://allseeing-i.com/i/logo.png"] autorelease];
  539. ASIHTTPRequest *request = [[[ASIHTTPRequest alloc] initWithURL:url] autorelease];
  540. [request startSynchronous];
  541. BOOL success = ([request contentLength] == 27872);
  542. GHAssertTrue(success,@"Got wrong content length");
  543. }
  544. - (void)testFileDownload
  545. {
  546. NSString *path = [[self filePathForTemporaryTestFiles] stringByAppendingPathComponent:@"testimage.png"];
  547. NSURL *url = [[[NSURL alloc] initWithString:@"http://allseeing-i.com/i/logo.png"] autorelease];
  548. ASIHTTPRequest *request = [[[ASIHTTPRequest alloc] initWithURL:url] autorelease];
  549. [request setDownloadDestinationPath:path];
  550. [request startSynchronous];
  551. #if TARGET_OS_IPHONE
  552. UIImage *image = [[[UIImage alloc] initWithContentsOfFile:path] autorelease];
  553. #else
  554. NSImage *image = [[[NSImage alloc] initWithContentsOfFile:path] autorelease];
  555. #endif
  556. GHAssertNotNil(image,@"Failed to download data to a file");
  557. }
  558. - (void)testCompressedResponseDownloadToFile
  559. {
  560. NSString *path = [[self filePathForTemporaryTestFiles] stringByAppendingPathComponent:@"testfile"];
  561. NSURL *url = [[[NSURL alloc] initWithString:@"http://allseeing-i.com/ASIHTTPRequest/tests/first"] autorelease];
  562. ASIHTTPRequest *request = [[[ASIHTTPRequest alloc] initWithURL:url] autorelease];
  563. [request setDownloadDestinationPath:path];
  564. [request startSynchronous];
  565. NSString *tempPath = [request temporaryFileDownloadPath];
  566. GHAssertNil(tempPath,@"Failed to clean up temporary download file");
  567. BOOL success = [[NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:NULL] isEqualToString:@"This is the expected content for the first string"];
  568. GHAssertTrue(success,@"Failed to download data to a file");
  569. // Now test with inflating the response on the fly
  570. NSError *error = nil;
  571. [ASIHTTPRequest removeFileAtPath:path error:&error];
  572. if (error) {
  573. GHFail(@"Failed to remove file, cannot proceed with test");
  574. }
  575. request = [[[ASIHTTPRequest alloc] initWithURL:url] autorelease];
  576. [request setDownloadDestinationPath:path];
  577. [request setShouldWaitToInflateCompressedResponses:NO];
  578. [request startSynchronous];
  579. tempPath = [request temporaryFileDownloadPath];
  580. GHAssertNil(tempPath,@"Failed to clean up temporary download file");
  581. success = [[NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:NULL] isEqualToString:@"This is the expected content for the first string"];
  582. GHAssertTrue(success,@"Failed to download data to a file");
  583. }
  584. - (void)request:(ASIHTTPRequest *)request didGetMoreData:(NSData *)data
  585. {
  586. [[self responseData] appendData:data];
  587. }
  588. - (void)downloadFinished:(ASIHTTPRequest *)request
  589. {
  590. finished = YES;
  591. }
  592. - (void)testCompressedResponseDelegateDataHandling
  593. {
  594. finished = NO;
  595. [self setResponseData:[NSMutableData data]];
  596. NSURL *url = [[[NSURL alloc] initWithString:@"http://allseeing-i.com/ASIHTTPRequest/tests/the_hound_of_the_baskervilles.text"] autorelease];
  597. ASIHTTPRequest *request = [[[ASIHTTPRequest alloc] initWithURL:url] autorelease];
  598. [request startSynchronous];
  599. NSString *response = [request responseString];
  600. // Now download again, using the delegate to handle the data
  601. request = [[[ASIHTTPRequest alloc] initWithURL:url] autorelease];
  602. [request setDelegate:self];
  603. [request setDidReceiveDataSelector:@selector(request:didGetMoreData:)];
  604. [request setDidFinishSelector:@selector(downloadFinished:)];
  605. [request setShouldWaitToInflateCompressedResponses:NO];
  606. [request startSynchronous];
  607. while (!finished) {
  608. sleep(1);
  609. }
  610. NSString *delegateResponse = [[[NSString alloc] initWithBytes:[responseData bytes] length:[responseData length] encoding:[request responseEncoding]] autorelease];
  611. BOOL success = [delegateResponse isEqualToString:response];
  612. GHAssertTrue(success,@"Failed to correctly download the response using a delegate");
  613. // Test again without compression
  614. finished = NO;
  615. [self setResponseData:[NSMutableData data]];
  616. request = [[[ASIHTTPRequest alloc] initWithURL:url] autorelease];
  617. [request setAllowCompressedResponse:NO];
  618. [request startSynchronous];
  619. response = [request responseString];
  620. // Now download again, using the delegate to handle the data
  621. request = [[[ASIHTTPRequest alloc] initWithURL:url] autorelease];
  622. [request setDelegate:self];
  623. [request setDidReceiveDataSelector:@selector(request:didGetMoreData:)];
  624. [request setDidFinishSelector:@selector(downloadFinished:)];
  625. [request setAllowCompressedResponse:NO];
  626. [request startSynchronous];
  627. while (!finished) {
  628. sleep(1);
  629. }
  630. delegateResponse = [[[NSString alloc] initWithBytes:[responseData bytes] length:[responseData length] encoding:[request responseEncoding]] autorelease];
  631. success = [delegateResponse isEqualToString:response];
  632. GHAssertTrue(success,@"Failed to correctly download the response using a delegate");
  633. }
  634. - (void)testDownloadProgress
  635. {
  636. // We run tests that measure progress on the main thread because otherwise we can't depend on the progress delegate being notified before we need to test it's working
  637. [self performSelectorOnMainThread:@selector(performDownloadProgressTest) withObject:nil waitUntilDone:YES];
  638. }
  639. - (void)performDownloadProgressTest
  640. {
  641. progress = 0;
  642. NSURL *url = [[[NSURL alloc] initWithString:@"http://allseeing-i.com/i/logo.png"] autorelease];
  643. ASIHTTPRequest *request = [[[ASIHTTPRequest alloc] initWithURL:url] autorelease];
  644. [request setDownloadProgressDelegate:self];
  645. [request startSynchronous];
  646. BOOL success = (progress == 1.0);
  647. GHAssertTrue(success,@"Failed to properly increment download progress %f != 1.0",progress);
  648. progress = 0;
  649. request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:@"http://allseeing-i.com/ASIHTTPRequest/tests/the_great_american_novel.txt"]];
  650. [request setDownloadProgressDelegate:self];
  651. [request startAsynchronous];
  652. [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:2]];
  653. success = (progress != 1.0);
  654. GHAssertTrue(success,@"Downloaded too quickly, cannot proceed with test");
  655. success = (progress > 0);
  656. GHAssertTrue(success,@"Either downloaded too slowly, or progress is not being correctly updated");
  657. }
  658. - (void)testUploadProgress
  659. {
  660. // We run tests that measure progress on the main thread because otherwise we can't depend on the progress delegate being notified before we need to test it's working
  661. [self performSelectorOnMainThread:@selector(performUploadProgressTest) withObject:nil waitUntilDone:YES];
  662. }
  663. - (void)performUploadProgressTest
  664. {
  665. progress = 0;
  666. ASIHTTPRequest *request = [[[ASIHTTPRequest alloc] initWithURL:[NSURL URLWithString:@"http://allseeing-i.com/ignore"]] autorelease];
  667. [request setPostBody:(NSMutableData *)[@"This is the request body" dataUsingEncoding:NSUTF8StringEncoding]];
  668. [request setUploadProgressDelegate:self];
  669. [request startSynchronous];
  670. BOOL success = (progress == 1.0);
  671. GHAssertTrue(success,@"Failed to properly increment upload progress %f != 1.0",progress);
  672. }
  673. - (void)testPostBodyStreamedFromDisk
  674. {
  675. // We run tests that measure progress on the main thread because otherwise we can't depend on the progress delegate being notified before we need to test it's working
  676. [self performSelectorOnMainThread:@selector(performPostBodyStreamedFromDiskTest) withObject:nil waitUntilDone:YES];
  677. }
  678. - (void)performPostBodyStreamedFromDiskTest
  679. {
  680. NSURL *url = [NSURL URLWithString:@"http://allseeing-i.com/ASIHTTPRequest/tests/print_request_body"];
  681. NSString *requestBody = @"This is the request body";
  682. NSString *requestContentPath = [[self filePathForTemporaryTestFiles] stringByAppendingPathComponent:@"testfile.txt"];
  683. [[requestBody dataUsingEncoding:NSUTF8StringEncoding] writeToFile:requestContentPath atomically:NO];
  684. // Test using a user-specified file as the request body (useful for PUT)
  685. progress = 0;
  686. ASIHTTPRequest *request = [[[ASIHTTPRequest alloc] initWithURL:url] autorelease];
  687. [request setRequestMethod:@"PUT"];
  688. [request setShouldStreamPostDataFromDisk:YES];
  689. [request setUploadProgressDelegate:self];
  690. [request setPostBodyFilePath:requestContentPath];
  691. [request startSynchronous];
  692. BOOL success = (progress == 1.0);
  693. GHAssertTrue(success,@"Failed to properly increment upload progress %f != 1.0",progress);
  694. success = [[request responseString] isEqualToString:requestBody];
  695. GHAssertTrue(success,@"Failed upload the correct request body");
  696. // Test building a request body by appending data
  697. progress = 0;
  698. request = [[[ASIHTTPRequest alloc] initWithURL:url] autorelease];
  699. [request setShouldStreamPostDataFromDisk:YES];
  700. [request setRequestMethod:@"PUT"];
  701. [request setUploadProgressDelegate:self];
  702. [request appendPostDataFromFile:requestContentPath];
  703. [request startSynchronous];
  704. success = (progress == 1.0);
  705. GHAssertTrue(success,@"Failed to properly increment upload progress %f != 1.0",progress);
  706. success = [[request responseString] isEqualToString:requestBody];
  707. GHAssertTrue(success,@"Failed upload the correct request body");
  708. }
  709. - (void)testCookies
  710. {
  711. BOOL success;
  712. // Set setting a cookie
  713. NSURL *url = [[[NSURL alloc] initWithString:@"http://allseeing-i.com/ASIHTTPRequest/tests/set_cookie"] autorelease];
  714. ASIHTTPRequest *request = [[[ASIHTTPRequest alloc] initWithURL:url] autorelease];
  715. [request setUseCookiePersistence:YES];
  716. [request startSynchronous];
  717. NSString *html = [request responseString];
  718. success = [html isEqualToString:@"I have set a cookie"];
  719. GHAssertTrue(success,@"Failed to set a cookie");
  720. // Test a cookie is stored in responseCookies
  721. NSArray *cookies = [request responseCookies];
  722. GHAssertNotNil(cookies,@"Failed to store cookie data in responseCookies");
  723. // Test the cookie contains the correct data
  724. NSHTTPCookie *cookie = nil;
  725. BOOL foundCookie = NO;
  726. for (cookie in cookies) {
  727. if ([[cookie name] isEqualToString:@"ASIHTTPRequestTestCookie"]) {
  728. foundCookie = YES;
  729. success = [[cookie value] isEqualToString:@"This+is+the+value"];
  730. GHAssertTrue(success,@"Failed to store the correct value for a cookie");
  731. success = [[cookie domain] isEqualToString:@"allseeing-i.com"];
  732. GHAssertTrue(success,@"Failed to store the correct domain for a cookie");
  733. success = [[cookie path] isEqualToString:@"/ASIHTTPRequest/tests"];
  734. GHAssertTrue(success,@"Failed to store the correct path for a cookie");
  735. break;
  736. }
  737. }
  738. GHAssertTrue(foundCookie,@"Failed store a particular cookie - can't continue with the rest of the tests");
  739. if (!foundCookie) {
  740. return;
  741. }
  742. // Test a cookie is presented when manually added to the request
  743. url = [[[NSURL alloc] initWithString:@"http://allseeing-i.com/ASIHTTPRequest/tests/read_cookie"] autorelease];
  744. request = [[[ASIHTTPRequest alloc] initWithURL:url] autorelease];
  745. [request setUseCookiePersistence:NO];
  746. [request setRequestCookies:[NSMutableArray arrayWithObject:cookie]];
  747. [request startSynchronous];
  748. html = [request responseString];
  749. success = [html isEqualToString:@"I have 'This is the value' as the value of 'ASIHTTPRequestTestCookie'"];
  750. GHAssertTrue(success,@"Cookie not presented to the server with cookie persistence OFF");
  751. // Test a cookie is presented from the persistent store
  752. url = [[[NSURL alloc] initWithString:@"http://allseeing-i.com/ASIHTTPRequest/tests/read_cookie"] autorelease];
  753. request = [[[ASIHTTPRequest alloc] initWithURL:url] autorelease];
  754. [request setUseCookiePersistence:YES];
  755. [request startSynchronous];
  756. html = [request responseString];
  757. success = [html isEqualToString:@"I have 'This is the value' as the value of 'ASIHTTPRequestTestCookie'"];
  758. GHAssertTrue(success,@"Cookie not presented to the server with cookie persistence ON");
  759. // Test removing a cookie
  760. url = [[[NSURL alloc] initWithString:@"http://allseeing-i.com/ASIHTTPRequest/tests/remove_cookie"] autorelease];
  761. request = [[[ASIHTTPRequest alloc] initWithURL:url] autorelease];
  762. [request startSynchronous];
  763. html = [request responseString];
  764. success = [html isEqualToString:@"I have removed a cookie"];
  765. GHAssertTrue(success,@"Failed to remove a cookie");
  766. // Test making sure cookie was properly removed
  767. url = [[[NSURL alloc] initWithString:@"http://allseeing-i.com/ASIHTTPRequest/tests/read_cookie"] autorelease];
  768. request = [[[ASIHTTPRequest alloc] initWithURL:url] autorelease];
  769. [request startSynchronous];
  770. html = [request responseString];
  771. success = [html isEqualToString:@"No cookie exists"];
  772. GHAssertTrue(success,@"Cookie presented to the server when it should have been removed");
  773. // Test setting a custom cookie works
  774. NSDictionary *cookieProperties = [[[NSMutableDictionary alloc] init] autorelease];
  775. // We'll add a line break to our cookie value to test it gets correctly encoded
  776. [cookieProperties setValue:@"Test%0D%0AValue" forKey:NSHTTPCookieValue];
  777. [cookieProperties setValue:@"ASIHTTPRequestTestCookie" forKey:NSHTTPCookieName];
  778. [cookieProperties setValue:@"allseeing-i.com" forKey:NSHTTPCookieDomain];
  779. [cookieProperties setValue:[NSDate dateWithTimeIntervalSinceNow:60*60*4] forKey:NSHTTPCookieExpires];
  780. [cookieProperties setValue:@"/ASIHTTPRequest/tests" forKey:NSHTTPCookiePath];
  781. cookie = [[[NSHTTPCookie alloc] initWithProperties:cookieProperties] autorelease];
  782. GHAssertNotNil(cookie,@"Failed to create a cookie - cookie value was not correctly encoded?");
  783. url = [[[NSURL alloc] initWithString:@"http://allseeing-i.com/ASIHTTPRequest/tests/read_cookie"] autorelease];
  784. request = [[[ASIHTTPRequest alloc] initWithURL:url] autorelease];
  785. [request setUseCookiePersistence:NO];
  786. [request setRequestCookies:[NSMutableArray arrayWithObject:cookie]];
  787. [request startSynchronous];
  788. html = [request responseString];
  789. success = [html isEqualToString:@"I have 'Test\r\nValue' as the value of 'ASIHTTPRequestTestCookie'"];
  790. GHAssertTrue(success,@"Custom cookie not presented to the server with cookie persistence OFF");
  791. // Test removing all cookies works
  792. [ASIHTTPRequest clearSession];
  793. NSArray *sessionCookies = [ASIHTTPRequest sessionCookies];
  794. success = ([sessionCookies count] == 0);
  795. GHAssertTrue(success,@"Cookies not removed");
  796. url = [[[NSURL alloc] initWithString:@"http://allseeing-i.com/ASIHTTPRequest/tests/read_cookie"] autorelease];
  797. request = [[[ASIHTTPRequest alloc] initWithURL:url] autorelease];
  798. [request setUseCookiePersistence:YES];
  799. [request startSynchronous];
  800. html = [request responseString];
  801. success = [html isEqualToString:@"No cookie exists"];
  802. GHAssertTrue(success,@"Cookie presented to the server when it should have been removed");
  803. // Test fetching cookies for a relative url - fixes a problem where urls created with URLWithString:relativeToURL: wouldn't always read cookies from the persistent store
  804. [ASIHTTPRequest clearSession];
  805. url = [[[NSURL alloc] initWithString:@"http://allseeing-i.com/ASIHTTPRequest/tests/set_cookie"] autorelease];
  806. request = [[[ASIHTTPRequest alloc] initWithURL:url] autorelease];
  807. [request setUseCookiePersistence:YES];
  808. [request setUseSessionPersistence:NO];
  809. [request startSynchronous];
  810. NSURL *originalURL = [NSURL URLWithString:@"http://allseeing-i.com/ASIHTTPRequest/tests/"];
  811. url = [NSURL URLWithString:@"read_cookie" relativeToURL:originalURL];
  812. request = [[[ASIHTTPRequest alloc] initWithURL:url] autorelease];
  813. [request setUseCookiePersistence:YES];
  814. [request setUseSessionPersistence:NO];
  815. [request startSynchronous];
  816. html = [request responseString];
  817. NSLog(@"%@",html);
  818. success = [html isEqualToString:@"I have 'This is the value' as the value of 'ASIHTTPRequestTestCookie'"];
  819. GHAssertTrue(success,@"Custom cookie not presented to the server with cookie persistence OFF");
  820. }
  821. // Test fix for a crash if you tried to remove credentials that didn't exist
  822. - (void)testRemoveCredentialsFromKeychain
  823. {
  824. [ASIHTTPRequest removeCredentialsForHost:@"apple.com" port:0 protocol:@"http" realm:@"Nothing to see here"];
  825. [ASIHTTPRequest removeCredentialsForProxy:@"apple.com" port:0 realm:@"Nothing to see here"];
  826. }
  827. - (void)testPreserveResponseWhenDownloadComplete
  828. {
  829. NSURL *url = [NSURL URLWithString:@"http://allseeing-i.com/ASIHTTPRequest/tests/basic-authentication"];
  830. ASIHTTPRequest *request;
  831. BOOL success;
  832. request = [ASIHTTPRequest requestWithURL:url];
  833. [request startSynchronous];
  834. success = ([[request responseString] length]);
  835. GHAssertTrue(success,@"Request removed the response body when we encountered an error, even though the download was complete");
  836. NSString *downloadPath = [[self filePathForTemporaryTestFiles] stringByAppendingPathComponent:@"test.txt"];
  837. if ([[NSFileManager defaultManager] fileExistsAtPath:downloadPath]) {
  838. [[NSFileManager defaultManager] removeItemAtPath:downloadPath error:NULL];
  839. }
  840. request = [ASIHTTPRequest requestWithURL:url];
  841. [request setDownloadDestinationPath:downloadPath];
  842. [request startSynchronous];
  843. success = ([[[NSFileManager defaultManager] attributesOfItemAtPath:downloadPath error:NULL] fileSize]);
  844. GHAssertTrue(success,@"Request removed or failed to copy the response to downloadDestinationPath");
  845. }
  846. - (void)testBasicAuthentication
  847. {
  848. [ASIHTTPRequest removeCredentialsForHost:@"allseeing-i.com" port:0 protocol:@"http" realm:@"SECRET_STUFF"];
  849. [ASIHTTPRequest clearSession];
  850. NSURL *url = [NSURL URLWithString:@"http://allseeing-i.com/ASIHTTPRequest/tests/basic-authentication"];
  851. ASIHTTPRequest *request;
  852. BOOL success;
  853. NSError *err;
  854. // Test authentication needed when no credentials supplied
  855. request = [[[ASIHTTPRequest alloc] initWithURL:url] autorelease];
  856. [request setUseKeychainPersistence:NO];
  857. [request startSynchronous];
  858. success = [[request error] code] == ASIAuthenticationErrorType;
  859. GHAssertTrue(success,@"Failed to generate permission denied error with no credentials");
  860. // Test wrong credentials supplied
  861. request = [[[ASIHTTPRequest alloc] initWithURL:url] autorelease];
  862. [request setUseKeychainPersistence:NO];
  863. [request setUsername:@"wrong"];
  864. [request setPassword:@"wrong"];
  865. [request startSynchronous];
  866. success = [[request error] code] == ASIAuthenticationErrorType;
  867. GHAssertTrue(success,@"Failed to generate permission denied error with wrong credentials");
  868. // Test correct credentials supplied
  869. request = [[[ASIHTTPRequest alloc] initWithURL:url] autorelease];
  870. [request setUseSessionPersistence:YES];
  871. [request setUseKeychainPersistence:YES];
  872. [request setShouldPresentCredentialsBeforeChallenge:NO];
  873. [request setUsername:@"secret_username"];
  874. [request setPassword:@"secret_password"];
  875. [request startSynchronous];
  876. err = [request error];
  877. GHAssertNil(err,@"Failed to supply correct username and password");
  878. // Ensure credentials are not reused
  879. request = [[[ASIHTTPRequest alloc] initWithURL:url] autorelease];
  880. [request setUseSessionPersistence:NO];
  881. [request setUseKeychainPersistence:NO];
  882. [request startSynchronous];
  883. success = [[request error] code] == ASIAuthenticationErrorType;
  884. GHAssertTrue(success,@"Reused credentials when we shouldn't have");
  885. // Ensure credentials stored in the session are reused
  886. request = [[[ASIHTTPRequest alloc] initWithURL:url] autorelease];
  887. [request setUseSessionPersistence:YES];
  888. [request setUseKeychainPersistence:NO];
  889. [request startSynchronous];
  890. err = [request error];
  891. GHAssertNil(err,@"Failed to reuse credentials");
  892. // Ensure new credentials are used in place of those in the session
  893. request = [[[ASIHTTPRequest alloc] initWithURL:[NSURL URLWithString:@"http://allseeing-i.com/ASIHTTPRequest/tests/basic-authentication-new-credentials"]] autorelease];
  894. [request setUsername:@"secret_username_2"];
  895. [request setPassword:@"secret_password_2"];
  896. [request setUseSessionPersistence:YES];
  897. [request setUseKeychainPersistence:NO];
  898. [request startSynchronous];
  899. err = [request error];
  900. GHAssertNil(err,@"Failed to reuse credentials");
  901. [ASIHTTPRequest clearSession];
  902. // Ensure credentials stored in the session were wiped
  903. request = [[[ASIHTTPRequest alloc] initWithURL:url] autorelease];
  904. [request setUseKeychainPersistence:NO];
  905. [request startSynchronous];
  906. success = [[request error] code] == ASIAuthenticationErrorType;
  907. GHAssertTrue(success,@"Failed to clear credentials");
  908. // Ensure credentials stored in the keychain are reused
  909. request = [[[ASIHTTPRequest alloc] initWithURL:url] autorelease];
  910. [request setUseKeychainPersistence:YES];
  911. [request startSynchronous];
  912. err = [request error];
  913. GHAssertNil(err,@"Failed to use stored credentials");
  914. [ASIHTTPRequest removeCredentialsForHost:@"allseeing-i.com" port:0 protocol:@"http" realm:@"SECRET_STUFF"];
  915. // Ensure credentials stored in the keychain were wiped
  916. request = [[[ASIHTTPRequest alloc] initWithURL:url] autorelease];
  917. [request setUseKeychainPersistence:YES];
  918. [request setUseSessionPersistence:NO];
  919. [request startSynchronous];
  920. success = [[request error] code] == ASIAuthenticationErrorType;
  921. GHAssertTrue(success,@"Failed to clear credentials");
  922. // Tests shouldPresentCredentialsBeforeChallenge with credentials stored in the session
  923. request = [[[ASIHTTPRequest alloc] initWithURL:url] autorelease];
  924. [request