1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751
|
/*
* Author: Sergei Golovin <svgdev@mail.ru>
*/
#import "NSURLConnectionTest.h"
/* the runloop's time slice */
#define TIMING 0.1
/* the max duration of a test */
#define MAXDURATION 5.0
@interface NSURLConnectionTest (Private)
/**
* The method tries to guess the request which the test case should make.
* It recognizes as an argument an NSDictionary with custom variable parts
* of connecting process (see the class's description). It also can be supplied
* with the exact request which must be made during test execution.
* The result of the method is stored in the ivar _request.
*/
- (void)_makeRequest:(id)extra;
/**
* The method analyzes the ivar _request and tries to guess the execution path
* inferring from it the reference flag set. If there is a deviation from the guessed
* execution path the caller can supply NSDictionary as the argument 'extra' with
* the key 'ReferenceFlags' is set to have a custom NSDictionary as a value explicitly
* setting the particular flags (see the class's description).
*/
- (void)_makeReferenceFlags:(id)extra;
@end /* NSURLConnectionTest (Private) */
@implementation NSURLConnectionTest
+ (Class) testWebServerClass
{
return [TestWebServer class];
}
/* The flag map connects flags's string names with flags... used to log actions */
static NSMapTable *_flagMap = nil;
+ (void)initialize
{
if (nil == _flagMap)
{
_flagMap = NSCreateMapTable(NSObjectMapKeyCallBacks,
NSIntegerMapValueCallBacks,
0);
NSMapInsert(_flagMap, @"SENTREQUEST", (void *)1);
NSMapInsert(_flagMap, @"AUTHORIZED", (void *)2);
NSMapInsert(_flagMap, @"NOTAUTHORIZED", (void *)4);
NSMapInsert(_flagMap, @"GOTUNAUTHORIZED", (void *)8);
NSMapInsert(_flagMap, @"GOTREQUEST", (void *)16);
NSMapInsert(_flagMap, @"SENTRESPONSE", (void *)32);
NSMapInsert(_flagMap, @"GOTRESPONSE", (void *)64);
NSMapInsert(_flagMap, @"GOTCONTENT", (void *)128);
NSMapInsert(_flagMap, @"GOTFINISH", (void *)256);
NSMapInsert(_flagMap, @"GOTFAIL", (void *)512);
NSMapInsert(_flagMap, @"GOTREDIRECT", (void *)1024);
}
}
- (id)init
{
if ((self = [super init]) != nil)
{
_conn = nil;
_error = nil;
_server = nil;
_auxServer = nil;
_received = nil;
_request = nil;
_redirectRequest = nil;
_expectedStatusCode = 204;
_expectedContent = nil;
}
return self;
}
// super's -[dealloc] calls the -[tearDownTest:]
// so place clearing there
- (void)setUpTest:(id)extra
{
[super setUpTest: extra];
[self _makeRequest: extra];
[self _makeReferenceFlags: extra];
_received = [NSMutableData new];
}
- (void)startTest:(id)extra
{
CREATE_AUTORELEASE_POOL(arp);
NSTimeInterval duration = 0.0;
if (YES == _debug)
{
NSLog(@"%@: started with request:\n%@", self, _request);
[self logFlags];
NSMutableSet *s = [[NSProcessInfo processInfo] debugSet];
[s addObject: @"NSURLConnection"];
[s addObject: @"NSURLProtocol"];
[s addObject: @"NSStream"];
[s addObject: @"NSRunLoop"];
}
_conn = [[NSURLConnection alloc] initWithRequest: _request
delegate: self];
while (!_done && !_failed)
{
[[NSRunLoop currentRunLoop]
runUntilDate: [NSDate dateWithTimeIntervalSinceNow: TIMING]];
duration += TIMING;
if (duration >= MAXDURATION)
{
_failed = YES;
}
}
if (YES == _debug)
{
NSLog(@"%@: stopped with request:\n%@", self, _request);
[self logFlags];
}
DESTROY(arp);
}
- (void)tearDownTest:(id)extra
{
BOOL isToStop = YES; // whether to stop the main TestWebServer instance
BOOL isToStopAux = YES; // whether to stop the auxilliary TestWebServer instance
if ([_extra isKindOfClass: [NSDictionary class]])
{
NSDictionary *d = _extra;
isToStop = ([d objectForKey: @"Instance"] == nil);
isToStopAux = ([d objectForKey: @"AuxInstance"] == nil &&
[[d objectForKey: @"IsAuxilliary"] isEqualToString: @"YES"]);
}
if (isToStop)
{
if (nil != _server)
{
[_server stop];
}
}
if (isToStopAux)
{
if (nil != _auxServer)
{
[_auxServer stop];
}
}
DESTROY(_server);
DESTROY(_auxServer);
DESTROY(_received);
DESTROY(_request);
DESTROY(_redirectRequest);
DESTROY(_expectedContent);
DESTROY(_conn);
DESTROY(_error);
[super tearDownTest: extra];
}
- (BOOL)isSuccess
{
BOOL ret = [super isSuccess];
if (!ret)
{
/* log the flags that differ */
NSString *key;
NSUInteger flag;
NSMapEnumerator en = NSEnumerateMapTable(_flagMap);
while (NSNextMapEnumeratorPair(&en, (void **)&key, (void **)&flag))
{
if ([self isReferenceFlagSet: flag] != [self isFlagSet: flag])
{
NSLog(@"ERR: %@", key);
}
}
NSEndMapTableEnumeration(&en);
if (_failed)
{
NSLog(@"FAILED for unknown reason possibly not related to the test (e.g. a timer has expired)");
}
}
return ret;
}
- (void)logFlags
{
NSString *value;
NSString *key;
NSUInteger flag;
NSMapEnumerator en = NSEnumerateMapTable(_flagMap);
while (NSNextMapEnumeratorPair(&en, (void **)&key, (void **)&flag))
{
if ([self isFlagSet: flag])
{
value = @"YES";
}
else
{
value = @"NO";
}
NSLog(@"ACTUAL: %@ -> %@", key, value);
if ([self isReferenceFlagSet: flag])
{
value = @"YES";
}
else
{
value = @"NO";
}
NSLog(@"REFERENCE: %@ -> %@", key, value);
}
NSEndMapTableEnumeration(&en);
}
- (NSError*) error
{
return _error;
}
/* TestWebServerDelegate */
- (void)handler:(id)handler
gotRequest:(GSMimeDocument *)request
with:(TestWebServer *)server
{
NSString *method = [_request HTTPMethod];
NSData *content = [request convertToData];
[self setFlags: SENTREQUEST];
NSDebugLog(@"%@: set SENTREQUEST (-[%@])", self, NSStringFromSelector(_cmd));
// TODO: more comparisons of _request and request
if ([method isEqualToString: @"POST"] ||
[method isEqualToString: @"PUT"])
{
if ([content isEqualToData: [_request HTTPBody]])
{
[self setFlags: GOTREQUEST];
NSDebugLog(@"%@: set GOTREQUEST (-[%@])", self, NSStringFromSelector(_cmd));
}
}
else
{
[self setFlags: GOTREQUEST];
NSDebugLog(@"%@: set GOTREQUEST (-[%@])", self, NSStringFromSelector(_cmd));
}
}
- (void)handler:(id)handler
willSendUnauthorized:(GSMimeDocument *)response
with:(TestWebServer *)server
{
[self setFlags: NOTAUTHORIZED];
NSDebugLog(@"%@: set NOTAUTHORIZED (-[%@])", self, NSStringFromSelector(_cmd));
}
- (void)handler:(id)handler
gotAuthorized:(GSMimeDocument *)request
with:(TestWebServer *)server
{
[self setFlags: AUTHORIZED];
NSDebugLog(@"%@: set AUTHORIZED (-[%@])", self, NSStringFromSelector(_cmd));
}
- (void)handler:(id)handler
willSend:(GSMimeDocument *)response
with:(TestWebServer *)server
{
[self setFlags: SENTRESPONSE];
NSDebugLog(@"%@: set SENTRESPONSE (-[%@])", self, NSStringFromSelector(_cmd));
}
- (void)timeoutExceededByHandler:(id)handler
{
_failed = YES;
}
/* end of TestWebServerDelegate */
/* NSURLConnectionDelegate */
- (NSURLRequest *)connection:(NSURLConnection *)connection
willSendRequest:(NSURLRequest *)request
redirectResponse:(NSURLResponse *)redirectResponse
{
if ([redirectResponse isKindOfClass: [NSHTTPURLResponse class]])
{
if ([(NSHTTPURLResponse *)redirectResponse statusCode] == _redirectStatusCode)
{
[self setFlags: GOTREDIRECT];
NSDebugLog(@"%@: set GOTREDIRECT (-[%@])", self, NSStringFromSelector(_cmd));
}
}
else
{
[self setFlags: GOTREDIRECT];
NSDebugLog(@"%@: set GOTREDIRECT (-[%@])", self, NSStringFromSelector(_cmd));
}
return _redirectRequest;
}
- (void)connection:(NSURLConnection *)connection
didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
[self setFlags: GOTUNAUTHORIZED];
NSDebugLog(@"%@: set GOTUNAUTHORIZED (-[%@])", self, NSStringFromSelector(_cmd));
if ([challenge previousFailureCount] == 0)
{
NSURLCredential *cred;
// TODO: _auxServer?
NSString *login = [_server login];
NSString *password = [_server password];
if (nil == login)
{
if ([_extra isKindOfClass: [NSDictionary class]])
{
login = [(NSDictionary *)_extra objectForKey: @"Login"];
}
}
if (nil == password)
{
if ([_extra isKindOfClass: [NSDictionary class]])
{
password = [(NSDictionary *)_extra objectForKey: @"Password"];
}
}
cred = [NSURLCredential credentialWithUser: login
password: password
persistence: NSURLCredentialPersistenceNone];
[[challenge sender] useCredential: cred
forAuthenticationChallenge: challenge];
}
else
{
[[challenge sender] cancelAuthenticationChallenge: challenge];
}
}
- (void)connection:(NSURLConnection *)connection
didReceiveResponse:(NSURLResponse *)response
{
if (YES == _debug)
{
if ([response isKindOfClass: [NSHTTPURLResponse class]])
{
NSLog(@"%@: received response (-[%@]):\nStatus Code: %i",
self, NSStringFromSelector(_cmd),
(int)[(NSHTTPURLResponse *)response statusCode]);
}
}
if ([response isKindOfClass: [NSHTTPURLResponse class]])
{
if ([(NSHTTPURLResponse *)response statusCode] == _expectedStatusCode)
{
[self setFlags: GOTRESPONSE];
NSDebugLog(@"%@: set GOTRESPONSE (-[%@])", self, NSStringFromSelector(_cmd));
}
}
else
{
[self setFlags: GOTRESPONSE];
NSDebugLog(@"%@: set GOTRESPONSE (-[%@])", self, NSStringFromSelector(_cmd));
}
}
- (void)connection:(NSURLConnection *)connection
didReceiveData:(NSData *)data
{
[_received appendData: data];
NSDebugLog(@"%@: received data '%@' (-[%@])", self, data, NSStringFromSelector(_cmd));
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
if (nil != _expectedContent &&
[_received isEqualToData: _expectedContent])
{
[self setFlags: GOTCONTENT];
NSDebugLog(@"%@: set GOTCONTENT (-[%@])", self, NSStringFromSelector(_cmd));
}
[self setFlags: GOTFINISH];
NSDebugLog(@"%@: set GOTFINISH (-[%@])", self, NSStringFromSelector(_cmd));
_done = YES;
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
ASSIGN(_error, error);
/* if ((nil != _expectedContent &&
[_received isEqualToData: _expectedContent]) ||
(nil == _expectedContent && [_received length] == 0))
{
[self setFlags: GOTCONTENT];
}
*/
[self setFlags: GOTFAIL];
NSDebugLog(@"%@: set GOTFAIL (-[%@])", self, NSStringFromSelector(_cmd));
NSDebugLog(@"%@: error %@", self, error);
_done = YES;
}
/* end of NSURLConnectionDelegate */
@end /* NSURLConnectionTest */
@implementation NSURLConnectionTest (Private)
- (void)_makeRequest:(id)extra
{
BOOL isOwnServer = YES;
BOOL isOwnAuxServer = NO;
NSString *tmp;
BOOL isDetached = NO;
TestWebServer *instance = nil;
TestWebServer *auxInstance = nil;
NSString *protocol = nil;
NSString *address = nil;
NSString *auxPort = nil;
NSString *port = nil;
// NSString *login = nil;
// NSString *password = nil;
NSString *path = nil;
NSString *redirectPath = nil;
NSString *statusCode = nil;
NSString *redirectCode = nil;
NSString *method = nil;
id payload = nil;
id content = nil;
NSURL *url;
NSDictionary *d = nil;
if ([extra isKindOfClass: [NSDictionary class]])
{
d = extra;
instance = [d objectForKey: @"Instance"];
if (nil != instance)
{
NSString *value;
protocol = [instance isSecure] ? @"https" : @"http";
if ((value = [d objectForKey: @"Protocol"]) == nil ||
![[value lowercaseString] isEqualToString: protocol])
{
d = [d mutableCopy];
[(NSMutableDictionary *)d setObject: protocol forKey: @"Protocol"];
AUTORELEASE(d);
}
address = [instance address];
port = [instance port];
ASSIGN(_server, instance);
[_server setDelegate: self];
[_server setDebug: _debug];
isOwnServer = NO;
}
else
{
protocol = [[d objectForKey: @"Protocol"] lowercaseString];
address = [d objectForKey: @"Address"];
port = [d objectForKey: @"Port"];
}
auxInstance = [d objectForKey: @"AuxInstance"];
if (nil != auxInstance)
{
auxPort = [auxInstance port];
ASSIGN(_auxServer, auxInstance);
[_auxServer setDelegate: self];
[_auxServer setDebug: _debug];
isOwnAuxServer = NO;
}
if (isOwnServer)
{
if ((tmp = [d objectForKey: @"IsDetached"]) != nil)
{
if ([tmp isEqualToString: @"YES"])
{
isDetached = YES;
}
else
{
isDetached = NO;
}
}
}
isOwnAuxServer
= [[d objectForKey: @"IsAuxilliary"] isEqualToString: @"YES"]
&& nil == _auxServer;
if (isOwnAuxServer)
{
auxPort = [d objectForKey: @"AuxPort"];
}
path = [d objectForKey: @"Path"];
if (isOwnAuxServer || nil != _auxServer)
{
redirectPath = [d objectForKey: @"RedirectPath"];
}
statusCode = [d objectForKey: @"StatusCode"];
// TODO: conditions?
redirectCode = [d objectForKey: @"RedirectCode"];
method = [d objectForKey: @"Method"];
payload = [d objectForKey: @"Payload"];
content = [d objectForKey: @"Content"];
} // Is extra NSDictionary?
else if ([extra isKindOfClass: [NSURLRequest class]])
{
ASSIGN(_request, extra);
}
if (nil == _request)
{
if (nil == protocol)
{
protocol = @"http";
}
if (nil == address)
{
address = @"localhost";
}
if (nil == port)
{
port = @"1234";
}
if (nil == auxPort)
{
auxPort = @"1235";
}
if (nil == path)
{
path = @"/";
}
if ((isOwnAuxServer || nil != _auxServer) && nil == redirectPath)
{
redirectPath = path;
}
if (nil != redirectPath && nil == redirectCode)
{
_redirectStatusCode = 301;
}
if (nil == statusCode)
{
_expectedStatusCode = 204;
}
else
{
_expectedStatusCode = [statusCode intValue];
if (_expectedStatusCode == 0)
{
[NSException raise: NSInvalidArgumentException
format: @"Invalid expected 'StatusCode' supplied %@",
statusCode];
}
}
if (nil == redirectCode)
{
_redirectStatusCode = 301;
}
else
{
_redirectStatusCode = [redirectCode intValue];
if (_redirectStatusCode == 0)
{
[NSException raise: NSInvalidArgumentException
format: @"Invalid expected 'RedirectCode' supplied %@",
redirectCode];
}
}
if (nil == method)
{
method = @"GET";
}
if (![path hasPrefix: @"/"])
{
// path MUST begin with '/'
path = [@"/" stringByAppendingString: path];
}
if (![redirectPath hasPrefix: @"/"])
{
// path MUST begin with '/'
redirectPath = [@"/" stringByAppendingString: redirectPath];
}
url = [NSURL URLWithString:
[NSString stringWithFormat:
@"%@://%@:%@%@", protocol, address, auxPort, redirectPath]];
_redirectRequest = [NSMutableURLRequest requestWithURL: url];
RETAIN(_redirectRequest);
url = [NSURL URLWithString:
[NSString stringWithFormat:
@"%@://%@:%@%@", protocol, address, port, path]];
_request = [NSMutableURLRequest requestWithURL: url];
RETAIN(_request);
[(NSMutableURLRequest *)_request setHTTPMethod: method];
if (nil != payload)
{
if ([payload isKindOfClass: [NSString class]])
{
payload = [payload dataUsingEncoding: NSUTF8StringEncoding];
}
if (![payload isKindOfClass: [NSData class]])
{
[NSException raise: NSInvalidArgumentException
format: @"invalid payload"];
}
[(NSMutableURLRequest *)_request setHTTPBody: payload];
}
if (nil != content)
{
if ([content isKindOfClass: [NSString class]])
{
content = [content dataUsingEncoding: NSUTF8StringEncoding];
}
if (![content isKindOfClass: [NSData class]])
{
[NSException raise: NSInvalidArgumentException
format: @"invalid content"];
}
ASSIGN(_expectedContent, content);
}
if (nil != _expectedContent && nil == statusCode)
{
_expectedStatusCode = 200;
}
}
if (isOwnServer)
{
_server = [[TestWebServer alloc] initWithAddress: address
port: port
mode: isDetached
extra: d];
[_server setDebug: _debug];
[_server setDelegate: self];
[_server start: d];
}
if (isOwnAuxServer)
{
_auxServer = [[TestWebServer alloc] initWithAddress: address
port: auxPort
mode: isDetached
extra: d];
[_auxServer setDebug: _debug];
[_auxServer setDelegate: self];
[_auxServer start: d];
}
}
- (void)_makeReferenceFlags:(id)extra
{
// trying to guess the execution path
// and to infer the reference flag set
if (nil != _request)
{
// default reference set
[self setReferenceFlags: SENTREQUEST];
[self setReferenceFlags: NOTAUTHORIZED];
[self setReferenceFlags: AUTHORIZED];
[self setReferenceFlags: GOTUNAUTHORIZED];
[self setReferenceFlags: GOTREQUEST];
[self setReferenceFlags: SENTRESPONSE];
[self setReferenceFlags: GOTRESPONSE];
if (nil != _expectedContent)
{
[self setReferenceFlags: GOTCONTENT];
}
[self setReferenceFlags: GOTFINISH];
}
else
{
[NSException raise: NSInvalidArgumentException
format: @"no request"];
}
if ([extra isKindOfClass: [NSDictionary class]])
{
// make correction in the reference flag set
NSDictionary *d = extra;
if ((d = [d objectForKey: @"ReferenceFlags"]) != nil)
{
NSEnumerator *en = [d keyEnumerator];
NSString *key;
NSString *value;
SEL sel;
while ((key = [en nextObject]) != nil)
{
value = [d objectForKey: key];
NSString *originalKey = nil;
NSUInteger flag = NORESULTS;
// NSUInteger flag = (NSUInteger)NSMapGet(_flagMap, key);
if (NSMapMember(_flagMap,
key, (void **)&originalKey, (void **)&flag))
{
if ([value isEqualToString: @"YES"])
{
sel = @selector(setReferenceFlags:);
}
else
{
sel = @selector(unsetReferenceFlags:);
}
[self performSelector: sel withObject: (void *)flag];
}
else
{
[NSException raise: NSInternalInconsistencyException
format: @"flag codes corrupted (key %@)", key];
}
}
}
}
}
@end /* NSURLConnectionTest (Private) */
|