blob: a11e00c19ddffa2f36d8d9f2fb50a90541bda819 [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"
Amin Hassaniec7bc112020-10-29 16:47:58 -070048#include "update_engine/cros/fake_system_state.h"
49#include "update_engine/cros/mock_p2p_manager.h"
50#include "update_engine/cros/mock_payload_state.h"
51#include "update_engine/cros/omaha_utils.h"
Jae Hoon Kim0ae8fe12019-06-26 14:32:50 -070052#include "update_engine/libcurl_http_fetcher.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080053#include "update_engine/payload_consumer/filesystem_verifier_action.h"
54#include "update_engine/payload_consumer/install_plan.h"
55#include "update_engine/payload_consumer/payload_constants.h"
56#include "update_engine/payload_consumer/postinstall_runner_action.h"
Amin Hassani0882a512018-04-05 16:25:44 -070057#include "update_engine/update_boot_flags_action.h"
Jae Hoon Kim504c3cb2019-07-02 11:17:24 -070058#include "update_engine/update_manager/mock_update_manager.h"
Darin Petkovf42cc1c2010-09-01 09:03:02 -070059
David Zeuthen985b1122013-10-09 12:13:15 -070060using base::Time;
61using base::TimeDelta;
Aaron Woodbf5a2522017-10-04 10:58:36 -070062using chromeos_update_manager::EvalStatus;
Jae Hoon Kim504c3cb2019-07-02 11:17:24 -070063using chromeos_update_manager::MockUpdateManager;
Adolfo Victoria497044c2018-07-18 07:51:42 -070064using chromeos_update_manager::StagingSchedule;
Aaron Woodbf5a2522017-10-04 10:58:36 -070065using chromeos_update_manager::UpdateCheckParams;
Adolfo Victoria497044c2018-07-18 07:51:42 -070066using policy::DevicePolicy;
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -070067using std::map;
Darin Petkovf42cc1c2010-09-01 09:03:02 -070068using std::string;
Ben Chan02f7c1d2014-10-18 15:18:02 -070069using std::unique_ptr;
Jae Hoon Kimedb65502019-06-14 11:52:17 -070070using std::unordered_set;
Xiaochu Liu88d90382018-08-29 16:09:11 -070071using std::vector;
Aaron Woodbf5a2522017-10-04 10:58:36 -070072using testing::_;
Andrew065d78d2020-04-07 15:43:07 -070073using testing::Contains;
Darin Petkov36275772010-10-01 11:40:57 -070074using testing::DoAll;
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -070075using testing::ElementsAre;
Aaron Wood7f92e2b2017-08-28 14:51:21 -070076using testing::Field;
Darin Petkovf42cc1c2010-09-01 09:03:02 -070077using testing::InSequence;
Jae Hoon Kimedb65502019-06-14 11:52:17 -070078using testing::Invoke;
Darin Petkov2dd01092010-10-08 15:43:05 -070079using testing::Ne;
Darin Petkov9c096d62010-11-17 14:49:04 -080080using testing::NiceMock;
Amin Hassanid3f4bea2018-04-30 14:52:40 -070081using testing::Pointee;
Darin Petkovf42cc1c2010-09-01 09:03:02 -070082using testing::Property;
83using testing::Return;
Gilad Arnold74b5f552014-10-07 08:17:16 -070084using testing::ReturnPointee;
Marton Hunyadye58bddb2018-04-10 20:27:26 +020085using testing::ReturnRef;
Alex Deymo2c0db7b2014-11-04 12:23:39 -080086using testing::SaveArg;
Ben Chan672c1f52017-10-23 15:41:39 -070087using testing::SetArgPointee;
Aaron Woodbf5a2522017-10-04 10:58:36 -070088using update_engine::UpdateAttemptFlags;
Aaron Wood7f92e2b2017-08-28 14:51:21 -070089using update_engine::UpdateEngineStatus;
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -070090using update_engine::UpdateStatus;
Darin Petkovf42cc1c2010-09-01 09:03:02 -070091
92namespace chromeos_update_engine {
93
Xiaochu Liu8ba486f2018-11-06 11:14:10 -080094namespace {
95
Jae Hoon Kimc437ea52019-07-11 11:20:38 -070096const UpdateStatus kNonIdleUpdateStatuses[] = {
97 UpdateStatus::CHECKING_FOR_UPDATE,
98 UpdateStatus::UPDATE_AVAILABLE,
99 UpdateStatus::DOWNLOADING,
100 UpdateStatus::VERIFYING,
101 UpdateStatus::FINALIZING,
102 UpdateStatus::UPDATED_NEED_REBOOT,
103 UpdateStatus::REPORTING_ERROR_EVENT,
104 UpdateStatus::ATTEMPTING_ROLLBACK,
105 UpdateStatus::DISABLED,
106 UpdateStatus::NEED_PERMISSION_TO_UPDATE,
107};
108
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -0700109struct CheckForUpdateTestParams {
110 // Setups + Inputs:
111 UpdateStatus status = UpdateStatus::IDLE;
112 string app_version = "fake_app_version";
113 string omaha_url = "fake_omaha_url";
114 UpdateAttemptFlags flags = UpdateAttemptFlags::kNone;
115 bool is_official_build = true;
116 bool are_dev_features_enabled = false;
117
118 // Expects:
119 string expected_forced_app_version = "";
120 string expected_forced_omaha_url = "";
Jae Hoon Kim2b73ac22019-07-02 11:17:24 -0700121 bool should_schedule_updates_be_called = true;
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -0700122 bool expected_result = true;
123};
124
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700125struct OnUpdateScheduledTestParams {
126 // Setups + Inputs:
127 UpdateCheckParams params = {};
128 EvalStatus status = EvalStatus::kFailed;
129 // Expects:
130 UpdateStatus exit_status = UpdateStatus::IDLE;
131 bool should_schedule_updates_be_called = false;
132 bool should_update_be_called = false;
133};
134
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -0700135struct ProcessingDoneTestParams {
136 // Setups + Inputs:
137 bool is_install = false;
138 UpdateStatus status = UpdateStatus::CHECKING_FOR_UPDATE;
139 ActionProcessor* processor = nullptr;
140 ErrorCode code = ErrorCode::kSuccess;
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -0700141 map<string, OmahaRequestParams::AppParams> dlc_apps_params;
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -0700142
143 // Expects:
144 const bool kExpectedIsInstall = false;
145 bool should_schedule_updates_be_called = true;
146 UpdateStatus expected_exit_status = UpdateStatus::IDLE;
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -0700147 bool should_install_completed_be_called = false;
148 bool should_update_completed_be_called = false;
149 vector<string> args_to_install_completed;
150 vector<string> args_to_update_completed;
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -0700151};
152
Xiaochu Liu8ba486f2018-11-06 11:14:10 -0800153class MockDlcService : public DlcServiceInterface {
154 public:
Amin Hassani2b68e6b2020-04-17 10:49:12 -0700155 MOCK_METHOD1(GetDlcsToUpdate, bool(vector<string>*));
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -0700156 MOCK_METHOD1(InstallCompleted, bool(const vector<string>&));
157 MOCK_METHOD1(UpdateCompleted, bool(const vector<string>&));
Xiaochu Liu8ba486f2018-11-06 11:14:10 -0800158};
159
160} // namespace
161
Marton Hunyadya0302682018-05-16 18:52:13 +0200162const char kRollbackVersion[] = "10575.39.2";
163
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700164// Test a subclass rather than the main class directly so that we can mock out
Darin Petkovcd1666f2010-09-23 09:53:44 -0700165// methods within the class. There're explicit unit tests for the mocked out
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700166// methods.
167class UpdateAttempterUnderTest : public UpdateAttempter {
168 public:
Amin Hassani538bd592020-11-04 20:46:08 -0800169 UpdateAttempterUnderTest() : UpdateAttempter(nullptr) {}
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700170
Amin Hassanie8153632020-10-27 15:11:28 -0700171 void Update(const UpdateCheckParams& params) override {
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700172 update_called_ = true;
173 if (do_update_) {
Amin Hassanie8153632020-10-27 15:11:28 -0700174 UpdateAttempter::Update(params);
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700175 return;
176 }
177 LOG(INFO) << "[TEST] Update() disabled.";
178 status_ = UpdateStatus::CHECKING_FOR_UPDATE;
179 }
180
181 void DisableUpdate() { do_update_ = false; }
182
183 bool WasUpdateCalled() const { return update_called_; }
184
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700185 // Wrap the update scheduling method, allowing us to opt out of scheduled
186 // updates for testing purposes.
Xiaochu Liu88d90382018-08-29 16:09:11 -0700187 bool ScheduleUpdates() override {
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700188 schedule_updates_called_ = true;
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700189 if (do_schedule_updates_)
190 return UpdateAttempter::ScheduleUpdates();
191 LOG(INFO) << "[TEST] Update scheduling disabled.";
192 waiting_for_scheduled_check_ = true;
Xiaochu Liu88d90382018-08-29 16:09:11 -0700193 return true;
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700194 }
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700195
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700196 void DisableScheduleUpdates() { do_schedule_updates_ = false; }
197
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700198 // Indicates whether |ScheduleUpdates()| was called.
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700199 bool WasScheduleUpdatesCalled() const { return schedule_updates_called_; }
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700200
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -0700201 // Need to expose following private members of |UpdateAttempter| for tests.
202 const string& forced_app_version() const { return forced_app_version_; }
Alex Deymo60ca1a72015-06-18 18:19:15 -0700203 const string& forced_omaha_url() const { return forced_omaha_url_; }
David Pursell02c18642014-11-06 11:26:11 -0800204
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700205 // Need to expose |waiting_for_scheduled_check_| for testing.
206 void SetWaitingForScheduledCheck(bool waiting) {
207 waiting_for_scheduled_check_ = waiting;
208 }
209
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700210 private:
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700211 // Used for overrides of |Update()|.
212 bool update_called_ = false;
213 bool do_update_ = true;
214
215 // Used for overrides of |ScheduleUpdates()|.
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700216 bool schedule_updates_called_ = false;
217 bool do_schedule_updates_ = true;
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700218};
219
220class UpdateAttempterTest : public ::testing::Test {
221 protected:
Amin Hassani538bd592020-11-04 20:46:08 -0800222 void SetUp() override {
Gilad Arnold1f847232014-04-07 12:07:49 -0700223 // Override system state members.
Amin Hassani538bd592020-11-04 20:46:08 -0800224 FakeSystemState::CreateInstance();
225 FakeSystemState::Get()->set_connection_manager(&mock_connection_manager);
226 FakeSystemState::Get()->set_update_attempter(&attempter_);
227 FakeSystemState::Get()->set_dlcservice(&mock_dlcservice_);
228 FakeSystemState::Get()->set_update_manager(&mock_update_manager_);
Alex Deymo60ca1a72015-06-18 18:19:15 -0700229 loop_.SetAsCurrent();
Gilad Arnold1f847232014-04-07 12:07:49 -0700230
Amin Hassani90e9f192020-11-18 14:20:56 -0800231 prefs_ = FakeSystemState::Get()->fake_prefs();
232 certificate_checker_.reset(
233 new CertificateChecker(prefs_, &openssl_wrapper_));
Amin Hassani538bd592020-11-04 20:46:08 -0800234 certificate_checker_->Init();
Alex Deymo33e91e72015-12-01 18:26:08 -0300235
Xiaochu Liu8ba486f2018-11-06 11:14:10 -0800236 attempter_.set_forced_update_pending_callback(
237 new base::Callback<void(bool, bool)>(base::Bind([](bool, bool) {})));
Sen Jiange67bb5b2016-06-20 15:53:56 -0700238 // Finish initializing the attempter.
Gilad Arnold1f847232014-04-07 12:07:49 -0700239 attempter_.Init();
Gilad Arnoldeff87cc2013-07-22 18:32:09 -0700240
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700241 EXPECT_EQ(0, attempter_.http_response_code_);
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700242 EXPECT_EQ(UpdateStatus::IDLE, attempter_.status_);
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700243 EXPECT_EQ(0.0, attempter_.download_progress_);
244 EXPECT_EQ(0, attempter_.last_checked_time_);
245 EXPECT_EQ("0.0.0.0", attempter_.new_version_);
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700246 EXPECT_EQ(0ULL, attempter_.new_payload_size_);
Alex Deymo8427b4a2014-11-05 14:00:32 -0800247 processor_ = new NiceMock<MockActionProcessor>();
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700248 attempter_.processor_.reset(processor_); // Transfers ownership.
Gilad Arnold74b5f552014-10-07 08:17:16 -0700249
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700250 // Setup store/load semantics of P2P properties via the mock |PayloadState|.
Gilad Arnold74b5f552014-10-07 08:17:16 -0700251 actual_using_p2p_for_downloading_ = false;
Amin Hassani538bd592020-11-04 20:46:08 -0800252 EXPECT_CALL(*FakeSystemState::Get()->mock_payload_state(),
Gilad Arnold74b5f552014-10-07 08:17:16 -0700253 SetUsingP2PForDownloading(_))
254 .WillRepeatedly(SaveArg<0>(&actual_using_p2p_for_downloading_));
Amin Hassani538bd592020-11-04 20:46:08 -0800255 EXPECT_CALL(*FakeSystemState::Get()->mock_payload_state(),
Gilad Arnold74b5f552014-10-07 08:17:16 -0700256 GetUsingP2PForDownloading())
257 .WillRepeatedly(ReturnPointee(&actual_using_p2p_for_downloading_));
258 actual_using_p2p_for_sharing_ = false;
Amin Hassani538bd592020-11-04 20:46:08 -0800259 EXPECT_CALL(*FakeSystemState::Get()->mock_payload_state(),
Gilad Arnold74b5f552014-10-07 08:17:16 -0700260 SetUsingP2PForSharing(_))
261 .WillRepeatedly(SaveArg<0>(&actual_using_p2p_for_sharing_));
Amin Hassani538bd592020-11-04 20:46:08 -0800262 EXPECT_CALL(*FakeSystemState::Get()->mock_payload_state(),
Gilad Arnold74b5f552014-10-07 08:17:16 -0700263 GetUsingP2PForDownloading())
264 .WillRepeatedly(ReturnPointee(&actual_using_p2p_for_sharing_));
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700265 }
266
Alex Deymo60ca1a72015-06-18 18:19:15 -0700267 public:
268 void ScheduleQuitMainLoop();
Patrick Dubroy7fbbe8a2011-08-01 17:28:22 +0200269
Alex Deymo60ca1a72015-06-18 18:19:15 -0700270 // Callbacks to run the different tests from the main loop.
Darin Petkove6ef2f82011-03-07 17:31:11 -0800271 void UpdateTestStart();
272 void UpdateTestVerify();
Alex Deymo60ca1a72015-06-18 18:19:15 -0700273 void RollbackTestStart(bool enterprise_rollback, bool valid_slot);
Chris Sosa76a29ae2013-07-11 17:59:24 -0700274 void RollbackTestVerify();
Thieu Le116fda32011-04-19 11:01:54 -0700275 void PingOmahaTestStart();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700276 void ReadScatterFactorFromPolicyTestStart();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700277 void DecrementUpdateCheckCountTestStart();
Jay Srinivasan08fce042012-06-07 16:31:01 -0700278 void NoScatteringDoneDuringManualUpdateTestStart();
David Zeuthen8f191b22013-08-06 12:27:50 -0700279 void P2PNotEnabledStart();
David Zeuthen8f191b22013-08-06 12:27:50 -0700280 void P2PEnabledStart();
David Zeuthen8f191b22013-08-06 12:27:50 -0700281 void P2PEnabledInteractiveStart();
David Zeuthen8f191b22013-08-06 12:27:50 -0700282 void P2PEnabledStartingFailsStart();
David Zeuthen8f191b22013-08-06 12:27:50 -0700283 void P2PEnabledHousekeepingFailsStart();
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700284 void SessionIdTestChange();
285 void SessionIdTestEnforceEmptyStrPingOmaha();
286 void SessionIdTestConsistencyInUpdateFlow();
Jae Hoon Kim0ae8fe12019-06-26 14:32:50 -0700287 void SessionIdTestInDownloadAction();
Marton Hunyadye58bddb2018-04-10 20:27:26 +0200288 void ResetRollbackHappenedStart(bool is_consumer,
289 bool is_policy_available,
290 bool expected_reset);
Adolfo Victoria497044c2018-07-18 07:51:42 -0700291 // Staging related callbacks.
Amin Hassani90e9f192020-11-18 14:20:56 -0800292 void SetUpStagingTest(const StagingSchedule& schedule);
Adolfo Victoria497044c2018-07-18 07:51:42 -0700293 void CheckStagingOff();
294 void StagingSetsPrefsAndTurnsOffScatteringStart();
295 void StagingOffIfInteractiveStart();
296 void StagingOffIfOobeStart();
David Zeuthen8f191b22013-08-06 12:27:50 -0700297
Gilad Arnold74b5f552014-10-07 08:17:16 -0700298 bool actual_using_p2p_for_downloading() {
299 return actual_using_p2p_for_downloading_;
300 }
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800301 bool actual_using_p2p_for_sharing() { return actual_using_p2p_for_sharing_; }
Gilad Arnold74b5f552014-10-07 08:17:16 -0700302
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -0700303 // |CheckForUpdate()| related member functions.
304 void TestCheckForUpdate();
305
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700306 // |OnUpdateScheduled()| related member functions.
307 void TestOnUpdateScheduled();
308
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -0700309 // |ProcessingDone()| related member functions.
310 void TestProcessingDone();
311
Qijiang Fanb0b6cc22020-10-15 21:54:11 +0900312 base::SingleThreadTaskExecutor base_loop_{base::MessagePumpType::IO};
313 brillo::BaseMessageLoop loop_{base_loop_.task_runner()};
Alex Deymo60ca1a72015-06-18 18:19:15 -0700314
Amin Hassani538bd592020-11-04 20:46:08 -0800315 UpdateAttempterUnderTest attempter_;
Alex Deymo33e91e72015-12-01 18:26:08 -0300316 OpenSSLWrapper openssl_wrapper_;
Amin Hassani538bd592020-11-04 20:46:08 -0800317 std::unique_ptr<CertificateChecker> certificate_checker_;
Xiaochu Liu8ba486f2018-11-06 11:14:10 -0800318 MockDlcService mock_dlcservice_;
Jae Hoon Kim504c3cb2019-07-02 11:17:24 -0700319 MockUpdateManager mock_update_manager_;
Alex Deymo30534502015-07-20 15:06:33 -0700320
Alex Deymo8427b4a2014-11-05 14:00:32 -0800321 NiceMock<MockActionProcessor>* processor_;
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800322 NiceMock<MockConnectionManager> mock_connection_manager;
Gilad Arnoldeff87cc2013-07-22 18:32:09 -0700323
Amin Hassani90e9f192020-11-18 14:20:56 -0800324 FakePrefs* prefs_;
325
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -0700326 // |CheckForUpdate()| test params.
327 CheckForUpdateTestParams cfu_params_;
328
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700329 // |OnUpdateScheduled()| test params.
330 OnUpdateScheduledTestParams ous_params_;
331
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -0700332 // |ProcessingDone()| test params.
333 ProcessingDoneTestParams pd_params_;
334
Gilad Arnold74b5f552014-10-07 08:17:16 -0700335 bool actual_using_p2p_for_downloading_;
336 bool actual_using_p2p_for_sharing_;
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700337};
338
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -0700339void UpdateAttempterTest::TestCheckForUpdate() {
340 // Setup
341 attempter_.status_ = cfu_params_.status;
Amin Hassani538bd592020-11-04 20:46:08 -0800342 FakeSystemState::Get()->fake_hardware()->SetIsOfficialBuild(
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -0700343 cfu_params_.is_official_build);
Amin Hassani538bd592020-11-04 20:46:08 -0800344 FakeSystemState::Get()->fake_hardware()->SetAreDevFeaturesEnabled(
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -0700345 cfu_params_.are_dev_features_enabled);
346
347 // Invocation
348 EXPECT_EQ(
349 cfu_params_.expected_result,
350 attempter_.CheckForUpdate(
351 cfu_params_.app_version, cfu_params_.omaha_url, cfu_params_.flags));
352
353 // Verify
354 EXPECT_EQ(cfu_params_.expected_forced_app_version,
355 attempter_.forced_app_version());
356 EXPECT_EQ(cfu_params_.expected_forced_omaha_url,
357 attempter_.forced_omaha_url());
Jae Hoon Kim2b73ac22019-07-02 11:17:24 -0700358 EXPECT_EQ(cfu_params_.should_schedule_updates_be_called,
359 attempter_.WasScheduleUpdatesCalled());
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -0700360}
361
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -0700362void UpdateAttempterTest::TestProcessingDone() {
363 // Setup
364 attempter_.DisableScheduleUpdates();
365 attempter_.is_install_ = pd_params_.is_install;
366 attempter_.status_ = pd_params_.status;
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -0700367 attempter_.omaha_request_params_->set_dlc_apps_params(
368 pd_params_.dlc_apps_params);
369
370 // Expects
371 if (pd_params_.should_install_completed_be_called)
372 EXPECT_CALL(mock_dlcservice_,
373 InstallCompleted(pd_params_.args_to_install_completed))
374 .WillOnce(Return(true));
375 else
376 EXPECT_CALL(mock_dlcservice_, InstallCompleted(_)).Times(0);
377 if (pd_params_.should_update_completed_be_called)
378 EXPECT_CALL(mock_dlcservice_,
379 UpdateCompleted(pd_params_.args_to_update_completed))
380 .WillOnce(Return(true));
381 else
382 EXPECT_CALL(mock_dlcservice_, UpdateCompleted(_)).Times(0);
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -0700383
384 // Invocation
385 attempter_.ProcessingDone(pd_params_.processor, pd_params_.code);
386
387 // Verify
388 EXPECT_EQ(pd_params_.kExpectedIsInstall, attempter_.is_install_);
389 EXPECT_EQ(pd_params_.should_schedule_updates_be_called,
390 attempter_.WasScheduleUpdatesCalled());
391 EXPECT_EQ(pd_params_.expected_exit_status, attempter_.status_);
392}
393
Alex Deymo60ca1a72015-06-18 18:19:15 -0700394void UpdateAttempterTest::ScheduleQuitMainLoop() {
Luis Hector Chavezf1cf3482016-07-19 14:29:19 -0700395 loop_.PostTask(
396 FROM_HERE,
397 base::Bind([](brillo::BaseMessageLoop* loop) { loop->BreakLoop(); },
398 base::Unretained(&loop_)));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700399}
400
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700401void UpdateAttempterTest::SessionIdTestChange() {
402 EXPECT_NE(UpdateStatus::UPDATED_NEED_REBOOT, attempter_.status());
403 const auto old_session_id = attempter_.session_id_;
Amin Hassanie8153632020-10-27 15:11:28 -0700404 attempter_.Update({});
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700405 EXPECT_NE(old_session_id, attempter_.session_id_);
406 ScheduleQuitMainLoop();
407}
408
409TEST_F(UpdateAttempterTest, SessionIdTestChange) {
410 loop_.PostTask(FROM_HERE,
411 base::Bind(&UpdateAttempterTest::SessionIdTestChange,
412 base::Unretained(this)));
413 loop_.Run();
414}
415
416void UpdateAttempterTest::SessionIdTestEnforceEmptyStrPingOmaha() {
417 // The |session_id_| should not be changed and should remain as an empty
418 // string when |status_| is |UPDATED_NEED_REBOOT| (only for consistency)
419 // and |PingOmaha()| is called.
420 attempter_.DisableScheduleUpdates();
421 attempter_.status_ = UpdateStatus::UPDATED_NEED_REBOOT;
422 const auto old_session_id = attempter_.session_id_;
423 auto CheckIfEmptySessionId = [](AbstractAction* aa) {
424 if (aa->Type() == OmahaRequestAction::StaticType()) {
425 EXPECT_TRUE(static_cast<OmahaRequestAction*>(aa)->session_id_.empty());
426 }
427 };
428 EXPECT_CALL(*processor_, EnqueueAction(Pointee(_)))
429 .WillRepeatedly(Invoke(CheckIfEmptySessionId));
430 EXPECT_CALL(*processor_, StartProcessing());
431 attempter_.PingOmaha();
432 EXPECT_EQ(old_session_id, attempter_.session_id_);
433 EXPECT_EQ(UpdateStatus::UPDATED_NEED_REBOOT, attempter_.status_);
434 ScheduleQuitMainLoop();
435}
436
437TEST_F(UpdateAttempterTest, SessionIdTestEnforceEmptyStrPingOmaha) {
438 loop_.PostTask(
439 FROM_HERE,
440 base::Bind(&UpdateAttempterTest::SessionIdTestEnforceEmptyStrPingOmaha,
441 base::Unretained(this)));
442 loop_.Run();
443}
444
445void UpdateAttempterTest::SessionIdTestConsistencyInUpdateFlow() {
446 // All session IDs passed into |OmahaRequestActions| should be enforced to
447 // have the same value in |BuildUpdateActions()|.
448 unordered_set<string> session_ids;
449 // Gather all the session IDs being passed to |OmahaRequestActions|.
450 auto CheckSessionId = [&session_ids](AbstractAction* aa) {
451 if (aa->Type() == OmahaRequestAction::StaticType())
452 session_ids.insert(static_cast<OmahaRequestAction*>(aa)->session_id_);
453 };
454 EXPECT_CALL(*processor_, EnqueueAction(Pointee(_)))
455 .WillRepeatedly(Invoke(CheckSessionId));
456 attempter_.BuildUpdateActions(false);
457 // Validate that all the session IDs are the same.
458 EXPECT_EQ(1, session_ids.size());
459 ScheduleQuitMainLoop();
460}
461
462TEST_F(UpdateAttempterTest, SessionIdTestConsistencyInUpdateFlow) {
463 loop_.PostTask(
464 FROM_HERE,
465 base::Bind(&UpdateAttempterTest::SessionIdTestConsistencyInUpdateFlow,
466 base::Unretained(this)));
467 loop_.Run();
468}
469
Jae Hoon Kim0ae8fe12019-06-26 14:32:50 -0700470void UpdateAttempterTest::SessionIdTestInDownloadAction() {
471 // The session ID passed into |DownloadAction|'s |LibcurlHttpFetcher| should
472 // be enforced to be included in the HTTP header as X-Goog-Update-SessionId.
473 string header_value;
474 auto CheckSessionIdInDownloadAction = [&header_value](AbstractAction* aa) {
475 if (aa->Type() == DownloadAction::StaticType()) {
476 DownloadAction* da = static_cast<DownloadAction*>(aa);
477 EXPECT_TRUE(da->http_fetcher()->GetHeader(kXGoogleUpdateSessionId,
478 &header_value));
479 }
480 };
481 EXPECT_CALL(*processor_, EnqueueAction(Pointee(_)))
482 .WillRepeatedly(Invoke(CheckSessionIdInDownloadAction));
483 attempter_.BuildUpdateActions(false);
484 // Validate that X-Goog-Update_SessionId is set correctly in HTTP Header.
485 EXPECT_EQ(attempter_.session_id_, header_value);
486 ScheduleQuitMainLoop();
487}
488
489TEST_F(UpdateAttempterTest, SessionIdTestInDownloadAction) {
490 loop_.PostTask(FROM_HERE,
491 base::Bind(&UpdateAttempterTest::SessionIdTestInDownloadAction,
492 base::Unretained(this)));
493 loop_.Run();
494}
495
Darin Petkov1b003102010-11-30 10:18:36 -0800496TEST_F(UpdateAttempterTest, ActionCompletedDownloadTest) {
Ben Chan02f7c1d2014-10-18 15:18:02 -0700497 unique_ptr<MockHttpFetcher> fetcher(new MockHttpFetcher("", 0, nullptr));
Darin Petkov1b003102010-11-30 10:18:36 -0800498 fetcher->FailTransfer(503); // Sets the HTTP response code.
Amin Hassani7ecda262017-07-11 17:10:50 -0700499 DownloadAction action(prefs_,
500 nullptr,
501 nullptr,
Amin Hassani7ecda262017-07-11 17:10:50 -0700502 fetcher.release(),
Amin Hassanied37d682018-04-06 13:22:00 -0700503 false /* interactive */);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700504 attempter_.ActionCompleted(nullptr, &action, ErrorCode::kSuccess);
Amin Hassani90e9f192020-11-18 14:20:56 -0800505 EXPECT_FALSE(prefs_->Exists(kPrefsDeltaUpdateFailures));
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700506 EXPECT_EQ(UpdateStatus::FINALIZING, attempter_.status());
Aaron Wood9321f502017-09-07 11:18:54 -0700507 EXPECT_EQ(0.0, attempter_.download_progress_);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700508 ASSERT_EQ(nullptr, attempter_.error_event_.get());
Darin Petkov1b003102010-11-30 10:18:36 -0800509}
510
511TEST_F(UpdateAttempterTest, ActionCompletedErrorTest) {
Alex Deymo8427b4a2014-11-05 14:00:32 -0800512 MockAction action;
513 EXPECT_CALL(action, Type()).WillRepeatedly(Return("MockAction"));
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700514 attempter_.status_ = UpdateStatus::DOWNLOADING;
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700515 attempter_.ActionCompleted(nullptr, &action, ErrorCode::kError);
516 ASSERT_NE(nullptr, attempter_.error_event_.get());
Darin Petkov1b003102010-11-30 10:18:36 -0800517}
518
Aaron Wood9321f502017-09-07 11:18:54 -0700519TEST_F(UpdateAttempterTest, DownloadProgressAccumulationTest) {
520 // Simple test case, where all the values match (nothing was skipped)
521 uint64_t bytes_progressed_1 = 1024 * 1024; // 1MB
522 uint64_t bytes_progressed_2 = 1024 * 1024; // 1MB
523 uint64_t bytes_received_1 = bytes_progressed_1;
524 uint64_t bytes_received_2 = bytes_received_1 + bytes_progressed_2;
525 uint64_t bytes_total = 20 * 1024 * 1024; // 20MB
526
527 double progress_1 =
528 static_cast<double>(bytes_received_1) / static_cast<double>(bytes_total);
529 double progress_2 =
530 static_cast<double>(bytes_received_2) / static_cast<double>(bytes_total);
531
532 EXPECT_EQ(0.0, attempter_.download_progress_);
533 // This is set via inspecting the InstallPlan payloads when the
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700534 // |OmahaResponseAction| is completed.
Aaron Wood9321f502017-09-07 11:18:54 -0700535 attempter_.new_payload_size_ = bytes_total;
536 NiceMock<MockServiceObserver> observer;
537 EXPECT_CALL(observer,
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700538 SendStatusUpdate(AllOf(
539 Field(&UpdateEngineStatus::progress, progress_1),
540 Field(&UpdateEngineStatus::status, UpdateStatus::DOWNLOADING),
541 Field(&UpdateEngineStatus::new_size_bytes, bytes_total))));
Aaron Wood9321f502017-09-07 11:18:54 -0700542 EXPECT_CALL(observer,
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700543 SendStatusUpdate(AllOf(
544 Field(&UpdateEngineStatus::progress, progress_2),
545 Field(&UpdateEngineStatus::status, UpdateStatus::DOWNLOADING),
546 Field(&UpdateEngineStatus::new_size_bytes, bytes_total))));
Aaron Wood9321f502017-09-07 11:18:54 -0700547 attempter_.AddObserver(&observer);
548 attempter_.BytesReceived(bytes_progressed_1, bytes_received_1, bytes_total);
549 EXPECT_EQ(progress_1, attempter_.download_progress_);
550 // This iteration validates that a later set of updates to the variables are
551 // properly handled (so that |getStatus()| will return the same progress info
552 // as the callback is receiving.
553 attempter_.BytesReceived(bytes_progressed_2, bytes_received_2, bytes_total);
554 EXPECT_EQ(progress_2, attempter_.download_progress_);
555}
556
557TEST_F(UpdateAttempterTest, ChangeToDownloadingOnReceivedBytesTest) {
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700558 // The transition into |UpdateStatus::DOWNLOADING| happens when the
Aaron Wood9321f502017-09-07 11:18:54 -0700559 // first bytes are received.
560 uint64_t bytes_progressed = 1024 * 1024; // 1MB
561 uint64_t bytes_received = 2 * 1024 * 1024; // 2MB
562 uint64_t bytes_total = 20 * 1024 * 1024; // 300MB
563 attempter_.status_ = UpdateStatus::CHECKING_FOR_UPDATE;
564 // This is set via inspecting the InstallPlan payloads when the
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700565 // |OmahaResponseAction| is completed.
Aaron Wood9321f502017-09-07 11:18:54 -0700566 attempter_.new_payload_size_ = bytes_total;
567 EXPECT_EQ(0.0, attempter_.download_progress_);
568 NiceMock<MockServiceObserver> observer;
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700569 EXPECT_CALL(observer,
570 SendStatusUpdate(AllOf(
571 Field(&UpdateEngineStatus::status, UpdateStatus::DOWNLOADING),
572 Field(&UpdateEngineStatus::new_size_bytes, bytes_total))));
Aaron Wood9321f502017-09-07 11:18:54 -0700573 attempter_.AddObserver(&observer);
574 attempter_.BytesReceived(bytes_progressed, bytes_received, bytes_total);
575 EXPECT_EQ(UpdateStatus::DOWNLOADING, attempter_.status_);
576}
577
578TEST_F(UpdateAttempterTest, BroadcastCompleteDownloadTest) {
579 // There is a special case to ensure that at 100% downloaded,
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700580 // |download_progress_| is updated and broadcastest.
Aaron Wood9321f502017-09-07 11:18:54 -0700581 uint64_t bytes_progressed = 0; // ignored
582 uint64_t bytes_received = 5 * 1024 * 1024; // ignored
583 uint64_t bytes_total = 5 * 1024 * 1024; // 300MB
584 attempter_.status_ = UpdateStatus::DOWNLOADING;
585 attempter_.new_payload_size_ = bytes_total;
586 EXPECT_EQ(0.0, attempter_.download_progress_);
587 NiceMock<MockServiceObserver> observer;
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700588 EXPECT_CALL(observer,
589 SendStatusUpdate(AllOf(
590 Field(&UpdateEngineStatus::progress, 1.0),
591 Field(&UpdateEngineStatus::status, UpdateStatus::DOWNLOADING),
592 Field(&UpdateEngineStatus::new_size_bytes, bytes_total))));
Aaron Wood9321f502017-09-07 11:18:54 -0700593 attempter_.AddObserver(&observer);
594 attempter_.BytesReceived(bytes_progressed, bytes_received, bytes_total);
595 EXPECT_EQ(1.0, attempter_.download_progress_);
596}
597
Darin Petkov1b003102010-11-30 10:18:36 -0800598TEST_F(UpdateAttempterTest, ActionCompletedOmahaRequestTest) {
Ben Chan02f7c1d2014-10-18 15:18:02 -0700599 unique_ptr<MockHttpFetcher> fetcher(new MockHttpFetcher("", 0, nullptr));
Darin Petkov1b003102010-11-30 10:18:36 -0800600 fetcher->FailTransfer(500); // Sets the HTTP response code.
Amin Hassani538bd592020-11-04 20:46:08 -0800601 OmahaRequestAction action(nullptr, std::move(fetcher), false, "");
Darin Petkov1b003102010-11-30 10:18:36 -0800602 ObjectCollectorAction<OmahaResponse> collector_action;
603 BondActions(&action, &collector_action);
604 OmahaResponse response;
605 response.poll_interval = 234;
606 action.SetOutputObject(response);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700607 attempter_.ActionCompleted(nullptr, &action, ErrorCode::kSuccess);
Amin Hassani90e9f192020-11-18 14:20:56 -0800608 EXPECT_FALSE(prefs_->Exists(kPrefsDeltaUpdateFailures));
Darin Petkov1b003102010-11-30 10:18:36 -0800609 EXPECT_EQ(500, attempter_.http_response_code());
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700610 EXPECT_EQ(UpdateStatus::IDLE, attempter_.status());
Alex Deymo80f70ff2016-02-10 16:08:11 -0800611 EXPECT_EQ(234U, attempter_.server_dictated_poll_interval_);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700612 ASSERT_TRUE(attempter_.error_event_.get() == nullptr);
Darin Petkov1b003102010-11-30 10:18:36 -0800613}
614
Alex Deymo30534502015-07-20 15:06:33 -0700615TEST_F(UpdateAttempterTest, ConstructWithUpdatedMarkerTest) {
Alex Deymo906191f2015-10-12 12:22:44 -0700616 string boot_id;
617 EXPECT_TRUE(utils::GetBootId(&boot_id));
Amin Hassani90e9f192020-11-18 14:20:56 -0800618 FakeSystemState::Get()->fake_prefs()->SetString(kPrefsUpdateCompletedOnBootId,
619 boot_id);
Sen Jiangaeeb2e02016-06-09 15:00:16 -0700620 attempter_.Init();
621 EXPECT_EQ(UpdateStatus::UPDATED_NEED_REBOOT, attempter_.status());
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700622}
623
624TEST_F(UpdateAttempterTest, GetErrorCodeForActionTest) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700625 EXPECT_EQ(ErrorCode::kSuccess,
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700626 GetErrorCodeForAction(nullptr, ErrorCode::kSuccess));
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700627
Amin Hassani538bd592020-11-04 20:46:08 -0800628 OmahaRequestAction omaha_request_action(nullptr, nullptr, false, "");
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700629 EXPECT_EQ(ErrorCode::kOmahaRequestError,
630 GetErrorCodeForAction(&omaha_request_action, ErrorCode::kError));
Amin Hassani538bd592020-11-04 20:46:08 -0800631 OmahaResponseHandlerAction omaha_response_handler_action;
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800632 EXPECT_EQ(
633 ErrorCode::kOmahaResponseHandlerError,
634 GetErrorCodeForAction(&omaha_response_handler_action, ErrorCode::kError));
Tianjie24f96092020-06-30 12:26:25 -0700635 DynamicPartitionControlStub dynamic_control_stub;
636 FilesystemVerifierAction filesystem_verifier_action(&dynamic_control_stub);
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800637 EXPECT_EQ(
638 ErrorCode::kFilesystemVerifierError,
639 GetErrorCodeForAction(&filesystem_verifier_action, ErrorCode::kError));
Alex Deymob15a0b82015-11-25 20:30:40 -0300640 PostinstallRunnerAction postinstall_runner_action(
Amin Hassani538bd592020-11-04 20:46:08 -0800641 FakeSystemState::Get()->fake_boot_control(),
642 FakeSystemState::Get()->fake_hardware());
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800643 EXPECT_EQ(
644 ErrorCode::kPostinstallRunnerError,
645 GetErrorCodeForAction(&postinstall_runner_action, ErrorCode::kError));
Alex Deymo8427b4a2014-11-05 14:00:32 -0800646 MockAction action_mock;
647 EXPECT_CALL(action_mock, Type()).WillOnce(Return("MockAction"));
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700648 EXPECT_EQ(ErrorCode::kError,
649 GetErrorCodeForAction(&action_mock, ErrorCode::kError));
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700650}
651
Darin Petkov36275772010-10-01 11:40:57 -0700652TEST_F(UpdateAttempterTest, DisableDeltaUpdateIfNeededTest) {
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700653 attempter_.omaha_request_params_->set_delta_okay(true);
Darin Petkov36275772010-10-01 11:40:57 -0700654 attempter_.DisableDeltaUpdateIfNeeded();
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700655 EXPECT_TRUE(attempter_.omaha_request_params_->delta_okay());
Amin Hassani90e9f192020-11-18 14:20:56 -0800656 prefs_->SetInt64(kPrefsDeltaUpdateFailures,
657 UpdateAttempter::kMaxDeltaUpdateFailures - 1);
Darin Petkov36275772010-10-01 11:40:57 -0700658 attempter_.DisableDeltaUpdateIfNeeded();
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700659 EXPECT_TRUE(attempter_.omaha_request_params_->delta_okay());
Amin Hassani90e9f192020-11-18 14:20:56 -0800660 prefs_->SetInt64(kPrefsDeltaUpdateFailures,
661 UpdateAttempter::kMaxDeltaUpdateFailures);
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 attempter_.DisableDeltaUpdateIfNeeded();
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700665 EXPECT_FALSE(attempter_.omaha_request_params_->delta_okay());
Darin Petkov36275772010-10-01 11:40:57 -0700666}
667
668TEST_F(UpdateAttempterTest, MarkDeltaUpdateFailureTest) {
Amin Hassani90e9f192020-11-18 14:20:56 -0800669 attempter_.MarkDeltaUpdateFailure();
670
671 EXPECT_TRUE(prefs_->SetInt64(kPrefsDeltaUpdateFailures, -1));
672 attempter_.MarkDeltaUpdateFailure();
673 int64_t value = 0;
674 EXPECT_TRUE(prefs_->GetInt64(kPrefsDeltaUpdateFailures, &value));
675 EXPECT_EQ(value, 1);
676
677 attempter_.MarkDeltaUpdateFailure();
678 EXPECT_TRUE(prefs_->GetInt64(kPrefsDeltaUpdateFailures, &value));
679 EXPECT_EQ(value, 2);
680
681 EXPECT_TRUE(prefs_->SetInt64(kPrefsDeltaUpdateFailures,
682 UpdateAttempter::kMaxDeltaUpdateFailures));
683 attempter_.MarkDeltaUpdateFailure();
684 EXPECT_TRUE(prefs_->GetInt64(kPrefsDeltaUpdateFailures, &value));
685 EXPECT_EQ(value, UpdateAttempter::kMaxDeltaUpdateFailures + 1);
Darin Petkov36275772010-10-01 11:40:57 -0700686}
687
Darin Petkov1b003102010-11-30 10:18:36 -0800688TEST_F(UpdateAttempterTest, ScheduleErrorEventActionNoEventTest) {
689 EXPECT_CALL(*processor_, EnqueueAction(_)).Times(0);
690 EXPECT_CALL(*processor_, StartProcessing()).Times(0);
Amin Hassani538bd592020-11-04 20:46:08 -0800691 EXPECT_CALL(*FakeSystemState::Get()->mock_payload_state(), UpdateFailed(_))
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800692 .Times(0);
693 OmahaResponse response;
Jay Srinivasan53173b92013-05-17 17:13:01 -0700694 string url1 = "http://url1";
Sen Jiang0affc2c2017-02-10 15:55:05 -0800695 response.packages.push_back({.payload_urls = {url1, "https://url"}});
Amin Hassani538bd592020-11-04 20:46:08 -0800696 EXPECT_CALL(*(FakeSystemState::Get()->mock_payload_state()), GetCurrentUrl())
Jay Srinivasan53173b92013-05-17 17:13:01 -0700697 .WillRepeatedly(Return(url1));
Amin Hassani538bd592020-11-04 20:46:08 -0800698 FakeSystemState::Get()->mock_payload_state()->SetResponse(response);
Darin Petkov1b003102010-11-30 10:18:36 -0800699 attempter_.ScheduleErrorEventAction();
Amin Hassani538bd592020-11-04 20:46:08 -0800700 EXPECT_EQ(url1,
701 FakeSystemState::Get()->mock_payload_state()->GetCurrentUrl());
Darin Petkov1b003102010-11-30 10:18:36 -0800702}
703
704TEST_F(UpdateAttempterTest, ScheduleErrorEventActionTest) {
705 EXPECT_CALL(*processor_,
Amin Hassanid3f4bea2018-04-30 14:52:40 -0700706 EnqueueAction(Pointee(Property(
707 &AbstractAction::Type, OmahaRequestAction::StaticType()))));
Gilad Arnold74b5f552014-10-07 08:17:16 -0700708 EXPECT_CALL(*processor_, StartProcessing());
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700709 ErrorCode err = ErrorCode::kError;
Amin Hassani538bd592020-11-04 20:46:08 -0800710 EXPECT_CALL(*FakeSystemState::Get()->mock_payload_state(), UpdateFailed(err));
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800711 attempter_.error_event_.reset(new OmahaEvent(
712 OmahaEvent::kTypeUpdateComplete, OmahaEvent::kResultError, err));
Darin Petkov1b003102010-11-30 10:18:36 -0800713 attempter_.ScheduleErrorEventAction();
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700714 EXPECT_EQ(UpdateStatus::REPORTING_ERROR_EVENT, attempter_.status());
Darin Petkov1b003102010-11-30 10:18:36 -0800715}
716
Darin Petkove6ef2f82011-03-07 17:31:11 -0800717namespace {
Chris Sosa76a29ae2013-07-11 17:59:24 -0700718// Actions that will be built as part of an update check.
Askar Aitzhan570ca872019-04-24 11:16:12 +0200719vector<string> GetUpdateActionTypes() {
720 return {OmahaRequestAction::StaticType(),
721 OmahaResponseHandlerAction::StaticType(),
722 UpdateBootFlagsAction::StaticType(),
723 OmahaRequestAction::StaticType(),
724 DownloadAction::StaticType(),
725 OmahaRequestAction::StaticType(),
726 FilesystemVerifierAction::StaticType(),
727 PostinstallRunnerAction::StaticType(),
728 OmahaRequestAction::StaticType()};
729}
Chris Sosa76a29ae2013-07-11 17:59:24 -0700730
731// Actions that will be built as part of a user-initiated rollback.
Askar Aitzhan570ca872019-04-24 11:16:12 +0200732vector<string> GetRollbackActionTypes() {
733 return {InstallPlanAction::StaticType(),
734 PostinstallRunnerAction::StaticType()};
735}
Chris Sosa76a29ae2013-07-11 17:59:24 -0700736
Adolfo Victoria497044c2018-07-18 07:51:42 -0700737const StagingSchedule kValidStagingSchedule = {
738 {4, 10}, {10, 40}, {19, 70}, {26, 100}};
739
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700740} // namespace
Darin Petkove6ef2f82011-03-07 17:31:11 -0800741
742void UpdateAttempterTest::UpdateTestStart() {
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700743 attempter_.set_http_response_code(200);
Alex Deymo749ecf12014-10-21 20:06:57 -0700744
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700745 // Expect that the device policy is loaded by the |UpdateAttempter| at some
746 // point by calling |RefreshDevicePolicy()|.
Igor9fd76b62017-12-11 15:24:18 +0100747 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Alex Deymo749ecf12014-10-21 20:06:57 -0700748 EXPECT_CALL(*device_policy, LoadPolicy())
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800749 .Times(testing::AtLeast(1))
750 .WillRepeatedly(Return(true));
Igor9fd76b62017-12-11 15:24:18 +0100751 attempter_.policy_provider_.reset(
752 new policy::PolicyProvider(std::move(device_policy)));
Alex Deymo749ecf12014-10-21 20:06:57 -0700753
754 {
755 InSequence s;
Askar Aitzhan570ca872019-04-24 11:16:12 +0200756 for (const auto& update_action_type : GetUpdateActionTypes()) {
Alex Deymo749ecf12014-10-21 20:06:57 -0700757 EXPECT_CALL(*processor_,
Amin Hassanid3f4bea2018-04-30 14:52:40 -0700758 EnqueueAction(Pointee(
Askar Aitzhan570ca872019-04-24 11:16:12 +0200759 Property(&AbstractAction::Type, update_action_type))));
Alex Deymo749ecf12014-10-21 20:06:57 -0700760 }
Gilad Arnold74b5f552014-10-07 08:17:16 -0700761 EXPECT_CALL(*processor_, StartProcessing());
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700762 }
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700763
Amin Hassanie8153632020-10-27 15:11:28 -0700764 attempter_.Update({});
Alex Deymo60ca1a72015-06-18 18:19:15 -0700765 loop_.PostTask(FROM_HERE,
766 base::Bind(&UpdateAttempterTest::UpdateTestVerify,
767 base::Unretained(this)));
Darin Petkove6ef2f82011-03-07 17:31:11 -0800768}
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700769
Darin Petkove6ef2f82011-03-07 17:31:11 -0800770void UpdateAttempterTest::UpdateTestVerify() {
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700771 EXPECT_EQ(0, attempter_.http_response_code());
772 EXPECT_EQ(&attempter_, processor_->delegate());
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700773 EXPECT_EQ(UpdateStatus::CHECKING_FOR_UPDATE, attempter_.status());
Alex Deymo60ca1a72015-06-18 18:19:15 -0700774 loop_.BreakLoop();
Darin Petkove6ef2f82011-03-07 17:31:11 -0800775}
776
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800777void UpdateAttempterTest::RollbackTestStart(bool enterprise_rollback,
778 bool valid_slot) {
Chris Sosa76a29ae2013-07-11 17:59:24 -0700779 // Create a device policy so that we can change settings.
Igor9fd76b62017-12-11 15:24:18 +0100780 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Chris Sosa76a29ae2013-07-11 17:59:24 -0700781 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
Amin Hassani538bd592020-11-04 20:46:08 -0800782 FakeSystemState::Get()->set_device_policy(device_policy.get());
Igor9fd76b62017-12-11 15:24:18 +0100783 if (enterprise_rollback) {
784 // We return an empty owner as this is an enterprise.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800785 EXPECT_CALL(*device_policy, GetOwner(_))
786 .WillRepeatedly(DoAll(SetArgPointee<0>(string("")), Return(true)));
Igor9fd76b62017-12-11 15:24:18 +0100787 } else {
788 // We return a fake owner as this is an owned consumer device.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800789 EXPECT_CALL(*device_policy, GetOwner(_))
790 .WillRepeatedly(DoAll(SetArgPointee<0>(string("fake.mail@fake.com")),
791 Return(true)));
Igor9fd76b62017-12-11 15:24:18 +0100792 }
793
794 attempter_.policy_provider_.reset(
795 new policy::PolicyProvider(std::move(device_policy)));
Chris Sosa76a29ae2013-07-11 17:59:24 -0700796
Alex Deymo763e7db2015-08-27 21:08:08 -0700797 if (valid_slot) {
798 BootControlInterface::Slot rollback_slot = 1;
799 LOG(INFO) << "Test Mark Bootable: "
800 << BootControlInterface::SlotName(rollback_slot);
Amin Hassani538bd592020-11-04 20:46:08 -0800801 FakeSystemState::Get()->fake_boot_control()->SetSlotBootable(rollback_slot,
802 true);
Don Garrett6646b442013-11-13 15:29:11 -0800803 }
804
Chris Sosa28e479c2013-07-12 11:39:53 -0700805 bool is_rollback_allowed = false;
Chris Sosa76a29ae2013-07-11 17:59:24 -0700806
Chris Sosad38b1132014-03-25 10:43:59 -0700807 // We only allow rollback on devices that are not enterprise enrolled and
808 // which have a valid slot to rollback to.
809 if (!enterprise_rollback && valid_slot) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800810 is_rollback_allowed = true;
Chris Sosa28e479c2013-07-12 11:39:53 -0700811 }
812
Chris Sosa28e479c2013-07-12 11:39:53 -0700813 if (is_rollback_allowed) {
Chris Sosa76a29ae2013-07-11 17:59:24 -0700814 InSequence s;
Askar Aitzhan570ca872019-04-24 11:16:12 +0200815 for (const auto& rollback_action_type : GetRollbackActionTypes()) {
Chris Sosa76a29ae2013-07-11 17:59:24 -0700816 EXPECT_CALL(*processor_,
Askar Aitzhan570ca872019-04-24 11:16:12 +0200817 EnqueueAction(Pointee(
818 Property(&AbstractAction::Type, rollback_action_type))));
Chris Sosa76a29ae2013-07-11 17:59:24 -0700819 }
Gilad Arnold74b5f552014-10-07 08:17:16 -0700820 EXPECT_CALL(*processor_, StartProcessing());
Chris Sosa76a29ae2013-07-11 17:59:24 -0700821
Chris Sosa44b9b7e2014-04-02 13:53:46 -0700822 EXPECT_TRUE(attempter_.Rollback(true));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700823 loop_.PostTask(FROM_HERE,
824 base::Bind(&UpdateAttempterTest::RollbackTestVerify,
825 base::Unretained(this)));
Chris Sosa76a29ae2013-07-11 17:59:24 -0700826 } else {
Chris Sosa44b9b7e2014-04-02 13:53:46 -0700827 EXPECT_FALSE(attempter_.Rollback(true));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700828 loop_.BreakLoop();
Chris Sosa76a29ae2013-07-11 17:59:24 -0700829 }
830}
831
832void UpdateAttempterTest::RollbackTestVerify() {
833 // Verifies the actions that were enqueued.
834 EXPECT_EQ(&attempter_, processor_->delegate());
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700835 EXPECT_EQ(UpdateStatus::ATTEMPTING_ROLLBACK, attempter_.status());
Amin Hassanid3f4bea2018-04-30 14:52:40 -0700836 EXPECT_EQ(0U, attempter_.install_plan_->partitions.size());
837 EXPECT_EQ(attempter_.install_plan_->powerwash_required, true);
Alex Deymo60ca1a72015-06-18 18:19:15 -0700838 loop_.BreakLoop();
Chris Sosa76a29ae2013-07-11 17:59:24 -0700839}
840
Darin Petkove6ef2f82011-03-07 17:31:11 -0800841TEST_F(UpdateAttempterTest, UpdateTest) {
Alex Deymo461b2592015-07-24 20:10:52 -0700842 UpdateTestStart();
Alex Deymo60ca1a72015-06-18 18:19:15 -0700843 loop_.Run();
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700844}
845
Chris Sosa76a29ae2013-07-11 17:59:24 -0700846TEST_F(UpdateAttempterTest, RollbackTest) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700847 loop_.PostTask(FROM_HERE,
848 base::Bind(&UpdateAttempterTest::RollbackTestStart,
849 base::Unretained(this),
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800850 false,
851 true));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700852 loop_.Run();
Chris Sosa76a29ae2013-07-11 17:59:24 -0700853}
854
Don Garrett6646b442013-11-13 15:29:11 -0800855TEST_F(UpdateAttempterTest, InvalidSlotRollbackTest) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700856 loop_.PostTask(FROM_HERE,
857 base::Bind(&UpdateAttempterTest::RollbackTestStart,
858 base::Unretained(this),
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800859 false,
860 false));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700861 loop_.Run();
Don Garrett6646b442013-11-13 15:29:11 -0800862}
863
Chris Sosa76a29ae2013-07-11 17:59:24 -0700864TEST_F(UpdateAttempterTest, EnterpriseRollbackTest) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700865 loop_.PostTask(FROM_HERE,
866 base::Bind(&UpdateAttempterTest::RollbackTestStart,
867 base::Unretained(this),
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800868 true,
869 true));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700870 loop_.Run();
Chris Sosa76a29ae2013-07-11 17:59:24 -0700871}
872
Thieu Le116fda32011-04-19 11:01:54 -0700873void UpdateAttempterTest::PingOmahaTestStart() {
874 EXPECT_CALL(*processor_,
Amin Hassanid3f4bea2018-04-30 14:52:40 -0700875 EnqueueAction(Pointee(Property(
876 &AbstractAction::Type, OmahaRequestAction::StaticType()))));
Gilad Arnold74b5f552014-10-07 08:17:16 -0700877 EXPECT_CALL(*processor_, StartProcessing());
Thieu Le116fda32011-04-19 11:01:54 -0700878 attempter_.PingOmaha();
Alex Deymo60ca1a72015-06-18 18:19:15 -0700879 ScheduleQuitMainLoop();
Thieu Le116fda32011-04-19 11:01:54 -0700880}
881
882TEST_F(UpdateAttempterTest, PingOmahaTest) {
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700883 EXPECT_FALSE(attempter_.waiting_for_scheduled_check_);
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700884 EXPECT_FALSE(attempter_.WasScheduleUpdatesCalled());
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700885 // Disable scheduling of subsequnet checks; we're using the |DefaultPolicy| in
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700886 // testing, which is more permissive than we want to handle here.
887 attempter_.DisableScheduleUpdates();
Alex Deymo60ca1a72015-06-18 18:19:15 -0700888 loop_.PostTask(FROM_HERE,
889 base::Bind(&UpdateAttempterTest::PingOmahaTestStart,
890 base::Unretained(this)));
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700891 brillo::MessageLoopRunMaxIterations(&loop_, 100);
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700892 EXPECT_EQ(UpdateStatus::UPDATED_NEED_REBOOT, attempter_.status());
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700893 EXPECT_TRUE(attempter_.WasScheduleUpdatesCalled());
Thieu Le116fda32011-04-19 11:01:54 -0700894}
895
Darin Petkov18c7bce2011-06-16 14:07:00 -0700896TEST_F(UpdateAttempterTest, CreatePendingErrorEventTest) {
Alex Deymo8427b4a2014-11-05 14:00:32 -0800897 MockAction action;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700898 const ErrorCode kCode = ErrorCode::kDownloadTransferError;
Darin Petkov18c7bce2011-06-16 14:07:00 -0700899 attempter_.CreatePendingErrorEvent(&action, kCode);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700900 ASSERT_NE(nullptr, attempter_.error_event_.get());
Darin Petkov18c7bce2011-06-16 14:07:00 -0700901 EXPECT_EQ(OmahaEvent::kTypeUpdateComplete, attempter_.error_event_->type);
902 EXPECT_EQ(OmahaEvent::kResultError, attempter_.error_event_->result);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700903 EXPECT_EQ(
904 static_cast<ErrorCode>(static_cast<int>(kCode) |
905 static_cast<int>(ErrorCode::kTestOmahaUrlFlag)),
906 attempter_.error_event_->error_code);
Darin Petkov18c7bce2011-06-16 14:07:00 -0700907}
908
909TEST_F(UpdateAttempterTest, CreatePendingErrorEventResumedTest) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -0700910 attempter_.install_plan_.reset(new InstallPlan);
911 attempter_.install_plan_->is_resume = true;
Alex Deymo8427b4a2014-11-05 14:00:32 -0800912 MockAction action;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700913 const ErrorCode kCode = ErrorCode::kInstallDeviceOpenError;
Darin Petkov18c7bce2011-06-16 14:07:00 -0700914 attempter_.CreatePendingErrorEvent(&action, kCode);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700915 ASSERT_NE(nullptr, attempter_.error_event_.get());
Darin Petkov18c7bce2011-06-16 14:07:00 -0700916 EXPECT_EQ(OmahaEvent::kTypeUpdateComplete, attempter_.error_event_->type);
917 EXPECT_EQ(OmahaEvent::kResultError, attempter_.error_event_->result);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700918 EXPECT_EQ(
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800919 static_cast<ErrorCode>(static_cast<int>(kCode) |
920 static_cast<int>(ErrorCode::kResumedFlag) |
921 static_cast<int>(ErrorCode::kTestOmahaUrlFlag)),
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700922 attempter_.error_event_->error_code);
Darin Petkov18c7bce2011-06-16 14:07:00 -0700923}
924
David Zeuthen8f191b22013-08-06 12:27:50 -0700925TEST_F(UpdateAttempterTest, P2PNotStartedAtStartupWhenNotEnabled) {
926 MockP2PManager mock_p2p_manager;
Amin Hassani538bd592020-11-04 20:46:08 -0800927 FakeSystemState::Get()->set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -0700928 mock_p2p_manager.fake().SetP2PEnabled(false);
929 EXPECT_CALL(mock_p2p_manager, EnsureP2PRunning()).Times(0);
930 attempter_.UpdateEngineStarted();
931}
932
933TEST_F(UpdateAttempterTest, P2PNotStartedAtStartupWhenEnabledButNotSharing) {
934 MockP2PManager mock_p2p_manager;
Amin Hassani538bd592020-11-04 20:46:08 -0800935 FakeSystemState::Get()->set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -0700936 mock_p2p_manager.fake().SetP2PEnabled(true);
937 EXPECT_CALL(mock_p2p_manager, EnsureP2PRunning()).Times(0);
938 attempter_.UpdateEngineStarted();
939}
940
941TEST_F(UpdateAttempterTest, P2PStartedAtStartupWhenEnabledAndSharing) {
942 MockP2PManager mock_p2p_manager;
Amin Hassani538bd592020-11-04 20:46:08 -0800943 FakeSystemState::Get()->set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -0700944 mock_p2p_manager.fake().SetP2PEnabled(true);
945 mock_p2p_manager.fake().SetCountSharedFilesResult(1);
Gilad Arnold74b5f552014-10-07 08:17:16 -0700946 EXPECT_CALL(mock_p2p_manager, EnsureP2PRunning());
David Zeuthen8f191b22013-08-06 12:27:50 -0700947 attempter_.UpdateEngineStarted();
948}
949
950TEST_F(UpdateAttempterTest, P2PNotEnabled) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700951 loop_.PostTask(FROM_HERE,
952 base::Bind(&UpdateAttempterTest::P2PNotEnabledStart,
953 base::Unretained(this)));
954 loop_.Run();
David Zeuthen8f191b22013-08-06 12:27:50 -0700955}
Alex Deymo60ca1a72015-06-18 18:19:15 -0700956
David Zeuthen8f191b22013-08-06 12:27:50 -0700957void UpdateAttempterTest::P2PNotEnabledStart() {
958 // If P2P is not enabled, check that we do not attempt housekeeping
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700959 // and do not convey that P2P is to be used.
David Zeuthen8f191b22013-08-06 12:27:50 -0700960 MockP2PManager mock_p2p_manager;
Amin Hassani538bd592020-11-04 20:46:08 -0800961 FakeSystemState::Get()->set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -0700962 mock_p2p_manager.fake().SetP2PEnabled(false);
963 EXPECT_CALL(mock_p2p_manager, PerformHousekeeping()).Times(0);
Amin Hassanie8153632020-10-27 15:11:28 -0700964 attempter_.Update({});
Alex Deymo60ca1a72015-06-18 18:19:15 -0700965 EXPECT_FALSE(actual_using_p2p_for_downloading_);
Gilad Arnold74b5f552014-10-07 08:17:16 -0700966 EXPECT_FALSE(actual_using_p2p_for_sharing());
Alex Deymo60ca1a72015-06-18 18:19:15 -0700967 ScheduleQuitMainLoop();
David Zeuthen8f191b22013-08-06 12:27:50 -0700968}
969
970TEST_F(UpdateAttempterTest, P2PEnabledStartingFails) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700971 loop_.PostTask(FROM_HERE,
972 base::Bind(&UpdateAttempterTest::P2PEnabledStartingFailsStart,
973 base::Unretained(this)));
974 loop_.Run();
David Zeuthen8f191b22013-08-06 12:27:50 -0700975}
Alex Deymo60ca1a72015-06-18 18:19:15 -0700976
David Zeuthen8f191b22013-08-06 12:27:50 -0700977void UpdateAttempterTest::P2PEnabledStartingFailsStart() {
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700978 // If P2P is enabled, but starting it fails ensure we don't do
979 // any housekeeping and do not convey that P2P should be used.
David Zeuthen8f191b22013-08-06 12:27:50 -0700980 MockP2PManager mock_p2p_manager;
Amin Hassani538bd592020-11-04 20:46:08 -0800981 FakeSystemState::Get()->set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -0700982 mock_p2p_manager.fake().SetP2PEnabled(true);
983 mock_p2p_manager.fake().SetEnsureP2PRunningResult(false);
984 mock_p2p_manager.fake().SetPerformHousekeepingResult(false);
985 EXPECT_CALL(mock_p2p_manager, PerformHousekeeping()).Times(0);
Amin Hassanie8153632020-10-27 15:11:28 -0700986 attempter_.Update({});
Gilad Arnold74b5f552014-10-07 08:17:16 -0700987 EXPECT_FALSE(actual_using_p2p_for_downloading());
988 EXPECT_FALSE(actual_using_p2p_for_sharing());
Alex Deymo60ca1a72015-06-18 18:19:15 -0700989 ScheduleQuitMainLoop();
David Zeuthen8f191b22013-08-06 12:27:50 -0700990}
991
992TEST_F(UpdateAttempterTest, P2PEnabledHousekeepingFails) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700993 loop_.PostTask(
994 FROM_HERE,
995 base::Bind(&UpdateAttempterTest::P2PEnabledHousekeepingFailsStart,
996 base::Unretained(this)));
997 loop_.Run();
David Zeuthen8f191b22013-08-06 12:27:50 -0700998}
Alex Deymo60ca1a72015-06-18 18:19:15 -0700999
David Zeuthen8f191b22013-08-06 12:27:50 -07001000void UpdateAttempterTest::P2PEnabledHousekeepingFailsStart() {
Jae Hoon Kimedb65502019-06-14 11:52:17 -07001001 // If P2P is enabled, starting it works but housekeeping fails, ensure
1002 // we do not convey P2P is to be used.
David Zeuthen8f191b22013-08-06 12:27:50 -07001003 MockP2PManager mock_p2p_manager;
Amin Hassani538bd592020-11-04 20:46:08 -08001004 FakeSystemState::Get()->set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -07001005 mock_p2p_manager.fake().SetP2PEnabled(true);
1006 mock_p2p_manager.fake().SetEnsureP2PRunningResult(true);
1007 mock_p2p_manager.fake().SetPerformHousekeepingResult(false);
Gilad Arnold74b5f552014-10-07 08:17:16 -07001008 EXPECT_CALL(mock_p2p_manager, PerformHousekeeping());
Amin Hassanie8153632020-10-27 15:11:28 -07001009 attempter_.Update({});
Gilad Arnold74b5f552014-10-07 08:17:16 -07001010 EXPECT_FALSE(actual_using_p2p_for_downloading());
1011 EXPECT_FALSE(actual_using_p2p_for_sharing());
Alex Deymo60ca1a72015-06-18 18:19:15 -07001012 ScheduleQuitMainLoop();
David Zeuthen8f191b22013-08-06 12:27:50 -07001013}
1014
1015TEST_F(UpdateAttempterTest, P2PEnabled) {
Alex Deymo60ca1a72015-06-18 18:19:15 -07001016 loop_.PostTask(FROM_HERE,
1017 base::Bind(&UpdateAttempterTest::P2PEnabledStart,
1018 base::Unretained(this)));
1019 loop_.Run();
David Zeuthen8f191b22013-08-06 12:27:50 -07001020}
Alex Deymo60ca1a72015-06-18 18:19:15 -07001021
David Zeuthen8f191b22013-08-06 12:27:50 -07001022void UpdateAttempterTest::P2PEnabledStart() {
1023 MockP2PManager mock_p2p_manager;
Amin Hassani538bd592020-11-04 20:46:08 -08001024 FakeSystemState::Get()->set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -07001025 // If P2P is enabled and starting it works, check that we performed
Jae Hoon Kimedb65502019-06-14 11:52:17 -07001026 // housekeeping and that we convey P2P should be used.
David Zeuthen8f191b22013-08-06 12:27:50 -07001027 mock_p2p_manager.fake().SetP2PEnabled(true);
1028 mock_p2p_manager.fake().SetEnsureP2PRunningResult(true);
1029 mock_p2p_manager.fake().SetPerformHousekeepingResult(true);
Gilad Arnold74b5f552014-10-07 08:17:16 -07001030 EXPECT_CALL(mock_p2p_manager, PerformHousekeeping());
Amin Hassanie8153632020-10-27 15:11:28 -07001031 attempter_.Update({});
Gilad Arnold74b5f552014-10-07 08:17:16 -07001032 EXPECT_TRUE(actual_using_p2p_for_downloading());
1033 EXPECT_TRUE(actual_using_p2p_for_sharing());
Alex Deymo60ca1a72015-06-18 18:19:15 -07001034 ScheduleQuitMainLoop();
David Zeuthen8f191b22013-08-06 12:27:50 -07001035}
1036
1037TEST_F(UpdateAttempterTest, P2PEnabledInteractive) {
Alex Deymo60ca1a72015-06-18 18:19:15 -07001038 loop_.PostTask(FROM_HERE,
1039 base::Bind(&UpdateAttempterTest::P2PEnabledInteractiveStart,
1040 base::Unretained(this)));
1041 loop_.Run();
David Zeuthen8f191b22013-08-06 12:27:50 -07001042}
Alex Deymo60ca1a72015-06-18 18:19:15 -07001043
David Zeuthen8f191b22013-08-06 12:27:50 -07001044void UpdateAttempterTest::P2PEnabledInteractiveStart() {
1045 MockP2PManager mock_p2p_manager;
Amin Hassani538bd592020-11-04 20:46:08 -08001046 FakeSystemState::Get()->set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -07001047 // For an interactive check, if P2P is enabled and starting it
1048 // works, check that we performed housekeeping and that we convey
Jae Hoon Kimedb65502019-06-14 11:52:17 -07001049 // P2P should be used for sharing but NOT for downloading.
David Zeuthen8f191b22013-08-06 12:27:50 -07001050 mock_p2p_manager.fake().SetP2PEnabled(true);
1051 mock_p2p_manager.fake().SetEnsureP2PRunningResult(true);
1052 mock_p2p_manager.fake().SetPerformHousekeepingResult(true);
Gilad Arnold74b5f552014-10-07 08:17:16 -07001053 EXPECT_CALL(mock_p2p_manager, PerformHousekeeping());
Amin Hassanie8153632020-10-27 15:11:28 -07001054 attempter_.Update({.interactive = true});
Gilad Arnold74b5f552014-10-07 08:17:16 -07001055 EXPECT_FALSE(actual_using_p2p_for_downloading());
1056 EXPECT_TRUE(actual_using_p2p_for_sharing());
Alex Deymo60ca1a72015-06-18 18:19:15 -07001057 ScheduleQuitMainLoop();
David Zeuthen8f191b22013-08-06 12:27:50 -07001058}
1059
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001060TEST_F(UpdateAttempterTest, ReadScatterFactorFromPolicy) {
Alex Deymo60ca1a72015-06-18 18:19:15 -07001061 loop_.PostTask(
1062 FROM_HERE,
1063 base::Bind(&UpdateAttempterTest::ReadScatterFactorFromPolicyTestStart,
1064 base::Unretained(this)));
1065 loop_.Run();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001066}
1067
1068// Tests that the scatter_factor_in_seconds value is properly fetched
1069// from the device policy.
1070void UpdateAttempterTest::ReadScatterFactorFromPolicyTestStart() {
Ben Chan9abb7632014-08-07 00:10:53 -07001071 int64_t scatter_factor_in_seconds = 36000;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001072
Igor9fd76b62017-12-11 15:24:18 +01001073 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001074 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
Amin Hassani538bd592020-11-04 20:46:08 -08001075 FakeSystemState::Get()->set_device_policy(device_policy.get());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001076
1077 EXPECT_CALL(*device_policy, GetScatterFactorInSeconds(_))
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001078 .WillRepeatedly(
1079 DoAll(SetArgPointee<0>(scatter_factor_in_seconds), Return(true)));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001080
Igor9fd76b62017-12-11 15:24:18 +01001081 attempter_.policy_provider_.reset(
1082 new policy::PolicyProvider(std::move(device_policy)));
1083
Amin Hassanie8153632020-10-27 15:11:28 -07001084 attempter_.Update({});
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001085 EXPECT_EQ(scatter_factor_in_seconds, attempter_.scatter_factor_.InSeconds());
1086
Alex Deymo60ca1a72015-06-18 18:19:15 -07001087 ScheduleQuitMainLoop();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001088}
1089
1090TEST_F(UpdateAttempterTest, DecrementUpdateCheckCountTest) {
Alex Deymo60ca1a72015-06-18 18:19:15 -07001091 loop_.PostTask(
1092 FROM_HERE,
1093 base::Bind(&UpdateAttempterTest::DecrementUpdateCheckCountTestStart,
1094 base::Unretained(this)));
1095 loop_.Run();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001096}
1097
1098void UpdateAttempterTest::DecrementUpdateCheckCountTestStart() {
1099 // Tests that the scatter_factor_in_seconds value is properly fetched
1100 // from the device policy and is decremented if value > 0.
Ben Chan9abb7632014-08-07 00:10:53 -07001101 int64_t initial_value = 5;
Amin Hassani90e9f192020-11-18 14:20:56 -08001102 auto* fake_prefs = FakeSystemState::Get()->fake_prefs();
Amin Hassani538bd592020-11-04 20:46:08 -08001103 FakeSystemState::Get()->fake_hardware()->SetIsOOBEComplete(Time::UnixEpoch());
Jay Srinivasan08fce042012-06-07 16:31:01 -07001104
Amin Hassani90e9f192020-11-18 14:20:56 -08001105 EXPECT_TRUE(fake_prefs->SetInt64(kPrefsUpdateCheckCount, initial_value));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001106
Ben Chan9abb7632014-08-07 00:10:53 -07001107 int64_t scatter_factor_in_seconds = 10;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001108
Igor9fd76b62017-12-11 15:24:18 +01001109 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001110 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
Amin Hassani538bd592020-11-04 20:46:08 -08001111 FakeSystemState::Get()->set_device_policy(device_policy.get());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001112
1113 EXPECT_CALL(*device_policy, GetScatterFactorInSeconds(_))
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001114 .WillRepeatedly(
1115 DoAll(SetArgPointee<0>(scatter_factor_in_seconds), Return(true)));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001116
Igor9fd76b62017-12-11 15:24:18 +01001117 attempter_.policy_provider_.reset(
1118 new policy::PolicyProvider(std::move(device_policy)));
1119
Amin Hassanie8153632020-10-27 15:11:28 -07001120 attempter_.Update({});
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001121 EXPECT_EQ(scatter_factor_in_seconds, attempter_.scatter_factor_.InSeconds());
1122
1123 // Make sure the file still exists.
Amin Hassani90e9f192020-11-18 14:20:56 -08001124 EXPECT_TRUE(fake_prefs->Exists(kPrefsUpdateCheckCount));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001125
Ben Chan9abb7632014-08-07 00:10:53 -07001126 int64_t new_value;
Amin Hassani90e9f192020-11-18 14:20:56 -08001127 EXPECT_TRUE(fake_prefs->GetInt64(kPrefsUpdateCheckCount, &new_value));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001128 EXPECT_EQ(initial_value - 1, new_value);
1129
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001130 EXPECT_TRUE(
1131 attempter_.omaha_request_params_->update_check_count_wait_enabled());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001132
1133 // However, if the count is already 0, it's not decremented. Test that.
1134 initial_value = 0;
Amin Hassani90e9f192020-11-18 14:20:56 -08001135 EXPECT_TRUE(fake_prefs->SetInt64(kPrefsUpdateCheckCount, initial_value));
Amin Hassanie8153632020-10-27 15:11:28 -07001136 attempter_.Update({});
Amin Hassani90e9f192020-11-18 14:20:56 -08001137 EXPECT_TRUE(fake_prefs->Exists(kPrefsUpdateCheckCount));
1138 EXPECT_TRUE(fake_prefs->GetInt64(kPrefsUpdateCheckCount, &new_value));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001139 EXPECT_EQ(initial_value, new_value);
1140
Alex Deymo60ca1a72015-06-18 18:19:15 -07001141 ScheduleQuitMainLoop();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001142}
1143
Jay Srinivasan08fce042012-06-07 16:31:01 -07001144TEST_F(UpdateAttempterTest, NoScatteringDoneDuringManualUpdateTestStart) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001145 loop_.PostTask(
1146 FROM_HERE,
1147 base::Bind(
1148 &UpdateAttempterTest::NoScatteringDoneDuringManualUpdateTestStart,
1149 base::Unretained(this)));
Alex Deymo60ca1a72015-06-18 18:19:15 -07001150 loop_.Run();
Jay Srinivasan08fce042012-06-07 16:31:01 -07001151}
1152
1153void UpdateAttempterTest::NoScatteringDoneDuringManualUpdateTestStart() {
1154 // Tests that no scattering logic is enabled if the update check
1155 // is manually done (as opposed to a scheduled update check)
Ben Chan9abb7632014-08-07 00:10:53 -07001156 int64_t initial_value = 8;
Amin Hassani90e9f192020-11-18 14:20:56 -08001157 auto* fake_prefs = FakeSystemState::Get()->fake_prefs();
Amin Hassani538bd592020-11-04 20:46:08 -08001158 FakeSystemState::Get()->fake_hardware()->SetIsOOBEComplete(Time::UnixEpoch());
Jay Srinivasan08fce042012-06-07 16:31:01 -07001159
Adolfo Victoriad3a1e352018-07-16 11:40:47 -07001160 EXPECT_TRUE(
Amin Hassani90e9f192020-11-18 14:20:56 -08001161 fake_prefs->SetInt64(kPrefsWallClockScatteringWaitPeriod, initial_value));
1162 EXPECT_TRUE(fake_prefs->SetInt64(kPrefsUpdateCheckCount, initial_value));
Jay Srinivasan08fce042012-06-07 16:31:01 -07001163
1164 // make sure scatter_factor is non-zero as scattering is disabled
1165 // otherwise.
Ben Chan9abb7632014-08-07 00:10:53 -07001166 int64_t scatter_factor_in_seconds = 50;
Jay Srinivasan08fce042012-06-07 16:31:01 -07001167
Igor9fd76b62017-12-11 15:24:18 +01001168 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Jay Srinivasan08fce042012-06-07 16:31:01 -07001169 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
Amin Hassani538bd592020-11-04 20:46:08 -08001170 FakeSystemState::Get()->set_device_policy(device_policy.get());
Jay Srinivasan08fce042012-06-07 16:31:01 -07001171
1172 EXPECT_CALL(*device_policy, GetScatterFactorInSeconds(_))
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001173 .WillRepeatedly(
1174 DoAll(SetArgPointee<0>(scatter_factor_in_seconds), Return(true)));
Jay Srinivasan08fce042012-06-07 16:31:01 -07001175
Igor9fd76b62017-12-11 15:24:18 +01001176 attempter_.policy_provider_.reset(
1177 new policy::PolicyProvider(std::move(device_policy)));
1178
Gilad Arnoldb92f0df2013-01-10 16:32:45 -08001179 // Trigger an interactive check so we can test that scattering is disabled.
Amin Hassanie8153632020-10-27 15:11:28 -07001180 attempter_.Update({.interactive = true});
Jay Srinivasan08fce042012-06-07 16:31:01 -07001181 EXPECT_EQ(scatter_factor_in_seconds, attempter_.scatter_factor_.InSeconds());
1182
1183 // Make sure scattering is disabled for manual (i.e. user initiated) update
Jay Srinivasan21be0752012-07-25 15:44:56 -07001184 // checks and all artifacts are removed.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001185 EXPECT_FALSE(
1186 attempter_.omaha_request_params_->wall_clock_based_wait_enabled());
Amin Hassani90e9f192020-11-18 14:20:56 -08001187 EXPECT_FALSE(fake_prefs->Exists(kPrefsWallClockScatteringWaitPeriod));
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001188 EXPECT_EQ(0, attempter_.omaha_request_params_->waiting_period().InSeconds());
1189 EXPECT_FALSE(
1190 attempter_.omaha_request_params_->update_check_count_wait_enabled());
Amin Hassani90e9f192020-11-18 14:20:56 -08001191 EXPECT_FALSE(fake_prefs->Exists(kPrefsUpdateCheckCount));
Jay Srinivasan08fce042012-06-07 16:31:01 -07001192
Alex Deymo60ca1a72015-06-18 18:19:15 -07001193 ScheduleQuitMainLoop();
Jay Srinivasan08fce042012-06-07 16:31:01 -07001194}
1195
Amin Hassani90e9f192020-11-18 14:20:56 -08001196void UpdateAttempterTest::SetUpStagingTest(const StagingSchedule& schedule) {
Adolfo Victoria497044c2018-07-18 07:51:42 -07001197 int64_t initial_value = 8;
1198 EXPECT_TRUE(
Amin Hassani90e9f192020-11-18 14:20:56 -08001199 prefs_->SetInt64(kPrefsWallClockScatteringWaitPeriod, initial_value));
1200 EXPECT_TRUE(prefs_->SetInt64(kPrefsUpdateCheckCount, initial_value));
Adolfo Victoria497044c2018-07-18 07:51:42 -07001201 attempter_.scatter_factor_ = TimeDelta::FromSeconds(20);
1202
1203 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
1204 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
Amin Hassani538bd592020-11-04 20:46:08 -08001205 FakeSystemState::Get()->set_device_policy(device_policy.get());
Adolfo Victoria497044c2018-07-18 07:51:42 -07001206 EXPECT_CALL(*device_policy, GetDeviceUpdateStagingSchedule(_))
1207 .WillRepeatedly(DoAll(SetArgPointee<0>(schedule), Return(true)));
1208
1209 attempter_.policy_provider_.reset(
1210 new policy::PolicyProvider(std::move(device_policy)));
1211}
1212
1213TEST_F(UpdateAttempterTest, StagingSetsPrefsAndTurnsOffScattering) {
1214 loop_.PostTask(
1215 FROM_HERE,
1216 base::Bind(
1217 &UpdateAttempterTest::StagingSetsPrefsAndTurnsOffScatteringStart,
1218 base::Unretained(this)));
1219 loop_.Run();
1220}
1221
1222void UpdateAttempterTest::StagingSetsPrefsAndTurnsOffScatteringStart() {
1223 // Tests that staging sets its prefs properly and turns off scattering.
Amin Hassani538bd592020-11-04 20:46:08 -08001224 FakeSystemState::Get()->fake_hardware()->SetIsOOBEComplete(Time::UnixEpoch());
Amin Hassani90e9f192020-11-18 14:20:56 -08001225 SetUpStagingTest(kValidStagingSchedule);
Adolfo Victoria497044c2018-07-18 07:51:42 -07001226
Amin Hassanie8153632020-10-27 15:11:28 -07001227 attempter_.Update({});
Amin Hassani90e9f192020-11-18 14:20:56 -08001228 auto* fake_prefs = FakeSystemState::Get()->fake_prefs();
Adolfo Victoria497044c2018-07-18 07:51:42 -07001229 // Check that prefs have the correct values.
1230 int64_t update_count;
Amin Hassani90e9f192020-11-18 14:20:56 -08001231 EXPECT_TRUE(fake_prefs->GetInt64(kPrefsUpdateCheckCount, &update_count));
Adolfo Victoria497044c2018-07-18 07:51:42 -07001232 int64_t waiting_time_days;
Amin Hassani90e9f192020-11-18 14:20:56 -08001233 EXPECT_TRUE(fake_prefs->GetInt64(kPrefsWallClockStagingWaitPeriod,
1234 &waiting_time_days));
Adolfo Victoria497044c2018-07-18 07:51:42 -07001235 EXPECT_GT(waiting_time_days, 0);
1236 // Update count should have been decremented.
1237 EXPECT_EQ(7, update_count);
1238 // Check that Omaha parameters were updated correctly.
1239 EXPECT_TRUE(
1240 attempter_.omaha_request_params_->update_check_count_wait_enabled());
1241 EXPECT_TRUE(
1242 attempter_.omaha_request_params_->wall_clock_based_wait_enabled());
1243 EXPECT_EQ(waiting_time_days,
1244 attempter_.omaha_request_params_->waiting_period().InDays());
1245 // Check class variables.
1246 EXPECT_EQ(waiting_time_days, attempter_.staging_wait_time_.InDays());
1247 EXPECT_EQ(kValidStagingSchedule, attempter_.staging_schedule_);
1248 // Check that scattering is turned off
1249 EXPECT_EQ(0, attempter_.scatter_factor_.InSeconds());
Amin Hassani90e9f192020-11-18 14:20:56 -08001250 EXPECT_FALSE(fake_prefs->Exists(kPrefsWallClockScatteringWaitPeriod));
Adolfo Victoria497044c2018-07-18 07:51:42 -07001251
1252 ScheduleQuitMainLoop();
1253}
1254
1255void UpdateAttempterTest::CheckStagingOff() {
1256 // Check that all prefs were removed.
Amin Hassani90e9f192020-11-18 14:20:56 -08001257 EXPECT_FALSE(prefs_->Exists(kPrefsUpdateCheckCount));
1258 EXPECT_FALSE(prefs_->Exists(kPrefsWallClockScatteringWaitPeriod));
1259 EXPECT_FALSE(prefs_->Exists(kPrefsWallClockStagingWaitPeriod));
Adolfo Victoria497044c2018-07-18 07:51:42 -07001260 // Check that the Omaha parameters have the correct value.
1261 EXPECT_EQ(0, attempter_.omaha_request_params_->waiting_period().InDays());
1262 EXPECT_EQ(attempter_.omaha_request_params_->waiting_period(),
1263 attempter_.staging_wait_time_);
1264 EXPECT_FALSE(
1265 attempter_.omaha_request_params_->update_check_count_wait_enabled());
1266 EXPECT_FALSE(
1267 attempter_.omaha_request_params_->wall_clock_based_wait_enabled());
1268 // Check that scattering is turned off too.
1269 EXPECT_EQ(0, attempter_.scatter_factor_.InSeconds());
1270}
1271
1272TEST_F(UpdateAttempterTest, StagingOffIfInteractive) {
1273 loop_.PostTask(FROM_HERE,
1274 base::Bind(&UpdateAttempterTest::StagingOffIfInteractiveStart,
1275 base::Unretained(this)));
1276 loop_.Run();
1277}
1278
1279void UpdateAttempterTest::StagingOffIfInteractiveStart() {
1280 // Tests that staging is turned off when an interactive update is requested.
Amin Hassani538bd592020-11-04 20:46:08 -08001281 FakeSystemState::Get()->fake_hardware()->SetIsOOBEComplete(Time::UnixEpoch());
Amin Hassani90e9f192020-11-18 14:20:56 -08001282 SetUpStagingTest(kValidStagingSchedule);
Adolfo Victoria497044c2018-07-18 07:51:42 -07001283
Amin Hassanie8153632020-10-27 15:11:28 -07001284 attempter_.Update({.interactive = true});
Adolfo Victoria497044c2018-07-18 07:51:42 -07001285 CheckStagingOff();
1286
1287 ScheduleQuitMainLoop();
1288}
1289
1290TEST_F(UpdateAttempterTest, StagingOffIfOobe) {
1291 loop_.PostTask(FROM_HERE,
1292 base::Bind(&UpdateAttempterTest::StagingOffIfOobeStart,
1293 base::Unretained(this)));
1294 loop_.Run();
1295}
1296
1297void UpdateAttempterTest::StagingOffIfOobeStart() {
1298 // Tests that staging is turned off if OOBE hasn't been completed.
Amin Hassani538bd592020-11-04 20:46:08 -08001299 FakeSystemState::Get()->fake_hardware()->SetIsOOBEEnabled(true);
1300 FakeSystemState::Get()->fake_hardware()->UnsetIsOOBEComplete();
Amin Hassani90e9f192020-11-18 14:20:56 -08001301 SetUpStagingTest(kValidStagingSchedule);
Adolfo Victoria497044c2018-07-18 07:51:42 -07001302
Amin Hassanie8153632020-10-27 15:11:28 -07001303 attempter_.Update({.interactive = true});
Adolfo Victoria497044c2018-07-18 07:51:42 -07001304 CheckStagingOff();
1305
1306 ScheduleQuitMainLoop();
1307}
1308
David Zeuthen985b1122013-10-09 12:13:15 -07001309// Checks that we only report daily metrics at most every 24 hours.
1310TEST_F(UpdateAttempterTest, ReportDailyMetrics) {
Amin Hassani0468a762020-11-17 23:53:48 -08001311 auto* fake_clock = FakeSystemState::Get()->fake_clock();
David Zeuthen985b1122013-10-09 12:13:15 -07001312 Time epoch = Time::FromInternalValue(0);
Amin Hassani0468a762020-11-17 23:53:48 -08001313 fake_clock->SetWallclockTime(epoch);
David Zeuthen985b1122013-10-09 12:13:15 -07001314
1315 // If there is no kPrefsDailyMetricsLastReportedAt state variable,
1316 // we should report.
1317 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1318 // We should not report again if no time has passed.
1319 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1320
1321 // We should not report if only 10 hours has passed.
Amin Hassani0468a762020-11-17 23:53:48 -08001322 fake_clock->SetWallclockTime(epoch + TimeDelta::FromHours(10));
David Zeuthen985b1122013-10-09 12:13:15 -07001323 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1324
1325 // We should not report if only 24 hours - 1 sec has passed.
Amin Hassani0468a762020-11-17 23:53:48 -08001326 fake_clock->SetWallclockTime(epoch + TimeDelta::FromHours(24) -
1327 TimeDelta::FromSeconds(1));
David Zeuthen985b1122013-10-09 12:13:15 -07001328 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1329
1330 // We should report if 24 hours has passed.
Amin Hassani0468a762020-11-17 23:53:48 -08001331 fake_clock->SetWallclockTime(epoch + TimeDelta::FromHours(24));
David Zeuthen985b1122013-10-09 12:13:15 -07001332 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1333
1334 // But then we should not report again..
1335 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1336
1337 // .. until another 24 hours has passed
Amin Hassani0468a762020-11-17 23:53:48 -08001338 fake_clock->SetWallclockTime(epoch + TimeDelta::FromHours(47));
David Zeuthen985b1122013-10-09 12:13:15 -07001339 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
Amin Hassani0468a762020-11-17 23:53:48 -08001340 fake_clock->SetWallclockTime(epoch + TimeDelta::FromHours(48));
David Zeuthen985b1122013-10-09 12:13:15 -07001341 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1342 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1343
1344 // .. and another 24 hours
Amin Hassani0468a762020-11-17 23:53:48 -08001345 fake_clock->SetWallclockTime(epoch + TimeDelta::FromHours(71));
David Zeuthen985b1122013-10-09 12:13:15 -07001346 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
Amin Hassani0468a762020-11-17 23:53:48 -08001347 fake_clock->SetWallclockTime(epoch + TimeDelta::FromHours(72));
David Zeuthen985b1122013-10-09 12:13:15 -07001348 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1349 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1350
1351 // If the span between time of reporting and present time is
1352 // negative, we report. This is in order to reset the timestamp and
1353 // avoid an edge condition whereby a distant point in the future is
1354 // in the state variable resulting in us never ever reporting again.
Amin Hassani0468a762020-11-17 23:53:48 -08001355 fake_clock->SetWallclockTime(epoch + TimeDelta::FromHours(71));
David Zeuthen985b1122013-10-09 12:13:15 -07001356 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1357 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1358
1359 // In this case we should not update until the clock reads 71 + 24 = 95.
1360 // Check that.
Amin Hassani0468a762020-11-17 23:53:48 -08001361 fake_clock->SetWallclockTime(epoch + TimeDelta::FromHours(94));
David Zeuthen985b1122013-10-09 12:13:15 -07001362 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
Amin Hassani0468a762020-11-17 23:53:48 -08001363 fake_clock->SetWallclockTime(epoch + TimeDelta::FromHours(95));
David Zeuthen985b1122013-10-09 12:13:15 -07001364 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1365 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
David Zeuthen985b1122013-10-09 12:13:15 -07001366}
1367
David Zeuthen3c55abd2013-10-14 12:48:03 -07001368TEST_F(UpdateAttempterTest, BootTimeInUpdateMarkerFile) {
Amin Hassani0468a762020-11-17 23:53:48 -08001369 FakeSystemState::Get()->fake_clock()->SetBootTime(Time::FromTimeT(42));
Sen Jiangaeeb2e02016-06-09 15:00:16 -07001370 attempter_.Init();
David Zeuthen3c55abd2013-10-14 12:48:03 -07001371
1372 Time boot_time;
Sen Jiangaeeb2e02016-06-09 15:00:16 -07001373 EXPECT_FALSE(attempter_.GetBootTimeAtUpdate(&boot_time));
David Zeuthen3c55abd2013-10-14 12:48:03 -07001374
Sen Jiangaeeb2e02016-06-09 15:00:16 -07001375 attempter_.WriteUpdateCompletedMarker();
David Zeuthen3c55abd2013-10-14 12:48:03 -07001376
Sen Jiangaeeb2e02016-06-09 15:00:16 -07001377 EXPECT_TRUE(attempter_.GetBootTimeAtUpdate(&boot_time));
David Zeuthen3c55abd2013-10-14 12:48:03 -07001378 EXPECT_EQ(boot_time.ToTimeT(), 42);
1379}
1380
David Pursell02c18642014-11-06 11:26:11 -08001381TEST_F(UpdateAttempterTest, AnyUpdateSourceAllowedUnofficial) {
Amin Hassani538bd592020-11-04 20:46:08 -08001382 FakeSystemState::Get()->fake_hardware()->SetIsOfficialBuild(false);
David Pursell02c18642014-11-06 11:26:11 -08001383 EXPECT_TRUE(attempter_.IsAnyUpdateSourceAllowed());
1384}
1385
1386TEST_F(UpdateAttempterTest, AnyUpdateSourceAllowedOfficialDevmode) {
Amin Hassani538bd592020-11-04 20:46:08 -08001387 FakeSystemState::Get()->fake_hardware()->SetIsOfficialBuild(true);
1388 FakeSystemState::Get()->fake_hardware()->SetAreDevFeaturesEnabled(true);
David Pursell02c18642014-11-06 11:26:11 -08001389 EXPECT_TRUE(attempter_.IsAnyUpdateSourceAllowed());
1390}
1391
1392TEST_F(UpdateAttempterTest, AnyUpdateSourceDisallowedOfficialNormal) {
Amin Hassani538bd592020-11-04 20:46:08 -08001393 FakeSystemState::Get()->fake_hardware()->SetIsOfficialBuild(true);
1394 FakeSystemState::Get()->fake_hardware()->SetAreDevFeaturesEnabled(false);
David Pursell02c18642014-11-06 11:26:11 -08001395 EXPECT_FALSE(attempter_.IsAnyUpdateSourceAllowed());
1396}
1397
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001398// TODO(kimjae): Follow testing pattern with params for |CheckForInstall()|.
1399// When adding, remove older tests related to |CheckForInstall()|.
1400TEST_F(UpdateAttempterTest, CheckForInstallNotIdleFails) {
1401 for (const auto status : kNonIdleUpdateStatuses) {
1402 // GIVEN a non-idle status.
1403 attempter_.status_ = status;
Xiaochu Liu8ba486f2018-11-06 11:14:10 -08001404
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001405 EXPECT_FALSE(attempter_.CheckForInstall({}, ""));
1406 }
Xiaochu Liu8ba486f2018-11-06 11:14:10 -08001407}
1408
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001409TEST_F(UpdateAttempterTest, CheckForUpdateNotIdleFails) {
1410 for (const auto status : kNonIdleUpdateStatuses) {
1411 // GIVEN a non-idle status.
1412 cfu_params_.status = status;
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001413
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001414 // THEN |ScheduleUpdates()| should not be called.
1415 cfu_params_.should_schedule_updates_be_called = false;
1416 // THEN result should indicate failure.
1417 cfu_params_.expected_result = false;
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001418
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001419 TestCheckForUpdate();
1420 }
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001421}
1422
1423TEST_F(UpdateAttempterTest, CheckForUpdateOfficalBuildClearsSource) {
1424 // GIVEN a official build.
1425
1426 // THEN we except forced app version + forced omaha url to be cleared.
1427
1428 TestCheckForUpdate();
1429}
1430
1431TEST_F(UpdateAttempterTest, CheckForUpdateUnofficialBuildChangesSource) {
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001432 // GIVEN a nonofficial build with dev features enabled.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001433 cfu_params_.is_official_build = false;
1434 cfu_params_.are_dev_features_enabled = true;
1435
1436 // THEN the forced app version + forced omaha url changes based on input.
1437 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1438 cfu_params_.expected_forced_omaha_url = cfu_params_.omaha_url;
1439
1440 TestCheckForUpdate();
1441}
1442
1443TEST_F(UpdateAttempterTest, CheckForUpdateOfficialBuildScheduledAUTest) {
1444 // GIVEN a scheduled autest omaha url.
1445 cfu_params_.omaha_url = "autest-scheduled";
1446
1447 // THEN forced app version is cleared.
1448 // THEN forced omaha url changes to default constant.
1449 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1450
1451 TestCheckForUpdate();
1452}
1453
1454TEST_F(UpdateAttempterTest, CheckForUpdateUnofficialBuildScheduledAUTest) {
1455 // GIVEN a scheduled autest omaha url.
1456 cfu_params_.omaha_url = "autest-scheduled";
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001457 // GIVEN a nonofficial build with dev features enabled.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001458 cfu_params_.is_official_build = false;
1459 cfu_params_.are_dev_features_enabled = true;
1460
1461 // THEN forced app version changes based on input.
1462 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1463 // THEN forced omaha url changes to default constant.
1464 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1465
1466 TestCheckForUpdate();
1467}
1468
1469TEST_F(UpdateAttempterTest, CheckForUpdateOfficialBuildAUTest) {
1470 // GIVEN a autest omaha url.
1471 cfu_params_.omaha_url = "autest";
1472
1473 // THEN forced app version is cleared.
1474 // THEN forced omaha url changes to default constant.
1475 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1476
1477 TestCheckForUpdate();
1478}
1479
1480TEST_F(UpdateAttempterTest, CheckForUpdateUnofficialBuildAUTest) {
1481 // GIVEN a autest omha url.
1482 cfu_params_.omaha_url = "autest";
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001483 // GIVEN a nonofficial build with dev features enabled.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001484 cfu_params_.is_official_build = false;
1485 cfu_params_.are_dev_features_enabled = true;
1486
1487 // THEN forced app version changes based on input.
1488 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1489 // THEN forced omaha url changes to default constant.
1490 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1491
1492 TestCheckForUpdate();
1493}
1494
1495TEST_F(UpdateAttempterTest,
1496 CheckForUpdateNonInteractiveOfficialBuildScheduledAUTest) {
1497 // GIVEN a scheduled autest omaha url.
1498 cfu_params_.omaha_url = "autest-scheduled";
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001499 // GIVEN a noninteractive update.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001500 cfu_params_.flags = UpdateAttemptFlags::kFlagNonInteractive;
1501
1502 // THEN forced app version is cleared.
1503 // THEN forced omaha url changes to default constant.
1504 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1505
1506 TestCheckForUpdate();
1507}
1508
1509TEST_F(UpdateAttempterTest,
1510 CheckForUpdateNonInteractiveUnofficialBuildScheduledAUTest) {
1511 // GIVEN a scheduled autest omaha url.
1512 cfu_params_.omaha_url = "autest-scheduled";
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001513 // GIVEN a noninteractive update.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001514 cfu_params_.flags = UpdateAttemptFlags::kFlagNonInteractive;
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001515 // GIVEN a nonofficial build with dev features enabled.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001516 cfu_params_.is_official_build = false;
1517 cfu_params_.are_dev_features_enabled = true;
1518
1519 // THEN forced app version changes based on input.
1520 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1521 // THEN forced omaha url changes to default constant.
1522 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1523
1524 TestCheckForUpdate();
1525}
1526
1527TEST_F(UpdateAttempterTest, CheckForUpdateNonInteractiveOfficialBuildAUTest) {
1528 // GIVEN a autest omaha url.
1529 cfu_params_.omaha_url = "autest";
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001530 // GIVEN a noninteractive update.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001531 cfu_params_.flags = UpdateAttemptFlags::kFlagNonInteractive;
1532
1533 // THEN forced app version is cleared.
1534 // THEN forced omaha url changes to default constant.
1535 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1536
1537 TestCheckForUpdate();
1538}
1539
1540TEST_F(UpdateAttempterTest, CheckForUpdateNonInteractiveUnofficialBuildAUTest) {
1541 // GIVEN a autest omaha url.
1542 cfu_params_.omaha_url = "autest";
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001543 // GIVEN a noninteractive update.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001544 cfu_params_.flags = UpdateAttemptFlags::kFlagNonInteractive;
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001545 // GIVEN a nonofficial build with dev features enabled.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001546 cfu_params_.is_official_build = false;
1547 cfu_params_.are_dev_features_enabled = true;
1548
1549 // THEN forced app version changes based on input.
1550 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1551 // THEN forced omaha url changes to default constant.
1552 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1553
1554 TestCheckForUpdate();
David Pursell02c18642014-11-06 11:26:11 -08001555}
1556
Jae Hoon Kim2b73ac22019-07-02 11:17:24 -07001557TEST_F(UpdateAttempterTest, CheckForUpdateMissingForcedCallback1) {
1558 // GIVEN a official build.
1559 // GIVEN forced callback is not set.
1560 attempter_.set_forced_update_pending_callback(nullptr);
1561
1562 // THEN we except forced app version + forced omaha url to be cleared.
1563 // THEN |ScheduleUpdates()| should not be called.
1564 cfu_params_.should_schedule_updates_be_called = false;
1565
1566 TestCheckForUpdate();
1567}
1568
1569TEST_F(UpdateAttempterTest, CheckForUpdateMissingForcedCallback2) {
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001570 // GIVEN a nonofficial build with dev features enabled.
Jae Hoon Kim2b73ac22019-07-02 11:17:24 -07001571 cfu_params_.is_official_build = false;
1572 cfu_params_.are_dev_features_enabled = true;
1573 // GIVEN forced callback is not set.
1574 attempter_.set_forced_update_pending_callback(nullptr);
1575
1576 // THEN the forced app version + forced omaha url changes based on input.
1577 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1578 cfu_params_.expected_forced_omaha_url = cfu_params_.omaha_url;
1579 // THEN |ScheduleUpdates()| should not be called.
1580 cfu_params_.should_schedule_updates_be_called = false;
1581
1582 TestCheckForUpdate();
1583}
1584
Xiaochu Liu88d90382018-08-29 16:09:11 -07001585TEST_F(UpdateAttempterTest, CheckForInstallTest) {
Amin Hassani538bd592020-11-04 20:46:08 -08001586 FakeSystemState::Get()->fake_hardware()->SetIsOfficialBuild(true);
1587 FakeSystemState::Get()->fake_hardware()->SetAreDevFeaturesEnabled(false);
Xiaochu Liu88d90382018-08-29 16:09:11 -07001588 attempter_.CheckForInstall({}, "autest");
1589 EXPECT_EQ(constants::kOmahaDefaultAUTestURL, attempter_.forced_omaha_url());
1590
1591 attempter_.CheckForInstall({}, "autest-scheduled");
1592 EXPECT_EQ(constants::kOmahaDefaultAUTestURL, attempter_.forced_omaha_url());
1593
1594 attempter_.CheckForInstall({}, "http://omaha.phishing");
1595 EXPECT_EQ("", attempter_.forced_omaha_url());
1596}
1597
Colin Howesac170d92018-11-20 16:29:28 -08001598TEST_F(UpdateAttempterTest, InstallSetsStatusIdle) {
1599 attempter_.CheckForInstall({}, "http://foo.bar");
1600 attempter_.status_ = UpdateStatus::DOWNLOADING;
1601 EXPECT_TRUE(attempter_.is_install_);
1602 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1603 UpdateEngineStatus status;
1604 attempter_.GetStatus(&status);
1605 // Should set status to idle after an install operation.
1606 EXPECT_EQ(UpdateStatus::IDLE, status.status);
1607}
1608
Colin Howes978c1082018-12-03 11:46:12 -08001609TEST_F(UpdateAttempterTest, RollbackAfterInstall) {
1610 attempter_.is_install_ = true;
1611 attempter_.Rollback(false);
1612 EXPECT_FALSE(attempter_.is_install_);
1613}
1614
1615TEST_F(UpdateAttempterTest, UpdateAfterInstall) {
1616 attempter_.is_install_ = true;
1617 attempter_.CheckForUpdate("", "", UpdateAttemptFlags::kNone);
1618 EXPECT_FALSE(attempter_.is_install_);
1619}
1620
Xiyuan Xiac0e8f9a2017-02-22 13:19:35 -08001621TEST_F(UpdateAttempterTest, TargetVersionPrefixSetAndReset) {
Amin Hassanie8153632020-10-27 15:11:28 -07001622 UpdateCheckParams params;
1623 attempter_.CalculateUpdateParams({.target_version_prefix = "1234"});
Xiyuan Xiac0e8f9a2017-02-22 13:19:35 -08001624 EXPECT_EQ("1234",
Amin Hassani538bd592020-11-04 20:46:08 -08001625 FakeSystemState::Get()->request_params()->target_version_prefix());
Xiyuan Xiac0e8f9a2017-02-22 13:19:35 -08001626
Amin Hassanie8153632020-10-27 15:11:28 -07001627 attempter_.CalculateUpdateParams({});
Amin Hassani538bd592020-11-04 20:46:08 -08001628 EXPECT_TRUE(FakeSystemState::Get()
1629 ->request_params()
1630 ->target_version_prefix()
1631 .empty());
Xiyuan Xiac0e8f9a2017-02-22 13:19:35 -08001632}
1633
Amin Hassani37b67232020-08-13 09:29:48 -07001634TEST_F(UpdateAttempterTest, TargetChannelHintSetAndReset) {
Amin Hassanie8153632020-10-27 15:11:28 -07001635 attempter_.CalculateUpdateParams({.lts_tag = "hint"});
Amin Hassani538bd592020-11-04 20:46:08 -08001636 EXPECT_EQ("hint", FakeSystemState::Get()->request_params()->lts_tag());
Amin Hassani37b67232020-08-13 09:29:48 -07001637
Amin Hassanie8153632020-10-27 15:11:28 -07001638 attempter_.CalculateUpdateParams({});
Amin Hassani538bd592020-11-04 20:46:08 -08001639 EXPECT_TRUE(FakeSystemState::Get()->request_params()->lts_tag().empty());
Amin Hassani37b67232020-08-13 09:29:48 -07001640}
1641
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001642TEST_F(UpdateAttempterTest, RollbackAllowedSetAndReset) {
Amin Hassanie8153632020-10-27 15:11:28 -07001643 attempter_.CalculateUpdateParams({
1644 .target_version_prefix = "1234",
1645 .rollback_allowed = true,
1646 .rollback_allowed_milestones = 4,
1647 });
Amin Hassani538bd592020-11-04 20:46:08 -08001648 EXPECT_TRUE(FakeSystemState::Get()->request_params()->rollback_allowed());
1649 EXPECT_EQ(
1650 4,
1651 FakeSystemState::Get()->request_params()->rollback_allowed_milestones());
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001652
Amin Hassanie8153632020-10-27 15:11:28 -07001653 attempter_.CalculateUpdateParams({
1654 .target_version_prefix = "1234",
1655 .rollback_allowed_milestones = 4,
1656 });
Amin Hassani538bd592020-11-04 20:46:08 -08001657 EXPECT_FALSE(FakeSystemState::Get()->request_params()->rollback_allowed());
1658 EXPECT_EQ(
1659 4,
1660 FakeSystemState::Get()->request_params()->rollback_allowed_milestones());
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001661}
1662
Miriam Polzeraff72002020-08-27 08:20:39 +02001663TEST_F(UpdateAttempterTest, ChannelDowngradeNoRollback) {
1664 base::ScopedTempDir tempdir;
1665 ASSERT_TRUE(tempdir.CreateUniqueTempDir());
Amin Hassani538bd592020-11-04 20:46:08 -08001666 FakeSystemState::Get()->request_params()->set_root(tempdir.GetPath().value());
Amin Hassanie8153632020-10-27 15:11:28 -07001667 attempter_.CalculateUpdateParams({
1668 .target_channel = "stable-channel",
1669 });
Amin Hassani538bd592020-11-04 20:46:08 -08001670 EXPECT_FALSE(
1671 FakeSystemState::Get()->request_params()->is_powerwash_allowed());
Miriam Polzeraff72002020-08-27 08:20:39 +02001672}
1673
1674TEST_F(UpdateAttempterTest, ChannelDowngradeRollback) {
1675 base::ScopedTempDir tempdir;
1676 ASSERT_TRUE(tempdir.CreateUniqueTempDir());
Amin Hassani538bd592020-11-04 20:46:08 -08001677 FakeSystemState::Get()->request_params()->set_root(tempdir.GetPath().value());
Amin Hassanie8153632020-10-27 15:11:28 -07001678 attempter_.CalculateUpdateParams({
1679 .rollback_on_channel_downgrade = true,
1680 .target_channel = "stable-channel",
1681 });
Amin Hassani538bd592020-11-04 20:46:08 -08001682 EXPECT_TRUE(FakeSystemState::Get()->request_params()->is_powerwash_allowed());
Miriam Polzeraff72002020-08-27 08:20:39 +02001683}
1684
Aaron Wood23bd3392017-10-06 14:48:25 -07001685TEST_F(UpdateAttempterTest, UpdateDeferredByPolicyTest) {
1686 // Construct an OmahaResponseHandlerAction that has processed an InstallPlan,
1687 // but the update is being deferred by the Policy.
Amin Hassani538bd592020-11-04 20:46:08 -08001688 OmahaResponseHandlerAction response_action;
Amin Hassani68512d42018-07-31 23:52:33 -07001689 response_action.install_plan_.version = "a.b.c.d";
Amin Hassani68512d42018-07-31 23:52:33 -07001690 response_action.install_plan_.payloads.push_back(
Aaron Wood23bd3392017-10-06 14:48:25 -07001691 {.size = 1234ULL, .type = InstallPayloadType::kFull});
Aaron Wood23bd3392017-10-06 14:48:25 -07001692 // Inform the UpdateAttempter that the OmahaResponseHandlerAction has
1693 // completed, with the deferred-update error code.
1694 attempter_.ActionCompleted(
Amin Hassani68512d42018-07-31 23:52:33 -07001695 nullptr, &response_action, ErrorCode::kOmahaUpdateDeferredPerPolicy);
Aaron Wood23bd3392017-10-06 14:48:25 -07001696 {
1697 UpdateEngineStatus status;
1698 attempter_.GetStatus(&status);
1699 EXPECT_EQ(UpdateStatus::UPDATE_AVAILABLE, status.status);
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001700 EXPECT_TRUE(attempter_.install_plan_);
1701 EXPECT_EQ(attempter_.install_plan_->version, status.new_version);
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001702 EXPECT_EQ(attempter_.install_plan_->payloads[0].size,
Aaron Wood23bd3392017-10-06 14:48:25 -07001703 status.new_size_bytes);
1704 }
1705 // An "error" event should have been created to tell Omaha that the update is
1706 // being deferred.
1707 EXPECT_TRUE(nullptr != attempter_.error_event_);
1708 EXPECT_EQ(OmahaEvent::kTypeUpdateComplete, attempter_.error_event_->type);
1709 EXPECT_EQ(OmahaEvent::kResultUpdateDeferred, attempter_.error_event_->result);
1710 ErrorCode expected_code = static_cast<ErrorCode>(
1711 static_cast<int>(ErrorCode::kOmahaUpdateDeferredPerPolicy) |
1712 static_cast<int>(ErrorCode::kTestOmahaUrlFlag));
1713 EXPECT_EQ(expected_code, attempter_.error_event_->error_code);
1714 // End the processing
1715 attempter_.ProcessingDone(nullptr, ErrorCode::kOmahaUpdateDeferredPerPolicy);
1716 // Validate the state of the attempter.
1717 {
1718 UpdateEngineStatus status;
1719 attempter_.GetStatus(&status);
1720 EXPECT_EQ(UpdateStatus::REPORTING_ERROR_EVENT, status.status);
Amin Hassani68512d42018-07-31 23:52:33 -07001721 EXPECT_EQ(response_action.install_plan_.version, status.new_version);
Amin Hassani68512d42018-07-31 23:52:33 -07001722 EXPECT_EQ(response_action.install_plan_.payloads[0].size,
Aaron Wood23bd3392017-10-06 14:48:25 -07001723 status.new_size_bytes);
1724 }
1725}
1726
1727TEST_F(UpdateAttempterTest, UpdateIsNotRunningWhenUpdateAvailable) {
Jae Hoon Kim75daa382019-07-02 11:17:24 -07001728 // Default construction for |waiting_for_scheduled_check_| is false.
Jae Hoon Kimba2fdce2019-07-11 13:18:58 -07001729 EXPECT_FALSE(attempter_.IsBusyOrUpdateScheduled());
Aaron Wood23bd3392017-10-06 14:48:25 -07001730 // Verify in-progress update with UPDATE_AVAILABLE is running
1731 attempter_.status_ = UpdateStatus::UPDATE_AVAILABLE;
Jae Hoon Kimba2fdce2019-07-11 13:18:58 -07001732 EXPECT_TRUE(attempter_.IsBusyOrUpdateScheduled());
Aaron Wood23bd3392017-10-06 14:48:25 -07001733}
1734
Aaron Woodbf5a2522017-10-04 10:58:36 -07001735TEST_F(UpdateAttempterTest, UpdateAttemptFlagsCachedAtUpdateStart) {
1736 attempter_.SetUpdateAttemptFlags(UpdateAttemptFlags::kFlagRestrictDownload);
1737
1738 UpdateCheckParams params = {.updates_enabled = true};
1739 attempter_.OnUpdateScheduled(EvalStatus::kSucceeded, params);
1740
1741 EXPECT_EQ(UpdateAttemptFlags::kFlagRestrictDownload,
1742 attempter_.GetCurrentUpdateAttemptFlags());
1743}
1744
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001745TEST_F(UpdateAttempterTest, RollbackNotAllowed) {
1746 UpdateCheckParams params = {.updates_enabled = true,
1747 .rollback_allowed = false};
1748 attempter_.OnUpdateScheduled(EvalStatus::kSucceeded, params);
Amin Hassani538bd592020-11-04 20:46:08 -08001749 EXPECT_FALSE(FakeSystemState::Get()->request_params()->rollback_allowed());
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001750}
1751
1752TEST_F(UpdateAttempterTest, RollbackAllowed) {
1753 UpdateCheckParams params = {.updates_enabled = true,
1754 .rollback_allowed = true};
1755 attempter_.OnUpdateScheduled(EvalStatus::kSucceeded, params);
Amin Hassani538bd592020-11-04 20:46:08 -08001756 EXPECT_TRUE(FakeSystemState::Get()->request_params()->rollback_allowed());
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001757}
1758
Aaron Wood081c0232017-10-19 17:14:58 -07001759TEST_F(UpdateAttempterTest, InteractiveUpdateUsesPassedRestrictions) {
1760 attempter_.SetUpdateAttemptFlags(UpdateAttemptFlags::kFlagRestrictDownload);
1761
1762 attempter_.CheckForUpdate("", "", UpdateAttemptFlags::kNone);
1763 EXPECT_EQ(UpdateAttemptFlags::kNone,
1764 attempter_.GetCurrentUpdateAttemptFlags());
1765}
1766
1767TEST_F(UpdateAttempterTest, NonInteractiveUpdateUsesSetRestrictions) {
1768 attempter_.SetUpdateAttemptFlags(UpdateAttemptFlags::kNone);
1769
1770 // This tests that when CheckForUpdate() is called with the non-interactive
1771 // flag set, that it doesn't change the current UpdateAttemptFlags.
1772 attempter_.CheckForUpdate("",
1773 "",
1774 UpdateAttemptFlags::kFlagNonInteractive |
1775 UpdateAttemptFlags::kFlagRestrictDownload);
1776 EXPECT_EQ(UpdateAttemptFlags::kNone,
1777 attempter_.GetCurrentUpdateAttemptFlags());
1778}
1779
Marton Hunyadye58bddb2018-04-10 20:27:26 +02001780void UpdateAttempterTest::ResetRollbackHappenedStart(bool is_consumer,
1781 bool is_policy_loaded,
1782 bool expected_reset) {
Amin Hassani538bd592020-11-04 20:46:08 -08001783 EXPECT_CALL(*FakeSystemState::Get()->mock_payload_state(),
1784 GetRollbackHappened())
Marton Hunyadye58bddb2018-04-10 20:27:26 +02001785 .WillRepeatedly(Return(true));
1786 auto mock_policy_provider =
1787 std::make_unique<NiceMock<policy::MockPolicyProvider>>();
1788 EXPECT_CALL(*mock_policy_provider, IsConsumerDevice())
1789 .WillRepeatedly(Return(is_consumer));
1790 EXPECT_CALL(*mock_policy_provider, device_policy_is_loaded())
1791 .WillRepeatedly(Return(is_policy_loaded));
1792 const policy::MockDevicePolicy device_policy;
1793 EXPECT_CALL(*mock_policy_provider, GetDevicePolicy())
1794 .WillRepeatedly(ReturnRef(device_policy));
Amin Hassani538bd592020-11-04 20:46:08 -08001795 EXPECT_CALL(*FakeSystemState::Get()->mock_payload_state(),
Marton Hunyadye58bddb2018-04-10 20:27:26 +02001796 SetRollbackHappened(false))
1797 .Times(expected_reset ? 1 : 0);
1798 attempter_.policy_provider_ = std::move(mock_policy_provider);
Amin Hassanie8153632020-10-27 15:11:28 -07001799 attempter_.Update({});
Marton Hunyadye58bddb2018-04-10 20:27:26 +02001800 ScheduleQuitMainLoop();
1801}
1802
1803TEST_F(UpdateAttempterTest, ResetRollbackHappenedOobe) {
1804 loop_.PostTask(FROM_HERE,
1805 base::Bind(&UpdateAttempterTest::ResetRollbackHappenedStart,
1806 base::Unretained(this),
1807 /*is_consumer=*/false,
1808 /*is_policy_loaded=*/false,
1809 /*expected_reset=*/false));
1810 loop_.Run();
1811}
1812
1813TEST_F(UpdateAttempterTest, ResetRollbackHappenedConsumer) {
1814 loop_.PostTask(FROM_HERE,
1815 base::Bind(&UpdateAttempterTest::ResetRollbackHappenedStart,
1816 base::Unretained(this),
1817 /*is_consumer=*/true,
1818 /*is_policy_loaded=*/false,
1819 /*expected_reset=*/true));
1820 loop_.Run();
1821}
1822
1823TEST_F(UpdateAttempterTest, ResetRollbackHappenedEnterprise) {
1824 loop_.PostTask(FROM_HERE,
1825 base::Bind(&UpdateAttempterTest::ResetRollbackHappenedStart,
1826 base::Unretained(this),
1827 /*is_consumer=*/false,
1828 /*is_policy_loaded=*/true,
1829 /*expected_reset=*/true));
1830 loop_.Run();
1831}
1832
Marton Hunyady199152d2018-05-07 19:08:48 +02001833TEST_F(UpdateAttempterTest, SetRollbackHappenedRollback) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001834 attempter_.install_plan_.reset(new InstallPlan);
1835 attempter_.install_plan_->is_rollback = true;
Marton Hunyady199152d2018-05-07 19:08:48 +02001836
Amin Hassani538bd592020-11-04 20:46:08 -08001837 EXPECT_CALL(*FakeSystemState::Get()->mock_payload_state(),
Marton Hunyady199152d2018-05-07 19:08:48 +02001838 SetRollbackHappened(true))
1839 .Times(1);
1840 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1841}
1842
1843TEST_F(UpdateAttempterTest, SetRollbackHappenedNotRollback) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001844 attempter_.install_plan_.reset(new InstallPlan);
1845 attempter_.install_plan_->is_rollback = false;
Marton Hunyady199152d2018-05-07 19:08:48 +02001846
Amin Hassani538bd592020-11-04 20:46:08 -08001847 EXPECT_CALL(*FakeSystemState::Get()->mock_payload_state(),
Marton Hunyady199152d2018-05-07 19:08:48 +02001848 SetRollbackHappened(true))
1849 .Times(0);
1850 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1851}
1852
Marton Hunyadya0302682018-05-16 18:52:13 +02001853TEST_F(UpdateAttempterTest, RollbackMetricsRollbackSuccess) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001854 attempter_.install_plan_.reset(new InstallPlan);
1855 attempter_.install_plan_->is_rollback = true;
1856 attempter_.install_plan_->version = kRollbackVersion;
Marton Hunyadya0302682018-05-16 18:52:13 +02001857
Amin Hassani538bd592020-11-04 20:46:08 -08001858 EXPECT_CALL(*FakeSystemState::Get()->mock_metrics_reporter(),
Marton Hunyadya0302682018-05-16 18:52:13 +02001859 ReportEnterpriseRollbackMetrics(true, kRollbackVersion))
1860 .Times(1);
1861 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1862}
1863
1864TEST_F(UpdateAttempterTest, RollbackMetricsNotRollbackSuccess) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001865 attempter_.install_plan_.reset(new InstallPlan);
1866 attempter_.install_plan_->is_rollback = false;
1867 attempter_.install_plan_->version = kRollbackVersion;
Marton Hunyadya0302682018-05-16 18:52:13 +02001868
Amin Hassani538bd592020-11-04 20:46:08 -08001869 EXPECT_CALL(*FakeSystemState::Get()->mock_metrics_reporter(),
Marton Hunyadya0302682018-05-16 18:52:13 +02001870 ReportEnterpriseRollbackMetrics(_, _))
1871 .Times(0);
1872 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1873}
1874
1875TEST_F(UpdateAttempterTest, RollbackMetricsRollbackFailure) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001876 attempter_.install_plan_.reset(new InstallPlan);
1877 attempter_.install_plan_->is_rollback = true;
1878 attempter_.install_plan_->version = kRollbackVersion;
Marton Hunyadya0302682018-05-16 18:52:13 +02001879
Amin Hassani538bd592020-11-04 20:46:08 -08001880 EXPECT_CALL(*FakeSystemState::Get()->mock_metrics_reporter(),
Marton Hunyadya0302682018-05-16 18:52:13 +02001881 ReportEnterpriseRollbackMetrics(false, kRollbackVersion))
1882 .Times(1);
1883 MockAction action;
1884 attempter_.CreatePendingErrorEvent(&action, ErrorCode::kRollbackNotPossible);
1885 attempter_.ProcessingDone(nullptr, ErrorCode::kRollbackNotPossible);
1886}
1887
1888TEST_F(UpdateAttempterTest, RollbackMetricsNotRollbackFailure) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001889 attempter_.install_plan_.reset(new InstallPlan);
1890 attempter_.install_plan_->is_rollback = false;
1891 attempter_.install_plan_->version = kRollbackVersion;
Marton Hunyadya0302682018-05-16 18:52:13 +02001892
Amin Hassani538bd592020-11-04 20:46:08 -08001893 EXPECT_CALL(*FakeSystemState::Get()->mock_metrics_reporter(),
Marton Hunyadya0302682018-05-16 18:52:13 +02001894 ReportEnterpriseRollbackMetrics(_, _))
1895 .Times(0);
1896 MockAction action;
1897 attempter_.CreatePendingErrorEvent(&action, ErrorCode::kRollbackNotPossible);
1898 attempter_.ProcessingDone(nullptr, ErrorCode::kRollbackNotPossible);
1899}
1900
May Lippert60aa3ca2018-08-15 16:55:29 -07001901TEST_F(UpdateAttempterTest, TimeToUpdateAppliedMetricFailure) {
Amin Hassani538bd592020-11-04 20:46:08 -08001902 EXPECT_CALL(*FakeSystemState::Get()->mock_metrics_reporter(),
May Lippert60aa3ca2018-08-15 16:55:29 -07001903 ReportEnterpriseUpdateSeenToDownloadDays(_, _))
1904 .Times(0);
1905 attempter_.ProcessingDone(nullptr, ErrorCode::kOmahaUpdateDeferredPerPolicy);
1906}
1907
1908TEST_F(UpdateAttempterTest, TimeToUpdateAppliedOnNonEnterprise) {
1909 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Amin Hassani538bd592020-11-04 20:46:08 -08001910 FakeSystemState::Get()->set_device_policy(device_policy.get());
May Lippert60aa3ca2018-08-15 16:55:29 -07001911 // Make device policy return that this is not enterprise enrolled
1912 EXPECT_CALL(*device_policy, IsEnterpriseEnrolled()).WillOnce(Return(false));
1913
1914 // Ensure that the metric is not recorded.
Amin Hassani538bd592020-11-04 20:46:08 -08001915 EXPECT_CALL(*FakeSystemState::Get()->mock_metrics_reporter(),
May Lippert60aa3ca2018-08-15 16:55:29 -07001916 ReportEnterpriseUpdateSeenToDownloadDays(_, _))
1917 .Times(0);
1918 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1919}
1920
1921TEST_F(UpdateAttempterTest,
1922 TimeToUpdateAppliedWithTimeRestrictionMetricSuccess) {
1923 constexpr int kDaysToUpdate = 15;
1924 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Amin Hassani538bd592020-11-04 20:46:08 -08001925 FakeSystemState::Get()->set_device_policy(device_policy.get());
May Lippert60aa3ca2018-08-15 16:55:29 -07001926 // Make device policy return that this is enterprise enrolled
1927 EXPECT_CALL(*device_policy, IsEnterpriseEnrolled()).WillOnce(Return(true));
1928 // Pretend that there's a time restriction policy in place
1929 EXPECT_CALL(*device_policy, GetDisallowedTimeIntervals(_))
1930 .WillOnce(Return(true));
1931
May Lippert60aa3ca2018-08-15 16:55:29 -07001932 Time update_first_seen_at = Time::Now();
Amin Hassani90e9f192020-11-18 14:20:56 -08001933 FakeSystemState::Get()->fake_prefs()->SetInt64(
1934 kPrefsUpdateFirstSeenAt, update_first_seen_at.ToInternalValue());
May Lippert60aa3ca2018-08-15 16:55:29 -07001935
May Lippert60aa3ca2018-08-15 16:55:29 -07001936 Time update_finished_at =
1937 update_first_seen_at + TimeDelta::FromDays(kDaysToUpdate);
Amin Hassani0468a762020-11-17 23:53:48 -08001938 FakeSystemState::Get()->fake_clock()->SetWallclockTime(update_finished_at);
May Lippert60aa3ca2018-08-15 16:55:29 -07001939
Amin Hassani538bd592020-11-04 20:46:08 -08001940 EXPECT_CALL(*FakeSystemState::Get()->mock_metrics_reporter(),
May Lippert60aa3ca2018-08-15 16:55:29 -07001941 ReportEnterpriseUpdateSeenToDownloadDays(true, kDaysToUpdate))
1942 .Times(1);
1943 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1944}
1945
1946TEST_F(UpdateAttempterTest,
1947 TimeToUpdateAppliedWithoutTimeRestrictionMetricSuccess) {
1948 constexpr int kDaysToUpdate = 15;
1949 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Amin Hassani538bd592020-11-04 20:46:08 -08001950 FakeSystemState::Get()->set_device_policy(device_policy.get());
May Lippert60aa3ca2018-08-15 16:55:29 -07001951 // Make device policy return that this is enterprise enrolled
1952 EXPECT_CALL(*device_policy, IsEnterpriseEnrolled()).WillOnce(Return(true));
1953 // Pretend that there's no time restriction policy in place
1954 EXPECT_CALL(*device_policy, GetDisallowedTimeIntervals(_))
1955 .WillOnce(Return(false));
1956
May Lippert60aa3ca2018-08-15 16:55:29 -07001957 Time update_first_seen_at = Time::Now();
Amin Hassani90e9f192020-11-18 14:20:56 -08001958 FakeSystemState::Get()->fake_prefs()->SetInt64(
1959 kPrefsUpdateFirstSeenAt, update_first_seen_at.ToInternalValue());
May Lippert60aa3ca2018-08-15 16:55:29 -07001960
May Lippert60aa3ca2018-08-15 16:55:29 -07001961 Time update_finished_at =
1962 update_first_seen_at + TimeDelta::FromDays(kDaysToUpdate);
Amin Hassani0468a762020-11-17 23:53:48 -08001963 FakeSystemState::Get()->fake_clock()->SetWallclockTime(update_finished_at);
May Lippert60aa3ca2018-08-15 16:55:29 -07001964
Amin Hassani538bd592020-11-04 20:46:08 -08001965 EXPECT_CALL(*FakeSystemState::Get()->mock_metrics_reporter(),
May Lippert60aa3ca2018-08-15 16:55:29 -07001966 ReportEnterpriseUpdateSeenToDownloadDays(false, kDaysToUpdate))
1967 .Times(1);
1968 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1969}
1970
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07001971TEST_F(UpdateAttempterTest, ProcessingDoneUpdated) {
1972 // GIVEN an update finished.
1973
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07001974 // THEN update_engine should call update completion.
1975 pd_params_.should_update_completed_be_called = true;
1976 // THEN need reboot since update applied.
1977 pd_params_.expected_exit_status = UpdateStatus::UPDATED_NEED_REBOOT;
1978 // THEN install indication should be false.
1979
1980 TestProcessingDone();
1981}
1982
1983TEST_F(UpdateAttempterTest, ProcessingDoneUpdatedDlcFilter) {
1984 // GIVEN an update finished.
1985 // GIVEN DLC |AppParams| list.
1986 auto dlc_1 = "dlc_1", dlc_2 = "dlc_2";
1987 pd_params_.dlc_apps_params = {{dlc_1, {.name = dlc_1, .updated = false}},
1988 {dlc_2, {.name = dlc_2}}};
1989
1990 // THEN update_engine should call update completion.
1991 pd_params_.should_update_completed_be_called = true;
1992 pd_params_.args_to_update_completed = {dlc_2};
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07001993 // THEN need reboot since update applied.
1994 pd_params_.expected_exit_status = UpdateStatus::UPDATED_NEED_REBOOT;
1995 // THEN install indication should be false.
1996
1997 TestProcessingDone();
1998}
1999
2000TEST_F(UpdateAttempterTest, ProcessingDoneInstalled) {
2001 // GIVEN an install finished.
2002 pd_params_.is_install = true;
2003
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002004 // THEN update_engine should call install completion.
2005 pd_params_.should_install_completed_be_called = true;
2006 // THEN go idle.
2007 // THEN install indication should be false.
2008
2009 TestProcessingDone();
2010}
2011
2012TEST_F(UpdateAttempterTest, ProcessingDoneInstalledDlcFilter) {
2013 // GIVEN an install finished.
2014 pd_params_.is_install = true;
2015 // GIVEN DLC |AppParams| list.
2016 auto dlc_1 = "dlc_1", dlc_2 = "dlc_2";
2017 pd_params_.dlc_apps_params = {{dlc_1, {.name = dlc_1, .updated = false}},
2018 {dlc_2, {.name = dlc_2}}};
2019
2020 // THEN update_engine should call install completion.
2021 pd_params_.should_install_completed_be_called = true;
2022 pd_params_.args_to_install_completed = {dlc_2};
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002023 // THEN go idle.
2024 // THEN install indication should be false.
2025
2026 TestProcessingDone();
2027}
2028
2029TEST_F(UpdateAttempterTest, ProcessingDoneInstallReportingError) {
2030 // GIVEN an install finished.
2031 pd_params_.is_install = true;
2032 // GIVEN a reporting error occurred.
2033 pd_params_.status = UpdateStatus::REPORTING_ERROR_EVENT;
2034
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002035 // THEN update_engine should not call install completion.
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002036 // THEN go idle.
2037 // THEN install indication should be false.
2038
2039 TestProcessingDone();
2040}
2041
2042TEST_F(UpdateAttempterTest, ProcessingDoneNoUpdate) {
2043 // GIVEN an update finished.
2044 // GIVEN an action error occured.
2045 pd_params_.code = ErrorCode::kNoUpdate;
2046
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002047 // THEN update_engine should not call update completion.
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002048 // THEN go idle.
2049 // THEN install indication should be false.
2050
2051 TestProcessingDone();
2052}
2053
2054TEST_F(UpdateAttempterTest, ProcessingDoneNoInstall) {
2055 // GIVEN an install finished.
2056 pd_params_.is_install = true;
2057 // GIVEN an action error occured.
2058 pd_params_.code = ErrorCode::kNoUpdate;
2059
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002060 // THEN update_engine should not call install completion.
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002061 // THEN go idle.
2062 // THEN install indication should be false.
2063
2064 TestProcessingDone();
2065}
2066
2067TEST_F(UpdateAttempterTest, ProcessingDoneUpdateError) {
2068 // GIVEN an update finished.
2069 // GIVEN an action error occured.
2070 pd_params_.code = ErrorCode::kError;
2071 // GIVEN an event error is set.
2072 attempter_.error_event_.reset(new OmahaEvent(OmahaEvent::kTypeUpdateComplete,
2073 OmahaEvent::kResultError,
2074 ErrorCode::kError));
2075
2076 // THEN indicate a error event.
2077 pd_params_.expected_exit_status = UpdateStatus::REPORTING_ERROR_EVENT;
2078 // THEN install indication should be false.
2079
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002080 // THEN update_engine should not call update completion.
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002081 // THEN expect critical actions of |ScheduleErrorEventAction()|.
2082 EXPECT_CALL(*processor_, EnqueueAction(Pointee(_))).Times(1);
2083 EXPECT_CALL(*processor_, StartProcessing()).Times(1);
2084 // THEN |ScheduleUpdates()| will be called next |ProcessingDone()| so skip.
2085 pd_params_.should_schedule_updates_be_called = false;
2086
2087 TestProcessingDone();
2088}
2089
2090TEST_F(UpdateAttempterTest, ProcessingDoneInstallError) {
2091 // GIVEN an install finished.
2092 pd_params_.is_install = true;
2093 // GIVEN an action error occured.
2094 pd_params_.code = ErrorCode::kError;
2095 // GIVEN an event error is set.
2096 attempter_.error_event_.reset(new OmahaEvent(OmahaEvent::kTypeUpdateComplete,
2097 OmahaEvent::kResultError,
2098 ErrorCode::kError));
2099
2100 // THEN indicate a error event.
2101 pd_params_.expected_exit_status = UpdateStatus::REPORTING_ERROR_EVENT;
2102 // THEN install indication should be false.
2103
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002104 // THEN update_engine should not call install completion.
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002105 // THEN expect critical actions of |ScheduleErrorEventAction()|.
2106 EXPECT_CALL(*processor_, EnqueueAction(Pointee(_))).Times(1);
2107 EXPECT_CALL(*processor_, StartProcessing()).Times(1);
2108 // THEN |ScheduleUpdates()| will be called next |ProcessingDone()| so skip.
2109 pd_params_.should_schedule_updates_be_called = false;
2110
2111 TestProcessingDone();
2112}
2113
Saurabh Nijhara43d7adc2020-11-06 16:13:02 +01002114TEST_F(UpdateAttempterTest, QuickFixTokenWhenDeviceIsEnterpriseEnrolled) {
2115 attempter_.CalculateUpdateParams({.quick_fix_build_token = "token"});
2116 EXPECT_EQ("token",
2117 FakeSystemState::Get()->request_params()->autoupdate_token());
Amr Aboelkher21ac9962019-05-15 14:50:05 +02002118
Saurabh Nijhara43d7adc2020-11-06 16:13:02 +01002119 attempter_.CalculateUpdateParams({});
2120 EXPECT_TRUE(
2121 FakeSystemState::Get()->request_params()->autoupdate_token().empty());
Askar Aitzhan570ca872019-04-24 11:16:12 +02002122}
2123
Jae Hoon Kim75daa382019-07-02 11:17:24 -07002124TEST_F(UpdateAttempterTest, ScheduleUpdateSpamHandlerTest) {
2125 EXPECT_CALL(mock_update_manager_, AsyncPolicyRequestUpdateCheckAllowed(_, _))
2126 .Times(1);
2127 EXPECT_TRUE(attempter_.ScheduleUpdates());
2128 // Now there is an update scheduled which means that all subsequent
2129 // |ScheduleUpdates()| should fail.
2130 EXPECT_FALSE(attempter_.ScheduleUpdates());
2131 EXPECT_FALSE(attempter_.ScheduleUpdates());
2132 EXPECT_FALSE(attempter_.ScheduleUpdates());
2133}
2134
2135// Critical tests to always make sure that an update is scheduled. The following
2136// unittest(s) try and cover the correctness in synergy between
2137// |UpdateAttempter| and |UpdateManager|. Also it is good to remember the
2138// actions that happen in the flow when |UpdateAttempter| get callbacked on
2139// |OnUpdateScheduled()| -> (various cases which leads to) -> |ProcessingDone()|
2140void UpdateAttempterTest::TestOnUpdateScheduled() {
2141 // Setup
2142 attempter_.SetWaitingForScheduledCheck(true);
2143 attempter_.DisableUpdate();
2144 attempter_.DisableScheduleUpdates();
2145
2146 // Invocation
2147 attempter_.OnUpdateScheduled(ous_params_.status, ous_params_.params);
2148
2149 // Verify
2150 EXPECT_EQ(ous_params_.exit_status, attempter_.status());
2151 EXPECT_EQ(ous_params_.should_schedule_updates_be_called,
2152 attempter_.WasScheduleUpdatesCalled());
2153 EXPECT_EQ(ous_params_.should_update_be_called, attempter_.WasUpdateCalled());
2154}
2155
2156TEST_F(UpdateAttempterTest, OnUpdatesScheduledFailed) {
2157 // GIVEN failed status.
2158
2159 // THEN update should be scheduled.
2160 ous_params_.should_schedule_updates_be_called = true;
2161
2162 TestOnUpdateScheduled();
2163}
2164
2165TEST_F(UpdateAttempterTest, OnUpdatesScheduledAskMeAgainLater) {
2166 // GIVEN ask me again later status.
2167 ous_params_.status = EvalStatus::kAskMeAgainLater;
2168
2169 // THEN update should be scheduled.
2170 ous_params_.should_schedule_updates_be_called = true;
2171
2172 TestOnUpdateScheduled();
2173}
2174
2175TEST_F(UpdateAttempterTest, OnUpdatesScheduledContinue) {
2176 // GIVEN continue status.
2177 ous_params_.status = EvalStatus::kContinue;
2178
2179 // THEN update should be scheduled.
2180 ous_params_.should_schedule_updates_be_called = true;
2181
2182 TestOnUpdateScheduled();
2183}
2184
2185TEST_F(UpdateAttempterTest, OnUpdatesScheduledSucceededButUpdateDisabledFails) {
2186 // GIVEN updates disabled.
2187 ous_params_.params = {.updates_enabled = false};
2188 // GIVEN succeeded status.
2189 ous_params_.status = EvalStatus::kSucceeded;
2190
2191 // THEN update should not be scheduled.
2192
2193 TestOnUpdateScheduled();
2194}
2195
2196TEST_F(UpdateAttempterTest, OnUpdatesScheduledSucceeded) {
2197 // GIVEN updates enabled.
2198 ous_params_.params = {.updates_enabled = true};
2199 // GIVEN succeeded status.
2200 ous_params_.status = EvalStatus::kSucceeded;
2201
2202 // THEN update should be called indicating status change.
2203 ous_params_.exit_status = UpdateStatus::CHECKING_FOR_UPDATE;
2204 ous_params_.should_update_be_called = true;
2205
2206 TestOnUpdateScheduled();
2207}
2208
Amin Hassani9be122e2019-08-29 09:20:12 -07002209TEST_F(UpdateAttempterTest, IsEnterpriseRollbackInGetStatusDefault) {
2210 UpdateEngineStatus status;
2211 attempter_.GetStatus(&status);
2212 EXPECT_FALSE(status.is_enterprise_rollback);
2213}
2214
2215TEST_F(UpdateAttempterTest, IsEnterpriseRollbackInGetStatusFalse) {
2216 attempter_.install_plan_.reset(new InstallPlan);
2217 attempter_.install_plan_->is_rollback = false;
2218
2219 UpdateEngineStatus status;
2220 attempter_.GetStatus(&status);
2221 EXPECT_FALSE(status.is_enterprise_rollback);
2222}
2223
2224TEST_F(UpdateAttempterTest, IsEnterpriseRollbackInGetStatusTrue) {
2225 attempter_.install_plan_.reset(new InstallPlan);
2226 attempter_.install_plan_->is_rollback = true;
2227
2228 UpdateEngineStatus status;
2229 attempter_.GetStatus(&status);
2230 EXPECT_TRUE(status.is_enterprise_rollback);
2231}
2232
Miriam Polzer0cf1acb2020-04-29 17:39:51 +02002233TEST_F(UpdateAttempterTest, PowerwashInGetStatusDefault) {
2234 UpdateEngineStatus status;
2235 attempter_.GetStatus(&status);
2236 EXPECT_FALSE(status.will_powerwash_after_reboot);
2237}
2238
2239TEST_F(UpdateAttempterTest, PowerwashInGetStatusTrueBecausePowerwashRequired) {
2240 attempter_.install_plan_.reset(new InstallPlan);
2241 attempter_.install_plan_->powerwash_required = true;
2242
2243 UpdateEngineStatus status;
2244 attempter_.GetStatus(&status);
2245 EXPECT_TRUE(status.will_powerwash_after_reboot);
2246}
2247
2248TEST_F(UpdateAttempterTest, PowerwashInGetStatusTrueBecauseRollback) {
2249 attempter_.install_plan_.reset(new InstallPlan);
2250 attempter_.install_plan_->is_rollback = true;
2251
2252 UpdateEngineStatus status;
2253 attempter_.GetStatus(&status);
2254 EXPECT_TRUE(status.will_powerwash_after_reboot);
2255}
2256
Jae Hoon Kim051627a2019-09-03 12:56:32 -07002257TEST_F(UpdateAttempterTest, FutureEolTest) {
2258 EolDate eol_date = std::numeric_limits<int64_t>::max();
Amin Hassani90e9f192020-11-18 14:20:56 -08002259 EXPECT_TRUE(prefs_->SetString(kPrefsOmahaEolDate, EolDateToString(eol_date)));
Jae Hoon Kim051627a2019-09-03 12:56:32 -07002260 UpdateEngineStatus status;
2261 attempter_.GetStatus(&status);
2262 EXPECT_EQ(eol_date, status.eol_date);
2263}
2264
2265TEST_F(UpdateAttempterTest, PastEolTest) {
2266 EolDate eol_date = 1;
Amin Hassani90e9f192020-11-18 14:20:56 -08002267 EXPECT_TRUE(prefs_->SetString(kPrefsOmahaEolDate, EolDateToString(eol_date)));
Jae Hoon Kim051627a2019-09-03 12:56:32 -07002268 UpdateEngineStatus status;
2269 attempter_.GetStatus(&status);
2270 EXPECT_EQ(eol_date, status.eol_date);
2271}
2272
Jae Hoon Kim2dfd35d2020-06-02 10:53:13 -07002273TEST_F(UpdateAttempterTest, MissingEolTest) {
Jae Hoon Kim2dfd35d2020-06-02 10:53:13 -07002274 UpdateEngineStatus status;
2275 attempter_.GetStatus(&status);
2276 EXPECT_EQ(kEolDateInvalid, status.eol_date);
Jae Hoon Kim051627a2019-09-03 12:56:32 -07002277}
2278
Andrewe045aef2020-01-08 16:29:22 -08002279TEST_F(UpdateAttempterTest, CalculateDlcParamsInstallTest) {
Andrewe045aef2020-01-08 16:29:22 -08002280 string dlc_id = "dlc0";
Andrewe045aef2020-01-08 16:29:22 -08002281 attempter_.is_install_ = true;
Amin Hassani2b68e6b2020-04-17 10:49:12 -07002282 attempter_.dlc_ids_ = {dlc_id};
Andrewe045aef2020-01-08 16:29:22 -08002283 attempter_.CalculateDlcParams();
2284
Amin Hassani538bd592020-11-04 20:46:08 -08002285 OmahaRequestParams* params = FakeSystemState::Get()->request_params();
Andrewe045aef2020-01-08 16:29:22 -08002286 EXPECT_EQ(1, params->dlc_apps_params().count(params->GetDlcAppId(dlc_id)));
2287 OmahaRequestParams::AppParams dlc_app_params =
2288 params->dlc_apps_params().at(params->GetDlcAppId(dlc_id));
2289 EXPECT_STREQ(dlc_id.c_str(), dlc_app_params.name.c_str());
2290 EXPECT_EQ(false, dlc_app_params.send_ping);
2291 // When the DLC gets installed, a ping is not sent, therefore we don't store
2292 // the values sent by Omaha.
Andrew065d78d2020-04-07 15:43:07 -07002293 auto last_active_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002294 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastActive});
Amin Hassani538bd592020-11-04 20:46:08 -08002295 EXPECT_FALSE(FakeSystemState::Get()->prefs()->Exists(last_active_key));
Andrew065d78d2020-04-07 15:43:07 -07002296 auto last_rollcall_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002297 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastRollcall});
Amin Hassani538bd592020-11-04 20:46:08 -08002298 EXPECT_FALSE(FakeSystemState::Get()->prefs()->Exists(last_rollcall_key));
Andrewe045aef2020-01-08 16:29:22 -08002299}
2300
2301TEST_F(UpdateAttempterTest, CalculateDlcParamsNoPrefFilesTest) {
Andrewe045aef2020-01-08 16:29:22 -08002302 string dlc_id = "dlc0";
Amin Hassani2b68e6b2020-04-17 10:49:12 -07002303 EXPECT_CALL(mock_dlcservice_, GetDlcsToUpdate(_))
Andrewe045aef2020-01-08 16:29:22 -08002304 .WillOnce(
2305 DoAll(SetArgPointee<0>(std::vector<string>({dlc_id})), Return(true)));
2306
2307 attempter_.is_install_ = false;
2308 attempter_.CalculateDlcParams();
2309
Amin Hassani538bd592020-11-04 20:46:08 -08002310 OmahaRequestParams* params = FakeSystemState::Get()->request_params();
Andrewe045aef2020-01-08 16:29:22 -08002311 EXPECT_EQ(1, params->dlc_apps_params().count(params->GetDlcAppId(dlc_id)));
2312 OmahaRequestParams::AppParams dlc_app_params =
2313 params->dlc_apps_params().at(params->GetDlcAppId(dlc_id));
2314 EXPECT_STREQ(dlc_id.c_str(), dlc_app_params.name.c_str());
2315
2316 EXPECT_EQ(true, dlc_app_params.send_ping);
2317 EXPECT_EQ(0, dlc_app_params.ping_active);
2318 EXPECT_EQ(-1, dlc_app_params.ping_date_last_active);
2319 EXPECT_EQ(-1, dlc_app_params.ping_date_last_rollcall);
2320}
2321
2322TEST_F(UpdateAttempterTest, CalculateDlcParamsNonParseableValuesTest) {
Andrewe045aef2020-01-08 16:29:22 -08002323 string dlc_id = "dlc0";
Andrew065d78d2020-04-07 15:43:07 -07002324 MemoryPrefs prefs;
Amin Hassani538bd592020-11-04 20:46:08 -08002325 FakeSystemState::Get()->set_prefs(&prefs);
Amin Hassani2b68e6b2020-04-17 10:49:12 -07002326 EXPECT_CALL(mock_dlcservice_, GetDlcsToUpdate(_))
Andrewe045aef2020-01-08 16:29:22 -08002327 .WillOnce(
2328 DoAll(SetArgPointee<0>(std::vector<string>({dlc_id})), Return(true)));
2329
2330 // Write non numeric values in the metadata files.
Andrew065d78d2020-04-07 15:43:07 -07002331 auto active_key =
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002332 PrefsInterface::CreateSubKey({kDlcPrefsSubDir, dlc_id, kPrefsPingActive});
Andrew065d78d2020-04-07 15:43:07 -07002333 auto last_active_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002334 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastActive});
Andrew065d78d2020-04-07 15:43:07 -07002335 auto last_rollcall_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002336 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastRollcall});
Amin Hassani538bd592020-11-04 20:46:08 -08002337 FakeSystemState::Get()->prefs()->SetString(active_key, "z2yz");
2338 FakeSystemState::Get()->prefs()->SetString(last_active_key, "z2yz");
2339 FakeSystemState::Get()->prefs()->SetString(last_rollcall_key, "z2yz");
Andrewe045aef2020-01-08 16:29:22 -08002340 attempter_.is_install_ = false;
2341 attempter_.CalculateDlcParams();
2342
Amin Hassani538bd592020-11-04 20:46:08 -08002343 OmahaRequestParams* params = FakeSystemState::Get()->request_params();
Andrewe045aef2020-01-08 16:29:22 -08002344 EXPECT_EQ(1, params->dlc_apps_params().count(params->GetDlcAppId(dlc_id)));
2345 OmahaRequestParams::AppParams dlc_app_params =
2346 params->dlc_apps_params().at(params->GetDlcAppId(dlc_id));
2347 EXPECT_STREQ(dlc_id.c_str(), dlc_app_params.name.c_str());
2348
2349 EXPECT_EQ(true, dlc_app_params.send_ping);
2350 EXPECT_EQ(0, dlc_app_params.ping_active);
2351 EXPECT_EQ(-2, dlc_app_params.ping_date_last_active);
2352 EXPECT_EQ(-2, dlc_app_params.ping_date_last_rollcall);
2353}
2354
2355TEST_F(UpdateAttempterTest, CalculateDlcParamsValidValuesTest) {
Andrewe045aef2020-01-08 16:29:22 -08002356 string dlc_id = "dlc0";
Amin Hassani2b68e6b2020-04-17 10:49:12 -07002357 EXPECT_CALL(mock_dlcservice_, GetDlcsToUpdate(_))
Andrewe045aef2020-01-08 16:29:22 -08002358 .WillOnce(
2359 DoAll(SetArgPointee<0>(std::vector<string>({dlc_id})), Return(true)));
2360
2361 // Write numeric values in the metadata files.
Andrew065d78d2020-04-07 15:43:07 -07002362 auto active_key =
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002363 PrefsInterface::CreateSubKey({kDlcPrefsSubDir, dlc_id, kPrefsPingActive});
Andrew065d78d2020-04-07 15:43:07 -07002364 auto last_active_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002365 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastActive});
Andrew065d78d2020-04-07 15:43:07 -07002366 auto last_rollcall_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002367 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastRollcall});
Andrew065d78d2020-04-07 15:43:07 -07002368
Amin Hassani538bd592020-11-04 20:46:08 -08002369 FakeSystemState::Get()->prefs()->SetInt64(active_key, 1);
2370 FakeSystemState::Get()->prefs()->SetInt64(last_active_key, 78);
2371 FakeSystemState::Get()->prefs()->SetInt64(last_rollcall_key, 99);
Andrewe045aef2020-01-08 16:29:22 -08002372 attempter_.is_install_ = false;
2373 attempter_.CalculateDlcParams();
2374
Amin Hassani538bd592020-11-04 20:46:08 -08002375 OmahaRequestParams* params = FakeSystemState::Get()->request_params();
Andrewe045aef2020-01-08 16:29:22 -08002376 EXPECT_EQ(1, params->dlc_apps_params().count(params->GetDlcAppId(dlc_id)));
2377 OmahaRequestParams::AppParams dlc_app_params =
2378 params->dlc_apps_params().at(params->GetDlcAppId(dlc_id));
2379 EXPECT_STREQ(dlc_id.c_str(), dlc_app_params.name.c_str());
2380
2381 EXPECT_EQ(true, dlc_app_params.send_ping);
2382 EXPECT_EQ(1, dlc_app_params.ping_active);
2383 EXPECT_EQ(78, dlc_app_params.ping_date_last_active);
2384 EXPECT_EQ(99, dlc_app_params.ping_date_last_rollcall);
2385}
Andrewa8d7df32020-03-15 20:10:01 -07002386
2387TEST_F(UpdateAttempterTest, CalculateDlcParamsRemoveStaleMetadata) {
Andrewa8d7df32020-03-15 20:10:01 -07002388 string dlc_id = "dlc0";
Andrew065d78d2020-04-07 15:43:07 -07002389 auto active_key =
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002390 PrefsInterface::CreateSubKey({kDlcPrefsSubDir, dlc_id, kPrefsPingActive});
Andrew065d78d2020-04-07 15:43:07 -07002391 auto last_active_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002392 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastActive});
Andrew065d78d2020-04-07 15:43:07 -07002393 auto last_rollcall_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002394 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastRollcall});
Amin Hassani538bd592020-11-04 20:46:08 -08002395 FakeSystemState::Get()->prefs()->SetInt64(active_key, kPingInactiveValue);
2396 FakeSystemState::Get()->prefs()->SetInt64(last_active_key, 0);
2397 FakeSystemState::Get()->prefs()->SetInt64(last_rollcall_key, 0);
2398 EXPECT_TRUE(FakeSystemState::Get()->prefs()->Exists(active_key));
2399 EXPECT_TRUE(FakeSystemState::Get()->prefs()->Exists(last_active_key));
2400 EXPECT_TRUE(FakeSystemState::Get()->prefs()->Exists(last_rollcall_key));
Andrewa8d7df32020-03-15 20:10:01 -07002401
Andrew065d78d2020-04-07 15:43:07 -07002402 attempter_.dlc_ids_ = {dlc_id};
2403 attempter_.is_install_ = true;
Andrewa8d7df32020-03-15 20:10:01 -07002404 attempter_.CalculateDlcParams();
2405
Amin Hassani538bd592020-11-04 20:46:08 -08002406 EXPECT_FALSE(FakeSystemState::Get()->prefs()->Exists(last_active_key));
2407 EXPECT_FALSE(FakeSystemState::Get()->prefs()->Exists(last_rollcall_key));
Andrew065d78d2020-04-07 15:43:07 -07002408 // Active key is set on install.
Amin Hassani538bd592020-11-04 20:46:08 -08002409 EXPECT_TRUE(FakeSystemState::Get()->prefs()->Exists(active_key));
Andrew065d78d2020-04-07 15:43:07 -07002410 int64_t temp_int;
Amin Hassani538bd592020-11-04 20:46:08 -08002411 EXPECT_TRUE(FakeSystemState::Get()->prefs()->GetInt64(active_key, &temp_int));
Andrew065d78d2020-04-07 15:43:07 -07002412 EXPECT_EQ(temp_int, kPingActiveValue);
Andrewa8d7df32020-03-15 20:10:01 -07002413}
2414
2415TEST_F(UpdateAttempterTest, SetDlcActiveValue) {
Andrewa8d7df32020-03-15 20:10:01 -07002416 string dlc_id = "dlc0";
Andrewa8d7df32020-03-15 20:10:01 -07002417 attempter_.SetDlcActiveValue(true, dlc_id);
Andrewa8d7df32020-03-15 20:10:01 -07002418 int64_t temp_int;
Andrew065d78d2020-04-07 15:43:07 -07002419 auto active_key =
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002420 PrefsInterface::CreateSubKey({kDlcPrefsSubDir, dlc_id, kPrefsPingActive});
Amin Hassani538bd592020-11-04 20:46:08 -08002421 EXPECT_TRUE(FakeSystemState::Get()->prefs()->Exists(active_key));
2422 EXPECT_TRUE(FakeSystemState::Get()->prefs()->GetInt64(active_key, &temp_int));
Andrewa8d7df32020-03-15 20:10:01 -07002423 EXPECT_EQ(temp_int, kPingActiveValue);
2424}
2425
2426TEST_F(UpdateAttempterTest, SetDlcInactive) {
Andrewa8d7df32020-03-15 20:10:01 -07002427 string dlc_id = "dlc0";
Andrew065d78d2020-04-07 15:43:07 -07002428 auto sub_keys = {
2429 kPrefsPingActive, kPrefsPingLastActive, kPrefsPingLastRollcall};
2430 for (auto& sub_key : sub_keys) {
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002431 auto key = PrefsInterface::CreateSubKey({kDlcPrefsSubDir, dlc_id, sub_key});
Amin Hassani538bd592020-11-04 20:46:08 -08002432 FakeSystemState::Get()->prefs()->SetInt64(key, 1);
2433 EXPECT_TRUE(FakeSystemState::Get()->prefs()->Exists(key));
Andrew065d78d2020-04-07 15:43:07 -07002434 }
Andrewa8d7df32020-03-15 20:10:01 -07002435 attempter_.SetDlcActiveValue(false, dlc_id);
Andrew065d78d2020-04-07 15:43:07 -07002436 for (auto& sub_key : sub_keys) {
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002437 auto key = PrefsInterface::CreateSubKey({kDlcPrefsSubDir, dlc_id, sub_key});
Amin Hassani538bd592020-11-04 20:46:08 -08002438 EXPECT_FALSE(FakeSystemState::Get()->prefs()->Exists(key));
Andrew065d78d2020-04-07 15:43:07 -07002439 }
Andrewa8d7df32020-03-15 20:10:01 -07002440}
2441
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002442TEST_F(UpdateAttempterTest, GetSuccessfulDlcIds) {
2443 auto dlc_1 = "1", dlc_2 = "2", dlc_3 = "3";
2444 attempter_.omaha_request_params_->set_dlc_apps_params(
2445 {{dlc_1, {.name = dlc_1, .updated = false}},
2446 {dlc_2, {.name = dlc_2}},
2447 {dlc_3, {.name = dlc_3, .updated = false}}});
2448 EXPECT_THAT(attempter_.GetSuccessfulDlcIds(), ElementsAre(dlc_2));
2449}
2450
Vyshu6e8a37b2020-11-25 10:31:00 -08002451TEST_F(UpdateAttempterTest, MoveToPrefs) {
2452 string key1 = kPrefsLastActivePingDay;
2453 string key2 = kPrefsPingLastRollcall;
2454
2455 FakePrefs fake_prefs;
2456 EXPECT_TRUE(fake_prefs.SetString(key2, "current-rollcall"));
2457 FakeSystemState::Get()->set_prefs(&fake_prefs);
2458
2459 FakePrefs powerwash_safe_prefs;
2460 EXPECT_TRUE(powerwash_safe_prefs.SetString(key1, "powerwash-last-active"));
2461 EXPECT_TRUE(powerwash_safe_prefs.SetString(key2, "powerwash-last-rollcall"));
2462 FakeSystemState::Get()->set_powerwash_safe_prefs(&powerwash_safe_prefs);
2463
2464 attempter_.Init();
2465 attempter_.MoveToPrefs({key1, key2});
2466
2467 string pref_value_1;
2468 fake_prefs.GetString(key1, &pref_value_1);
2469 EXPECT_EQ(pref_value_1, "powerwash-last-active");
2470 // Do not overwrite if value already exists.
2471 string pref_value_2;
2472 fake_prefs.GetString(key2, &pref_value_2);
2473 EXPECT_EQ(pref_value_2, "current-rollcall");
2474
2475 // Make sure keys are deleted from powerwash safe prefs regardless of whether
2476 // they are written to prefs.
2477 EXPECT_FALSE(FakeSystemState::Get()->powerwash_safe_prefs()->Exists(key1));
2478 EXPECT_FALSE(FakeSystemState::Get()->powerwash_safe_prefs()->Exists(key2));
2479}
2480
Darin Petkovf42cc1c2010-09-01 09:03:02 -07002481} // namespace chromeos_update_engine