Skip to content

Commit

Permalink
[base][test] Add a RunUntil(<predicate>) utility
Browse files Browse the repository at this point in the history
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
Show file tree
Hide file tree
Showing 9 changed files with 279 additions and 145 deletions.
44 changes: 10 additions & 34 deletions ash/system/holding_space/holding_space_tray_unittest.cc
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@
#include "base/strings/strcat.h"
#include "base/test/bind.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/run_until.h"
#include "base/test/scoped_feature_list.h"
#include "build/branding_buildflags.h"
#include "testing/gmock/include/gmock/gmock.h"
Expand Down Expand Up @@ -77,6 +78,7 @@ namespace ash {

namespace {

using base::test::RunUntil;
using testing::_;
using testing::ElementsAre;

Expand Down Expand Up @@ -254,32 +256,6 @@ const views::MenuItemView* GetMenuItemByCommandId(HoldingSpaceCommandId id) {
return nullptr;
}

// PredicateWaiter -------------------------------------------------------------

// A class capable of waiting until a predicate returns true.
class PredicateWaiter {
public:
PredicateWaiter() = default;
PredicateWaiter(const PredicateWaiter&) = delete;
PredicateWaiter& operator=(const PredicateWaiter&) = delete;
~PredicateWaiter() = default;

void WaitUntil(base::RepeatingCallback<bool()> predicate,
base::TimeDelta polling_interval = base::Milliseconds(100)) {
DCHECK(polling_interval.is_positive());
if (predicate.Run())
return;
base::RunLoop run_loop;
base::RepeatingTimer scheduler;
scheduler.Start(FROM_HERE, polling_interval,
base::BindLambdaForTesting([&]() {
if (predicate.Run())
run_loop.Quit();
}));
run_loop.Run();
}
};

// ViewVisibilityChangedWaiter -------------------------------------------------

// A class capable of waiting until a view's visibility is changed.
Expand Down Expand Up @@ -3267,7 +3243,7 @@ TEST_P(HoldingSpaceTrayDownloadsSectionTest,

// Wait until the `progress_indicator` is synced with the model, which happens
// asynchronously in response to compositor scheduling.
PredicateWaiter().WaitUntil(base::BindLambdaForTesting([&]() {
ASSERT_TRUE(RunUntil([&]() {
return progress_indicator->progress() ==
ProgressIndicator::kProgressComplete;
}));
Expand All @@ -3284,8 +3260,8 @@ TEST_P(HoldingSpaceTrayDownloadsSectionTest,
// Wait until the `progress_indicator` is synced with the model. Note that
// this happens asynchronously since the `progress_indicator` does so in
// response to compositor scheduling.
PredicateWaiter().WaitUntil(base::BindLambdaForTesting(
[&]() { return progress_indicator->progress() == 0.f; }));
ASSERT_TRUE(
RunUntil([&]() { return progress_indicator->progress() == 0.f; }));

// The `default_tray_icon` should not be visible so as to avoid overlap with
// the `progress_indicator`'s inner icon while in progress.
Expand All @@ -3297,7 +3273,7 @@ TEST_P(HoldingSpaceTrayDownloadsSectionTest,

// Wait until the `progress_indicator` is synced with the model, which happens
// asynchronously in response to compositor scheduling.
PredicateWaiter().WaitUntil(base::BindLambdaForTesting([&]() {
ASSERT_TRUE(RunUntil([&]() {
return progress_indicator->progress() ==
ProgressIndicator::kProgressComplete;
}));
Expand Down Expand Up @@ -3339,8 +3315,8 @@ TEST_P(HoldingSpaceTrayDownloadsSectionTest,

// Wait until the `progress_indicator` is synced with the model, which happens
// asynchronously in response to compositor scheduling.
PredicateWaiter().WaitUntil(base::BindLambdaForTesting(
[&]() { return progress_indicator->progress() == 0.f; }));
ASSERT_TRUE(
RunUntil([&]() { return progress_indicator->progress() == 0.f; }));

// Verify image opacity/transform.
EXPECT_EQ(image->GetTargetOpacity(), 0.f);
Expand All @@ -3353,7 +3329,7 @@ TEST_P(HoldingSpaceTrayDownloadsSectionTest,

// Wait until the `progress_indicator` is synced with the model, which happens
// asynchronously in response to compositor scheduling.
PredicateWaiter().WaitUntil(base::BindLambdaForTesting([&]() {
ASSERT_TRUE(RunUntil([&]() {
return progress_indicator->progress() ==
ProgressIndicator::kProgressComplete;
}));
Expand Down Expand Up @@ -4011,7 +3987,7 @@ TEST_P(HoldingSpaceTrayPrimaryAndSecondaryActionsTest, HasExpectedActions) {
} else {
// For screen capture items, the holding space image should always be shown.
EXPECT_TRUE(IsShowingImage(item_views.front()));
};
}

// Right click the item view to show the context menu.
RightClick(item_views.front());
Expand Down
1 change: 1 addition & 0 deletions base/BUILD.gn
Original file line number Diff line number Diff line change
Expand Up @@ -3375,6 +3375,7 @@ test("base_unittests") {
"test/mock_callback_unittest.cc",
"test/rectify_callback_unittest.cc",
"test/repeating_test_future_unittest.cc",
"test/run_until_unittest.cc",
"test/scoped_feature_list_unittest.cc",
"test/scoped_logging_settings.h",
"test/scoped_mock_clock_override_unittest.cc",
Expand Down
2 changes: 2 additions & 0 deletions base/test/BUILD.gn
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,8 @@ static_library("test_support") {
"rectify_callback.h",
"rectify_callback_internal.h",
"repeating_test_future.h",
"run_until.cc",
"run_until.h",
"scoped_amount_of_physical_memory_override.cc",
"scoped_amount_of_physical_memory_override.h",
"scoped_command_line.cc",
Expand Down
53 changes: 53 additions & 0 deletions base/test/run_until.cc
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
33 changes: 33 additions & 0 deletions base/test/run_until.h
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_
121 changes: 121 additions & 0 deletions base/test/run_until_unittest.cc
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

0 comments on commit a4e2fe0

Please sign in to comment.