File: traffic_counters_handler_unittest.cc

package info (click to toggle)
chromium 138.0.7204.183-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 6,071,908 kB
  • sloc: cpp: 34,937,088; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,953; asm: 946,768; xml: 739,971; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,806; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (501 lines) | stat: -rw-r--r-- 18,077 bytes parent folder | download | duplicates (8)
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
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chromeos/ash/components/network/traffic_counters_handler.h"

#include <optional>
#include <string>

#include "base/functional/bind.h"
#include "base/test/task_environment.h"
#include "base/test/scoped_feature_list.h"
#include "base/time/clock.h"
#include "base/time/time.h"
#include "base/values.h"
#include "chromeos/ash/components/login/login_state/login_state.h"
#include "chromeos/ash/components/network/managed_network_configuration_handler.h"
#include "chromeos/ash/components/network/network_configuration_handler.h"
#include "chromeos/ash/components/network/network_handler_test_helper.h"
#include "chromeos/ash/components/network/network_metadata_store.h"
#include "chromeos/ash/components/network/network_profile_handler.h"
#include "components/proxy_config/pref_proxy_config_tracker_impl.h"
#include "components/sync_preferences/testing_pref_service_syncable.h"
#include "components/user_manager/fake_user_manager.h"
#include "components/user_manager/scoped_user_manager.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/cros_system_api/dbus/shill/dbus-constants.h"

namespace ash {
namespace traffic_counters {

namespace {

const char kDecLastResetTime[] = "Fri, 15 December 2023 10:00:00 UTC";

class TrafficCountersHandlerTest : public ::testing::Test {
 public:
  TrafficCountersHandlerTest()
      : task_environment_(base::test::TaskEnvironment::TimeSource::MOCK_TIME) {
    //  TODO(b/278643115) Remove LoginState dependency.
    LoginState::Initialize();

    scoped_user_manager_ = std::make_unique<user_manager::ScopedUserManager>(
        std::make_unique<user_manager::FakeUserManager>());

    feature_list_.InitWithFeatures(
      /*enabled_features=*/{features::kTrafficCountersEnabled,
      features::kTrafficCountersForWiFiTesting}, /*disabled_features=*/{});

    helper_ = std::make_unique<NetworkHandlerTestHelper>();
    helper_->AddDefaultProfiles();
    helper_->ResetDevicesAndServices();
    helper_->RegisterPrefs(user_prefs_.registry(), local_state_.registry());

    PrefProxyConfigTrackerImpl::RegisterProfilePrefs(user_prefs_.registry());
    PrefProxyConfigTrackerImpl::RegisterPrefs(local_state_.registry());
    helper_->InitializePrefs(&user_prefs_, &local_state_);

    NetworkHandler::Get()->managed_network_configuration_handler()->SetPolicy(
        ::onc::ONC_SOURCE_DEVICE_POLICY,
        /*userhash=*/std::string(),
        /*network_configs_onc=*/base::Value::List(),
        /*global_network_config=*/base::Value::Dict());

    task_environment_.RunUntilIdle();

    helper_->service_test()->SetTimeGetterForTest(base::BindRepeating(
        [](base::test::TaskEnvironment* env) {
          return env->GetMockClock()->Now();
        },
        &task_environment_));

    TrafficCountersHandler::InitializeForTesting();
    TrafficCountersHandler::Get()->SetTimeGetterForTesting(
      base::BindRepeating(
        [](base::test::TaskEnvironment* env) {
          return env->GetMockClock()->Now();
        },
        &task_environment_));

    SetUpWiFi();
  }

  ~TrafficCountersHandlerTest() override {
    TrafficCountersHandler::Shutdown();
    helper_.reset();
    scoped_user_manager_.reset();
    LoginState::Shutdown();
  }

  base::Time GetTime() { return task_environment_.GetMockClock()->Now(); }

 protected:
  base::Time SetLastResetTimeAndRun(const std::string& time_str) {
    base::Time reset_time = GetTimeFromString(time_str);
    double last_reset_time_ms =
        reset_time.ToDeltaSinceWindowsEpoch().InMilliseconds();
    SetServiceProperty(wifi_path_, shill::kTrafficCounterResetTimeProperty,
                       base::Value(last_reset_time_ms));
    task_environment_.RunUntilIdle();
    RunTrafficCountersHandler();
    return reset_time;
  }

  base::Time GetLastResetTime() {
    double traffic_counter_reset_time_ms =
        helper_
            ->GetServiceDoubleProperty(wifi_path_,
                                       shill::kTrafficCounterResetTimeProperty)
            .value();
    return base::Time::FromDeltaSinceWindowsEpoch(
        base::Milliseconds(traffic_counter_reset_time_ms));
  }

  void SetResetDay(int user_specified_day) {
    NetworkHandler::Get()
        ->network_metadata_store()
        ->SetDayOfTrafficCountersAutoReset(wifi_guid_, user_specified_day);
    task_environment_.RunUntilIdle();
  }

  base::Time AdvanceClockTo(const std::string& time_str) {
    base::Time time = GetTimeFromString(time_str);
    task_environment_.AdvanceClock(
        time.ToDeltaSinceWindowsEpoch() -
        task_environment_.GetMockClock()->Now().ToDeltaSinceWindowsEpoch());
    task_environment_.RunUntilIdle();
    return task_environment_.GetMockClock()->Now();
  }

  void RunTrafficCountersHandler() {
    TrafficCountersHandler::Get()->RunForTesting();
    task_environment_.RunUntilIdle();
  }

  void FastForwardBy(const base::TimeDelta& days) {
    task_environment_.FastForwardBy(days);
  }

  void RunUntilIdle() { task_environment_.RunUntilIdle(); }

  TrafficCountersHandler* traffic_counters_handler() {
    return TrafficCountersHandler::Get();
  }

  const std::string& wifi_guid() const { return wifi_guid_; }
  const std::string& wifi_path() const { return wifi_path_; }

 private:
  void SetUpWiFi() {
    ASSERT_TRUE(wifi_path_.empty());
    // By default, NetworkStateTestHelper already adds a WiFi device, so, we
    // do not need to add one here. All that remains to be done is configuring
    // the WiFi service.
    wifi_guid_ = "wifi_guid";
    wifi_path_ = helper_->ConfigureService(
        R"({"GUID": "wifi_guid", "Type": "wifi", "State": "idle",
            "SSID": "wifi", "Strength": 100, "AutoConnect": true,
            "WiFi.HiddenSSID": false, "TrafficCounterResetTime": 0})");
    SetServiceProperty(wifi_path_, shill::kStateProperty,
                       base::Value(shill::kStateOnline));
    helper_->profile_test()->AddService(
        NetworkProfileHandler::GetSharedProfilePath(), wifi_path_);
    task_environment_.RunUntilIdle();
  }

  base::Time GetTimeFromString(const std::string& time_str) {
    base::Time time;
    EXPECT_TRUE(base::Time::FromString(time_str.c_str(), &time));
    return time;
  }

  void SetServiceProperty(const std::string& service_path,
                          const std::string& key,
                          const base::Value& value) {
    helper_->SetServiceProperty(service_path, key, value);
  }

  // Member order declaration done in a way so that members outlive those that
  // are dependent on them.
  base::test::TaskEnvironment task_environment_;
  base::test::ScopedFeatureList feature_list_;
  std::unique_ptr<user_manager::ScopedUserManager> scoped_user_manager_;
  std::unique_ptr<NetworkHandlerTestHelper> helper_;
  sync_preferences::TestingPrefServiceSyncable user_prefs_;
  TestingPrefServiceSimple local_state_;
  std::string wifi_path_;
  std::string wifi_guid_;
};

}  // namespace

TEST_F(TrafficCountersHandlerTest, GetLastResetTime) {
  // Set the task_environment time to |kDecLastResetTime, ensuring that
  // the base::Now() (simulated "current" time) returns this value.
  AdvanceClockTo(kDecLastResetTime);

  base::Time reset_time =
      SetLastResetTimeAndRun(kDecLastResetTime);
  EXPECT_EQ(GetLastResetTime(), reset_time);
}

TEST_F(TrafficCountersHandlerTest, SetUserSpecifiedResetDay) {
  RunTrafficCountersHandler();
  NetworkHandler::Get()
      ->network_metadata_store()
      ->SetDayOfTrafficCountersAutoReset(wifi_guid(), 13);
  RunUntilIdle();
  const base::Value* reset_day_value =
      NetworkHandler::Get()
          ->network_metadata_store()
          ->GetDayOfTrafficCountersAutoReset(wifi_guid());
  ASSERT_TRUE(reset_day_value && reset_day_value->is_int());
  EXPECT_EQ(reset_day_value->GetInt(), 13);
}

TEST_F(TrafficCountersHandlerTest, FirstOfMonth) {
  AdvanceClockTo(kDecLastResetTime);
  base::Time reset_time =
      SetLastResetTimeAndRun(kDecLastResetTime);
  EXPECT_EQ(GetLastResetTime(), reset_time);

  SetResetDay(1);

  // Advance the clock to Jan 1st, 2024. The counters should get reset.
  base::Time simulated_time1 =
      AdvanceClockTo("Mon, 1 January 2024 07:01:00 UTC");

  RunTrafficCountersHandler();
  EXPECT_EQ(GetLastResetTime(), simulated_time1);
}

TEST_F(TrafficCountersHandlerTest, EndOfMonth) {
  const std::string last_reset_time_string = "Fri, 1 March 2024 07:01:00 UTC";
  AdvanceClockTo(last_reset_time_string);
  SetLastResetTimeAndRun(last_reset_time_string);

  // Adjust the user specified day to the 15th and ensure that a reset occurs
  // on March 15th.
  SetResetDay(15);
  base::Time simulated_time = AdvanceClockTo("Fri, 15 March 2024 07:01:00 UTC");
  RunTrafficCountersHandler();
  EXPECT_EQ(GetLastResetTime(), simulated_time);

  // Adjust the user specified day to the 14th and fast forward by 1 day to
  // March 16th. Ensure that no reset occurs on March 16th.
  SetResetDay(14);
  FastForwardBy(base::Days(1));
  RunTrafficCountersHandler();
  EXPECT_EQ(GetLastResetTime(), simulated_time);

  // Adjust the user specified day to the 31st and Fast forward to Mar 31st.
  // Ensure that a reset occurs.
  SetResetDay(31);
  simulated_time = AdvanceClockTo("Sun, 31 March 2024 07:01:00 UTC");
  RunTrafficCountersHandler();
  EXPECT_EQ(GetLastResetTime(), simulated_time);

  // Advance the clock to Apr 30th and ensure auto reset occurs on April
  // 30th since April 31st does not exist.
  simulated_time = AdvanceClockTo("Tue, 30 Apr 2024 07:01:00 UTC");
  RunTrafficCountersHandler();
  EXPECT_EQ(GetLastResetTime(), simulated_time);

  // Fast forward by 1 day to May 1st and ensure no auto reset occurs.
  FastForwardBy(base::Days(1));
  RunTrafficCountersHandler();
  EXPECT_EQ(GetLastResetTime(), simulated_time);

  // Advance the clock to May 31st and ensure reset occurs.
  simulated_time = AdvanceClockTo("Fri, 31 May 2024 07:01:00 UTC");
  RunTrafficCountersHandler();
  EXPECT_EQ(GetLastResetTime(), simulated_time);
}

TEST_F(TrafficCountersHandlerTest, LeapYear) {
  // Set last reset time.
  AdvanceClockTo(kDecLastResetTime);
  base::Time reset_time =
      SetLastResetTimeAndRun(kDecLastResetTime);
  EXPECT_EQ(GetLastResetTime(), reset_time);

  // The first traffic counters reset is expected on Jan 1st.
  SetResetDay(1);
  base::Time simulated_time =
      AdvanceClockTo("Mon, 1 January 2024 07:01:00 UTC");
  RunTrafficCountersHandler();
  EXPECT_EQ(GetLastResetTime(), simulated_time);

  // Fast forwarding the date by 15 days to Jan 16th should not affect the
  // last reset time.
  FastForwardBy(base::Days(15));
  RunTrafficCountersHandler();
  EXPECT_EQ(GetLastResetTime(), simulated_time);

  // Fast forwarding the date to Feb 1st should update the last reset time.
  simulated_time = AdvanceClockTo("Thu, 1 February 2024 07:01:00 UTC");
  RunTrafficCountersHandler();
  EXPECT_EQ(GetLastResetTime(), simulated_time);

  // After fast forwarding the date by 28 days to Feb 29th, ensure February
  // 29th on leap years does not reset traffic counters when the user
  // specified day is the 1st.
  FastForwardBy(base::Days(28));
  RunTrafficCountersHandler();
  EXPECT_EQ(GetLastResetTime(), simulated_time);

  // After fast forwarding the date to Mar 1st, ensure that two auto
  // traffic counter resets do not occur on the same day.
  // First, ensure traffic counters are reset on March 1st.
  simulated_time = AdvanceClockTo("Fri, 1 March 2024 07:01:00 UTC");
  RunTrafficCountersHandler();
  EXPECT_EQ(GetLastResetTime(), simulated_time);

  // Second, run TrafficCountersHandler later on Mar 1st to ensure
  // that another reset doesn't occur.
  FastForwardBy(base::Hours(12));
  RunTrafficCountersHandler();
  EXPECT_EQ(GetLastResetTime(), simulated_time);
}

TEST_F(TrafficCountersHandlerTest, NoLeapYear) {
  // Set last reset time.
  const std::string last_reset_time_string =
    "Sat, 15 January 2023 10:00:00 UTC";
  AdvanceClockTo(last_reset_time_string);
  base::Time reset_time =
      SetLastResetTimeAndRun(last_reset_time_string);
  EXPECT_EQ(GetLastResetTime(), reset_time);

  // Set the reset day.
  SetResetDay(31);

  // Adjust the clock to set the "current time". Use Jan 31st, 2023
  // to test whether the functionality is correct on non-leap years.
  base::Time simulated_time =
      AdvanceClockTo("Tue, 31 January 2023 07:01:00 UTC");
  RunTrafficCountersHandler();

  // The first traffic counters reset is expected on Jan 31st.
  EXPECT_EQ(GetLastResetTime(), simulated_time);

  // After fast forwarding the date to Feb 28th, ensure traffic
  // counters are reset on February 28th on non-leap years when the user
  // specified day is the 31st.
  simulated_time = AdvanceClockTo("Tue, 28 February 2023 07:01:00 UTC");
  RunTrafficCountersHandler();
  EXPECT_EQ(GetLastResetTime(), simulated_time);

  // After fast forwarding the date by 1 day to Mar 1st, ensure traffic
  // counters are not reset again.
  FastForwardBy(base::Days(1));
  RunTrafficCountersHandler();
  EXPECT_EQ(GetLastResetTime(), simulated_time);

  // After fast forwarding the date by 27 days to March 28th, ensure a
  // traffic counter reset has not occurred.
  FastForwardBy(base::Days(27));
  RunTrafficCountersHandler();
  EXPECT_EQ(GetLastResetTime(), simulated_time);

  // After fast forwarding by 2 days to March 30th, ensure a traffic counter
  // reset has not occurred.
  FastForwardBy(base::Days(2));
  RunTrafficCountersHandler();
  EXPECT_EQ(GetLastResetTime(), simulated_time);

  // After fast forwarding the date by 1 day to March 31st, ensure a traffic
  // counter reset occurs.
  simulated_time = AdvanceClockTo("Fri, 31 March 2023 07:01:00 UTC");
  RunTrafficCountersHandler();
  EXPECT_EQ(GetLastResetTime(), simulated_time);
}

TEST_F(TrafficCountersHandlerTest, ChangeUserSpecifiedDate) {
  // Set last reset time.
  const std::string last_reset_time_string =
    "Sat, 15 January 2023 10:00:00 UTC";
  AdvanceClockTo(last_reset_time_string);
  base::Time reset_time =
      SetLastResetTimeAndRun(last_reset_time_string);
  EXPECT_EQ(GetLastResetTime(), reset_time);

  // Advancing the date to Jan 31st should reset the traffic counters.
  SetResetDay(31);
  base::Time simulated_time =
      AdvanceClockTo("Tue, 31 January 2023 07:01:00 UTC");
  RunTrafficCountersHandler();
  EXPECT_EQ(GetLastResetTime(), simulated_time);

  // Change user specified auto reset day.
  SetResetDay(5);
  RunTrafficCountersHandler();

  // After fast forwarding the date to February 5th, ensure traffic counters
  // are reset.
  simulated_time = AdvanceClockTo("Sun, 5 February 2023 07:01:00 UTC");
  RunTrafficCountersHandler();
  EXPECT_EQ(GetLastResetTime(), simulated_time);
}

TEST_F(TrafficCountersHandlerTest, RunFromStart) {
  // Set last reset time.
  const std::string last_reset_time_string =
    "Sat, 15 January 2023 10:00:00 UTC";
  AdvanceClockTo(last_reset_time_string);
  base::Time reset_time =
      SetLastResetTimeAndRun(last_reset_time_string);
  EXPECT_EQ(GetLastResetTime(), reset_time);

  // Set the reset day.
  SetResetDay(1);

  // Start the traffic counters timer.
  traffic_counters_handler()->StartAutoResetForTesting();
  RunUntilIdle();

  // Advance the clock to Jan 2nd, 2024. The timer should run and the
  // counters should get reset.
  base::Time simulated_time =
      AdvanceClockTo("Tue, 2 January 2024 07:01:00 UTC");
  EXPECT_EQ(GetLastResetTime(), simulated_time);
}

TEST_F(TrafficCountersHandlerTest, FastForward40Days) {
  // Set the clock to the specified time and then run traffic counters.
  base::Time simulated_time =
      AdvanceClockTo("Sun, 5 February 2023 07:01:00 UTC");
  RunTrafficCountersHandler();

  // Since no last_reset_time was available in the model, a reset should
  // occur at the time specified above.
  EXPECT_EQ(GetLastResetTime(), simulated_time);

  // Simulate a device shutdown for 40 days.
  simulated_time = AdvanceClockTo("2023-03-17 07:01:00.000000 UTC");

  // Once device is up and running, run TrafficCountersHandler and confirm
  // that reset date is correct.
  RunTrafficCountersHandler();
  EXPECT_EQ(GetLastResetTime(), simulated_time);
}

TEST_F(TrafficCountersHandlerTest, ChangeResetDayToDayGreaterThanCurrentDay)
{
  // Set last reset time.
  base::Time simulated_time = AdvanceClockTo(kDecLastResetTime);

  // Start the traffic counters timer.
  traffic_counters_handler()->StartAutoResetForTesting();
  RunUntilIdle();

  // Confirm the reset time.
  EXPECT_EQ(GetLastResetTime(), simulated_time);

  // Set the reset day.
  SetResetDay(20);

  // Set simulated time.
  const std::string current_time = "Wed, 20 December 2023 10:00:00 UTC";
  simulated_time = AdvanceClockTo(current_time);
  base::Time reset_time = SetLastResetTimeAndRun(current_time);
  EXPECT_EQ(GetLastResetTime(), reset_time);
}

TEST_F(TrafficCountersHandlerTest, RequestTrafficCounters) {
  base::RunLoop run_loop;
  traffic_counters_handler()->RequestTrafficCounters(
    wifi_path(),
    base::BindOnce(
    [](base::OnceClosure quit_closure,
      std::optional<base::Value> traffic_counters) {
      EXPECT_TRUE(traffic_counters.has_value() && traffic_counters->is_list() &&
                  !traffic_counters->GetList().empty());
      std::move(quit_closure).Run();
    },
    run_loop.QuitClosure()));
    run_loop.Run();
}

TEST_F(TrafficCountersHandlerTest, ResetTrafficCounters) {
  traffic_counters_handler()->ResetTrafficCounters(wifi_path());
  RunUntilIdle();

  base::RunLoop run_loop;
  traffic_counters_handler()->RequestTrafficCounters(
    wifi_path(),
    base::BindOnce(
    [](base::OnceClosure quit_closure,
      std::optional<base::Value> traffic_counters) {
      EXPECT_TRUE(traffic_counters.has_value() && traffic_counters->is_list() &&
                  traffic_counters->GetList().empty());
      std::move(quit_closure).Run();
    },
    run_loop.QuitClosure()));
    run_loop.Run();
}

}  // namespace traffic_counters

}  // namespace ash