Unit testing for code like dispatch_async. - testing

Need to do unit testing for the following code, dispatch_async means code won't be executed by app logic sequence, any idea on how to make it run timely?
Thank you.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
[AdTracker dosomething];
});

See http://www.mikeash.com/pyblog/friday-qa-2011-07-22-writing-unit-tests.html
+ (BOOL)waitFor2:(finishBlock)block {
NSTimeInterval timeoutInSeconds = 10.0;
NSDate* giveUpDate = [NSDate dateWithTimeIntervalSinceNow:timeoutInSeconds];
while (!block() && ([giveUpDate timeIntervalSinceNow] > 0)) {
NSDate *stopDate = [NSDate dateWithTimeIntervalSinceNow:1.0];
[[NSRunLoop currentRunLoop] runUntilDate:stopDate]; // un-blocking.
DLog(#"+++++ %#", [NSDate date]);
}
return block();
}

Related

Objective-C Implement a timeout in non-blocking way

I am invoking an external async function that should invoke a callback once it completes.
However since the function is external, I do not control its implementation and I want to set a timeout for 5 seconds as an example and consider the operation of being timed out if the callback passed to that external async function wasn't invoked during those 5 seconds.
And the only way I currently found is to make the current thread sleep that actually blocks the thread.
Here is an example:
+(void)myFuncWithCompletion:(void (^ _Nonnull)(BOOL))completion{
BOOL timedOut = NO;
BOOL __block finishedAsyncCall = NO;
[someObj someAsyncMethod {
// completion callback
finishedAsyncCall = YES;
if (!timedOut) {
completion(YES);
}
}];
// This is the logic I want to fix. My goal is to make something similar but non-blocking.
long timeoutInSeconds = 5;
long startTime = [[NSDate date] timeIntervalSince1970];
long currTime = [[NSDate date] timeIntervalSince1970];
while (!finishedAsyncCall && startTime + timeoutInSeconds > currTime) {
[NSThread sleepForTimeInterval:0];
currTime = [[NSDate date] timeIntervalSince1970];
}
if (!finishedAsyncCall) {
timedOut = YES;
completion(NO);
}
}
You can use dispatch_after instead of -[NSThread sleepForTimeInterval:]
double delayInSeconds = 5.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC)); // 1
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){ // 2
if (!finishedAsyncCall ) {
timedOut = YES;
completion(NO);
}
});

NSTimer Repeats not working for me

Problem, runs once.
-(void)firingLogicForPlayer:(Player *)player {
if (player.playerTargetLock) {
if (!_fireRateTimer) {
_fireCounter = 0;
_fireRateTimer = [NSTimer timerWithTimeInterval:1
target:self
selector:#selector(burstControl:)
userInfo:player.name
repeats:YES];
[_fireRateTimer fire];
BOOL timerState = [_fireRateTimer isValid];
NSLog(#"Timer validity is: %#", timerState?#"YES":#"NO");
}
}
}
-(void)burstControl:(NSTimer *)theTimer {
NSLog(#"burstControl Initiated");
NSString *playerName = (NSString *)[theTimer userInfo];
Player *player = (Player *)[self childNodeWithName:playerName];
if (_fireCounter < 5) {
[self playerBeginFiring:player];
_fireCounter++;
} else {
NSLog(#"this ran to kill timer");
[_fireRateTimer invalidate];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[self firingLogicForPlayer:player];
});
}
}
2015-09-16 13:37:44.964 ***[20592:3367845] burstControl Initiated
2015-09-16 13:37:44.974 ***[20592:3367845] Timer validity is: YES
2015-09-16 13:37:45.147 ***[20592:3367845] hit made
This is what logs, how the logic works is, firingLogic is initialised on a target lock. So the timer should run 5 times before being invalidated because of the _fireCounter counter. timer begins burst control, checks firecounter if firecounter is < 5 it fires a bullet, increases the firecounter. if the firecounter > 5 it invalidates the timer, and dispatches it to run again after 1.5 seconds.
However, the problem is that the timer is only running once. Yet, it's valid after the initial fire. Pretty confused.
You have to add it to the NSRunLoop. Otherwise you can use + (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)seconds target:(id)target selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)repeats
Please check below code
if (!_fireRateTimer) {
_fireCounter = 0;
_fireRateTimer = [NSTimer timerWithTimeInterval:1
target:self
selector:#selector(burstControl:)
userInfo:nil
repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:_fireRateTimer forMode:NSDefaultRunLoopMode];
BOOL timerState = [_fireRateTimer isValid];
NSLog(#"Timer validity is: %#", timerState?#"YES":#"NO");
}
Thanks :)

Different behaviour of asynchronous code in test target and deployment target

While trying to apply TDD to asynchronous code I found out that the same code that was working in the deployment target, didn't work in the test target.
One of the examples of this problems I found using CLLocationManager:
- (void)testReceivingLocation
{
locationManager = [[CLLocationManager alloc] init];
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.delegate = self;
locationManager.pausesLocationUpdatesAutomatically = NO;
if ([CLLocationManager locationServicesEnabled])
{
[locationManager startUpdatingLocation];
}
startLocation = nil;
NSDate *until = [NSDate dateWithTimeIntervalSinceNow:10];
while ([until timeIntervalSinceNow] > 0)
{
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
beforeDate:until];
}
XCTAssert(alreadyReceivedLocation, #"Location wasn't received.");
}
-(void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
alreadyReceivedLocation = true;
// Never actually get there.
}
What can be the problem?
You should elaborate a bit more on how [SomeClass performActionWithAsyncResponse] does its job.
Supposing completionWithResult is called in a block on the main queue, this won't work because the thread ends after the the test method is finished. Which is not the case in production, because the app keeps running.
Usually I use code like this to wait for async calls which calls back on the main queue in tests.
NSDate *until = [NSDate dateWithTimeIntervalSinceNow:30];
while ([loopUntil timeIntervalSinceNow] > 0)
{
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
beforeDate:until];
}
You could also stop the while loop with a condition that indicates if asynchronous work is done, using a property of the test for example.
See this post for more about asynchronous test patterns:
Pattern for unit testing async queue that calls main queue on completion

Stopwatch using NSTimer incorrectly includes paused time in display

This is my code for an iPhone stopwatch. It works as expected and stops and resumes when the buttons are clicked.
When I hit "Stop", however, the timer won't stop running in the background, and when I hit "Start" to resume it, it will update the time and skip to where it is currently instead of resuming from the stopped time.
How can I stop the NSTimer? What is causing this to occur?
#implementation FirstViewController;
#synthesize stopWatchLabel;
NSDate *startDate;
NSTimer *stopWatchTimer;
int touchCount;
-(void)showActivity {
NSDate *currentDate = [NSDate date];
NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:startDate];
NSDate *timerDate = [NSDate dateWithTimeIntervalSince1970:timeInterval];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"mm:ss.SS"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]];
NSString *timeString=[dateFormatter stringFromDate:timerDate];
stopWatchLabel.text = timeString;
[dateFormatter release];
}
- (IBAction)onStartPressed:(id)sender {
stopWatchTimer = [NSTimer scheduledTimerWithTimeInterval:1/10 target:self selector:#selector(showActivity) userInfo:nil repeats:YES];
touchCount += 1;
if (touchCount > 1)
{
[stopWatchTimer fire];
}
else
{
startDate = [[NSDate date]retain];
[stopWatchTimer fire];
}
}
- (IBAction)onStopPressed:(id)sender {
[stopWatchTimer invalidate];
stopWatchTimer = nil;
[self showActivity];
}
- (IBAction)reset:(id)sender; {
touchCount = 0;
stopWatchLabel.text = #"00:00.00";
}
Your calculation of the current display always uses the original start time of the timer, so the display after pausing includes the interval that the timer was paused.
The easiest thing to do would be to store another NSTimeInterval, say secondsAlreadyRun, when the timer is paused, and add that to the time interval you calculate when you resume. You'll want to update the timer's startDate every time the timer starts counting. In reset:, you would also clear out that secondsAlreadyRun interval.
-(void)showActivity:(NSTimer *)tim {
NSDate *currentDate = [NSDate date];
NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:startDate];
// Add the saved interval
timeInterval += secondsAlreadyRun;
NSDate *timerDate = [NSDate dateWithTimeIntervalSince1970:timeInterval];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"mm:ss.SS"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]];
NSString *timeString=[dateFormatter stringFromDate:timerDate];
stopWatchLabel.text = timeString;
[dateFormatter release];
}
- (IBAction)onStartPressed:(id)sender {
stopWatchTimer = [NSTimer scheduledTimerWithTimeInterval:1/10
target:self
selector:#selector(showActivity:)
userInfo:nil
repeats:YES];
// Save the new start date every time
startDate = [[NSDate alloc] init]; // equivalent to [[NSDate date] retain];
[stopWatchTimer fire];
}
- (IBAction)onStopPressed:(id)sender {
// _Increment_ secondsAlreadyRun to allow for multiple pauses and restarts
secondsAlreadyRun += [[NSDate date] timeIntervalSinceDate:startDate];
[stopWatchTimer invalidate];
stopWatchTimer = nil;
[startDate release];
[self showActivity];
}
- (IBAction)reset:(id)sender; {
secondsAlreadyRun = 0;
stopWatchLabel.text = #"00:00.00";
}
Don't forget to release that startDate somewhere appropriate! Also keep in mind that the documented NSTimer interface is for the method you give it to accept one argument, which will be the timer itself. It seems to work without that, but why tempt fate?
Finally, since you're using that NSDateFormatter so much, you might want to consider making it an ivar or put it in static storage in showActivity:, like so:
static NSDateFormatter * dateFormatter = nil;
if( !dateFormatter ){
dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"mm:ss.SS"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]];
}
So, when the user presses stop, and then start again, you aren't resetting the start time. But when you update the label, you are basing that on the total elapsed time from the original start time to the current time.
So if you run the timer for 10 seconds, stop, wait 10 seconds, and then start again, the timer will show 00:20.00 and start counting again from there.
What you want to do is reset the start time each time the user starts the clock, but then add the elapsed times of all previous runs as well. Or something similar.
BTW, you are leaking the start time every time you reset it now. Minor bug.
EDIT: looks like #Josh Caswell was thinking the same thing, but he types a LOT faster. :)
Are you using ARC or not?
If you are using ARC, it looks like you arent using a _strong reference. If you aren't using ARC, it doesn't looking you are retaining a reference to the timer.
I'm posting this from mobile so might be missing something.
EDIT: just noticed you were using release elsewhere, so I'll assume no ARC. You need to retain the timer after setting it to be able to access it later and invalidate.
You can use NSTimeInterval instead of timer. I have a functional code to pause and stop the timer.
#interface PerformBenchmarksViewController () {
int currMinute;
int currSecond;
int currHour;
int mins;
NSDate *startDate;
NSTimeInterval secondsAlreadyRun;
}
#end
- (void)viewDidLoad
{
[super viewDidLoad];
running = false;
}
- (IBAction)StartTimer:(id)sender {
if(running == false) {
//start timer
running = true;
startDate = [[NSDate alloc] init];
startTime = [NSDate timeIntervalSinceReferenceDate];
[sender setTitle:#"Pause" forState:UIControlStateNormal];
[self updateTime];
}
else {
//pause timer
secondsAlreadyRun += [[NSDate date] timeIntervalSinceDate:startDate];
startDate = [[NSDate alloc] init];
[sender setTitle:#"Start" forState:UIControlStateNormal];
running = false;
}
}
- (void)updateTime {
if(running == false) return;
//calculate elapsed time
NSTimeInterval currentTime = [NSDate timeIntervalSinceReferenceDate];
NSTimeInterval elapsed = secondsAlreadyRun + currentTime - startTime;
// extract out the minutes, seconds, and hours of seconds from elapsed time:
int hours = (int)(mins / 60.0);
elapsed -= hours * 60;
mins = (int)(elapsed / 60.0);
elapsed -= mins * 60;
int secs = (int) (elapsed);
//update our lable using the format of 00:00:00
timerLabel.text = [NSString stringWithFormat:#"%02u:%02u:%02u", hours, mins, secs];
//call uptadeTime again after 1 second
[self performSelector:#selector(updateTime) withObject:self afterDelay:1];
}
Hope this will help. Thanks
A timer class I created in Swift for a timer program in which a counter is updated every second from a set time. Answered to illustrate the Swift solution and the NSTimer function.
The timer can be stopped and restarted; it will resume from where it stopped. Events can be intercepted by the delegate for start, stop, reset, end and second events. Just check the code.
import Foundation
protocol TimerDelegate {
func didStart()
func didStop()
func didReset()
func didEnd()
func updateSecond(timeToGo: NSTimeInterval)
}
// Inherit from NSObject to workaround Selector bug
class Timer : NSObject {
var delegate: TimerDelegate?
var defaultDuration: NSTimeInterval?
var isRunning: Bool {
get {
return self.timer != nil && timer!.valid
}
}
private var secondsToGo: NSTimeInterval = 0
private var timer: NSTimer?
init(defaultDuration: NSTimeInterval, delegate: TimerDelegate? = nil) {
self.defaultDuration = defaultDuration
self.delegate = delegate
super.init()
}
func start() {
self.timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "updateTimer", userInfo: nil, repeats: true)
self.timer!.tolerance = 0.05
if delegate != nil { delegate!.didStart() }
}
func stop () {
self.timer?.invalidate()
self.timer = nil
if delegate != nil { delegate!.didStop() }
}
func reset() {
self.secondsToGo = self.defaultDuration!
if delegate != nil { delegate!.didReset() }
}
func updateTimer() {
--self.secondsToGo
if delegate != nil { delegate!.updateSecond(self.secondsToGo) }
if self.secondsToGo == 0 {
self.stop()
if delegate != nil { delegate!.didEnd() }
}
}
}

Comparing dates inside a nstimer selector

I am writing a countdowtimer application like the timer tab in the clock app of the iPhone. Right now I am having trouble comparing to dates, the 'now' and 'futureDate'.
all the variables are synthesized and are nonatomic and retain.
I have this code right now.
- (IBAction)startTimer:(id)sender {
NSLog(#"startTimer");
pickerView.hidden = YES;
labelView.hidden = NO;
now = [[NSDate alloc] init];
futureDate = [[NSDate alloc] initWithTimeInterval:picker.countDownDuration sinceDate:now];
NSLog(#"Dates.\nNow = (%#) \nfutureDate (%#)", now, futureDate);
timerLabelUpdater = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:#selector(labelUpdater) userInfo:nil repeats:YES];
}
- (void)labelUpdater {
if ([now timeIntervalSinceDate:futureDate] < 0.0) {
NSLog(#"YES\nDates.\nNow = (%#) \nfutureDate (%#)", now, futureDate);
} else {
NSLog(#"NO\nNow = (%#) \nfutureDate (%#)", now, futureDate);
}
}
Debugger info:
2011-02-08 16:46:02.449 App[22504:207] startTimer
2011-02-08 16:46:02.451 App[22504:207] Dates.
Now = (2011-02-08 18:46:02 +0000)
futureDate (2011-02-08 18:47:02 +0000)
2011-02-08 16:46:03.451 App[22504:207] YES
And it stay giving me yes "forever".
But if you see the variable hours, they are +2h in the future compared from my clock time. Is this the bug?
Sorry my if was testing the wrong date, comparing the variable now and futureDate the time interval will be the same forever. I replaced the now variable for a [[NSDate alloc] init] in the test. Right now the code works.
if ([[[NSDate alloc]init] timeIntervalSinceDate:futureDate] < 0.0) {
NSLog(#"YES\nDates.\nNow = (%#) \nfutureDate (%#)", now, futureDate);
} else {
NSLog(#"NO\nNow = (%#) \nfutureDate (%#)", now, futureDate);
}
sorry for the stupid question.