blob: 18705bda82fe39a79156f4d0339e43081f4689d1 [file] [log] [blame]
Alex Deymoaea4c1c2015-08-19 20:24:43 -07001//
2// Copyright (C) 2012 The Android Open Source Project
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15//
Darin Petkovf42cc1c2010-09-01 09:03:02 -070016
Amin Hassaniec7bc112020-10-29 16:47:58 -070017#include "update_engine/cros/update_attempter.h"
Alex Deymo2c0db7b2014-11-04 12:23:39 -080018
Ben Chan9abb7632014-08-07 00:10:53 -070019#include <stdint.h>
20
Jae Hoon Kim051627a2019-09-03 12:56:32 -070021#include <limits>
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -070022#include <map>
Ben Chan02f7c1d2014-10-18 15:18:02 -070023#include <memory>
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -070024#include <string>
Jae Hoon Kimedb65502019-06-14 11:52:17 -070025#include <unordered_set>
Ben Chan02f7c1d2014-10-18 15:18:02 -070026
Ben Chan06c76a42014-09-05 08:21:06 -070027#include <base/files/file_util.h>
Miriam Polzeraff72002020-08-27 08:20:39 +020028#include <base/files/scoped_temp_dir.h>
Qijiang Fanb0b6cc22020-10-15 21:54:11 +090029#include <base/task/single_thread_task_executor.h>
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -070030#include <brillo/message_loops/base_message_loop.h>
31#include <brillo/message_loops/message_loop.h>
32#include <brillo/message_loops/message_loop_utils.h>
Darin Petkovf42cc1c2010-09-01 09:03:02 -070033#include <gtest/gtest.h>
Patrick Dubroy7fbbe8a2011-08-01 17:28:22 +020034#include <policy/libpolicy.h>
35#include <policy/mock_device_policy.h>
Marton Hunyadye58bddb2018-04-10 20:27:26 +020036#include <policy/mock_libpolicy.h>
Darin Petkovf42cc1c2010-09-01 09:03:02 -070037
Jae Hoon Kim0ae8fe12019-06-26 14:32:50 -070038#include "update_engine/common/constants.h"
Xiaochu Liu8ba486f2018-11-06 11:14:10 -080039#include "update_engine/common/dlcservice_interface.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080040#include "update_engine/common/fake_prefs.h"
Alex Deymo14fd1ec2016-02-24 22:03:57 -080041#include "update_engine/common/mock_action.h"
42#include "update_engine/common/mock_action_processor.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080043#include "update_engine/common/mock_http_fetcher.h"
44#include "update_engine/common/mock_prefs.h"
Amin Hassaniec7bc112020-10-29 16:47:58 -070045#include "update_engine/common/mock_service_observer.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080046#include "update_engine/common/platform_constants.h"
47#include "update_engine/common/prefs.h"
48#include "update_engine/common/test_utils.h"
49#include "update_engine/common/utils.h"
Amin Hassaniec7bc112020-10-29 16:47:58 -070050#include "update_engine/cros/fake_system_state.h"
51#include "update_engine/cros/mock_p2p_manager.h"
52#include "update_engine/cros/mock_payload_state.h"
53#include "update_engine/cros/omaha_utils.h"
Jae Hoon Kim0ae8fe12019-06-26 14:32:50 -070054#include "update_engine/libcurl_http_fetcher.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080055#include "update_engine/payload_consumer/filesystem_verifier_action.h"
56#include "update_engine/payload_consumer/install_plan.h"
57#include "update_engine/payload_consumer/payload_constants.h"
58#include "update_engine/payload_consumer/postinstall_runner_action.h"
Amin Hassani0882a512018-04-05 16:25:44 -070059#include "update_engine/update_boot_flags_action.h"
Jae Hoon Kim504c3cb2019-07-02 11:17:24 -070060#include "update_engine/update_manager/mock_update_manager.h"
Darin Petkovf42cc1c2010-09-01 09:03:02 -070061
David Zeuthen985b1122013-10-09 12:13:15 -070062using base::Time;
63using base::TimeDelta;
Aaron Woodbf5a2522017-10-04 10:58:36 -070064using chromeos_update_manager::EvalStatus;
Jae Hoon Kim504c3cb2019-07-02 11:17:24 -070065using chromeos_update_manager::MockUpdateManager;
Adolfo Victoria497044c2018-07-18 07:51:42 -070066using chromeos_update_manager::StagingSchedule;
Aaron Woodbf5a2522017-10-04 10:58:36 -070067using chromeos_update_manager::UpdateCheckParams;
Adolfo Victoria497044c2018-07-18 07:51:42 -070068using policy::DevicePolicy;
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -070069using std::map;
Darin Petkovf42cc1c2010-09-01 09:03:02 -070070using std::string;
Ben Chan02f7c1d2014-10-18 15:18:02 -070071using std::unique_ptr;
Jae Hoon Kimedb65502019-06-14 11:52:17 -070072using std::unordered_set;
Xiaochu Liu88d90382018-08-29 16:09:11 -070073using std::vector;
Aaron Woodbf5a2522017-10-04 10:58:36 -070074using testing::_;
Andrew065d78d2020-04-07 15:43:07 -070075using testing::Contains;
Darin Petkov36275772010-10-01 11:40:57 -070076using testing::DoAll;
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -070077using testing::ElementsAre;
Aaron Wood7f92e2b2017-08-28 14:51:21 -070078using testing::Field;
Darin Petkovf42cc1c2010-09-01 09:03:02 -070079using testing::InSequence;
Jae Hoon Kimedb65502019-06-14 11:52:17 -070080using testing::Invoke;
Darin Petkov2dd01092010-10-08 15:43:05 -070081using testing::Ne;
Darin Petkov9c096d62010-11-17 14:49:04 -080082using testing::NiceMock;
Amin Hassanid3f4bea2018-04-30 14:52:40 -070083using testing::Pointee;
Darin Petkovf42cc1c2010-09-01 09:03:02 -070084using testing::Property;
85using testing::Return;
Gilad Arnold74b5f552014-10-07 08:17:16 -070086using testing::ReturnPointee;
Marton Hunyadye58bddb2018-04-10 20:27:26 +020087using testing::ReturnRef;
Alex Deymo2c0db7b2014-11-04 12:23:39 -080088using testing::SaveArg;
Ben Chan672c1f52017-10-23 15:41:39 -070089using testing::SetArgPointee;
Aaron Woodbf5a2522017-10-04 10:58:36 -070090using update_engine::UpdateAttemptFlags;
Aaron Wood7f92e2b2017-08-28 14:51:21 -070091using update_engine::UpdateEngineStatus;
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -070092using update_engine::UpdateStatus;
Darin Petkovf42cc1c2010-09-01 09:03:02 -070093
94namespace chromeos_update_engine {
95
Xiaochu Liu8ba486f2018-11-06 11:14:10 -080096namespace {
97
Jae Hoon Kimc437ea52019-07-11 11:20:38 -070098const UpdateStatus kNonIdleUpdateStatuses[] = {
99 UpdateStatus::CHECKING_FOR_UPDATE,
100 UpdateStatus::UPDATE_AVAILABLE,
101 UpdateStatus::DOWNLOADING,
102 UpdateStatus::VERIFYING,
103 UpdateStatus::FINALIZING,
104 UpdateStatus::UPDATED_NEED_REBOOT,
105 UpdateStatus::REPORTING_ERROR_EVENT,
106 UpdateStatus::ATTEMPTING_ROLLBACK,
107 UpdateStatus::DISABLED,
108 UpdateStatus::NEED_PERMISSION_TO_UPDATE,
109};
110
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -0700111struct CheckForUpdateTestParams {
112 // Setups + Inputs:
113 UpdateStatus status = UpdateStatus::IDLE;
114 string app_version = "fake_app_version";
115 string omaha_url = "fake_omaha_url";
116 UpdateAttemptFlags flags = UpdateAttemptFlags::kNone;
117 bool is_official_build = true;
118 bool are_dev_features_enabled = false;
119
120 // Expects:
121 string expected_forced_app_version = "";
122 string expected_forced_omaha_url = "";
Jae Hoon Kim2b73ac22019-07-02 11:17:24 -0700123 bool should_schedule_updates_be_called = true;
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -0700124 bool expected_result = true;
125};
126
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700127struct OnUpdateScheduledTestParams {
128 // Setups + Inputs:
129 UpdateCheckParams params = {};
130 EvalStatus status = EvalStatus::kFailed;
131 // Expects:
132 UpdateStatus exit_status = UpdateStatus::IDLE;
133 bool should_schedule_updates_be_called = false;
134 bool should_update_be_called = false;
135};
136
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -0700137struct ProcessingDoneTestParams {
138 // Setups + Inputs:
139 bool is_install = false;
140 UpdateStatus status = UpdateStatus::CHECKING_FOR_UPDATE;
141 ActionProcessor* processor = nullptr;
142 ErrorCode code = ErrorCode::kSuccess;
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -0700143 map<string, OmahaRequestParams::AppParams> dlc_apps_params;
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -0700144
145 // Expects:
146 const bool kExpectedIsInstall = false;
147 bool should_schedule_updates_be_called = true;
148 UpdateStatus expected_exit_status = UpdateStatus::IDLE;
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -0700149 bool should_install_completed_be_called = false;
150 bool should_update_completed_be_called = false;
151 vector<string> args_to_install_completed;
152 vector<string> args_to_update_completed;
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -0700153};
154
Xiaochu Liu8ba486f2018-11-06 11:14:10 -0800155class MockDlcService : public DlcServiceInterface {
156 public:
Amin Hassani2b68e6b2020-04-17 10:49:12 -0700157 MOCK_METHOD1(GetDlcsToUpdate, bool(vector<string>*));
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -0700158 MOCK_METHOD1(InstallCompleted, bool(const vector<string>&));
159 MOCK_METHOD1(UpdateCompleted, bool(const vector<string>&));
Xiaochu Liu8ba486f2018-11-06 11:14:10 -0800160};
161
162} // namespace
163
Marton Hunyadya0302682018-05-16 18:52:13 +0200164const char kRollbackVersion[] = "10575.39.2";
165
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700166// Test a subclass rather than the main class directly so that we can mock out
Darin Petkovcd1666f2010-09-23 09:53:44 -0700167// methods within the class. There're explicit unit tests for the mocked out
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700168// methods.
169class UpdateAttempterUnderTest : public UpdateAttempter {
170 public:
Amin Hassani538bd592020-11-04 20:46:08 -0800171 UpdateAttempterUnderTest() : UpdateAttempter(nullptr) {}
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700172
Amin Hassanie8153632020-10-27 15:11:28 -0700173 void Update(const UpdateCheckParams& params) override {
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700174 update_called_ = true;
175 if (do_update_) {
Amin Hassanie8153632020-10-27 15:11:28 -0700176 UpdateAttempter::Update(params);
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700177 return;
178 }
179 LOG(INFO) << "[TEST] Update() disabled.";
180 status_ = UpdateStatus::CHECKING_FOR_UPDATE;
181 }
182
183 void DisableUpdate() { do_update_ = false; }
184
185 bool WasUpdateCalled() const { return update_called_; }
186
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700187 // Wrap the update scheduling method, allowing us to opt out of scheduled
188 // updates for testing purposes.
Xiaochu Liu88d90382018-08-29 16:09:11 -0700189 bool ScheduleUpdates() override {
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700190 schedule_updates_called_ = true;
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700191 if (do_schedule_updates_)
192 return UpdateAttempter::ScheduleUpdates();
193 LOG(INFO) << "[TEST] Update scheduling disabled.";
194 waiting_for_scheduled_check_ = true;
Xiaochu Liu88d90382018-08-29 16:09:11 -0700195 return true;
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700196 }
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700197
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700198 void DisableScheduleUpdates() { do_schedule_updates_ = false; }
199
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700200 // Indicates whether |ScheduleUpdates()| was called.
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700201 bool WasScheduleUpdatesCalled() const { return schedule_updates_called_; }
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700202
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -0700203 // Need to expose following private members of |UpdateAttempter| for tests.
204 const string& forced_app_version() const { return forced_app_version_; }
Alex Deymo60ca1a72015-06-18 18:19:15 -0700205 const string& forced_omaha_url() const { return forced_omaha_url_; }
David Pursell02c18642014-11-06 11:26:11 -0800206
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700207 // Need to expose |waiting_for_scheduled_check_| for testing.
208 void SetWaitingForScheduledCheck(bool waiting) {
209 waiting_for_scheduled_check_ = waiting;
210 }
211
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700212 private:
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700213 // Used for overrides of |Update()|.
214 bool update_called_ = false;
215 bool do_update_ = true;
216
217 // Used for overrides of |ScheduleUpdates()|.
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700218 bool schedule_updates_called_ = false;
219 bool do_schedule_updates_ = true;
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700220};
221
222class UpdateAttempterTest : public ::testing::Test {
223 protected:
Amin Hassani538bd592020-11-04 20:46:08 -0800224 void SetUp() override {
Gilad Arnold1f847232014-04-07 12:07:49 -0700225 // Override system state members.
Amin Hassani538bd592020-11-04 20:46:08 -0800226 FakeSystemState::CreateInstance();
227 FakeSystemState::Get()->set_connection_manager(&mock_connection_manager);
228 FakeSystemState::Get()->set_update_attempter(&attempter_);
229 FakeSystemState::Get()->set_dlcservice(&mock_dlcservice_);
230 FakeSystemState::Get()->set_update_manager(&mock_update_manager_);
Alex Deymo60ca1a72015-06-18 18:19:15 -0700231 loop_.SetAsCurrent();
Gilad Arnold1f847232014-04-07 12:07:49 -0700232
Amin Hassani538bd592020-11-04 20:46:08 -0800233 certificate_checker_.reset(new CertificateChecker(
234 FakeSystemState::Get()->mock_prefs(), &openssl_wrapper_));
235 certificate_checker_->Init();
Alex Deymo33e91e72015-12-01 18:26:08 -0300236
Xiaochu Liu8ba486f2018-11-06 11:14:10 -0800237 attempter_.set_forced_update_pending_callback(
238 new base::Callback<void(bool, bool)>(base::Bind([](bool, bool) {})));
Sen Jiange67bb5b2016-06-20 15:53:56 -0700239 // Finish initializing the attempter.
Gilad Arnold1f847232014-04-07 12:07:49 -0700240 attempter_.Init();
Gilad Arnoldeff87cc2013-07-22 18:32:09 -0700241
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700242 EXPECT_EQ(0, attempter_.http_response_code_);
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700243 EXPECT_EQ(UpdateStatus::IDLE, attempter_.status_);
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700244 EXPECT_EQ(0.0, attempter_.download_progress_);
245 EXPECT_EQ(0, attempter_.last_checked_time_);
246 EXPECT_EQ("0.0.0.0", attempter_.new_version_);
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700247 EXPECT_EQ(0ULL, attempter_.new_payload_size_);
Alex Deymo8427b4a2014-11-05 14:00:32 -0800248 processor_ = new NiceMock<MockActionProcessor>();
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700249 attempter_.processor_.reset(processor_); // Transfers ownership.
Amin Hassani538bd592020-11-04 20:46:08 -0800250 prefs_ = FakeSystemState::Get()->mock_prefs();
Gilad Arnold74b5f552014-10-07 08:17:16 -0700251
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700252 // Setup store/load semantics of P2P properties via the mock |PayloadState|.
Gilad Arnold74b5f552014-10-07 08:17:16 -0700253 actual_using_p2p_for_downloading_ = false;
Amin Hassani538bd592020-11-04 20:46:08 -0800254 EXPECT_CALL(*FakeSystemState::Get()->mock_payload_state(),
Gilad Arnold74b5f552014-10-07 08:17:16 -0700255 SetUsingP2PForDownloading(_))
256 .WillRepeatedly(SaveArg<0>(&actual_using_p2p_for_downloading_));
Amin Hassani538bd592020-11-04 20:46:08 -0800257 EXPECT_CALL(*FakeSystemState::Get()->mock_payload_state(),
Gilad Arnold74b5f552014-10-07 08:17:16 -0700258 GetUsingP2PForDownloading())
259 .WillRepeatedly(ReturnPointee(&actual_using_p2p_for_downloading_));
260 actual_using_p2p_for_sharing_ = false;
Amin Hassani538bd592020-11-04 20:46:08 -0800261 EXPECT_CALL(*FakeSystemState::Get()->mock_payload_state(),
Gilad Arnold74b5f552014-10-07 08:17:16 -0700262 SetUsingP2PForSharing(_))
263 .WillRepeatedly(SaveArg<0>(&actual_using_p2p_for_sharing_));
Amin Hassani538bd592020-11-04 20:46:08 -0800264 EXPECT_CALL(*FakeSystemState::Get()->mock_payload_state(),
Gilad Arnold74b5f552014-10-07 08:17:16 -0700265 GetUsingP2PForDownloading())
266 .WillRepeatedly(ReturnPointee(&actual_using_p2p_for_sharing_));
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700267 }
268
Alex Deymo60ca1a72015-06-18 18:19:15 -0700269 public:
270 void ScheduleQuitMainLoop();
Patrick Dubroy7fbbe8a2011-08-01 17:28:22 +0200271
Alex Deymo60ca1a72015-06-18 18:19:15 -0700272 // Callbacks to run the different tests from the main loop.
Darin Petkove6ef2f82011-03-07 17:31:11 -0800273 void UpdateTestStart();
274 void UpdateTestVerify();
Alex Deymo60ca1a72015-06-18 18:19:15 -0700275 void RollbackTestStart(bool enterprise_rollback, bool valid_slot);
Chris Sosa76a29ae2013-07-11 17:59:24 -0700276 void RollbackTestVerify();
Thieu Le116fda32011-04-19 11:01:54 -0700277 void PingOmahaTestStart();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700278 void ReadScatterFactorFromPolicyTestStart();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700279 void DecrementUpdateCheckCountTestStart();
Jay Srinivasan08fce042012-06-07 16:31:01 -0700280 void NoScatteringDoneDuringManualUpdateTestStart();
David Zeuthen8f191b22013-08-06 12:27:50 -0700281 void P2PNotEnabledStart();
David Zeuthen8f191b22013-08-06 12:27:50 -0700282 void P2PEnabledStart();
David Zeuthen8f191b22013-08-06 12:27:50 -0700283 void P2PEnabledInteractiveStart();
David Zeuthen8f191b22013-08-06 12:27:50 -0700284 void P2PEnabledStartingFailsStart();
David Zeuthen8f191b22013-08-06 12:27:50 -0700285 void P2PEnabledHousekeepingFailsStart();
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700286 void SessionIdTestChange();
287 void SessionIdTestEnforceEmptyStrPingOmaha();
288 void SessionIdTestConsistencyInUpdateFlow();
Jae Hoon Kim0ae8fe12019-06-26 14:32:50 -0700289 void SessionIdTestInDownloadAction();
Marton Hunyadye58bddb2018-04-10 20:27:26 +0200290 void ResetRollbackHappenedStart(bool is_consumer,
291 bool is_policy_available,
292 bool expected_reset);
Adolfo Victoria497044c2018-07-18 07:51:42 -0700293 // Staging related callbacks.
294 void SetUpStagingTest(const StagingSchedule& schedule, FakePrefs* prefs);
295 void CheckStagingOff();
296 void StagingSetsPrefsAndTurnsOffScatteringStart();
297 void StagingOffIfInteractiveStart();
298 void StagingOffIfOobeStart();
David Zeuthen8f191b22013-08-06 12:27:50 -0700299
Gilad Arnold74b5f552014-10-07 08:17:16 -0700300 bool actual_using_p2p_for_downloading() {
301 return actual_using_p2p_for_downloading_;
302 }
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800303 bool actual_using_p2p_for_sharing() { return actual_using_p2p_for_sharing_; }
Gilad Arnold74b5f552014-10-07 08:17:16 -0700304
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -0700305 // |CheckForUpdate()| related member functions.
306 void TestCheckForUpdate();
307
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700308 // |OnUpdateScheduled()| related member functions.
309 void TestOnUpdateScheduled();
310
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -0700311 // |ProcessingDone()| related member functions.
312 void TestProcessingDone();
313
Qijiang Fanb0b6cc22020-10-15 21:54:11 +0900314 base::SingleThreadTaskExecutor base_loop_{base::MessagePumpType::IO};
315 brillo::BaseMessageLoop loop_{base_loop_.task_runner()};
Alex Deymo60ca1a72015-06-18 18:19:15 -0700316
Amin Hassani538bd592020-11-04 20:46:08 -0800317 UpdateAttempterUnderTest attempter_;
Alex Deymo33e91e72015-12-01 18:26:08 -0300318 OpenSSLWrapper openssl_wrapper_;
Amin Hassani538bd592020-11-04 20:46:08 -0800319 std::unique_ptr<CertificateChecker> certificate_checker_;
Xiaochu Liu8ba486f2018-11-06 11:14:10 -0800320 MockDlcService mock_dlcservice_;
Jae Hoon Kim504c3cb2019-07-02 11:17:24 -0700321 MockUpdateManager mock_update_manager_;
Alex Deymo30534502015-07-20 15:06:33 -0700322
Alex Deymo8427b4a2014-11-05 14:00:32 -0800323 NiceMock<MockActionProcessor>* processor_;
Amin Hassani538bd592020-11-04 20:46:08 -0800324 NiceMock<MockPrefs>* prefs_;
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800325 NiceMock<MockConnectionManager> mock_connection_manager;
Gilad Arnoldeff87cc2013-07-22 18:32:09 -0700326
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -0700327 // |CheckForUpdate()| test params.
328 CheckForUpdateTestParams cfu_params_;
329
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700330 // |OnUpdateScheduled()| test params.
331 OnUpdateScheduledTestParams ous_params_;
332
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -0700333 // |ProcessingDone()| test params.
334 ProcessingDoneTestParams pd_params_;
335
Gilad Arnold74b5f552014-10-07 08:17:16 -0700336 bool actual_using_p2p_for_downloading_;
337 bool actual_using_p2p_for_sharing_;
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700338};
339
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -0700340void UpdateAttempterTest::TestCheckForUpdate() {
341 // Setup
342 attempter_.status_ = cfu_params_.status;
Amin Hassani538bd592020-11-04 20:46:08 -0800343 FakeSystemState::Get()->fake_hardware()->SetIsOfficialBuild(
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -0700344 cfu_params_.is_official_build);
Amin Hassani538bd592020-11-04 20:46:08 -0800345 FakeSystemState::Get()->fake_hardware()->SetAreDevFeaturesEnabled(
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -0700346 cfu_params_.are_dev_features_enabled);
347
348 // Invocation
349 EXPECT_EQ(
350 cfu_params_.expected_result,
351 attempter_.CheckForUpdate(
352 cfu_params_.app_version, cfu_params_.omaha_url, cfu_params_.flags));
353
354 // Verify
355 EXPECT_EQ(cfu_params_.expected_forced_app_version,
356 attempter_.forced_app_version());
357 EXPECT_EQ(cfu_params_.expected_forced_omaha_url,
358 attempter_.forced_omaha_url());
Jae Hoon Kim2b73ac22019-07-02 11:17:24 -0700359 EXPECT_EQ(cfu_params_.should_schedule_updates_be_called,
360 attempter_.WasScheduleUpdatesCalled());
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -0700361}
362
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -0700363void UpdateAttempterTest::TestProcessingDone() {
364 // Setup
365 attempter_.DisableScheduleUpdates();
366 attempter_.is_install_ = pd_params_.is_install;
367 attempter_.status_ = pd_params_.status;
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -0700368 attempter_.omaha_request_params_->set_dlc_apps_params(
369 pd_params_.dlc_apps_params);
370
371 // Expects
372 if (pd_params_.should_install_completed_be_called)
373 EXPECT_CALL(mock_dlcservice_,
374 InstallCompleted(pd_params_.args_to_install_completed))
375 .WillOnce(Return(true));
376 else
377 EXPECT_CALL(mock_dlcservice_, InstallCompleted(_)).Times(0);
378 if (pd_params_.should_update_completed_be_called)
379 EXPECT_CALL(mock_dlcservice_,
380 UpdateCompleted(pd_params_.args_to_update_completed))
381 .WillOnce(Return(true));
382 else
383 EXPECT_CALL(mock_dlcservice_, UpdateCompleted(_)).Times(0);
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -0700384
385 // Invocation
386 attempter_.ProcessingDone(pd_params_.processor, pd_params_.code);
387
388 // Verify
389 EXPECT_EQ(pd_params_.kExpectedIsInstall, attempter_.is_install_);
390 EXPECT_EQ(pd_params_.should_schedule_updates_be_called,
391 attempter_.WasScheduleUpdatesCalled());
392 EXPECT_EQ(pd_params_.expected_exit_status, attempter_.status_);
393}
394
Alex Deymo60ca1a72015-06-18 18:19:15 -0700395void UpdateAttempterTest::ScheduleQuitMainLoop() {
Luis Hector Chavezf1cf3482016-07-19 14:29:19 -0700396 loop_.PostTask(
397 FROM_HERE,
398 base::Bind([](brillo::BaseMessageLoop* loop) { loop->BreakLoop(); },
399 base::Unretained(&loop_)));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700400}
401
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700402void UpdateAttempterTest::SessionIdTestChange() {
403 EXPECT_NE(UpdateStatus::UPDATED_NEED_REBOOT, attempter_.status());
404 const auto old_session_id = attempter_.session_id_;
Amin Hassanie8153632020-10-27 15:11:28 -0700405 attempter_.Update({});
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700406 EXPECT_NE(old_session_id, attempter_.session_id_);
407 ScheduleQuitMainLoop();
408}
409
410TEST_F(UpdateAttempterTest, SessionIdTestChange) {
411 loop_.PostTask(FROM_HERE,
412 base::Bind(&UpdateAttempterTest::SessionIdTestChange,
413 base::Unretained(this)));
414 loop_.Run();
415}
416
417void UpdateAttempterTest::SessionIdTestEnforceEmptyStrPingOmaha() {
418 // The |session_id_| should not be changed and should remain as an empty
419 // string when |status_| is |UPDATED_NEED_REBOOT| (only for consistency)
420 // and |PingOmaha()| is called.
421 attempter_.DisableScheduleUpdates();
422 attempter_.status_ = UpdateStatus::UPDATED_NEED_REBOOT;
423 const auto old_session_id = attempter_.session_id_;
424 auto CheckIfEmptySessionId = [](AbstractAction* aa) {
425 if (aa->Type() == OmahaRequestAction::StaticType()) {
426 EXPECT_TRUE(static_cast<OmahaRequestAction*>(aa)->session_id_.empty());
427 }
428 };
429 EXPECT_CALL(*processor_, EnqueueAction(Pointee(_)))
430 .WillRepeatedly(Invoke(CheckIfEmptySessionId));
431 EXPECT_CALL(*processor_, StartProcessing());
432 attempter_.PingOmaha();
433 EXPECT_EQ(old_session_id, attempter_.session_id_);
434 EXPECT_EQ(UpdateStatus::UPDATED_NEED_REBOOT, attempter_.status_);
435 ScheduleQuitMainLoop();
436}
437
438TEST_F(UpdateAttempterTest, SessionIdTestEnforceEmptyStrPingOmaha) {
439 loop_.PostTask(
440 FROM_HERE,
441 base::Bind(&UpdateAttempterTest::SessionIdTestEnforceEmptyStrPingOmaha,
442 base::Unretained(this)));
443 loop_.Run();
444}
445
446void UpdateAttempterTest::SessionIdTestConsistencyInUpdateFlow() {
447 // All session IDs passed into |OmahaRequestActions| should be enforced to
448 // have the same value in |BuildUpdateActions()|.
449 unordered_set<string> session_ids;
450 // Gather all the session IDs being passed to |OmahaRequestActions|.
451 auto CheckSessionId = [&session_ids](AbstractAction* aa) {
452 if (aa->Type() == OmahaRequestAction::StaticType())
453 session_ids.insert(static_cast<OmahaRequestAction*>(aa)->session_id_);
454 };
455 EXPECT_CALL(*processor_, EnqueueAction(Pointee(_)))
456 .WillRepeatedly(Invoke(CheckSessionId));
457 attempter_.BuildUpdateActions(false);
458 // Validate that all the session IDs are the same.
459 EXPECT_EQ(1, session_ids.size());
460 ScheduleQuitMainLoop();
461}
462
463TEST_F(UpdateAttempterTest, SessionIdTestConsistencyInUpdateFlow) {
464 loop_.PostTask(
465 FROM_HERE,
466 base::Bind(&UpdateAttempterTest::SessionIdTestConsistencyInUpdateFlow,
467 base::Unretained(this)));
468 loop_.Run();
469}
470
Jae Hoon Kim0ae8fe12019-06-26 14:32:50 -0700471void UpdateAttempterTest::SessionIdTestInDownloadAction() {
472 // The session ID passed into |DownloadAction|'s |LibcurlHttpFetcher| should
473 // be enforced to be included in the HTTP header as X-Goog-Update-SessionId.
474 string header_value;
475 auto CheckSessionIdInDownloadAction = [&header_value](AbstractAction* aa) {
476 if (aa->Type() == DownloadAction::StaticType()) {
477 DownloadAction* da = static_cast<DownloadAction*>(aa);
478 EXPECT_TRUE(da->http_fetcher()->GetHeader(kXGoogleUpdateSessionId,
479 &header_value));
480 }
481 };
482 EXPECT_CALL(*processor_, EnqueueAction(Pointee(_)))
483 .WillRepeatedly(Invoke(CheckSessionIdInDownloadAction));
484 attempter_.BuildUpdateActions(false);
485 // Validate that X-Goog-Update_SessionId is set correctly in HTTP Header.
486 EXPECT_EQ(attempter_.session_id_, header_value);
487 ScheduleQuitMainLoop();
488}
489
490TEST_F(UpdateAttempterTest, SessionIdTestInDownloadAction) {
491 loop_.PostTask(FROM_HERE,
492 base::Bind(&UpdateAttempterTest::SessionIdTestInDownloadAction,
493 base::Unretained(this)));
494 loop_.Run();
495}
496
Darin Petkov1b003102010-11-30 10:18:36 -0800497TEST_F(UpdateAttempterTest, ActionCompletedDownloadTest) {
Ben Chan02f7c1d2014-10-18 15:18:02 -0700498 unique_ptr<MockHttpFetcher> fetcher(new MockHttpFetcher("", 0, nullptr));
Darin Petkov1b003102010-11-30 10:18:36 -0800499 fetcher->FailTransfer(503); // Sets the HTTP response code.
Amin Hassani7ecda262017-07-11 17:10:50 -0700500 DownloadAction action(prefs_,
501 nullptr,
502 nullptr,
Amin Hassani7ecda262017-07-11 17:10:50 -0700503 fetcher.release(),
Amin Hassanied37d682018-04-06 13:22:00 -0700504 false /* interactive */);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800505 EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _)).Times(0);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700506 attempter_.ActionCompleted(nullptr, &action, ErrorCode::kSuccess);
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700507 EXPECT_EQ(UpdateStatus::FINALIZING, attempter_.status());
Aaron Wood9321f502017-09-07 11:18:54 -0700508 EXPECT_EQ(0.0, attempter_.download_progress_);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700509 ASSERT_EQ(nullptr, attempter_.error_event_.get());
Darin Petkov1b003102010-11-30 10:18:36 -0800510}
511
512TEST_F(UpdateAttempterTest, ActionCompletedErrorTest) {
Alex Deymo8427b4a2014-11-05 14:00:32 -0800513 MockAction action;
514 EXPECT_CALL(action, Type()).WillRepeatedly(Return("MockAction"));
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700515 attempter_.status_ = UpdateStatus::DOWNLOADING;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800516 EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _))
Darin Petkov1b003102010-11-30 10:18:36 -0800517 .WillOnce(Return(false));
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700518 attempter_.ActionCompleted(nullptr, &action, ErrorCode::kError);
519 ASSERT_NE(nullptr, attempter_.error_event_.get());
Darin Petkov1b003102010-11-30 10:18:36 -0800520}
521
Aaron Wood9321f502017-09-07 11:18:54 -0700522TEST_F(UpdateAttempterTest, DownloadProgressAccumulationTest) {
523 // Simple test case, where all the values match (nothing was skipped)
524 uint64_t bytes_progressed_1 = 1024 * 1024; // 1MB
525 uint64_t bytes_progressed_2 = 1024 * 1024; // 1MB
526 uint64_t bytes_received_1 = bytes_progressed_1;
527 uint64_t bytes_received_2 = bytes_received_1 + bytes_progressed_2;
528 uint64_t bytes_total = 20 * 1024 * 1024; // 20MB
529
530 double progress_1 =
531 static_cast<double>(bytes_received_1) / static_cast<double>(bytes_total);
532 double progress_2 =
533 static_cast<double>(bytes_received_2) / static_cast<double>(bytes_total);
534
535 EXPECT_EQ(0.0, attempter_.download_progress_);
536 // This is set via inspecting the InstallPlan payloads when the
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700537 // |OmahaResponseAction| is completed.
Aaron Wood9321f502017-09-07 11:18:54 -0700538 attempter_.new_payload_size_ = bytes_total;
539 NiceMock<MockServiceObserver> observer;
540 EXPECT_CALL(observer,
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700541 SendStatusUpdate(AllOf(
542 Field(&UpdateEngineStatus::progress, progress_1),
543 Field(&UpdateEngineStatus::status, UpdateStatus::DOWNLOADING),
544 Field(&UpdateEngineStatus::new_size_bytes, bytes_total))));
Aaron Wood9321f502017-09-07 11:18:54 -0700545 EXPECT_CALL(observer,
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700546 SendStatusUpdate(AllOf(
547 Field(&UpdateEngineStatus::progress, progress_2),
548 Field(&UpdateEngineStatus::status, UpdateStatus::DOWNLOADING),
549 Field(&UpdateEngineStatus::new_size_bytes, bytes_total))));
Aaron Wood9321f502017-09-07 11:18:54 -0700550 attempter_.AddObserver(&observer);
551 attempter_.BytesReceived(bytes_progressed_1, bytes_received_1, bytes_total);
552 EXPECT_EQ(progress_1, attempter_.download_progress_);
553 // This iteration validates that a later set of updates to the variables are
554 // properly handled (so that |getStatus()| will return the same progress info
555 // as the callback is receiving.
556 attempter_.BytesReceived(bytes_progressed_2, bytes_received_2, bytes_total);
557 EXPECT_EQ(progress_2, attempter_.download_progress_);
558}
559
560TEST_F(UpdateAttempterTest, ChangeToDownloadingOnReceivedBytesTest) {
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700561 // The transition into |UpdateStatus::DOWNLOADING| happens when the
Aaron Wood9321f502017-09-07 11:18:54 -0700562 // first bytes are received.
563 uint64_t bytes_progressed = 1024 * 1024; // 1MB
564 uint64_t bytes_received = 2 * 1024 * 1024; // 2MB
565 uint64_t bytes_total = 20 * 1024 * 1024; // 300MB
566 attempter_.status_ = UpdateStatus::CHECKING_FOR_UPDATE;
567 // This is set via inspecting the InstallPlan payloads when the
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700568 // |OmahaResponseAction| is completed.
Aaron Wood9321f502017-09-07 11:18:54 -0700569 attempter_.new_payload_size_ = bytes_total;
570 EXPECT_EQ(0.0, attempter_.download_progress_);
571 NiceMock<MockServiceObserver> observer;
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700572 EXPECT_CALL(observer,
573 SendStatusUpdate(AllOf(
574 Field(&UpdateEngineStatus::status, UpdateStatus::DOWNLOADING),
575 Field(&UpdateEngineStatus::new_size_bytes, bytes_total))));
Aaron Wood9321f502017-09-07 11:18:54 -0700576 attempter_.AddObserver(&observer);
577 attempter_.BytesReceived(bytes_progressed, bytes_received, bytes_total);
578 EXPECT_EQ(UpdateStatus::DOWNLOADING, attempter_.status_);
579}
580
581TEST_F(UpdateAttempterTest, BroadcastCompleteDownloadTest) {
582 // There is a special case to ensure that at 100% downloaded,
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700583 // |download_progress_| is updated and broadcastest.
Aaron Wood9321f502017-09-07 11:18:54 -0700584 uint64_t bytes_progressed = 0; // ignored
585 uint64_t bytes_received = 5 * 1024 * 1024; // ignored
586 uint64_t bytes_total = 5 * 1024 * 1024; // 300MB
587 attempter_.status_ = UpdateStatus::DOWNLOADING;
588 attempter_.new_payload_size_ = bytes_total;
589 EXPECT_EQ(0.0, attempter_.download_progress_);
590 NiceMock<MockServiceObserver> observer;
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700591 EXPECT_CALL(observer,
592 SendStatusUpdate(AllOf(
593 Field(&UpdateEngineStatus::progress, 1.0),
594 Field(&UpdateEngineStatus::status, UpdateStatus::DOWNLOADING),
595 Field(&UpdateEngineStatus::new_size_bytes, bytes_total))));
Aaron Wood9321f502017-09-07 11:18:54 -0700596 attempter_.AddObserver(&observer);
597 attempter_.BytesReceived(bytes_progressed, bytes_received, bytes_total);
598 EXPECT_EQ(1.0, attempter_.download_progress_);
599}
600
Darin Petkov1b003102010-11-30 10:18:36 -0800601TEST_F(UpdateAttempterTest, ActionCompletedOmahaRequestTest) {
Ben Chan02f7c1d2014-10-18 15:18:02 -0700602 unique_ptr<MockHttpFetcher> fetcher(new MockHttpFetcher("", 0, nullptr));
Darin Petkov1b003102010-11-30 10:18:36 -0800603 fetcher->FailTransfer(500); // Sets the HTTP response code.
Amin Hassani538bd592020-11-04 20:46:08 -0800604 OmahaRequestAction action(nullptr, std::move(fetcher), false, "");
Darin Petkov1b003102010-11-30 10:18:36 -0800605 ObjectCollectorAction<OmahaResponse> collector_action;
606 BondActions(&action, &collector_action);
607 OmahaResponse response;
608 response.poll_interval = 234;
609 action.SetOutputObject(response);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800610 EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _)).Times(0);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700611 attempter_.ActionCompleted(nullptr, &action, ErrorCode::kSuccess);
Darin Petkov1b003102010-11-30 10:18:36 -0800612 EXPECT_EQ(500, attempter_.http_response_code());
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700613 EXPECT_EQ(UpdateStatus::IDLE, attempter_.status());
Alex Deymo80f70ff2016-02-10 16:08:11 -0800614 EXPECT_EQ(234U, attempter_.server_dictated_poll_interval_);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700615 ASSERT_TRUE(attempter_.error_event_.get() == nullptr);
Darin Petkov1b003102010-11-30 10:18:36 -0800616}
617
Alex Deymo30534502015-07-20 15:06:33 -0700618TEST_F(UpdateAttempterTest, ConstructWithUpdatedMarkerTest) {
Alex Deymo906191f2015-10-12 12:22:44 -0700619 FakePrefs fake_prefs;
620 string boot_id;
621 EXPECT_TRUE(utils::GetBootId(&boot_id));
622 fake_prefs.SetString(kPrefsUpdateCompletedOnBootId, boot_id);
Amin Hassani538bd592020-11-04 20:46:08 -0800623 FakeSystemState::Get()->set_prefs(&fake_prefs);
Sen Jiangaeeb2e02016-06-09 15:00:16 -0700624 attempter_.Init();
625 EXPECT_EQ(UpdateStatus::UPDATED_NEED_REBOOT, attempter_.status());
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700626}
627
628TEST_F(UpdateAttempterTest, GetErrorCodeForActionTest) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700629 EXPECT_EQ(ErrorCode::kSuccess,
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700630 GetErrorCodeForAction(nullptr, ErrorCode::kSuccess));
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700631
Amin Hassani538bd592020-11-04 20:46:08 -0800632 OmahaRequestAction omaha_request_action(nullptr, nullptr, false, "");
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700633 EXPECT_EQ(ErrorCode::kOmahaRequestError,
634 GetErrorCodeForAction(&omaha_request_action, ErrorCode::kError));
Amin Hassani538bd592020-11-04 20:46:08 -0800635 OmahaResponseHandlerAction omaha_response_handler_action;
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800636 EXPECT_EQ(
637 ErrorCode::kOmahaResponseHandlerError,
638 GetErrorCodeForAction(&omaha_response_handler_action, ErrorCode::kError));
Tianjie24f96092020-06-30 12:26:25 -0700639 DynamicPartitionControlStub dynamic_control_stub;
640 FilesystemVerifierAction filesystem_verifier_action(&dynamic_control_stub);
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800641 EXPECT_EQ(
642 ErrorCode::kFilesystemVerifierError,
643 GetErrorCodeForAction(&filesystem_verifier_action, ErrorCode::kError));
Alex Deymob15a0b82015-11-25 20:30:40 -0300644 PostinstallRunnerAction postinstall_runner_action(
Amin Hassani538bd592020-11-04 20:46:08 -0800645 FakeSystemState::Get()->fake_boot_control(),
646 FakeSystemState::Get()->fake_hardware());
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800647 EXPECT_EQ(
648 ErrorCode::kPostinstallRunnerError,
649 GetErrorCodeForAction(&postinstall_runner_action, ErrorCode::kError));
Alex Deymo8427b4a2014-11-05 14:00:32 -0800650 MockAction action_mock;
651 EXPECT_CALL(action_mock, Type()).WillOnce(Return("MockAction"));
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700652 EXPECT_EQ(ErrorCode::kError,
653 GetErrorCodeForAction(&action_mock, ErrorCode::kError));
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700654}
655
Darin Petkov36275772010-10-01 11:40:57 -0700656TEST_F(UpdateAttempterTest, DisableDeltaUpdateIfNeededTest) {
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700657 attempter_.omaha_request_params_->set_delta_okay(true);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800658 EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _))
Darin Petkov36275772010-10-01 11:40:57 -0700659 .WillOnce(Return(false));
660 attempter_.DisableDeltaUpdateIfNeeded();
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700661 EXPECT_TRUE(attempter_.omaha_request_params_->delta_okay());
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800662 EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _))
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800663 .WillOnce(
664 DoAll(SetArgPointee<1>(UpdateAttempter::kMaxDeltaUpdateFailures - 1),
665 Return(true)));
Darin Petkov36275772010-10-01 11:40:57 -0700666 attempter_.DisableDeltaUpdateIfNeeded();
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700667 EXPECT_TRUE(attempter_.omaha_request_params_->delta_okay());
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800668 EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _))
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800669 .WillOnce(
670 DoAll(SetArgPointee<1>(UpdateAttempter::kMaxDeltaUpdateFailures),
671 Return(true)));
Darin Petkov36275772010-10-01 11:40:57 -0700672 attempter_.DisableDeltaUpdateIfNeeded();
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700673 EXPECT_FALSE(attempter_.omaha_request_params_->delta_okay());
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800674 EXPECT_CALL(*prefs_, GetInt64(_, _)).Times(0);
Darin Petkov36275772010-10-01 11:40:57 -0700675 attempter_.DisableDeltaUpdateIfNeeded();
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700676 EXPECT_FALSE(attempter_.omaha_request_params_->delta_okay());
Darin Petkov36275772010-10-01 11:40:57 -0700677}
678
679TEST_F(UpdateAttempterTest, MarkDeltaUpdateFailureTest) {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800680 EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _))
Darin Petkov36275772010-10-01 11:40:57 -0700681 .WillOnce(Return(false))
Ben Chan672c1f52017-10-23 15:41:39 -0700682 .WillOnce(DoAll(SetArgPointee<1>(-1), Return(true)))
683 .WillOnce(DoAll(SetArgPointee<1>(1), Return(true)))
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800684 .WillOnce(
685 DoAll(SetArgPointee<1>(UpdateAttempter::kMaxDeltaUpdateFailures),
686 Return(true)));
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800687 EXPECT_CALL(*prefs_, SetInt64(Ne(kPrefsDeltaUpdateFailures), _))
Darin Petkov2dd01092010-10-08 15:43:05 -0700688 .WillRepeatedly(Return(true));
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800689 EXPECT_CALL(*prefs_, SetInt64(kPrefsDeltaUpdateFailures, 1)).Times(2);
Gilad Arnold74b5f552014-10-07 08:17:16 -0700690 EXPECT_CALL(*prefs_, SetInt64(kPrefsDeltaUpdateFailures, 2));
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800691 EXPECT_CALL(*prefs_,
692 SetInt64(kPrefsDeltaUpdateFailures,
693 UpdateAttempter::kMaxDeltaUpdateFailures + 1));
694 for (int i = 0; i < 4; i++)
Darin Petkov36275772010-10-01 11:40:57 -0700695 attempter_.MarkDeltaUpdateFailure();
696}
697
Darin Petkov1b003102010-11-30 10:18:36 -0800698TEST_F(UpdateAttempterTest, ScheduleErrorEventActionNoEventTest) {
699 EXPECT_CALL(*processor_, EnqueueAction(_)).Times(0);
700 EXPECT_CALL(*processor_, StartProcessing()).Times(0);
Amin Hassani538bd592020-11-04 20:46:08 -0800701 EXPECT_CALL(*FakeSystemState::Get()->mock_payload_state(), UpdateFailed(_))
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800702 .Times(0);
703 OmahaResponse response;
Jay Srinivasan53173b92013-05-17 17:13:01 -0700704 string url1 = "http://url1";
Sen Jiang0affc2c2017-02-10 15:55:05 -0800705 response.packages.push_back({.payload_urls = {url1, "https://url"}});
Amin Hassani538bd592020-11-04 20:46:08 -0800706 EXPECT_CALL(*(FakeSystemState::Get()->mock_payload_state()), GetCurrentUrl())
Jay Srinivasan53173b92013-05-17 17:13:01 -0700707 .WillRepeatedly(Return(url1));
Amin Hassani538bd592020-11-04 20:46:08 -0800708 FakeSystemState::Get()->mock_payload_state()->SetResponse(response);
Darin Petkov1b003102010-11-30 10:18:36 -0800709 attempter_.ScheduleErrorEventAction();
Amin Hassani538bd592020-11-04 20:46:08 -0800710 EXPECT_EQ(url1,
711 FakeSystemState::Get()->mock_payload_state()->GetCurrentUrl());
Darin Petkov1b003102010-11-30 10:18:36 -0800712}
713
714TEST_F(UpdateAttempterTest, ScheduleErrorEventActionTest) {
715 EXPECT_CALL(*processor_,
Amin Hassanid3f4bea2018-04-30 14:52:40 -0700716 EnqueueAction(Pointee(Property(
717 &AbstractAction::Type, OmahaRequestAction::StaticType()))));
Gilad Arnold74b5f552014-10-07 08:17:16 -0700718 EXPECT_CALL(*processor_, StartProcessing());
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700719 ErrorCode err = ErrorCode::kError;
Amin Hassani538bd592020-11-04 20:46:08 -0800720 EXPECT_CALL(*FakeSystemState::Get()->mock_payload_state(), UpdateFailed(err));
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800721 attempter_.error_event_.reset(new OmahaEvent(
722 OmahaEvent::kTypeUpdateComplete, OmahaEvent::kResultError, err));
Darin Petkov1b003102010-11-30 10:18:36 -0800723 attempter_.ScheduleErrorEventAction();
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700724 EXPECT_EQ(UpdateStatus::REPORTING_ERROR_EVENT, attempter_.status());
Darin Petkov1b003102010-11-30 10:18:36 -0800725}
726
Darin Petkove6ef2f82011-03-07 17:31:11 -0800727namespace {
Chris Sosa76a29ae2013-07-11 17:59:24 -0700728// Actions that will be built as part of an update check.
Askar Aitzhan570ca872019-04-24 11:16:12 +0200729vector<string> GetUpdateActionTypes() {
730 return {OmahaRequestAction::StaticType(),
731 OmahaResponseHandlerAction::StaticType(),
732 UpdateBootFlagsAction::StaticType(),
733 OmahaRequestAction::StaticType(),
734 DownloadAction::StaticType(),
735 OmahaRequestAction::StaticType(),
736 FilesystemVerifierAction::StaticType(),
737 PostinstallRunnerAction::StaticType(),
738 OmahaRequestAction::StaticType()};
739}
Chris Sosa76a29ae2013-07-11 17:59:24 -0700740
741// Actions that will be built as part of a user-initiated rollback.
Askar Aitzhan570ca872019-04-24 11:16:12 +0200742vector<string> GetRollbackActionTypes() {
743 return {InstallPlanAction::StaticType(),
744 PostinstallRunnerAction::StaticType()};
745}
Chris Sosa76a29ae2013-07-11 17:59:24 -0700746
Adolfo Victoria497044c2018-07-18 07:51:42 -0700747const StagingSchedule kValidStagingSchedule = {
748 {4, 10}, {10, 40}, {19, 70}, {26, 100}};
749
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700750} // namespace
Darin Petkove6ef2f82011-03-07 17:31:11 -0800751
752void UpdateAttempterTest::UpdateTestStart() {
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700753 attempter_.set_http_response_code(200);
Alex Deymo749ecf12014-10-21 20:06:57 -0700754
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700755 // Expect that the device policy is loaded by the |UpdateAttempter| at some
756 // point by calling |RefreshDevicePolicy()|.
Igor9fd76b62017-12-11 15:24:18 +0100757 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Alex Deymo749ecf12014-10-21 20:06:57 -0700758 EXPECT_CALL(*device_policy, LoadPolicy())
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800759 .Times(testing::AtLeast(1))
760 .WillRepeatedly(Return(true));
Igor9fd76b62017-12-11 15:24:18 +0100761 attempter_.policy_provider_.reset(
762 new policy::PolicyProvider(std::move(device_policy)));
Alex Deymo749ecf12014-10-21 20:06:57 -0700763
764 {
765 InSequence s;
Askar Aitzhan570ca872019-04-24 11:16:12 +0200766 for (const auto& update_action_type : GetUpdateActionTypes()) {
Alex Deymo749ecf12014-10-21 20:06:57 -0700767 EXPECT_CALL(*processor_,
Amin Hassanid3f4bea2018-04-30 14:52:40 -0700768 EnqueueAction(Pointee(
Askar Aitzhan570ca872019-04-24 11:16:12 +0200769 Property(&AbstractAction::Type, update_action_type))));
Alex Deymo749ecf12014-10-21 20:06:57 -0700770 }
Gilad Arnold74b5f552014-10-07 08:17:16 -0700771 EXPECT_CALL(*processor_, StartProcessing());
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700772 }
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700773
Amin Hassanie8153632020-10-27 15:11:28 -0700774 attempter_.Update({});
Alex Deymo60ca1a72015-06-18 18:19:15 -0700775 loop_.PostTask(FROM_HERE,
776 base::Bind(&UpdateAttempterTest::UpdateTestVerify,
777 base::Unretained(this)));
Darin Petkove6ef2f82011-03-07 17:31:11 -0800778}
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700779
Darin Petkove6ef2f82011-03-07 17:31:11 -0800780void UpdateAttempterTest::UpdateTestVerify() {
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700781 EXPECT_EQ(0, attempter_.http_response_code());
782 EXPECT_EQ(&attempter_, processor_->delegate());
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700783 EXPECT_EQ(UpdateStatus::CHECKING_FOR_UPDATE, attempter_.status());
Alex Deymo60ca1a72015-06-18 18:19:15 -0700784 loop_.BreakLoop();
Darin Petkove6ef2f82011-03-07 17:31:11 -0800785}
786
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800787void UpdateAttempterTest::RollbackTestStart(bool enterprise_rollback,
788 bool valid_slot) {
Chris Sosa76a29ae2013-07-11 17:59:24 -0700789 // Create a device policy so that we can change settings.
Igor9fd76b62017-12-11 15:24:18 +0100790 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Chris Sosa76a29ae2013-07-11 17:59:24 -0700791 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
Amin Hassani538bd592020-11-04 20:46:08 -0800792 FakeSystemState::Get()->set_device_policy(device_policy.get());
Igor9fd76b62017-12-11 15:24:18 +0100793 if (enterprise_rollback) {
794 // We return an empty owner as this is an enterprise.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800795 EXPECT_CALL(*device_policy, GetOwner(_))
796 .WillRepeatedly(DoAll(SetArgPointee<0>(string("")), Return(true)));
Igor9fd76b62017-12-11 15:24:18 +0100797 } else {
798 // We return a fake owner as this is an owned consumer device.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800799 EXPECT_CALL(*device_policy, GetOwner(_))
800 .WillRepeatedly(DoAll(SetArgPointee<0>(string("fake.mail@fake.com")),
801 Return(true)));
Igor9fd76b62017-12-11 15:24:18 +0100802 }
803
804 attempter_.policy_provider_.reset(
805 new policy::PolicyProvider(std::move(device_policy)));
Chris Sosa76a29ae2013-07-11 17:59:24 -0700806
Alex Deymo763e7db2015-08-27 21:08:08 -0700807 if (valid_slot) {
808 BootControlInterface::Slot rollback_slot = 1;
809 LOG(INFO) << "Test Mark Bootable: "
810 << BootControlInterface::SlotName(rollback_slot);
Amin Hassani538bd592020-11-04 20:46:08 -0800811 FakeSystemState::Get()->fake_boot_control()->SetSlotBootable(rollback_slot,
812 true);
Don Garrett6646b442013-11-13 15:29:11 -0800813 }
814
Chris Sosa28e479c2013-07-12 11:39:53 -0700815 bool is_rollback_allowed = false;
Chris Sosa76a29ae2013-07-11 17:59:24 -0700816
Chris Sosad38b1132014-03-25 10:43:59 -0700817 // We only allow rollback on devices that are not enterprise enrolled and
818 // which have a valid slot to rollback to.
819 if (!enterprise_rollback && valid_slot) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800820 is_rollback_allowed = true;
Chris Sosa28e479c2013-07-12 11:39:53 -0700821 }
822
Chris Sosa28e479c2013-07-12 11:39:53 -0700823 if (is_rollback_allowed) {
Chris Sosa76a29ae2013-07-11 17:59:24 -0700824 InSequence s;
Askar Aitzhan570ca872019-04-24 11:16:12 +0200825 for (const auto& rollback_action_type : GetRollbackActionTypes()) {
Chris Sosa76a29ae2013-07-11 17:59:24 -0700826 EXPECT_CALL(*processor_,
Askar Aitzhan570ca872019-04-24 11:16:12 +0200827 EnqueueAction(Pointee(
828 Property(&AbstractAction::Type, rollback_action_type))));
Chris Sosa76a29ae2013-07-11 17:59:24 -0700829 }
Gilad Arnold74b5f552014-10-07 08:17:16 -0700830 EXPECT_CALL(*processor_, StartProcessing());
Chris Sosa76a29ae2013-07-11 17:59:24 -0700831
Chris Sosa44b9b7e2014-04-02 13:53:46 -0700832 EXPECT_TRUE(attempter_.Rollback(true));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700833 loop_.PostTask(FROM_HERE,
834 base::Bind(&UpdateAttempterTest::RollbackTestVerify,
835 base::Unretained(this)));
Chris Sosa76a29ae2013-07-11 17:59:24 -0700836 } else {
Chris Sosa44b9b7e2014-04-02 13:53:46 -0700837 EXPECT_FALSE(attempter_.Rollback(true));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700838 loop_.BreakLoop();
Chris Sosa76a29ae2013-07-11 17:59:24 -0700839 }
840}
841
842void UpdateAttempterTest::RollbackTestVerify() {
843 // Verifies the actions that were enqueued.
844 EXPECT_EQ(&attempter_, processor_->delegate());
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700845 EXPECT_EQ(UpdateStatus::ATTEMPTING_ROLLBACK, attempter_.status());
Amin Hassanid3f4bea2018-04-30 14:52:40 -0700846 EXPECT_EQ(0U, attempter_.install_plan_->partitions.size());
847 EXPECT_EQ(attempter_.install_plan_->powerwash_required, true);
Alex Deymo60ca1a72015-06-18 18:19:15 -0700848 loop_.BreakLoop();
Chris Sosa76a29ae2013-07-11 17:59:24 -0700849}
850
Darin Petkove6ef2f82011-03-07 17:31:11 -0800851TEST_F(UpdateAttempterTest, UpdateTest) {
Alex Deymo461b2592015-07-24 20:10:52 -0700852 UpdateTestStart();
Alex Deymo60ca1a72015-06-18 18:19:15 -0700853 loop_.Run();
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700854}
855
Chris Sosa76a29ae2013-07-11 17:59:24 -0700856TEST_F(UpdateAttempterTest, RollbackTest) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700857 loop_.PostTask(FROM_HERE,
858 base::Bind(&UpdateAttempterTest::RollbackTestStart,
859 base::Unretained(this),
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800860 false,
861 true));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700862 loop_.Run();
Chris Sosa76a29ae2013-07-11 17:59:24 -0700863}
864
Don Garrett6646b442013-11-13 15:29:11 -0800865TEST_F(UpdateAttempterTest, InvalidSlotRollbackTest) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700866 loop_.PostTask(FROM_HERE,
867 base::Bind(&UpdateAttempterTest::RollbackTestStart,
868 base::Unretained(this),
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800869 false,
870 false));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700871 loop_.Run();
Don Garrett6646b442013-11-13 15:29:11 -0800872}
873
Chris Sosa76a29ae2013-07-11 17:59:24 -0700874TEST_F(UpdateAttempterTest, EnterpriseRollbackTest) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700875 loop_.PostTask(FROM_HERE,
876 base::Bind(&UpdateAttempterTest::RollbackTestStart,
877 base::Unretained(this),
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800878 true,
879 true));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700880 loop_.Run();
Chris Sosa76a29ae2013-07-11 17:59:24 -0700881}
882
Thieu Le116fda32011-04-19 11:01:54 -0700883void UpdateAttempterTest::PingOmahaTestStart() {
884 EXPECT_CALL(*processor_,
Amin Hassanid3f4bea2018-04-30 14:52:40 -0700885 EnqueueAction(Pointee(Property(
886 &AbstractAction::Type, OmahaRequestAction::StaticType()))));
Gilad Arnold74b5f552014-10-07 08:17:16 -0700887 EXPECT_CALL(*processor_, StartProcessing());
Thieu Le116fda32011-04-19 11:01:54 -0700888 attempter_.PingOmaha();
Alex Deymo60ca1a72015-06-18 18:19:15 -0700889 ScheduleQuitMainLoop();
Thieu Le116fda32011-04-19 11:01:54 -0700890}
891
892TEST_F(UpdateAttempterTest, PingOmahaTest) {
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700893 EXPECT_FALSE(attempter_.waiting_for_scheduled_check_);
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700894 EXPECT_FALSE(attempter_.WasScheduleUpdatesCalled());
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700895 // Disable scheduling of subsequnet checks; we're using the |DefaultPolicy| in
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700896 // testing, which is more permissive than we want to handle here.
897 attempter_.DisableScheduleUpdates();
Alex Deymo60ca1a72015-06-18 18:19:15 -0700898 loop_.PostTask(FROM_HERE,
899 base::Bind(&UpdateAttempterTest::PingOmahaTestStart,
900 base::Unretained(this)));
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700901 brillo::MessageLoopRunMaxIterations(&loop_, 100);
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700902 EXPECT_EQ(UpdateStatus::UPDATED_NEED_REBOOT, attempter_.status());
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700903 EXPECT_TRUE(attempter_.WasScheduleUpdatesCalled());
Thieu Le116fda32011-04-19 11:01:54 -0700904}
905
Darin Petkov18c7bce2011-06-16 14:07:00 -0700906TEST_F(UpdateAttempterTest, CreatePendingErrorEventTest) {
Alex Deymo8427b4a2014-11-05 14:00:32 -0800907 MockAction action;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700908 const ErrorCode kCode = ErrorCode::kDownloadTransferError;
Darin Petkov18c7bce2011-06-16 14:07:00 -0700909 attempter_.CreatePendingErrorEvent(&action, kCode);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700910 ASSERT_NE(nullptr, attempter_.error_event_.get());
Darin Petkov18c7bce2011-06-16 14:07:00 -0700911 EXPECT_EQ(OmahaEvent::kTypeUpdateComplete, attempter_.error_event_->type);
912 EXPECT_EQ(OmahaEvent::kResultError, attempter_.error_event_->result);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700913 EXPECT_EQ(
914 static_cast<ErrorCode>(static_cast<int>(kCode) |
915 static_cast<int>(ErrorCode::kTestOmahaUrlFlag)),
916 attempter_.error_event_->error_code);
Darin Petkov18c7bce2011-06-16 14:07:00 -0700917}
918
919TEST_F(UpdateAttempterTest, CreatePendingErrorEventResumedTest) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -0700920 attempter_.install_plan_.reset(new InstallPlan);
921 attempter_.install_plan_->is_resume = true;
Alex Deymo8427b4a2014-11-05 14:00:32 -0800922 MockAction action;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700923 const ErrorCode kCode = ErrorCode::kInstallDeviceOpenError;
Darin Petkov18c7bce2011-06-16 14:07:00 -0700924 attempter_.CreatePendingErrorEvent(&action, kCode);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700925 ASSERT_NE(nullptr, attempter_.error_event_.get());
Darin Petkov18c7bce2011-06-16 14:07:00 -0700926 EXPECT_EQ(OmahaEvent::kTypeUpdateComplete, attempter_.error_event_->type);
927 EXPECT_EQ(OmahaEvent::kResultError, attempter_.error_event_->result);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700928 EXPECT_EQ(
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800929 static_cast<ErrorCode>(static_cast<int>(kCode) |
930 static_cast<int>(ErrorCode::kResumedFlag) |
931 static_cast<int>(ErrorCode::kTestOmahaUrlFlag)),
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700932 attempter_.error_event_->error_code);
Darin Petkov18c7bce2011-06-16 14:07:00 -0700933}
934
David Zeuthen8f191b22013-08-06 12:27:50 -0700935TEST_F(UpdateAttempterTest, P2PNotStartedAtStartupWhenNotEnabled) {
936 MockP2PManager mock_p2p_manager;
Amin Hassani538bd592020-11-04 20:46:08 -0800937 FakeSystemState::Get()->set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -0700938 mock_p2p_manager.fake().SetP2PEnabled(false);
939 EXPECT_CALL(mock_p2p_manager, EnsureP2PRunning()).Times(0);
940 attempter_.UpdateEngineStarted();
941}
942
943TEST_F(UpdateAttempterTest, P2PNotStartedAtStartupWhenEnabledButNotSharing) {
944 MockP2PManager mock_p2p_manager;
Amin Hassani538bd592020-11-04 20:46:08 -0800945 FakeSystemState::Get()->set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -0700946 mock_p2p_manager.fake().SetP2PEnabled(true);
947 EXPECT_CALL(mock_p2p_manager, EnsureP2PRunning()).Times(0);
948 attempter_.UpdateEngineStarted();
949}
950
951TEST_F(UpdateAttempterTest, P2PStartedAtStartupWhenEnabledAndSharing) {
952 MockP2PManager mock_p2p_manager;
Amin Hassani538bd592020-11-04 20:46:08 -0800953 FakeSystemState::Get()->set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -0700954 mock_p2p_manager.fake().SetP2PEnabled(true);
955 mock_p2p_manager.fake().SetCountSharedFilesResult(1);
Gilad Arnold74b5f552014-10-07 08:17:16 -0700956 EXPECT_CALL(mock_p2p_manager, EnsureP2PRunning());
David Zeuthen8f191b22013-08-06 12:27:50 -0700957 attempter_.UpdateEngineStarted();
958}
959
960TEST_F(UpdateAttempterTest, P2PNotEnabled) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700961 loop_.PostTask(FROM_HERE,
962 base::Bind(&UpdateAttempterTest::P2PNotEnabledStart,
963 base::Unretained(this)));
964 loop_.Run();
David Zeuthen8f191b22013-08-06 12:27:50 -0700965}
Alex Deymo60ca1a72015-06-18 18:19:15 -0700966
David Zeuthen8f191b22013-08-06 12:27:50 -0700967void UpdateAttempterTest::P2PNotEnabledStart() {
968 // If P2P is not enabled, check that we do not attempt housekeeping
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700969 // and do not convey that P2P is to be used.
David Zeuthen8f191b22013-08-06 12:27:50 -0700970 MockP2PManager mock_p2p_manager;
Amin Hassani538bd592020-11-04 20:46:08 -0800971 FakeSystemState::Get()->set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -0700972 mock_p2p_manager.fake().SetP2PEnabled(false);
973 EXPECT_CALL(mock_p2p_manager, PerformHousekeeping()).Times(0);
Amin Hassanie8153632020-10-27 15:11:28 -0700974 attempter_.Update({});
Alex Deymo60ca1a72015-06-18 18:19:15 -0700975 EXPECT_FALSE(actual_using_p2p_for_downloading_);
Gilad Arnold74b5f552014-10-07 08:17:16 -0700976 EXPECT_FALSE(actual_using_p2p_for_sharing());
Alex Deymo60ca1a72015-06-18 18:19:15 -0700977 ScheduleQuitMainLoop();
David Zeuthen8f191b22013-08-06 12:27:50 -0700978}
979
980TEST_F(UpdateAttempterTest, P2PEnabledStartingFails) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700981 loop_.PostTask(FROM_HERE,
982 base::Bind(&UpdateAttempterTest::P2PEnabledStartingFailsStart,
983 base::Unretained(this)));
984 loop_.Run();
David Zeuthen8f191b22013-08-06 12:27:50 -0700985}
Alex Deymo60ca1a72015-06-18 18:19:15 -0700986
David Zeuthen8f191b22013-08-06 12:27:50 -0700987void UpdateAttempterTest::P2PEnabledStartingFailsStart() {
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700988 // If P2P is enabled, but starting it fails ensure we don't do
989 // any housekeeping and do not convey that P2P should be used.
David Zeuthen8f191b22013-08-06 12:27:50 -0700990 MockP2PManager mock_p2p_manager;
Amin Hassani538bd592020-11-04 20:46:08 -0800991 FakeSystemState::Get()->set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -0700992 mock_p2p_manager.fake().SetP2PEnabled(true);
993 mock_p2p_manager.fake().SetEnsureP2PRunningResult(false);
994 mock_p2p_manager.fake().SetPerformHousekeepingResult(false);
995 EXPECT_CALL(mock_p2p_manager, PerformHousekeeping()).Times(0);
Amin Hassanie8153632020-10-27 15:11:28 -0700996 attempter_.Update({});
Gilad Arnold74b5f552014-10-07 08:17:16 -0700997 EXPECT_FALSE(actual_using_p2p_for_downloading());
998 EXPECT_FALSE(actual_using_p2p_for_sharing());
Alex Deymo60ca1a72015-06-18 18:19:15 -0700999 ScheduleQuitMainLoop();
David Zeuthen8f191b22013-08-06 12:27:50 -07001000}
1001
1002TEST_F(UpdateAttempterTest, P2PEnabledHousekeepingFails) {
Alex Deymo60ca1a72015-06-18 18:19:15 -07001003 loop_.PostTask(
1004 FROM_HERE,
1005 base::Bind(&UpdateAttempterTest::P2PEnabledHousekeepingFailsStart,
1006 base::Unretained(this)));
1007 loop_.Run();
David Zeuthen8f191b22013-08-06 12:27:50 -07001008}
Alex Deymo60ca1a72015-06-18 18:19:15 -07001009
David Zeuthen8f191b22013-08-06 12:27:50 -07001010void UpdateAttempterTest::P2PEnabledHousekeepingFailsStart() {
Jae Hoon Kimedb65502019-06-14 11:52:17 -07001011 // If P2P is enabled, starting it works but housekeeping fails, ensure
1012 // we do not convey P2P is to be used.
David Zeuthen8f191b22013-08-06 12:27:50 -07001013 MockP2PManager mock_p2p_manager;
Amin Hassani538bd592020-11-04 20:46:08 -08001014 FakeSystemState::Get()->set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -07001015 mock_p2p_manager.fake().SetP2PEnabled(true);
1016 mock_p2p_manager.fake().SetEnsureP2PRunningResult(true);
1017 mock_p2p_manager.fake().SetPerformHousekeepingResult(false);
Gilad Arnold74b5f552014-10-07 08:17:16 -07001018 EXPECT_CALL(mock_p2p_manager, PerformHousekeeping());
Amin Hassanie8153632020-10-27 15:11:28 -07001019 attempter_.Update({});
Gilad Arnold74b5f552014-10-07 08:17:16 -07001020 EXPECT_FALSE(actual_using_p2p_for_downloading());
1021 EXPECT_FALSE(actual_using_p2p_for_sharing());
Alex Deymo60ca1a72015-06-18 18:19:15 -07001022 ScheduleQuitMainLoop();
David Zeuthen8f191b22013-08-06 12:27:50 -07001023}
1024
1025TEST_F(UpdateAttempterTest, P2PEnabled) {
Alex Deymo60ca1a72015-06-18 18:19:15 -07001026 loop_.PostTask(FROM_HERE,
1027 base::Bind(&UpdateAttempterTest::P2PEnabledStart,
1028 base::Unretained(this)));
1029 loop_.Run();
David Zeuthen8f191b22013-08-06 12:27:50 -07001030}
Alex Deymo60ca1a72015-06-18 18:19:15 -07001031
David Zeuthen8f191b22013-08-06 12:27:50 -07001032void UpdateAttempterTest::P2PEnabledStart() {
1033 MockP2PManager mock_p2p_manager;
Amin Hassani538bd592020-11-04 20:46:08 -08001034 FakeSystemState::Get()->set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -07001035 // If P2P is enabled and starting it works, check that we performed
Jae Hoon Kimedb65502019-06-14 11:52:17 -07001036 // housekeeping and that we convey P2P should be used.
David Zeuthen8f191b22013-08-06 12:27:50 -07001037 mock_p2p_manager.fake().SetP2PEnabled(true);
1038 mock_p2p_manager.fake().SetEnsureP2PRunningResult(true);
1039 mock_p2p_manager.fake().SetPerformHousekeepingResult(true);
Gilad Arnold74b5f552014-10-07 08:17:16 -07001040 EXPECT_CALL(mock_p2p_manager, PerformHousekeeping());
Amin Hassanie8153632020-10-27 15:11:28 -07001041 attempter_.Update({});
Gilad Arnold74b5f552014-10-07 08:17:16 -07001042 EXPECT_TRUE(actual_using_p2p_for_downloading());
1043 EXPECT_TRUE(actual_using_p2p_for_sharing());
Alex Deymo60ca1a72015-06-18 18:19:15 -07001044 ScheduleQuitMainLoop();
David Zeuthen8f191b22013-08-06 12:27:50 -07001045}
1046
1047TEST_F(UpdateAttempterTest, P2PEnabledInteractive) {
Alex Deymo60ca1a72015-06-18 18:19:15 -07001048 loop_.PostTask(FROM_HERE,
1049 base::Bind(&UpdateAttempterTest::P2PEnabledInteractiveStart,
1050 base::Unretained(this)));
1051 loop_.Run();
David Zeuthen8f191b22013-08-06 12:27:50 -07001052}
Alex Deymo60ca1a72015-06-18 18:19:15 -07001053
David Zeuthen8f191b22013-08-06 12:27:50 -07001054void UpdateAttempterTest::P2PEnabledInteractiveStart() {
1055 MockP2PManager mock_p2p_manager;
Amin Hassani538bd592020-11-04 20:46:08 -08001056 FakeSystemState::Get()->set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -07001057 // For an interactive check, if P2P is enabled and starting it
1058 // works, check that we performed housekeeping and that we convey
Jae Hoon Kimedb65502019-06-14 11:52:17 -07001059 // P2P should be used for sharing but NOT for downloading.
David Zeuthen8f191b22013-08-06 12:27:50 -07001060 mock_p2p_manager.fake().SetP2PEnabled(true);
1061 mock_p2p_manager.fake().SetEnsureP2PRunningResult(true);
1062 mock_p2p_manager.fake().SetPerformHousekeepingResult(true);
Gilad Arnold74b5f552014-10-07 08:17:16 -07001063 EXPECT_CALL(mock_p2p_manager, PerformHousekeeping());
Amin Hassanie8153632020-10-27 15:11:28 -07001064 attempter_.Update({.interactive = true});
Gilad Arnold74b5f552014-10-07 08:17:16 -07001065 EXPECT_FALSE(actual_using_p2p_for_downloading());
1066 EXPECT_TRUE(actual_using_p2p_for_sharing());
Alex Deymo60ca1a72015-06-18 18:19:15 -07001067 ScheduleQuitMainLoop();
David Zeuthen8f191b22013-08-06 12:27:50 -07001068}
1069
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001070TEST_F(UpdateAttempterTest, ReadScatterFactorFromPolicy) {
Alex Deymo60ca1a72015-06-18 18:19:15 -07001071 loop_.PostTask(
1072 FROM_HERE,
1073 base::Bind(&UpdateAttempterTest::ReadScatterFactorFromPolicyTestStart,
1074 base::Unretained(this)));
1075 loop_.Run();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001076}
1077
1078// Tests that the scatter_factor_in_seconds value is properly fetched
1079// from the device policy.
1080void UpdateAttempterTest::ReadScatterFactorFromPolicyTestStart() {
Ben Chan9abb7632014-08-07 00:10:53 -07001081 int64_t scatter_factor_in_seconds = 36000;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001082
Igor9fd76b62017-12-11 15:24:18 +01001083 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001084 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
Amin Hassani538bd592020-11-04 20:46:08 -08001085 FakeSystemState::Get()->set_device_policy(device_policy.get());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001086
1087 EXPECT_CALL(*device_policy, GetScatterFactorInSeconds(_))
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001088 .WillRepeatedly(
1089 DoAll(SetArgPointee<0>(scatter_factor_in_seconds), Return(true)));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001090
Igor9fd76b62017-12-11 15:24:18 +01001091 attempter_.policy_provider_.reset(
1092 new policy::PolicyProvider(std::move(device_policy)));
1093
Amin Hassanie8153632020-10-27 15:11:28 -07001094 attempter_.Update({});
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001095 EXPECT_EQ(scatter_factor_in_seconds, attempter_.scatter_factor_.InSeconds());
1096
Alex Deymo60ca1a72015-06-18 18:19:15 -07001097 ScheduleQuitMainLoop();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001098}
1099
1100TEST_F(UpdateAttempterTest, DecrementUpdateCheckCountTest) {
Alex Deymo60ca1a72015-06-18 18:19:15 -07001101 loop_.PostTask(
1102 FROM_HERE,
1103 base::Bind(&UpdateAttempterTest::DecrementUpdateCheckCountTestStart,
1104 base::Unretained(this)));
1105 loop_.Run();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001106}
1107
1108void UpdateAttempterTest::DecrementUpdateCheckCountTestStart() {
1109 // Tests that the scatter_factor_in_seconds value is properly fetched
1110 // from the device policy and is decremented if value > 0.
Ben Chan9abb7632014-08-07 00:10:53 -07001111 int64_t initial_value = 5;
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001112 FakePrefs fake_prefs;
1113 attempter_.prefs_ = &fake_prefs;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001114
Amin Hassani538bd592020-11-04 20:46:08 -08001115 FakeSystemState::Get()->fake_hardware()->SetIsOOBEComplete(Time::UnixEpoch());
Jay Srinivasan08fce042012-06-07 16:31:01 -07001116
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001117 EXPECT_TRUE(fake_prefs.SetInt64(kPrefsUpdateCheckCount, initial_value));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001118
Ben Chan9abb7632014-08-07 00:10:53 -07001119 int64_t scatter_factor_in_seconds = 10;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001120
Igor9fd76b62017-12-11 15:24:18 +01001121 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001122 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
Amin Hassani538bd592020-11-04 20:46:08 -08001123 FakeSystemState::Get()->set_device_policy(device_policy.get());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001124
1125 EXPECT_CALL(*device_policy, GetScatterFactorInSeconds(_))
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001126 .WillRepeatedly(
1127 DoAll(SetArgPointee<0>(scatter_factor_in_seconds), Return(true)));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001128
Igor9fd76b62017-12-11 15:24:18 +01001129 attempter_.policy_provider_.reset(
1130 new policy::PolicyProvider(std::move(device_policy)));
1131
Amin Hassanie8153632020-10-27 15:11:28 -07001132 attempter_.Update({});
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001133 EXPECT_EQ(scatter_factor_in_seconds, attempter_.scatter_factor_.InSeconds());
1134
1135 // Make sure the file still exists.
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001136 EXPECT_TRUE(fake_prefs.Exists(kPrefsUpdateCheckCount));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001137
Ben Chan9abb7632014-08-07 00:10:53 -07001138 int64_t new_value;
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001139 EXPECT_TRUE(fake_prefs.GetInt64(kPrefsUpdateCheckCount, &new_value));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001140 EXPECT_EQ(initial_value - 1, new_value);
1141
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001142 EXPECT_TRUE(
1143 attempter_.omaha_request_params_->update_check_count_wait_enabled());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001144
1145 // However, if the count is already 0, it's not decremented. Test that.
1146 initial_value = 0;
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001147 EXPECT_TRUE(fake_prefs.SetInt64(kPrefsUpdateCheckCount, initial_value));
Amin Hassanie8153632020-10-27 15:11:28 -07001148 attempter_.Update({});
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001149 EXPECT_TRUE(fake_prefs.Exists(kPrefsUpdateCheckCount));
1150 EXPECT_TRUE(fake_prefs.GetInt64(kPrefsUpdateCheckCount, &new_value));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001151 EXPECT_EQ(initial_value, new_value);
1152
Alex Deymo60ca1a72015-06-18 18:19:15 -07001153 ScheduleQuitMainLoop();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001154}
1155
Jay Srinivasan08fce042012-06-07 16:31:01 -07001156TEST_F(UpdateAttempterTest, NoScatteringDoneDuringManualUpdateTestStart) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001157 loop_.PostTask(
1158 FROM_HERE,
1159 base::Bind(
1160 &UpdateAttempterTest::NoScatteringDoneDuringManualUpdateTestStart,
1161 base::Unretained(this)));
Alex Deymo60ca1a72015-06-18 18:19:15 -07001162 loop_.Run();
Jay Srinivasan08fce042012-06-07 16:31:01 -07001163}
1164
1165void UpdateAttempterTest::NoScatteringDoneDuringManualUpdateTestStart() {
1166 // Tests that no scattering logic is enabled if the update check
1167 // is manually done (as opposed to a scheduled update check)
Ben Chan9abb7632014-08-07 00:10:53 -07001168 int64_t initial_value = 8;
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001169 FakePrefs fake_prefs;
1170 attempter_.prefs_ = &fake_prefs;
Jay Srinivasan08fce042012-06-07 16:31:01 -07001171
Amin Hassani538bd592020-11-04 20:46:08 -08001172 FakeSystemState::Get()->fake_hardware()->SetIsOOBEComplete(Time::UnixEpoch());
1173 FakeSystemState::Get()->set_prefs(&fake_prefs);
Jay Srinivasan08fce042012-06-07 16:31:01 -07001174
Adolfo Victoriad3a1e352018-07-16 11:40:47 -07001175 EXPECT_TRUE(
1176 fake_prefs.SetInt64(kPrefsWallClockScatteringWaitPeriod, initial_value));
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001177 EXPECT_TRUE(fake_prefs.SetInt64(kPrefsUpdateCheckCount, initial_value));
Jay Srinivasan08fce042012-06-07 16:31:01 -07001178
1179 // make sure scatter_factor is non-zero as scattering is disabled
1180 // otherwise.
Ben Chan9abb7632014-08-07 00:10:53 -07001181 int64_t scatter_factor_in_seconds = 50;
Jay Srinivasan08fce042012-06-07 16:31:01 -07001182
Igor9fd76b62017-12-11 15:24:18 +01001183 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Jay Srinivasan08fce042012-06-07 16:31:01 -07001184 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
Amin Hassani538bd592020-11-04 20:46:08 -08001185 FakeSystemState::Get()->set_device_policy(device_policy.get());
Jay Srinivasan08fce042012-06-07 16:31:01 -07001186
1187 EXPECT_CALL(*device_policy, GetScatterFactorInSeconds(_))
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001188 .WillRepeatedly(
1189 DoAll(SetArgPointee<0>(scatter_factor_in_seconds), Return(true)));
Jay Srinivasan08fce042012-06-07 16:31:01 -07001190
Igor9fd76b62017-12-11 15:24:18 +01001191 attempter_.policy_provider_.reset(
1192 new policy::PolicyProvider(std::move(device_policy)));
1193
Gilad Arnoldb92f0df2013-01-10 16:32:45 -08001194 // Trigger an interactive check so we can test that scattering is disabled.
Amin Hassanie8153632020-10-27 15:11:28 -07001195 attempter_.Update({.interactive = true});
Jay Srinivasan08fce042012-06-07 16:31:01 -07001196 EXPECT_EQ(scatter_factor_in_seconds, attempter_.scatter_factor_.InSeconds());
1197
1198 // Make sure scattering is disabled for manual (i.e. user initiated) update
Jay Srinivasan21be0752012-07-25 15:44:56 -07001199 // checks and all artifacts are removed.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001200 EXPECT_FALSE(
1201 attempter_.omaha_request_params_->wall_clock_based_wait_enabled());
Adolfo Victoriad3a1e352018-07-16 11:40:47 -07001202 EXPECT_FALSE(fake_prefs.Exists(kPrefsWallClockScatteringWaitPeriod));
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001203 EXPECT_EQ(0, attempter_.omaha_request_params_->waiting_period().InSeconds());
1204 EXPECT_FALSE(
1205 attempter_.omaha_request_params_->update_check_count_wait_enabled());
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001206 EXPECT_FALSE(fake_prefs.Exists(kPrefsUpdateCheckCount));
Jay Srinivasan08fce042012-06-07 16:31:01 -07001207
Alex Deymo60ca1a72015-06-18 18:19:15 -07001208 ScheduleQuitMainLoop();
Jay Srinivasan08fce042012-06-07 16:31:01 -07001209}
1210
Adolfo Victoria497044c2018-07-18 07:51:42 -07001211void UpdateAttempterTest::SetUpStagingTest(const StagingSchedule& schedule,
1212 FakePrefs* prefs) {
1213 attempter_.prefs_ = prefs;
Amin Hassani538bd592020-11-04 20:46:08 -08001214 FakeSystemState::Get()->set_prefs(prefs);
Adolfo Victoria497044c2018-07-18 07:51:42 -07001215
1216 int64_t initial_value = 8;
1217 EXPECT_TRUE(
1218 prefs->SetInt64(kPrefsWallClockScatteringWaitPeriod, initial_value));
1219 EXPECT_TRUE(prefs->SetInt64(kPrefsUpdateCheckCount, initial_value));
1220 attempter_.scatter_factor_ = TimeDelta::FromSeconds(20);
1221
1222 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
1223 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
Amin Hassani538bd592020-11-04 20:46:08 -08001224 FakeSystemState::Get()->set_device_policy(device_policy.get());
Adolfo Victoria497044c2018-07-18 07:51:42 -07001225 EXPECT_CALL(*device_policy, GetDeviceUpdateStagingSchedule(_))
1226 .WillRepeatedly(DoAll(SetArgPointee<0>(schedule), Return(true)));
1227
1228 attempter_.policy_provider_.reset(
1229 new policy::PolicyProvider(std::move(device_policy)));
1230}
1231
1232TEST_F(UpdateAttempterTest, StagingSetsPrefsAndTurnsOffScattering) {
1233 loop_.PostTask(
1234 FROM_HERE,
1235 base::Bind(
1236 &UpdateAttempterTest::StagingSetsPrefsAndTurnsOffScatteringStart,
1237 base::Unretained(this)));
1238 loop_.Run();
1239}
1240
1241void UpdateAttempterTest::StagingSetsPrefsAndTurnsOffScatteringStart() {
1242 // Tests that staging sets its prefs properly and turns off scattering.
Amin Hassani538bd592020-11-04 20:46:08 -08001243 FakeSystemState::Get()->fake_hardware()->SetIsOOBEComplete(Time::UnixEpoch());
Adolfo Victoria497044c2018-07-18 07:51:42 -07001244 FakePrefs fake_prefs;
1245 SetUpStagingTest(kValidStagingSchedule, &fake_prefs);
1246
Amin Hassanie8153632020-10-27 15:11:28 -07001247 attempter_.Update({});
Adolfo Victoria497044c2018-07-18 07:51:42 -07001248 // Check that prefs have the correct values.
1249 int64_t update_count;
1250 EXPECT_TRUE(fake_prefs.GetInt64(kPrefsUpdateCheckCount, &update_count));
1251 int64_t waiting_time_days;
1252 EXPECT_TRUE(fake_prefs.GetInt64(kPrefsWallClockStagingWaitPeriod,
1253 &waiting_time_days));
1254 EXPECT_GT(waiting_time_days, 0);
1255 // Update count should have been decremented.
1256 EXPECT_EQ(7, update_count);
1257 // Check that Omaha parameters were updated correctly.
1258 EXPECT_TRUE(
1259 attempter_.omaha_request_params_->update_check_count_wait_enabled());
1260 EXPECT_TRUE(
1261 attempter_.omaha_request_params_->wall_clock_based_wait_enabled());
1262 EXPECT_EQ(waiting_time_days,
1263 attempter_.omaha_request_params_->waiting_period().InDays());
1264 // Check class variables.
1265 EXPECT_EQ(waiting_time_days, attempter_.staging_wait_time_.InDays());
1266 EXPECT_EQ(kValidStagingSchedule, attempter_.staging_schedule_);
1267 // Check that scattering is turned off
1268 EXPECT_EQ(0, attempter_.scatter_factor_.InSeconds());
1269 EXPECT_FALSE(fake_prefs.Exists(kPrefsWallClockScatteringWaitPeriod));
1270
1271 ScheduleQuitMainLoop();
1272}
1273
1274void UpdateAttempterTest::CheckStagingOff() {
1275 // Check that all prefs were removed.
1276 EXPECT_FALSE(attempter_.prefs_->Exists(kPrefsUpdateCheckCount));
1277 EXPECT_FALSE(attempter_.prefs_->Exists(kPrefsWallClockScatteringWaitPeriod));
1278 EXPECT_FALSE(attempter_.prefs_->Exists(kPrefsWallClockStagingWaitPeriod));
1279 // Check that the Omaha parameters have the correct value.
1280 EXPECT_EQ(0, attempter_.omaha_request_params_->waiting_period().InDays());
1281 EXPECT_EQ(attempter_.omaha_request_params_->waiting_period(),
1282 attempter_.staging_wait_time_);
1283 EXPECT_FALSE(
1284 attempter_.omaha_request_params_->update_check_count_wait_enabled());
1285 EXPECT_FALSE(
1286 attempter_.omaha_request_params_->wall_clock_based_wait_enabled());
1287 // Check that scattering is turned off too.
1288 EXPECT_EQ(0, attempter_.scatter_factor_.InSeconds());
1289}
1290
1291TEST_F(UpdateAttempterTest, StagingOffIfInteractive) {
1292 loop_.PostTask(FROM_HERE,
1293 base::Bind(&UpdateAttempterTest::StagingOffIfInteractiveStart,
1294 base::Unretained(this)));
1295 loop_.Run();
1296}
1297
1298void UpdateAttempterTest::StagingOffIfInteractiveStart() {
1299 // Tests that staging is turned off when an interactive update is requested.
Amin Hassani538bd592020-11-04 20:46:08 -08001300 FakeSystemState::Get()->fake_hardware()->SetIsOOBEComplete(Time::UnixEpoch());
Adolfo Victoria497044c2018-07-18 07:51:42 -07001301 FakePrefs fake_prefs;
1302 SetUpStagingTest(kValidStagingSchedule, &fake_prefs);
1303
Amin Hassanie8153632020-10-27 15:11:28 -07001304 attempter_.Update({.interactive = true});
Adolfo Victoria497044c2018-07-18 07:51:42 -07001305 CheckStagingOff();
1306
1307 ScheduleQuitMainLoop();
1308}
1309
1310TEST_F(UpdateAttempterTest, StagingOffIfOobe) {
1311 loop_.PostTask(FROM_HERE,
1312 base::Bind(&UpdateAttempterTest::StagingOffIfOobeStart,
1313 base::Unretained(this)));
1314 loop_.Run();
1315}
1316
1317void UpdateAttempterTest::StagingOffIfOobeStart() {
1318 // Tests that staging is turned off if OOBE hasn't been completed.
Amin Hassani538bd592020-11-04 20:46:08 -08001319 FakeSystemState::Get()->fake_hardware()->SetIsOOBEEnabled(true);
1320 FakeSystemState::Get()->fake_hardware()->UnsetIsOOBEComplete();
Adolfo Victoria497044c2018-07-18 07:51:42 -07001321 FakePrefs fake_prefs;
1322 SetUpStagingTest(kValidStagingSchedule, &fake_prefs);
1323
Amin Hassanie8153632020-10-27 15:11:28 -07001324 attempter_.Update({.interactive = true});
Adolfo Victoria497044c2018-07-18 07:51:42 -07001325 CheckStagingOff();
1326
1327 ScheduleQuitMainLoop();
1328}
1329
David Zeuthen985b1122013-10-09 12:13:15 -07001330// Checks that we only report daily metrics at most every 24 hours.
1331TEST_F(UpdateAttempterTest, ReportDailyMetrics) {
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001332 FakePrefs fake_prefs;
Amin Hassani538bd592020-11-04 20:46:08 -08001333 FakeSystemState::Get()->set_prefs(&fake_prefs);
Amin Hassani0468a762020-11-17 23:53:48 -08001334 auto* fake_clock = FakeSystemState::Get()->fake_clock();
David Zeuthen985b1122013-10-09 12:13:15 -07001335
1336 Time epoch = Time::FromInternalValue(0);
Amin Hassani0468a762020-11-17 23:53:48 -08001337 fake_clock->SetWallclockTime(epoch);
David Zeuthen985b1122013-10-09 12:13:15 -07001338
1339 // If there is no kPrefsDailyMetricsLastReportedAt state variable,
1340 // we should report.
1341 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1342 // We should not report again if no time has passed.
1343 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1344
1345 // We should not report if only 10 hours has passed.
Amin Hassani0468a762020-11-17 23:53:48 -08001346 fake_clock->SetWallclockTime(epoch + TimeDelta::FromHours(10));
David Zeuthen985b1122013-10-09 12:13:15 -07001347 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1348
1349 // We should not report if only 24 hours - 1 sec has passed.
Amin Hassani0468a762020-11-17 23:53:48 -08001350 fake_clock->SetWallclockTime(epoch + TimeDelta::FromHours(24) -
1351 TimeDelta::FromSeconds(1));
David Zeuthen985b1122013-10-09 12:13:15 -07001352 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1353
1354 // We should report if 24 hours has passed.
Amin Hassani0468a762020-11-17 23:53:48 -08001355 fake_clock->SetWallclockTime(epoch + TimeDelta::FromHours(24));
David Zeuthen985b1122013-10-09 12:13:15 -07001356 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1357
1358 // But then we should not report again..
1359 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1360
1361 // .. until another 24 hours has passed
Amin Hassani0468a762020-11-17 23:53:48 -08001362 fake_clock->SetWallclockTime(epoch + TimeDelta::FromHours(47));
David Zeuthen985b1122013-10-09 12:13:15 -07001363 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
Amin Hassani0468a762020-11-17 23:53:48 -08001364 fake_clock->SetWallclockTime(epoch + TimeDelta::FromHours(48));
David Zeuthen985b1122013-10-09 12:13:15 -07001365 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1366 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1367
1368 // .. and another 24 hours
Amin Hassani0468a762020-11-17 23:53:48 -08001369 fake_clock->SetWallclockTime(epoch + TimeDelta::FromHours(71));
David Zeuthen985b1122013-10-09 12:13:15 -07001370 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
Amin Hassani0468a762020-11-17 23:53:48 -08001371 fake_clock->SetWallclockTime(epoch + TimeDelta::FromHours(72));
David Zeuthen985b1122013-10-09 12:13:15 -07001372 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1373 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1374
1375 // If the span between time of reporting and present time is
1376 // negative, we report. This is in order to reset the timestamp and
1377 // avoid an edge condition whereby a distant point in the future is
1378 // in the state variable resulting in us never ever reporting again.
Amin Hassani0468a762020-11-17 23:53:48 -08001379 fake_clock->SetWallclockTime(epoch + TimeDelta::FromHours(71));
David Zeuthen985b1122013-10-09 12:13:15 -07001380 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1381 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1382
1383 // In this case we should not update until the clock reads 71 + 24 = 95.
1384 // Check that.
Amin Hassani0468a762020-11-17 23:53:48 -08001385 fake_clock->SetWallclockTime(epoch + TimeDelta::FromHours(94));
David Zeuthen985b1122013-10-09 12:13:15 -07001386 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
Amin Hassani0468a762020-11-17 23:53:48 -08001387 fake_clock->SetWallclockTime(epoch + TimeDelta::FromHours(95));
David Zeuthen985b1122013-10-09 12:13:15 -07001388 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1389 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
David Zeuthen985b1122013-10-09 12:13:15 -07001390}
1391
David Zeuthen3c55abd2013-10-14 12:48:03 -07001392TEST_F(UpdateAttempterTest, BootTimeInUpdateMarkerFile) {
Amin Hassani0468a762020-11-17 23:53:48 -08001393 FakeSystemState::Get()->fake_clock()->SetBootTime(Time::FromTimeT(42));
Alex Deymo906191f2015-10-12 12:22:44 -07001394 FakePrefs fake_prefs;
Amin Hassani538bd592020-11-04 20:46:08 -08001395 FakeSystemState::Get()->set_prefs(&fake_prefs);
Sen Jiangaeeb2e02016-06-09 15:00:16 -07001396 attempter_.Init();
David Zeuthen3c55abd2013-10-14 12:48:03 -07001397
1398 Time boot_time;
Sen Jiangaeeb2e02016-06-09 15:00:16 -07001399 EXPECT_FALSE(attempter_.GetBootTimeAtUpdate(&boot_time));
David Zeuthen3c55abd2013-10-14 12:48:03 -07001400
Sen Jiangaeeb2e02016-06-09 15:00:16 -07001401 attempter_.WriteUpdateCompletedMarker();
David Zeuthen3c55abd2013-10-14 12:48:03 -07001402
Sen Jiangaeeb2e02016-06-09 15:00:16 -07001403 EXPECT_TRUE(attempter_.GetBootTimeAtUpdate(&boot_time));
David Zeuthen3c55abd2013-10-14 12:48:03 -07001404 EXPECT_EQ(boot_time.ToTimeT(), 42);
1405}
1406
David Pursell02c18642014-11-06 11:26:11 -08001407TEST_F(UpdateAttempterTest, AnyUpdateSourceAllowedUnofficial) {
Amin Hassani538bd592020-11-04 20:46:08 -08001408 FakeSystemState::Get()->fake_hardware()->SetIsOfficialBuild(false);
David Pursell02c18642014-11-06 11:26:11 -08001409 EXPECT_TRUE(attempter_.IsAnyUpdateSourceAllowed());
1410}
1411
1412TEST_F(UpdateAttempterTest, AnyUpdateSourceAllowedOfficialDevmode) {
Amin Hassani538bd592020-11-04 20:46:08 -08001413 FakeSystemState::Get()->fake_hardware()->SetIsOfficialBuild(true);
1414 FakeSystemState::Get()->fake_hardware()->SetAreDevFeaturesEnabled(true);
David Pursell02c18642014-11-06 11:26:11 -08001415 EXPECT_TRUE(attempter_.IsAnyUpdateSourceAllowed());
1416}
1417
1418TEST_F(UpdateAttempterTest, AnyUpdateSourceDisallowedOfficialNormal) {
Amin Hassani538bd592020-11-04 20:46:08 -08001419 FakeSystemState::Get()->fake_hardware()->SetIsOfficialBuild(true);
1420 FakeSystemState::Get()->fake_hardware()->SetAreDevFeaturesEnabled(false);
David Pursell02c18642014-11-06 11:26:11 -08001421 EXPECT_FALSE(attempter_.IsAnyUpdateSourceAllowed());
1422}
1423
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001424// TODO(kimjae): Follow testing pattern with params for |CheckForInstall()|.
1425// When adding, remove older tests related to |CheckForInstall()|.
1426TEST_F(UpdateAttempterTest, CheckForInstallNotIdleFails) {
1427 for (const auto status : kNonIdleUpdateStatuses) {
1428 // GIVEN a non-idle status.
1429 attempter_.status_ = status;
Xiaochu Liu8ba486f2018-11-06 11:14:10 -08001430
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001431 EXPECT_FALSE(attempter_.CheckForInstall({}, ""));
1432 }
Xiaochu Liu8ba486f2018-11-06 11:14:10 -08001433}
1434
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001435TEST_F(UpdateAttempterTest, CheckForUpdateNotIdleFails) {
1436 for (const auto status : kNonIdleUpdateStatuses) {
1437 // GIVEN a non-idle status.
1438 cfu_params_.status = status;
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001439
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001440 // THEN |ScheduleUpdates()| should not be called.
1441 cfu_params_.should_schedule_updates_be_called = false;
1442 // THEN result should indicate failure.
1443 cfu_params_.expected_result = false;
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001444
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001445 TestCheckForUpdate();
1446 }
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001447}
1448
1449TEST_F(UpdateAttempterTest, CheckForUpdateOfficalBuildClearsSource) {
1450 // GIVEN a official build.
1451
1452 // THEN we except forced app version + forced omaha url to be cleared.
1453
1454 TestCheckForUpdate();
1455}
1456
1457TEST_F(UpdateAttempterTest, CheckForUpdateUnofficialBuildChangesSource) {
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001458 // GIVEN a nonofficial build with dev features enabled.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001459 cfu_params_.is_official_build = false;
1460 cfu_params_.are_dev_features_enabled = true;
1461
1462 // THEN the forced app version + forced omaha url changes based on input.
1463 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1464 cfu_params_.expected_forced_omaha_url = cfu_params_.omaha_url;
1465
1466 TestCheckForUpdate();
1467}
1468
1469TEST_F(UpdateAttempterTest, CheckForUpdateOfficialBuildScheduledAUTest) {
1470 // GIVEN a scheduled autest omaha url.
1471 cfu_params_.omaha_url = "autest-scheduled";
1472
1473 // THEN forced app version is cleared.
1474 // THEN forced omaha url changes to default constant.
1475 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1476
1477 TestCheckForUpdate();
1478}
1479
1480TEST_F(UpdateAttempterTest, CheckForUpdateUnofficialBuildScheduledAUTest) {
1481 // GIVEN a scheduled autest omaha url.
1482 cfu_params_.omaha_url = "autest-scheduled";
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001483 // GIVEN a nonofficial build with dev features enabled.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001484 cfu_params_.is_official_build = false;
1485 cfu_params_.are_dev_features_enabled = true;
1486
1487 // THEN forced app version changes based on input.
1488 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1489 // THEN forced omaha url changes to default constant.
1490 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1491
1492 TestCheckForUpdate();
1493}
1494
1495TEST_F(UpdateAttempterTest, CheckForUpdateOfficialBuildAUTest) {
1496 // GIVEN a autest omaha url.
1497 cfu_params_.omaha_url = "autest";
1498
1499 // THEN forced app version is cleared.
1500 // THEN forced omaha url changes to default constant.
1501 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1502
1503 TestCheckForUpdate();
1504}
1505
1506TEST_F(UpdateAttempterTest, CheckForUpdateUnofficialBuildAUTest) {
1507 // GIVEN a autest omha url.
1508 cfu_params_.omaha_url = "autest";
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001509 // GIVEN a nonofficial build with dev features enabled.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001510 cfu_params_.is_official_build = false;
1511 cfu_params_.are_dev_features_enabled = true;
1512
1513 // THEN forced app version changes based on input.
1514 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1515 // THEN forced omaha url changes to default constant.
1516 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1517
1518 TestCheckForUpdate();
1519}
1520
1521TEST_F(UpdateAttempterTest,
1522 CheckForUpdateNonInteractiveOfficialBuildScheduledAUTest) {
1523 // GIVEN a scheduled autest omaha url.
1524 cfu_params_.omaha_url = "autest-scheduled";
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001525 // GIVEN a noninteractive update.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001526 cfu_params_.flags = UpdateAttemptFlags::kFlagNonInteractive;
1527
1528 // THEN forced app version is cleared.
1529 // THEN forced omaha url changes to default constant.
1530 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1531
1532 TestCheckForUpdate();
1533}
1534
1535TEST_F(UpdateAttempterTest,
1536 CheckForUpdateNonInteractiveUnofficialBuildScheduledAUTest) {
1537 // GIVEN a scheduled autest omaha url.
1538 cfu_params_.omaha_url = "autest-scheduled";
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001539 // GIVEN a noninteractive update.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001540 cfu_params_.flags = UpdateAttemptFlags::kFlagNonInteractive;
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001541 // GIVEN a nonofficial build with dev features enabled.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001542 cfu_params_.is_official_build = false;
1543 cfu_params_.are_dev_features_enabled = true;
1544
1545 // THEN forced app version changes based on input.
1546 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1547 // THEN forced omaha url changes to default constant.
1548 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1549
1550 TestCheckForUpdate();
1551}
1552
1553TEST_F(UpdateAttempterTest, CheckForUpdateNonInteractiveOfficialBuildAUTest) {
1554 // GIVEN a autest omaha url.
1555 cfu_params_.omaha_url = "autest";
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001556 // GIVEN a noninteractive update.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001557 cfu_params_.flags = UpdateAttemptFlags::kFlagNonInteractive;
1558
1559 // THEN forced app version is cleared.
1560 // THEN forced omaha url changes to default constant.
1561 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1562
1563 TestCheckForUpdate();
1564}
1565
1566TEST_F(UpdateAttempterTest, CheckForUpdateNonInteractiveUnofficialBuildAUTest) {
1567 // GIVEN a autest omaha url.
1568 cfu_params_.omaha_url = "autest";
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001569 // GIVEN a noninteractive update.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001570 cfu_params_.flags = UpdateAttemptFlags::kFlagNonInteractive;
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001571 // GIVEN a nonofficial build with dev features enabled.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001572 cfu_params_.is_official_build = false;
1573 cfu_params_.are_dev_features_enabled = true;
1574
1575 // THEN forced app version changes based on input.
1576 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1577 // THEN forced omaha url changes to default constant.
1578 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1579
1580 TestCheckForUpdate();
David Pursell02c18642014-11-06 11:26:11 -08001581}
1582
Jae Hoon Kim2b73ac22019-07-02 11:17:24 -07001583TEST_F(UpdateAttempterTest, CheckForUpdateMissingForcedCallback1) {
1584 // GIVEN a official build.
1585 // GIVEN forced callback is not set.
1586 attempter_.set_forced_update_pending_callback(nullptr);
1587
1588 // THEN we except forced app version + forced omaha url to be cleared.
1589 // THEN |ScheduleUpdates()| should not be called.
1590 cfu_params_.should_schedule_updates_be_called = false;
1591
1592 TestCheckForUpdate();
1593}
1594
1595TEST_F(UpdateAttempterTest, CheckForUpdateMissingForcedCallback2) {
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001596 // GIVEN a nonofficial build with dev features enabled.
Jae Hoon Kim2b73ac22019-07-02 11:17:24 -07001597 cfu_params_.is_official_build = false;
1598 cfu_params_.are_dev_features_enabled = true;
1599 // GIVEN forced callback is not set.
1600 attempter_.set_forced_update_pending_callback(nullptr);
1601
1602 // THEN the forced app version + forced omaha url changes based on input.
1603 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1604 cfu_params_.expected_forced_omaha_url = cfu_params_.omaha_url;
1605 // THEN |ScheduleUpdates()| should not be called.
1606 cfu_params_.should_schedule_updates_be_called = false;
1607
1608 TestCheckForUpdate();
1609}
1610
Xiaochu Liu88d90382018-08-29 16:09:11 -07001611TEST_F(UpdateAttempterTest, CheckForInstallTest) {
Amin Hassani538bd592020-11-04 20:46:08 -08001612 FakeSystemState::Get()->fake_hardware()->SetIsOfficialBuild(true);
1613 FakeSystemState::Get()->fake_hardware()->SetAreDevFeaturesEnabled(false);
Xiaochu Liu88d90382018-08-29 16:09:11 -07001614 attempter_.CheckForInstall({}, "autest");
1615 EXPECT_EQ(constants::kOmahaDefaultAUTestURL, attempter_.forced_omaha_url());
1616
1617 attempter_.CheckForInstall({}, "autest-scheduled");
1618 EXPECT_EQ(constants::kOmahaDefaultAUTestURL, attempter_.forced_omaha_url());
1619
1620 attempter_.CheckForInstall({}, "http://omaha.phishing");
1621 EXPECT_EQ("", attempter_.forced_omaha_url());
1622}
1623
Colin Howesac170d92018-11-20 16:29:28 -08001624TEST_F(UpdateAttempterTest, InstallSetsStatusIdle) {
1625 attempter_.CheckForInstall({}, "http://foo.bar");
1626 attempter_.status_ = UpdateStatus::DOWNLOADING;
1627 EXPECT_TRUE(attempter_.is_install_);
1628 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1629 UpdateEngineStatus status;
1630 attempter_.GetStatus(&status);
1631 // Should set status to idle after an install operation.
1632 EXPECT_EQ(UpdateStatus::IDLE, status.status);
1633}
1634
Colin Howes978c1082018-12-03 11:46:12 -08001635TEST_F(UpdateAttempterTest, RollbackAfterInstall) {
1636 attempter_.is_install_ = true;
1637 attempter_.Rollback(false);
1638 EXPECT_FALSE(attempter_.is_install_);
1639}
1640
1641TEST_F(UpdateAttempterTest, UpdateAfterInstall) {
1642 attempter_.is_install_ = true;
1643 attempter_.CheckForUpdate("", "", UpdateAttemptFlags::kNone);
1644 EXPECT_FALSE(attempter_.is_install_);
1645}
1646
Xiyuan Xiac0e8f9a2017-02-22 13:19:35 -08001647TEST_F(UpdateAttempterTest, TargetVersionPrefixSetAndReset) {
Amin Hassanie8153632020-10-27 15:11:28 -07001648 UpdateCheckParams params;
1649 attempter_.CalculateUpdateParams({.target_version_prefix = "1234"});
Xiyuan Xiac0e8f9a2017-02-22 13:19:35 -08001650 EXPECT_EQ("1234",
Amin Hassani538bd592020-11-04 20:46:08 -08001651 FakeSystemState::Get()->request_params()->target_version_prefix());
Xiyuan Xiac0e8f9a2017-02-22 13:19:35 -08001652
Amin Hassanie8153632020-10-27 15:11:28 -07001653 attempter_.CalculateUpdateParams({});
Amin Hassani538bd592020-11-04 20:46:08 -08001654 EXPECT_TRUE(FakeSystemState::Get()
1655 ->request_params()
1656 ->target_version_prefix()
1657 .empty());
Xiyuan Xiac0e8f9a2017-02-22 13:19:35 -08001658}
1659
Amin Hassani37b67232020-08-13 09:29:48 -07001660TEST_F(UpdateAttempterTest, TargetChannelHintSetAndReset) {
Amin Hassanie8153632020-10-27 15:11:28 -07001661 attempter_.CalculateUpdateParams({.lts_tag = "hint"});
Amin Hassani538bd592020-11-04 20:46:08 -08001662 EXPECT_EQ("hint", FakeSystemState::Get()->request_params()->lts_tag());
Amin Hassani37b67232020-08-13 09:29:48 -07001663
Amin Hassanie8153632020-10-27 15:11:28 -07001664 attempter_.CalculateUpdateParams({});
Amin Hassani538bd592020-11-04 20:46:08 -08001665 EXPECT_TRUE(FakeSystemState::Get()->request_params()->lts_tag().empty());
Amin Hassani37b67232020-08-13 09:29:48 -07001666}
1667
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001668TEST_F(UpdateAttempterTest, RollbackAllowedSetAndReset) {
Amin Hassanie8153632020-10-27 15:11:28 -07001669 attempter_.CalculateUpdateParams({
1670 .target_version_prefix = "1234",
1671 .rollback_allowed = true,
1672 .rollback_allowed_milestones = 4,
1673 });
Amin Hassani538bd592020-11-04 20:46:08 -08001674 EXPECT_TRUE(FakeSystemState::Get()->request_params()->rollback_allowed());
1675 EXPECT_EQ(
1676 4,
1677 FakeSystemState::Get()->request_params()->rollback_allowed_milestones());
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001678
Amin Hassanie8153632020-10-27 15:11:28 -07001679 attempter_.CalculateUpdateParams({
1680 .target_version_prefix = "1234",
1681 .rollback_allowed_milestones = 4,
1682 });
Amin Hassani538bd592020-11-04 20:46:08 -08001683 EXPECT_FALSE(FakeSystemState::Get()->request_params()->rollback_allowed());
1684 EXPECT_EQ(
1685 4,
1686 FakeSystemState::Get()->request_params()->rollback_allowed_milestones());
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001687}
1688
Miriam Polzeraff72002020-08-27 08:20:39 +02001689TEST_F(UpdateAttempterTest, ChannelDowngradeNoRollback) {
1690 base::ScopedTempDir tempdir;
1691 ASSERT_TRUE(tempdir.CreateUniqueTempDir());
Amin Hassani538bd592020-11-04 20:46:08 -08001692 FakeSystemState::Get()->request_params()->set_root(tempdir.GetPath().value());
Amin Hassanie8153632020-10-27 15:11:28 -07001693 attempter_.CalculateUpdateParams({
1694 .target_channel = "stable-channel",
1695 });
Amin Hassani538bd592020-11-04 20:46:08 -08001696 EXPECT_FALSE(
1697 FakeSystemState::Get()->request_params()->is_powerwash_allowed());
Miriam Polzeraff72002020-08-27 08:20:39 +02001698}
1699
1700TEST_F(UpdateAttempterTest, ChannelDowngradeRollback) {
1701 base::ScopedTempDir tempdir;
1702 ASSERT_TRUE(tempdir.CreateUniqueTempDir());
Amin Hassani538bd592020-11-04 20:46:08 -08001703 FakeSystemState::Get()->request_params()->set_root(tempdir.GetPath().value());
Amin Hassanie8153632020-10-27 15:11:28 -07001704 attempter_.CalculateUpdateParams({
1705 .rollback_on_channel_downgrade = true,
1706 .target_channel = "stable-channel",
1707 });
Amin Hassani538bd592020-11-04 20:46:08 -08001708 EXPECT_TRUE(FakeSystemState::Get()->request_params()->is_powerwash_allowed());
Miriam Polzeraff72002020-08-27 08:20:39 +02001709}
1710
Aaron Wood23bd3392017-10-06 14:48:25 -07001711TEST_F(UpdateAttempterTest, UpdateDeferredByPolicyTest) {
1712 // Construct an OmahaResponseHandlerAction that has processed an InstallPlan,
1713 // but the update is being deferred by the Policy.
Amin Hassani538bd592020-11-04 20:46:08 -08001714 OmahaResponseHandlerAction response_action;
Amin Hassani68512d42018-07-31 23:52:33 -07001715 response_action.install_plan_.version = "a.b.c.d";
Amin Hassani68512d42018-07-31 23:52:33 -07001716 response_action.install_plan_.payloads.push_back(
Aaron Wood23bd3392017-10-06 14:48:25 -07001717 {.size = 1234ULL, .type = InstallPayloadType::kFull});
Aaron Wood23bd3392017-10-06 14:48:25 -07001718 // Inform the UpdateAttempter that the OmahaResponseHandlerAction has
1719 // completed, with the deferred-update error code.
1720 attempter_.ActionCompleted(
Amin Hassani68512d42018-07-31 23:52:33 -07001721 nullptr, &response_action, ErrorCode::kOmahaUpdateDeferredPerPolicy);
Aaron Wood23bd3392017-10-06 14:48:25 -07001722 {
1723 UpdateEngineStatus status;
1724 attempter_.GetStatus(&status);
1725 EXPECT_EQ(UpdateStatus::UPDATE_AVAILABLE, status.status);
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001726 EXPECT_TRUE(attempter_.install_plan_);
1727 EXPECT_EQ(attempter_.install_plan_->version, status.new_version);
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001728 EXPECT_EQ(attempter_.install_plan_->payloads[0].size,
Aaron Wood23bd3392017-10-06 14:48:25 -07001729 status.new_size_bytes);
1730 }
1731 // An "error" event should have been created to tell Omaha that the update is
1732 // being deferred.
1733 EXPECT_TRUE(nullptr != attempter_.error_event_);
1734 EXPECT_EQ(OmahaEvent::kTypeUpdateComplete, attempter_.error_event_->type);
1735 EXPECT_EQ(OmahaEvent::kResultUpdateDeferred, attempter_.error_event_->result);
1736 ErrorCode expected_code = static_cast<ErrorCode>(
1737 static_cast<int>(ErrorCode::kOmahaUpdateDeferredPerPolicy) |
1738 static_cast<int>(ErrorCode::kTestOmahaUrlFlag));
1739 EXPECT_EQ(expected_code, attempter_.error_event_->error_code);
1740 // End the processing
1741 attempter_.ProcessingDone(nullptr, ErrorCode::kOmahaUpdateDeferredPerPolicy);
1742 // Validate the state of the attempter.
1743 {
1744 UpdateEngineStatus status;
1745 attempter_.GetStatus(&status);
1746 EXPECT_EQ(UpdateStatus::REPORTING_ERROR_EVENT, status.status);
Amin Hassani68512d42018-07-31 23:52:33 -07001747 EXPECT_EQ(response_action.install_plan_.version, status.new_version);
Amin Hassani68512d42018-07-31 23:52:33 -07001748 EXPECT_EQ(response_action.install_plan_.payloads[0].size,
Aaron Wood23bd3392017-10-06 14:48:25 -07001749 status.new_size_bytes);
1750 }
1751}
1752
1753TEST_F(UpdateAttempterTest, UpdateIsNotRunningWhenUpdateAvailable) {
Jae Hoon Kim75daa382019-07-02 11:17:24 -07001754 // Default construction for |waiting_for_scheduled_check_| is false.
Jae Hoon Kimba2fdce2019-07-11 13:18:58 -07001755 EXPECT_FALSE(attempter_.IsBusyOrUpdateScheduled());
Aaron Wood23bd3392017-10-06 14:48:25 -07001756 // Verify in-progress update with UPDATE_AVAILABLE is running
1757 attempter_.status_ = UpdateStatus::UPDATE_AVAILABLE;
Jae Hoon Kimba2fdce2019-07-11 13:18:58 -07001758 EXPECT_TRUE(attempter_.IsBusyOrUpdateScheduled());
Aaron Wood23bd3392017-10-06 14:48:25 -07001759}
1760
Aaron Woodbf5a2522017-10-04 10:58:36 -07001761TEST_F(UpdateAttempterTest, UpdateAttemptFlagsCachedAtUpdateStart) {
1762 attempter_.SetUpdateAttemptFlags(UpdateAttemptFlags::kFlagRestrictDownload);
1763
1764 UpdateCheckParams params = {.updates_enabled = true};
1765 attempter_.OnUpdateScheduled(EvalStatus::kSucceeded, params);
1766
1767 EXPECT_EQ(UpdateAttemptFlags::kFlagRestrictDownload,
1768 attempter_.GetCurrentUpdateAttemptFlags());
1769}
1770
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001771TEST_F(UpdateAttempterTest, RollbackNotAllowed) {
1772 UpdateCheckParams params = {.updates_enabled = true,
1773 .rollback_allowed = false};
1774 attempter_.OnUpdateScheduled(EvalStatus::kSucceeded, params);
Amin Hassani538bd592020-11-04 20:46:08 -08001775 EXPECT_FALSE(FakeSystemState::Get()->request_params()->rollback_allowed());
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001776}
1777
1778TEST_F(UpdateAttempterTest, RollbackAllowed) {
1779 UpdateCheckParams params = {.updates_enabled = true,
1780 .rollback_allowed = true};
1781 attempter_.OnUpdateScheduled(EvalStatus::kSucceeded, params);
Amin Hassani538bd592020-11-04 20:46:08 -08001782 EXPECT_TRUE(FakeSystemState::Get()->request_params()->rollback_allowed());
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001783}
1784
Aaron Wood081c0232017-10-19 17:14:58 -07001785TEST_F(UpdateAttempterTest, InteractiveUpdateUsesPassedRestrictions) {
1786 attempter_.SetUpdateAttemptFlags(UpdateAttemptFlags::kFlagRestrictDownload);
1787
1788 attempter_.CheckForUpdate("", "", UpdateAttemptFlags::kNone);
1789 EXPECT_EQ(UpdateAttemptFlags::kNone,
1790 attempter_.GetCurrentUpdateAttemptFlags());
1791}
1792
1793TEST_F(UpdateAttempterTest, NonInteractiveUpdateUsesSetRestrictions) {
1794 attempter_.SetUpdateAttemptFlags(UpdateAttemptFlags::kNone);
1795
1796 // This tests that when CheckForUpdate() is called with the non-interactive
1797 // flag set, that it doesn't change the current UpdateAttemptFlags.
1798 attempter_.CheckForUpdate("",
1799 "",
1800 UpdateAttemptFlags::kFlagNonInteractive |
1801 UpdateAttemptFlags::kFlagRestrictDownload);
1802 EXPECT_EQ(UpdateAttemptFlags::kNone,
1803 attempter_.GetCurrentUpdateAttemptFlags());
1804}
1805
Marton Hunyadye58bddb2018-04-10 20:27:26 +02001806void UpdateAttempterTest::ResetRollbackHappenedStart(bool is_consumer,
1807 bool is_policy_loaded,
1808 bool expected_reset) {
Amin Hassani538bd592020-11-04 20:46:08 -08001809 EXPECT_CALL(*FakeSystemState::Get()->mock_payload_state(),
1810 GetRollbackHappened())
Marton Hunyadye58bddb2018-04-10 20:27:26 +02001811 .WillRepeatedly(Return(true));
1812 auto mock_policy_provider =
1813 std::make_unique<NiceMock<policy::MockPolicyProvider>>();
1814 EXPECT_CALL(*mock_policy_provider, IsConsumerDevice())
1815 .WillRepeatedly(Return(is_consumer));
1816 EXPECT_CALL(*mock_policy_provider, device_policy_is_loaded())
1817 .WillRepeatedly(Return(is_policy_loaded));
1818 const policy::MockDevicePolicy device_policy;
1819 EXPECT_CALL(*mock_policy_provider, GetDevicePolicy())
1820 .WillRepeatedly(ReturnRef(device_policy));
Amin Hassani538bd592020-11-04 20:46:08 -08001821 EXPECT_CALL(*FakeSystemState::Get()->mock_payload_state(),
Marton Hunyadye58bddb2018-04-10 20:27:26 +02001822 SetRollbackHappened(false))
1823 .Times(expected_reset ? 1 : 0);
1824 attempter_.policy_provider_ = std::move(mock_policy_provider);
Amin Hassanie8153632020-10-27 15:11:28 -07001825 attempter_.Update({});
Marton Hunyadye58bddb2018-04-10 20:27:26 +02001826 ScheduleQuitMainLoop();
1827}
1828
1829TEST_F(UpdateAttempterTest, ResetRollbackHappenedOobe) {
1830 loop_.PostTask(FROM_HERE,
1831 base::Bind(&UpdateAttempterTest::ResetRollbackHappenedStart,
1832 base::Unretained(this),
1833 /*is_consumer=*/false,
1834 /*is_policy_loaded=*/false,
1835 /*expected_reset=*/false));
1836 loop_.Run();
1837}
1838
1839TEST_F(UpdateAttempterTest, ResetRollbackHappenedConsumer) {
1840 loop_.PostTask(FROM_HERE,
1841 base::Bind(&UpdateAttempterTest::ResetRollbackHappenedStart,
1842 base::Unretained(this),
1843 /*is_consumer=*/true,
1844 /*is_policy_loaded=*/false,
1845 /*expected_reset=*/true));
1846 loop_.Run();
1847}
1848
1849TEST_F(UpdateAttempterTest, ResetRollbackHappenedEnterprise) {
1850 loop_.PostTask(FROM_HERE,
1851 base::Bind(&UpdateAttempterTest::ResetRollbackHappenedStart,
1852 base::Unretained(this),
1853 /*is_consumer=*/false,
1854 /*is_policy_loaded=*/true,
1855 /*expected_reset=*/true));
1856 loop_.Run();
1857}
1858
Marton Hunyady199152d2018-05-07 19:08:48 +02001859TEST_F(UpdateAttempterTest, SetRollbackHappenedRollback) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001860 attempter_.install_plan_.reset(new InstallPlan);
1861 attempter_.install_plan_->is_rollback = true;
Marton Hunyady199152d2018-05-07 19:08:48 +02001862
Amin Hassani538bd592020-11-04 20:46:08 -08001863 EXPECT_CALL(*FakeSystemState::Get()->mock_payload_state(),
Marton Hunyady199152d2018-05-07 19:08:48 +02001864 SetRollbackHappened(true))
1865 .Times(1);
1866 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1867}
1868
1869TEST_F(UpdateAttempterTest, SetRollbackHappenedNotRollback) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001870 attempter_.install_plan_.reset(new InstallPlan);
1871 attempter_.install_plan_->is_rollback = false;
Marton Hunyady199152d2018-05-07 19:08:48 +02001872
Amin Hassani538bd592020-11-04 20:46:08 -08001873 EXPECT_CALL(*FakeSystemState::Get()->mock_payload_state(),
Marton Hunyady199152d2018-05-07 19:08:48 +02001874 SetRollbackHappened(true))
1875 .Times(0);
1876 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1877}
1878
Marton Hunyadya0302682018-05-16 18:52:13 +02001879TEST_F(UpdateAttempterTest, RollbackMetricsRollbackSuccess) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001880 attempter_.install_plan_.reset(new InstallPlan);
1881 attempter_.install_plan_->is_rollback = true;
1882 attempter_.install_plan_->version = kRollbackVersion;
Marton Hunyadya0302682018-05-16 18:52:13 +02001883
Amin Hassani538bd592020-11-04 20:46:08 -08001884 EXPECT_CALL(*FakeSystemState::Get()->mock_metrics_reporter(),
Marton Hunyadya0302682018-05-16 18:52:13 +02001885 ReportEnterpriseRollbackMetrics(true, kRollbackVersion))
1886 .Times(1);
1887 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1888}
1889
1890TEST_F(UpdateAttempterTest, RollbackMetricsNotRollbackSuccess) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001891 attempter_.install_plan_.reset(new InstallPlan);
1892 attempter_.install_plan_->is_rollback = false;
1893 attempter_.install_plan_->version = kRollbackVersion;
Marton Hunyadya0302682018-05-16 18:52:13 +02001894
Amin Hassani538bd592020-11-04 20:46:08 -08001895 EXPECT_CALL(*FakeSystemState::Get()->mock_metrics_reporter(),
Marton Hunyadya0302682018-05-16 18:52:13 +02001896 ReportEnterpriseRollbackMetrics(_, _))
1897 .Times(0);
1898 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1899}
1900
1901TEST_F(UpdateAttempterTest, RollbackMetricsRollbackFailure) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001902 attempter_.install_plan_.reset(new InstallPlan);
1903 attempter_.install_plan_->is_rollback = true;
1904 attempter_.install_plan_->version = kRollbackVersion;
Marton Hunyadya0302682018-05-16 18:52:13 +02001905
Amin Hassani538bd592020-11-04 20:46:08 -08001906 EXPECT_CALL(*FakeSystemState::Get()->mock_metrics_reporter(),
Marton Hunyadya0302682018-05-16 18:52:13 +02001907 ReportEnterpriseRollbackMetrics(false, kRollbackVersion))
1908 .Times(1);
1909 MockAction action;
1910 attempter_.CreatePendingErrorEvent(&action, ErrorCode::kRollbackNotPossible);
1911 attempter_.ProcessingDone(nullptr, ErrorCode::kRollbackNotPossible);
1912}
1913
1914TEST_F(UpdateAttempterTest, RollbackMetricsNotRollbackFailure) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001915 attempter_.install_plan_.reset(new InstallPlan);
1916 attempter_.install_plan_->is_rollback = false;
1917 attempter_.install_plan_->version = kRollbackVersion;
Marton Hunyadya0302682018-05-16 18:52:13 +02001918
Amin Hassani538bd592020-11-04 20:46:08 -08001919 EXPECT_CALL(*FakeSystemState::Get()->mock_metrics_reporter(),
Marton Hunyadya0302682018-05-16 18:52:13 +02001920 ReportEnterpriseRollbackMetrics(_, _))
1921 .Times(0);
1922 MockAction action;
1923 attempter_.CreatePendingErrorEvent(&action, ErrorCode::kRollbackNotPossible);
1924 attempter_.ProcessingDone(nullptr, ErrorCode::kRollbackNotPossible);
1925}
1926
May Lippert60aa3ca2018-08-15 16:55:29 -07001927TEST_F(UpdateAttempterTest, TimeToUpdateAppliedMetricFailure) {
Amin Hassani538bd592020-11-04 20:46:08 -08001928 EXPECT_CALL(*FakeSystemState::Get()->mock_metrics_reporter(),
May Lippert60aa3ca2018-08-15 16:55:29 -07001929 ReportEnterpriseUpdateSeenToDownloadDays(_, _))
1930 .Times(0);
1931 attempter_.ProcessingDone(nullptr, ErrorCode::kOmahaUpdateDeferredPerPolicy);
1932}
1933
1934TEST_F(UpdateAttempterTest, TimeToUpdateAppliedOnNonEnterprise) {
1935 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Amin Hassani538bd592020-11-04 20:46:08 -08001936 FakeSystemState::Get()->set_device_policy(device_policy.get());
May Lippert60aa3ca2018-08-15 16:55:29 -07001937 // Make device policy return that this is not enterprise enrolled
1938 EXPECT_CALL(*device_policy, IsEnterpriseEnrolled()).WillOnce(Return(false));
1939
1940 // Ensure that the metric is not recorded.
Amin Hassani538bd592020-11-04 20:46:08 -08001941 EXPECT_CALL(*FakeSystemState::Get()->mock_metrics_reporter(),
May Lippert60aa3ca2018-08-15 16:55:29 -07001942 ReportEnterpriseUpdateSeenToDownloadDays(_, _))
1943 .Times(0);
1944 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1945}
1946
1947TEST_F(UpdateAttempterTest,
1948 TimeToUpdateAppliedWithTimeRestrictionMetricSuccess) {
1949 constexpr int kDaysToUpdate = 15;
1950 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Amin Hassani538bd592020-11-04 20:46:08 -08001951 FakeSystemState::Get()->set_device_policy(device_policy.get());
May Lippert60aa3ca2018-08-15 16:55:29 -07001952 // Make device policy return that this is enterprise enrolled
1953 EXPECT_CALL(*device_policy, IsEnterpriseEnrolled()).WillOnce(Return(true));
1954 // Pretend that there's a time restriction policy in place
1955 EXPECT_CALL(*device_policy, GetDisallowedTimeIntervals(_))
1956 .WillOnce(Return(true));
1957
1958 FakePrefs fake_prefs;
1959 Time update_first_seen_at = Time::Now();
1960 fake_prefs.SetInt64(kPrefsUpdateFirstSeenAt,
1961 update_first_seen_at.ToInternalValue());
1962
May Lippert60aa3ca2018-08-15 16:55:29 -07001963 Time update_finished_at =
1964 update_first_seen_at + TimeDelta::FromDays(kDaysToUpdate);
Amin Hassani0468a762020-11-17 23:53:48 -08001965 FakeSystemState::Get()->fake_clock()->SetWallclockTime(update_finished_at);
May Lippert60aa3ca2018-08-15 16:55:29 -07001966
Amin Hassani538bd592020-11-04 20:46:08 -08001967 FakeSystemState::Get()->set_prefs(&fake_prefs);
May Lippert60aa3ca2018-08-15 16:55:29 -07001968
Amin Hassani538bd592020-11-04 20:46:08 -08001969 EXPECT_CALL(*FakeSystemState::Get()->mock_metrics_reporter(),
May Lippert60aa3ca2018-08-15 16:55:29 -07001970 ReportEnterpriseUpdateSeenToDownloadDays(true, kDaysToUpdate))
1971 .Times(1);
1972 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1973}
1974
1975TEST_F(UpdateAttempterTest,
1976 TimeToUpdateAppliedWithoutTimeRestrictionMetricSuccess) {
1977 constexpr int kDaysToUpdate = 15;
1978 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Amin Hassani538bd592020-11-04 20:46:08 -08001979 FakeSystemState::Get()->set_device_policy(device_policy.get());
May Lippert60aa3ca2018-08-15 16:55:29 -07001980 // Make device policy return that this is enterprise enrolled
1981 EXPECT_CALL(*device_policy, IsEnterpriseEnrolled()).WillOnce(Return(true));
1982 // Pretend that there's no time restriction policy in place
1983 EXPECT_CALL(*device_policy, GetDisallowedTimeIntervals(_))
1984 .WillOnce(Return(false));
1985
1986 FakePrefs fake_prefs;
1987 Time update_first_seen_at = Time::Now();
1988 fake_prefs.SetInt64(kPrefsUpdateFirstSeenAt,
1989 update_first_seen_at.ToInternalValue());
1990
May Lippert60aa3ca2018-08-15 16:55:29 -07001991 Time update_finished_at =
1992 update_first_seen_at + TimeDelta::FromDays(kDaysToUpdate);
Amin Hassani0468a762020-11-17 23:53:48 -08001993 FakeSystemState::Get()->fake_clock()->SetWallclockTime(update_finished_at);
Amin Hassani538bd592020-11-04 20:46:08 -08001994 FakeSystemState::Get()->set_prefs(&fake_prefs);
May Lippert60aa3ca2018-08-15 16:55:29 -07001995
Amin Hassani538bd592020-11-04 20:46:08 -08001996 EXPECT_CALL(*FakeSystemState::Get()->mock_metrics_reporter(),
May Lippert60aa3ca2018-08-15 16:55:29 -07001997 ReportEnterpriseUpdateSeenToDownloadDays(false, kDaysToUpdate))
1998 .Times(1);
1999 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
2000}
2001
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002002TEST_F(UpdateAttempterTest, ProcessingDoneUpdated) {
2003 // GIVEN an update finished.
2004
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002005 // THEN update_engine should call update completion.
2006 pd_params_.should_update_completed_be_called = true;
2007 // THEN need reboot since update applied.
2008 pd_params_.expected_exit_status = UpdateStatus::UPDATED_NEED_REBOOT;
2009 // THEN install indication should be false.
2010
2011 TestProcessingDone();
2012}
2013
2014TEST_F(UpdateAttempterTest, ProcessingDoneUpdatedDlcFilter) {
2015 // GIVEN an update finished.
2016 // GIVEN DLC |AppParams| list.
2017 auto dlc_1 = "dlc_1", dlc_2 = "dlc_2";
2018 pd_params_.dlc_apps_params = {{dlc_1, {.name = dlc_1, .updated = false}},
2019 {dlc_2, {.name = dlc_2}}};
2020
2021 // THEN update_engine should call update completion.
2022 pd_params_.should_update_completed_be_called = true;
2023 pd_params_.args_to_update_completed = {dlc_2};
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002024 // THEN need reboot since update applied.
2025 pd_params_.expected_exit_status = UpdateStatus::UPDATED_NEED_REBOOT;
2026 // THEN install indication should be false.
2027
2028 TestProcessingDone();
2029}
2030
2031TEST_F(UpdateAttempterTest, ProcessingDoneInstalled) {
2032 // GIVEN an install finished.
2033 pd_params_.is_install = true;
2034
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002035 // THEN update_engine should call install completion.
2036 pd_params_.should_install_completed_be_called = true;
2037 // THEN go idle.
2038 // THEN install indication should be false.
2039
2040 TestProcessingDone();
2041}
2042
2043TEST_F(UpdateAttempterTest, ProcessingDoneInstalledDlcFilter) {
2044 // GIVEN an install finished.
2045 pd_params_.is_install = true;
2046 // GIVEN DLC |AppParams| list.
2047 auto dlc_1 = "dlc_1", dlc_2 = "dlc_2";
2048 pd_params_.dlc_apps_params = {{dlc_1, {.name = dlc_1, .updated = false}},
2049 {dlc_2, {.name = dlc_2}}};
2050
2051 // THEN update_engine should call install completion.
2052 pd_params_.should_install_completed_be_called = true;
2053 pd_params_.args_to_install_completed = {dlc_2};
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002054 // THEN go idle.
2055 // THEN install indication should be false.
2056
2057 TestProcessingDone();
2058}
2059
2060TEST_F(UpdateAttempterTest, ProcessingDoneInstallReportingError) {
2061 // GIVEN an install finished.
2062 pd_params_.is_install = true;
2063 // GIVEN a reporting error occurred.
2064 pd_params_.status = UpdateStatus::REPORTING_ERROR_EVENT;
2065
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002066 // THEN update_engine should not call install completion.
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002067 // THEN go idle.
2068 // THEN install indication should be false.
2069
2070 TestProcessingDone();
2071}
2072
2073TEST_F(UpdateAttempterTest, ProcessingDoneNoUpdate) {
2074 // GIVEN an update finished.
2075 // GIVEN an action error occured.
2076 pd_params_.code = ErrorCode::kNoUpdate;
2077
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002078 // THEN update_engine should not call update completion.
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002079 // THEN go idle.
2080 // THEN install indication should be false.
2081
2082 TestProcessingDone();
2083}
2084
2085TEST_F(UpdateAttempterTest, ProcessingDoneNoInstall) {
2086 // GIVEN an install finished.
2087 pd_params_.is_install = true;
2088 // GIVEN an action error occured.
2089 pd_params_.code = ErrorCode::kNoUpdate;
2090
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002091 // THEN update_engine should not call install completion.
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002092 // THEN go idle.
2093 // THEN install indication should be false.
2094
2095 TestProcessingDone();
2096}
2097
2098TEST_F(UpdateAttempterTest, ProcessingDoneUpdateError) {
2099 // GIVEN an update finished.
2100 // GIVEN an action error occured.
2101 pd_params_.code = ErrorCode::kError;
2102 // GIVEN an event error is set.
2103 attempter_.error_event_.reset(new OmahaEvent(OmahaEvent::kTypeUpdateComplete,
2104 OmahaEvent::kResultError,
2105 ErrorCode::kError));
2106
2107 // THEN indicate a error event.
2108 pd_params_.expected_exit_status = UpdateStatus::REPORTING_ERROR_EVENT;
2109 // THEN install indication should be false.
2110
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002111 // THEN update_engine should not call update completion.
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002112 // THEN expect critical actions of |ScheduleErrorEventAction()|.
2113 EXPECT_CALL(*processor_, EnqueueAction(Pointee(_))).Times(1);
2114 EXPECT_CALL(*processor_, StartProcessing()).Times(1);
2115 // THEN |ScheduleUpdates()| will be called next |ProcessingDone()| so skip.
2116 pd_params_.should_schedule_updates_be_called = false;
2117
2118 TestProcessingDone();
2119}
2120
2121TEST_F(UpdateAttempterTest, ProcessingDoneInstallError) {
2122 // GIVEN an install finished.
2123 pd_params_.is_install = true;
2124 // GIVEN an action error occured.
2125 pd_params_.code = ErrorCode::kError;
2126 // GIVEN an event error is set.
2127 attempter_.error_event_.reset(new OmahaEvent(OmahaEvent::kTypeUpdateComplete,
2128 OmahaEvent::kResultError,
2129 ErrorCode::kError));
2130
2131 // THEN indicate a error event.
2132 pd_params_.expected_exit_status = UpdateStatus::REPORTING_ERROR_EVENT;
2133 // THEN install indication should be false.
2134
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002135 // THEN update_engine should not call install completion.
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002136 // THEN expect critical actions of |ScheduleErrorEventAction()|.
2137 EXPECT_CALL(*processor_, EnqueueAction(Pointee(_))).Times(1);
2138 EXPECT_CALL(*processor_, StartProcessing()).Times(1);
2139 // THEN |ScheduleUpdates()| will be called next |ProcessingDone()| so skip.
2140 pd_params_.should_schedule_updates_be_called = false;
2141
2142 TestProcessingDone();
2143}
2144
Saurabh Nijhara43d7adc2020-11-06 16:13:02 +01002145TEST_F(UpdateAttempterTest, QuickFixTokenWhenDeviceIsEnterpriseEnrolled) {
2146 attempter_.CalculateUpdateParams({.quick_fix_build_token = "token"});
2147 EXPECT_EQ("token",
2148 FakeSystemState::Get()->request_params()->autoupdate_token());
Amr Aboelkher21ac9962019-05-15 14:50:05 +02002149
Saurabh Nijhara43d7adc2020-11-06 16:13:02 +01002150 attempter_.CalculateUpdateParams({});
2151 EXPECT_TRUE(
2152 FakeSystemState::Get()->request_params()->autoupdate_token().empty());
Askar Aitzhan570ca872019-04-24 11:16:12 +02002153}
2154
Jae Hoon Kim75daa382019-07-02 11:17:24 -07002155TEST_F(UpdateAttempterTest, ScheduleUpdateSpamHandlerTest) {
2156 EXPECT_CALL(mock_update_manager_, AsyncPolicyRequestUpdateCheckAllowed(_, _))
2157 .Times(1);
2158 EXPECT_TRUE(attempter_.ScheduleUpdates());
2159 // Now there is an update scheduled which means that all subsequent
2160 // |ScheduleUpdates()| should fail.
2161 EXPECT_FALSE(attempter_.ScheduleUpdates());
2162 EXPECT_FALSE(attempter_.ScheduleUpdates());
2163 EXPECT_FALSE(attempter_.ScheduleUpdates());
2164}
2165
2166// Critical tests to always make sure that an update is scheduled. The following
2167// unittest(s) try and cover the correctness in synergy between
2168// |UpdateAttempter| and |UpdateManager|. Also it is good to remember the
2169// actions that happen in the flow when |UpdateAttempter| get callbacked on
2170// |OnUpdateScheduled()| -> (various cases which leads to) -> |ProcessingDone()|
2171void UpdateAttempterTest::TestOnUpdateScheduled() {
2172 // Setup
2173 attempter_.SetWaitingForScheduledCheck(true);
2174 attempter_.DisableUpdate();
2175 attempter_.DisableScheduleUpdates();
2176
2177 // Invocation
2178 attempter_.OnUpdateScheduled(ous_params_.status, ous_params_.params);
2179
2180 // Verify
2181 EXPECT_EQ(ous_params_.exit_status, attempter_.status());
2182 EXPECT_EQ(ous_params_.should_schedule_updates_be_called,
2183 attempter_.WasScheduleUpdatesCalled());
2184 EXPECT_EQ(ous_params_.should_update_be_called, attempter_.WasUpdateCalled());
2185}
2186
2187TEST_F(UpdateAttempterTest, OnUpdatesScheduledFailed) {
2188 // GIVEN failed status.
2189
2190 // THEN update should be scheduled.
2191 ous_params_.should_schedule_updates_be_called = true;
2192
2193 TestOnUpdateScheduled();
2194}
2195
2196TEST_F(UpdateAttempterTest, OnUpdatesScheduledAskMeAgainLater) {
2197 // GIVEN ask me again later status.
2198 ous_params_.status = EvalStatus::kAskMeAgainLater;
2199
2200 // THEN update should be scheduled.
2201 ous_params_.should_schedule_updates_be_called = true;
2202
2203 TestOnUpdateScheduled();
2204}
2205
2206TEST_F(UpdateAttempterTest, OnUpdatesScheduledContinue) {
2207 // GIVEN continue status.
2208 ous_params_.status = EvalStatus::kContinue;
2209
2210 // THEN update should be scheduled.
2211 ous_params_.should_schedule_updates_be_called = true;
2212
2213 TestOnUpdateScheduled();
2214}
2215
2216TEST_F(UpdateAttempterTest, OnUpdatesScheduledSucceededButUpdateDisabledFails) {
2217 // GIVEN updates disabled.
2218 ous_params_.params = {.updates_enabled = false};
2219 // GIVEN succeeded status.
2220 ous_params_.status = EvalStatus::kSucceeded;
2221
2222 // THEN update should not be scheduled.
2223
2224 TestOnUpdateScheduled();
2225}
2226
2227TEST_F(UpdateAttempterTest, OnUpdatesScheduledSucceeded) {
2228 // GIVEN updates enabled.
2229 ous_params_.params = {.updates_enabled = true};
2230 // GIVEN succeeded status.
2231 ous_params_.status = EvalStatus::kSucceeded;
2232
2233 // THEN update should be called indicating status change.
2234 ous_params_.exit_status = UpdateStatus::CHECKING_FOR_UPDATE;
2235 ous_params_.should_update_be_called = true;
2236
2237 TestOnUpdateScheduled();
2238}
2239
Amin Hassani9be122e2019-08-29 09:20:12 -07002240TEST_F(UpdateAttempterTest, IsEnterpriseRollbackInGetStatusDefault) {
2241 UpdateEngineStatus status;
2242 attempter_.GetStatus(&status);
2243 EXPECT_FALSE(status.is_enterprise_rollback);
2244}
2245
2246TEST_F(UpdateAttempterTest, IsEnterpriseRollbackInGetStatusFalse) {
2247 attempter_.install_plan_.reset(new InstallPlan);
2248 attempter_.install_plan_->is_rollback = false;
2249
2250 UpdateEngineStatus status;
2251 attempter_.GetStatus(&status);
2252 EXPECT_FALSE(status.is_enterprise_rollback);
2253}
2254
2255TEST_F(UpdateAttempterTest, IsEnterpriseRollbackInGetStatusTrue) {
2256 attempter_.install_plan_.reset(new InstallPlan);
2257 attempter_.install_plan_->is_rollback = true;
2258
2259 UpdateEngineStatus status;
2260 attempter_.GetStatus(&status);
2261 EXPECT_TRUE(status.is_enterprise_rollback);
2262}
2263
Miriam Polzer0cf1acb2020-04-29 17:39:51 +02002264TEST_F(UpdateAttempterTest, PowerwashInGetStatusDefault) {
2265 UpdateEngineStatus status;
2266 attempter_.GetStatus(&status);
2267 EXPECT_FALSE(status.will_powerwash_after_reboot);
2268}
2269
2270TEST_F(UpdateAttempterTest, PowerwashInGetStatusTrueBecausePowerwashRequired) {
2271 attempter_.install_plan_.reset(new InstallPlan);
2272 attempter_.install_plan_->powerwash_required = true;
2273
2274 UpdateEngineStatus status;
2275 attempter_.GetStatus(&status);
2276 EXPECT_TRUE(status.will_powerwash_after_reboot);
2277}
2278
2279TEST_F(UpdateAttempterTest, PowerwashInGetStatusTrueBecauseRollback) {
2280 attempter_.install_plan_.reset(new InstallPlan);
2281 attempter_.install_plan_->is_rollback = true;
2282
2283 UpdateEngineStatus status;
2284 attempter_.GetStatus(&status);
2285 EXPECT_TRUE(status.will_powerwash_after_reboot);
2286}
2287
Jae Hoon Kim051627a2019-09-03 12:56:32 -07002288TEST_F(UpdateAttempterTest, FutureEolTest) {
2289 EolDate eol_date = std::numeric_limits<int64_t>::max();
Jae Hoon Kim2dfd35d2020-06-02 10:53:13 -07002290 EXPECT_CALL(*prefs_, Exists(kPrefsOmahaEolDate)).WillOnce(Return(true));
Jae Hoon Kim051627a2019-09-03 12:56:32 -07002291 EXPECT_CALL(*prefs_, GetString(kPrefsOmahaEolDate, _))
2292 .WillOnce(
2293 DoAll(SetArgPointee<1>(EolDateToString(eol_date)), Return(true)));
2294
2295 UpdateEngineStatus status;
2296 attempter_.GetStatus(&status);
2297 EXPECT_EQ(eol_date, status.eol_date);
2298}
2299
2300TEST_F(UpdateAttempterTest, PastEolTest) {
2301 EolDate eol_date = 1;
Jae Hoon Kim2dfd35d2020-06-02 10:53:13 -07002302 EXPECT_CALL(*prefs_, Exists(kPrefsOmahaEolDate)).WillOnce(Return(true));
Jae Hoon Kim051627a2019-09-03 12:56:32 -07002303 EXPECT_CALL(*prefs_, GetString(kPrefsOmahaEolDate, _))
2304 .WillOnce(
2305 DoAll(SetArgPointee<1>(EolDateToString(eol_date)), Return(true)));
2306
2307 UpdateEngineStatus status;
2308 attempter_.GetStatus(&status);
2309 EXPECT_EQ(eol_date, status.eol_date);
2310}
2311
2312TEST_F(UpdateAttempterTest, FailedEolTest) {
Jae Hoon Kim2dfd35d2020-06-02 10:53:13 -07002313 EXPECT_CALL(*prefs_, Exists(kPrefsOmahaEolDate)).WillOnce(Return(true));
Jae Hoon Kim051627a2019-09-03 12:56:32 -07002314 EXPECT_CALL(*prefs_, GetString(kPrefsOmahaEolDate, _))
2315 .WillOnce(Return(false));
2316
2317 UpdateEngineStatus status;
2318 attempter_.GetStatus(&status);
Jae Hoon Kim2dfd35d2020-06-02 10:53:13 -07002319 EXPECT_EQ(kEolDateInvalid, status.eol_date);
2320}
2321
2322TEST_F(UpdateAttempterTest, MissingEolTest) {
2323 EXPECT_CALL(*prefs_, Exists(kPrefsOmahaEolDate)).WillOnce(Return(false));
2324
2325 UpdateEngineStatus status;
2326 attempter_.GetStatus(&status);
2327 EXPECT_EQ(kEolDateInvalid, status.eol_date);
Jae Hoon Kim051627a2019-09-03 12:56:32 -07002328}
2329
Andrewe045aef2020-01-08 16:29:22 -08002330TEST_F(UpdateAttempterTest, CalculateDlcParamsInstallTest) {
Andrewe045aef2020-01-08 16:29:22 -08002331 string dlc_id = "dlc0";
Andrew065d78d2020-04-07 15:43:07 -07002332 FakePrefs fake_prefs;
Amin Hassani538bd592020-11-04 20:46:08 -08002333 FakeSystemState::Get()->set_prefs(&fake_prefs);
Andrewe045aef2020-01-08 16:29:22 -08002334 attempter_.is_install_ = true;
Amin Hassani2b68e6b2020-04-17 10:49:12 -07002335 attempter_.dlc_ids_ = {dlc_id};
Andrewe045aef2020-01-08 16:29:22 -08002336 attempter_.CalculateDlcParams();
2337
Amin Hassani538bd592020-11-04 20:46:08 -08002338 OmahaRequestParams* params = FakeSystemState::Get()->request_params();
Andrewe045aef2020-01-08 16:29:22 -08002339 EXPECT_EQ(1, params->dlc_apps_params().count(params->GetDlcAppId(dlc_id)));
2340 OmahaRequestParams::AppParams dlc_app_params =
2341 params->dlc_apps_params().at(params->GetDlcAppId(dlc_id));
2342 EXPECT_STREQ(dlc_id.c_str(), dlc_app_params.name.c_str());
2343 EXPECT_EQ(false, dlc_app_params.send_ping);
2344 // When the DLC gets installed, a ping is not sent, therefore we don't store
2345 // the values sent by Omaha.
Andrew065d78d2020-04-07 15:43:07 -07002346 auto last_active_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002347 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastActive});
Amin Hassani538bd592020-11-04 20:46:08 -08002348 EXPECT_FALSE(FakeSystemState::Get()->prefs()->Exists(last_active_key));
Andrew065d78d2020-04-07 15:43:07 -07002349 auto last_rollcall_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002350 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastRollcall});
Amin Hassani538bd592020-11-04 20:46:08 -08002351 EXPECT_FALSE(FakeSystemState::Get()->prefs()->Exists(last_rollcall_key));
Andrewe045aef2020-01-08 16:29:22 -08002352}
2353
2354TEST_F(UpdateAttempterTest, CalculateDlcParamsNoPrefFilesTest) {
Andrewe045aef2020-01-08 16:29:22 -08002355 string dlc_id = "dlc0";
Andrew065d78d2020-04-07 15:43:07 -07002356 FakePrefs fake_prefs;
Amin Hassani538bd592020-11-04 20:46:08 -08002357 FakeSystemState::Get()->set_prefs(&fake_prefs);
Amin Hassani2b68e6b2020-04-17 10:49:12 -07002358 EXPECT_CALL(mock_dlcservice_, GetDlcsToUpdate(_))
Andrewe045aef2020-01-08 16:29:22 -08002359 .WillOnce(
2360 DoAll(SetArgPointee<0>(std::vector<string>({dlc_id})), Return(true)));
2361
2362 attempter_.is_install_ = false;
2363 attempter_.CalculateDlcParams();
2364
Amin Hassani538bd592020-11-04 20:46:08 -08002365 OmahaRequestParams* params = FakeSystemState::Get()->request_params();
Andrewe045aef2020-01-08 16:29:22 -08002366 EXPECT_EQ(1, params->dlc_apps_params().count(params->GetDlcAppId(dlc_id)));
2367 OmahaRequestParams::AppParams dlc_app_params =
2368 params->dlc_apps_params().at(params->GetDlcAppId(dlc_id));
2369 EXPECT_STREQ(dlc_id.c_str(), dlc_app_params.name.c_str());
2370
2371 EXPECT_EQ(true, dlc_app_params.send_ping);
2372 EXPECT_EQ(0, dlc_app_params.ping_active);
2373 EXPECT_EQ(-1, dlc_app_params.ping_date_last_active);
2374 EXPECT_EQ(-1, dlc_app_params.ping_date_last_rollcall);
2375}
2376
2377TEST_F(UpdateAttempterTest, CalculateDlcParamsNonParseableValuesTest) {
Andrewe045aef2020-01-08 16:29:22 -08002378 string dlc_id = "dlc0";
Andrew065d78d2020-04-07 15:43:07 -07002379 MemoryPrefs prefs;
Amin Hassani538bd592020-11-04 20:46:08 -08002380 FakeSystemState::Get()->set_prefs(&prefs);
Amin Hassani2b68e6b2020-04-17 10:49:12 -07002381 EXPECT_CALL(mock_dlcservice_, GetDlcsToUpdate(_))
Andrewe045aef2020-01-08 16:29:22 -08002382 .WillOnce(
2383 DoAll(SetArgPointee<0>(std::vector<string>({dlc_id})), Return(true)));
2384
2385 // Write non numeric values in the metadata files.
Andrew065d78d2020-04-07 15:43:07 -07002386 auto active_key =
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002387 PrefsInterface::CreateSubKey({kDlcPrefsSubDir, dlc_id, kPrefsPingActive});
Andrew065d78d2020-04-07 15:43:07 -07002388 auto last_active_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002389 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastActive});
Andrew065d78d2020-04-07 15:43:07 -07002390 auto last_rollcall_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002391 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastRollcall});
Amin Hassani538bd592020-11-04 20:46:08 -08002392 FakeSystemState::Get()->prefs()->SetString(active_key, "z2yz");
2393 FakeSystemState::Get()->prefs()->SetString(last_active_key, "z2yz");
2394 FakeSystemState::Get()->prefs()->SetString(last_rollcall_key, "z2yz");
Andrewe045aef2020-01-08 16:29:22 -08002395 attempter_.is_install_ = false;
2396 attempter_.CalculateDlcParams();
2397
Amin Hassani538bd592020-11-04 20:46:08 -08002398 OmahaRequestParams* params = FakeSystemState::Get()->request_params();
Andrewe045aef2020-01-08 16:29:22 -08002399 EXPECT_EQ(1, params->dlc_apps_params().count(params->GetDlcAppId(dlc_id)));
2400 OmahaRequestParams::AppParams dlc_app_params =
2401 params->dlc_apps_params().at(params->GetDlcAppId(dlc_id));
2402 EXPECT_STREQ(dlc_id.c_str(), dlc_app_params.name.c_str());
2403
2404 EXPECT_EQ(true, dlc_app_params.send_ping);
2405 EXPECT_EQ(0, dlc_app_params.ping_active);
2406 EXPECT_EQ(-2, dlc_app_params.ping_date_last_active);
2407 EXPECT_EQ(-2, dlc_app_params.ping_date_last_rollcall);
2408}
2409
2410TEST_F(UpdateAttempterTest, CalculateDlcParamsValidValuesTest) {
Andrewe045aef2020-01-08 16:29:22 -08002411 string dlc_id = "dlc0";
Andrew065d78d2020-04-07 15:43:07 -07002412 MemoryPrefs fake_prefs;
Amin Hassani538bd592020-11-04 20:46:08 -08002413 FakeSystemState::Get()->set_prefs(&fake_prefs);
Amin Hassani2b68e6b2020-04-17 10:49:12 -07002414 EXPECT_CALL(mock_dlcservice_, GetDlcsToUpdate(_))
Andrewe045aef2020-01-08 16:29:22 -08002415 .WillOnce(
2416 DoAll(SetArgPointee<0>(std::vector<string>({dlc_id})), Return(true)));
2417
2418 // Write numeric values in the metadata files.
Andrew065d78d2020-04-07 15:43:07 -07002419 auto active_key =
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002420 PrefsInterface::CreateSubKey({kDlcPrefsSubDir, dlc_id, kPrefsPingActive});
Andrew065d78d2020-04-07 15:43:07 -07002421 auto last_active_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002422 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastActive});
Andrew065d78d2020-04-07 15:43:07 -07002423 auto last_rollcall_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002424 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastRollcall});
Andrew065d78d2020-04-07 15:43:07 -07002425
Amin Hassani538bd592020-11-04 20:46:08 -08002426 FakeSystemState::Get()->prefs()->SetInt64(active_key, 1);
2427 FakeSystemState::Get()->prefs()->SetInt64(last_active_key, 78);
2428 FakeSystemState::Get()->prefs()->SetInt64(last_rollcall_key, 99);
Andrewe045aef2020-01-08 16:29:22 -08002429 attempter_.is_install_ = false;
2430 attempter_.CalculateDlcParams();
2431
Amin Hassani538bd592020-11-04 20:46:08 -08002432 OmahaRequestParams* params = FakeSystemState::Get()->request_params();
Andrewe045aef2020-01-08 16:29:22 -08002433 EXPECT_EQ(1, params->dlc_apps_params().count(params->GetDlcAppId(dlc_id)));
2434 OmahaRequestParams::AppParams dlc_app_params =
2435 params->dlc_apps_params().at(params->GetDlcAppId(dlc_id));
2436 EXPECT_STREQ(dlc_id.c_str(), dlc_app_params.name.c_str());
2437
2438 EXPECT_EQ(true, dlc_app_params.send_ping);
2439 EXPECT_EQ(1, dlc_app_params.ping_active);
2440 EXPECT_EQ(78, dlc_app_params.ping_date_last_active);
2441 EXPECT_EQ(99, dlc_app_params.ping_date_last_rollcall);
2442}
Andrewa8d7df32020-03-15 20:10:01 -07002443
2444TEST_F(UpdateAttempterTest, CalculateDlcParamsRemoveStaleMetadata) {
Andrewa8d7df32020-03-15 20:10:01 -07002445 string dlc_id = "dlc0";
Andrew065d78d2020-04-07 15:43:07 -07002446 FakePrefs fake_prefs;
Amin Hassani538bd592020-11-04 20:46:08 -08002447 FakeSystemState::Get()->set_prefs(&fake_prefs);
Andrew065d78d2020-04-07 15:43:07 -07002448 auto active_key =
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002449 PrefsInterface::CreateSubKey({kDlcPrefsSubDir, dlc_id, kPrefsPingActive});
Andrew065d78d2020-04-07 15:43:07 -07002450 auto last_active_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002451 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastActive});
Andrew065d78d2020-04-07 15:43:07 -07002452 auto last_rollcall_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002453 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastRollcall});
Amin Hassani538bd592020-11-04 20:46:08 -08002454 FakeSystemState::Get()->prefs()->SetInt64(active_key, kPingInactiveValue);
2455 FakeSystemState::Get()->prefs()->SetInt64(last_active_key, 0);
2456 FakeSystemState::Get()->prefs()->SetInt64(last_rollcall_key, 0);
2457 EXPECT_TRUE(FakeSystemState::Get()->prefs()->Exists(active_key));
2458 EXPECT_TRUE(FakeSystemState::Get()->prefs()->Exists(last_active_key));
2459 EXPECT_TRUE(FakeSystemState::Get()->prefs()->Exists(last_rollcall_key));
Andrewa8d7df32020-03-15 20:10:01 -07002460
Andrew065d78d2020-04-07 15:43:07 -07002461 attempter_.dlc_ids_ = {dlc_id};
2462 attempter_.is_install_ = true;
Andrewa8d7df32020-03-15 20:10:01 -07002463 attempter_.CalculateDlcParams();
2464
Amin Hassani538bd592020-11-04 20:46:08 -08002465 EXPECT_FALSE(FakeSystemState::Get()->prefs()->Exists(last_active_key));
2466 EXPECT_FALSE(FakeSystemState::Get()->prefs()->Exists(last_rollcall_key));
Andrew065d78d2020-04-07 15:43:07 -07002467 // Active key is set on install.
Amin Hassani538bd592020-11-04 20:46:08 -08002468 EXPECT_TRUE(FakeSystemState::Get()->prefs()->Exists(active_key));
Andrew065d78d2020-04-07 15:43:07 -07002469 int64_t temp_int;
Amin Hassani538bd592020-11-04 20:46:08 -08002470 EXPECT_TRUE(FakeSystemState::Get()->prefs()->GetInt64(active_key, &temp_int));
Andrew065d78d2020-04-07 15:43:07 -07002471 EXPECT_EQ(temp_int, kPingActiveValue);
Andrewa8d7df32020-03-15 20:10:01 -07002472}
2473
2474TEST_F(UpdateAttempterTest, SetDlcActiveValue) {
Andrewa8d7df32020-03-15 20:10:01 -07002475 string dlc_id = "dlc0";
Andrew065d78d2020-04-07 15:43:07 -07002476 FakePrefs fake_prefs;
Amin Hassani538bd592020-11-04 20:46:08 -08002477 FakeSystemState::Get()->set_prefs(&fake_prefs);
Andrewa8d7df32020-03-15 20:10:01 -07002478 attempter_.SetDlcActiveValue(true, dlc_id);
Andrewa8d7df32020-03-15 20:10:01 -07002479 int64_t temp_int;
Andrew065d78d2020-04-07 15:43:07 -07002480 auto active_key =
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002481 PrefsInterface::CreateSubKey({kDlcPrefsSubDir, dlc_id, kPrefsPingActive});
Amin Hassani538bd592020-11-04 20:46:08 -08002482 EXPECT_TRUE(FakeSystemState::Get()->prefs()->Exists(active_key));
2483 EXPECT_TRUE(FakeSystemState::Get()->prefs()->GetInt64(active_key, &temp_int));
Andrewa8d7df32020-03-15 20:10:01 -07002484 EXPECT_EQ(temp_int, kPingActiveValue);
2485}
2486
2487TEST_F(UpdateAttempterTest, SetDlcInactive) {
Andrewa8d7df32020-03-15 20:10:01 -07002488 string dlc_id = "dlc0";
Andrew065d78d2020-04-07 15:43:07 -07002489 MemoryPrefs fake_prefs;
Amin Hassani538bd592020-11-04 20:46:08 -08002490 FakeSystemState::Get()->set_prefs(&fake_prefs);
Andrew065d78d2020-04-07 15:43:07 -07002491 auto sub_keys = {
2492 kPrefsPingActive, kPrefsPingLastActive, kPrefsPingLastRollcall};
2493 for (auto& sub_key : sub_keys) {
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002494 auto key = PrefsInterface::CreateSubKey({kDlcPrefsSubDir, dlc_id, sub_key});
Amin Hassani538bd592020-11-04 20:46:08 -08002495 FakeSystemState::Get()->prefs()->SetInt64(key, 1);
2496 EXPECT_TRUE(FakeSystemState::Get()->prefs()->Exists(key));
Andrew065d78d2020-04-07 15:43:07 -07002497 }
Andrewa8d7df32020-03-15 20:10:01 -07002498 attempter_.SetDlcActiveValue(false, dlc_id);
Andrew065d78d2020-04-07 15:43:07 -07002499 for (auto& sub_key : sub_keys) {
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002500 auto key = PrefsInterface::CreateSubKey({kDlcPrefsSubDir, dlc_id, sub_key});
Amin Hassani538bd592020-11-04 20:46:08 -08002501 EXPECT_FALSE(FakeSystemState::Get()->prefs()->Exists(key));
Andrew065d78d2020-04-07 15:43:07 -07002502 }
Andrewa8d7df32020-03-15 20:10:01 -07002503}
2504
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002505TEST_F(UpdateAttempterTest, GetSuccessfulDlcIds) {
2506 auto dlc_1 = "1", dlc_2 = "2", dlc_3 = "3";
2507 attempter_.omaha_request_params_->set_dlc_apps_params(
2508 {{dlc_1, {.name = dlc_1, .updated = false}},
2509 {dlc_2, {.name = dlc_2}},
2510 {dlc_3, {.name = dlc_3, .updated = false}}});
2511 EXPECT_THAT(attempter_.GetSuccessfulDlcIds(), ElementsAre(dlc_2));
2512}
2513
Darin Petkovf42cc1c2010-09-01 09:03:02 -07002514} // namespace chromeos_update_engine