Commit 7d714d6a authored by Sergio Villar Senin's avatar Sergio Villar Senin Committed by Commit Bot

Reland "Remove time overrides from TestingPlatformSupportWithMockScheduler"

This is a reland of f75182ab

TBR=jbroman@chromium.org, dcheng@chromium.org

Original change's description:
> Remove time overrides from TestingPlatformSupportWithMockScheduler
>
> TestingPlatformSupportWithMockScheduler used time overrides to control time in
> tests. Time overrides are removed as part of the OnionSoup effort. Tests should
> use the mock clock from the TestTaskRunner provided by the platform.
>
> Bug: 919383
> Change-Id: Idf3d44ed2aeff8c73de09671b50b779419146d3b
> Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1591634
> Reviewed-by: Jeremy Roman <jbroman@chromium.org>
> Reviewed-by: Daniel Cheng <dcheng@chromium.org>
> Commit-Queue: Sergio Villar <svillar@igalia.com>
> Cr-Commit-Position: refs/heads/master@{#665724}

Bug: 919383
Change-Id: I76d14136b8f239b90dde32442af3cca0c4efe044
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1642554Reviewed-by: default avatarSergio Villar <svillar@igalia.com>
Commit-Queue: Sergio Villar <svillar@igalia.com>
Cr-Commit-Position: refs/heads/master@{#665888}
parent 9f40e17e
......@@ -53,9 +53,9 @@ void AnimationClock::UpdateTime(base::TimeTicks time) {
}
double AnimationClock::CurrentTime() {
if (monotonically_increasing_time_ &&
if (clock_ &&
task_for_which_time_was_calculated_ != currently_running_task_) {
const base::TimeTicks current_time = monotonically_increasing_time_();
const base::TimeTicks current_time = clock_->NowTicks();
if (time_ < current_time) {
// Advance to the first estimated frame after the current time.
const base::TimeDelta frame_shift =
......
......@@ -34,9 +34,9 @@
#include <limits>
#include "base/macros.h"
#include "base/time/default_tick_clock.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
#include "third_party/blink/renderer/platform/wtf/time.h"
namespace blink {
......@@ -49,8 +49,8 @@ class CORE_EXPORT AnimationClock {
public:
using TimeTicksFunction = base::TimeTicks (*)();
explicit AnimationClock(
TimeTicksFunction monotonically_increasing_time = WTF::CurrentTimeTicks)
: monotonically_increasing_time_(monotonically_increasing_time),
const base::TickClock* clock = base::DefaultTickClock::GetInstance())
: clock_(clock),
time_(),
task_for_which_time_was_calculated_(
std::numeric_limits<unsigned>::max()) {}
......@@ -58,16 +58,15 @@ class CORE_EXPORT AnimationClock {
void UpdateTime(base::TimeTicks time);
double CurrentTime();
void ResetTimeForTesting(base::TimeTicks time = base::TimeTicks());
void DisableSyntheticTimeForTesting() {
monotonically_increasing_time_ = nullptr;
}
// The caller owns the |clock| which must outlive the AnimationClock.
void SetClockForTesting(const base::TickClock* clock) { clock_ = clock; }
// notifyTaskStart should be called right before the main message loop starts
// to run the next task from the message queue.
static void NotifyTaskStart() { ++currently_running_task_; }
private:
TimeTicksFunction monotonically_increasing_time_;
const base::TickClock* clock_;
base::TimeTicks time_;
unsigned task_for_which_time_was_calculated_;
static unsigned currently_running_task_;
......
......@@ -29,14 +29,15 @@
*/
#include "third_party/blink/renderer/core/animation/animation_clock.h"
#include "base/time/tick_clock.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace blink {
class AnimationAnimationClockTest : public testing::Test {
class AnimationAnimationClockTest : public testing::Test, base::TickClock {
public:
AnimationAnimationClockTest() : animation_clock(MockTimeFunction) {}
AnimationAnimationClockTest() : animation_clock(this) {}
protected:
void SetUp() override {
......@@ -44,16 +45,14 @@ class AnimationAnimationClockTest : public testing::Test {
animation_clock.ResetTimeForTesting();
}
static base::TimeTicks MockTimeFunction() {
base::TimeTicks NowTicks() const override {
return base::TimeTicks() + base::TimeDelta::FromSecondsD(mock_time_);
}
static double mock_time_;
double mock_time_;
AnimationClock animation_clock;
};
double AnimationAnimationClockTest::mock_time_;
TEST_F(AnimationAnimationClockTest, TimeIsGreaterThanZeroForUnitTests) {
AnimationClock clock;
// unit tests outside core/animation shouldn't need to do anything to get
......
......@@ -37,7 +37,7 @@ TEST_F(AnimationSimTest, CustomPropertyBaseComputedStyle) {
ScopedStackedCSSPropertyAnimationsForTest stacked_css_property_animation(
true);
WebView().GetPage()->Animator().Clock().DisableSyntheticTimeForTesting();
WebView().GetPage()->Animator().Clock().SetClockForTesting(nullptr);
SimRequest main_resource("https://example.com/", "text/html");
LoadURL("https://example.com/");
......
......@@ -26,6 +26,7 @@ class CSSAnimationsTest : public RenderingTest {
platform()->AdvanceClockSeconds(1.);
RenderingTest::SetUp();
EnableCompositing();
SetUpAnimationClockForTesting();
}
void TearDown() override {
......@@ -35,8 +36,11 @@ class CSSAnimationsTest : public RenderingTest {
void StartAnimationOnCompositor(Animation* animation) {
static_cast<CompositorAnimationDelegate*>(animation)
->NotifyAnimationStarted(
(CurrentTimeTicks() - base::TimeTicks()).InSecondsF(),
->NotifyAnimationStarted(platform()
->test_task_runner()
->NowTicks()
.since_origin()
.InSecondsF(),
animation->CompositorGroup());
}
......@@ -53,6 +57,17 @@ class CSSAnimationsTest : public RenderingTest {
return static_cast<const BasicComponentTransferFilterOperation*>(filter)
->Amount();
}
private:
void SetUpAnimationClockForTesting() {
auto& animator_clock = GetPage().Animator().Clock();
animator_clock.SetClockForTesting(
platform()->test_task_runner()->GetMockTickClock());
animator_clock.ResetTimeForTesting();
// Call NofifyTaskStart() to force the computation of animation clock times
// after reset.
animator_clock.NotifyTaskStart();
}
};
// Verify that a composited animation is retargeted according to its composited
......@@ -79,13 +94,15 @@ TEST_F(CSSAnimationsTest, RetargetedTransition) {
// Starting the second transition should retarget the active transition.
element->setAttribute(html_names::kClassAttr, "contrast2");
GetPage().Animator().ServiceScriptedAnimations(CurrentTimeTicks());
GetPage().Animator().ServiceScriptedAnimations(
platform()->test_task_runner()->NowTicks());
UpdateAllLifecyclePhasesForTest();
EXPECT_NEAR(0.6, GetContrastFilterAmount(element), 0.0000000001);
// As it has been retargeted, advancing halfway should go to 0.3.
AdvanceClockSeconds(0.5);
GetPage().Animator().ServiceScriptedAnimations(CurrentTimeTicks());
GetPage().Animator().ServiceScriptedAnimations(
platform()->test_task_runner()->NowTicks());
UpdateAllLifecyclePhasesForTest();
EXPECT_NEAR(0.3, GetContrastFilterAmount(element), 0.0000000001);
}
......@@ -113,6 +130,7 @@ TEST_F(CSSAnimationsTest, IncompatibleRetargetedTransition) {
StartAnimationOnCompositor(animation);
EXPECT_TRUE(animation->HasActiveAnimationsOnCompositor());
AdvanceClockSeconds(0.003);
platform()->RunUntilIdle();
// The computed style still contains no filter until the next frame.
EXPECT_TRUE(element->GetComputedStyle()->Filter().IsEmpty());
......
......@@ -5,6 +5,7 @@
#include "third_party/blink/renderer/core/loader/idleness_detector.h"
#include "base/logging.h"
#include "base/time/default_tick_clock.h"
#include "services/resource_coordinator/public/cpp/resource_coordinator_features.h"
#include "third_party/blink/public/platform/modules/service_worker/web_service_worker_network_provider.h"
#include "third_party/blink/public/platform/platform.h"
......@@ -19,6 +20,10 @@
#include "third_party/blink/renderer/platform/instrumentation/resource_coordinator/document_resource_coordinator.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_fetcher.h"
namespace {
const base::TickClock* g_clock = nullptr;
} // namespace
namespace blink {
constexpr TimeDelta IdlenessDetector::kNetworkQuietWindow;
......@@ -93,7 +98,7 @@ void IdlenessDetector::OnDidLoadResource() {
if (request_count > 2)
return;
TimeTicks timestamp = CurrentTimeTicks();
TimeTicks timestamp = g_clock->NowTicks();
// Arriving at =2 updates the quiet_2 base timestamp.
// Arriving at <2 sets the quiet_2 base timestamp only if
// it was not already set.
......@@ -199,6 +204,8 @@ IdlenessDetector::IdlenessDetector(LocalFrame* local_frame)
local_frame->GetTaskRunner(TaskType::kInternalLoading),
this,
&IdlenessDetector::NetworkQuietTimerFired) {
if (!g_clock)
g_clock = base::DefaultTickClock::GetInstance();
if (local_frame->GetSettings()) {
network_quiet_window_ = TimeDelta::FromSecondsD(
local_frame->GetSettings()->GetNetworkQuietTimeout());
......@@ -221,6 +228,11 @@ void IdlenessDetector::NetworkQuietTimerFired(TimerBase*) {
}
}
// static
void IdlenessDetector::SetTickClockForTesting(const base::TickClock* clock) {
g_clock = clock;
}
void IdlenessDetector::Trace(blink::Visitor* visitor) {
visitor->Trace(local_frame_);
}
......
......@@ -11,6 +11,10 @@
#include "third_party/blink/renderer/platform/heap/handle.h"
#include "third_party/blink/renderer/platform/timer.h"
namespace base {
class TickClock;
}
namespace blink {
class LocalFrame;
......@@ -39,6 +43,9 @@ class CORE_EXPORT IdlenessDetector
TimeTicks GetNetworkIdleTime();
bool NetworkIsAlmostIdle();
// The caller owns the |clock| which must outlive the IdlenessDetector.
static void SetTickClockForTesting(const base::TickClock* clock);
void Trace(blink::Visitor*);
private:
......
......@@ -13,11 +13,19 @@ namespace blink {
class IdlenessDetectorTest : public PageTestBase {
protected:
void SetUp() override {
platform_time_ = CurrentTimeTicks();
auto task_runner = platform_->test_task_runner();
platform_time_ = task_runner->NowTicks();
DCHECK(!platform_time_.is_null());
IdlenessDetector::SetTickClockForTesting(task_runner->GetMockTickClock());
PageTestBase::SetUp();
}
void TearDown() override {
PageTestBase::TearDown();
IdlenessDetector::SetTickClockForTesting(
base::DefaultTickClock::GetInstance());
}
IdlenessDetector* Detector() { return GetFrame().GetIdlenessDetector(); }
bool IsNetworkQuietTimerActive() {
......
......@@ -36,9 +36,9 @@ class LongTaskDetectorTest : public testing::Test {
public:
// Public because it's executed on a task queue.
void DummyTaskWithDuration(base::TimeDelta duration) {
dummy_task_start_time_ = CurrentTimeTicks();
dummy_task_start_time_ = platform_->test_task_runner()->NowTicks();
platform_->AdvanceClock(duration);
dummy_task_end_time_ = CurrentTimeTicks();
dummy_task_end_time_ = platform_->test_task_runner()->NowTicks();
}
protected:
......
......@@ -4,6 +4,7 @@
#include "third_party/blink/renderer/core/paint/first_meaningful_paint_detector.h"
#include "base/time/default_tick_clock.h"
#include "third_party/blink/public/platform/task_type.h"
#include "third_party/blink/renderer/core/css/font_face_set_document.h"
#include "third_party/blink/renderer/core/paint/paint_timing.h"
......@@ -21,6 +22,7 @@ namespace {
// Meaningful Paint.
const int kBlankCharactersThreshold = 200;
const base::TickClock* g_clock = nullptr;
} // namespace
FirstMeaningfulPaintDetector& FirstMeaningfulPaintDetector::From(
......@@ -30,7 +32,10 @@ FirstMeaningfulPaintDetector& FirstMeaningfulPaintDetector::From(
FirstMeaningfulPaintDetector::FirstMeaningfulPaintDetector(
PaintTiming* paint_timing)
: paint_timing_(paint_timing) {}
: paint_timing_(paint_timing) {
if (!g_clock)
g_clock = base::DefaultTickClock::GetInstance();
}
Document* FirstMeaningfulPaintDetector::GetDocument() {
return paint_timing_->GetSupplementable();
......@@ -84,7 +89,7 @@ void FirstMeaningfulPaintDetector::NotifyPaint() {
// Skip document background-only paints.
if (paint_timing_->FirstPaintRendered().is_null())
return;
provisional_first_meaningful_paint_ = CurrentTimeTicks();
provisional_first_meaningful_paint_ = g_clock->NowTicks();
next_paint_is_meaningful_ = false;
if (network2_quiet_reached_)
......@@ -275,6 +280,12 @@ void FirstMeaningfulPaintDetector::SetFirstMeaningfulPaint(
swap_stamp, had_user_input_before_provisional_first_meaningful_paint_);
}
// static
void FirstMeaningfulPaintDetector::SetTickClockForTesting(
const base::TickClock* clock) {
g_clock = clock;
}
void FirstMeaningfulPaintDetector::Trace(blink::Visitor* visitor) {
visitor->Trace(paint_timing_);
}
......
......@@ -12,6 +12,10 @@
#include "third_party/blink/renderer/platform/heap/handle.h"
#include "third_party/blink/renderer/platform/wtf/time.h"
namespace base {
class TickClock;
}
namespace blink {
class Document;
......@@ -41,6 +45,9 @@ class CORE_EXPORT FirstMeaningfulPaintDetector
void OnNetwork0Quiet();
void OnNetwork2Quiet();
// The caller owns the |clock| which must outlive the paint detector.
static void SetTickClockForTesting(const base::TickClock* clock);
void Trace(blink::Visitor*);
enum HadUserInput { kNoUserInput, kHadUserInput, kHadUserInputEnumMax };
......
......@@ -19,12 +19,25 @@ class FirstMeaningfulPaintDetectorTest : public PageTestBase {
protected:
void SetUp() override {
platform_->AdvanceClock(TimeDelta::FromSeconds(1));
const base::TickClock* test_clock =
platform_->test_task_runner()->GetMockTickClock();
FirstMeaningfulPaintDetector::SetTickClockForTesting(test_clock);
PageTestBase::SetUp();
GetPaintTiming().SetTickClockForTesting(test_clock);
}
void TearDown() override {
const base::TickClock* clock = base::DefaultTickClock::GetInstance();
GetPaintTiming().SetTickClockForTesting(clock);
PageTestBase::TearDown();
FirstMeaningfulPaintDetector::SetTickClockForTesting(clock);
}
base::TimeTicks Now() { return platform_->test_task_runner()->NowTicks(); }
TimeTicks AdvanceClockAndGetTime() {
platform_->AdvanceClock(TimeDelta::FromSeconds(1));
return CurrentTimeTicks();
return Now();
}
PaintTiming& GetPaintTiming() { return PaintTiming::From(GetDocument()); }
......@@ -62,21 +75,20 @@ class FirstMeaningfulPaintDetectorTest : public PageTestBase {
void ClearFirstPaintSwapPromise() {
platform_->AdvanceClock(TimeDelta::FromMilliseconds(1));
GetPaintTiming().ReportSwapTime(PaintEvent::kFirstPaint,
WebWidgetClient::SwapResult::kDidSwap,
CurrentTimeTicks());
GetPaintTiming().ReportSwapTime(
PaintEvent::kFirstPaint, WebWidgetClient::SwapResult::kDidSwap, Now());
}
void ClearFirstContentfulPaintSwapPromise() {
platform_->AdvanceClock(TimeDelta::FromMilliseconds(1));
GetPaintTiming().ReportSwapTime(PaintEvent::kFirstContentfulPaint,
WebWidgetClient::SwapResult::kDidSwap,
CurrentTimeTicks());
Now());
}
void ClearProvisionalFirstMeaningfulPaintSwapPromise() {
platform_->AdvanceClock(TimeDelta::FromMilliseconds(1));
ClearProvisionalFirstMeaningfulPaintSwapPromise(CurrentTimeTicks());
ClearProvisionalFirstMeaningfulPaintSwapPromise(Now());
}
void ClearProvisionalFirstMeaningfulPaintSwapPromise(
......
......@@ -7,6 +7,7 @@
#include <memory>
#include <utility>
#include "base/time/default_tick_clock.h"
#include "third_party/blink/public/platform/web_layer_tree_view.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/frame/local_dom_window.h"
......@@ -59,7 +60,7 @@ void PaintTiming::MarkFirstPaint() {
// markFirstPaint().
if (!first_paint_.is_null())
return;
SetFirstPaint(CurrentTimeTicks());
SetFirstPaint(clock_->NowTicks());
}
void PaintTiming::MarkFirstContentfulPaint() {
......@@ -69,13 +70,13 @@ void PaintTiming::MarkFirstContentfulPaint() {
// markFirstContentfulPaint().
if (!first_contentful_paint_.is_null())
return;
SetFirstContentfulPaint(CurrentTimeTicks());
SetFirstContentfulPaint(clock_->NowTicks());
}
void PaintTiming::MarkFirstImagePaint() {
if (!first_image_paint_.is_null())
return;
first_image_paint_ = CurrentTimeTicks();
first_image_paint_ = clock_->NowTicks();
SetFirstContentfulPaint(first_image_paint_);
RegisterNotifySwapTime(PaintEvent::kFirstImagePaint);
}
......@@ -138,6 +139,10 @@ void PaintTiming::NotifyPaint(bool is_first_paint,
fmp_detector_->NotifyPaint();
}
void PaintTiming::SetTickClockForTesting(const base::TickClock* clock) {
clock_ = clock;
}
void PaintTiming::Trace(blink::Visitor* visitor) {
visitor->Trace(fmp_detector_);
Supplement<Document>::Trace(visitor);
......@@ -145,7 +150,8 @@ void PaintTiming::Trace(blink::Visitor* visitor) {
PaintTiming::PaintTiming(Document& document)
: Supplement<Document>(document),
fmp_detector_(MakeGarbageCollected<FirstMeaningfulPaintDetector>(this)) {}
fmp_detector_(MakeGarbageCollected<FirstMeaningfulPaintDetector>(this)),
clock_(base::DefaultTickClock::GetInstance()) {}
LocalFrame* PaintTiming::GetFrame() const {
return GetSupplementable()->GetFrame();
......
......@@ -17,6 +17,10 @@
#include "third_party/blink/renderer/platform/wtf/functional.h"
#include "third_party/blink/renderer/platform/wtf/time.h"
namespace base {
class TickClock;
}
namespace blink {
class LocalFrame;
......@@ -103,6 +107,9 @@ class CORE_EXPORT PaintTiming final
void ReportSwapResultHistogram(WebWidgetClient::SwapResult);
// The caller owns the |clock| which must outlive the PaintTiming.
void SetTickClockForTesting(const base::TickClock* clock);
void Trace(blink::Visitor*) override;
private:
......@@ -154,6 +161,8 @@ class CORE_EXPORT PaintTiming final
Member<FirstMeaningfulPaintDetector> fmp_detector_;
const base::TickClock* clock_;
FRIEND_TEST_ALL_PREFIXES(FirstMeaningfulPaintDetectorTest, NoFirstPaint);
FRIEND_TEST_ALL_PREFIXES(FirstMeaningfulPaintDetectorTest, OneLayout);
FRIEND_TEST_ALL_PREFIXES(FirstMeaningfulPaintDetectorTest,
......
......@@ -4,6 +4,7 @@
#include "third_party/blink/renderer/modules/media_controls/elements/media_control_overflow_menu_list_element.h"
#include "base/time/default_tick_clock.h"
#include "third_party/blink/public/platform/task_type.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/dom/dom_token_list.h"
......@@ -18,7 +19,8 @@ namespace blink {
MediaControlOverflowMenuListElement::MediaControlOverflowMenuListElement(
MediaControlsImpl& media_controls)
: MediaControlPopupMenuElement(media_controls) {
: MediaControlPopupMenuElement(media_controls),
clock_(base::DefaultTickClock::GetInstance()) {
SetShadowPseudoId(
AtomicString("-internal-media-controls-overflow-menu-list"));
setAttribute(html_names::kRoleAttr, "menu");
......@@ -45,7 +47,7 @@ void MediaControlOverflowMenuListElement::MaybeRecordTimeTaken(
: "Media.Controls.Overflow.TimeToDismiss",
1, 100, 100);
histogram.Count(static_cast<int32_t>(
(CurrentTimeTicks() - time_shown_.value()).InSeconds()));
(clock_->NowTicks() - time_shown_.value()).InSeconds()));
time_shown_.reset();
}
......@@ -68,7 +70,7 @@ void MediaControlOverflowMenuListElement::SetIsWanted(bool wanted) {
// Record the time the overflow menu was shown to a histogram.
if (wanted) {
DCHECK(!time_shown_);
time_shown_ = CurrentTimeTicks();
time_shown_ = clock_->NowTicks();
} else if (time_shown_) {
// Records the time taken to dismiss using a task runner. This ensures the
// time to dismiss is always called after the time to action (if there is
......@@ -92,4 +94,9 @@ void MediaControlOverflowMenuListElement::OnItemSelected() {
MediaControlPopupMenuElement::OnItemSelected();
}
void MediaControlOverflowMenuListElement::SetTickClockForTesting(
const base::TickClock* clock) {
clock_ = clock;
}
} // namespace blink
......@@ -10,6 +10,10 @@
#include "third_party/blink/renderer/platform/scheduler/public/post_cancellable_task.h"
#include "third_party/blink/renderer/platform/wtf/time.h"
namespace base {
class TickClock;
}
namespace blink {
class Event;
......@@ -29,6 +33,9 @@ class MediaControlOverflowMenuListElement final
Element* PopupAnchor() const final;
void OnItemSelected() final;
// The caller owns the |clock| which must outlive the media control element.
MODULES_EXPORT void SetTickClockForTesting(const base::TickClock* clock);
private:
enum TimeTakenHistogram {
kTimeToAction,
......@@ -41,6 +48,7 @@ class MediaControlOverflowMenuListElement final
TaskHandle current_task_handle_;
base::Optional<WTF::TimeTicks> time_shown_;
const base::TickClock* clock_;
};
} // namespace blink
......
......@@ -244,6 +244,9 @@ class MediaControlsImplTest : public PageTestBase,
MediaControlOverflowMenuButtonElement* OverflowMenuButtonElement() const {
return media_controls_->overflow_menu_;
}
MediaControlOverflowMenuListElement* OverflowMenuListElement() const {
return media_controls_->overflow_list_;
}
MockWebMediaPlayerForImpl* WebMediaPlayer() {
return static_cast<MockWebMediaPlayerForImpl*>(
......@@ -1188,6 +1191,9 @@ TEST_F(MediaControlsImplTest, InfinityDurationChangeHidesDurationField) {
TEST_F(MediaControlsImplTestWithMockScheduler,
OverflowMenuMetricsTimeToAction) {
OverflowMenuListElement()->SetTickClockForTesting(
platform()->test_task_runner()->GetMockTickClock());
GetHistogramTester().ExpectTotalCount(kTimeToActionHistogramName, 0);
GetHistogramTester().ExpectTotalCount(kTimeToDismissHistogramName, 0);
......@@ -1224,6 +1230,9 @@ TEST_F(MediaControlsImplTestWithMockScheduler,
TEST_F(MediaControlsImplTestWithMockScheduler,
OverflowMenuMetricsTimeToDismiss) {
OverflowMenuListElement()->SetTickClockForTesting(
platform()->test_task_runner()->GetMockTickClock());
GetHistogramTester().ExpectTotalCount(kTimeToDismissHistogramName, 0);
GetHistogramTester().ExpectTotalCount(kTimeToActionHistogramName, 0);
......
......@@ -124,10 +124,13 @@ class MemoryCacheCorrectnessTest : public testing::Test {
ResourceFetcherInit(properties->MakeDetachable(), context,
base::MakeRefCounted<scheduler::FakeTaskRunner>(),
MakeGarbageCollected<TestLoaderFactory>()));
Resource::SetClockForTesting(platform_->test_task_runner()->GetMockClock());
}
void TearDown() override {
GetMemoryCache()->EvictResources();
Resource::SetClockForTesting(nullptr);
// Yield the ownership of the global memory cache back.
ReplaceMemoryCacheForTesting(global_memory_cache_.Release());
}
......
......@@ -32,6 +32,7 @@
#include "base/single_thread_task_runner.h"
#include "base/stl_util.h"
#include "base/time/default_clock.h"
#include "build/build_config.h"
#include "services/network/public/mojom/fetch_api.mojom-blink.h"
#include "third_party/blink/public/platform/platform.h"
......@@ -57,7 +58,6 @@
#include "third_party/blink/renderer/platform/wtf/std_lib_extras.h"
#include "third_party/blink/renderer/platform/wtf/text/cstring.h"
#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
#include "third_party/blink/renderer/platform/wtf/time.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
namespace blink {
......@@ -120,6 +120,17 @@ static inline bool ShouldUpdateHeaderAfterRevalidation(
return true;
}
namespace {
const base::Clock* g_clock_for_testing = nullptr;
}
static inline double Now() {
const base::Clock* clock = g_clock_for_testing
? g_clock_for_testing
: base::DefaultClock::GetInstance();
return clock->Now().ToDoubleT();
}
Resource::Resource(const ResourceRequest& request,
ResourceType type,
const ResourceLoaderOptions& options)
......@@ -135,7 +146,7 @@ Resource::Resource(const ResourceRequest& request,
is_add_remove_client_prohibited_(false),
integrity_disposition_(ResourceIntegrityDisposition::kNotChecked),
options_(options),
response_timestamp_(CurrentTime()),
response_timestamp_(Now()),
resource_request_(request),
overhead_size_(CalculateOverheadSize()) {
InstanceCounters::IncrementCounter(InstanceCounters::kResourceCounter);
......@@ -378,7 +389,7 @@ static double CurrentAge(const ResourceResponse& response,
double corrected_received_age = std::isfinite(age_value)
? std::max(apparent_age, age_value)
: apparent_age;
double resident_time = CurrentTime() - response_timestamp;
double resident_time = Now() - response_timestamp;
return corrected_received_age + resident_time;
}
......@@ -490,7 +501,7 @@ void Resource::SetResponse(const ResourceResponse& response) {
}
void Resource::ResponseReceived(const ResourceResponse& response) {
response_timestamp_ = CurrentTime();
response_timestamp_ = Now();
if (is_revalidating_) {
if (response.HttpStatusCode() == 304) {
RevalidationSucceeded(response);
......@@ -1230,4 +1241,9 @@ bool Resource::IsLoadEventBlockingResourceType() const {
return false;
}
// static
void Resource::SetClockForTesting(const base::Clock* clock) {
g_clock_for_testing = clock;
}
} // namespace blink
......@@ -54,7 +54,10 @@
#include "third_party/blink/renderer/platform/wtf/text/atomic_string.h"
#include "third_party/blink/renderer/platform/wtf/text/text_encoding.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
#include "third_party/blink/renderer/platform/wtf/time.h"
namespace base {
class Clock;
}
namespace blink {
......@@ -422,6 +425,9 @@ class PLATFORM_EXPORT Resource : public GarbageCollectedFinalized<Resource>,
return virtual_time_pauser_;
}
// The caller owns the |clock| which must outlive the Resource.
static void SetClockForTesting(const base::Clock* clock);
protected:
Resource(const ResourceRequest&, ResourceType, const ResourceLoaderOptions&);
......
......@@ -500,8 +500,17 @@ TEST(ResourceTest, RedirectDuringRevalidation) {
EXPECT_FALSE(resource->IsAlive());
}
class ScopedResourceMockClock {
public:
explicit ScopedResourceMockClock(const base::Clock* clock) {
Resource::SetClockForTesting(clock);
}
~ScopedResourceMockClock() { Resource::SetClockForTesting(nullptr); }
};
TEST(ResourceTest, StaleWhileRevalidateCacheControl) {
ScopedTestingPlatformSupport<MockPlatform> mock;
ScopedResourceMockClock clock(mock->test_task_runner()->GetMockClock());
const KURL url("http://127.0.0.1:8000/foo.html");
ResourceResponse response(url);
response.SetHttpStatusCode(200);
......@@ -529,6 +538,7 @@ TEST(ResourceTest, StaleWhileRevalidateCacheControl) {
TEST(ResourceTest, StaleWhileRevalidateCacheControlWithRedirect) {
ScopedTestingPlatformSupport<MockPlatform> mock;
ScopedResourceMockClock clock(mock->test_task_runner()->GetMockClock());
const KURL url("http://127.0.0.1:8000/foo.html");
const KURL redirect_target_url("http://127.0.0.1:8000/food.html");
ResourceResponse response(url);
......
......@@ -29,13 +29,10 @@ TestingPlatformSupportWithMockScheduler::
scheduler_->CreateMainThread());
// Set the work batch size to one so TakePendingTasks behaves as expected.
scheduler_->GetSchedulerHelperForTesting()->SetWorkBatchSizeForTesting(1);
WTF::SetTimeFunctionsForTesting(GetTestTime);
}
TestingPlatformSupportWithMockScheduler::
~TestingPlatformSupportWithMockScheduler() {
WTF::SetTimeFunctionsForTesting(nullptr);
scheduler_->Shutdown();
}
......@@ -92,13 +89,4 @@ TestingPlatformSupportWithMockScheduler::GetMainThreadScheduler() const {
return scheduler_.get();
}
// static
double TestingPlatformSupportWithMockScheduler::GetTestTime() {
TestingPlatformSupportWithMockScheduler* platform =
static_cast<TestingPlatformSupportWithMockScheduler*>(
Platform::Current());
return (platform->test_task_runner_->NowTicks() - base::TimeTicks())
.InSecondsF();
}
} // namespace blink
......@@ -17,7 +17,6 @@
#include "third_party/blink/renderer/platform/scheduler/public/thread_scheduler.h"
#include "third_party/blink/renderer/platform/testing/testing_platform_support_with_mock_scheduler.h"
#include "third_party/blink/renderer/platform/wtf/ref_counted.h"
#include "third_party/blink/renderer/platform/wtf/time.h"
using base::sequence_manager::TaskQueue;
using blink::scheduler::MainThreadTaskQueue;
......@@ -39,17 +38,19 @@ class TimerTest : public testing::Test {
void SetUp() override {
run_times_.clear();
platform_->AdvanceClock(TimeDelta::FromSeconds(10));
start_time_ = CurrentTimeTicks();
start_time_ = Now();
}
void CountingTask(TimerBase*) { run_times_.push_back(CurrentTimeTicks()); }
base::TimeTicks Now() { return platform_->test_task_runner()->NowTicks(); }
void CountingTask(TimerBase*) { run_times_.push_back(Now()); }
void RecordNextFireTimeTask(TimerBase* timer) {
next_fire_times_.push_back(CurrentTimeTicks() + timer->NextFireInterval());
next_fire_times_.push_back(Now() + timer->NextFireInterval());
}
void RunUntilDeadline(TimeTicks deadline) {
TimeDelta period = deadline - CurrentTimeTicks();
TimeDelta period = deadline - Now();
EXPECT_GE(period, TimeDelta());
platform_->RunForPeriod(period);
}
......@@ -250,7 +251,7 @@ TEST_F(TimerTest, StartOneShot_NonZeroAndCancelThenRepost) {
platform_->RunUntilIdle();
EXPECT_FALSE(run_times_.size());
TimeTicks second_post_time = CurrentTimeTicks();
TimeTicks second_post_time = Now();
timer.StartOneShot(TimeDelta::FromSeconds(10), FROM_HERE);
EXPECT_TRUE(TimeTillNextDelayedTask(&run_time));
......@@ -554,7 +555,7 @@ TEST_F(TimerTest, RepeatingTimerDoesNotDrift) {
// Simulate timer firing early. Next scheduled task to run at
// |start_time_| + 4s
platform_->AdvanceClock(TimeDelta::FromMilliseconds(1900));
RunUntilDeadline(CurrentTimeTicks() + TimeDelta::FromMilliseconds(200));
RunUntilDeadline(Now() + TimeDelta::FromMilliseconds(200));
// Next scheduled task to run at |start_time_| + 6s
platform_->RunForPeriod(TimeDelta::FromSeconds(2));
......@@ -716,7 +717,7 @@ TEST_F(TimerTest, MoveToNewTaskRunnerOneShot) {
TimerForTest<TimerTest> timer(task_runner1, this, &TimerTest::CountingTask);
TimeTicks start_time = CurrentTimeTicks();
TimeTicks start_time = Now();
timer.StartOneShot(TimeDelta::FromSeconds(1), FROM_HERE);
......@@ -757,7 +758,7 @@ TEST_F(TimerTest, MoveToNewTaskRunnerRepeating) {
TimerForTest<TimerTest> timer(task_runner1, this, &TimerTest::CountingTask);
TimeTicks start_time = CurrentTimeTicks();
TimeTicks start_time = Now();
timer.StartRepeating(TimeDelta::FromSeconds(1), FROM_HERE);
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment