PageRenderTime 76ms CodeModel.GetById 13ms app.highlight 59ms RepoModel.GetById 1ms app.codeStats 0ms

/Source/externals/GData/Source/HTTPFetcher/Tests/GTMHTTPFetcherCachingTest.m

http://google-email-uploader-mac.googlecode.com/
Objective C | 275 lines | 172 code | 44 blank | 59 comment | 13 complexity | ac585bfd49496ab262a02bf0d7f62d69 MD5 | raw file
  1/* Copyright (c) 2010 Google Inc.
  2 *
  3 * Licensed under the Apache License, Version 2.0 (the "License");
  4 * you may not use this file except in compliance with the License.
  5 * You may obtain a copy of the License at
  6 *
  7 *     http://www.apache.org/licenses/LICENSE-2.0
  8 *
  9 * Unless required by applicable law or agreed to in writing, software
 10 * distributed under the License is distributed on an "AS IS" BASIS,
 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 12 * See the License for the specific language governing permissions and
 13 * limitations under the License.
 14 */
 15
 16//
 17//  GTMHTTPFetcherCachingTest.m
 18//
 19
 20#import <XCTest/XCTest.h>
 21
 22#import "GTMHTTPFetcher.h"
 23
 24// copies of interfaces to private fetch history classes
 25@interface GTMCachedURLResponse : NSObject
 26- (id)initWithResponse:(NSURLResponse *)response data:(NSData *)data;
 27- (NSURLResponse *)response;
 28- (NSData *)data;
 29- (NSDate *)useDate;
 30- (void)setUseDate:(NSDate *)date;
 31- (NSDate *)reservationDate;
 32- (void)setReservationDate:(NSDate *)date;
 33@end
 34
 35@interface GTMURLCache : NSObject
 36- (id)initWithMemoryCapacity:(NSUInteger)totalBytes;
 37- (GTMCachedURLResponse *)cachedResponseForRequest:(NSURLRequest *)request;
 38- (void)storeCachedResponse:(GTMCachedURLResponse *)cachedResponse forRequest:(NSURLRequest *)request;
 39- (void)removeCachedResponseForRequest:(NSURLRequest *)request;
 40- (void)removeAllCachedResponses;
 41- (NSUInteger)memoryCapacity;
 42- (void)setMemoryCapacity:(NSUInteger)totalBytes;
 43- (NSDictionary *)responses;
 44- (NSUInteger)totalDataSize;
 45- (void)setReservationInterval:(NSTimeInterval)secs;
 46@end
 47
 48@interface GTMCookieStorage : NSObject
 49- (void)setCookies:(NSArray *)newCookies;
 50- (NSArray *)cookiesForURL:(NSURL *)theURL;
 51- (NSHTTPCookie *)cookieMatchingCookie:(NSHTTPCookie *)cookie;
 52- (void)removeExpiredCookies;
 53- (void)removeAllCookies;
 54@end
 55
 56@interface GTMHTTPFetcherCachingTest : XCTestCase
 57@end
 58
 59@implementation GTMHTTPFetcherCachingTest
 60
 61- (void)testURLCache {
 62  // allocate a cache that prunes at 30 bytes of response data
 63  NSUInteger cacheCapacity = 30;
 64  GTMURLCache *cache = [[[GTMURLCache alloc] initWithMemoryCapacity:cacheCapacity] autorelease];
 65
 66  // set the reservation interval for our cache to something quick
 67  const NSTimeInterval resInterval = 0.1;
 68  [cache setReservationInterval:resInterval];
 69
 70  // allocate 6 responses with 10 bytes of data each; put a reservation on just
 71  // the second of the 6
 72  NSMutableArray *requests = [NSMutableArray array];
 73  NSMutableArray *cachedResponses = [NSMutableArray array];
 74
 75  for (int idx = 0; idx < 6; idx++) {
 76    NSString *urlStr = [NSString stringWithFormat:@"http://example.com/%d", idx];
 77    NSURL *url = [NSURL URLWithString:urlStr];
 78    NSURLRequest *request = [NSURLRequest requestWithURL:url];
 79    [requests addObject:request];
 80
 81    NSURLResponse *response;
 82    response = [[[NSURLResponse alloc] initWithURL:url
 83                                          MIMEType:@"text/xml"
 84                             expectedContentLength:-1
 85                                  textEncodingName:nil] autorelease];
 86
 87    GTMCachedURLResponse *cachedResponse;
 88    NSData *data = [@"1234567890" dataUsingEncoding:NSUTF8StringEncoding];
 89    XCTAssertEqual([data length], (NSUInteger) 10, @"data should be 10 bytes");
 90
 91    cachedResponse = [[[GTMCachedURLResponse alloc] initWithResponse:response
 92                                                                  data:data] autorelease];
 93    [cachedResponses addObject:cachedResponse];
 94    if (idx == 1) {
 95      [cachedResponse setReservationDate:[NSDate date]];
 96    }
 97
 98    [cache storeCachedResponse:cachedResponse
 99                    forRequest:request];
100  }
101
102  // step through retrieving all previous requests
103  //
104  // the cache should contain the second response (since it's reserved) and the
105  // last two responses
106  for (int idx = 0; idx < 6; idx++) {
107    NSURLRequest *request = [requests objectAtIndex:idx];
108    GTMCachedURLResponse *cachedResponse, *expectedResponse;
109
110    cachedResponse = [cache cachedResponseForRequest:request];
111    if (idx == 1 || idx >= 4) {
112      expectedResponse = [cachedResponses objectAtIndex:idx];
113      XCTAssertEqualObjects(cachedResponse, expectedResponse, @"wrong response");
114    } else {
115      // these should be pruned out
116      XCTAssertNil(cachedResponse, @"unexpected response present");
117    }
118  }
119
120  // wait for the reservation to expire
121  [NSThread sleepForTimeInterval:(2 * resInterval)];
122
123  // re-store the first response, with its date set to now; the
124  // previously-reserved response should be oldest and thus pruned out
125  NSURLRequest *firstRequest = [requests objectAtIndex:0];
126  GTMCachedURLResponse *firstResponse = [cachedResponses objectAtIndex:0];
127  [firstResponse setUseDate:[NSDate date]];
128
129  [cache storeCachedResponse:firstResponse
130                  forRequest:firstRequest];
131
132  // again, step through retrieving all previous requests
133  //
134  // now the cache should contain the first response and the last two responses
135  for (int idx = 0; idx < 6; idx++) {
136    NSURLRequest *request = [requests objectAtIndex:idx];
137    GTMCachedURLResponse *cachedResponse, *expectedResponse;
138
139    cachedResponse = [cache cachedResponseForRequest:request];
140    if (idx == 0 || idx >= 4) {
141      expectedResponse = [cachedResponses objectAtIndex:idx];
142      XCTAssertEqualObjects(cachedResponse, expectedResponse, @"wrong response");
143    } else {
144      // these should be aged out
145      XCTAssertNil(cachedResponse, @"unexpected response present");
146    }
147  }
148
149  // create a response too big to fit in the cache, and verify that it wasn't
150  NSString *hugeUrlStr = [NSString stringWithFormat:@"http://example.com/huge"];
151  NSURL *hugeURL = [NSURL URLWithString:hugeUrlStr];
152  NSURLRequest *hugeRequest = [NSURLRequest requestWithURL:hugeURL];
153
154  NSURLResponse *response;
155  response = [[[NSURLResponse alloc] initWithURL:hugeURL
156                                        MIMEType:@"text/xml"
157                           expectedContentLength:-1
158                                textEncodingName:nil] autorelease];
159
160  NSMutableData *hugeData = [NSMutableData data];
161  [hugeData setLength:cacheCapacity];
162  GTMCachedURLResponse *hugeResponse;
163  hugeResponse = [[[GTMCachedURLResponse alloc] initWithResponse:response
164                                                              data:hugeData] autorelease];
165  [cache storeCachedResponse:hugeResponse
166                  forRequest:hugeRequest];
167
168  // verify that the response wasn't really stored in the cache
169  XCTAssertEqual([[cache responses] count], (NSUInteger)3,
170                 @"huge not ignored");
171  GTMCachedURLResponse *foundResponse;
172  foundResponse = [cache cachedResponseForRequest:hugeRequest];
173  XCTAssertNil(foundResponse, @"huge was cached");
174
175  // make the huge response size just right for pushing everything else out of
176  // the cache
177  [hugeData setLength:(cacheCapacity - 1)];
178  hugeResponse = [[[GTMCachedURLResponse alloc] initWithResponse:response
179                                                              data:hugeData] autorelease];
180  [cache storeCachedResponse:hugeResponse
181                  forRequest:hugeRequest];
182
183  // verify that it crowded out the other responses
184  XCTAssertEqual([[cache responses] count], (NSUInteger)1,
185                 @"huge didn't fill the cache");
186  foundResponse = [cache cachedResponseForRequest:hugeRequest];
187  XCTAssertNotNil(foundResponse, @"huge was not cached");
188}
189
190- (void)testCookieStorage {
191  GTMCookieStorage *cookieStorage = [[[GTMCookieStorage alloc] init] autorelease];
192  NSArray *foundCookies;
193
194  NSURL *fullURL = [NSURL URLWithString:@"http://photos.example.com"];
195  NSURL *subdomainURL = [NSURL URLWithString:@"http://frogbreath.example.com"];
196
197  foundCookies = [cookieStorage cookiesForURL:fullURL];
198  XCTAssertEqual([foundCookies count], (NSUInteger) 0, @"no cookies expected");
199
200  // make two unique cookies
201  NSDictionary *cookie1Props = [NSDictionary dictionaryWithObjectsAndKeys:
202                               @"TRUE", NSHTTPCookieDiscard,
203                               @"photos.example.com", NSHTTPCookieDomain,
204                               @"Snark", NSHTTPCookieName,
205                               @"/", NSHTTPCookiePath,
206                               @"cook1=foo", NSHTTPCookieValue, nil];
207  NSHTTPCookie *testCookie1 = [NSHTTPCookie cookieWithProperties:cookie1Props];
208
209  NSDictionary *cookie2Props = [NSDictionary dictionaryWithObjectsAndKeys:
210                                @"FALSE", NSHTTPCookieDiscard,
211                                @".example.com", NSHTTPCookieDomain,
212                                @"Trump", NSHTTPCookieName,
213                                @"/", NSHTTPCookiePath,
214                                @"cook2=gnu", NSHTTPCookieValue, nil];
215  NSHTTPCookie *testCookie2 = [NSHTTPCookie cookieWithProperties:cookie2Props];
216
217  // make a cookie that would replace cookie 2, and make this one expire
218  //
219  // expirations have to be in the future or the cookie won't get stored
220  NSTimeInterval kExpirationInterval = 0.1;
221  NSDate *expiredDate = [NSDate dateWithTimeIntervalSinceNow:kExpirationInterval];
222  NSDictionary *cookie2aProps = [NSDictionary dictionaryWithObjectsAndKeys:
223                                @"FALSE", NSHTTPCookieDiscard,
224                                @".example.com", NSHTTPCookieDomain,
225                                @"Trump", NSHTTPCookieName,
226                                @"/", NSHTTPCookiePath,
227                                expiredDate, NSHTTPCookieExpires,
228                                @"cook2=snu", NSHTTPCookieValue, nil];
229  NSHTTPCookie *testCookie2a = [NSHTTPCookie cookieWithProperties:cookie2aProps];
230
231  // store the first two cookies
232  NSArray *array = [NSArray arrayWithObjects:
233                    testCookie1, testCookie2, nil];
234  [cookieStorage setCookies:array];
235
236  foundCookies = [cookieStorage cookiesForURL:fullURL];
237  XCTAssertEqual([foundCookies count], (NSUInteger) 2,
238                 @"full domain cookie retrieval");
239
240  foundCookies = [cookieStorage cookiesForURL:subdomainURL];
241  XCTAssertEqual((int)[foundCookies count], 1, @"subdomain cookie retrieval");
242
243  // store cookie 2a, replacing cookie 2
244  array = [NSArray arrayWithObject:testCookie2a];
245  [cookieStorage setCookies:array];
246
247  foundCookies = [cookieStorage cookiesForURL:subdomainURL];
248  XCTAssertEqual((int)[foundCookies count], 1, @"subdomain 2a retrieval");
249
250  NSHTTPCookie *foundCookie = [foundCookies lastObject];
251  XCTAssertEqualObjects([foundCookie value], [testCookie2a value],
252                 @"cookie replacement");
253
254  // wait for cookie 2a to expire, then remove expired cookies
255  //
256  // 30-May-2012: Apparently, on Mac OS X 10.7.4, the expiration is no
257  // longer stored, even for version 0 cookies.
258  //
259  //  [NSThread sleepForTimeInterval:(2 * kExpirationInterval)];
260  //  [cookieStorage removeExpiredCookies];
261  //
262  //  foundCookies = [cookieStorage cookiesForURL:subdomainURL];
263  //  STAssertEquals((int)[foundCookies count], 0, @"pruned removal");
264  //
265  //  foundCookies = [cookieStorage cookiesForURL:fullURL];
266  //  STAssertEquals((int)[foundCookies count], 1, @"pruned removal remaining");
267  XCTAssertNil([testCookie2a expiresDate]);
268
269  // remove all cookies
270  [cookieStorage removeAllCookies];
271  foundCookies = [cookieStorage cookiesForURL:fullURL];
272  XCTAssertEqual((int)[foundCookies count], 0, @"remove all");
273}
274
275@end