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

base / power_monitor / battery_state_sampler_unittest.cc [blame]

// Copyright 2022 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/power_monitor/battery_state_sampler.h"

#include <queue>
#include <utility>

#include "base/power_monitor/power_monitor_buildflags.h"
#include "base/power_monitor/sampling_event_source.h"
#include "base/run_loop.h"
#include "base/task/sequenced_task_runner.h"
#include "base/test/bind.h"
#include "base/test/gtest_util.h"
#include "base/test/power_monitor_test_utils.h"
#include "base/test/task_environment.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace base {

class TestBatteryLevelProvider : public BatteryLevelProvider {
 public:
  TestBatteryLevelProvider() = default;
  ~TestBatteryLevelProvider() override = default;

  void GetBatteryState(OnceCallback<void(const std::optional<BatteryState>&)>
                           callback) override {
    DCHECK(!battery_states_.empty());

    auto next_battery_state = std::move(battery_states_.front());
    battery_states_.pop();

    std::move(callback).Run(next_battery_state);
  }

  void PushBatteryState(const std::optional<BatteryState>& battery_state) {
    battery_states_.push(battery_state);
  }

 protected:
  std::queue<std::optional<BatteryState>> battery_states_;
};

class TestBatteryLevelProviderAsync : public TestBatteryLevelProvider {
 public:
  TestBatteryLevelProviderAsync() = default;
  ~TestBatteryLevelProviderAsync() override = default;

  void GetBatteryState(OnceCallback<void(const std::optional<BatteryState>&)>
                           callback) override {
    DCHECK(!battery_states_.empty());

    auto next_battery_state = std::move(battery_states_.front());
    battery_states_.pop();

    SequencedTaskRunner::GetCurrentDefault()->PostTask(
        FROM_HERE,
        BindLambdaForTesting([callback = std::move(callback),
                              battery_state = next_battery_state]() mutable {
          std::move(callback).Run(battery_state);
        }));
  }
};

// A test observer that exposes the last battery state received.
class TestObserver : public BatteryStateSampler::Observer {
 public:
  TestObserver() = default;
  ~TestObserver() override = default;

  void OnBatteryStateSampled(
      const std::optional<BatteryLevelProvider::BatteryState>& battery_state)
      override {
    battery_state_ = battery_state;
  }

  std::optional<BatteryLevelProvider::BatteryState> battery_state() const {
    return battery_state_;
  }

 private:
  std::optional<BatteryLevelProvider::BatteryState> battery_state_;
};

// Those test battery states just need to be different. The actual values don't
// matter.
const std::optional<BatteryLevelProvider::BatteryState> kTestBatteryState1 =
    BatteryLevelProvider::BatteryState{
        .battery_count = 1,
        .is_external_power_connected = false,
        .current_capacity = 10000,
        .full_charged_capacity = 10000,
        .charge_unit = BatteryLevelProvider::BatteryLevelUnit::kMWh};
const std::optional<BatteryLevelProvider::BatteryState> kTestBatteryState2 =
    BatteryLevelProvider::BatteryState{
        .battery_count = 1,
        .is_external_power_connected = false,
        .current_capacity = 5000,
        .full_charged_capacity = 10000,
        .charge_unit = BatteryLevelProvider::BatteryLevelUnit::kMWh};
const std::optional<BatteryLevelProvider::BatteryState> kTestBatteryState3 =
    BatteryLevelProvider::BatteryState{
        .battery_count = 1,
        .is_external_power_connected = true,
        .current_capacity = 2000,
        .full_charged_capacity = 10000,
        .charge_unit = BatteryLevelProvider::BatteryLevelUnit::kMWh};

bool operator==(const BatteryLevelProvider::BatteryState& lhs,
                const BatteryLevelProvider::BatteryState& rhs) {
  return std::tie(lhs.battery_count, lhs.is_external_power_connected,
                  lhs.current_capacity, lhs.full_charged_capacity,
                  lhs.charge_unit) ==
         std::tie(rhs.battery_count, rhs.is_external_power_connected,
                  rhs.current_capacity, rhs.full_charged_capacity,
                  rhs.charge_unit);
}

bool operator!=(const BatteryLevelProvider::BatteryState& lhs,
                const BatteryLevelProvider::BatteryState& rhs) {
  return !(lhs == rhs);
}

TEST(BatteryStateSamplerTest, GlobalInstance) {
#if BUILDFLAG(HAS_BATTERY_LEVEL_PROVIDER_IMPL) || BUILDFLAG(IS_CHROMEOS_ASH)
  // Get() DCHECKs on platforms with a battery level provider if it's called
  // without being initialized. ChromeOS behaves the same because it has a
  // `BatteryLevelProvider`, but it doesn't live in base so it doesn't exist in
  // this test.
  EXPECT_DCHECK_DEATH(BatteryStateSampler::Get());
#else
  // Get() returns null if the sampler doesn't exist on platforms without a
  // battery level provider.
  EXPECT_FALSE(BatteryStateSampler::Get());
#endif

  auto battery_level_provider = std::make_unique<TestBatteryLevelProvider>();
  battery_level_provider->PushBatteryState(kTestBatteryState1);

  // Create the sampler.
  auto battery_state_sampler = std::make_unique<BatteryStateSampler>(
      std::make_unique<test::TestSamplingEventSource>(),
      std::move(battery_level_provider));

  // Now the getter works.
  EXPECT_TRUE(BatteryStateSampler::Get());

  // Can't create a second sampler.
  EXPECT_DCHECK_DEATH({
    BatteryStateSampler another_battery_state_sampler(
        std::make_unique<test::TestSamplingEventSource>(),
        std::make_unique<TestBatteryLevelProvider>());
  });

  battery_state_sampler.reset();

  // The sampler no longer exists.
#if BUILDFLAG(HAS_BATTERY_LEVEL_PROVIDER_IMPL) || BUILDFLAG(IS_CHROMEOS_ASH)
  EXPECT_DCHECK_DEATH(BatteryStateSampler::Get());
#else
  EXPECT_FALSE(BatteryStateSampler::Get());
#endif
}

TEST(BatteryStateSamplerTest, InitialSample) {
  auto sampling_event_source =
      std::make_unique<test::TestSamplingEventSource>();

  auto battery_level_provider = std::make_unique<TestBatteryLevelProvider>();
  // Push the initial battery state that will be queried by the sampler.
  battery_level_provider->PushBatteryState(kTestBatteryState1);

  BatteryStateSampler battery_state_sampler(std::move(sampling_event_source),
                                            std::move(battery_level_provider));

  TestObserver observer;
  battery_state_sampler.AddObserver(&observer);

  EXPECT_EQ(observer.battery_state(), kTestBatteryState1);
}

TEST(BatteryStateSamplerTest, MultipleSamples) {
  auto battery_level_provider = std::make_unique<TestBatteryLevelProvider>();
  // Push the initial battery state and the first 3 samples after it.
  battery_level_provider->PushBatteryState(kTestBatteryState1);
  battery_level_provider->PushBatteryState(kTestBatteryState2);
  battery_level_provider->PushBatteryState(kTestBatteryState3);
  battery_level_provider->PushBatteryState(kTestBatteryState1);

  auto sampling_event_source =
      std::make_unique<test::TestSamplingEventSource>();
  auto* sampling_event_source_ptr = sampling_event_source.get();

  BatteryStateSampler battery_state_sampler(std::move(sampling_event_source),
                                            std::move(battery_level_provider));

  TestObserver observer;
  battery_state_sampler.AddObserver(&observer);
  EXPECT_EQ(observer.battery_state(), kTestBatteryState1);

  // Simulate 2 events to trigger 2 more samples.
  sampling_event_source_ptr->SimulateEvent();
  EXPECT_EQ(observer.battery_state(), kTestBatteryState2);
  sampling_event_source_ptr->SimulateEvent();
  EXPECT_EQ(observer.battery_state(), kTestBatteryState3);

  battery_state_sampler.RemoveObserver(&observer);

  // Simulate 1 event and ensure the observer does not receive the new state.
  sampling_event_source_ptr->SimulateEvent();
  EXPECT_NE(observer.battery_state(), kTestBatteryState1);
}

TEST(BatteryStateSamplerTest, MultipleObservers) {
  auto battery_level_provider = std::make_unique<TestBatteryLevelProvider>();
  // Push the initial battery state and the first sample after it.
  battery_level_provider->PushBatteryState(kTestBatteryState1);
  battery_level_provider->PushBatteryState(kTestBatteryState2);

  auto sampling_event_source =
      std::make_unique<test::TestSamplingEventSource>();
  auto* sampling_event_source_ptr = sampling_event_source.get();

  BatteryStateSampler battery_state_sampler(std::move(sampling_event_source),
                                            std::move(battery_level_provider));

  // Add 2 observers.
  TestObserver observer1;
  battery_state_sampler.AddObserver(&observer1);
  EXPECT_EQ(observer1.battery_state(), kTestBatteryState1);
  TestObserver observer2;
  battery_state_sampler.AddObserver(&observer2);
  EXPECT_EQ(observer2.battery_state(), kTestBatteryState1);

  // Simulate an event to get another sample.
  sampling_event_source_ptr->SimulateEvent();
  EXPECT_EQ(observer1.battery_state(), kTestBatteryState2);
  EXPECT_EQ(observer2.battery_state(), kTestBatteryState2);
}

// Tests that if sampling the battery state is asynchronous (like it is on
// Windows), the sampler will correctly notify new observers when the first
// sample arrives.
TEST(BatteryStateSamplerTest, InitialSample_Async) {
  test::SingleThreadTaskEnvironment task_environment;

  auto battery_level_provider =
      std::make_unique<TestBatteryLevelProviderAsync>();
  // Push the initial battery state.
  battery_level_provider->PushBatteryState(kTestBatteryState1);

  auto sampling_event_source =
      std::make_unique<test::TestSamplingEventSource>();

  // Creating the sampler starts the first async sample.
  BatteryStateSampler battery_state_sampler(std::move(sampling_event_source),
                                            std::move(battery_level_provider));

  TestObserver observer;
  battery_state_sampler.AddObserver(&observer);
  EXPECT_EQ(observer.battery_state(), std::nullopt);

  RunLoop().RunUntilIdle();
  EXPECT_EQ(observer.battery_state(), kTestBatteryState1);
}

}  // namespace base