File: tab_lifecycle_unit_unittest.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (606 lines) | stat: -rw-r--r-- 26,679 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
// Copyright 2017 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/resource_coordinator/tab_lifecycle_unit.h"

#include <memory>
#include <string>

#include "base/auto_reset.h"
#include "base/functional/bind.h"
#include "base/functional/callback.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/weak_ptr.h"
#include "base/scoped_observation.h"
#include "base/test/simple_test_clock.h"
#include "base/test/simple_test_tick_clock.h"
#include "base/time/time.h"
#include "build/build_config.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/media/webrtc/media_capture_devices_dispatcher.h"
#include "chrome/browser/media/webrtc/media_stream_capture_indicator.h"
#include "chrome/browser/metrics/desktop_session_duration/desktop_session_duration_tracker.h"
#include "chrome/browser/notifications/notification_permission_context.h"
#include "chrome/browser/resource_coordinator/tab_helper.h"
#include "chrome/browser/resource_coordinator/tab_lifecycle_unit_external.h"
#include "chrome/browser/resource_coordinator/tab_lifecycle_unit_source.h"
#include "chrome/browser/resource_coordinator/tab_load_tracker.h"
#include "chrome/browser/resource_coordinator/tab_manager_features.h"
#include "chrome/browser/resource_coordinator/test_lifecycle_unit.h"
#include "chrome/browser/resource_coordinator/time.h"
#include "chrome/browser/resource_coordinator/utils.h"
#include "chrome/browser/tab_contents/form_interaction_tab_helper.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/browser/ui/tabs/test_tab_strip_model_delegate.h"
#include "chrome/browser/ui/tabs/test_util.h"
#include "chrome/test/base/chrome_render_view_host_test_harness.h"
#include "chrome/test/base/test_browser_window.h"
#include "chrome/test/base/testing_browser_process.h"
#include "chrome/test/base/testing_profile.h"
#include "components/performance_manager/public/decorators/page_live_state_decorator.h"
#include "components/performance_manager/public/graph/graph.h"
#include "components/performance_manager/public/graph/page_node.h"
#include "components/performance_manager/public/performance_manager.h"
#include "components/performance_manager/test_support/test_harness_helper.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/referrer.h"
#include "content/public/test/navigation_simulator.h"
#include "content/public/test/web_contents_tester.h"
#include "mojo/public/cpp/bindings/pending_remote.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/public/mojom/mediastream/media_stream.mojom.h"

#if BUILDFLAG(IS_CHROMEOS)
#include "chrome/browser/permissions/system/system_permission_settings.h"
#include "components/content_settings/core/common/content_settings_types.h"
#endif  // BUILDFLAG(IS_CHROMEOS)

namespace resource_coordinator {

namespace {

using LoadingState = TabLoadTracker::LoadingState;
using PageNode = performance_manager::PageNode;
using PageLiveStateDecorator = performance_manager::PageLiveStateDecorator;
using PerformanceManager = performance_manager::PerformanceManager;

constexpr base::TimeDelta kShortDelay = base::Seconds(1);

class MockLifecycleUnitObserver : public LifecycleUnitObserver {
 public:
  MockLifecycleUnitObserver() = default;

  MockLifecycleUnitObserver(const MockLifecycleUnitObserver&) = delete;
  MockLifecycleUnitObserver& operator=(const MockLifecycleUnitObserver&) =
      delete;

  MOCK_METHOD(void,
              OnLifecycleUnitStateChanged,
              (LifecycleUnit*,
               LifecycleUnitState,
               LifecycleUnitStateChangeReason),
              (override));
};

class MockPageLiveStateObserver
    : public performance_manager::PageLiveStateObserver {
 public:
  MOCK_METHOD(void,
              OnIsAutoDiscardableChanged,
              (const PageNode* page_node),
              (override));
};

}  // namespace

class TabLifecycleUnitTest : public ChromeRenderViewHostTestHarness {
 protected:
  using TabLifecycleUnit = TabLifecycleUnitSource::TabLifecycleUnit;

  // This is an internal class so that it is also friends with
  // TabLifecycleUnitTest.
  class ScopedEnterpriseOptOut;

  TabLifecycleUnitTest()
      : scoped_set_clocks_for_testing_(&test_clock_, &test_tick_clock_) {
    test_clock_.SetNow(base::Time::NowFromSystemTime());
    // Advance the clock so that it doesn't yield null time ticks.
    test_tick_clock_.Advance(base::Seconds(1));
  }

  TabLifecycleUnitTest(const TabLifecycleUnitTest&) = delete;
  TabLifecycleUnitTest& operator=(const TabLifecycleUnitTest&) = delete;

  void SetUp() override {
    TestingBrowserProcess::GetGlobal()->CreateGlobalFeaturesForTesting();
    ChromeRenderViewHostTestHarness::SetUp();
    pm_helper_.SetUp();

    PerformanceManager::GetGraph()->PassToGraph(
        std::make_unique<PageLiveStateDecorator>());

    // FormInteractionTabHelper asserts that its observer exists whenever
    // PerformanceManager is initialized.
    PerformanceManager::GetGraph()->PassToGraph(
        FormInteractionTabHelper::CreateGraphObserver());

    metrics::DesktopSessionDurationTracker::Initialize();

    // Force TabManager/TabLifecycleUnitSource creation.
    g_browser_process->GetTabManager();

    std::unique_ptr<content::WebContents> test_web_contents =
        CreateTestWebContents();
    web_contents_ = test_web_contents.get();
    auto* tester = content::WebContentsTester::For(web_contents_);
    tester->SetLastActiveTimeTicks(NowTicks());
    tester->SetLastActiveTime(Now());
    ResourceCoordinatorTabHelper::CreateForWebContents(web_contents_);
    // Commit an URL to allow discarding.
    auto navigation = content::NavigationSimulator::CreateBrowserInitiated(
        GURL("https://www.example.com"), web_contents_);
    navigation->SetKeepLoading(true);
    navigation->Commit();

    tab_strip_model_ =
        std::make_unique<TabStripModel>(&tab_strip_model_delegate_, profile());
    tab_strip_model_->AppendWebContents(std::move(test_web_contents), false);
    web_contents_->WasHidden();

    std::unique_ptr<content::WebContents> second_web_contents =
        CreateTestWebContents();
    content::WebContents* raw_second_web_contents = second_web_contents.get();
    tab_strip_model_->AppendWebContents(std::move(second_web_contents),
                                        /*foreground=*/true);
    raw_second_web_contents->WasHidden();
  }

  void TearDown() override {
    while (!tab_strip_model_->empty())
      tab_strip_model_->DetachAndDeleteWebContentsAt(0);
    tab_strip_model_.reset();
    metrics::DesktopSessionDurationTracker::CleanupForTesting();
    pm_helper_.TearDown();
    ChromeRenderViewHostTestHarness::TearDown();
  }

  // Create a new test WebContents and append it to the tab strip to allow
  // testing discarding operations on it. The returned WebContents is in the
  // hidden state.
  content::WebContents* AddNewHiddenWebContentsToTabStrip() {
    std::unique_ptr<content::WebContents> test_web_contents =
        CreateTestWebContents();
    content::WebContents* web_contents = test_web_contents.get();
    ResourceCoordinatorTabHelper::CreateForWebContents(web_contents);
    tab_strip_model_->AppendWebContents(std::move(test_web_contents), false);
    web_contents->WasHidden();
    return web_contents;
  }

  // Create a new test WebContents, as in AddNewHiddenWebContentsToTabStrip().
  // If the TabLifecycleUnitSource is observing the tab strip, returns the
  // TabLifecycleUnit that it created for the WebContents, otherwise returns
  // nullptr. (By default tests don't observe the tab strip so that they can
  // manually create TabLifecycleUnits.)
  TabLifecycleUnit* AddNewHiddenLifecycleUnitToTabStrip() {
    content::WebContents* contents = AddNewHiddenWebContentsToTabStrip();
    return GetTabLifecycleUnitSource()->GetTabLifecycleUnit(contents);
  }

  raw_ptr<content::WebContents, DanglingUntriaged>
      web_contents_;  // Owned by tab_strip_model_.
  std::unique_ptr<TabStripModel> tab_strip_model_;
  base::SimpleTestClock test_clock_;
  base::SimpleTestTickClock test_tick_clock_;

 private:
  // So that the main thread looks like the UI thread as expected.
  TestTabStripModelDelegate tab_strip_model_delegate_;
  ScopedSetClocksForTesting scoped_set_clocks_for_testing_;
  tabs::PreventTabFeatureInitialization prevent_;
  performance_manager::PerformanceManagerTestHarnessHelper pm_helper_;
};

class TabLifecycleUnitTest::ScopedEnterpriseOptOut {
 public:
  ScopedEnterpriseOptOut() {
    GetTabLifecycleUnitSource()->SetTabLifecyclesEnterprisePolicy(false);
  }

  ~ScopedEnterpriseOptOut() {
    GetTabLifecycleUnitSource()->SetTabLifecyclesEnterprisePolicy(true);
  }
};

TEST_F(TabLifecycleUnitTest, AsTabLifecycleUnitExternal) {
  TabLifecycleUnit tab_lifecycle_unit(GetTabLifecycleUnitSource(),
                                      web_contents_, tab_strip_model_.get());
  EXPECT_TRUE(tab_lifecycle_unit.AsTabLifecycleUnitExternal());
}

TEST_F(TabLifecycleUnitTest, CanDiscardByDefault) {
  TabLifecycleUnit tab_lifecycle_unit(GetTabLifecycleUnitSource(),
                                      web_contents_, tab_strip_model_.get());
  // Advance time enough that the tab is urgent discardable.
  test_tick_clock_.Advance(kBackgroundUrgentProtectionTime);
  ExpectCanDiscardTrueAllReasons(&tab_lifecycle_unit);
}

TEST_F(TabLifecycleUnitTest, SetFocused) {
  TabLifecycleUnit tab_lifecycle_unit(GetTabLifecycleUnitSource(),
                                      web_contents_, tab_strip_model_.get());
  EXPECT_EQ(NowTicks(), tab_lifecycle_unit.GetLastFocusedTimeTicks());
  EXPECT_EQ(Now(), tab_lifecycle_unit.GetLastFocusedTime());
  // Advance time enough that the tab is urgent discardable.
  test_tick_clock_.Advance(kBackgroundUrgentProtectionTime);
  test_clock_.Advance(kBackgroundUrgentProtectionTime);
  ExpectCanDiscardTrueAllReasons(&tab_lifecycle_unit);

  tab_lifecycle_unit.SetFocused(true);
  tab_strip_model_->ActivateTabAt(0);
  web_contents_->WasShown();
  EXPECT_EQ(base::TimeTicks::Max(),
            tab_lifecycle_unit.GetLastFocusedTimeTicks());
  EXPECT_EQ(base::Time::Max(), tab_lifecycle_unit.GetLastFocusedTime());
  ExpectCanDiscardFalseAllReasons(&tab_lifecycle_unit,
                                  DecisionFailureReason::LIVE_STATE_VISIBLE);

  tab_lifecycle_unit.SetFocused(false);
  tab_strip_model_->ActivateTabAt(1);
  web_contents_->WasHidden();
  EXPECT_EQ(test_tick_clock_.NowTicks(),
            tab_lifecycle_unit.GetLastFocusedTimeTicks());
  EXPECT_EQ(test_clock_.Now(), tab_lifecycle_unit.GetLastFocusedTime());
  // Advance time enough that the tab is urgent discardable.
  test_tick_clock_.Advance(kBackgroundUrgentProtectionTime);
  ExpectCanDiscardTrueAllReasons(&tab_lifecycle_unit);
}

TEST_F(TabLifecycleUnitTest, AutoDiscardable) {
  base::WeakPtr<PageNode> page_node =
      PerformanceManager::GetPrimaryPageNodeForWebContents(web_contents_);
  ASSERT_TRUE(page_node);
  auto* page_live_state_data =
      PageLiveStateDecorator::Data::GetOrCreateForPageNode(page_node.get());

  ::testing::StrictMock<MockPageLiveStateObserver> page_observer;
  base::ScopedObservation<PageLiveStateDecorator::Data,
                          MockPageLiveStateObserver>
      page_observation(&page_observer);
  page_observation.Observe(page_live_state_data);

  TabLifecycleUnit tab_lifecycle_unit(GetTabLifecycleUnitSource(),
                                      web_contents_, tab_strip_model_.get());

  // Advance time enough that the tab is urgent discardable.
  test_tick_clock_.Advance(kBackgroundUrgentProtectionTime);
  EXPECT_TRUE(tab_lifecycle_unit.IsAutoDiscardable());
  EXPECT_TRUE(page_live_state_data->IsAutoDiscardable());
  ExpectCanDiscardTrueAllReasons(&tab_lifecycle_unit);

  EXPECT_CALL(page_observer, OnIsAutoDiscardableChanged(page_node.get()));
  tab_lifecycle_unit.SetAutoDiscardable(false);
  ::testing::Mock::VerifyAndClear(&page_observer);
  EXPECT_FALSE(tab_lifecycle_unit.IsAutoDiscardable());
  EXPECT_FALSE(page_live_state_data->IsAutoDiscardable());
  ExpectCanDiscardFalseAllReasons(
      &tab_lifecycle_unit,
      DecisionFailureReason::LIVE_STATE_EXTENSION_DISALLOWED);

  EXPECT_CALL(page_observer, OnIsAutoDiscardableChanged(page_node.get()));
  tab_lifecycle_unit.SetAutoDiscardable(true);
  ::testing::Mock::VerifyAndClear(&page_observer);
  EXPECT_TRUE(tab_lifecycle_unit.IsAutoDiscardable());
  EXPECT_TRUE(page_live_state_data->IsAutoDiscardable());
  ExpectCanDiscardTrueAllReasons(&tab_lifecycle_unit);
}

TEST_F(TabLifecycleUnitTest, AutoDiscardablePersistsThroughDiscard) {
  // Start observing the TabStripModel so that TabLifecycleUnitSource will be
  // informed when the tab is discarded. TabLifecycleUnitSource expects to fully
  // manage TabLifecycleUnits after this, so create a new WebContents that will
  // get a TabLifecycleUnit attached.
  tab_strip_model_->AddObserver(GetTabLifecycleUnitSource());
  TabLifecycleUnit* tab_lifecycle_unit = AddNewHiddenLifecycleUnitToTabStrip();

  tab_lifecycle_unit->SetAutoDiscardable(false);

  // Manual discard by an extension is allowed when AutoDiscardable is false.
  EXPECT_TRUE(
      tab_lifecycle_unit->DiscardTab(LifecycleUnitDiscardReason::EXTERNAL, 0));
  EXPECT_FALSE(tab_lifecycle_unit->IsAutoDiscardable());
  EXPECT_FALSE(PageLiveStateDecorator::IsAutoDiscardable(
      tab_lifecycle_unit->GetWebContents()));

  EXPECT_TRUE(tab_lifecycle_unit->Load());
  EXPECT_FALSE(tab_lifecycle_unit->IsAutoDiscardable());
  EXPECT_FALSE(PageLiveStateDecorator::IsAutoDiscardable(
      tab_lifecycle_unit->GetWebContents()));

  tab_strip_model_->RemoveObserver(GetTabLifecycleUnitSource());
}

TEST_F(TabLifecycleUnitTest, CannotDiscardCrashed) {
  TabLifecycleUnit tab_lifecycle_unit(GetTabLifecycleUnitSource(),
                                      web_contents_, tab_strip_model_.get());

  auto* tester = content::WebContentsTester::For(web_contents_);
  tester->SetIsCrashed(base::TERMINATION_STATUS_PROCESS_CRASHED, 0);
  ExpectCanDiscardFalseTrivialAllReasons(&tab_lifecycle_unit);
}

#if !BUILDFLAG(IS_CHROMEOS)
TEST_F(TabLifecycleUnitTest, CannotDiscardActive) {
  TabLifecycleUnit tab_lifecycle_unit(GetTabLifecycleUnitSource(),
                                      web_contents_, tab_strip_model_.get());

  tab_strip_model_->ActivateTabAt(0);

  // Advance time enough that the tab is urgent discardable.
  test_tick_clock_.Advance(kBackgroundUrgentProtectionTime);

  ExpectCanDiscardFalseAllReasons(&tab_lifecycle_unit,
                                  DecisionFailureReason::LIVE_STATE_VISIBLE);
}

TEST_F(TabLifecycleUnitTest, UrgentDiscardProtections) {
  TabLifecycleUnit tab_lifecycle_unit(GetTabLifecycleUnitSource(),
                                      web_contents_, tab_strip_model_.get());
  // EXTERNAL or FROZEN_WITH_GROWING_MEMORY discarding is allowed, but URGENT
  // discarding is blocked because the tab is too recent.
  ExpectCanDiscardTrue(&tab_lifecycle_unit,
                       LifecycleUnitDiscardReason::EXTERNAL);
  ExpectCanDiscardTrue(&tab_lifecycle_unit,
                       LifecycleUnitDiscardReason::FROZEN_WITH_GROWING_MEMORY);
  ExpectCanDiscardFalseTrivial(&tab_lifecycle_unit,
                               LifecycleUnitDiscardReason::URGENT);

  // Advance time enough that the tab is urgent discardable.
  test_tick_clock_.Advance(kBackgroundUrgentProtectionTime);

  // The tab should now be discardable for all reasons.
  ExpectCanDiscardTrueAllReasons(&tab_lifecycle_unit);

  // Mark the tab as having been discarded.
  tab_lifecycle_unit.SetDiscardCountForTesting(1);

  // Advance time enough that the time protection no longer applies. The tab
  // should still not be urgent discardable at this point, because it has
  // already been discarded at least once.
  test_tick_clock_.Advance(kBackgroundUrgentProtectionTime);

  // EXTERNAL or FROZEN_WITH_GROWING_MEMORY discarding is allowed, but URGENT
  // discarding is blocked because the tab has been discarded previously.
  ExpectCanDiscardTrue(&tab_lifecycle_unit,
                       LifecycleUnitDiscardReason::EXTERNAL);
  ExpectCanDiscardTrue(&tab_lifecycle_unit,
                       LifecycleUnitDiscardReason::FROZEN_WITH_GROWING_MEMORY);
  ExpectCanDiscardFalseTrivial(&tab_lifecycle_unit,
                               LifecycleUnitDiscardReason::URGENT);

  // The tab should be discardable a second time when the memory limit
  // enterprise policy is set.
  GetTabLifecycleUnitSource()->SetMemoryLimitEnterprisePolicyFlag(true);
  ExpectCanDiscardTrue(&tab_lifecycle_unit, LifecycleUnitDiscardReason::URGENT);
}
#endif  // !BUILDFLAG(IS_CHROMEOS)

TEST_F(TabLifecycleUnitTest, CannotDiscardInvalidURL) {
  content::WebContents* web_contents = AddNewHiddenWebContentsToTabStrip();
  TabLifecycleUnit tab_lifecycle_unit(GetTabLifecycleUnitSource(), web_contents,
                                      tab_strip_model_.get());
  // TODO(sebmarchand): Fix this test, this doesn't really test that it's not
  // possible to discard an invalid URL, TestWebContents::GetLastCommittedURL()
  // doesn't return the URL set with "SetLastCommittedURL" if this one is
  // invalid.
  content::WebContentsTester::For(web_contents)
      ->SetLastCommittedURL(GURL("Invalid :)"));
  ExpectCanDiscardFalseTrivialAllReasons(&tab_lifecycle_unit);
}

TEST_F(TabLifecycleUnitTest, CannotDiscardEmptyURL) {
  content::WebContents* web_contents = AddNewHiddenWebContentsToTabStrip();
  TabLifecycleUnit tab_lifecycle_unit(GetTabLifecycleUnitSource(), web_contents,
                                      tab_strip_model_.get());

  ExpectCanDiscardFalseTrivialAllReasons(&tab_lifecycle_unit);
}

TEST_F(TabLifecycleUnitTest, CannotDiscardVideoCapture) {
#if BUILDFLAG(IS_CHROMEOS)
  // Mock system-level microphone permission.
  system_permission_settings::ScopedSettingsForTesting mic_settings(
      ContentSettingsType::MEDIASTREAM_MIC, false);
#endif  // BUILDFLAG(IS_CHROMEOS)

  TabLifecycleUnit tab_lifecycle_unit(GetTabLifecycleUnitSource(),
                                      web_contents_, tab_strip_model_.get());
  // Advance time enough that the tab is urgent discardable.
  test_tick_clock_.Advance(kBackgroundUrgentProtectionTime);
  ExpectCanDiscardTrueAllReasons(&tab_lifecycle_unit);

  blink::mojom::StreamDevices devices;
  devices.video_device = blink::MediaStreamDevice(
      blink::mojom::MediaStreamType::DEVICE_VIDEO_CAPTURE, "fake_media_device",
      "fake_media_device");

  std::unique_ptr<content::MediaStreamUI> ui =
      MediaCaptureDevicesDispatcher::GetInstance()
          ->GetMediaStreamCaptureIndicator()
          ->RegisterMediaStream(web_contents_, devices);
  ui->OnStarted(base::RepeatingClosure(),
                content::MediaStreamUI::SourceCallback(),
                /*label=*/std::string(), /*screen_capture_ids=*/{},
                content::MediaStreamUI::StateChangeCallback());
  ExpectCanDiscardFalseAllReasons(&tab_lifecycle_unit,
                                  DecisionFailureReason::LIVE_STATE_CAPTURING);

  ui.reset();
  ExpectCanDiscardTrueAllReasons(&tab_lifecycle_unit);
}

TEST_F(TabLifecycleUnitTest, CannotDiscardHasFormInteractions) {
  TabLifecycleUnit tab_lifecycle_unit(GetTabLifecycleUnitSource(),
                                      web_contents_, tab_strip_model_.get());
  // Advance time enough that the tab is urgent discardable.
  test_tick_clock_.Advance(kBackgroundUrgentProtectionTime);
  ExpectCanDiscardTrueAllReasons(&tab_lifecycle_unit);

  FormInteractionTabHelper::CreateForWebContents(web_contents_);
  FormInteractionTabHelper::FromWebContents(web_contents_)
      ->OnHadFormInteractionChangedForTesting(true);
  ExpectCanDiscardFalseAllReasons(&tab_lifecycle_unit,
                                  DecisionFailureReason::LIVE_STATE_FORM_ENTRY);

  FormInteractionTabHelper::FromWebContents(web_contents_)
      ->OnHadFormInteractionChangedForTesting(false);
  ExpectCanDiscardTrueAllReasons(&tab_lifecycle_unit);
}

TEST_F(TabLifecycleUnitTest, CannotDiscardDesktopCapture) {
  TabLifecycleUnit tab_lifecycle_unit(GetTabLifecycleUnitSource(),
                                      web_contents_, tab_strip_model_.get());
  // Advance time enough that the tab is urgent discardable.
  test_tick_clock_.Advance(kBackgroundUrgentProtectionTime);
  ExpectCanDiscardTrueAllReasons(&tab_lifecycle_unit);

  blink::mojom::StreamDevices devices;
  devices.video_device = blink::MediaStreamDevice(
      blink::mojom::MediaStreamType::GUM_DESKTOP_VIDEO_CAPTURE,
      "fake_media_device", "fake_media_device");
  devices.video_device->display_media_info =
      media::mojom::DisplayMediaInformation::New(
          media::mojom::DisplayCaptureSurfaceType::MONITOR,
          /*logical_surface=*/true, media::mojom::CursorCaptureType::NEVER,
          /*capture_handle=*/nullptr,
          /*initial_zoom_level=*/100);
  std::unique_ptr<content::MediaStreamUI> ui =
      MediaCaptureDevicesDispatcher::GetInstance()
          ->GetMediaStreamCaptureIndicator()
          ->RegisterMediaStream(web_contents_, devices);
  ui->OnStarted(base::RepeatingClosure(),
                content::MediaStreamUI::SourceCallback(),
                /*label=*/std::string(), /*screen_capture_ids=*/{},
                content::MediaStreamUI::StateChangeCallback());
  ExpectCanDiscardFalseAllReasons(
      &tab_lifecycle_unit, DecisionFailureReason::LIVE_STATE_DESKTOP_CAPTURE);

  ui.reset();
  ExpectCanDiscardTrueAllReasons(&tab_lifecycle_unit);
}

TEST_F(TabLifecycleUnitTest, CannotDiscardRecentlyAudible) {
  TabLifecycleUnit tab_lifecycle_unit(GetTabLifecycleUnitSource(),
                                      web_contents_, tab_strip_model_.get());
  // Advance time enough that the tab is urgent discardable.
  test_tick_clock_.Advance(kBackgroundUrgentProtectionTime);
  ExpectCanDiscardTrueAllReasons(&tab_lifecycle_unit);

  // Cannot discard when the "recently audible" bit is set.
  tab_lifecycle_unit.SetRecentlyAudible(true);
  ExpectCanDiscardFalseAllReasons(
      &tab_lifecycle_unit, DecisionFailureReason::LIVE_STATE_PLAYING_AUDIO);

  // The "recently audible" bit is still set. The tab cannot be discarded.
  test_tick_clock_.Advance(kTabAudioProtectionTime);
  ExpectCanDiscardFalseAllReasons(
      &tab_lifecycle_unit, DecisionFailureReason::LIVE_STATE_PLAYING_AUDIO);

  // The "recently audible" bit was unset less than
  // kTabAudioProtectionTime ago. The tab cannot be discarded.
  tab_lifecycle_unit.SetRecentlyAudible(false);
  test_tick_clock_.Advance(kShortDelay);
  ExpectCanDiscardFalseAllReasons(
      &tab_lifecycle_unit, DecisionFailureReason::LIVE_STATE_PLAYING_AUDIO);

  // The "recently audible" bit was unset kTabAudioProtectionTime ago. The tab
  // can be discarded.
  test_tick_clock_.Advance(kTabAudioProtectionTime - kShortDelay);
  ExpectCanDiscardTrueAllReasons(&tab_lifecycle_unit);

  // Calling SetRecentlyAudible(false) again does not change the fact that the
  // tab can be discarded.
  tab_lifecycle_unit.SetRecentlyAudible(false);
  ExpectCanDiscardTrueAllReasons(&tab_lifecycle_unit);
}

TEST_F(TabLifecycleUnitTest, CanDiscardNeverAudibleTab) {
  TabLifecycleUnit tab_lifecycle_unit(GetTabLifecycleUnitSource(),
                                      web_contents_, tab_strip_model_.get());
  // Advance time enough that the tab is urgent discardable.
  test_tick_clock_.Advance(kBackgroundUrgentProtectionTime);
  ExpectCanDiscardTrueAllReasons(&tab_lifecycle_unit);

  tab_lifecycle_unit.SetRecentlyAudible(false);
  // Since the tab was never audible, it should be possible to discard it,
  // even if there was a recent call to SetRecentlyAudible(false).
  ExpectCanDiscardTrueAllReasons(&tab_lifecycle_unit);
}

TEST_F(TabLifecycleUnitTest, CannotDiscardPDF) {
  TabLifecycleUnit tab_lifecycle_unit(GetTabLifecycleUnitSource(),
                                      web_contents_, tab_strip_model_.get());
  // Advance time enough that the tab is urgent discardable.
  test_tick_clock_.Advance(kBackgroundUrgentProtectionTime);
  ExpectCanDiscardTrueAllReasons(&tab_lifecycle_unit);

  content::WebContentsTester::For(web_contents_)
      ->SetMainFrameMimeType("application/pdf");
  ExpectCanDiscardFalseAllReasons(&tab_lifecycle_unit,
                                  DecisionFailureReason::LIVE_STATE_IS_PDF);
}

// Verify the initial GetWallTimeWhenHidden() of a visible LifecycleUnit.
TEST_F(TabLifecycleUnitTest, InitialLastActiveTimeForVisibleLifecycleUnit) {
  web_contents_->WasShown();
  TabLifecycleUnit lifecycle_unit(GetTabLifecycleUnitSource(), web_contents_,
                                  tab_strip_model_.get());
  EXPECT_EQ(base::TimeTicks::Max(),
            lifecycle_unit.GetWallTimeWhenHiddenForTesting());
}

// Verify the initial GetWallTimeWhenHidden() of a hidden LifecycleUnit.
TEST_F(TabLifecycleUnitTest, InitialLastActiveTimeForHiddenLifecycleUnit) {
  web_contents_->WasHidden();
  TabLifecycleUnit lifecycle_unit(GetTabLifecycleUnitSource(), web_contents_,
                                  tab_strip_model_.get());
  EXPECT_EQ(NowTicks(), lifecycle_unit.GetWallTimeWhenHiddenForTesting());
}

TEST_F(TabLifecycleUnitTest, LastActiveTimeUpdatedOnVisibilityChange) {
  TabLifecycleUnit tab_lifecycle_unit(GetTabLifecycleUnitSource(),
                                      web_contents_, tab_strip_model_.get());

  web_contents_->WasShown();
  EXPECT_EQ(base::TimeTicks::Max(),
            tab_lifecycle_unit.GetWallTimeWhenHiddenForTesting());

  test_tick_clock_.Advance(base::Minutes(1));
  web_contents_->WasHidden();
  base::TimeTicks wall_time_when_hidden = NowTicks();
  EXPECT_EQ(wall_time_when_hidden,
            tab_lifecycle_unit.GetWallTimeWhenHiddenForTesting());

  test_tick_clock_.Advance(base::Minutes(1));
  web_contents_->WasOccluded();
  // `wall_time_when_hidden` not updated because it was already HIDDEN.
  EXPECT_EQ(wall_time_when_hidden,
            tab_lifecycle_unit.GetWallTimeWhenHiddenForTesting());

  test_tick_clock_.Advance(base::Minutes(1));
  web_contents_->WasShown();
  EXPECT_EQ(base::TimeTicks::Max(),
            tab_lifecycle_unit.GetWallTimeWhenHiddenForTesting());

  test_tick_clock_.Advance(base::Minutes(1));
  web_contents_->WasOccluded();
  wall_time_when_hidden = NowTicks();
  EXPECT_EQ(wall_time_when_hidden,
            tab_lifecycle_unit.GetWallTimeWhenHiddenForTesting());
}

}  // namespace resource_coordinator