1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #import "base/test/ios/wait_util.h"
7 #import <Foundation/Foundation.h>
9 #include "base/logging.h"
10 #include "base/mac/scoped_nsobject.h"
11 #include "base/message_loop/message_loop.h"
12 #include "base/test/test_timeouts.h"
13 #include "base/timer/elapsed_timer.h"
19 TimeDelta TimeUntilCondition(ProceduralBlock action,
20 ConditionBlock condition,
21 MessageLoop* message_loop,
26 if (timeout == TimeDelta())
27 timeout = TestTimeouts::action_timeout();
28 const TimeDelta spin_delay(TimeDelta::FromMilliseconds(10));
29 while (timer.Elapsed() < timeout && (!condition || !condition())) {
30 SpinRunLoopWithMaxDelay(spin_delay);
32 message_loop->RunUntilIdle();
35 TimeDelta elapsed = timer.Elapsed();
36 // If DCHECK is ever hit, check if |action| is doing something that is
37 // taking an unreasonably long time, or if |condition| does not come
38 // true quickly enough. Increase |timeout| only if necessary.
39 DCHECK(!condition || condition());
43 void WaitUntilCondition(ConditionBlock condition,
44 MessageLoop* message_loop,
46 TimeUntilCondition(nil, condition, message_loop, timeout);
49 void WaitUntilCondition(ConditionBlock condition) {
50 WaitUntilCondition(condition, nullptr, TimeDelta());
53 void SpinRunLoopWithMaxDelay(TimeDelta max_delay) {
54 scoped_nsobject<NSDate> beforeDate(
55 [[NSDate alloc] initWithTimeIntervalSinceNow:max_delay.InSecondsF()]);
56 [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
57 beforeDate:beforeDate];