File: site_data_impl_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 (678 lines) | stat: -rw-r--r-- 27,589 bytes parent folder | download | duplicates (6)
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
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/performance_manager/persistence/site_data/site_data_impl.h"

#include "base/functional/callback.h"
#include "base/memory/ref_counted.h"
#include "base/test/bind.h"
#include "components/performance_manager/test_support/persistence/unittest_utils.h"
#include "content/public/test/browser_task_environment.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "url/gurl.h"

namespace performance_manager {
namespace internal {

namespace {

class TestSiteDataImpl : public SiteDataImpl {
 public:
  using SiteDataImpl::FeatureObservationDuration;
  using SiteDataImpl::OnDestroyDelegate;
  using SiteDataImpl::site_characteristics_for_testing;
  using SiteDataImpl::TimeDeltaToInternalRepresentation;

  explicit TestSiteDataImpl(
      const url::Origin& origin,
      base::WeakPtr<SiteDataImpl::OnDestroyDelegate> delegate,
      SiteDataStore* data_store)
      : SiteDataImpl(origin, delegate, data_store) {}

  base::TimeDelta FeatureObservationTimestamp(
      const SiteDataFeatureProto& feature_proto) {
    return InternalRepresentationToTimeDelta(feature_proto.use_timestamp());
  }

 protected:
  ~TestSiteDataImpl() override = default;
};

class MockDataStore : public testing::NoopSiteDataStore {
 public:
  MockDataStore() = default;

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

  ~MockDataStore() override = default;

  MOCK_METHOD(void,
              ReadSiteDataFromStore,
              (const url::Origin&,
               SiteDataStore::ReadSiteDataFromStoreCallback),
              (override));
  MOCK_METHOD(void,
              WriteSiteDataIntoStore,
              (const url::Origin&, const SiteDataProto&),
              (override));
};

// Returns a SiteDataFeatureProto that indicates that a feature hasn't been
// used.
SiteDataFeatureProto GetUnusedFeatureProto() {
  SiteDataFeatureProto unused_feature_proto;
  unused_feature_proto.set_observation_duration(1U);
  unused_feature_proto.set_use_timestamp(0U);
  return unused_feature_proto;
}

// Returns a SiteDataFeatureProto that indicates that a feature has been used.
SiteDataFeatureProto GetUsedFeatureProto() {
  SiteDataFeatureProto used_feature_proto;
  used_feature_proto.set_observation_duration(0U);
  used_feature_proto.set_use_timestamp(1U);
  return used_feature_proto;
}

}  // namespace

class SiteDataImplTest : public ::testing::Test {
 protected:
  void AdvanceClock(base::TimeDelta delta) {
    task_environment_.FastForwardBy(delta);
  }

  scoped_refptr<TestSiteDataImpl> GetDataImpl(
      const url::Origin& origin,
      base::WeakPtr<SiteDataImpl::OnDestroyDelegate> destroy_delegate,
      SiteDataStore* data_store) {
    return base::MakeRefCounted<TestSiteDataImpl>(origin, destroy_delegate,
                                                  data_store);
  }

  // Use a mock data store to intercept the initialization callback and save it
  // locally so it can be run later.
  scoped_refptr<TestSiteDataImpl> GetDataImplAndInterceptReadCallback(
      const url::Origin& origin,
      base::WeakPtr<SiteDataImpl::OnDestroyDelegate> destroy_delegate,
      MockDataStore* mock_data_store,
      SiteDataStore::ReadSiteDataFromStoreCallback* read_cb) {
    auto read_from_store_mock_impl =
        [&](const url::Origin& origin,
            SiteDataStore::ReadSiteDataFromStoreCallback callback) {
          *read_cb = std::move(callback);
        };

    EXPECT_CALL(*mock_data_store,
                ReadSiteDataFromStore(::testing::_, ::testing::_))
        .WillOnce(::testing::Invoke(read_from_store_mock_impl));
    auto local_site_data =
        GetDataImpl(origin, destroy_delegate_.GetWeakPtr(), mock_data_store);
    ::testing::Mock::VerifyAndClear(mock_data_store);
    return local_site_data;
  }

  const url::Origin kDummyOrigin = url::Origin::Create(GURL("foo.com"));
  const url::Origin kDummyOrigin2 = url::Origin::Create(GURL("bar.com"));

  content::BrowserTaskEnvironment task_environment_{
      base::test::TaskEnvironment::TimeSource::MOCK_TIME};

  // Use a NiceMock as there's no need to add expectations in these tests,
  // there's a dedicated test that ensure that the delegate works as expected.
  ::testing::NiceMock<testing::MockSiteDataImplOnDestroyDelegate>
      destroy_delegate_;

  testing::NoopSiteDataStore data_store_;
};

TEST_F(SiteDataImplTest, BasicTestEndToEnd) {
  auto local_site_data =
      GetDataImpl(kDummyOrigin, destroy_delegate_.GetWeakPtr(), &data_store_);

  local_site_data->NotifySiteLoaded();
  local_site_data->NotifyLoadedSiteBackgrounded();

  // Initially the feature usage should be reported as unknown.
  EXPECT_EQ(SiteFeatureUsage::kSiteFeatureUsageUnknown,
            local_site_data->UsesAudioInBackground());

  // Advance the clock by a time lower than the minimum observation time for
  // the audio feature.
  AdvanceClock(SiteDataImpl::GetFeatureObservationWindowLengthForTesting() -
               base::Seconds(1));

  // The audio feature usage is still unknown as the observation window hasn't
  // expired.
  EXPECT_EQ(SiteFeatureUsage::kSiteFeatureUsageUnknown,
            local_site_data->UsesAudioInBackground());

  // Report that the audio feature has been used.
  local_site_data->NotifyUsesAudioInBackground();
  EXPECT_EQ(SiteFeatureUsage::kSiteFeatureInUse,
            local_site_data->UsesAudioInBackground());

  // When a feature is in use it's expected that its recorded observation
  // timestamp is equal to the time delta since Unix Epoch when the observation
  // has been made.
  EXPECT_EQ(
      local_site_data
          ->FeatureObservationTimestamp(
              local_site_data->site_characteristics_for_testing()
                  .uses_audio_in_background())
          .InSeconds(),
      (base::TimeTicks::Now() - base::TimeTicks::UnixEpoch()).InSeconds());
  EXPECT_EQ(local_site_data->FeatureObservationDuration(
                local_site_data->site_characteristics_for_testing()
                    .uses_audio_in_background()),
            base::TimeDelta());

  // Advance the clock and make sure that title change feature gets reported as
  // unused.
  AdvanceClock(SiteDataImpl::GetFeatureObservationWindowLengthForTesting());
  EXPECT_EQ(SiteFeatureUsage::kSiteFeatureNotInUse,
            local_site_data->UpdatesTitleInBackground());

  // Observating that a feature has been used after its observation window has
  // expired should still be recorded, the feature should then be reported as
  // used.
  local_site_data->NotifyUpdatesTitleInBackground();
  EXPECT_EQ(SiteFeatureUsage::kSiteFeatureInUse,
            local_site_data->UpdatesTitleInBackground());

  local_site_data->NotifySiteUnloaded(TabVisibility::kBackground);
}

TEST_F(SiteDataImplTest, LastLoadedTime) {
  auto local_site_data =
      GetDataImpl(kDummyOrigin, destroy_delegate_.GetWeakPtr(), &data_store_);

  // Create a second instance of this object, simulates having several tab
  // owning it.
  auto local_site_data2(local_site_data);

  local_site_data->NotifySiteLoaded();
  base::TimeDelta last_loaded_time =
      local_site_data->last_loaded_time_for_testing();

  AdvanceClock(base::Seconds(1));

  // Loading the site a second time shouldn't change the last loaded time.
  local_site_data2->NotifySiteLoaded();
  EXPECT_EQ(last_loaded_time, local_site_data2->last_loaded_time_for_testing());

  AdvanceClock(base::Seconds(1));

  // Unloading the site shouldn't update the last loaded time as there's still
  // a loaded instance.
  local_site_data2->NotifySiteUnloaded(TabVisibility::kForeground);
  EXPECT_EQ(last_loaded_time, local_site_data->last_loaded_time_for_testing());

  AdvanceClock(base::Seconds(1));

  local_site_data->NotifySiteUnloaded(TabVisibility::kForeground);
  EXPECT_NE(last_loaded_time, local_site_data->last_loaded_time_for_testing());
}

TEST_F(SiteDataImplTest, GetFeatureUsageForUnloadedSite) {
  auto local_site_data =
      GetDataImpl(kDummyOrigin, destroy_delegate_.GetWeakPtr(), &data_store_);

  local_site_data->NotifySiteLoaded();
  local_site_data->NotifyLoadedSiteBackgrounded();
  local_site_data->NotifyUsesAudioInBackground();

  AdvanceClock(SiteDataImpl::GetFeatureObservationWindowLengthForTesting() -
               base::Seconds(1));
  EXPECT_EQ(SiteFeatureUsage::kSiteFeatureInUse,
            local_site_data->UsesAudioInBackground());
  EXPECT_EQ(SiteFeatureUsage::kSiteFeatureUsageUnknown,
            local_site_data->UpdatesTitleInBackground());

  const base::TimeDelta observation_duration_before_unload =
      local_site_data->FeatureObservationDuration(
          local_site_data->site_characteristics_for_testing()
              .updates_title_in_background());

  local_site_data->NotifySiteUnloaded(TabVisibility::kBackground);

  // Once unloaded the feature observations should still be accessible.
  EXPECT_EQ(SiteFeatureUsage::kSiteFeatureInUse,
            local_site_data->UsesAudioInBackground());
  EXPECT_EQ(SiteFeatureUsage::kSiteFeatureUsageUnknown,
            local_site_data->UpdatesTitleInBackground());

  // Advancing the clock shouldn't affect the observation duration for this
  // feature.
  AdvanceClock(base::Seconds(1));
  EXPECT_EQ(observation_duration_before_unload,
            local_site_data->FeatureObservationDuration(
                local_site_data->site_characteristics_for_testing()
                    .updates_title_in_background()));
  EXPECT_EQ(SiteFeatureUsage::kSiteFeatureUsageUnknown,
            local_site_data->UpdatesTitleInBackground());

  local_site_data->NotifySiteLoaded();
  local_site_data->NotifyLoadedSiteBackgrounded();

  AdvanceClock(base::Seconds(1));

  EXPECT_EQ(SiteFeatureUsage::kSiteFeatureInUse,
            local_site_data->UsesAudioInBackground());
  EXPECT_EQ(SiteFeatureUsage::kSiteFeatureNotInUse,
            local_site_data->UpdatesTitleInBackground());

  local_site_data->NotifySiteUnloaded(TabVisibility::kBackground);
}

TEST_F(SiteDataImplTest, AllDurationGetSavedOnUnload) {
  // This test helps making sure that the observation/timestamp fields get saved
  // for all the features being tracked.
  auto local_site_data =
      GetDataImpl(kDummyOrigin, destroy_delegate_.GetWeakPtr(), &data_store_);

  const base::TimeDelta kInterval = base::Seconds(1);
  const auto kIntervalInternalRepresentation =
      TestSiteDataImpl::TimeDeltaToInternalRepresentation(kInterval);
  const auto kZeroIntervalInternalRepresentation =
      TestSiteDataImpl::TimeDeltaToInternalRepresentation(base::TimeDelta());

  // The internal representation of a zero interval is expected to be equal to
  // zero as the protobuf use variable size integers and so storing zero values
  // is really efficient (uses only one bit).
  EXPECT_EQ(0U, kZeroIntervalInternalRepresentation);

  const base::TimeDelta kInitialTimeSinceEpoch =
      base::TimeTicks::Now() - base::TimeTicks::UnixEpoch();

  local_site_data->NotifySiteLoaded();
  local_site_data->NotifyLoadedSiteBackgrounded();
  AdvanceClock(kInterval);
  // Makes use of a feature to make sure that the observation timestamps get
  // saved.
  local_site_data->NotifyUsesAudioInBackground();
  local_site_data->NotifySiteUnloaded(TabVisibility::kBackground);

  SiteDataProto expected_proto;

  auto expected_last_loaded_time =
      TestSiteDataImpl::TimeDeltaToInternalRepresentation(
          kInterval + kInitialTimeSinceEpoch);

  expected_proto.set_last_loaded(expected_last_loaded_time);

  // Features that haven't been used should have an observation duration of
  // |kIntervalInternalRepresentation| and an observation timestamp equal to
  // zero.
  SiteDataFeatureProto unused_feature_proto;
  unused_feature_proto.set_observation_duration(
      kIntervalInternalRepresentation);

  expected_proto.mutable_updates_favicon_in_background()->CopyFrom(
      unused_feature_proto);
  expected_proto.mutable_updates_title_in_background()->CopyFrom(
      unused_feature_proto);

  // The audio feature has been used, so its observation duration value should
  // be equal to zero, and its observation timestamp should be equal to the last
  // loaded time in this case (as this feature has been used right before
  // unloading).
  SiteDataFeatureProto used_feature_proto;
  used_feature_proto.set_use_timestamp(expected_last_loaded_time);
  expected_proto.mutable_uses_audio_in_background()->CopyFrom(
      used_feature_proto);

  EXPECT_EQ(
      expected_proto.SerializeAsString(),
      local_site_data->site_characteristics_for_testing().SerializeAsString());
}

// Verify that the OnDestroyDelegate gets notified when a
// SiteDataImpl object gets destroyed.
TEST_F(SiteDataImplTest, DestroyNotifiesDelegate) {
  ::testing::StrictMock<testing::MockSiteDataImplOnDestroyDelegate>
      strict_delegate;
  {
    auto local_site_data =
        GetDataImpl(kDummyOrigin, strict_delegate.GetWeakPtr(), &data_store_);
    EXPECT_CALL(strict_delegate,
                OnSiteDataImplDestroyed(local_site_data.get()));
  }
  ::testing::Mock::VerifyAndClear(&strict_delegate);
}

TEST_F(SiteDataImplTest, OnInitCallbackMergePreviousObservations) {
  // Use a mock data store to intercept the initialization callback and save it
  // locally so it can be run later. This simulates an asynchronous
  // initialization of this object and is used to test that the observations
  // made between the time this object has been created and the callback is
  // called get properly merged.
  ::testing::StrictMock<MockDataStore> mock_data_store;
  SiteDataStore::ReadSiteDataFromStoreCallback read_cb;

  auto local_site_data = GetDataImplAndInterceptReadCallback(
      kDummyOrigin, destroy_delegate_.GetWeakPtr(), &mock_data_store, &read_cb);

  // Simulates audio in background usage before the callback gets called.
  local_site_data->NotifySiteLoaded();
  local_site_data->NotifyLoadedSiteBackgrounded();
  local_site_data->NotifyUsesAudioInBackground();
  EXPECT_EQ(SiteFeatureUsage::kSiteFeatureInUse,
            local_site_data->UsesAudioInBackground());
  EXPECT_EQ(SiteFeatureUsage::kSiteFeatureUsageUnknown,
            local_site_data->UpdatesFaviconInBackground());
  EXPECT_EQ(SiteFeatureUsage::kSiteFeatureUsageUnknown,
            local_site_data->UpdatesTitleInBackground());

  // Unload the site and save the last loaded time to make sure the
  // initialization doesn't overwrite it.
  AdvanceClock(base::Seconds(1));
  local_site_data->NotifySiteUnloaded(TabVisibility::kBackground);
  AdvanceClock(base::Seconds(1));
  auto last_loaded = local_site_data->last_loaded_time_for_testing();

  // Add a couple of performance samples.
  local_site_data->NotifyLoadTimePerformanceMeasurement(
      base::Microseconds(100), base::Microseconds(1000), 2000u);
  local_site_data->NotifyLoadTimePerformanceMeasurement(
      base::Microseconds(200), base::Microseconds(500), 1000u);

  // Make sure the local performance samples are averaged as expected.
  EXPECT_EQ(2U, local_site_data->load_duration().num_datums());
  EXPECT_EQ(150, local_site_data->load_duration().value());

  EXPECT_EQ(2U, local_site_data->cpu_usage_estimate().num_datums());
  EXPECT_EQ(750.0, local_site_data->cpu_usage_estimate().value());

  EXPECT_EQ(2U, local_site_data->private_footprint_kb_estimate().num_datums());
  EXPECT_EQ(1500.0, local_site_data->private_footprint_kb_estimate().value());

  // This protobuf should have a valid |last_loaded| field and valid observation
  // durations for each features, but the |use_timestamp| field shouldn't have
  // been initialized for the features that haven't been used.
  EXPECT_TRUE(
      local_site_data->site_characteristics_for_testing().has_last_loaded());
  EXPECT_TRUE(local_site_data->site_characteristics_for_testing()
                  .uses_audio_in_background()
                  .has_use_timestamp());
  EXPECT_FALSE(local_site_data->site_characteristics_for_testing()
                   .updates_title_in_background()
                   .has_use_timestamp());
  EXPECT_TRUE(local_site_data->site_characteristics_for_testing()
                  .updates_title_in_background()
                  .has_observation_duration());
  EXPECT_FALSE(local_site_data->site_characteristics_for_testing()
                   .has_load_time_estimates());

  // Initialize a fake protobuf that indicates that this site updates its title
  // while in background and set a fake last loaded time (this should be
  // overridden once the callback runs).
  std::optional<SiteDataProto> test_proto = SiteDataProto();
  SiteDataFeatureProto unused_feature_proto = GetUnusedFeatureProto();
  test_proto->mutable_updates_title_in_background()->CopyFrom(
      GetUsedFeatureProto());
  test_proto->mutable_updates_favicon_in_background()->CopyFrom(
      unused_feature_proto);
  test_proto->mutable_uses_audio_in_background()->CopyFrom(
      unused_feature_proto);
  test_proto->set_last_loaded(42);

  // Set the previously saved performance averages.
  auto* estimates = test_proto->mutable_load_time_estimates();
  estimates->set_avg_load_duration_us(50);
  estimates->set_avg_cpu_usage_us(250);
  estimates->set_avg_footprint_kb(500);

  // Run the callback to indicate that the initialization has completed.
  std::move(read_cb).Run(test_proto);

  EXPECT_EQ(SiteFeatureUsage::kSiteFeatureInUse,
            local_site_data->UsesAudioInBackground());
  EXPECT_EQ(SiteFeatureUsage::kSiteFeatureInUse,
            local_site_data->UpdatesTitleInBackground());
  EXPECT_EQ(SiteFeatureUsage::kSiteFeatureUsageUnknown,
            local_site_data->UpdatesFaviconInBackground());
  EXPECT_EQ(last_loaded, local_site_data->last_loaded_time_for_testing());

  // Make sure the local performance samples have been updated with the previous
  // averages.
  EXPECT_EQ(3U, local_site_data->load_duration().num_datums());
  EXPECT_EQ(137.5, local_site_data->load_duration().value());

  EXPECT_EQ(3U, local_site_data->cpu_usage_estimate().num_datums());
  EXPECT_EQ(562.5, local_site_data->cpu_usage_estimate().value());

  EXPECT_EQ(3U, local_site_data->private_footprint_kb_estimate().num_datums());
  EXPECT_EQ(1125, local_site_data->private_footprint_kb_estimate().value());

  // Verify that the in-memory data is flushed to the protobuffer on write.
  EXPECT_CALL(mock_data_store,
              WriteSiteDataIntoStore(::testing::_, ::testing::_))
      .WillOnce(::testing::Invoke(
          [](const url::Origin& origin, const SiteDataProto& proto) {
            ASSERT_TRUE(proto.has_load_time_estimates());
            const auto& estimates = proto.load_time_estimates();
            ASSERT_TRUE(estimates.has_avg_load_duration_us());
            EXPECT_EQ(137.5, estimates.avg_load_duration_us());
            ASSERT_TRUE(estimates.has_avg_cpu_usage_us());
            EXPECT_EQ(562.5, estimates.avg_cpu_usage_us());
            ASSERT_TRUE(estimates.has_avg_footprint_kb());
            EXPECT_EQ(1125, estimates.avg_footprint_kb());
          }));

  local_site_data = nullptr;
  ::testing::Mock::VerifyAndClear(&mock_data_store);
}

TEST_F(SiteDataImplTest, LateAsyncReadDoesntEraseData) {
  // Ensure that no historical data get lost if an asynchronous read from the
  // data store finishes after the last reference to a SiteDataImpl gets
  // destroyed.

  ::testing::StrictMock<MockDataStore> mock_data_store;
  SiteDataStore::ReadSiteDataFromStoreCallback read_cb;

  auto local_site_data_writer = GetDataImplAndInterceptReadCallback(
      kDummyOrigin, destroy_delegate_.GetWeakPtr(), &mock_data_store, &read_cb);

  local_site_data_writer->NotifySiteLoaded();
  local_site_data_writer->NotifyLoadedSiteBackgrounded();
  local_site_data_writer->NotifyUsesAudioInBackground();
  EXPECT_EQ(SiteFeatureUsage::kSiteFeatureInUse,
            local_site_data_writer->UsesAudioInBackground());

  local_site_data_writer->NotifySiteUnloaded(TabVisibility::kBackground);

  // Releasing |local_site_data_writer| should cause this object to get
  // destroyed but there shouldn't be any write operation as the read hasn't
  // completed.
  EXPECT_CALL(destroy_delegate_, OnSiteDataImplDestroyed(::testing::_));
  EXPECT_CALL(mock_data_store,
              WriteSiteDataIntoStore(::testing::_, ::testing::_))
      .Times(0);
  local_site_data_writer = nullptr;
  ::testing::Mock::VerifyAndClear(&destroy_delegate_);
  ::testing::Mock::VerifyAndClear(&mock_data_store);

  EXPECT_TRUE(read_cb.IsCancelled());
}

TEST_F(SiteDataImplTest, LateAsyncReadDoesntBypassClearEvent) {
  ::testing::NiceMock<MockDataStore> mock_data_store;
  SiteDataStore::ReadSiteDataFromStoreCallback read_cb;

  auto local_site_data = GetDataImplAndInterceptReadCallback(
      kDummyOrigin, destroy_delegate_.GetWeakPtr(), &mock_data_store, &read_cb);

  local_site_data->NotifySiteLoaded();
  local_site_data->NotifyLoadedSiteBackgrounded();
  local_site_data->NotifyUsesAudioInBackground();
  EXPECT_EQ(SiteFeatureUsage::kSiteFeatureInUse,
            local_site_data->UsesAudioInBackground());
  local_site_data->NotifySiteUnloaded(TabVisibility::kBackground);

  // TODO(sebmarchand): Test that data is cleared here.
  local_site_data->ClearObservationsAndInvalidateReadOperation();

  EXPECT_TRUE(read_cb.IsCancelled());
}

TEST_F(SiteDataImplTest, BackgroundedCountTests) {
  auto local_site_data =
      GetDataImpl(kDummyOrigin, destroy_delegate_.GetWeakPtr(), &data_store_);

  // By default the tabs are expected to be foregrounded.
  EXPECT_EQ(0U, local_site_data->loaded_tabs_in_background_count_for_testing());

  local_site_data->NotifySiteLoaded();
  AdvanceClock(base::Seconds(1));
  local_site_data->NotifyLoadedSiteBackgrounded();

  auto background_session_begin =
      local_site_data->background_session_begin_for_testing();
  EXPECT_EQ(base::TimeTicks::Now(), background_session_begin);

  EXPECT_EQ(1U, local_site_data->loaded_tabs_in_background_count_for_testing());

  AdvanceClock(base::Seconds(1));

  // Add a second instance of this object, this one pretending to be in
  // foreground.
  auto local_site_data_copy(local_site_data);
  local_site_data_copy->NotifySiteLoaded();
  EXPECT_EQ(1U, local_site_data->loaded_tabs_in_background_count_for_testing());

  EXPECT_EQ(background_session_begin,
            local_site_data->background_session_begin_for_testing());

  AdvanceClock(base::Seconds(1));

  local_site_data->NotifyLoadedSiteForegrounded();
  EXPECT_EQ(0U, local_site_data->loaded_tabs_in_background_count_for_testing());

  auto expected_observation_duration =
      base::TimeTicks::Now() - background_session_begin;

  auto observed_observation_duration =
      local_site_data->FeatureObservationDuration(
          local_site_data->site_characteristics_for_testing()
              .updates_title_in_background());

  EXPECT_EQ(expected_observation_duration, observed_observation_duration);

  AdvanceClock(base::Seconds(1));

  local_site_data->NotifyLoadedSiteBackgrounded();
  EXPECT_EQ(1U, local_site_data->loaded_tabs_in_background_count_for_testing());
  background_session_begin =
      local_site_data->background_session_begin_for_testing();
  EXPECT_EQ(base::TimeTicks::Now(), background_session_begin);

  local_site_data->NotifySiteUnloaded(TabVisibility::kBackground);
  local_site_data_copy->NotifySiteUnloaded(TabVisibility::kForeground);
}

TEST_F(SiteDataImplTest, OptionalFieldsNotPopulatedWhenClean) {
  ::testing::StrictMock<MockDataStore> mock_data_store;
  SiteDataStore::ReadSiteDataFromStoreCallback read_cb;

  auto local_site_data = GetDataImplAndInterceptReadCallback(
      kDummyOrigin, destroy_delegate_.GetWeakPtr(), &mock_data_store, &read_cb);

  EXPECT_EQ(0u, local_site_data->cpu_usage_estimate().num_datums());
  EXPECT_EQ(0u, local_site_data->private_footprint_kb_estimate().num_datums());

  std::optional<SiteDataProto> test_proto = SiteDataProto();

  // Run the callback to indicate that the initialization has completed.
  std::move(read_cb).Run(test_proto);

  // There still should be no perf data.
  EXPECT_EQ(0u, local_site_data->cpu_usage_estimate().num_datums());
  EXPECT_EQ(0u, local_site_data->private_footprint_kb_estimate().num_datums());

  // Dirty the record to force a write.
  local_site_data->NotifySiteLoaded();
  local_site_data->NotifyLoadedSiteBackgrounded();
  local_site_data->NotifyUsesAudioInBackground();

  // Verify that the saved protobuffer isn't populated with the perf fields.
  EXPECT_CALL(mock_data_store,
              WriteSiteDataIntoStore(::testing::_, ::testing::_))
      .WillOnce(::testing::Invoke(
          [](const url::Origin& origin, const SiteDataProto& proto) {
            ASSERT_FALSE(proto.has_load_time_estimates());
          }));

  local_site_data->NotifySiteUnloaded(TabVisibility::kBackground);
  local_site_data = nullptr;
  ::testing::Mock::VerifyAndClear(&mock_data_store);
}

TEST_F(SiteDataImplTest, FlushingStateToProtoDoesntAffectData) {
  // Create 2 DataImpl object and do the same operations on them, ensures that
  // calling FlushStateToProto doesn't affect the data that gets recorded.

  auto local_site_data =
      GetDataImpl(kDummyOrigin, destroy_delegate_.GetWeakPtr(), &data_store_);
  auto local_site_data_ref =
      GetDataImpl(kDummyOrigin2, destroy_delegate_.GetWeakPtr(), &data_store_);

  local_site_data->NotifySiteLoaded();
  local_site_data->NotifyLoadedSiteBackgrounded();
  local_site_data_ref->NotifySiteLoaded();
  local_site_data_ref->NotifyLoadedSiteBackgrounded();

  AdvanceClock(base::Seconds(15));
  local_site_data->FlushStateToProto();
  AdvanceClock(base::Seconds(15));

  local_site_data->NotifyUsesAudioInBackground();
  local_site_data_ref->NotifyUsesAudioInBackground();

  local_site_data->FlushStateToProto();

  EXPECT_EQ(local_site_data->FeatureObservationTimestamp(
                local_site_data->site_characteristics_for_testing()
                    .uses_audio_in_background()),
            local_site_data_ref->FeatureObservationTimestamp(
                local_site_data_ref->site_characteristics_for_testing()
                    .uses_audio_in_background()));

  EXPECT_EQ(local_site_data->FeatureObservationDuration(
                local_site_data->site_characteristics_for_testing()
                    .updates_title_in_background()),
            local_site_data_ref->FeatureObservationDuration(
                local_site_data_ref->site_characteristics_for_testing()
                    .updates_title_in_background()));

  local_site_data->NotifySiteUnloaded(TabVisibility::kBackground);
  local_site_data_ref->NotifySiteUnloaded(TabVisibility::kBackground);
}

TEST_F(SiteDataImplTest, DataLoadedCallbackInvoked) {
  ::testing::StrictMock<MockDataStore> mock_data_store;
  SiteDataStore::ReadSiteDataFromStoreCallback read_cb;

  auto local_site_data = GetDataImplAndInterceptReadCallback(
      kDummyOrigin, destroy_delegate_.GetWeakPtr(), &mock_data_store, &read_cb);

  EXPECT_FALSE(local_site_data->DataLoaded());

  bool callback_invoked = false;
  local_site_data->RegisterDataLoadedCallback(
      base::BindLambdaForTesting([&]() { callback_invoked = true; }));

  // Run the callback to indicate that the initialization has completed.
  std::optional<SiteDataProto> test_proto = SiteDataProto();
  std::move(read_cb).Run(test_proto);

  EXPECT_TRUE(callback_invoked);
  EXPECT_TRUE(local_site_data->DataLoaded());
}

}  // namespace internal
}  // namespace performance_manager