blob: a7f5236eff61be6b2f836dd9f110d43ae3e26590 [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 Deymo14fd1ec2016-02-24 22:03:57 -080040#include "update_engine/common/mock_action.h"
41#include "update_engine/common/mock_action_processor.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080042#include "update_engine/common/mock_http_fetcher.h"
Amin Hassaniec7bc112020-10-29 16:47:58 -070043#include "update_engine/common/mock_service_observer.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080044#include "update_engine/common/platform_constants.h"
45#include "update_engine/common/prefs.h"
46#include "update_engine/common/test_utils.h"
47#include "update_engine/common/utils.h"
Kelvin Zhang97cb0582020-12-02 16:42:15 -050048#include "update_engine/cros/download_action_chromeos.h"
Amin Hassaniec7bc112020-10-29 16:47:58 -070049#include "update_engine/cros/fake_system_state.h"
50#include "update_engine/cros/mock_p2p_manager.h"
51#include "update_engine/cros/mock_payload_state.h"
52#include "update_engine/cros/omaha_utils.h"
Jae Hoon Kim0ae8fe12019-06-26 14:32:50 -070053#include "update_engine/libcurl_http_fetcher.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080054#include "update_engine/payload_consumer/filesystem_verifier_action.h"
55#include "update_engine/payload_consumer/install_plan.h"
56#include "update_engine/payload_consumer/payload_constants.h"
57#include "update_engine/payload_consumer/postinstall_runner_action.h"
Amin Hassani0882a512018-04-05 16:25:44 -070058#include "update_engine/update_boot_flags_action.h"
Jae Hoon Kim504c3cb2019-07-02 11:17:24 -070059#include "update_engine/update_manager/mock_update_manager.h"
Darin Petkovf42cc1c2010-09-01 09:03:02 -070060
David Zeuthen985b1122013-10-09 12:13:15 -070061using base::Time;
62using base::TimeDelta;
Aaron Woodbf5a2522017-10-04 10:58:36 -070063using chromeos_update_manager::EvalStatus;
Jae Hoon Kim504c3cb2019-07-02 11:17:24 -070064using chromeos_update_manager::MockUpdateManager;
Adolfo Victoria497044c2018-07-18 07:51:42 -070065using chromeos_update_manager::StagingSchedule;
Aaron Woodbf5a2522017-10-04 10:58:36 -070066using chromeos_update_manager::UpdateCheckParams;
Adolfo Victoria497044c2018-07-18 07:51:42 -070067using policy::DevicePolicy;
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -070068using std::map;
Darin Petkovf42cc1c2010-09-01 09:03:02 -070069using std::string;
Ben Chan02f7c1d2014-10-18 15:18:02 -070070using std::unique_ptr;
Jae Hoon Kimedb65502019-06-14 11:52:17 -070071using std::unordered_set;
Xiaochu Liu88d90382018-08-29 16:09:11 -070072using std::vector;
Aaron Woodbf5a2522017-10-04 10:58:36 -070073using testing::_;
Andrew065d78d2020-04-07 15:43:07 -070074using testing::Contains;
Darin Petkov36275772010-10-01 11:40:57 -070075using testing::DoAll;
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -070076using testing::ElementsAre;
Aaron Wood7f92e2b2017-08-28 14:51:21 -070077using testing::Field;
Darin Petkovf42cc1c2010-09-01 09:03:02 -070078using testing::InSequence;
Jae Hoon Kimedb65502019-06-14 11:52:17 -070079using testing::Invoke;
Darin Petkov2dd01092010-10-08 15:43:05 -070080using testing::Ne;
Darin Petkov9c096d62010-11-17 14:49:04 -080081using testing::NiceMock;
Amin Hassanid3f4bea2018-04-30 14:52:40 -070082using testing::Pointee;
Darin Petkovf42cc1c2010-09-01 09:03:02 -070083using testing::Property;
84using testing::Return;
Gilad Arnold74b5f552014-10-07 08:17:16 -070085using testing::ReturnPointee;
Marton Hunyadye58bddb2018-04-10 20:27:26 +020086using testing::ReturnRef;
Alex Deymo2c0db7b2014-11-04 12:23:39 -080087using testing::SaveArg;
Ben Chan672c1f52017-10-23 15:41:39 -070088using testing::SetArgPointee;
Aaron Woodbf5a2522017-10-04 10:58:36 -070089using update_engine::UpdateAttemptFlags;
Aaron Wood7f92e2b2017-08-28 14:51:21 -070090using update_engine::UpdateEngineStatus;
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -070091using update_engine::UpdateStatus;
Darin Petkovf42cc1c2010-09-01 09:03:02 -070092
93namespace chromeos_update_engine {
94
Xiaochu Liu8ba486f2018-11-06 11:14:10 -080095namespace {
96
Jae Hoon Kimc437ea52019-07-11 11:20:38 -070097const UpdateStatus kNonIdleUpdateStatuses[] = {
98 UpdateStatus::CHECKING_FOR_UPDATE,
99 UpdateStatus::UPDATE_AVAILABLE,
100 UpdateStatus::DOWNLOADING,
101 UpdateStatus::VERIFYING,
102 UpdateStatus::FINALIZING,
103 UpdateStatus::UPDATED_NEED_REBOOT,
104 UpdateStatus::REPORTING_ERROR_EVENT,
105 UpdateStatus::ATTEMPTING_ROLLBACK,
106 UpdateStatus::DISABLED,
107 UpdateStatus::NEED_PERMISSION_TO_UPDATE,
108};
109
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -0700110struct CheckForUpdateTestParams {
111 // Setups + Inputs:
112 UpdateStatus status = UpdateStatus::IDLE;
113 string app_version = "fake_app_version";
114 string omaha_url = "fake_omaha_url";
115 UpdateAttemptFlags flags = UpdateAttemptFlags::kNone;
116 bool is_official_build = true;
117 bool are_dev_features_enabled = false;
118
119 // Expects:
120 string expected_forced_app_version = "";
121 string expected_forced_omaha_url = "";
Jae Hoon Kim2b73ac22019-07-02 11:17:24 -0700122 bool should_schedule_updates_be_called = true;
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -0700123 bool expected_result = true;
124};
125
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700126struct OnUpdateScheduledTestParams {
127 // Setups + Inputs:
128 UpdateCheckParams params = {};
129 EvalStatus status = EvalStatus::kFailed;
130 // Expects:
131 UpdateStatus exit_status = UpdateStatus::IDLE;
132 bool should_schedule_updates_be_called = false;
133 bool should_update_be_called = false;
134};
135
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -0700136struct ProcessingDoneTestParams {
137 // Setups + Inputs:
138 bool is_install = false;
139 UpdateStatus status = UpdateStatus::CHECKING_FOR_UPDATE;
140 ActionProcessor* processor = nullptr;
141 ErrorCode code = ErrorCode::kSuccess;
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -0700142 map<string, OmahaRequestParams::AppParams> dlc_apps_params;
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -0700143
144 // Expects:
145 const bool kExpectedIsInstall = false;
146 bool should_schedule_updates_be_called = true;
147 UpdateStatus expected_exit_status = UpdateStatus::IDLE;
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -0700148 bool should_install_completed_be_called = false;
149 bool should_update_completed_be_called = false;
150 vector<string> args_to_install_completed;
151 vector<string> args_to_update_completed;
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -0700152};
153
Xiaochu Liu8ba486f2018-11-06 11:14:10 -0800154class MockDlcService : public DlcServiceInterface {
155 public:
Amin Hassani2b68e6b2020-04-17 10:49:12 -0700156 MOCK_METHOD1(GetDlcsToUpdate, bool(vector<string>*));
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -0700157 MOCK_METHOD1(InstallCompleted, bool(const vector<string>&));
158 MOCK_METHOD1(UpdateCompleted, bool(const vector<string>&));
Xiaochu Liu8ba486f2018-11-06 11:14:10 -0800159};
160
161} // namespace
162
Marton Hunyadya0302682018-05-16 18:52:13 +0200163const char kRollbackVersion[] = "10575.39.2";
164
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700165// Test a subclass rather than the main class directly so that we can mock out
Darin Petkovcd1666f2010-09-23 09:53:44 -0700166// methods within the class. There're explicit unit tests for the mocked out
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700167// methods.
168class UpdateAttempterUnderTest : public UpdateAttempter {
169 public:
Amin Hassani538bd592020-11-04 20:46:08 -0800170 UpdateAttempterUnderTest() : UpdateAttempter(nullptr) {}
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700171
Amin Hassanie8153632020-10-27 15:11:28 -0700172 void Update(const UpdateCheckParams& params) override {
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700173 update_called_ = true;
174 if (do_update_) {
Amin Hassanie8153632020-10-27 15:11:28 -0700175 UpdateAttempter::Update(params);
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700176 return;
177 }
178 LOG(INFO) << "[TEST] Update() disabled.";
179 status_ = UpdateStatus::CHECKING_FOR_UPDATE;
180 }
181
182 void DisableUpdate() { do_update_ = false; }
183
184 bool WasUpdateCalled() const { return update_called_; }
185
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700186 // Wrap the update scheduling method, allowing us to opt out of scheduled
187 // updates for testing purposes.
Xiaochu Liu88d90382018-08-29 16:09:11 -0700188 bool ScheduleUpdates() override {
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700189 schedule_updates_called_ = true;
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700190 if (do_schedule_updates_)
191 return UpdateAttempter::ScheduleUpdates();
192 LOG(INFO) << "[TEST] Update scheduling disabled.";
193 waiting_for_scheduled_check_ = true;
Xiaochu Liu88d90382018-08-29 16:09:11 -0700194 return true;
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700195 }
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700196
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700197 void DisableScheduleUpdates() { do_schedule_updates_ = false; }
198
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700199 // Indicates whether |ScheduleUpdates()| was called.
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700200 bool WasScheduleUpdatesCalled() const { return schedule_updates_called_; }
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700201
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -0700202 // Need to expose following private members of |UpdateAttempter| for tests.
203 const string& forced_app_version() const { return forced_app_version_; }
Alex Deymo60ca1a72015-06-18 18:19:15 -0700204 const string& forced_omaha_url() const { return forced_omaha_url_; }
David Pursell02c18642014-11-06 11:26:11 -0800205
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700206 // Need to expose |waiting_for_scheduled_check_| for testing.
207 void SetWaitingForScheduledCheck(bool waiting) {
208 waiting_for_scheduled_check_ = waiting;
209 }
210
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700211 private:
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700212 // Used for overrides of |Update()|.
213 bool update_called_ = false;
214 bool do_update_ = true;
215
216 // Used for overrides of |ScheduleUpdates()|.
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700217 bool schedule_updates_called_ = false;
218 bool do_schedule_updates_ = true;
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700219};
220
221class UpdateAttempterTest : public ::testing::Test {
222 protected:
Amin Hassani538bd592020-11-04 20:46:08 -0800223 void SetUp() override {
Gilad Arnold1f847232014-04-07 12:07:49 -0700224 // Override system state members.
Amin Hassani538bd592020-11-04 20:46:08 -0800225 FakeSystemState::CreateInstance();
226 FakeSystemState::Get()->set_connection_manager(&mock_connection_manager);
227 FakeSystemState::Get()->set_update_attempter(&attempter_);
228 FakeSystemState::Get()->set_dlcservice(&mock_dlcservice_);
229 FakeSystemState::Get()->set_update_manager(&mock_update_manager_);
Alex Deymo60ca1a72015-06-18 18:19:15 -0700230 loop_.SetAsCurrent();
Gilad Arnold1f847232014-04-07 12:07:49 -0700231
Amin Hassani90e9f192020-11-18 14:20:56 -0800232 prefs_ = FakeSystemState::Get()->fake_prefs();
233 certificate_checker_.reset(
234 new CertificateChecker(prefs_, &openssl_wrapper_));
Amin Hassani538bd592020-11-04 20:46:08 -0800235 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.
Gilad Arnold74b5f552014-10-07 08:17:16 -0700250
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700251 // Setup store/load semantics of P2P properties via the mock |PayloadState|.
Gilad Arnold74b5f552014-10-07 08:17:16 -0700252 actual_using_p2p_for_downloading_ = false;
Amin Hassani538bd592020-11-04 20:46:08 -0800253 EXPECT_CALL(*FakeSystemState::Get()->mock_payload_state(),
Gilad Arnold74b5f552014-10-07 08:17:16 -0700254 SetUsingP2PForDownloading(_))
255 .WillRepeatedly(SaveArg<0>(&actual_using_p2p_for_downloading_));
Amin Hassani538bd592020-11-04 20:46:08 -0800256 EXPECT_CALL(*FakeSystemState::Get()->mock_payload_state(),
Gilad Arnold74b5f552014-10-07 08:17:16 -0700257 GetUsingP2PForDownloading())
258 .WillRepeatedly(ReturnPointee(&actual_using_p2p_for_downloading_));
259 actual_using_p2p_for_sharing_ = false;
Amin Hassani538bd592020-11-04 20:46:08 -0800260 EXPECT_CALL(*FakeSystemState::Get()->mock_payload_state(),
Gilad Arnold74b5f552014-10-07 08:17:16 -0700261 SetUsingP2PForSharing(_))
262 .WillRepeatedly(SaveArg<0>(&actual_using_p2p_for_sharing_));
Amin Hassani538bd592020-11-04 20:46:08 -0800263 EXPECT_CALL(*FakeSystemState::Get()->mock_payload_state(),
Gilad Arnold74b5f552014-10-07 08:17:16 -0700264 GetUsingP2PForDownloading())
265 .WillRepeatedly(ReturnPointee(&actual_using_p2p_for_sharing_));
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700266 }
267
Alex Deymo60ca1a72015-06-18 18:19:15 -0700268 public:
269 void ScheduleQuitMainLoop();
Patrick Dubroy7fbbe8a2011-08-01 17:28:22 +0200270
Alex Deymo60ca1a72015-06-18 18:19:15 -0700271 // Callbacks to run the different tests from the main loop.
Darin Petkove6ef2f82011-03-07 17:31:11 -0800272 void UpdateTestStart();
273 void UpdateTestVerify();
Alex Deymo60ca1a72015-06-18 18:19:15 -0700274 void RollbackTestStart(bool enterprise_rollback, bool valid_slot);
Chris Sosa76a29ae2013-07-11 17:59:24 -0700275 void RollbackTestVerify();
Thieu Le116fda32011-04-19 11:01:54 -0700276 void PingOmahaTestStart();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700277 void ReadScatterFactorFromPolicyTestStart();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700278 void DecrementUpdateCheckCountTestStart();
Jay Srinivasan08fce042012-06-07 16:31:01 -0700279 void NoScatteringDoneDuringManualUpdateTestStart();
David Zeuthen8f191b22013-08-06 12:27:50 -0700280 void P2PNotEnabledStart();
David Zeuthen8f191b22013-08-06 12:27:50 -0700281 void P2PEnabledStart();
David Zeuthen8f191b22013-08-06 12:27:50 -0700282 void P2PEnabledInteractiveStart();
David Zeuthen8f191b22013-08-06 12:27:50 -0700283 void P2PEnabledStartingFailsStart();
David Zeuthen8f191b22013-08-06 12:27:50 -0700284 void P2PEnabledHousekeepingFailsStart();
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700285 void SessionIdTestChange();
286 void SessionIdTestEnforceEmptyStrPingOmaha();
287 void SessionIdTestConsistencyInUpdateFlow();
Jae Hoon Kim0ae8fe12019-06-26 14:32:50 -0700288 void SessionIdTestInDownloadAction();
Marton Hunyadye58bddb2018-04-10 20:27:26 +0200289 void ResetRollbackHappenedStart(bool is_consumer,
290 bool is_policy_available,
291 bool expected_reset);
Adolfo Victoria497044c2018-07-18 07:51:42 -0700292 // Staging related callbacks.
Amin Hassani90e9f192020-11-18 14:20:56 -0800293 void SetUpStagingTest(const StagingSchedule& schedule);
Adolfo Victoria497044c2018-07-18 07:51:42 -0700294 void CheckStagingOff();
295 void StagingSetsPrefsAndTurnsOffScatteringStart();
296 void StagingOffIfInteractiveStart();
297 void StagingOffIfOobeStart();
David Zeuthen8f191b22013-08-06 12:27:50 -0700298
Gilad Arnold74b5f552014-10-07 08:17:16 -0700299 bool actual_using_p2p_for_downloading() {
300 return actual_using_p2p_for_downloading_;
301 }
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800302 bool actual_using_p2p_for_sharing() { return actual_using_p2p_for_sharing_; }
Gilad Arnold74b5f552014-10-07 08:17:16 -0700303
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -0700304 // |CheckForUpdate()| related member functions.
305 void TestCheckForUpdate();
306
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700307 // |OnUpdateScheduled()| related member functions.
308 void TestOnUpdateScheduled();
309
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -0700310 // |ProcessingDone()| related member functions.
311 void TestProcessingDone();
312
Qijiang Fanb0b6cc22020-10-15 21:54:11 +0900313 base::SingleThreadTaskExecutor base_loop_{base::MessagePumpType::IO};
314 brillo::BaseMessageLoop loop_{base_loop_.task_runner()};
Alex Deymo60ca1a72015-06-18 18:19:15 -0700315
Amin Hassani538bd592020-11-04 20:46:08 -0800316 UpdateAttempterUnderTest attempter_;
Alex Deymo33e91e72015-12-01 18:26:08 -0300317 OpenSSLWrapper openssl_wrapper_;
Amin Hassani538bd592020-11-04 20:46:08 -0800318 std::unique_ptr<CertificateChecker> certificate_checker_;
Xiaochu Liu8ba486f2018-11-06 11:14:10 -0800319 MockDlcService mock_dlcservice_;
Jae Hoon Kim504c3cb2019-07-02 11:17:24 -0700320 MockUpdateManager mock_update_manager_;
Alex Deymo30534502015-07-20 15:06:33 -0700321
Alex Deymo8427b4a2014-11-05 14:00:32 -0800322 NiceMock<MockActionProcessor>* processor_;
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800323 NiceMock<MockConnectionManager> mock_connection_manager;
Gilad Arnoldeff87cc2013-07-22 18:32:09 -0700324
Amin Hassani90e9f192020-11-18 14:20:56 -0800325 FakePrefs* prefs_;
326
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) {
Kelvin Zhang97cb0582020-12-02 16:42:15 -0500476 if (aa->Type() == DownloadActionChromeos::StaticType()) {
477 DownloadActionChromeos* da = static_cast<DownloadActionChromeos*>(aa);
Jae Hoon Kim0ae8fe12019-06-26 14:32:50 -0700478 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.
Kelvin Zhang97cb0582020-12-02 16:42:15 -0500500 DownloadActionChromeos action(
501 prefs_, nullptr, nullptr, fetcher.release(), false /* interactive */);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700502 attempter_.ActionCompleted(nullptr, &action, ErrorCode::kSuccess);
Amin Hassani90e9f192020-11-18 14:20:56 -0800503 EXPECT_FALSE(prefs_->Exists(kPrefsDeltaUpdateFailures));
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700504 EXPECT_EQ(UpdateStatus::FINALIZING, attempter_.status());
Aaron Wood9321f502017-09-07 11:18:54 -0700505 EXPECT_EQ(0.0, attempter_.download_progress_);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700506 ASSERT_EQ(nullptr, attempter_.error_event_.get());
Darin Petkov1b003102010-11-30 10:18:36 -0800507}
508
509TEST_F(UpdateAttempterTest, ActionCompletedErrorTest) {
Alex Deymo8427b4a2014-11-05 14:00:32 -0800510 MockAction action;
511 EXPECT_CALL(action, Type()).WillRepeatedly(Return("MockAction"));
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700512 attempter_.status_ = UpdateStatus::DOWNLOADING;
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700513 attempter_.ActionCompleted(nullptr, &action, ErrorCode::kError);
514 ASSERT_NE(nullptr, attempter_.error_event_.get());
Darin Petkov1b003102010-11-30 10:18:36 -0800515}
516
Aaron Wood9321f502017-09-07 11:18:54 -0700517TEST_F(UpdateAttempterTest, DownloadProgressAccumulationTest) {
518 // Simple test case, where all the values match (nothing was skipped)
519 uint64_t bytes_progressed_1 = 1024 * 1024; // 1MB
520 uint64_t bytes_progressed_2 = 1024 * 1024; // 1MB
521 uint64_t bytes_received_1 = bytes_progressed_1;
522 uint64_t bytes_received_2 = bytes_received_1 + bytes_progressed_2;
523 uint64_t bytes_total = 20 * 1024 * 1024; // 20MB
524
525 double progress_1 =
526 static_cast<double>(bytes_received_1) / static_cast<double>(bytes_total);
527 double progress_2 =
528 static_cast<double>(bytes_received_2) / static_cast<double>(bytes_total);
529
530 EXPECT_EQ(0.0, attempter_.download_progress_);
531 // This is set via inspecting the InstallPlan payloads when the
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700532 // |OmahaResponseAction| is completed.
Aaron Wood9321f502017-09-07 11:18:54 -0700533 attempter_.new_payload_size_ = bytes_total;
534 NiceMock<MockServiceObserver> observer;
535 EXPECT_CALL(observer,
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700536 SendStatusUpdate(AllOf(
537 Field(&UpdateEngineStatus::progress, progress_1),
538 Field(&UpdateEngineStatus::status, UpdateStatus::DOWNLOADING),
539 Field(&UpdateEngineStatus::new_size_bytes, bytes_total))));
Aaron Wood9321f502017-09-07 11:18:54 -0700540 EXPECT_CALL(observer,
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700541 SendStatusUpdate(AllOf(
542 Field(&UpdateEngineStatus::progress, progress_2),
543 Field(&UpdateEngineStatus::status, UpdateStatus::DOWNLOADING),
544 Field(&UpdateEngineStatus::new_size_bytes, bytes_total))));
Aaron Wood9321f502017-09-07 11:18:54 -0700545 attempter_.AddObserver(&observer);
546 attempter_.BytesReceived(bytes_progressed_1, bytes_received_1, bytes_total);
547 EXPECT_EQ(progress_1, attempter_.download_progress_);
548 // This iteration validates that a later set of updates to the variables are
549 // properly handled (so that |getStatus()| will return the same progress info
550 // as the callback is receiving.
551 attempter_.BytesReceived(bytes_progressed_2, bytes_received_2, bytes_total);
552 EXPECT_EQ(progress_2, attempter_.download_progress_);
553}
554
555TEST_F(UpdateAttempterTest, ChangeToDownloadingOnReceivedBytesTest) {
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700556 // The transition into |UpdateStatus::DOWNLOADING| happens when the
Aaron Wood9321f502017-09-07 11:18:54 -0700557 // first bytes are received.
558 uint64_t bytes_progressed = 1024 * 1024; // 1MB
559 uint64_t bytes_received = 2 * 1024 * 1024; // 2MB
560 uint64_t bytes_total = 20 * 1024 * 1024; // 300MB
561 attempter_.status_ = UpdateStatus::CHECKING_FOR_UPDATE;
562 // This is set via inspecting the InstallPlan payloads when the
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700563 // |OmahaResponseAction| is completed.
Aaron Wood9321f502017-09-07 11:18:54 -0700564 attempter_.new_payload_size_ = bytes_total;
565 EXPECT_EQ(0.0, attempter_.download_progress_);
566 NiceMock<MockServiceObserver> observer;
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700567 EXPECT_CALL(observer,
568 SendStatusUpdate(AllOf(
569 Field(&UpdateEngineStatus::status, UpdateStatus::DOWNLOADING),
570 Field(&UpdateEngineStatus::new_size_bytes, bytes_total))));
Aaron Wood9321f502017-09-07 11:18:54 -0700571 attempter_.AddObserver(&observer);
572 attempter_.BytesReceived(bytes_progressed, bytes_received, bytes_total);
573 EXPECT_EQ(UpdateStatus::DOWNLOADING, attempter_.status_);
574}
575
576TEST_F(UpdateAttempterTest, BroadcastCompleteDownloadTest) {
577 // There is a special case to ensure that at 100% downloaded,
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700578 // |download_progress_| is updated and broadcastest.
Aaron Wood9321f502017-09-07 11:18:54 -0700579 uint64_t bytes_progressed = 0; // ignored
580 uint64_t bytes_received = 5 * 1024 * 1024; // ignored
581 uint64_t bytes_total = 5 * 1024 * 1024; // 300MB
582 attempter_.status_ = UpdateStatus::DOWNLOADING;
583 attempter_.new_payload_size_ = bytes_total;
584 EXPECT_EQ(0.0, attempter_.download_progress_);
585 NiceMock<MockServiceObserver> observer;
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700586 EXPECT_CALL(observer,
587 SendStatusUpdate(AllOf(
588 Field(&UpdateEngineStatus::progress, 1.0),
589 Field(&UpdateEngineStatus::status, UpdateStatus::DOWNLOADING),
590 Field(&UpdateEngineStatus::new_size_bytes, bytes_total))));
Aaron Wood9321f502017-09-07 11:18:54 -0700591 attempter_.AddObserver(&observer);
592 attempter_.BytesReceived(bytes_progressed, bytes_received, bytes_total);
593 EXPECT_EQ(1.0, attempter_.download_progress_);
594}
595
Darin Petkov1b003102010-11-30 10:18:36 -0800596TEST_F(UpdateAttempterTest, ActionCompletedOmahaRequestTest) {
Ben Chan02f7c1d2014-10-18 15:18:02 -0700597 unique_ptr<MockHttpFetcher> fetcher(new MockHttpFetcher("", 0, nullptr));
Darin Petkov1b003102010-11-30 10:18:36 -0800598 fetcher->FailTransfer(500); // Sets the HTTP response code.
Amin Hassani538bd592020-11-04 20:46:08 -0800599 OmahaRequestAction action(nullptr, std::move(fetcher), false, "");
Darin Petkov1b003102010-11-30 10:18:36 -0800600 ObjectCollectorAction<OmahaResponse> collector_action;
601 BondActions(&action, &collector_action);
602 OmahaResponse response;
603 response.poll_interval = 234;
604 action.SetOutputObject(response);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700605 attempter_.ActionCompleted(nullptr, &action, ErrorCode::kSuccess);
Amin Hassani90e9f192020-11-18 14:20:56 -0800606 EXPECT_FALSE(prefs_->Exists(kPrefsDeltaUpdateFailures));
Darin Petkov1b003102010-11-30 10:18:36 -0800607 EXPECT_EQ(500, attempter_.http_response_code());
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700608 EXPECT_EQ(UpdateStatus::IDLE, attempter_.status());
Alex Deymo80f70ff2016-02-10 16:08:11 -0800609 EXPECT_EQ(234U, attempter_.server_dictated_poll_interval_);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700610 ASSERT_TRUE(attempter_.error_event_.get() == nullptr);
Darin Petkov1b003102010-11-30 10:18:36 -0800611}
612
Alex Deymo30534502015-07-20 15:06:33 -0700613TEST_F(UpdateAttempterTest, ConstructWithUpdatedMarkerTest) {
Alex Deymo906191f2015-10-12 12:22:44 -0700614 string boot_id;
615 EXPECT_TRUE(utils::GetBootId(&boot_id));
Amin Hassani90e9f192020-11-18 14:20:56 -0800616 FakeSystemState::Get()->fake_prefs()->SetString(kPrefsUpdateCompletedOnBootId,
617 boot_id);
Sen Jiangaeeb2e02016-06-09 15:00:16 -0700618 attempter_.Init();
619 EXPECT_EQ(UpdateStatus::UPDATED_NEED_REBOOT, attempter_.status());
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700620}
621
622TEST_F(UpdateAttempterTest, GetErrorCodeForActionTest) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700623 EXPECT_EQ(ErrorCode::kSuccess,
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700624 GetErrorCodeForAction(nullptr, ErrorCode::kSuccess));
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700625
Amin Hassani538bd592020-11-04 20:46:08 -0800626 OmahaRequestAction omaha_request_action(nullptr, nullptr, false, "");
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700627 EXPECT_EQ(ErrorCode::kOmahaRequestError,
628 GetErrorCodeForAction(&omaha_request_action, ErrorCode::kError));
Amin Hassani538bd592020-11-04 20:46:08 -0800629 OmahaResponseHandlerAction omaha_response_handler_action;
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800630 EXPECT_EQ(
631 ErrorCode::kOmahaResponseHandlerError,
632 GetErrorCodeForAction(&omaha_response_handler_action, ErrorCode::kError));
Tianjie24f96092020-06-30 12:26:25 -0700633 DynamicPartitionControlStub dynamic_control_stub;
634 FilesystemVerifierAction filesystem_verifier_action(&dynamic_control_stub);
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800635 EXPECT_EQ(
636 ErrorCode::kFilesystemVerifierError,
637 GetErrorCodeForAction(&filesystem_verifier_action, ErrorCode::kError));
Alex Deymob15a0b82015-11-25 20:30:40 -0300638 PostinstallRunnerAction postinstall_runner_action(
Amin Hassani538bd592020-11-04 20:46:08 -0800639 FakeSystemState::Get()->fake_boot_control(),
640 FakeSystemState::Get()->fake_hardware());
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800641 EXPECT_EQ(
642 ErrorCode::kPostinstallRunnerError,
643 GetErrorCodeForAction(&postinstall_runner_action, ErrorCode::kError));
Alex Deymo8427b4a2014-11-05 14:00:32 -0800644 MockAction action_mock;
645 EXPECT_CALL(action_mock, Type()).WillOnce(Return("MockAction"));
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700646 EXPECT_EQ(ErrorCode::kError,
647 GetErrorCodeForAction(&action_mock, ErrorCode::kError));
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700648}
649
Darin Petkov36275772010-10-01 11:40:57 -0700650TEST_F(UpdateAttempterTest, DisableDeltaUpdateIfNeededTest) {
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700651 attempter_.omaha_request_params_->set_delta_okay(true);
Darin Petkov36275772010-10-01 11:40:57 -0700652 attempter_.DisableDeltaUpdateIfNeeded();
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700653 EXPECT_TRUE(attempter_.omaha_request_params_->delta_okay());
Amin Hassani90e9f192020-11-18 14:20:56 -0800654 prefs_->SetInt64(kPrefsDeltaUpdateFailures,
655 UpdateAttempter::kMaxDeltaUpdateFailures - 1);
Darin Petkov36275772010-10-01 11:40:57 -0700656 attempter_.DisableDeltaUpdateIfNeeded();
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700657 EXPECT_TRUE(attempter_.omaha_request_params_->delta_okay());
Amin Hassani90e9f192020-11-18 14:20:56 -0800658 prefs_->SetInt64(kPrefsDeltaUpdateFailures,
659 UpdateAttempter::kMaxDeltaUpdateFailures);
Darin Petkov36275772010-10-01 11:40:57 -0700660 attempter_.DisableDeltaUpdateIfNeeded();
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700661 EXPECT_FALSE(attempter_.omaha_request_params_->delta_okay());
Darin Petkov36275772010-10-01 11:40:57 -0700662 attempter_.DisableDeltaUpdateIfNeeded();
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700663 EXPECT_FALSE(attempter_.omaha_request_params_->delta_okay());
Darin Petkov36275772010-10-01 11:40:57 -0700664}
665
666TEST_F(UpdateAttempterTest, MarkDeltaUpdateFailureTest) {
Amin Hassani90e9f192020-11-18 14:20:56 -0800667 attempter_.MarkDeltaUpdateFailure();
668
669 EXPECT_TRUE(prefs_->SetInt64(kPrefsDeltaUpdateFailures, -1));
670 attempter_.MarkDeltaUpdateFailure();
671 int64_t value = 0;
672 EXPECT_TRUE(prefs_->GetInt64(kPrefsDeltaUpdateFailures, &value));
673 EXPECT_EQ(value, 1);
674
675 attempter_.MarkDeltaUpdateFailure();
676 EXPECT_TRUE(prefs_->GetInt64(kPrefsDeltaUpdateFailures, &value));
677 EXPECT_EQ(value, 2);
678
679 EXPECT_TRUE(prefs_->SetInt64(kPrefsDeltaUpdateFailures,
680 UpdateAttempter::kMaxDeltaUpdateFailures));
681 attempter_.MarkDeltaUpdateFailure();
682 EXPECT_TRUE(prefs_->GetInt64(kPrefsDeltaUpdateFailures, &value));
683 EXPECT_EQ(value, UpdateAttempter::kMaxDeltaUpdateFailures + 1);
Darin Petkov36275772010-10-01 11:40:57 -0700684}
685
Darin Petkov1b003102010-11-30 10:18:36 -0800686TEST_F(UpdateAttempterTest, ScheduleErrorEventActionNoEventTest) {
687 EXPECT_CALL(*processor_, EnqueueAction(_)).Times(0);
688 EXPECT_CALL(*processor_, StartProcessing()).Times(0);
Amin Hassani538bd592020-11-04 20:46:08 -0800689 EXPECT_CALL(*FakeSystemState::Get()->mock_payload_state(), UpdateFailed(_))
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800690 .Times(0);
691 OmahaResponse response;
Jay Srinivasan53173b92013-05-17 17:13:01 -0700692 string url1 = "http://url1";
Sen Jiang0affc2c2017-02-10 15:55:05 -0800693 response.packages.push_back({.payload_urls = {url1, "https://url"}});
Amin Hassani538bd592020-11-04 20:46:08 -0800694 EXPECT_CALL(*(FakeSystemState::Get()->mock_payload_state()), GetCurrentUrl())
Jay Srinivasan53173b92013-05-17 17:13:01 -0700695 .WillRepeatedly(Return(url1));
Amin Hassani538bd592020-11-04 20:46:08 -0800696 FakeSystemState::Get()->mock_payload_state()->SetResponse(response);
Darin Petkov1b003102010-11-30 10:18:36 -0800697 attempter_.ScheduleErrorEventAction();
Amin Hassani538bd592020-11-04 20:46:08 -0800698 EXPECT_EQ(url1,
699 FakeSystemState::Get()->mock_payload_state()->GetCurrentUrl());
Darin Petkov1b003102010-11-30 10:18:36 -0800700}
701
702TEST_F(UpdateAttempterTest, ScheduleErrorEventActionTest) {
703 EXPECT_CALL(*processor_,
Amin Hassanid3f4bea2018-04-30 14:52:40 -0700704 EnqueueAction(Pointee(Property(
705 &AbstractAction::Type, OmahaRequestAction::StaticType()))));
Gilad Arnold74b5f552014-10-07 08:17:16 -0700706 EXPECT_CALL(*processor_, StartProcessing());
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700707 ErrorCode err = ErrorCode::kError;
Amin Hassani538bd592020-11-04 20:46:08 -0800708 EXPECT_CALL(*FakeSystemState::Get()->mock_payload_state(), UpdateFailed(err));
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800709 attempter_.error_event_.reset(new OmahaEvent(
710 OmahaEvent::kTypeUpdateComplete, OmahaEvent::kResultError, err));
Darin Petkov1b003102010-11-30 10:18:36 -0800711 attempter_.ScheduleErrorEventAction();
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700712 EXPECT_EQ(UpdateStatus::REPORTING_ERROR_EVENT, attempter_.status());
Darin Petkov1b003102010-11-30 10:18:36 -0800713}
714
Darin Petkove6ef2f82011-03-07 17:31:11 -0800715namespace {
Chris Sosa76a29ae2013-07-11 17:59:24 -0700716// Actions that will be built as part of an update check.
Askar Aitzhan570ca872019-04-24 11:16:12 +0200717vector<string> GetUpdateActionTypes() {
718 return {OmahaRequestAction::StaticType(),
719 OmahaResponseHandlerAction::StaticType(),
720 UpdateBootFlagsAction::StaticType(),
721 OmahaRequestAction::StaticType(),
Kelvin Zhang97cb0582020-12-02 16:42:15 -0500722 DownloadActionChromeos::StaticType(),
Askar Aitzhan570ca872019-04-24 11:16:12 +0200723 OmahaRequestAction::StaticType(),
724 FilesystemVerifierAction::StaticType(),
725 PostinstallRunnerAction::StaticType(),
726 OmahaRequestAction::StaticType()};
727}
Chris Sosa76a29ae2013-07-11 17:59:24 -0700728
729// Actions that will be built as part of a user-initiated rollback.
Askar Aitzhan570ca872019-04-24 11:16:12 +0200730vector<string> GetRollbackActionTypes() {
731 return {InstallPlanAction::StaticType(),
732 PostinstallRunnerAction::StaticType()};
733}
Chris Sosa76a29ae2013-07-11 17:59:24 -0700734
Adolfo Victoria497044c2018-07-18 07:51:42 -0700735const StagingSchedule kValidStagingSchedule = {
736 {4, 10}, {10, 40}, {19, 70}, {26, 100}};
737
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700738} // namespace
Darin Petkove6ef2f82011-03-07 17:31:11 -0800739
740void UpdateAttempterTest::UpdateTestStart() {
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700741 attempter_.set_http_response_code(200);
Alex Deymo749ecf12014-10-21 20:06:57 -0700742
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700743 // Expect that the device policy is loaded by the |UpdateAttempter| at some
744 // point by calling |RefreshDevicePolicy()|.
Igor9fd76b62017-12-11 15:24:18 +0100745 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Alex Deymo749ecf12014-10-21 20:06:57 -0700746 EXPECT_CALL(*device_policy, LoadPolicy())
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800747 .Times(testing::AtLeast(1))
748 .WillRepeatedly(Return(true));
Igor9fd76b62017-12-11 15:24:18 +0100749 attempter_.policy_provider_.reset(
750 new policy::PolicyProvider(std::move(device_policy)));
Alex Deymo749ecf12014-10-21 20:06:57 -0700751
752 {
753 InSequence s;
Askar Aitzhan570ca872019-04-24 11:16:12 +0200754 for (const auto& update_action_type : GetUpdateActionTypes()) {
Alex Deymo749ecf12014-10-21 20:06:57 -0700755 EXPECT_CALL(*processor_,
Amin Hassanid3f4bea2018-04-30 14:52:40 -0700756 EnqueueAction(Pointee(
Askar Aitzhan570ca872019-04-24 11:16:12 +0200757 Property(&AbstractAction::Type, update_action_type))));
Alex Deymo749ecf12014-10-21 20:06:57 -0700758 }
Gilad Arnold74b5f552014-10-07 08:17:16 -0700759 EXPECT_CALL(*processor_, StartProcessing());
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700760 }
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700761
Amin Hassanie8153632020-10-27 15:11:28 -0700762 attempter_.Update({});
Alex Deymo60ca1a72015-06-18 18:19:15 -0700763 loop_.PostTask(FROM_HERE,
764 base::Bind(&UpdateAttempterTest::UpdateTestVerify,
765 base::Unretained(this)));
Darin Petkove6ef2f82011-03-07 17:31:11 -0800766}
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700767
Darin Petkove6ef2f82011-03-07 17:31:11 -0800768void UpdateAttempterTest::UpdateTestVerify() {
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700769 EXPECT_EQ(0, attempter_.http_response_code());
770 EXPECT_EQ(&attempter_, processor_->delegate());
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700771 EXPECT_EQ(UpdateStatus::CHECKING_FOR_UPDATE, attempter_.status());
Alex Deymo60ca1a72015-06-18 18:19:15 -0700772 loop_.BreakLoop();
Darin Petkove6ef2f82011-03-07 17:31:11 -0800773}
774
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800775void UpdateAttempterTest::RollbackTestStart(bool enterprise_rollback,
776 bool valid_slot) {
Chris Sosa76a29ae2013-07-11 17:59:24 -0700777 // Create a device policy so that we can change settings.
Igor9fd76b62017-12-11 15:24:18 +0100778 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Chris Sosa76a29ae2013-07-11 17:59:24 -0700779 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
Amin Hassani538bd592020-11-04 20:46:08 -0800780 FakeSystemState::Get()->set_device_policy(device_policy.get());
Igor9fd76b62017-12-11 15:24:18 +0100781 if (enterprise_rollback) {
782 // We return an empty owner as this is an enterprise.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800783 EXPECT_CALL(*device_policy, GetOwner(_))
784 .WillRepeatedly(DoAll(SetArgPointee<0>(string("")), Return(true)));
Igor9fd76b62017-12-11 15:24:18 +0100785 } else {
786 // We return a fake owner as this is an owned consumer device.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800787 EXPECT_CALL(*device_policy, GetOwner(_))
788 .WillRepeatedly(DoAll(SetArgPointee<0>(string("fake.mail@fake.com")),
789 Return(true)));
Igor9fd76b62017-12-11 15:24:18 +0100790 }
791
792 attempter_.policy_provider_.reset(
793 new policy::PolicyProvider(std::move(device_policy)));
Chris Sosa76a29ae2013-07-11 17:59:24 -0700794
Alex Deymo763e7db2015-08-27 21:08:08 -0700795 if (valid_slot) {
796 BootControlInterface::Slot rollback_slot = 1;
797 LOG(INFO) << "Test Mark Bootable: "
798 << BootControlInterface::SlotName(rollback_slot);
Amin Hassani538bd592020-11-04 20:46:08 -0800799 FakeSystemState::Get()->fake_boot_control()->SetSlotBootable(rollback_slot,
800 true);
Don Garrett6646b442013-11-13 15:29:11 -0800801 }
802
Chris Sosa28e479c2013-07-12 11:39:53 -0700803 bool is_rollback_allowed = false;
Chris Sosa76a29ae2013-07-11 17:59:24 -0700804
Chris Sosad38b1132014-03-25 10:43:59 -0700805 // We only allow rollback on devices that are not enterprise enrolled and
806 // which have a valid slot to rollback to.
807 if (!enterprise_rollback && valid_slot) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800808 is_rollback_allowed = true;
Chris Sosa28e479c2013-07-12 11:39:53 -0700809 }
810
Chris Sosa28e479c2013-07-12 11:39:53 -0700811 if (is_rollback_allowed) {
Chris Sosa76a29ae2013-07-11 17:59:24 -0700812 InSequence s;
Askar Aitzhan570ca872019-04-24 11:16:12 +0200813 for (const auto& rollback_action_type : GetRollbackActionTypes()) {
Chris Sosa76a29ae2013-07-11 17:59:24 -0700814 EXPECT_CALL(*processor_,
Askar Aitzhan570ca872019-04-24 11:16:12 +0200815 EnqueueAction(Pointee(
816 Property(&AbstractAction::Type, rollback_action_type))));
Chris Sosa76a29ae2013-07-11 17:59:24 -0700817 }
Gilad Arnold74b5f552014-10-07 08:17:16 -0700818 EXPECT_CALL(*processor_, StartProcessing());
Chris Sosa76a29ae2013-07-11 17:59:24 -0700819
Chris Sosa44b9b7e2014-04-02 13:53:46 -0700820 EXPECT_TRUE(attempter_.Rollback(true));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700821 loop_.PostTask(FROM_HERE,
822 base::Bind(&UpdateAttempterTest::RollbackTestVerify,
823 base::Unretained(this)));
Chris Sosa76a29ae2013-07-11 17:59:24 -0700824 } else {
Chris Sosa44b9b7e2014-04-02 13:53:46 -0700825 EXPECT_FALSE(attempter_.Rollback(true));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700826 loop_.BreakLoop();
Chris Sosa76a29ae2013-07-11 17:59:24 -0700827 }
828}
829
830void UpdateAttempterTest::RollbackTestVerify() {
831 // Verifies the actions that were enqueued.
832 EXPECT_EQ(&attempter_, processor_->delegate());
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700833 EXPECT_EQ(UpdateStatus::ATTEMPTING_ROLLBACK, attempter_.status());
Amin Hassanid3f4bea2018-04-30 14:52:40 -0700834 EXPECT_EQ(0U, attempter_.install_plan_->partitions.size());
835 EXPECT_EQ(attempter_.install_plan_->powerwash_required, true);
Alex Deymo60ca1a72015-06-18 18:19:15 -0700836 loop_.BreakLoop();
Chris Sosa76a29ae2013-07-11 17:59:24 -0700837}
838
Darin Petkove6ef2f82011-03-07 17:31:11 -0800839TEST_F(UpdateAttempterTest, UpdateTest) {
Alex Deymo461b2592015-07-24 20:10:52 -0700840 UpdateTestStart();
Alex Deymo60ca1a72015-06-18 18:19:15 -0700841 loop_.Run();
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700842}
843
Chris Sosa76a29ae2013-07-11 17:59:24 -0700844TEST_F(UpdateAttempterTest, RollbackTest) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700845 loop_.PostTask(FROM_HERE,
846 base::Bind(&UpdateAttempterTest::RollbackTestStart,
847 base::Unretained(this),
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800848 false,
849 true));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700850 loop_.Run();
Chris Sosa76a29ae2013-07-11 17:59:24 -0700851}
852
Don Garrett6646b442013-11-13 15:29:11 -0800853TEST_F(UpdateAttempterTest, InvalidSlotRollbackTest) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700854 loop_.PostTask(FROM_HERE,
855 base::Bind(&UpdateAttempterTest::RollbackTestStart,
856 base::Unretained(this),
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800857 false,
858 false));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700859 loop_.Run();
Don Garrett6646b442013-11-13 15:29:11 -0800860}
861
Chris Sosa76a29ae2013-07-11 17:59:24 -0700862TEST_F(UpdateAttempterTest, EnterpriseRollbackTest) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700863 loop_.PostTask(FROM_HERE,
864 base::Bind(&UpdateAttempterTest::RollbackTestStart,
865 base::Unretained(this),
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800866 true,
867 true));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700868 loop_.Run();
Chris Sosa76a29ae2013-07-11 17:59:24 -0700869}
870
Thieu Le116fda32011-04-19 11:01:54 -0700871void UpdateAttempterTest::PingOmahaTestStart() {
872 EXPECT_CALL(*processor_,
Amin Hassanid3f4bea2018-04-30 14:52:40 -0700873 EnqueueAction(Pointee(Property(
874 &AbstractAction::Type, OmahaRequestAction::StaticType()))));
Gilad Arnold74b5f552014-10-07 08:17:16 -0700875 EXPECT_CALL(*processor_, StartProcessing());
Thieu Le116fda32011-04-19 11:01:54 -0700876 attempter_.PingOmaha();
Alex Deymo60ca1a72015-06-18 18:19:15 -0700877 ScheduleQuitMainLoop();
Thieu Le116fda32011-04-19 11:01:54 -0700878}
879
880TEST_F(UpdateAttempterTest, PingOmahaTest) {
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700881 EXPECT_FALSE(attempter_.waiting_for_scheduled_check_);
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700882 EXPECT_FALSE(attempter_.WasScheduleUpdatesCalled());
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700883 // Disable scheduling of subsequnet checks; we're using the |DefaultPolicy| in
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700884 // testing, which is more permissive than we want to handle here.
885 attempter_.DisableScheduleUpdates();
Alex Deymo60ca1a72015-06-18 18:19:15 -0700886 loop_.PostTask(FROM_HERE,
887 base::Bind(&UpdateAttempterTest::PingOmahaTestStart,
888 base::Unretained(this)));
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700889 brillo::MessageLoopRunMaxIterations(&loop_, 100);
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700890 EXPECT_EQ(UpdateStatus::UPDATED_NEED_REBOOT, attempter_.status());
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700891 EXPECT_TRUE(attempter_.WasScheduleUpdatesCalled());
Thieu Le116fda32011-04-19 11:01:54 -0700892}
893
Darin Petkov18c7bce2011-06-16 14:07:00 -0700894TEST_F(UpdateAttempterTest, CreatePendingErrorEventTest) {
Alex Deymo8427b4a2014-11-05 14:00:32 -0800895 MockAction action;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700896 const ErrorCode kCode = ErrorCode::kDownloadTransferError;
Darin Petkov18c7bce2011-06-16 14:07:00 -0700897 attempter_.CreatePendingErrorEvent(&action, kCode);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700898 ASSERT_NE(nullptr, attempter_.error_event_.get());
Darin Petkov18c7bce2011-06-16 14:07:00 -0700899 EXPECT_EQ(OmahaEvent::kTypeUpdateComplete, attempter_.error_event_->type);
900 EXPECT_EQ(OmahaEvent::kResultError, attempter_.error_event_->result);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700901 EXPECT_EQ(
902 static_cast<ErrorCode>(static_cast<int>(kCode) |
903 static_cast<int>(ErrorCode::kTestOmahaUrlFlag)),
904 attempter_.error_event_->error_code);
Darin Petkov18c7bce2011-06-16 14:07:00 -0700905}
906
907TEST_F(UpdateAttempterTest, CreatePendingErrorEventResumedTest) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -0700908 attempter_.install_plan_.reset(new InstallPlan);
909 attempter_.install_plan_->is_resume = true;
Alex Deymo8427b4a2014-11-05 14:00:32 -0800910 MockAction action;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700911 const ErrorCode kCode = ErrorCode::kInstallDeviceOpenError;
Darin Petkov18c7bce2011-06-16 14:07:00 -0700912 attempter_.CreatePendingErrorEvent(&action, kCode);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700913 ASSERT_NE(nullptr, attempter_.error_event_.get());
Darin Petkov18c7bce2011-06-16 14:07:00 -0700914 EXPECT_EQ(OmahaEvent::kTypeUpdateComplete, attempter_.error_event_->type);
915 EXPECT_EQ(OmahaEvent::kResultError, attempter_.error_event_->result);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700916 EXPECT_EQ(
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800917 static_cast<ErrorCode>(static_cast<int>(kCode) |
918 static_cast<int>(ErrorCode::kResumedFlag) |
919 static_cast<int>(ErrorCode::kTestOmahaUrlFlag)),
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700920 attempter_.error_event_->error_code);
Darin Petkov18c7bce2011-06-16 14:07:00 -0700921}
922
David Zeuthen8f191b22013-08-06 12:27:50 -0700923TEST_F(UpdateAttempterTest, P2PNotStartedAtStartupWhenNotEnabled) {
924 MockP2PManager mock_p2p_manager;
Amin Hassani538bd592020-11-04 20:46:08 -0800925 FakeSystemState::Get()->set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -0700926 mock_p2p_manager.fake().SetP2PEnabled(false);
927 EXPECT_CALL(mock_p2p_manager, EnsureP2PRunning()).Times(0);
928 attempter_.UpdateEngineStarted();
929}
930
931TEST_F(UpdateAttempterTest, P2PNotStartedAtStartupWhenEnabledButNotSharing) {
932 MockP2PManager mock_p2p_manager;
Amin Hassani538bd592020-11-04 20:46:08 -0800933 FakeSystemState::Get()->set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -0700934 mock_p2p_manager.fake().SetP2PEnabled(true);
935 EXPECT_CALL(mock_p2p_manager, EnsureP2PRunning()).Times(0);
936 attempter_.UpdateEngineStarted();
937}
938
939TEST_F(UpdateAttempterTest, P2PStartedAtStartupWhenEnabledAndSharing) {
940 MockP2PManager mock_p2p_manager;
Amin Hassani538bd592020-11-04 20:46:08 -0800941 FakeSystemState::Get()->set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -0700942 mock_p2p_manager.fake().SetP2PEnabled(true);
943 mock_p2p_manager.fake().SetCountSharedFilesResult(1);
Gilad Arnold74b5f552014-10-07 08:17:16 -0700944 EXPECT_CALL(mock_p2p_manager, EnsureP2PRunning());
David Zeuthen8f191b22013-08-06 12:27:50 -0700945 attempter_.UpdateEngineStarted();
946}
947
948TEST_F(UpdateAttempterTest, P2PNotEnabled) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700949 loop_.PostTask(FROM_HERE,
950 base::Bind(&UpdateAttempterTest::P2PNotEnabledStart,
951 base::Unretained(this)));
952 loop_.Run();
David Zeuthen8f191b22013-08-06 12:27:50 -0700953}
Alex Deymo60ca1a72015-06-18 18:19:15 -0700954
David Zeuthen8f191b22013-08-06 12:27:50 -0700955void UpdateAttempterTest::P2PNotEnabledStart() {
956 // If P2P is not enabled, check that we do not attempt housekeeping
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700957 // and do not convey that P2P is to be used.
David Zeuthen8f191b22013-08-06 12:27:50 -0700958 MockP2PManager mock_p2p_manager;
Amin Hassani538bd592020-11-04 20:46:08 -0800959 FakeSystemState::Get()->set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -0700960 mock_p2p_manager.fake().SetP2PEnabled(false);
961 EXPECT_CALL(mock_p2p_manager, PerformHousekeeping()).Times(0);
Amin Hassanie8153632020-10-27 15:11:28 -0700962 attempter_.Update({});
Alex Deymo60ca1a72015-06-18 18:19:15 -0700963 EXPECT_FALSE(actual_using_p2p_for_downloading_);
Gilad Arnold74b5f552014-10-07 08:17:16 -0700964 EXPECT_FALSE(actual_using_p2p_for_sharing());
Alex Deymo60ca1a72015-06-18 18:19:15 -0700965 ScheduleQuitMainLoop();
David Zeuthen8f191b22013-08-06 12:27:50 -0700966}
967
968TEST_F(UpdateAttempterTest, P2PEnabledStartingFails) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700969 loop_.PostTask(FROM_HERE,
970 base::Bind(&UpdateAttempterTest::P2PEnabledStartingFailsStart,
971 base::Unretained(this)));
972 loop_.Run();
David Zeuthen8f191b22013-08-06 12:27:50 -0700973}
Alex Deymo60ca1a72015-06-18 18:19:15 -0700974
David Zeuthen8f191b22013-08-06 12:27:50 -0700975void UpdateAttempterTest::P2PEnabledStartingFailsStart() {
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700976 // If P2P is enabled, but starting it fails ensure we don't do
977 // any housekeeping and do not convey that P2P should be used.
David Zeuthen8f191b22013-08-06 12:27:50 -0700978 MockP2PManager mock_p2p_manager;
Amin Hassani538bd592020-11-04 20:46:08 -0800979 FakeSystemState::Get()->set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -0700980 mock_p2p_manager.fake().SetP2PEnabled(true);
981 mock_p2p_manager.fake().SetEnsureP2PRunningResult(false);
982 mock_p2p_manager.fake().SetPerformHousekeepingResult(false);
983 EXPECT_CALL(mock_p2p_manager, PerformHousekeeping()).Times(0);
Amin Hassanie8153632020-10-27 15:11:28 -0700984 attempter_.Update({});
Gilad Arnold74b5f552014-10-07 08:17:16 -0700985 EXPECT_FALSE(actual_using_p2p_for_downloading());
986 EXPECT_FALSE(actual_using_p2p_for_sharing());
Alex Deymo60ca1a72015-06-18 18:19:15 -0700987 ScheduleQuitMainLoop();
David Zeuthen8f191b22013-08-06 12:27:50 -0700988}
989
990TEST_F(UpdateAttempterTest, P2PEnabledHousekeepingFails) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700991 loop_.PostTask(
992 FROM_HERE,
993 base::Bind(&UpdateAttempterTest::P2PEnabledHousekeepingFailsStart,
994 base::Unretained(this)));
995 loop_.Run();
David Zeuthen8f191b22013-08-06 12:27:50 -0700996}
Alex Deymo60ca1a72015-06-18 18:19:15 -0700997
David Zeuthen8f191b22013-08-06 12:27:50 -0700998void UpdateAttempterTest::P2PEnabledHousekeepingFailsStart() {
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700999 // If P2P is enabled, starting it works but housekeeping fails, ensure
1000 // we do not convey P2P is to be used.
David Zeuthen8f191b22013-08-06 12:27:50 -07001001 MockP2PManager mock_p2p_manager;
Amin Hassani538bd592020-11-04 20:46:08 -08001002 FakeSystemState::Get()->set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -07001003 mock_p2p_manager.fake().SetP2PEnabled(true);
1004 mock_p2p_manager.fake().SetEnsureP2PRunningResult(true);
1005 mock_p2p_manager.fake().SetPerformHousekeepingResult(false);
Gilad Arnold74b5f552014-10-07 08:17:16 -07001006 EXPECT_CALL(mock_p2p_manager, PerformHousekeeping());
Amin Hassanie8153632020-10-27 15:11:28 -07001007 attempter_.Update({});
Gilad Arnold74b5f552014-10-07 08:17:16 -07001008 EXPECT_FALSE(actual_using_p2p_for_downloading());
1009 EXPECT_FALSE(actual_using_p2p_for_sharing());
Alex Deymo60ca1a72015-06-18 18:19:15 -07001010 ScheduleQuitMainLoop();
David Zeuthen8f191b22013-08-06 12:27:50 -07001011}
1012
1013TEST_F(UpdateAttempterTest, P2PEnabled) {
Alex Deymo60ca1a72015-06-18 18:19:15 -07001014 loop_.PostTask(FROM_HERE,
1015 base::Bind(&UpdateAttempterTest::P2PEnabledStart,
1016 base::Unretained(this)));
1017 loop_.Run();
David Zeuthen8f191b22013-08-06 12:27:50 -07001018}
Alex Deymo60ca1a72015-06-18 18:19:15 -07001019
David Zeuthen8f191b22013-08-06 12:27:50 -07001020void UpdateAttempterTest::P2PEnabledStart() {
1021 MockP2PManager mock_p2p_manager;
Amin Hassani538bd592020-11-04 20:46:08 -08001022 FakeSystemState::Get()->set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -07001023 // If P2P is enabled and starting it works, check that we performed
Jae Hoon Kimedb65502019-06-14 11:52:17 -07001024 // housekeeping and that we convey P2P should be used.
David Zeuthen8f191b22013-08-06 12:27:50 -07001025 mock_p2p_manager.fake().SetP2PEnabled(true);
1026 mock_p2p_manager.fake().SetEnsureP2PRunningResult(true);
1027 mock_p2p_manager.fake().SetPerformHousekeepingResult(true);
Gilad Arnold74b5f552014-10-07 08:17:16 -07001028 EXPECT_CALL(mock_p2p_manager, PerformHousekeeping());
Amin Hassanie8153632020-10-27 15:11:28 -07001029 attempter_.Update({});
Gilad Arnold74b5f552014-10-07 08:17:16 -07001030 EXPECT_TRUE(actual_using_p2p_for_downloading());
1031 EXPECT_TRUE(actual_using_p2p_for_sharing());
Alex Deymo60ca1a72015-06-18 18:19:15 -07001032 ScheduleQuitMainLoop();
David Zeuthen8f191b22013-08-06 12:27:50 -07001033}
1034
1035TEST_F(UpdateAttempterTest, P2PEnabledInteractive) {
Alex Deymo60ca1a72015-06-18 18:19:15 -07001036 loop_.PostTask(FROM_HERE,
1037 base::Bind(&UpdateAttempterTest::P2PEnabledInteractiveStart,
1038 base::Unretained(this)));
1039 loop_.Run();
David Zeuthen8f191b22013-08-06 12:27:50 -07001040}
Alex Deymo60ca1a72015-06-18 18:19:15 -07001041
David Zeuthen8f191b22013-08-06 12:27:50 -07001042void UpdateAttempterTest::P2PEnabledInteractiveStart() {
1043 MockP2PManager mock_p2p_manager;
Amin Hassani538bd592020-11-04 20:46:08 -08001044 FakeSystemState::Get()->set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -07001045 // For an interactive check, if P2P is enabled and starting it
1046 // works, check that we performed housekeeping and that we convey
Jae Hoon Kimedb65502019-06-14 11:52:17 -07001047 // P2P should be used for sharing but NOT for downloading.
David Zeuthen8f191b22013-08-06 12:27:50 -07001048 mock_p2p_manager.fake().SetP2PEnabled(true);
1049 mock_p2p_manager.fake().SetEnsureP2PRunningResult(true);
1050 mock_p2p_manager.fake().SetPerformHousekeepingResult(true);
Gilad Arnold74b5f552014-10-07 08:17:16 -07001051 EXPECT_CALL(mock_p2p_manager, PerformHousekeeping());
Amin Hassanie8153632020-10-27 15:11:28 -07001052 attempter_.Update({.interactive = true});
Gilad Arnold74b5f552014-10-07 08:17:16 -07001053 EXPECT_FALSE(actual_using_p2p_for_downloading());
1054 EXPECT_TRUE(actual_using_p2p_for_sharing());
Alex Deymo60ca1a72015-06-18 18:19:15 -07001055 ScheduleQuitMainLoop();
David Zeuthen8f191b22013-08-06 12:27:50 -07001056}
1057
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001058TEST_F(UpdateAttempterTest, ReadScatterFactorFromPolicy) {
Alex Deymo60ca1a72015-06-18 18:19:15 -07001059 loop_.PostTask(
1060 FROM_HERE,
1061 base::Bind(&UpdateAttempterTest::ReadScatterFactorFromPolicyTestStart,
1062 base::Unretained(this)));
1063 loop_.Run();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001064}
1065
1066// Tests that the scatter_factor_in_seconds value is properly fetched
1067// from the device policy.
1068void UpdateAttempterTest::ReadScatterFactorFromPolicyTestStart() {
Ben Chan9abb7632014-08-07 00:10:53 -07001069 int64_t scatter_factor_in_seconds = 36000;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001070
Igor9fd76b62017-12-11 15:24:18 +01001071 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001072 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
Amin Hassani538bd592020-11-04 20:46:08 -08001073 FakeSystemState::Get()->set_device_policy(device_policy.get());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001074
1075 EXPECT_CALL(*device_policy, GetScatterFactorInSeconds(_))
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001076 .WillRepeatedly(
1077 DoAll(SetArgPointee<0>(scatter_factor_in_seconds), Return(true)));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001078
Igor9fd76b62017-12-11 15:24:18 +01001079 attempter_.policy_provider_.reset(
1080 new policy::PolicyProvider(std::move(device_policy)));
1081
Amin Hassanie8153632020-10-27 15:11:28 -07001082 attempter_.Update({});
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001083 EXPECT_EQ(scatter_factor_in_seconds, attempter_.scatter_factor_.InSeconds());
1084
Alex Deymo60ca1a72015-06-18 18:19:15 -07001085 ScheduleQuitMainLoop();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001086}
1087
1088TEST_F(UpdateAttempterTest, DecrementUpdateCheckCountTest) {
Alex Deymo60ca1a72015-06-18 18:19:15 -07001089 loop_.PostTask(
1090 FROM_HERE,
1091 base::Bind(&UpdateAttempterTest::DecrementUpdateCheckCountTestStart,
1092 base::Unretained(this)));
1093 loop_.Run();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001094}
1095
1096void UpdateAttempterTest::DecrementUpdateCheckCountTestStart() {
1097 // Tests that the scatter_factor_in_seconds value is properly fetched
1098 // from the device policy and is decremented if value > 0.
Ben Chan9abb7632014-08-07 00:10:53 -07001099 int64_t initial_value = 5;
Amin Hassani90e9f192020-11-18 14:20:56 -08001100 auto* fake_prefs = FakeSystemState::Get()->fake_prefs();
Amin Hassani538bd592020-11-04 20:46:08 -08001101 FakeSystemState::Get()->fake_hardware()->SetIsOOBEComplete(Time::UnixEpoch());
Jay Srinivasan08fce042012-06-07 16:31:01 -07001102
Amin Hassani90e9f192020-11-18 14:20:56 -08001103 EXPECT_TRUE(fake_prefs->SetInt64(kPrefsUpdateCheckCount, initial_value));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001104
Ben Chan9abb7632014-08-07 00:10:53 -07001105 int64_t scatter_factor_in_seconds = 10;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001106
Igor9fd76b62017-12-11 15:24:18 +01001107 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001108 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
Amin Hassani538bd592020-11-04 20:46:08 -08001109 FakeSystemState::Get()->set_device_policy(device_policy.get());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001110
1111 EXPECT_CALL(*device_policy, GetScatterFactorInSeconds(_))
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001112 .WillRepeatedly(
1113 DoAll(SetArgPointee<0>(scatter_factor_in_seconds), Return(true)));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001114
Igor9fd76b62017-12-11 15:24:18 +01001115 attempter_.policy_provider_.reset(
1116 new policy::PolicyProvider(std::move(device_policy)));
1117
Amin Hassanie8153632020-10-27 15:11:28 -07001118 attempter_.Update({});
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001119 EXPECT_EQ(scatter_factor_in_seconds, attempter_.scatter_factor_.InSeconds());
1120
1121 // Make sure the file still exists.
Amin Hassani90e9f192020-11-18 14:20:56 -08001122 EXPECT_TRUE(fake_prefs->Exists(kPrefsUpdateCheckCount));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001123
Ben Chan9abb7632014-08-07 00:10:53 -07001124 int64_t new_value;
Amin Hassani90e9f192020-11-18 14:20:56 -08001125 EXPECT_TRUE(fake_prefs->GetInt64(kPrefsUpdateCheckCount, &new_value));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001126 EXPECT_EQ(initial_value - 1, new_value);
1127
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001128 EXPECT_TRUE(
1129 attempter_.omaha_request_params_->update_check_count_wait_enabled());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001130
1131 // However, if the count is already 0, it's not decremented. Test that.
1132 initial_value = 0;
Amin Hassani90e9f192020-11-18 14:20:56 -08001133 EXPECT_TRUE(fake_prefs->SetInt64(kPrefsUpdateCheckCount, initial_value));
Amin Hassanie8153632020-10-27 15:11:28 -07001134 attempter_.Update({});
Amin Hassani90e9f192020-11-18 14:20:56 -08001135 EXPECT_TRUE(fake_prefs->Exists(kPrefsUpdateCheckCount));
1136 EXPECT_TRUE(fake_prefs->GetInt64(kPrefsUpdateCheckCount, &new_value));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001137 EXPECT_EQ(initial_value, new_value);
1138
Alex Deymo60ca1a72015-06-18 18:19:15 -07001139 ScheduleQuitMainLoop();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001140}
1141
Jay Srinivasan08fce042012-06-07 16:31:01 -07001142TEST_F(UpdateAttempterTest, NoScatteringDoneDuringManualUpdateTestStart) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001143 loop_.PostTask(
1144 FROM_HERE,
1145 base::Bind(
1146 &UpdateAttempterTest::NoScatteringDoneDuringManualUpdateTestStart,
1147 base::Unretained(this)));
Alex Deymo60ca1a72015-06-18 18:19:15 -07001148 loop_.Run();
Jay Srinivasan08fce042012-06-07 16:31:01 -07001149}
1150
1151void UpdateAttempterTest::NoScatteringDoneDuringManualUpdateTestStart() {
1152 // Tests that no scattering logic is enabled if the update check
1153 // is manually done (as opposed to a scheduled update check)
Ben Chan9abb7632014-08-07 00:10:53 -07001154 int64_t initial_value = 8;
Amin Hassani90e9f192020-11-18 14:20:56 -08001155 auto* fake_prefs = FakeSystemState::Get()->fake_prefs();
Amin Hassani538bd592020-11-04 20:46:08 -08001156 FakeSystemState::Get()->fake_hardware()->SetIsOOBEComplete(Time::UnixEpoch());
Jay Srinivasan08fce042012-06-07 16:31:01 -07001157
Adolfo Victoriad3a1e352018-07-16 11:40:47 -07001158 EXPECT_TRUE(
Amin Hassani90e9f192020-11-18 14:20:56 -08001159 fake_prefs->SetInt64(kPrefsWallClockScatteringWaitPeriod, initial_value));
1160 EXPECT_TRUE(fake_prefs->SetInt64(kPrefsUpdateCheckCount, initial_value));
Jay Srinivasan08fce042012-06-07 16:31:01 -07001161
1162 // make sure scatter_factor is non-zero as scattering is disabled
1163 // otherwise.
Ben Chan9abb7632014-08-07 00:10:53 -07001164 int64_t scatter_factor_in_seconds = 50;
Jay Srinivasan08fce042012-06-07 16:31:01 -07001165
Igor9fd76b62017-12-11 15:24:18 +01001166 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Jay Srinivasan08fce042012-06-07 16:31:01 -07001167 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
Amin Hassani538bd592020-11-04 20:46:08 -08001168 FakeSystemState::Get()->set_device_policy(device_policy.get());
Jay Srinivasan08fce042012-06-07 16:31:01 -07001169
1170 EXPECT_CALL(*device_policy, GetScatterFactorInSeconds(_))
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001171 .WillRepeatedly(
1172 DoAll(SetArgPointee<0>(scatter_factor_in_seconds), Return(true)));
Jay Srinivasan08fce042012-06-07 16:31:01 -07001173
Igor9fd76b62017-12-11 15:24:18 +01001174 attempter_.policy_provider_.reset(
1175 new policy::PolicyProvider(std::move(device_policy)));
1176
Gilad Arnoldb92f0df2013-01-10 16:32:45 -08001177 // Trigger an interactive check so we can test that scattering is disabled.
Amin Hassanie8153632020-10-27 15:11:28 -07001178 attempter_.Update({.interactive = true});
Jay Srinivasan08fce042012-06-07 16:31:01 -07001179 EXPECT_EQ(scatter_factor_in_seconds, attempter_.scatter_factor_.InSeconds());
1180
1181 // Make sure scattering is disabled for manual (i.e. user initiated) update
Jay Srinivasan21be0752012-07-25 15:44:56 -07001182 // checks and all artifacts are removed.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001183 EXPECT_FALSE(
1184 attempter_.omaha_request_params_->wall_clock_based_wait_enabled());
Amin Hassani90e9f192020-11-18 14:20:56 -08001185 EXPECT_FALSE(fake_prefs->Exists(kPrefsWallClockScatteringWaitPeriod));
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001186 EXPECT_EQ(0, attempter_.omaha_request_params_->waiting_period().InSeconds());
1187 EXPECT_FALSE(
1188 attempter_.omaha_request_params_->update_check_count_wait_enabled());
Amin Hassani90e9f192020-11-18 14:20:56 -08001189 EXPECT_FALSE(fake_prefs->Exists(kPrefsUpdateCheckCount));
Jay Srinivasan08fce042012-06-07 16:31:01 -07001190
Alex Deymo60ca1a72015-06-18 18:19:15 -07001191 ScheduleQuitMainLoop();
Jay Srinivasan08fce042012-06-07 16:31:01 -07001192}
1193
Amin Hassani90e9f192020-11-18 14:20:56 -08001194void UpdateAttempterTest::SetUpStagingTest(const StagingSchedule& schedule) {
Adolfo Victoria497044c2018-07-18 07:51:42 -07001195 int64_t initial_value = 8;
1196 EXPECT_TRUE(
Amin Hassani90e9f192020-11-18 14:20:56 -08001197 prefs_->SetInt64(kPrefsWallClockScatteringWaitPeriod, initial_value));
1198 EXPECT_TRUE(prefs_->SetInt64(kPrefsUpdateCheckCount, initial_value));
Adolfo Victoria497044c2018-07-18 07:51:42 -07001199 attempter_.scatter_factor_ = TimeDelta::FromSeconds(20);
1200
1201 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
1202 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
Amin Hassani538bd592020-11-04 20:46:08 -08001203 FakeSystemState::Get()->set_device_policy(device_policy.get());
Adolfo Victoria497044c2018-07-18 07:51:42 -07001204 EXPECT_CALL(*device_policy, GetDeviceUpdateStagingSchedule(_))
1205 .WillRepeatedly(DoAll(SetArgPointee<0>(schedule), Return(true)));
1206
1207 attempter_.policy_provider_.reset(
1208 new policy::PolicyProvider(std::move(device_policy)));
1209}
1210
1211TEST_F(UpdateAttempterTest, StagingSetsPrefsAndTurnsOffScattering) {
1212 loop_.PostTask(
1213 FROM_HERE,
1214 base::Bind(
1215 &UpdateAttempterTest::StagingSetsPrefsAndTurnsOffScatteringStart,
1216 base::Unretained(this)));
1217 loop_.Run();
1218}
1219
1220void UpdateAttempterTest::StagingSetsPrefsAndTurnsOffScatteringStart() {
1221 // Tests that staging sets its prefs properly and turns off scattering.
Amin Hassani538bd592020-11-04 20:46:08 -08001222 FakeSystemState::Get()->fake_hardware()->SetIsOOBEComplete(Time::UnixEpoch());
Amin Hassani90e9f192020-11-18 14:20:56 -08001223 SetUpStagingTest(kValidStagingSchedule);
Adolfo Victoria497044c2018-07-18 07:51:42 -07001224
Amin Hassanie8153632020-10-27 15:11:28 -07001225 attempter_.Update({});
Amin Hassani90e9f192020-11-18 14:20:56 -08001226 auto* fake_prefs = FakeSystemState::Get()->fake_prefs();
Adolfo Victoria497044c2018-07-18 07:51:42 -07001227 // Check that prefs have the correct values.
1228 int64_t update_count;
Amin Hassani90e9f192020-11-18 14:20:56 -08001229 EXPECT_TRUE(fake_prefs->GetInt64(kPrefsUpdateCheckCount, &update_count));
Adolfo Victoria497044c2018-07-18 07:51:42 -07001230 int64_t waiting_time_days;
Amin Hassani90e9f192020-11-18 14:20:56 -08001231 EXPECT_TRUE(fake_prefs->GetInt64(kPrefsWallClockStagingWaitPeriod,
1232 &waiting_time_days));
Adolfo Victoria497044c2018-07-18 07:51:42 -07001233 EXPECT_GT(waiting_time_days, 0);
1234 // Update count should have been decremented.
1235 EXPECT_EQ(7, update_count);
1236 // Check that Omaha parameters were updated correctly.
1237 EXPECT_TRUE(
1238 attempter_.omaha_request_params_->update_check_count_wait_enabled());
1239 EXPECT_TRUE(
1240 attempter_.omaha_request_params_->wall_clock_based_wait_enabled());
1241 EXPECT_EQ(waiting_time_days,
1242 attempter_.omaha_request_params_->waiting_period().InDays());
1243 // Check class variables.
1244 EXPECT_EQ(waiting_time_days, attempter_.staging_wait_time_.InDays());
1245 EXPECT_EQ(kValidStagingSchedule, attempter_.staging_schedule_);
1246 // Check that scattering is turned off
1247 EXPECT_EQ(0, attempter_.scatter_factor_.InSeconds());
Amin Hassani90e9f192020-11-18 14:20:56 -08001248 EXPECT_FALSE(fake_prefs->Exists(kPrefsWallClockScatteringWaitPeriod));
Adolfo Victoria497044c2018-07-18 07:51:42 -07001249
1250 ScheduleQuitMainLoop();
1251}
1252
1253void UpdateAttempterTest::CheckStagingOff() {
1254 // Check that all prefs were removed.
Amin Hassani90e9f192020-11-18 14:20:56 -08001255 EXPECT_FALSE(prefs_->Exists(kPrefsUpdateCheckCount));
1256 EXPECT_FALSE(prefs_->Exists(kPrefsWallClockScatteringWaitPeriod));
1257 EXPECT_FALSE(prefs_->Exists(kPrefsWallClockStagingWaitPeriod));
Adolfo Victoria497044c2018-07-18 07:51:42 -07001258 // Check that the Omaha parameters have the correct value.
1259 EXPECT_EQ(0, attempter_.omaha_request_params_->waiting_period().InDays());
1260 EXPECT_EQ(attempter_.omaha_request_params_->waiting_period(),
1261 attempter_.staging_wait_time_);
1262 EXPECT_FALSE(
1263 attempter_.omaha_request_params_->update_check_count_wait_enabled());
1264 EXPECT_FALSE(
1265 attempter_.omaha_request_params_->wall_clock_based_wait_enabled());
1266 // Check that scattering is turned off too.
1267 EXPECT_EQ(0, attempter_.scatter_factor_.InSeconds());
1268}
1269
1270TEST_F(UpdateAttempterTest, StagingOffIfInteractive) {
1271 loop_.PostTask(FROM_HERE,
1272 base::Bind(&UpdateAttempterTest::StagingOffIfInteractiveStart,
1273 base::Unretained(this)));
1274 loop_.Run();
1275}
1276
1277void UpdateAttempterTest::StagingOffIfInteractiveStart() {
1278 // Tests that staging is turned off when an interactive update is requested.
Amin Hassani538bd592020-11-04 20:46:08 -08001279 FakeSystemState::Get()->fake_hardware()->SetIsOOBEComplete(Time::UnixEpoch());
Amin Hassani90e9f192020-11-18 14:20:56 -08001280 SetUpStagingTest(kValidStagingSchedule);
Adolfo Victoria497044c2018-07-18 07:51:42 -07001281
Amin Hassanie8153632020-10-27 15:11:28 -07001282 attempter_.Update({.interactive = true});
Adolfo Victoria497044c2018-07-18 07:51:42 -07001283 CheckStagingOff();
1284
1285 ScheduleQuitMainLoop();
1286}
1287
1288TEST_F(UpdateAttempterTest, StagingOffIfOobe) {
1289 loop_.PostTask(FROM_HERE,
1290 base::Bind(&UpdateAttempterTest::StagingOffIfOobeStart,
1291 base::Unretained(this)));
1292 loop_.Run();
1293}
1294
1295void UpdateAttempterTest::StagingOffIfOobeStart() {
1296 // Tests that staging is turned off if OOBE hasn't been completed.
Amin Hassani538bd592020-11-04 20:46:08 -08001297 FakeSystemState::Get()->fake_hardware()->SetIsOOBEEnabled(true);
1298 FakeSystemState::Get()->fake_hardware()->UnsetIsOOBEComplete();
Amin Hassani90e9f192020-11-18 14:20:56 -08001299 SetUpStagingTest(kValidStagingSchedule);
Adolfo Victoria497044c2018-07-18 07:51:42 -07001300
Amin Hassanie8153632020-10-27 15:11:28 -07001301 attempter_.Update({.interactive = true});
Adolfo Victoria497044c2018-07-18 07:51:42 -07001302 CheckStagingOff();
1303
1304 ScheduleQuitMainLoop();
1305}
1306
David Zeuthen985b1122013-10-09 12:13:15 -07001307// Checks that we only report daily metrics at most every 24 hours.
1308TEST_F(UpdateAttempterTest, ReportDailyMetrics) {
Amin Hassani0468a762020-11-17 23:53:48 -08001309 auto* fake_clock = FakeSystemState::Get()->fake_clock();
David Zeuthen985b1122013-10-09 12:13:15 -07001310 Time epoch = Time::FromInternalValue(0);
Amin Hassani0468a762020-11-17 23:53:48 -08001311 fake_clock->SetWallclockTime(epoch);
David Zeuthen985b1122013-10-09 12:13:15 -07001312
1313 // If there is no kPrefsDailyMetricsLastReportedAt state variable,
1314 // we should report.
1315 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1316 // We should not report again if no time has passed.
1317 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1318
1319 // We should not report if only 10 hours has passed.
Amin Hassani0468a762020-11-17 23:53:48 -08001320 fake_clock->SetWallclockTime(epoch + TimeDelta::FromHours(10));
David Zeuthen985b1122013-10-09 12:13:15 -07001321 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1322
1323 // We should not report if only 24 hours - 1 sec has passed.
Amin Hassani0468a762020-11-17 23:53:48 -08001324 fake_clock->SetWallclockTime(epoch + TimeDelta::FromHours(24) -
1325 TimeDelta::FromSeconds(1));
David Zeuthen985b1122013-10-09 12:13:15 -07001326 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1327
1328 // We should report if 24 hours has passed.
Amin Hassani0468a762020-11-17 23:53:48 -08001329 fake_clock->SetWallclockTime(epoch + TimeDelta::FromHours(24));
David Zeuthen985b1122013-10-09 12:13:15 -07001330 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1331
1332 // But then we should not report again..
1333 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1334
1335 // .. until another 24 hours has passed
Amin Hassani0468a762020-11-17 23:53:48 -08001336 fake_clock->SetWallclockTime(epoch + TimeDelta::FromHours(47));
David Zeuthen985b1122013-10-09 12:13:15 -07001337 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
Amin Hassani0468a762020-11-17 23:53:48 -08001338 fake_clock->SetWallclockTime(epoch + TimeDelta::FromHours(48));
David Zeuthen985b1122013-10-09 12:13:15 -07001339 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1340 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1341
1342 // .. and another 24 hours
Amin Hassani0468a762020-11-17 23:53:48 -08001343 fake_clock->SetWallclockTime(epoch + TimeDelta::FromHours(71));
David Zeuthen985b1122013-10-09 12:13:15 -07001344 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
Amin Hassani0468a762020-11-17 23:53:48 -08001345 fake_clock->SetWallclockTime(epoch + TimeDelta::FromHours(72));
David Zeuthen985b1122013-10-09 12:13:15 -07001346 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1347 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1348
1349 // If the span between time of reporting and present time is
1350 // negative, we report. This is in order to reset the timestamp and
1351 // avoid an edge condition whereby a distant point in the future is
1352 // in the state variable resulting in us never ever reporting again.
Amin Hassani0468a762020-11-17 23:53:48 -08001353 fake_clock->SetWallclockTime(epoch + TimeDelta::FromHours(71));
David Zeuthen985b1122013-10-09 12:13:15 -07001354 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1355 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1356
1357 // In this case we should not update until the clock reads 71 + 24 = 95.
1358 // Check that.
Amin Hassani0468a762020-11-17 23:53:48 -08001359 fake_clock->SetWallclockTime(epoch + TimeDelta::FromHours(94));
David Zeuthen985b1122013-10-09 12:13:15 -07001360 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
Amin Hassani0468a762020-11-17 23:53:48 -08001361 fake_clock->SetWallclockTime(epoch + TimeDelta::FromHours(95));
David Zeuthen985b1122013-10-09 12:13:15 -07001362 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1363 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
David Zeuthen985b1122013-10-09 12:13:15 -07001364}
1365
David Zeuthen3c55abd2013-10-14 12:48:03 -07001366TEST_F(UpdateAttempterTest, BootTimeInUpdateMarkerFile) {
Amin Hassani0468a762020-11-17 23:53:48 -08001367 FakeSystemState::Get()->fake_clock()->SetBootTime(Time::FromTimeT(42));
Sen Jiangaeeb2e02016-06-09 15:00:16 -07001368 attempter_.Init();
David Zeuthen3c55abd2013-10-14 12:48:03 -07001369
1370 Time boot_time;
Sen Jiangaeeb2e02016-06-09 15:00:16 -07001371 EXPECT_FALSE(attempter_.GetBootTimeAtUpdate(&boot_time));
David Zeuthen3c55abd2013-10-14 12:48:03 -07001372
Sen Jiangaeeb2e02016-06-09 15:00:16 -07001373 attempter_.WriteUpdateCompletedMarker();
David Zeuthen3c55abd2013-10-14 12:48:03 -07001374
Sen Jiangaeeb2e02016-06-09 15:00:16 -07001375 EXPECT_TRUE(attempter_.GetBootTimeAtUpdate(&boot_time));
David Zeuthen3c55abd2013-10-14 12:48:03 -07001376 EXPECT_EQ(boot_time.ToTimeT(), 42);
1377}
1378
David Pursell02c18642014-11-06 11:26:11 -08001379TEST_F(UpdateAttempterTest, AnyUpdateSourceAllowedUnofficial) {
Amin Hassani538bd592020-11-04 20:46:08 -08001380 FakeSystemState::Get()->fake_hardware()->SetIsOfficialBuild(false);
David Pursell02c18642014-11-06 11:26:11 -08001381 EXPECT_TRUE(attempter_.IsAnyUpdateSourceAllowed());
1382}
1383
1384TEST_F(UpdateAttempterTest, AnyUpdateSourceAllowedOfficialDevmode) {
Amin Hassani538bd592020-11-04 20:46:08 -08001385 FakeSystemState::Get()->fake_hardware()->SetIsOfficialBuild(true);
1386 FakeSystemState::Get()->fake_hardware()->SetAreDevFeaturesEnabled(true);
David Pursell02c18642014-11-06 11:26:11 -08001387 EXPECT_TRUE(attempter_.IsAnyUpdateSourceAllowed());
1388}
1389
1390TEST_F(UpdateAttempterTest, AnyUpdateSourceDisallowedOfficialNormal) {
Amin Hassani538bd592020-11-04 20:46:08 -08001391 FakeSystemState::Get()->fake_hardware()->SetIsOfficialBuild(true);
1392 FakeSystemState::Get()->fake_hardware()->SetAreDevFeaturesEnabled(false);
David Pursell02c18642014-11-06 11:26:11 -08001393 EXPECT_FALSE(attempter_.IsAnyUpdateSourceAllowed());
1394}
1395
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001396// TODO(kimjae): Follow testing pattern with params for |CheckForInstall()|.
1397// When adding, remove older tests related to |CheckForInstall()|.
1398TEST_F(UpdateAttempterTest, CheckForInstallNotIdleFails) {
1399 for (const auto status : kNonIdleUpdateStatuses) {
1400 // GIVEN a non-idle status.
1401 attempter_.status_ = status;
Xiaochu Liu8ba486f2018-11-06 11:14:10 -08001402
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001403 EXPECT_FALSE(attempter_.CheckForInstall({}, ""));
1404 }
Xiaochu Liu8ba486f2018-11-06 11:14:10 -08001405}
1406
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001407TEST_F(UpdateAttempterTest, CheckForUpdateNotIdleFails) {
1408 for (const auto status : kNonIdleUpdateStatuses) {
1409 // GIVEN a non-idle status.
1410 cfu_params_.status = status;
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001411
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001412 // THEN |ScheduleUpdates()| should not be called.
1413 cfu_params_.should_schedule_updates_be_called = false;
1414 // THEN result should indicate failure.
1415 cfu_params_.expected_result = false;
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001416
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001417 TestCheckForUpdate();
1418 }
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001419}
1420
1421TEST_F(UpdateAttempterTest, CheckForUpdateOfficalBuildClearsSource) {
1422 // GIVEN a official build.
1423
1424 // THEN we except forced app version + forced omaha url to be cleared.
1425
1426 TestCheckForUpdate();
1427}
1428
1429TEST_F(UpdateAttempterTest, CheckForUpdateUnofficialBuildChangesSource) {
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001430 // GIVEN a nonofficial build with dev features enabled.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001431 cfu_params_.is_official_build = false;
1432 cfu_params_.are_dev_features_enabled = true;
1433
1434 // THEN the forced app version + forced omaha url changes based on input.
1435 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1436 cfu_params_.expected_forced_omaha_url = cfu_params_.omaha_url;
1437
1438 TestCheckForUpdate();
1439}
1440
1441TEST_F(UpdateAttempterTest, CheckForUpdateOfficialBuildScheduledAUTest) {
1442 // GIVEN a scheduled autest omaha url.
1443 cfu_params_.omaha_url = "autest-scheduled";
1444
1445 // THEN forced app version is cleared.
1446 // THEN forced omaha url changes to default constant.
1447 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1448
1449 TestCheckForUpdate();
1450}
1451
1452TEST_F(UpdateAttempterTest, CheckForUpdateUnofficialBuildScheduledAUTest) {
1453 // GIVEN a scheduled autest omaha url.
1454 cfu_params_.omaha_url = "autest-scheduled";
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001455 // GIVEN a nonofficial build with dev features enabled.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001456 cfu_params_.is_official_build = false;
1457 cfu_params_.are_dev_features_enabled = true;
1458
1459 // THEN forced app version changes based on input.
1460 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1461 // THEN forced omaha url changes to default constant.
1462 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1463
1464 TestCheckForUpdate();
1465}
1466
1467TEST_F(UpdateAttempterTest, CheckForUpdateOfficialBuildAUTest) {
1468 // GIVEN a autest omaha url.
1469 cfu_params_.omaha_url = "autest";
1470
1471 // THEN forced app version is cleared.
1472 // THEN forced omaha url changes to default constant.
1473 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1474
1475 TestCheckForUpdate();
1476}
1477
1478TEST_F(UpdateAttempterTest, CheckForUpdateUnofficialBuildAUTest) {
1479 // GIVEN a autest omha url.
1480 cfu_params_.omaha_url = "autest";
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001481 // GIVEN a nonofficial build with dev features enabled.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001482 cfu_params_.is_official_build = false;
1483 cfu_params_.are_dev_features_enabled = true;
1484
1485 // THEN forced app version changes based on input.
1486 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1487 // THEN forced omaha url changes to default constant.
1488 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1489
1490 TestCheckForUpdate();
1491}
1492
1493TEST_F(UpdateAttempterTest,
1494 CheckForUpdateNonInteractiveOfficialBuildScheduledAUTest) {
1495 // GIVEN a scheduled autest omaha url.
1496 cfu_params_.omaha_url = "autest-scheduled";
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001497 // GIVEN a noninteractive update.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001498 cfu_params_.flags = UpdateAttemptFlags::kFlagNonInteractive;
1499
1500 // THEN forced app version is cleared.
1501 // THEN forced omaha url changes to default constant.
1502 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1503
1504 TestCheckForUpdate();
1505}
1506
1507TEST_F(UpdateAttempterTest,
1508 CheckForUpdateNonInteractiveUnofficialBuildScheduledAUTest) {
1509 // GIVEN a scheduled autest omaha url.
1510 cfu_params_.omaha_url = "autest-scheduled";
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001511 // GIVEN a noninteractive update.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001512 cfu_params_.flags = UpdateAttemptFlags::kFlagNonInteractive;
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001513 // GIVEN a nonofficial build with dev features enabled.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001514 cfu_params_.is_official_build = false;
1515 cfu_params_.are_dev_features_enabled = true;
1516
1517 // THEN forced app version changes based on input.
1518 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1519 // THEN forced omaha url changes to default constant.
1520 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1521
1522 TestCheckForUpdate();
1523}
1524
1525TEST_F(UpdateAttempterTest, CheckForUpdateNonInteractiveOfficialBuildAUTest) {
1526 // GIVEN a autest omaha url.
1527 cfu_params_.omaha_url = "autest";
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001528 // GIVEN a noninteractive update.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001529 cfu_params_.flags = UpdateAttemptFlags::kFlagNonInteractive;
1530
1531 // THEN forced app version is cleared.
1532 // THEN forced omaha url changes to default constant.
1533 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1534
1535 TestCheckForUpdate();
1536}
1537
1538TEST_F(UpdateAttempterTest, CheckForUpdateNonInteractiveUnofficialBuildAUTest) {
1539 // GIVEN a autest omaha url.
1540 cfu_params_.omaha_url = "autest";
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001541 // GIVEN a noninteractive update.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001542 cfu_params_.flags = UpdateAttemptFlags::kFlagNonInteractive;
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001543 // GIVEN a nonofficial build with dev features enabled.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001544 cfu_params_.is_official_build = false;
1545 cfu_params_.are_dev_features_enabled = true;
1546
1547 // THEN forced app version changes based on input.
1548 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1549 // THEN forced omaha url changes to default constant.
1550 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1551
1552 TestCheckForUpdate();
David Pursell02c18642014-11-06 11:26:11 -08001553}
1554
Jae Hoon Kim2b73ac22019-07-02 11:17:24 -07001555TEST_F(UpdateAttempterTest, CheckForUpdateMissingForcedCallback1) {
1556 // GIVEN a official build.
1557 // GIVEN forced callback is not set.
1558 attempter_.set_forced_update_pending_callback(nullptr);
1559
1560 // THEN we except forced app version + forced omaha url to be cleared.
1561 // THEN |ScheduleUpdates()| should not be called.
1562 cfu_params_.should_schedule_updates_be_called = false;
1563
1564 TestCheckForUpdate();
1565}
1566
1567TEST_F(UpdateAttempterTest, CheckForUpdateMissingForcedCallback2) {
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001568 // GIVEN a nonofficial build with dev features enabled.
Jae Hoon Kim2b73ac22019-07-02 11:17:24 -07001569 cfu_params_.is_official_build = false;
1570 cfu_params_.are_dev_features_enabled = true;
1571 // GIVEN forced callback is not set.
1572 attempter_.set_forced_update_pending_callback(nullptr);
1573
1574 // THEN the forced app version + forced omaha url changes based on input.
1575 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1576 cfu_params_.expected_forced_omaha_url = cfu_params_.omaha_url;
1577 // THEN |ScheduleUpdates()| should not be called.
1578 cfu_params_.should_schedule_updates_be_called = false;
1579
1580 TestCheckForUpdate();
1581}
1582
Xiaochu Liu88d90382018-08-29 16:09:11 -07001583TEST_F(UpdateAttempterTest, CheckForInstallTest) {
Amin Hassani538bd592020-11-04 20:46:08 -08001584 FakeSystemState::Get()->fake_hardware()->SetIsOfficialBuild(true);
1585 FakeSystemState::Get()->fake_hardware()->SetAreDevFeaturesEnabled(false);
Xiaochu Liu88d90382018-08-29 16:09:11 -07001586 attempter_.CheckForInstall({}, "autest");
1587 EXPECT_EQ(constants::kOmahaDefaultAUTestURL, attempter_.forced_omaha_url());
1588
1589 attempter_.CheckForInstall({}, "autest-scheduled");
1590 EXPECT_EQ(constants::kOmahaDefaultAUTestURL, attempter_.forced_omaha_url());
1591
1592 attempter_.CheckForInstall({}, "http://omaha.phishing");
1593 EXPECT_EQ("", attempter_.forced_omaha_url());
1594}
1595
Colin Howesac170d92018-11-20 16:29:28 -08001596TEST_F(UpdateAttempterTest, InstallSetsStatusIdle) {
1597 attempter_.CheckForInstall({}, "http://foo.bar");
1598 attempter_.status_ = UpdateStatus::DOWNLOADING;
1599 EXPECT_TRUE(attempter_.is_install_);
1600 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1601 UpdateEngineStatus status;
1602 attempter_.GetStatus(&status);
1603 // Should set status to idle after an install operation.
1604 EXPECT_EQ(UpdateStatus::IDLE, status.status);
1605}
1606
Colin Howes978c1082018-12-03 11:46:12 -08001607TEST_F(UpdateAttempterTest, RollbackAfterInstall) {
1608 attempter_.is_install_ = true;
1609 attempter_.Rollback(false);
1610 EXPECT_FALSE(attempter_.is_install_);
1611}
1612
1613TEST_F(UpdateAttempterTest, UpdateAfterInstall) {
1614 attempter_.is_install_ = true;
1615 attempter_.CheckForUpdate("", "", UpdateAttemptFlags::kNone);
1616 EXPECT_FALSE(attempter_.is_install_);
1617}
1618
Xiyuan Xiac0e8f9a2017-02-22 13:19:35 -08001619TEST_F(UpdateAttempterTest, TargetVersionPrefixSetAndReset) {
Amin Hassanie8153632020-10-27 15:11:28 -07001620 UpdateCheckParams params;
1621 attempter_.CalculateUpdateParams({.target_version_prefix = "1234"});
Xiyuan Xiac0e8f9a2017-02-22 13:19:35 -08001622 EXPECT_EQ("1234",
Amin Hassani538bd592020-11-04 20:46:08 -08001623 FakeSystemState::Get()->request_params()->target_version_prefix());
Xiyuan Xiac0e8f9a2017-02-22 13:19:35 -08001624
Amin Hassanie8153632020-10-27 15:11:28 -07001625 attempter_.CalculateUpdateParams({});
Amin Hassani538bd592020-11-04 20:46:08 -08001626 EXPECT_TRUE(FakeSystemState::Get()
1627 ->request_params()
1628 ->target_version_prefix()
1629 .empty());
Xiyuan Xiac0e8f9a2017-02-22 13:19:35 -08001630}
1631
Amin Hassani37b67232020-08-13 09:29:48 -07001632TEST_F(UpdateAttempterTest, TargetChannelHintSetAndReset) {
Amin Hassanie8153632020-10-27 15:11:28 -07001633 attempter_.CalculateUpdateParams({.lts_tag = "hint"});
Amin Hassani538bd592020-11-04 20:46:08 -08001634 EXPECT_EQ("hint", FakeSystemState::Get()->request_params()->lts_tag());
Amin Hassani37b67232020-08-13 09:29:48 -07001635
Amin Hassanie8153632020-10-27 15:11:28 -07001636 attempter_.CalculateUpdateParams({});
Amin Hassani538bd592020-11-04 20:46:08 -08001637 EXPECT_TRUE(FakeSystemState::Get()->request_params()->lts_tag().empty());
Amin Hassani37b67232020-08-13 09:29:48 -07001638}
1639
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001640TEST_F(UpdateAttempterTest, RollbackAllowedSetAndReset) {
Amin Hassanie8153632020-10-27 15:11:28 -07001641 attempter_.CalculateUpdateParams({
1642 .target_version_prefix = "1234",
1643 .rollback_allowed = true,
1644 .rollback_allowed_milestones = 4,
1645 });
Amin Hassani538bd592020-11-04 20:46:08 -08001646 EXPECT_TRUE(FakeSystemState::Get()->request_params()->rollback_allowed());
1647 EXPECT_EQ(
1648 4,
1649 FakeSystemState::Get()->request_params()->rollback_allowed_milestones());
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001650
Amin Hassanie8153632020-10-27 15:11:28 -07001651 attempter_.CalculateUpdateParams({
1652 .target_version_prefix = "1234",
1653 .rollback_allowed_milestones = 4,
1654 });
Amin Hassani538bd592020-11-04 20:46:08 -08001655 EXPECT_FALSE(FakeSystemState::Get()->request_params()->rollback_allowed());
1656 EXPECT_EQ(
1657 4,
1658 FakeSystemState::Get()->request_params()->rollback_allowed_milestones());
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001659}
1660
Miriam Polzeraff72002020-08-27 08:20:39 +02001661TEST_F(UpdateAttempterTest, ChannelDowngradeNoRollback) {
1662 base::ScopedTempDir tempdir;
1663 ASSERT_TRUE(tempdir.CreateUniqueTempDir());
Amin Hassani538bd592020-11-04 20:46:08 -08001664 FakeSystemState::Get()->request_params()->set_root(tempdir.GetPath().value());
Amin Hassanie8153632020-10-27 15:11:28 -07001665 attempter_.CalculateUpdateParams({
1666 .target_channel = "stable-channel",
1667 });
Amin Hassani538bd592020-11-04 20:46:08 -08001668 EXPECT_FALSE(
1669 FakeSystemState::Get()->request_params()->is_powerwash_allowed());
Miriam Polzeraff72002020-08-27 08:20:39 +02001670}
1671
1672TEST_F(UpdateAttempterTest, ChannelDowngradeRollback) {
1673 base::ScopedTempDir tempdir;
1674 ASSERT_TRUE(tempdir.CreateUniqueTempDir());
Amin Hassani538bd592020-11-04 20:46:08 -08001675 FakeSystemState::Get()->request_params()->set_root(tempdir.GetPath().value());
Amin Hassanie8153632020-10-27 15:11:28 -07001676 attempter_.CalculateUpdateParams({
1677 .rollback_on_channel_downgrade = true,
1678 .target_channel = "stable-channel",
1679 });
Amin Hassani538bd592020-11-04 20:46:08 -08001680 EXPECT_TRUE(FakeSystemState::Get()->request_params()->is_powerwash_allowed());
Miriam Polzeraff72002020-08-27 08:20:39 +02001681}
1682
Aaron Wood23bd3392017-10-06 14:48:25 -07001683TEST_F(UpdateAttempterTest, UpdateDeferredByPolicyTest) {
1684 // Construct an OmahaResponseHandlerAction that has processed an InstallPlan,
1685 // but the update is being deferred by the Policy.
Amin Hassani538bd592020-11-04 20:46:08 -08001686 OmahaResponseHandlerAction response_action;
Amin Hassani68512d42018-07-31 23:52:33 -07001687 response_action.install_plan_.version = "a.b.c.d";
Amin Hassani68512d42018-07-31 23:52:33 -07001688 response_action.install_plan_.payloads.push_back(
Aaron Wood23bd3392017-10-06 14:48:25 -07001689 {.size = 1234ULL, .type = InstallPayloadType::kFull});
Aaron Wood23bd3392017-10-06 14:48:25 -07001690 // Inform the UpdateAttempter that the OmahaResponseHandlerAction has
1691 // completed, with the deferred-update error code.
1692 attempter_.ActionCompleted(
Amin Hassani68512d42018-07-31 23:52:33 -07001693 nullptr, &response_action, ErrorCode::kOmahaUpdateDeferredPerPolicy);
Aaron Wood23bd3392017-10-06 14:48:25 -07001694 {
1695 UpdateEngineStatus status;
1696 attempter_.GetStatus(&status);
1697 EXPECT_EQ(UpdateStatus::UPDATE_AVAILABLE, status.status);
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001698 EXPECT_TRUE(attempter_.install_plan_);
1699 EXPECT_EQ(attempter_.install_plan_->version, status.new_version);
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001700 EXPECT_EQ(attempter_.install_plan_->payloads[0].size,
Aaron Wood23bd3392017-10-06 14:48:25 -07001701 status.new_size_bytes);
1702 }
1703 // An "error" event should have been created to tell Omaha that the update is
1704 // being deferred.
1705 EXPECT_TRUE(nullptr != attempter_.error_event_);
1706 EXPECT_EQ(OmahaEvent::kTypeUpdateComplete, attempter_.error_event_->type);
1707 EXPECT_EQ(OmahaEvent::kResultUpdateDeferred, attempter_.error_event_->result);
1708 ErrorCode expected_code = static_cast<ErrorCode>(
1709 static_cast<int>(ErrorCode::kOmahaUpdateDeferredPerPolicy) |
1710 static_cast<int>(ErrorCode::kTestOmahaUrlFlag));
1711 EXPECT_EQ(expected_code, attempter_.error_event_->error_code);
1712 // End the processing
1713 attempter_.ProcessingDone(nullptr, ErrorCode::kOmahaUpdateDeferredPerPolicy);
1714 // Validate the state of the attempter.
1715 {
1716 UpdateEngineStatus status;
1717 attempter_.GetStatus(&status);
1718 EXPECT_EQ(UpdateStatus::REPORTING_ERROR_EVENT, status.status);
Amin Hassani68512d42018-07-31 23:52:33 -07001719 EXPECT_EQ(response_action.install_plan_.version, status.new_version);
Amin Hassani68512d42018-07-31 23:52:33 -07001720 EXPECT_EQ(response_action.install_plan_.payloads[0].size,
Aaron Wood23bd3392017-10-06 14:48:25 -07001721 status.new_size_bytes);
1722 }
1723}
1724
1725TEST_F(UpdateAttempterTest, UpdateIsNotRunningWhenUpdateAvailable) {
Jae Hoon Kim75daa382019-07-02 11:17:24 -07001726 // Default construction for |waiting_for_scheduled_check_| is false.
Jae Hoon Kimba2fdce2019-07-11 13:18:58 -07001727 EXPECT_FALSE(attempter_.IsBusyOrUpdateScheduled());
Aaron Wood23bd3392017-10-06 14:48:25 -07001728 // Verify in-progress update with UPDATE_AVAILABLE is running
1729 attempter_.status_ = UpdateStatus::UPDATE_AVAILABLE;
Jae Hoon Kimba2fdce2019-07-11 13:18:58 -07001730 EXPECT_TRUE(attempter_.IsBusyOrUpdateScheduled());
Aaron Wood23bd3392017-10-06 14:48:25 -07001731}
1732
Aaron Woodbf5a2522017-10-04 10:58:36 -07001733TEST_F(UpdateAttempterTest, UpdateAttemptFlagsCachedAtUpdateStart) {
1734 attempter_.SetUpdateAttemptFlags(UpdateAttemptFlags::kFlagRestrictDownload);
1735
1736 UpdateCheckParams params = {.updates_enabled = true};
1737 attempter_.OnUpdateScheduled(EvalStatus::kSucceeded, params);
1738
1739 EXPECT_EQ(UpdateAttemptFlags::kFlagRestrictDownload,
1740 attempter_.GetCurrentUpdateAttemptFlags());
1741}
1742
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001743TEST_F(UpdateAttempterTest, RollbackNotAllowed) {
1744 UpdateCheckParams params = {.updates_enabled = true,
1745 .rollback_allowed = false};
1746 attempter_.OnUpdateScheduled(EvalStatus::kSucceeded, params);
Amin Hassani538bd592020-11-04 20:46:08 -08001747 EXPECT_FALSE(FakeSystemState::Get()->request_params()->rollback_allowed());
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001748}
1749
1750TEST_F(UpdateAttempterTest, RollbackAllowed) {
1751 UpdateCheckParams params = {.updates_enabled = true,
1752 .rollback_allowed = true};
1753 attempter_.OnUpdateScheduled(EvalStatus::kSucceeded, params);
Amin Hassani538bd592020-11-04 20:46:08 -08001754 EXPECT_TRUE(FakeSystemState::Get()->request_params()->rollback_allowed());
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001755}
1756
Aaron Wood081c0232017-10-19 17:14:58 -07001757TEST_F(UpdateAttempterTest, InteractiveUpdateUsesPassedRestrictions) {
1758 attempter_.SetUpdateAttemptFlags(UpdateAttemptFlags::kFlagRestrictDownload);
1759
1760 attempter_.CheckForUpdate("", "", UpdateAttemptFlags::kNone);
1761 EXPECT_EQ(UpdateAttemptFlags::kNone,
1762 attempter_.GetCurrentUpdateAttemptFlags());
1763}
1764
1765TEST_F(UpdateAttempterTest, NonInteractiveUpdateUsesSetRestrictions) {
1766 attempter_.SetUpdateAttemptFlags(UpdateAttemptFlags::kNone);
1767
1768 // This tests that when CheckForUpdate() is called with the non-interactive
1769 // flag set, that it doesn't change the current UpdateAttemptFlags.
1770 attempter_.CheckForUpdate("",
1771 "",
1772 UpdateAttemptFlags::kFlagNonInteractive |
1773 UpdateAttemptFlags::kFlagRestrictDownload);
1774 EXPECT_EQ(UpdateAttemptFlags::kNone,
1775 attempter_.GetCurrentUpdateAttemptFlags());
1776}
1777
Marton Hunyadye58bddb2018-04-10 20:27:26 +02001778void UpdateAttempterTest::ResetRollbackHappenedStart(bool is_consumer,
1779 bool is_policy_loaded,
1780 bool expected_reset) {
Amin Hassani538bd592020-11-04 20:46:08 -08001781 EXPECT_CALL(*FakeSystemState::Get()->mock_payload_state(),
1782 GetRollbackHappened())
Marton Hunyadye58bddb2018-04-10 20:27:26 +02001783 .WillRepeatedly(Return(true));
1784 auto mock_policy_provider =
1785 std::make_unique<NiceMock<policy::MockPolicyProvider>>();
1786 EXPECT_CALL(*mock_policy_provider, IsConsumerDevice())
1787 .WillRepeatedly(Return(is_consumer));
1788 EXPECT_CALL(*mock_policy_provider, device_policy_is_loaded())
1789 .WillRepeatedly(Return(is_policy_loaded));
1790 const policy::MockDevicePolicy device_policy;
1791 EXPECT_CALL(*mock_policy_provider, GetDevicePolicy())
1792 .WillRepeatedly(ReturnRef(device_policy));
Amin Hassani538bd592020-11-04 20:46:08 -08001793 EXPECT_CALL(*FakeSystemState::Get()->mock_payload_state(),
Marton Hunyadye58bddb2018-04-10 20:27:26 +02001794 SetRollbackHappened(false))
1795 .Times(expected_reset ? 1 : 0);
1796 attempter_.policy_provider_ = std::move(mock_policy_provider);
Amin Hassanie8153632020-10-27 15:11:28 -07001797 attempter_.Update({});
Marton Hunyadye58bddb2018-04-10 20:27:26 +02001798 ScheduleQuitMainLoop();
1799}
1800
1801TEST_F(UpdateAttempterTest, ResetRollbackHappenedOobe) {
1802 loop_.PostTask(FROM_HERE,
1803 base::Bind(&UpdateAttempterTest::ResetRollbackHappenedStart,
1804 base::Unretained(this),
1805 /*is_consumer=*/false,
1806 /*is_policy_loaded=*/false,
1807 /*expected_reset=*/false));
1808 loop_.Run();
1809}
1810
1811TEST_F(UpdateAttempterTest, ResetRollbackHappenedConsumer) {
1812 loop_.PostTask(FROM_HERE,
1813 base::Bind(&UpdateAttempterTest::ResetRollbackHappenedStart,
1814 base::Unretained(this),
1815 /*is_consumer=*/true,
1816 /*is_policy_loaded=*/false,
1817 /*expected_reset=*/true));
1818 loop_.Run();
1819}
1820
1821TEST_F(UpdateAttempterTest, ResetRollbackHappenedEnterprise) {
1822 loop_.PostTask(FROM_HERE,
1823 base::Bind(&UpdateAttempterTest::ResetRollbackHappenedStart,
1824 base::Unretained(this),
1825 /*is_consumer=*/false,
1826 /*is_policy_loaded=*/true,
1827 /*expected_reset=*/true));
1828 loop_.Run();
1829}
1830
Marton Hunyady199152d2018-05-07 19:08:48 +02001831TEST_F(UpdateAttempterTest, SetRollbackHappenedRollback) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001832 attempter_.install_plan_.reset(new InstallPlan);
1833 attempter_.install_plan_->is_rollback = true;
Marton Hunyady199152d2018-05-07 19:08:48 +02001834
Amin Hassani538bd592020-11-04 20:46:08 -08001835 EXPECT_CALL(*FakeSystemState::Get()->mock_payload_state(),
Marton Hunyady199152d2018-05-07 19:08:48 +02001836 SetRollbackHappened(true))
1837 .Times(1);
1838 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1839}
1840
1841TEST_F(UpdateAttempterTest, SetRollbackHappenedNotRollback) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001842 attempter_.install_plan_.reset(new InstallPlan);
1843 attempter_.install_plan_->is_rollback = false;
Marton Hunyady199152d2018-05-07 19:08:48 +02001844
Amin Hassani538bd592020-11-04 20:46:08 -08001845 EXPECT_CALL(*FakeSystemState::Get()->mock_payload_state(),
Marton Hunyady199152d2018-05-07 19:08:48 +02001846 SetRollbackHappened(true))
1847 .Times(0);
1848 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1849}
1850
Marton Hunyadya0302682018-05-16 18:52:13 +02001851TEST_F(UpdateAttempterTest, RollbackMetricsRollbackSuccess) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001852 attempter_.install_plan_.reset(new InstallPlan);
1853 attempter_.install_plan_->is_rollback = true;
1854 attempter_.install_plan_->version = kRollbackVersion;
Marton Hunyadya0302682018-05-16 18:52:13 +02001855
Amin Hassani538bd592020-11-04 20:46:08 -08001856 EXPECT_CALL(*FakeSystemState::Get()->mock_metrics_reporter(),
Marton Hunyadya0302682018-05-16 18:52:13 +02001857 ReportEnterpriseRollbackMetrics(true, kRollbackVersion))
1858 .Times(1);
1859 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1860}
1861
1862TEST_F(UpdateAttempterTest, RollbackMetricsNotRollbackSuccess) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001863 attempter_.install_plan_.reset(new InstallPlan);
1864 attempter_.install_plan_->is_rollback = false;
1865 attempter_.install_plan_->version = kRollbackVersion;
Marton Hunyadya0302682018-05-16 18:52:13 +02001866
Amin Hassani538bd592020-11-04 20:46:08 -08001867 EXPECT_CALL(*FakeSystemState::Get()->mock_metrics_reporter(),
Marton Hunyadya0302682018-05-16 18:52:13 +02001868 ReportEnterpriseRollbackMetrics(_, _))
1869 .Times(0);
1870 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1871}
1872
1873TEST_F(UpdateAttempterTest, RollbackMetricsRollbackFailure) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001874 attempter_.install_plan_.reset(new InstallPlan);
1875 attempter_.install_plan_->is_rollback = true;
1876 attempter_.install_plan_->version = kRollbackVersion;
Marton Hunyadya0302682018-05-16 18:52:13 +02001877
Amin Hassani538bd592020-11-04 20:46:08 -08001878 EXPECT_CALL(*FakeSystemState::Get()->mock_metrics_reporter(),
Marton Hunyadya0302682018-05-16 18:52:13 +02001879 ReportEnterpriseRollbackMetrics(false, kRollbackVersion))
1880 .Times(1);
1881 MockAction action;
1882 attempter_.CreatePendingErrorEvent(&action, ErrorCode::kRollbackNotPossible);
1883 attempter_.ProcessingDone(nullptr, ErrorCode::kRollbackNotPossible);
1884}
1885
1886TEST_F(UpdateAttempterTest, RollbackMetricsNotRollbackFailure) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001887 attempter_.install_plan_.reset(new InstallPlan);
1888 attempter_.install_plan_->is_rollback = false;
1889 attempter_.install_plan_->version = kRollbackVersion;
Marton Hunyadya0302682018-05-16 18:52:13 +02001890
Amin Hassani538bd592020-11-04 20:46:08 -08001891 EXPECT_CALL(*FakeSystemState::Get()->mock_metrics_reporter(),
Marton Hunyadya0302682018-05-16 18:52:13 +02001892 ReportEnterpriseRollbackMetrics(_, _))
1893 .Times(0);
1894 MockAction action;
1895 attempter_.CreatePendingErrorEvent(&action, ErrorCode::kRollbackNotPossible);
1896 attempter_.ProcessingDone(nullptr, ErrorCode::kRollbackNotPossible);
1897}
1898
May Lippert60aa3ca2018-08-15 16:55:29 -07001899TEST_F(UpdateAttempterTest, TimeToUpdateAppliedMetricFailure) {
Amin Hassani538bd592020-11-04 20:46:08 -08001900 EXPECT_CALL(*FakeSystemState::Get()->mock_metrics_reporter(),
May Lippert60aa3ca2018-08-15 16:55:29 -07001901 ReportEnterpriseUpdateSeenToDownloadDays(_, _))
1902 .Times(0);
1903 attempter_.ProcessingDone(nullptr, ErrorCode::kOmahaUpdateDeferredPerPolicy);
1904}
1905
1906TEST_F(UpdateAttempterTest, TimeToUpdateAppliedOnNonEnterprise) {
1907 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Amin Hassani538bd592020-11-04 20:46:08 -08001908 FakeSystemState::Get()->set_device_policy(device_policy.get());
May Lippert60aa3ca2018-08-15 16:55:29 -07001909 // Make device policy return that this is not enterprise enrolled
1910 EXPECT_CALL(*device_policy, IsEnterpriseEnrolled()).WillOnce(Return(false));
1911
1912 // Ensure that the metric is not recorded.
Amin Hassani538bd592020-11-04 20:46:08 -08001913 EXPECT_CALL(*FakeSystemState::Get()->mock_metrics_reporter(),
May Lippert60aa3ca2018-08-15 16:55:29 -07001914 ReportEnterpriseUpdateSeenToDownloadDays(_, _))
1915 .Times(0);
1916 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1917}
1918
1919TEST_F(UpdateAttempterTest,
1920 TimeToUpdateAppliedWithTimeRestrictionMetricSuccess) {
1921 constexpr int kDaysToUpdate = 15;
1922 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Amin Hassani538bd592020-11-04 20:46:08 -08001923 FakeSystemState::Get()->set_device_policy(device_policy.get());
May Lippert60aa3ca2018-08-15 16:55:29 -07001924 // Make device policy return that this is enterprise enrolled
1925 EXPECT_CALL(*device_policy, IsEnterpriseEnrolled()).WillOnce(Return(true));
1926 // Pretend that there's a time restriction policy in place
1927 EXPECT_CALL(*device_policy, GetDisallowedTimeIntervals(_))
1928 .WillOnce(Return(true));
1929
May Lippert60aa3ca2018-08-15 16:55:29 -07001930 Time update_first_seen_at = Time::Now();
Amin Hassani90e9f192020-11-18 14:20:56 -08001931 FakeSystemState::Get()->fake_prefs()->SetInt64(
1932 kPrefsUpdateFirstSeenAt, update_first_seen_at.ToInternalValue());
May Lippert60aa3ca2018-08-15 16:55:29 -07001933
May Lippert60aa3ca2018-08-15 16:55:29 -07001934 Time update_finished_at =
1935 update_first_seen_at + TimeDelta::FromDays(kDaysToUpdate);
Amin Hassani0468a762020-11-17 23:53:48 -08001936 FakeSystemState::Get()->fake_clock()->SetWallclockTime(update_finished_at);
May Lippert60aa3ca2018-08-15 16:55:29 -07001937
Amin Hassani538bd592020-11-04 20:46:08 -08001938 EXPECT_CALL(*FakeSystemState::Get()->mock_metrics_reporter(),
May Lippert60aa3ca2018-08-15 16:55:29 -07001939 ReportEnterpriseUpdateSeenToDownloadDays(true, kDaysToUpdate))
1940 .Times(1);
1941 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1942}
1943
1944TEST_F(UpdateAttempterTest,
1945 TimeToUpdateAppliedWithoutTimeRestrictionMetricSuccess) {
1946 constexpr int kDaysToUpdate = 15;
1947 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Amin Hassani538bd592020-11-04 20:46:08 -08001948 FakeSystemState::Get()->set_device_policy(device_policy.get());
May Lippert60aa3ca2018-08-15 16:55:29 -07001949 // Make device policy return that this is enterprise enrolled
1950 EXPECT_CALL(*device_policy, IsEnterpriseEnrolled()).WillOnce(Return(true));
1951 // Pretend that there's no time restriction policy in place
1952 EXPECT_CALL(*device_policy, GetDisallowedTimeIntervals(_))
1953 .WillOnce(Return(false));
1954
May Lippert60aa3ca2018-08-15 16:55:29 -07001955 Time update_first_seen_at = Time::Now();
Amin Hassani90e9f192020-11-18 14:20:56 -08001956 FakeSystemState::Get()->fake_prefs()->SetInt64(
1957 kPrefsUpdateFirstSeenAt, update_first_seen_at.ToInternalValue());
May Lippert60aa3ca2018-08-15 16:55:29 -07001958
May Lippert60aa3ca2018-08-15 16:55:29 -07001959 Time update_finished_at =
1960 update_first_seen_at + TimeDelta::FromDays(kDaysToUpdate);
Amin Hassani0468a762020-11-17 23:53:48 -08001961 FakeSystemState::Get()->fake_clock()->SetWallclockTime(update_finished_at);
May Lippert60aa3ca2018-08-15 16:55:29 -07001962
Amin Hassani538bd592020-11-04 20:46:08 -08001963 EXPECT_CALL(*FakeSystemState::Get()->mock_metrics_reporter(),
May Lippert60aa3ca2018-08-15 16:55:29 -07001964 ReportEnterpriseUpdateSeenToDownloadDays(false, kDaysToUpdate))
1965 .Times(1);
1966 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1967}
1968
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07001969TEST_F(UpdateAttempterTest, ProcessingDoneUpdated) {
1970 // GIVEN an update finished.
1971
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07001972 // THEN update_engine should call update completion.
1973 pd_params_.should_update_completed_be_called = true;
1974 // THEN need reboot since update applied.
1975 pd_params_.expected_exit_status = UpdateStatus::UPDATED_NEED_REBOOT;
1976 // THEN install indication should be false.
1977
1978 TestProcessingDone();
1979}
1980
1981TEST_F(UpdateAttempterTest, ProcessingDoneUpdatedDlcFilter) {
1982 // GIVEN an update finished.
1983 // GIVEN DLC |AppParams| list.
1984 auto dlc_1 = "dlc_1", dlc_2 = "dlc_2";
1985 pd_params_.dlc_apps_params = {{dlc_1, {.name = dlc_1, .updated = false}},
1986 {dlc_2, {.name = dlc_2}}};
1987
1988 // THEN update_engine should call update completion.
1989 pd_params_.should_update_completed_be_called = true;
1990 pd_params_.args_to_update_completed = {dlc_2};
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07001991 // THEN need reboot since update applied.
1992 pd_params_.expected_exit_status = UpdateStatus::UPDATED_NEED_REBOOT;
1993 // THEN install indication should be false.
1994
1995 TestProcessingDone();
1996}
1997
1998TEST_F(UpdateAttempterTest, ProcessingDoneInstalled) {
1999 // GIVEN an install finished.
2000 pd_params_.is_install = true;
2001
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002002 // THEN update_engine should call install completion.
2003 pd_params_.should_install_completed_be_called = true;
2004 // THEN go idle.
2005 // THEN install indication should be false.
2006
2007 TestProcessingDone();
2008}
2009
2010TEST_F(UpdateAttempterTest, ProcessingDoneInstalledDlcFilter) {
2011 // GIVEN an install finished.
2012 pd_params_.is_install = true;
2013 // GIVEN DLC |AppParams| list.
2014 auto dlc_1 = "dlc_1", dlc_2 = "dlc_2";
2015 pd_params_.dlc_apps_params = {{dlc_1, {.name = dlc_1, .updated = false}},
2016 {dlc_2, {.name = dlc_2}}};
2017
2018 // THEN update_engine should call install completion.
2019 pd_params_.should_install_completed_be_called = true;
2020 pd_params_.args_to_install_completed = {dlc_2};
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002021 // THEN go idle.
2022 // THEN install indication should be false.
2023
2024 TestProcessingDone();
2025}
2026
2027TEST_F(UpdateAttempterTest, ProcessingDoneInstallReportingError) {
2028 // GIVEN an install finished.
2029 pd_params_.is_install = true;
2030 // GIVEN a reporting error occurred.
2031 pd_params_.status = UpdateStatus::REPORTING_ERROR_EVENT;
2032
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002033 // THEN update_engine should not call install completion.
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002034 // THEN go idle.
2035 // THEN install indication should be false.
2036
2037 TestProcessingDone();
2038}
2039
2040TEST_F(UpdateAttempterTest, ProcessingDoneNoUpdate) {
2041 // GIVEN an update finished.
2042 // GIVEN an action error occured.
2043 pd_params_.code = ErrorCode::kNoUpdate;
2044
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002045 // THEN update_engine should not call update completion.
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002046 // THEN go idle.
2047 // THEN install indication should be false.
2048
2049 TestProcessingDone();
2050}
2051
2052TEST_F(UpdateAttempterTest, ProcessingDoneNoInstall) {
2053 // GIVEN an install finished.
2054 pd_params_.is_install = true;
2055 // GIVEN an action error occured.
2056 pd_params_.code = ErrorCode::kNoUpdate;
2057
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002058 // THEN update_engine should not call install completion.
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002059 // THEN go idle.
2060 // THEN install indication should be false.
2061
2062 TestProcessingDone();
2063}
2064
2065TEST_F(UpdateAttempterTest, ProcessingDoneUpdateError) {
2066 // GIVEN an update finished.
2067 // GIVEN an action error occured.
2068 pd_params_.code = ErrorCode::kError;
2069 // GIVEN an event error is set.
2070 attempter_.error_event_.reset(new OmahaEvent(OmahaEvent::kTypeUpdateComplete,
2071 OmahaEvent::kResultError,
2072 ErrorCode::kError));
2073
2074 // THEN indicate a error event.
2075 pd_params_.expected_exit_status = UpdateStatus::REPORTING_ERROR_EVENT;
2076 // THEN install indication should be false.
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 expect critical actions of |ScheduleErrorEventAction()|.
2080 EXPECT_CALL(*processor_, EnqueueAction(Pointee(_))).Times(1);
2081 EXPECT_CALL(*processor_, StartProcessing()).Times(1);
2082 // THEN |ScheduleUpdates()| will be called next |ProcessingDone()| so skip.
2083 pd_params_.should_schedule_updates_be_called = false;
2084
2085 TestProcessingDone();
2086}
2087
2088TEST_F(UpdateAttempterTest, ProcessingDoneInstallError) {
2089 // GIVEN an install finished.
2090 pd_params_.is_install = true;
2091 // GIVEN an action error occured.
2092 pd_params_.code = ErrorCode::kError;
2093 // GIVEN an event error is set.
2094 attempter_.error_event_.reset(new OmahaEvent(OmahaEvent::kTypeUpdateComplete,
2095 OmahaEvent::kResultError,
2096 ErrorCode::kError));
2097
2098 // THEN indicate a error event.
2099 pd_params_.expected_exit_status = UpdateStatus::REPORTING_ERROR_EVENT;
2100 // THEN install indication should be false.
2101
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002102 // THEN update_engine should not call install completion.
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002103 // THEN expect critical actions of |ScheduleErrorEventAction()|.
2104 EXPECT_CALL(*processor_, EnqueueAction(Pointee(_))).Times(1);
2105 EXPECT_CALL(*processor_, StartProcessing()).Times(1);
2106 // THEN |ScheduleUpdates()| will be called next |ProcessingDone()| so skip.
2107 pd_params_.should_schedule_updates_be_called = false;
2108
2109 TestProcessingDone();
2110}
2111
Saurabh Nijhara43d7adc2020-11-06 16:13:02 +01002112TEST_F(UpdateAttempterTest, QuickFixTokenWhenDeviceIsEnterpriseEnrolled) {
2113 attempter_.CalculateUpdateParams({.quick_fix_build_token = "token"});
2114 EXPECT_EQ("token",
2115 FakeSystemState::Get()->request_params()->autoupdate_token());
Amr Aboelkher21ac9962019-05-15 14:50:05 +02002116
Saurabh Nijhara43d7adc2020-11-06 16:13:02 +01002117 attempter_.CalculateUpdateParams({});
2118 EXPECT_TRUE(
2119 FakeSystemState::Get()->request_params()->autoupdate_token().empty());
Askar Aitzhan570ca872019-04-24 11:16:12 +02002120}
2121
Jae Hoon Kim75daa382019-07-02 11:17:24 -07002122TEST_F(UpdateAttempterTest, ScheduleUpdateSpamHandlerTest) {
2123 EXPECT_CALL(mock_update_manager_, AsyncPolicyRequestUpdateCheckAllowed(_, _))
2124 .Times(1);
2125 EXPECT_TRUE(attempter_.ScheduleUpdates());
2126 // Now there is an update scheduled which means that all subsequent
2127 // |ScheduleUpdates()| should fail.
2128 EXPECT_FALSE(attempter_.ScheduleUpdates());
2129 EXPECT_FALSE(attempter_.ScheduleUpdates());
2130 EXPECT_FALSE(attempter_.ScheduleUpdates());
2131}
2132
2133// Critical tests to always make sure that an update is scheduled. The following
2134// unittest(s) try and cover the correctness in synergy between
2135// |UpdateAttempter| and |UpdateManager|. Also it is good to remember the
2136// actions that happen in the flow when |UpdateAttempter| get callbacked on
2137// |OnUpdateScheduled()| -> (various cases which leads to) -> |ProcessingDone()|
2138void UpdateAttempterTest::TestOnUpdateScheduled() {
2139 // Setup
2140 attempter_.SetWaitingForScheduledCheck(true);
2141 attempter_.DisableUpdate();
2142 attempter_.DisableScheduleUpdates();
2143
2144 // Invocation
2145 attempter_.OnUpdateScheduled(ous_params_.status, ous_params_.params);
2146
2147 // Verify
2148 EXPECT_EQ(ous_params_.exit_status, attempter_.status());
2149 EXPECT_EQ(ous_params_.should_schedule_updates_be_called,
2150 attempter_.WasScheduleUpdatesCalled());
2151 EXPECT_EQ(ous_params_.should_update_be_called, attempter_.WasUpdateCalled());
2152}
2153
2154TEST_F(UpdateAttempterTest, OnUpdatesScheduledFailed) {
2155 // GIVEN failed status.
2156
2157 // THEN update should be scheduled.
2158 ous_params_.should_schedule_updates_be_called = true;
2159
2160 TestOnUpdateScheduled();
2161}
2162
2163TEST_F(UpdateAttempterTest, OnUpdatesScheduledAskMeAgainLater) {
2164 // GIVEN ask me again later status.
2165 ous_params_.status = EvalStatus::kAskMeAgainLater;
2166
2167 // THEN update should be scheduled.
2168 ous_params_.should_schedule_updates_be_called = true;
2169
2170 TestOnUpdateScheduled();
2171}
2172
2173TEST_F(UpdateAttempterTest, OnUpdatesScheduledContinue) {
2174 // GIVEN continue status.
2175 ous_params_.status = EvalStatus::kContinue;
2176
2177 // THEN update should be scheduled.
2178 ous_params_.should_schedule_updates_be_called = true;
2179
2180 TestOnUpdateScheduled();
2181}
2182
2183TEST_F(UpdateAttempterTest, OnUpdatesScheduledSucceededButUpdateDisabledFails) {
2184 // GIVEN updates disabled.
2185 ous_params_.params = {.updates_enabled = false};
2186 // GIVEN succeeded status.
2187 ous_params_.status = EvalStatus::kSucceeded;
2188
2189 // THEN update should not be scheduled.
2190
2191 TestOnUpdateScheduled();
2192}
2193
2194TEST_F(UpdateAttempterTest, OnUpdatesScheduledSucceeded) {
2195 // GIVEN updates enabled.
2196 ous_params_.params = {.updates_enabled = true};
2197 // GIVEN succeeded status.
2198 ous_params_.status = EvalStatus::kSucceeded;
2199
2200 // THEN update should be called indicating status change.
2201 ous_params_.exit_status = UpdateStatus::CHECKING_FOR_UPDATE;
2202 ous_params_.should_update_be_called = true;
2203
2204 TestOnUpdateScheduled();
2205}
2206
Amin Hassani9be122e2019-08-29 09:20:12 -07002207TEST_F(UpdateAttempterTest, IsEnterpriseRollbackInGetStatusDefault) {
2208 UpdateEngineStatus status;
2209 attempter_.GetStatus(&status);
2210 EXPECT_FALSE(status.is_enterprise_rollback);
2211}
2212
2213TEST_F(UpdateAttempterTest, IsEnterpriseRollbackInGetStatusFalse) {
2214 attempter_.install_plan_.reset(new InstallPlan);
2215 attempter_.install_plan_->is_rollback = false;
2216
2217 UpdateEngineStatus status;
2218 attempter_.GetStatus(&status);
2219 EXPECT_FALSE(status.is_enterprise_rollback);
2220}
2221
2222TEST_F(UpdateAttempterTest, IsEnterpriseRollbackInGetStatusTrue) {
2223 attempter_.install_plan_.reset(new InstallPlan);
2224 attempter_.install_plan_->is_rollback = true;
2225
2226 UpdateEngineStatus status;
2227 attempter_.GetStatus(&status);
2228 EXPECT_TRUE(status.is_enterprise_rollback);
2229}
2230
Miriam Polzer0cf1acb2020-04-29 17:39:51 +02002231TEST_F(UpdateAttempterTest, PowerwashInGetStatusDefault) {
2232 UpdateEngineStatus status;
2233 attempter_.GetStatus(&status);
2234 EXPECT_FALSE(status.will_powerwash_after_reboot);
2235}
2236
2237TEST_F(UpdateAttempterTest, PowerwashInGetStatusTrueBecausePowerwashRequired) {
2238 attempter_.install_plan_.reset(new InstallPlan);
2239 attempter_.install_plan_->powerwash_required = true;
2240
2241 UpdateEngineStatus status;
2242 attempter_.GetStatus(&status);
2243 EXPECT_TRUE(status.will_powerwash_after_reboot);
2244}
2245
2246TEST_F(UpdateAttempterTest, PowerwashInGetStatusTrueBecauseRollback) {
2247 attempter_.install_plan_.reset(new InstallPlan);
2248 attempter_.install_plan_->is_rollback = true;
2249
2250 UpdateEngineStatus status;
2251 attempter_.GetStatus(&status);
2252 EXPECT_TRUE(status.will_powerwash_after_reboot);
2253}
2254
Jae Hoon Kim051627a2019-09-03 12:56:32 -07002255TEST_F(UpdateAttempterTest, FutureEolTest) {
2256 EolDate eol_date = std::numeric_limits<int64_t>::max();
Amin Hassani90e9f192020-11-18 14:20:56 -08002257 EXPECT_TRUE(prefs_->SetString(kPrefsOmahaEolDate, EolDateToString(eol_date)));
Jae Hoon Kim051627a2019-09-03 12:56:32 -07002258 UpdateEngineStatus status;
2259 attempter_.GetStatus(&status);
2260 EXPECT_EQ(eol_date, status.eol_date);
2261}
2262
2263TEST_F(UpdateAttempterTest, PastEolTest) {
2264 EolDate eol_date = 1;
Amin Hassani90e9f192020-11-18 14:20:56 -08002265 EXPECT_TRUE(prefs_->SetString(kPrefsOmahaEolDate, EolDateToString(eol_date)));
Jae Hoon Kim051627a2019-09-03 12:56:32 -07002266 UpdateEngineStatus status;
2267 attempter_.GetStatus(&status);
2268 EXPECT_EQ(eol_date, status.eol_date);
2269}
2270
Jae Hoon Kim2dfd35d2020-06-02 10:53:13 -07002271TEST_F(UpdateAttempterTest, MissingEolTest) {
Jae Hoon Kim2dfd35d2020-06-02 10:53:13 -07002272 UpdateEngineStatus status;
2273 attempter_.GetStatus(&status);
2274 EXPECT_EQ(kEolDateInvalid, status.eol_date);
Jae Hoon Kim051627a2019-09-03 12:56:32 -07002275}
2276
Andrewe045aef2020-01-08 16:29:22 -08002277TEST_F(UpdateAttempterTest, CalculateDlcParamsInstallTest) {
Andrewe045aef2020-01-08 16:29:22 -08002278 string dlc_id = "dlc0";
Andrewe045aef2020-01-08 16:29:22 -08002279 attempter_.is_install_ = true;
Amin Hassani2b68e6b2020-04-17 10:49:12 -07002280 attempter_.dlc_ids_ = {dlc_id};
Andrewe045aef2020-01-08 16:29:22 -08002281 attempter_.CalculateDlcParams();
2282
Amin Hassani538bd592020-11-04 20:46:08 -08002283 OmahaRequestParams* params = FakeSystemState::Get()->request_params();
Andrewe045aef2020-01-08 16:29:22 -08002284 EXPECT_EQ(1, params->dlc_apps_params().count(params->GetDlcAppId(dlc_id)));
2285 OmahaRequestParams::AppParams dlc_app_params =
2286 params->dlc_apps_params().at(params->GetDlcAppId(dlc_id));
2287 EXPECT_STREQ(dlc_id.c_str(), dlc_app_params.name.c_str());
2288 EXPECT_EQ(false, dlc_app_params.send_ping);
2289 // When the DLC gets installed, a ping is not sent, therefore we don't store
2290 // the values sent by Omaha.
Andrew065d78d2020-04-07 15:43:07 -07002291 auto last_active_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002292 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastActive});
Amin Hassani538bd592020-11-04 20:46:08 -08002293 EXPECT_FALSE(FakeSystemState::Get()->prefs()->Exists(last_active_key));
Andrew065d78d2020-04-07 15:43:07 -07002294 auto last_rollcall_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002295 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastRollcall});
Amin Hassani538bd592020-11-04 20:46:08 -08002296 EXPECT_FALSE(FakeSystemState::Get()->prefs()->Exists(last_rollcall_key));
Andrewe045aef2020-01-08 16:29:22 -08002297}
2298
2299TEST_F(UpdateAttempterTest, CalculateDlcParamsNoPrefFilesTest) {
Andrewe045aef2020-01-08 16:29:22 -08002300 string dlc_id = "dlc0";
Amin Hassani2b68e6b2020-04-17 10:49:12 -07002301 EXPECT_CALL(mock_dlcservice_, GetDlcsToUpdate(_))
Andrewe045aef2020-01-08 16:29:22 -08002302 .WillOnce(
2303 DoAll(SetArgPointee<0>(std::vector<string>({dlc_id})), Return(true)));
2304
2305 attempter_.is_install_ = false;
2306 attempter_.CalculateDlcParams();
2307
Amin Hassani538bd592020-11-04 20:46:08 -08002308 OmahaRequestParams* params = FakeSystemState::Get()->request_params();
Andrewe045aef2020-01-08 16:29:22 -08002309 EXPECT_EQ(1, params->dlc_apps_params().count(params->GetDlcAppId(dlc_id)));
2310 OmahaRequestParams::AppParams dlc_app_params =
2311 params->dlc_apps_params().at(params->GetDlcAppId(dlc_id));
2312 EXPECT_STREQ(dlc_id.c_str(), dlc_app_params.name.c_str());
2313
2314 EXPECT_EQ(true, dlc_app_params.send_ping);
2315 EXPECT_EQ(0, dlc_app_params.ping_active);
2316 EXPECT_EQ(-1, dlc_app_params.ping_date_last_active);
2317 EXPECT_EQ(-1, dlc_app_params.ping_date_last_rollcall);
2318}
2319
2320TEST_F(UpdateAttempterTest, CalculateDlcParamsNonParseableValuesTest) {
Andrewe045aef2020-01-08 16:29:22 -08002321 string dlc_id = "dlc0";
Andrew065d78d2020-04-07 15:43:07 -07002322 MemoryPrefs prefs;
Amin Hassani538bd592020-11-04 20:46:08 -08002323 FakeSystemState::Get()->set_prefs(&prefs);
Amin Hassani2b68e6b2020-04-17 10:49:12 -07002324 EXPECT_CALL(mock_dlcservice_, GetDlcsToUpdate(_))
Andrewe045aef2020-01-08 16:29:22 -08002325 .WillOnce(
2326 DoAll(SetArgPointee<0>(std::vector<string>({dlc_id})), Return(true)));
2327
2328 // Write non numeric values in the metadata files.
Andrew065d78d2020-04-07 15:43:07 -07002329 auto active_key =
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002330 PrefsInterface::CreateSubKey({kDlcPrefsSubDir, dlc_id, kPrefsPingActive});
Andrew065d78d2020-04-07 15:43:07 -07002331 auto last_active_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002332 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastActive});
Andrew065d78d2020-04-07 15:43:07 -07002333 auto last_rollcall_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002334 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastRollcall});
Amin Hassani538bd592020-11-04 20:46:08 -08002335 FakeSystemState::Get()->prefs()->SetString(active_key, "z2yz");
2336 FakeSystemState::Get()->prefs()->SetString(last_active_key, "z2yz");
2337 FakeSystemState::Get()->prefs()->SetString(last_rollcall_key, "z2yz");
Andrewe045aef2020-01-08 16:29:22 -08002338 attempter_.is_install_ = false;
2339 attempter_.CalculateDlcParams();
2340
Amin Hassani538bd592020-11-04 20:46:08 -08002341 OmahaRequestParams* params = FakeSystemState::Get()->request_params();
Andrewe045aef2020-01-08 16:29:22 -08002342 EXPECT_EQ(1, params->dlc_apps_params().count(params->GetDlcAppId(dlc_id)));
2343 OmahaRequestParams::AppParams dlc_app_params =
2344 params->dlc_apps_params().at(params->GetDlcAppId(dlc_id));
2345 EXPECT_STREQ(dlc_id.c_str(), dlc_app_params.name.c_str());
2346
2347 EXPECT_EQ(true, dlc_app_params.send_ping);
2348 EXPECT_EQ(0, dlc_app_params.ping_active);
2349 EXPECT_EQ(-2, dlc_app_params.ping_date_last_active);
2350 EXPECT_EQ(-2, dlc_app_params.ping_date_last_rollcall);
2351}
2352
2353TEST_F(UpdateAttempterTest, CalculateDlcParamsValidValuesTest) {
Andrewe045aef2020-01-08 16:29:22 -08002354 string dlc_id = "dlc0";
Amin Hassani2b68e6b2020-04-17 10:49:12 -07002355 EXPECT_CALL(mock_dlcservice_, GetDlcsToUpdate(_))
Andrewe045aef2020-01-08 16:29:22 -08002356 .WillOnce(
2357 DoAll(SetArgPointee<0>(std::vector<string>({dlc_id})), Return(true)));
2358
2359 // Write numeric values in the metadata files.
Andrew065d78d2020-04-07 15:43:07 -07002360 auto active_key =
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002361 PrefsInterface::CreateSubKey({kDlcPrefsSubDir, dlc_id, kPrefsPingActive});
Andrew065d78d2020-04-07 15:43:07 -07002362 auto last_active_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002363 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastActive});
Andrew065d78d2020-04-07 15:43:07 -07002364 auto last_rollcall_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002365 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastRollcall});
Andrew065d78d2020-04-07 15:43:07 -07002366
Amin Hassani538bd592020-11-04 20:46:08 -08002367 FakeSystemState::Get()->prefs()->SetInt64(active_key, 1);
2368 FakeSystemState::Get()->prefs()->SetInt64(last_active_key, 78);
2369 FakeSystemState::Get()->prefs()->SetInt64(last_rollcall_key, 99);
Andrewe045aef2020-01-08 16:29:22 -08002370 attempter_.is_install_ = false;
2371 attempter_.CalculateDlcParams();
2372
Amin Hassani538bd592020-11-04 20:46:08 -08002373 OmahaRequestParams* params = FakeSystemState::Get()->request_params();
Andrewe045aef2020-01-08 16:29:22 -08002374 EXPECT_EQ(1, params->dlc_apps_params().count(params->GetDlcAppId(dlc_id)));
2375 OmahaRequestParams::AppParams dlc_app_params =
2376 params->dlc_apps_params().at(params->GetDlcAppId(dlc_id));
2377 EXPECT_STREQ(dlc_id.c_str(), dlc_app_params.name.c_str());
2378
2379 EXPECT_EQ(true, dlc_app_params.send_ping);
2380 EXPECT_EQ(1, dlc_app_params.ping_active);
2381 EXPECT_EQ(78, dlc_app_params.ping_date_last_active);
2382 EXPECT_EQ(99, dlc_app_params.ping_date_last_rollcall);
2383}
Andrewa8d7df32020-03-15 20:10:01 -07002384
2385TEST_F(UpdateAttempterTest, CalculateDlcParamsRemoveStaleMetadata) {
Andrewa8d7df32020-03-15 20:10:01 -07002386 string dlc_id = "dlc0";
Andrew065d78d2020-04-07 15:43:07 -07002387 auto active_key =
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002388 PrefsInterface::CreateSubKey({kDlcPrefsSubDir, dlc_id, kPrefsPingActive});
Andrew065d78d2020-04-07 15:43:07 -07002389 auto last_active_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002390 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastActive});
Andrew065d78d2020-04-07 15:43:07 -07002391 auto last_rollcall_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002392 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastRollcall});
Amin Hassani538bd592020-11-04 20:46:08 -08002393 FakeSystemState::Get()->prefs()->SetInt64(active_key, kPingInactiveValue);
2394 FakeSystemState::Get()->prefs()->SetInt64(last_active_key, 0);
2395 FakeSystemState::Get()->prefs()->SetInt64(last_rollcall_key, 0);
2396 EXPECT_TRUE(FakeSystemState::Get()->prefs()->Exists(active_key));
2397 EXPECT_TRUE(FakeSystemState::Get()->prefs()->Exists(last_active_key));
2398 EXPECT_TRUE(FakeSystemState::Get()->prefs()->Exists(last_rollcall_key));
Andrewa8d7df32020-03-15 20:10:01 -07002399
Andrew065d78d2020-04-07 15:43:07 -07002400 attempter_.dlc_ids_ = {dlc_id};
2401 attempter_.is_install_ = true;
Andrewa8d7df32020-03-15 20:10:01 -07002402 attempter_.CalculateDlcParams();
2403
Amin Hassani538bd592020-11-04 20:46:08 -08002404 EXPECT_FALSE(FakeSystemState::Get()->prefs()->Exists(last_active_key));
2405 EXPECT_FALSE(FakeSystemState::Get()->prefs()->Exists(last_rollcall_key));
Andrew065d78d2020-04-07 15:43:07 -07002406 // Active key is set on install.
Amin Hassani538bd592020-11-04 20:46:08 -08002407 EXPECT_TRUE(FakeSystemState::Get()->prefs()->Exists(active_key));
Andrew065d78d2020-04-07 15:43:07 -07002408 int64_t temp_int;
Amin Hassani538bd592020-11-04 20:46:08 -08002409 EXPECT_TRUE(FakeSystemState::Get()->prefs()->GetInt64(active_key, &temp_int));
Andrew065d78d2020-04-07 15:43:07 -07002410 EXPECT_EQ(temp_int, kPingActiveValue);
Andrewa8d7df32020-03-15 20:10:01 -07002411}
2412
2413TEST_F(UpdateAttempterTest, SetDlcActiveValue) {
Andrewa8d7df32020-03-15 20:10:01 -07002414 string dlc_id = "dlc0";
Andrewa8d7df32020-03-15 20:10:01 -07002415 attempter_.SetDlcActiveValue(true, dlc_id);
Andrewa8d7df32020-03-15 20:10:01 -07002416 int64_t temp_int;
Andrew065d78d2020-04-07 15:43:07 -07002417 auto active_key =
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002418 PrefsInterface::CreateSubKey({kDlcPrefsSubDir, dlc_id, kPrefsPingActive});
Amin Hassani538bd592020-11-04 20:46:08 -08002419 EXPECT_TRUE(FakeSystemState::Get()->prefs()->Exists(active_key));
2420 EXPECT_TRUE(FakeSystemState::Get()->prefs()->GetInt64(active_key, &temp_int));
Andrewa8d7df32020-03-15 20:10:01 -07002421 EXPECT_EQ(temp_int, kPingActiveValue);
2422}
2423
2424TEST_F(UpdateAttempterTest, SetDlcInactive) {
Andrewa8d7df32020-03-15 20:10:01 -07002425 string dlc_id = "dlc0";
Andrew065d78d2020-04-07 15:43:07 -07002426 auto sub_keys = {
2427 kPrefsPingActive, kPrefsPingLastActive, kPrefsPingLastRollcall};
2428 for (auto& sub_key : sub_keys) {
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002429 auto key = PrefsInterface::CreateSubKey({kDlcPrefsSubDir, dlc_id, sub_key});
Amin Hassani538bd592020-11-04 20:46:08 -08002430 FakeSystemState::Get()->prefs()->SetInt64(key, 1);
2431 EXPECT_TRUE(FakeSystemState::Get()->prefs()->Exists(key));
Andrew065d78d2020-04-07 15:43:07 -07002432 }
Andrewa8d7df32020-03-15 20:10:01 -07002433 attempter_.SetDlcActiveValue(false, dlc_id);
Andrew065d78d2020-04-07 15:43:07 -07002434 for (auto& sub_key : sub_keys) {
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002435 auto key = PrefsInterface::CreateSubKey({kDlcPrefsSubDir, dlc_id, sub_key});
Amin Hassani538bd592020-11-04 20:46:08 -08002436 EXPECT_FALSE(FakeSystemState::Get()->prefs()->Exists(key));
Andrew065d78d2020-04-07 15:43:07 -07002437 }
Andrewa8d7df32020-03-15 20:10:01 -07002438}
2439
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002440TEST_F(UpdateAttempterTest, GetSuccessfulDlcIds) {
2441 auto dlc_1 = "1", dlc_2 = "2", dlc_3 = "3";
2442 attempter_.omaha_request_params_->set_dlc_apps_params(
2443 {{dlc_1, {.name = dlc_1, .updated = false}},
2444 {dlc_2, {.name = dlc_2}},
2445 {dlc_3, {.name = dlc_3, .updated = false}}});
2446 EXPECT_THAT(attempter_.GetSuccessfulDlcIds(), ElementsAre(dlc_2));
2447}
2448
Vyshu6e8a37b2020-11-25 10:31:00 -08002449TEST_F(UpdateAttempterTest, MoveToPrefs) {
2450 string key1 = kPrefsLastActivePingDay;
2451 string key2 = kPrefsPingLastRollcall;
2452
2453 FakePrefs fake_prefs;
2454 EXPECT_TRUE(fake_prefs.SetString(key2, "current-rollcall"));
2455 FakeSystemState::Get()->set_prefs(&fake_prefs);
2456
2457 FakePrefs powerwash_safe_prefs;
2458 EXPECT_TRUE(powerwash_safe_prefs.SetString(key1, "powerwash-last-active"));
2459 EXPECT_TRUE(powerwash_safe_prefs.SetString(key2, "powerwash-last-rollcall"));
2460 FakeSystemState::Get()->set_powerwash_safe_prefs(&powerwash_safe_prefs);
2461
2462 attempter_.Init();
2463 attempter_.MoveToPrefs({key1, key2});
2464
2465 string pref_value_1;
2466 fake_prefs.GetString(key1, &pref_value_1);
2467 EXPECT_EQ(pref_value_1, "powerwash-last-active");
2468 // Do not overwrite if value already exists.
2469 string pref_value_2;
2470 fake_prefs.GetString(key2, &pref_value_2);
2471 EXPECT_EQ(pref_value_2, "current-rollcall");
2472
2473 // Make sure keys are deleted from powerwash safe prefs regardless of whether
2474 // they are written to prefs.
2475 EXPECT_FALSE(FakeSystemState::Get()->powerwash_safe_prefs()->Exists(key1));
2476 EXPECT_FALSE(FakeSystemState::Get()->powerwash_safe_prefs()->Exists(key2));
2477}
2478
Darin Petkovf42cc1c2010-09-01 09:03:02 -07002479} // namespace chromeos_update_engine