-
Notifications
You must be signed in to change notification settings - Fork 6.6k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[base][test] Add a
RunUntil(<predicate>)
utility
It's very common that a test has to wait until a certain condition is fulfilled. Often, the test knows this is the case by installing an observer or callback. However, quite often the code under test doesn't have an observer or callback to report it is done, since it doesn't need one. This makes testing this code a challenge. This CL adds a utility that can be used in these cases: // Example usage ChangeColorFieldAsyncTo(object_under_test, kRed); ASSERT_TRUE(RunUntil( base::BindLambdaForTesting([&](){ return object_under_test.Color() == kRed; }))); // When we come here we are guaranteed that // `object_under_test.Color()` is set to `kRed`. This utility will poll periodically until the predicate returns `true` (or until we hit a timeout). Change-Id: I4f4f49fb06362cd1a5d8969fb0a3d50bb5a58ada Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/4370081 Commit-Queue: Jeroen Dhollander <jeroendh@google.com> Reviewed-by: David Roger <droger@chromium.org> Reviewed-by: David Black <dmblack@google.com> Reviewed-by: Primiano Tucci <primiano@chromium.org> Reviewed-by: Denis Kuznetsov <antrim@chromium.org> Reviewed-by: Wez <wez@chromium.org> Cr-Commit-Position: refs/heads/main@{#1151826}
- Loading branch information
Jeroen Dhollander
authored and
Chromium LUCI CQ
committed
Jun 1, 2023
1 parent
551fed9
commit a4e2fe0
Showing
9 changed files
with
279 additions
and
145 deletions.
There are no files selected for viewing
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
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
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,53 @@ | ||
// Copyright 2023 The Chromium Authors | ||
// Use of this source code is governed by a BSD-style license that can be | ||
// found in the LICENSE file. | ||
|
||
#include "base/test/run_until.h" | ||
|
||
#include <functional> | ||
|
||
#include "base/functional/callback.h" | ||
#include "base/functional/callback_forward.h" | ||
#include "base/task/current_thread.h" | ||
#include "base/test/scoped_run_loop_timeout.h" | ||
#include "base/test/test_future.h" | ||
#include "base/time/time_override.h" | ||
|
||
namespace base::test { | ||
|
||
namespace { | ||
|
||
void TestPredicateOrRegisterOnNextIdleCallback( | ||
base::FunctionRef<bool(void)> condition, | ||
OnceClosure ready_callback) { | ||
if (condition()) { | ||
// Invoke `ready_callback` if `condition` evaluates to true. | ||
std::move(ready_callback).Run(); | ||
} else { | ||
// Otherwise try again the next time the thread is idle. | ||
CurrentThread::Get().RegisterOnNextIdleCallback( | ||
BindOnce(TestPredicateOrRegisterOnNextIdleCallback, condition, | ||
std::move(ready_callback))); | ||
} | ||
} | ||
|
||
} // namespace | ||
|
||
bool RunUntil(base::FunctionRef<bool(void)> condition) { | ||
CHECK(!subtle::ScopedTimeClockOverrides::overrides_active()) | ||
<< "Mocked timesource detected, which would cause `RunUntil` to hang " | ||
"forever on failure."; | ||
CHECK(test::ScopedRunLoopTimeout::ExistsForCurrentThread()) | ||
<< "No RunLoop timeout set, meaning `RunUntil` will hang forever on " | ||
"failure."; | ||
|
||
test::TestFuture<void> ready_signal; | ||
|
||
CurrentThread::Get().RegisterOnNextIdleCallback( | ||
BindOnce(TestPredicateOrRegisterOnNextIdleCallback, condition, | ||
ready_signal.GetCallback())); | ||
|
||
return ready_signal.Wait(); | ||
} | ||
|
||
} // namespace base::test |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
// Copyright 2023 The Chromium Authors | ||
// Use of this source code is governed by a BSD-style license that can be | ||
// found in the LICENSE file. | ||
|
||
#ifndef BASE_TEST_RUN_UNTIL_H_ | ||
#define BASE_TEST_RUN_UNTIL_H_ | ||
|
||
#include "base/functional/function_ref.h" | ||
|
||
namespace base::test { | ||
|
||
// Waits until `condition` evaluates to `true`, by evaluating `condition` | ||
// whenever the current task becomes idle (while allowing the message loop of | ||
// the calling thread to spin). | ||
// | ||
// Returns true if `condition` became true, or false if a timeout happens. | ||
// | ||
// Example usage: | ||
// | ||
// ChangeColorAsyncTo(object_under_tests, Color::Red); | ||
// | ||
// // Waits until the color is red, or aborts the tests otherwise. | ||
// ASSERT_TRUE(RunUntil([&](){ | ||
// return object_under_test.Color() == Color::Red; | ||
// })) << "Timeout waiting for the color to turn red"; | ||
// | ||
// // When we come here `Color()` is guaranteed to be `Color::Red`. | ||
// | ||
[[nodiscard]] bool RunUntil(base::FunctionRef<bool(void)> condition); | ||
|
||
} // namespace base::test | ||
|
||
#endif // BASE_TEST_RUN_UNTIL_H_ |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,121 @@ | ||
// Copyright 2023 The Chromium Authors | ||
// Use of this source code is governed by a BSD-style license that can be | ||
// found in the LICENSE file. | ||
|
||
#include "base/test/run_until.h" | ||
|
||
#include "base/functional/callback_forward.h" | ||
#include "base/functional/callback_helpers.h" | ||
#include "base/task/single_thread_task_runner.h" | ||
#include "base/test/bind.h" | ||
#include "base/test/task_environment.h" | ||
#include "base/timer/timer.h" | ||
#include "testing/gtest/include/gtest/gtest-spi.h" | ||
#include "testing/gtest/include/gtest/gtest.h" | ||
|
||
namespace base::test { | ||
|
||
namespace { | ||
|
||
template <typename Lambda> | ||
void RunLater(Lambda lambda) { | ||
SingleThreadTaskRunner::GetCurrentDefault()->PostTask( | ||
FROM_HERE, base::BindLambdaForTesting(lambda)); | ||
} | ||
|
||
void PostDelayedTask(base::OnceClosure closure, base::TimeDelta delay) { | ||
base::SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask( | ||
FROM_HERE, std::move(closure), delay); | ||
} | ||
|
||
} // namespace | ||
|
||
class RunUntilTest : public ::testing::Test { | ||
public: | ||
RunUntilTest() = default; | ||
RunUntilTest(const RunUntilTest&) = delete; | ||
RunUntilTest& operator=(const RunUntilTest&) = delete; | ||
~RunUntilTest() override = default; | ||
|
||
private: | ||
test::SingleThreadTaskEnvironment environment_; | ||
}; | ||
|
||
TEST_F(RunUntilTest, ShouldReturnTrueIfPredicateIsAlreadyFulfilled) { | ||
EXPECT_TRUE(RunUntil([]() { return true; })); | ||
} | ||
|
||
TEST_F(RunUntilTest, ShouldReturnTrueOncePredicateIsFulfilled) { | ||
bool done = false; | ||
|
||
RunLater([&done]() { done = true; }); | ||
|
||
EXPECT_TRUE(RunUntil([&done]() { return done; })); | ||
} | ||
|
||
TEST_F(RunUntilTest, ShouldNotSimplyActivelyInvokePredicateInALoop) { | ||
bool done = false; | ||
int call_count = 0; | ||
|
||
PostDelayedTask(base::BindLambdaForTesting([&done]() { done = true; }), | ||
base::Milliseconds(50)); | ||
|
||
EXPECT_TRUE(RunUntil([&]() { | ||
call_count++; | ||
return done; | ||
})); | ||
|
||
// Ensure the predicate is not called a ton of times. | ||
EXPECT_LT(call_count, 10); | ||
} | ||
|
||
TEST_F(RunUntilTest, ShouldNotSimplyReturnOnFirstIdle) { | ||
bool done = false; | ||
|
||
PostDelayedTask(base::DoNothing(), base::Milliseconds(1)); | ||
PostDelayedTask(base::DoNothing(), base::Milliseconds(5)); | ||
PostDelayedTask(base::BindLambdaForTesting([&done]() { done = true; }), | ||
base::Milliseconds(10)); | ||
|
||
EXPECT_TRUE(RunUntil([&]() { return done; })); | ||
} | ||
|
||
TEST_F(RunUntilTest, | ||
ShouldAlwaysLetOtherTasksRunFirstEvenIfPredicateIsAlreadyFulfilled) { | ||
// This ensures that no tests can (accidentally) rely on `RunUntil` | ||
// immediately returning. | ||
bool other_job_done = false; | ||
RunLater([&other_job_done] { other_job_done = true; }); | ||
|
||
EXPECT_TRUE(RunUntil([]() { return true; })); | ||
|
||
EXPECT_TRUE(other_job_done); | ||
} | ||
|
||
TEST_F(RunUntilTest, ShouldWorkEvenWhenTimerIsRunning) { | ||
bool done = false; | ||
|
||
base::RepeatingTimer timer; | ||
timer.Start(FROM_HERE, base::Seconds(1), base::DoNothing()); | ||
|
||
PostDelayedTask(base::BindLambdaForTesting([&done]() { done = true; }), | ||
base::Milliseconds(10)); | ||
|
||
EXPECT_TRUE(RunUntil([&]() { return done; })); | ||
} | ||
|
||
TEST_F(RunUntilTest, ShouldReturnFalseIfTimeoutHappens) { | ||
test::ScopedRunLoopTimeout timeout(FROM_HERE, Milliseconds(1)); | ||
|
||
// `ScopedRunLoopTimeout` will automatically fail the test when a timeout | ||
// happens, so we use EXPECT_FATAL_FAILURE to handle this failure. | ||
// EXPECT_FATAL_FAILURE only works on static objects. | ||
static bool success; | ||
|
||
EXPECT_FATAL_FAILURE({ success = RunUntil([]() { return false; }); }, | ||
"timed out"); | ||
|
||
EXPECT_FALSE(success); | ||
} | ||
|
||
} // namespace base::test |
Oops, something went wrong.