我正在尝试向这个SimpleHTTPServer 示例添加一个 GHUnit 测试用例。该示例包括一个对我来说很好的 Cocoa 应用程序。但我无法在测试用例中复制该行为。
这是测试类:
#import <GHUnit/GHUnit.h>
#import "SimpleHTTPServer.h"
@interface ServerTest : GHTestCase
{
SimpleHTTPServer *server;
}
@end
@implementation ServerTest
-(void)setUpClass
{
[[NSRunLoop currentRunLoop] run];
}
- (NSString*)requestToURL:(NSString*)urlString error:(NSError**)error
{
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:1];
NSURLResponse *response = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:error];
NSString *page = nil;
if (error == nil)
{
NSStringEncoding responseEncoding = CFStringConvertEncodingToNSStringEncoding(CFStringConvertIANACharSetNameToEncoding((CFStringRef)[response textEncodingName]));
page = [[NSString alloc] initWithData:data encoding:responseEncoding];
[page autorelease];
}
return page;
}
- (void)testPortReuse
{
unsigned int port = 50001;
NSError *error = nil;
NSString *path, *url;
server = [[SimpleHTTPServer alloc] initWithTCPPort:port delegate:self];
sleep(10);
path = @"/x/y/z";
url = [NSString stringWithFormat:@"http://localhost:%u%@", port, path];
[self requestToURL:url error:&error];
GHAssertNil(error, @"%@ : %@", url, error);
[server release];
}
- (void)processURL:(NSURL *)path connection:(SimpleHTTPConnection *)connection
{
NSLog(@"processURL");
}
- (void)stopProcessing
{
NSLog(@"stopProcessing");
}
@end
我尝试通过 NSURLRequest 以及(在 期间sleep
)通过网络浏览器发送请求。委托方法-processURL
和-stopProcessing
永远不会被调用。问题似乎是[fileHandle acceptConnectionInBackgroundAndNotify]
SimpleHTTPServer-initWithTCPPort:delegate:
没有导致任何 NSFileHandleConnectionAcceptedNotifications 到达 NSNotificationCenter - 所以我怀疑涉及运行循环的问题。
问题似乎出在 NSFileHandle 上,而不是 NSNotificationCenter 上,因为当[nc postNotificationName:NSFileHandleConnectionAcceptedNotification object:nil]
添加到 的末尾时initWithTCPPort:delegate:
,NSNotificationCenter 确实会收到通知。