Skip to content

Instantly share code, notes, and snippets.

@finestructure
Created August 6, 2012 11:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save finestructure/3273766 to your computer and use it in GitHub Desktop.
Save finestructure/3273766 to your computer and use it in GitHub Desktop.
Async test for SenTestCase
//
// 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
//
// 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