Created
August 6, 2012 11:37
-
-
Save finestructure/3273766 to your computer and use it in GitHub Desktop.
Async test for SenTestCase
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// SenTestCase+Async.h | |
// | |
// Created by Sven A. Schmidt on 2012-08-06. | |
// | |
#import <SenTestingKit/SenTestingKit.h> | |
@interface SenTestCase (Async) | |
@property (nonatomic, readonly) dispatch_queue_t serialQueue; | |
- (void)waitWithTimeout:(NSTimeInterval)timeout forSuccessInBlock:(BOOL(^)())block; | |
@end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// SenTestCase+Async.m | |
// | |
// Created by Sven A. Schmidt on 2012-08-06. | |
// | |
#import "SenTestCase+Async.h" | |
@implementation SenTestCase (Async) | |
- (dispatch_queue_t)serialQueue | |
{ | |
static dispatch_queue_t serialQueue; | |
static dispatch_once_t onceToken; | |
dispatch_once(&onceToken, ^{ | |
serialQueue = dispatch_queue_create("SenTestCase.serialQueue", DISPATCH_QUEUE_SERIAL); | |
}); | |
return serialQueue; | |
} | |
// new version based on GHUnit | |
- (void)waitWithTimeout:(NSTimeInterval)timeout forSuccessInBlock:(BOOL(^)())block | |
{ | |
BOOL(^serialBlock)() = ^BOOL{ | |
__block BOOL result; | |
dispatch_sync(self.serialQueue, ^{ | |
result = block(); | |
}); | |
return result; | |
}; | |
NSArray *_runLoopModes = [NSArray arrayWithObjects:NSDefaultRunLoopMode, NSRunLoopCommonModes, nil]; | |
NSTimeInterval checkEveryInterval = 0.2; | |
NSDate *runUntilDate = [NSDate dateWithTimeIntervalSinceNow:timeout]; | |
NSInteger runIndex = 0; | |
while(! serialBlock()) { | |
NSString *mode = [_runLoopModes objectAtIndex:(runIndex++ % [_runLoopModes count])]; | |
@autoreleasepool { | |
if (!mode || ![[NSRunLoop currentRunLoop] runMode:mode beforeDate:[NSDate dateWithTimeIntervalSinceNow:checkEveryInterval]]) { | |
// If there were no run loop sources or timers then we should sleep for the interval | |
[NSThread sleepForTimeInterval:checkEveryInterval]; | |
} | |
} | |
// If current date is after the run until date | |
if ([runUntilDate compare:[NSDate date]] == NSOrderedAscending) { | |
break; | |
} | |
} | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment