blob: ab4a5f2c82e057ae54dfe0efa490da6ce81d7fda [file] [log] [blame]
Alex Deymoaea4c1c2015-08-19 20:24:43 -07001//
2// Copyright (C) 2012 The Android Open Source Project
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15//
Darin Petkovf42cc1c2010-09-01 09:03:02 -070016
Amin Hassaniec7bc112020-10-29 16:47:58 -070017#include "update_engine/cros/update_attempter.h"
Alex Deymo2c0db7b2014-11-04 12:23:39 -080018
Ben Chan9abb7632014-08-07 00:10:53 -070019#include <stdint.h>
20
Jae Hoon Kim051627a2019-09-03 12:56:32 -070021#include <limits>
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -070022#include <map>
Ben Chan02f7c1d2014-10-18 15:18:02 -070023#include <memory>
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -070024#include <string>
Jae Hoon Kimedb65502019-06-14 11:52:17 -070025#include <unordered_set>
Ben Chan02f7c1d2014-10-18 15:18:02 -070026
Ben Chan06c76a42014-09-05 08:21:06 -070027#include <base/files/file_util.h>
Miriam Polzeraff72002020-08-27 08:20:39 +020028#include <base/files/scoped_temp_dir.h>
Qijiang Fanb0b6cc22020-10-15 21:54:11 +090029#include <base/task/single_thread_task_executor.h>
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -070030#include <brillo/message_loops/base_message_loop.h>
31#include <brillo/message_loops/message_loop.h>
32#include <brillo/message_loops/message_loop_utils.h>
Darin Petkovf42cc1c2010-09-01 09:03:02 -070033#include <gtest/gtest.h>
Patrick Dubroy7fbbe8a2011-08-01 17:28:22 +020034#include <policy/libpolicy.h>
35#include <policy/mock_device_policy.h>
Marton Hunyadye58bddb2018-04-10 20:27:26 +020036#include <policy/mock_libpolicy.h>
Darin Petkovf42cc1c2010-09-01 09:03:02 -070037
Jae Hoon Kim0ae8fe12019-06-26 14:32:50 -070038#include "update_engine/common/constants.h"
Xiaochu Liu8ba486f2018-11-06 11:14:10 -080039#include "update_engine/common/dlcservice_interface.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080040#include "update_engine/common/fake_clock.h"
41#include "update_engine/common/fake_prefs.h"
Alex Deymo14fd1ec2016-02-24 22:03:57 -080042#include "update_engine/common/mock_action.h"
43#include "update_engine/common/mock_action_processor.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080044#include "update_engine/common/mock_http_fetcher.h"
45#include "update_engine/common/mock_prefs.h"
Amin Hassaniec7bc112020-10-29 16:47:58 -070046#include "update_engine/common/mock_service_observer.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080047#include "update_engine/common/platform_constants.h"
48#include "update_engine/common/prefs.h"
49#include "update_engine/common/test_utils.h"
50#include "update_engine/common/utils.h"
Amin Hassaniec7bc112020-10-29 16:47:58 -070051#include "update_engine/cros/fake_system_state.h"
52#include "update_engine/cros/mock_p2p_manager.h"
53#include "update_engine/cros/mock_payload_state.h"
54#include "update_engine/cros/omaha_utils.h"
Jae Hoon Kim0ae8fe12019-06-26 14:32:50 -070055#include "update_engine/libcurl_http_fetcher.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080056#include "update_engine/payload_consumer/filesystem_verifier_action.h"
57#include "update_engine/payload_consumer/install_plan.h"
58#include "update_engine/payload_consumer/payload_constants.h"
59#include "update_engine/payload_consumer/postinstall_runner_action.h"
Amin Hassani0882a512018-04-05 16:25:44 -070060#include "update_engine/update_boot_flags_action.h"
Jae Hoon Kim504c3cb2019-07-02 11:17:24 -070061#include "update_engine/update_manager/mock_update_manager.h"
Darin Petkovf42cc1c2010-09-01 09:03:02 -070062
David Zeuthen985b1122013-10-09 12:13:15 -070063using base::Time;
64using base::TimeDelta;
Aaron Woodbf5a2522017-10-04 10:58:36 -070065using chromeos_update_manager::EvalStatus;
Jae Hoon Kim504c3cb2019-07-02 11:17:24 -070066using chromeos_update_manager::MockUpdateManager;
Adolfo Victoria497044c2018-07-18 07:51:42 -070067using chromeos_update_manager::StagingSchedule;
Aaron Woodbf5a2522017-10-04 10:58:36 -070068using chromeos_update_manager::UpdateCheckParams;
Adolfo Victoria497044c2018-07-18 07:51:42 -070069using policy::DevicePolicy;
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -070070using std::map;
Darin Petkovf42cc1c2010-09-01 09:03:02 -070071using std::string;
Ben Chan02f7c1d2014-10-18 15:18:02 -070072using std::unique_ptr;
Jae Hoon Kimedb65502019-06-14 11:52:17 -070073using std::unordered_set;
Xiaochu Liu88d90382018-08-29 16:09:11 -070074using std::vector;
Aaron Woodbf5a2522017-10-04 10:58:36 -070075using testing::_;
Andrew065d78d2020-04-07 15:43:07 -070076using testing::Contains;
Darin Petkov36275772010-10-01 11:40:57 -070077using testing::DoAll;
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -070078using testing::ElementsAre;
Aaron Wood7f92e2b2017-08-28 14:51:21 -070079using testing::Field;
Darin Petkovf42cc1c2010-09-01 09:03:02 -070080using testing::InSequence;
Jae Hoon Kimedb65502019-06-14 11:52:17 -070081using testing::Invoke;
Darin Petkov2dd01092010-10-08 15:43:05 -070082using testing::Ne;
Darin Petkov9c096d62010-11-17 14:49:04 -080083using testing::NiceMock;
Amin Hassanid3f4bea2018-04-30 14:52:40 -070084using testing::Pointee;
Darin Petkovf42cc1c2010-09-01 09:03:02 -070085using testing::Property;
86using testing::Return;
Gilad Arnold74b5f552014-10-07 08:17:16 -070087using testing::ReturnPointee;
Marton Hunyadye58bddb2018-04-10 20:27:26 +020088using testing::ReturnRef;
Alex Deymo2c0db7b2014-11-04 12:23:39 -080089using testing::SaveArg;
Ben Chan672c1f52017-10-23 15:41:39 -070090using testing::SetArgPointee;
Aaron Woodbf5a2522017-10-04 10:58:36 -070091using update_engine::UpdateAttemptFlags;
Aaron Wood7f92e2b2017-08-28 14:51:21 -070092using update_engine::UpdateEngineStatus;
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -070093using update_engine::UpdateStatus;
Darin Petkovf42cc1c2010-09-01 09:03:02 -070094
95namespace chromeos_update_engine {
96
Xiaochu Liu8ba486f2018-11-06 11:14:10 -080097namespace {
98
Jae Hoon Kimc437ea52019-07-11 11:20:38 -070099const UpdateStatus kNonIdleUpdateStatuses[] = {
100 UpdateStatus::CHECKING_FOR_UPDATE,
101 UpdateStatus::UPDATE_AVAILABLE,
102 UpdateStatus::DOWNLOADING,
103 UpdateStatus::VERIFYING,
104 UpdateStatus::FINALIZING,
105 UpdateStatus::UPDATED_NEED_REBOOT,
106 UpdateStatus::REPORTING_ERROR_EVENT,
107 UpdateStatus::ATTEMPTING_ROLLBACK,
108 UpdateStatus::DISABLED,
109 UpdateStatus::NEED_PERMISSION_TO_UPDATE,
110};
111
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -0700112struct CheckForUpdateTestParams {
113 // Setups + Inputs:
114 UpdateStatus status = UpdateStatus::IDLE;
115 string app_version = "fake_app_version";
116 string omaha_url = "fake_omaha_url";
117 UpdateAttemptFlags flags = UpdateAttemptFlags::kNone;
118 bool is_official_build = true;
119 bool are_dev_features_enabled = false;
120
121 // Expects:
122 string expected_forced_app_version = "";
123 string expected_forced_omaha_url = "";
Jae Hoon Kim2b73ac22019-07-02 11:17:24 -0700124 bool should_schedule_updates_be_called = true;
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -0700125 bool expected_result = true;
126};
127
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700128struct OnUpdateScheduledTestParams {
129 // Setups + Inputs:
130 UpdateCheckParams params = {};
131 EvalStatus status = EvalStatus::kFailed;
132 // Expects:
133 UpdateStatus exit_status = UpdateStatus::IDLE;
134 bool should_schedule_updates_be_called = false;
135 bool should_update_be_called = false;
136};
137
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -0700138struct ProcessingDoneTestParams {
139 // Setups + Inputs:
140 bool is_install = false;
141 UpdateStatus status = UpdateStatus::CHECKING_FOR_UPDATE;
142 ActionProcessor* processor = nullptr;
143 ErrorCode code = ErrorCode::kSuccess;
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -0700144 map<string, OmahaRequestParams::AppParams> dlc_apps_params;
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -0700145
146 // Expects:
147 const bool kExpectedIsInstall = false;
148 bool should_schedule_updates_be_called = true;
149 UpdateStatus expected_exit_status = UpdateStatus::IDLE;
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -0700150 bool should_install_completed_be_called = false;
151 bool should_update_completed_be_called = false;
152 vector<string> args_to_install_completed;
153 vector<string> args_to_update_completed;
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -0700154};
155
Xiaochu Liu8ba486f2018-11-06 11:14:10 -0800156class MockDlcService : public DlcServiceInterface {
157 public:
Amin Hassani2b68e6b2020-04-17 10:49:12 -0700158 MOCK_METHOD1(GetDlcsToUpdate, bool(vector<string>*));
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -0700159 MOCK_METHOD1(InstallCompleted, bool(const vector<string>&));
160 MOCK_METHOD1(UpdateCompleted, bool(const vector<string>&));
Xiaochu Liu8ba486f2018-11-06 11:14:10 -0800161};
162
163} // namespace
164
Marton Hunyadya0302682018-05-16 18:52:13 +0200165const char kRollbackVersion[] = "10575.39.2";
166
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700167// Test a subclass rather than the main class directly so that we can mock out
Darin Petkovcd1666f2010-09-23 09:53:44 -0700168// methods within the class. There're explicit unit tests for the mocked out
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700169// methods.
170class UpdateAttempterUnderTest : public UpdateAttempter {
171 public:
Amin Hassani538bd592020-11-04 20:46:08 -0800172 UpdateAttempterUnderTest() : UpdateAttempter(nullptr) {}
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700173
Amin Hassanie8153632020-10-27 15:11:28 -0700174 void Update(const UpdateCheckParams& params) override {
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700175 update_called_ = true;
176 if (do_update_) {
Amin Hassanie8153632020-10-27 15:11:28 -0700177 UpdateAttempter::Update(params);
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700178 return;
179 }
180 LOG(INFO) << "[TEST] Update() disabled.";
181 status_ = UpdateStatus::CHECKING_FOR_UPDATE;
182 }
183
184 void DisableUpdate() { do_update_ = false; }
185
186 bool WasUpdateCalled() const { return update_called_; }
187
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700188 // Wrap the update scheduling method, allowing us to opt out of scheduled
189 // updates for testing purposes.
Xiaochu Liu88d90382018-08-29 16:09:11 -0700190 bool ScheduleUpdates() override {
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700191 schedule_updates_called_ = true;
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700192 if (do_schedule_updates_)
193 return UpdateAttempter::ScheduleUpdates();
194 LOG(INFO) << "[TEST] Update scheduling disabled.";
195 waiting_for_scheduled_check_ = true;
Xiaochu Liu88d90382018-08-29 16:09:11 -0700196 return true;
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700197 }
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700198
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700199 void DisableScheduleUpdates() { do_schedule_updates_ = false; }
200
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700201 // Indicates whether |ScheduleUpdates()| was called.
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700202 bool WasScheduleUpdatesCalled() const { return schedule_updates_called_; }
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700203
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -0700204 // Need to expose following private members of |UpdateAttempter| for tests.
205 const string& forced_app_version() const { return forced_app_version_; }
Alex Deymo60ca1a72015-06-18 18:19:15 -0700206 const string& forced_omaha_url() const { return forced_omaha_url_; }
David Pursell02c18642014-11-06 11:26:11 -0800207
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700208 // Need to expose |waiting_for_scheduled_check_| for testing.
209 void SetWaitingForScheduledCheck(bool waiting) {
210 waiting_for_scheduled_check_ = waiting;
211 }
212
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700213 private:
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700214 // Used for overrides of |Update()|.
215 bool update_called_ = false;
216 bool do_update_ = true;
217
218 // Used for overrides of |ScheduleUpdates()|.
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700219 bool schedule_updates_called_ = false;
220 bool do_schedule_updates_ = true;
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700221};
222
223class UpdateAttempterTest : public ::testing::Test {
224 protected:
Amin Hassani538bd592020-11-04 20:46:08 -0800225 void SetUp() override {
Gilad Arnold1f847232014-04-07 12:07:49 -0700226 // Override system state members.
Amin Hassani538bd592020-11-04 20:46:08 -0800227 FakeSystemState::CreateInstance();
228 FakeSystemState::Get()->set_connection_manager(&mock_connection_manager);
229 FakeSystemState::Get()->set_update_attempter(&attempter_);
230 FakeSystemState::Get()->set_dlcservice(&mock_dlcservice_);
231 FakeSystemState::Get()->set_update_manager(&mock_update_manager_);
Alex Deymo60ca1a72015-06-18 18:19:15 -0700232 loop_.SetAsCurrent();
Gilad Arnold1f847232014-04-07 12:07:49 -0700233
Amin Hassani538bd592020-11-04 20:46:08 -0800234 certificate_checker_.reset(new CertificateChecker(
235 FakeSystemState::Get()->mock_prefs(), &openssl_wrapper_));
236 certificate_checker_->Init();
Alex Deymo33e91e72015-12-01 18:26:08 -0300237
Xiaochu Liu8ba486f2018-11-06 11:14:10 -0800238 attempter_.set_forced_update_pending_callback(
239 new base::Callback<void(bool, bool)>(base::Bind([](bool, bool) {})));
Sen Jiange67bb5b2016-06-20 15:53:56 -0700240 // Finish initializing the attempter.
Gilad Arnold1f847232014-04-07 12:07:49 -0700241 attempter_.Init();
Gilad Arnoldeff87cc2013-07-22 18:32:09 -0700242
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700243 EXPECT_EQ(0, attempter_.http_response_code_);
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700244 EXPECT_EQ(UpdateStatus::IDLE, attempter_.status_);
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700245 EXPECT_EQ(0.0, attempter_.download_progress_);
246 EXPECT_EQ(0, attempter_.last_checked_time_);
247 EXPECT_EQ("0.0.0.0", attempter_.new_version_);
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700248 EXPECT_EQ(0ULL, attempter_.new_payload_size_);
Alex Deymo8427b4a2014-11-05 14:00:32 -0800249 processor_ = new NiceMock<MockActionProcessor>();
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700250 attempter_.processor_.reset(processor_); // Transfers ownership.
Amin Hassani538bd592020-11-04 20:46:08 -0800251 prefs_ = FakeSystemState::Get()->mock_prefs();
Gilad Arnold74b5f552014-10-07 08:17:16 -0700252
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700253 // Setup store/load semantics of P2P properties via the mock |PayloadState|.
Gilad Arnold74b5f552014-10-07 08:17:16 -0700254 actual_using_p2p_for_downloading_ = false;
Amin Hassani538bd592020-11-04 20:46:08 -0800255 EXPECT_CALL(*FakeSystemState::Get()->mock_payload_state(),
Gilad Arnold74b5f552014-10-07 08:17:16 -0700256 SetUsingP2PForDownloading(_))
257 .WillRepeatedly(SaveArg<0>(&actual_using_p2p_for_downloading_));
Amin Hassani538bd592020-11-04 20:46:08 -0800258 EXPECT_CALL(*FakeSystemState::Get()->mock_payload_state(),
Gilad Arnold74b5f552014-10-07 08:17:16 -0700259 GetUsingP2PForDownloading())
260 .WillRepeatedly(ReturnPointee(&actual_using_p2p_for_downloading_));
261 actual_using_p2p_for_sharing_ = false;
Amin Hassani538bd592020-11-04 20:46:08 -0800262 EXPECT_CALL(*FakeSystemState::Get()->mock_payload_state(),
Gilad Arnold74b5f552014-10-07 08:17:16 -0700263 SetUsingP2PForSharing(_))
264 .WillRepeatedly(SaveArg<0>(&actual_using_p2p_for_sharing_));
Amin Hassani538bd592020-11-04 20:46:08 -0800265 EXPECT_CALL(*FakeSystemState::Get()->mock_payload_state(),
Gilad Arnold74b5f552014-10-07 08:17:16 -0700266 GetUsingP2PForDownloading())
267 .WillRepeatedly(ReturnPointee(&actual_using_p2p_for_sharing_));
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700268 }
269
Alex Deymo60ca1a72015-06-18 18:19:15 -0700270 public:
271 void ScheduleQuitMainLoop();
Patrick Dubroy7fbbe8a2011-08-01 17:28:22 +0200272
Alex Deymo60ca1a72015-06-18 18:19:15 -0700273 // Callbacks to run the different tests from the main loop.
Darin Petkove6ef2f82011-03-07 17:31:11 -0800274 void UpdateTestStart();
275 void UpdateTestVerify();
Alex Deymo60ca1a72015-06-18 18:19:15 -0700276 void RollbackTestStart(bool enterprise_rollback, bool valid_slot);
Chris Sosa76a29ae2013-07-11 17:59:24 -0700277 void RollbackTestVerify();
Thieu Le116fda32011-04-19 11:01:54 -0700278 void PingOmahaTestStart();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700279 void ReadScatterFactorFromPolicyTestStart();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700280 void DecrementUpdateCheckCountTestStart();
Jay Srinivasan08fce042012-06-07 16:31:01 -0700281 void NoScatteringDoneDuringManualUpdateTestStart();
David Zeuthen8f191b22013-08-06 12:27:50 -0700282 void P2PNotEnabledStart();
David Zeuthen8f191b22013-08-06 12:27:50 -0700283 void P2PEnabledStart();
David Zeuthen8f191b22013-08-06 12:27:50 -0700284 void P2PEnabledInteractiveStart();
David Zeuthen8f191b22013-08-06 12:27:50 -0700285 void P2PEnabledStartingFailsStart();
David Zeuthen8f191b22013-08-06 12:27:50 -0700286 void P2PEnabledHousekeepingFailsStart();
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700287 void SessionIdTestChange();
288 void SessionIdTestEnforceEmptyStrPingOmaha();
289 void SessionIdTestConsistencyInUpdateFlow();
Jae Hoon Kim0ae8fe12019-06-26 14:32:50 -0700290 void SessionIdTestInDownloadAction();
Amr Aboelkher21ac9962019-05-15 14:50:05 +0200291 void UpdateToQuickFixBuildStart(bool set_token);
Marton Hunyadye58bddb2018-04-10 20:27:26 +0200292 void ResetRollbackHappenedStart(bool is_consumer,
293 bool is_policy_available,
294 bool expected_reset);
Adolfo Victoria497044c2018-07-18 07:51:42 -0700295 // Staging related callbacks.
296 void SetUpStagingTest(const StagingSchedule& schedule, FakePrefs* prefs);
297 void CheckStagingOff();
298 void StagingSetsPrefsAndTurnsOffScatteringStart();
299 void StagingOffIfInteractiveStart();
300 void StagingOffIfOobeStart();
David Zeuthen8f191b22013-08-06 12:27:50 -0700301
Gilad Arnold74b5f552014-10-07 08:17:16 -0700302 bool actual_using_p2p_for_downloading() {
303 return actual_using_p2p_for_downloading_;
304 }
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800305 bool actual_using_p2p_for_sharing() { return actual_using_p2p_for_sharing_; }
Gilad Arnold74b5f552014-10-07 08:17:16 -0700306
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -0700307 // |CheckForUpdate()| related member functions.
308 void TestCheckForUpdate();
309
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700310 // |OnUpdateScheduled()| related member functions.
311 void TestOnUpdateScheduled();
312
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -0700313 // |ProcessingDone()| related member functions.
314 void TestProcessingDone();
315
Qijiang Fanb0b6cc22020-10-15 21:54:11 +0900316 base::SingleThreadTaskExecutor base_loop_{base::MessagePumpType::IO};
317 brillo::BaseMessageLoop loop_{base_loop_.task_runner()};
Alex Deymo60ca1a72015-06-18 18:19:15 -0700318
Amin Hassani538bd592020-11-04 20:46:08 -0800319 UpdateAttempterUnderTest attempter_;
Alex Deymo33e91e72015-12-01 18:26:08 -0300320 OpenSSLWrapper openssl_wrapper_;
Amin Hassani538bd592020-11-04 20:46:08 -0800321 std::unique_ptr<CertificateChecker> certificate_checker_;
Xiaochu Liu8ba486f2018-11-06 11:14:10 -0800322 MockDlcService mock_dlcservice_;
Jae Hoon Kim504c3cb2019-07-02 11:17:24 -0700323 MockUpdateManager mock_update_manager_;
Alex Deymo30534502015-07-20 15:06:33 -0700324
Alex Deymo8427b4a2014-11-05 14:00:32 -0800325 NiceMock<MockActionProcessor>* processor_;
Amin Hassani538bd592020-11-04 20:46:08 -0800326 NiceMock<MockPrefs>* prefs_;
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800327 NiceMock<MockConnectionManager> mock_connection_manager;
Gilad Arnoldeff87cc2013-07-22 18:32:09 -0700328
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -0700329 // |CheckForUpdate()| test params.
330 CheckForUpdateTestParams cfu_params_;
331
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700332 // |OnUpdateScheduled()| test params.
333 OnUpdateScheduledTestParams ous_params_;
334
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -0700335 // |ProcessingDone()| test params.
336 ProcessingDoneTestParams pd_params_;
337
Gilad Arnold74b5f552014-10-07 08:17:16 -0700338 bool actual_using_p2p_for_downloading_;
339 bool actual_using_p2p_for_sharing_;
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700340};
341
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -0700342void UpdateAttempterTest::TestCheckForUpdate() {
343 // Setup
344 attempter_.status_ = cfu_params_.status;
Amin Hassani538bd592020-11-04 20:46:08 -0800345 FakeSystemState::Get()->fake_hardware()->SetIsOfficialBuild(
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -0700346 cfu_params_.is_official_build);
Amin Hassani538bd592020-11-04 20:46:08 -0800347 FakeSystemState::Get()->fake_hardware()->SetAreDevFeaturesEnabled(
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -0700348 cfu_params_.are_dev_features_enabled);
349
350 // Invocation
351 EXPECT_EQ(
352 cfu_params_.expected_result,
353 attempter_.CheckForUpdate(
354 cfu_params_.app_version, cfu_params_.omaha_url, cfu_params_.flags));
355
356 // Verify
357 EXPECT_EQ(cfu_params_.expected_forced_app_version,
358 attempter_.forced_app_version());
359 EXPECT_EQ(cfu_params_.expected_forced_omaha_url,
360 attempter_.forced_omaha_url());
Jae Hoon Kim2b73ac22019-07-02 11:17:24 -0700361 EXPECT_EQ(cfu_params_.should_schedule_updates_be_called,
362 attempter_.WasScheduleUpdatesCalled());
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -0700363}
364
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -0700365void UpdateAttempterTest::TestProcessingDone() {
366 // Setup
367 attempter_.DisableScheduleUpdates();
368 attempter_.is_install_ = pd_params_.is_install;
369 attempter_.status_ = pd_params_.status;
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -0700370 attempter_.omaha_request_params_->set_dlc_apps_params(
371 pd_params_.dlc_apps_params);
372
373 // Expects
374 if (pd_params_.should_install_completed_be_called)
375 EXPECT_CALL(mock_dlcservice_,
376 InstallCompleted(pd_params_.args_to_install_completed))
377 .WillOnce(Return(true));
378 else
379 EXPECT_CALL(mock_dlcservice_, InstallCompleted(_)).Times(0);
380 if (pd_params_.should_update_completed_be_called)
381 EXPECT_CALL(mock_dlcservice_,
382 UpdateCompleted(pd_params_.args_to_update_completed))
383 .WillOnce(Return(true));
384 else
385 EXPECT_CALL(mock_dlcservice_, UpdateCompleted(_)).Times(0);
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -0700386
387 // Invocation
388 attempter_.ProcessingDone(pd_params_.processor, pd_params_.code);
389
390 // Verify
391 EXPECT_EQ(pd_params_.kExpectedIsInstall, attempter_.is_install_);
392 EXPECT_EQ(pd_params_.should_schedule_updates_be_called,
393 attempter_.WasScheduleUpdatesCalled());
394 EXPECT_EQ(pd_params_.expected_exit_status, attempter_.status_);
395}
396
Alex Deymo60ca1a72015-06-18 18:19:15 -0700397void UpdateAttempterTest::ScheduleQuitMainLoop() {
Luis Hector Chavezf1cf3482016-07-19 14:29:19 -0700398 loop_.PostTask(
399 FROM_HERE,
400 base::Bind([](brillo::BaseMessageLoop* loop) { loop->BreakLoop(); },
401 base::Unretained(&loop_)));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700402}
403
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700404void UpdateAttempterTest::SessionIdTestChange() {
405 EXPECT_NE(UpdateStatus::UPDATED_NEED_REBOOT, attempter_.status());
406 const auto old_session_id = attempter_.session_id_;
Amin Hassanie8153632020-10-27 15:11:28 -0700407 attempter_.Update({});
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700408 EXPECT_NE(old_session_id, attempter_.session_id_);
409 ScheduleQuitMainLoop();
410}
411
412TEST_F(UpdateAttempterTest, SessionIdTestChange) {
413 loop_.PostTask(FROM_HERE,
414 base::Bind(&UpdateAttempterTest::SessionIdTestChange,
415 base::Unretained(this)));
416 loop_.Run();
417}
418
419void UpdateAttempterTest::SessionIdTestEnforceEmptyStrPingOmaha() {
420 // The |session_id_| should not be changed and should remain as an empty
421 // string when |status_| is |UPDATED_NEED_REBOOT| (only for consistency)
422 // and |PingOmaha()| is called.
423 attempter_.DisableScheduleUpdates();
424 attempter_.status_ = UpdateStatus::UPDATED_NEED_REBOOT;
425 const auto old_session_id = attempter_.session_id_;
426 auto CheckIfEmptySessionId = [](AbstractAction* aa) {
427 if (aa->Type() == OmahaRequestAction::StaticType()) {
428 EXPECT_TRUE(static_cast<OmahaRequestAction*>(aa)->session_id_.empty());
429 }
430 };
431 EXPECT_CALL(*processor_, EnqueueAction(Pointee(_)))
432 .WillRepeatedly(Invoke(CheckIfEmptySessionId));
433 EXPECT_CALL(*processor_, StartProcessing());
434 attempter_.PingOmaha();
435 EXPECT_EQ(old_session_id, attempter_.session_id_);
436 EXPECT_EQ(UpdateStatus::UPDATED_NEED_REBOOT, attempter_.status_);
437 ScheduleQuitMainLoop();
438}
439
440TEST_F(UpdateAttempterTest, SessionIdTestEnforceEmptyStrPingOmaha) {
441 loop_.PostTask(
442 FROM_HERE,
443 base::Bind(&UpdateAttempterTest::SessionIdTestEnforceEmptyStrPingOmaha,
444 base::Unretained(this)));
445 loop_.Run();
446}
447
448void UpdateAttempterTest::SessionIdTestConsistencyInUpdateFlow() {
449 // All session IDs passed into |OmahaRequestActions| should be enforced to
450 // have the same value in |BuildUpdateActions()|.
451 unordered_set<string> session_ids;
452 // Gather all the session IDs being passed to |OmahaRequestActions|.
453 auto CheckSessionId = [&session_ids](AbstractAction* aa) {
454 if (aa->Type() == OmahaRequestAction::StaticType())
455 session_ids.insert(static_cast<OmahaRequestAction*>(aa)->session_id_);
456 };
457 EXPECT_CALL(*processor_, EnqueueAction(Pointee(_)))
458 .WillRepeatedly(Invoke(CheckSessionId));
459 attempter_.BuildUpdateActions(false);
460 // Validate that all the session IDs are the same.
461 EXPECT_EQ(1, session_ids.size());
462 ScheduleQuitMainLoop();
463}
464
465TEST_F(UpdateAttempterTest, SessionIdTestConsistencyInUpdateFlow) {
466 loop_.PostTask(
467 FROM_HERE,
468 base::Bind(&UpdateAttempterTest::SessionIdTestConsistencyInUpdateFlow,
469 base::Unretained(this)));
470 loop_.Run();
471}
472
Jae Hoon Kim0ae8fe12019-06-26 14:32:50 -0700473void UpdateAttempterTest::SessionIdTestInDownloadAction() {
474 // The session ID passed into |DownloadAction|'s |LibcurlHttpFetcher| should
475 // be enforced to be included in the HTTP header as X-Goog-Update-SessionId.
476 string header_value;
477 auto CheckSessionIdInDownloadAction = [&header_value](AbstractAction* aa) {
478 if (aa->Type() == DownloadAction::StaticType()) {
479 DownloadAction* da = static_cast<DownloadAction*>(aa);
480 EXPECT_TRUE(da->http_fetcher()->GetHeader(kXGoogleUpdateSessionId,
481 &header_value));
482 }
483 };
484 EXPECT_CALL(*processor_, EnqueueAction(Pointee(_)))
485 .WillRepeatedly(Invoke(CheckSessionIdInDownloadAction));
486 attempter_.BuildUpdateActions(false);
487 // Validate that X-Goog-Update_SessionId is set correctly in HTTP Header.
488 EXPECT_EQ(attempter_.session_id_, header_value);
489 ScheduleQuitMainLoop();
490}
491
492TEST_F(UpdateAttempterTest, SessionIdTestInDownloadAction) {
493 loop_.PostTask(FROM_HERE,
494 base::Bind(&UpdateAttempterTest::SessionIdTestInDownloadAction,
495 base::Unretained(this)));
496 loop_.Run();
497}
498
Darin Petkov1b003102010-11-30 10:18:36 -0800499TEST_F(UpdateAttempterTest, ActionCompletedDownloadTest) {
Ben Chan02f7c1d2014-10-18 15:18:02 -0700500 unique_ptr<MockHttpFetcher> fetcher(new MockHttpFetcher("", 0, nullptr));
Darin Petkov1b003102010-11-30 10:18:36 -0800501 fetcher->FailTransfer(503); // Sets the HTTP response code.
Amin Hassani7ecda262017-07-11 17:10:50 -0700502 DownloadAction action(prefs_,
503 nullptr,
504 nullptr,
Amin Hassani7ecda262017-07-11 17:10:50 -0700505 fetcher.release(),
Amin Hassanied37d682018-04-06 13:22:00 -0700506 false /* interactive */);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800507 EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _)).Times(0);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700508 attempter_.ActionCompleted(nullptr, &action, ErrorCode::kSuccess);
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700509 EXPECT_EQ(UpdateStatus::FINALIZING, attempter_.status());
Aaron Wood9321f502017-09-07 11:18:54 -0700510 EXPECT_EQ(0.0, attempter_.download_progress_);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700511 ASSERT_EQ(nullptr, attempter_.error_event_.get());
Darin Petkov1b003102010-11-30 10:18:36 -0800512}
513
514TEST_F(UpdateAttempterTest, ActionCompletedErrorTest) {
Alex Deymo8427b4a2014-11-05 14:00:32 -0800515 MockAction action;
516 EXPECT_CALL(action, Type()).WillRepeatedly(Return("MockAction"));
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700517 attempter_.status_ = UpdateStatus::DOWNLOADING;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800518 EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _))
Darin Petkov1b003102010-11-30 10:18:36 -0800519 .WillOnce(Return(false));
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700520 attempter_.ActionCompleted(nullptr, &action, ErrorCode::kError);
521 ASSERT_NE(nullptr, attempter_.error_event_.get());
Darin Petkov1b003102010-11-30 10:18:36 -0800522}
523
Aaron Wood9321f502017-09-07 11:18:54 -0700524TEST_F(UpdateAttempterTest, DownloadProgressAccumulationTest) {
525 // Simple test case, where all the values match (nothing was skipped)
526 uint64_t bytes_progressed_1 = 1024 * 1024; // 1MB
527 uint64_t bytes_progressed_2 = 1024 * 1024; // 1MB
528 uint64_t bytes_received_1 = bytes_progressed_1;
529 uint64_t bytes_received_2 = bytes_received_1 + bytes_progressed_2;
530 uint64_t bytes_total = 20 * 1024 * 1024; // 20MB
531
532 double progress_1 =
533 static_cast<double>(bytes_received_1) / static_cast<double>(bytes_total);
534 double progress_2 =
535 static_cast<double>(bytes_received_2) / static_cast<double>(bytes_total);
536
537 EXPECT_EQ(0.0, attempter_.download_progress_);
538 // This is set via inspecting the InstallPlan payloads when the
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700539 // |OmahaResponseAction| is completed.
Aaron Wood9321f502017-09-07 11:18:54 -0700540 attempter_.new_payload_size_ = bytes_total;
541 NiceMock<MockServiceObserver> observer;
542 EXPECT_CALL(observer,
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700543 SendStatusUpdate(AllOf(
544 Field(&UpdateEngineStatus::progress, progress_1),
545 Field(&UpdateEngineStatus::status, UpdateStatus::DOWNLOADING),
546 Field(&UpdateEngineStatus::new_size_bytes, bytes_total))));
Aaron Wood9321f502017-09-07 11:18:54 -0700547 EXPECT_CALL(observer,
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700548 SendStatusUpdate(AllOf(
549 Field(&UpdateEngineStatus::progress, progress_2),
550 Field(&UpdateEngineStatus::status, UpdateStatus::DOWNLOADING),
551 Field(&UpdateEngineStatus::new_size_bytes, bytes_total))));
Aaron Wood9321f502017-09-07 11:18:54 -0700552 attempter_.AddObserver(&observer);
553 attempter_.BytesReceived(bytes_progressed_1, bytes_received_1, bytes_total);
554 EXPECT_EQ(progress_1, attempter_.download_progress_);
555 // This iteration validates that a later set of updates to the variables are
556 // properly handled (so that |getStatus()| will return the same progress info
557 // as the callback is receiving.
558 attempter_.BytesReceived(bytes_progressed_2, bytes_received_2, bytes_total);
559 EXPECT_EQ(progress_2, attempter_.download_progress_);
560}
561
562TEST_F(UpdateAttempterTest, ChangeToDownloadingOnReceivedBytesTest) {
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700563 // The transition into |UpdateStatus::DOWNLOADING| happens when the
Aaron Wood9321f502017-09-07 11:18:54 -0700564 // first bytes are received.
565 uint64_t bytes_progressed = 1024 * 1024; // 1MB
566 uint64_t bytes_received = 2 * 1024 * 1024; // 2MB
567 uint64_t bytes_total = 20 * 1024 * 1024; // 300MB
568 attempter_.status_ = UpdateStatus::CHECKING_FOR_UPDATE;
569 // This is set via inspecting the InstallPlan payloads when the
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700570 // |OmahaResponseAction| is completed.
Aaron Wood9321f502017-09-07 11:18:54 -0700571 attempter_.new_payload_size_ = bytes_total;
572 EXPECT_EQ(0.0, attempter_.download_progress_);
573 NiceMock<MockServiceObserver> observer;
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700574 EXPECT_CALL(observer,
575 SendStatusUpdate(AllOf(
576 Field(&UpdateEngineStatus::status, UpdateStatus::DOWNLOADING),
577 Field(&UpdateEngineStatus::new_size_bytes, bytes_total))));
Aaron Wood9321f502017-09-07 11:18:54 -0700578 attempter_.AddObserver(&observer);
579 attempter_.BytesReceived(bytes_progressed, bytes_received, bytes_total);
580 EXPECT_EQ(UpdateStatus::DOWNLOADING, attempter_.status_);
581}
582
583TEST_F(UpdateAttempterTest, BroadcastCompleteDownloadTest) {
584 // There is a special case to ensure that at 100% downloaded,
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700585 // |download_progress_| is updated and broadcastest.
Aaron Wood9321f502017-09-07 11:18:54 -0700586 uint64_t bytes_progressed = 0; // ignored
587 uint64_t bytes_received = 5 * 1024 * 1024; // ignored
588 uint64_t bytes_total = 5 * 1024 * 1024; // 300MB
589 attempter_.status_ = UpdateStatus::DOWNLOADING;
590 attempter_.new_payload_size_ = bytes_total;
591 EXPECT_EQ(0.0, attempter_.download_progress_);
592 NiceMock<MockServiceObserver> observer;
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700593 EXPECT_CALL(observer,
594 SendStatusUpdate(AllOf(
595 Field(&UpdateEngineStatus::progress, 1.0),
596 Field(&UpdateEngineStatus::status, UpdateStatus::DOWNLOADING),
597 Field(&UpdateEngineStatus::new_size_bytes, bytes_total))));
Aaron Wood9321f502017-09-07 11:18:54 -0700598 attempter_.AddObserver(&observer);
599 attempter_.BytesReceived(bytes_progressed, bytes_received, bytes_total);
600 EXPECT_EQ(1.0, attempter_.download_progress_);
601}
602
Darin Petkov1b003102010-11-30 10:18:36 -0800603TEST_F(UpdateAttempterTest, ActionCompletedOmahaRequestTest) {
Ben Chan02f7c1d2014-10-18 15:18:02 -0700604 unique_ptr<MockHttpFetcher> fetcher(new MockHttpFetcher("", 0, nullptr));
Darin Petkov1b003102010-11-30 10:18:36 -0800605 fetcher->FailTransfer(500); // Sets the HTTP response code.
Amin Hassani538bd592020-11-04 20:46:08 -0800606 OmahaRequestAction action(nullptr, std::move(fetcher), false, "");
Darin Petkov1b003102010-11-30 10:18:36 -0800607 ObjectCollectorAction<OmahaResponse> collector_action;
608 BondActions(&action, &collector_action);
609 OmahaResponse response;
610 response.poll_interval = 234;
611 action.SetOutputObject(response);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800612 EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _)).Times(0);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700613 attempter_.ActionCompleted(nullptr, &action, ErrorCode::kSuccess);
Darin Petkov1b003102010-11-30 10:18:36 -0800614 EXPECT_EQ(500, attempter_.http_response_code());
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700615 EXPECT_EQ(UpdateStatus::IDLE, attempter_.status());
Alex Deymo80f70ff2016-02-10 16:08:11 -0800616 EXPECT_EQ(234U, attempter_.server_dictated_poll_interval_);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700617 ASSERT_TRUE(attempter_.error_event_.get() == nullptr);
Darin Petkov1b003102010-11-30 10:18:36 -0800618}
619
Alex Deymo30534502015-07-20 15:06:33 -0700620TEST_F(UpdateAttempterTest, ConstructWithUpdatedMarkerTest) {
Alex Deymo906191f2015-10-12 12:22:44 -0700621 FakePrefs fake_prefs;
622 string boot_id;
623 EXPECT_TRUE(utils::GetBootId(&boot_id));
624 fake_prefs.SetString(kPrefsUpdateCompletedOnBootId, boot_id);
Amin Hassani538bd592020-11-04 20:46:08 -0800625 FakeSystemState::Get()->set_prefs(&fake_prefs);
Sen Jiangaeeb2e02016-06-09 15:00:16 -0700626 attempter_.Init();
627 EXPECT_EQ(UpdateStatus::UPDATED_NEED_REBOOT, attempter_.status());
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700628}
629
630TEST_F(UpdateAttempterTest, GetErrorCodeForActionTest) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700631 EXPECT_EQ(ErrorCode::kSuccess,
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700632 GetErrorCodeForAction(nullptr, ErrorCode::kSuccess));
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700633
Amin Hassani538bd592020-11-04 20:46:08 -0800634 OmahaRequestAction omaha_request_action(nullptr, nullptr, false, "");
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700635 EXPECT_EQ(ErrorCode::kOmahaRequestError,
636 GetErrorCodeForAction(&omaha_request_action, ErrorCode::kError));
Amin Hassani538bd592020-11-04 20:46:08 -0800637 OmahaResponseHandlerAction omaha_response_handler_action;
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800638 EXPECT_EQ(
639 ErrorCode::kOmahaResponseHandlerError,
640 GetErrorCodeForAction(&omaha_response_handler_action, ErrorCode::kError));
Tianjie24f96092020-06-30 12:26:25 -0700641 DynamicPartitionControlStub dynamic_control_stub;
642 FilesystemVerifierAction filesystem_verifier_action(&dynamic_control_stub);
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800643 EXPECT_EQ(
644 ErrorCode::kFilesystemVerifierError,
645 GetErrorCodeForAction(&filesystem_verifier_action, ErrorCode::kError));
Alex Deymob15a0b82015-11-25 20:30:40 -0300646 PostinstallRunnerAction postinstall_runner_action(
Amin Hassani538bd592020-11-04 20:46:08 -0800647 FakeSystemState::Get()->fake_boot_control(),
648 FakeSystemState::Get()->fake_hardware());
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800649 EXPECT_EQ(
650 ErrorCode::kPostinstallRunnerError,
651 GetErrorCodeForAction(&postinstall_runner_action, ErrorCode::kError));
Alex Deymo8427b4a2014-11-05 14:00:32 -0800652 MockAction action_mock;
653 EXPECT_CALL(action_mock, Type()).WillOnce(Return("MockAction"));
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700654 EXPECT_EQ(ErrorCode::kError,
655 GetErrorCodeForAction(&action_mock, ErrorCode::kError));
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700656}
657
Darin Petkov36275772010-10-01 11:40:57 -0700658TEST_F(UpdateAttempterTest, DisableDeltaUpdateIfNeededTest) {
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700659 attempter_.omaha_request_params_->set_delta_okay(true);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800660 EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _))
Darin Petkov36275772010-10-01 11:40:57 -0700661 .WillOnce(Return(false));
662 attempter_.DisableDeltaUpdateIfNeeded();
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700663 EXPECT_TRUE(attempter_.omaha_request_params_->delta_okay());
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800664 EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _))
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800665 .WillOnce(
666 DoAll(SetArgPointee<1>(UpdateAttempter::kMaxDeltaUpdateFailures - 1),
667 Return(true)));
Darin Petkov36275772010-10-01 11:40:57 -0700668 attempter_.DisableDeltaUpdateIfNeeded();
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700669 EXPECT_TRUE(attempter_.omaha_request_params_->delta_okay());
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800670 EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _))
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800671 .WillOnce(
672 DoAll(SetArgPointee<1>(UpdateAttempter::kMaxDeltaUpdateFailures),
673 Return(true)));
Darin Petkov36275772010-10-01 11:40:57 -0700674 attempter_.DisableDeltaUpdateIfNeeded();
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700675 EXPECT_FALSE(attempter_.omaha_request_params_->delta_okay());
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800676 EXPECT_CALL(*prefs_, GetInt64(_, _)).Times(0);
Darin Petkov36275772010-10-01 11:40:57 -0700677 attempter_.DisableDeltaUpdateIfNeeded();
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700678 EXPECT_FALSE(attempter_.omaha_request_params_->delta_okay());
Darin Petkov36275772010-10-01 11:40:57 -0700679}
680
681TEST_F(UpdateAttempterTest, MarkDeltaUpdateFailureTest) {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800682 EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _))
Darin Petkov36275772010-10-01 11:40:57 -0700683 .WillOnce(Return(false))
Ben Chan672c1f52017-10-23 15:41:39 -0700684 .WillOnce(DoAll(SetArgPointee<1>(-1), Return(true)))
685 .WillOnce(DoAll(SetArgPointee<1>(1), Return(true)))
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800686 .WillOnce(
687 DoAll(SetArgPointee<1>(UpdateAttempter::kMaxDeltaUpdateFailures),
688 Return(true)));
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800689 EXPECT_CALL(*prefs_, SetInt64(Ne(kPrefsDeltaUpdateFailures), _))
Darin Petkov2dd01092010-10-08 15:43:05 -0700690 .WillRepeatedly(Return(true));
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800691 EXPECT_CALL(*prefs_, SetInt64(kPrefsDeltaUpdateFailures, 1)).Times(2);
Gilad Arnold74b5f552014-10-07 08:17:16 -0700692 EXPECT_CALL(*prefs_, SetInt64(kPrefsDeltaUpdateFailures, 2));
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800693 EXPECT_CALL(*prefs_,
694 SetInt64(kPrefsDeltaUpdateFailures,
695 UpdateAttempter::kMaxDeltaUpdateFailures + 1));
696 for (int i = 0; i < 4; i++)
Darin Petkov36275772010-10-01 11:40:57 -0700697 attempter_.MarkDeltaUpdateFailure();
698}
699
Darin Petkov1b003102010-11-30 10:18:36 -0800700TEST_F(UpdateAttempterTest, ScheduleErrorEventActionNoEventTest) {
701 EXPECT_CALL(*processor_, EnqueueAction(_)).Times(0);
702 EXPECT_CALL(*processor_, StartProcessing()).Times(0);
Amin Hassani538bd592020-11-04 20:46:08 -0800703 EXPECT_CALL(*FakeSystemState::Get()->mock_payload_state(), UpdateFailed(_))
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800704 .Times(0);
705 OmahaResponse response;
Jay Srinivasan53173b92013-05-17 17:13:01 -0700706 string url1 = "http://url1";
Sen Jiang0affc2c2017-02-10 15:55:05 -0800707 response.packages.push_back({.payload_urls = {url1, "https://url"}});
Amin Hassani538bd592020-11-04 20:46:08 -0800708 EXPECT_CALL(*(FakeSystemState::Get()->mock_payload_state()), GetCurrentUrl())
Jay Srinivasan53173b92013-05-17 17:13:01 -0700709 .WillRepeatedly(Return(url1));
Amin Hassani538bd592020-11-04 20:46:08 -0800710 FakeSystemState::Get()->mock_payload_state()->SetResponse(response);
Darin Petkov1b003102010-11-30 10:18:36 -0800711 attempter_.ScheduleErrorEventAction();
Amin Hassani538bd592020-11-04 20:46:08 -0800712 EXPECT_EQ(url1,
713 FakeSystemState::Get()->mock_payload_state()->GetCurrentUrl());
Darin Petkov1b003102010-11-30 10:18:36 -0800714}
715
716TEST_F(UpdateAttempterTest, ScheduleErrorEventActionTest) {
717 EXPECT_CALL(*processor_,
Amin Hassanid3f4bea2018-04-30 14:52:40 -0700718 EnqueueAction(Pointee(Property(
719 &AbstractAction::Type, OmahaRequestAction::StaticType()))));
Gilad Arnold74b5f552014-10-07 08:17:16 -0700720 EXPECT_CALL(*processor_, StartProcessing());
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700721 ErrorCode err = ErrorCode::kError;
Amin Hassani538bd592020-11-04 20:46:08 -0800722 EXPECT_CALL(*FakeSystemState::Get()->mock_payload_state(), UpdateFailed(err));
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800723 attempter_.error_event_.reset(new OmahaEvent(
724 OmahaEvent::kTypeUpdateComplete, OmahaEvent::kResultError, err));
Darin Petkov1b003102010-11-30 10:18:36 -0800725 attempter_.ScheduleErrorEventAction();
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700726 EXPECT_EQ(UpdateStatus::REPORTING_ERROR_EVENT, attempter_.status());
Darin Petkov1b003102010-11-30 10:18:36 -0800727}
728
Darin Petkove6ef2f82011-03-07 17:31:11 -0800729namespace {
Chris Sosa76a29ae2013-07-11 17:59:24 -0700730// Actions that will be built as part of an update check.
Askar Aitzhan570ca872019-04-24 11:16:12 +0200731vector<string> GetUpdateActionTypes() {
732 return {OmahaRequestAction::StaticType(),
733 OmahaResponseHandlerAction::StaticType(),
734 UpdateBootFlagsAction::StaticType(),
735 OmahaRequestAction::StaticType(),
736 DownloadAction::StaticType(),
737 OmahaRequestAction::StaticType(),
738 FilesystemVerifierAction::StaticType(),
739 PostinstallRunnerAction::StaticType(),
740 OmahaRequestAction::StaticType()};
741}
Chris Sosa76a29ae2013-07-11 17:59:24 -0700742
743// Actions that will be built as part of a user-initiated rollback.
Askar Aitzhan570ca872019-04-24 11:16:12 +0200744vector<string> GetRollbackActionTypes() {
745 return {InstallPlanAction::StaticType(),
746 PostinstallRunnerAction::StaticType()};
747}
Chris Sosa76a29ae2013-07-11 17:59:24 -0700748
Adolfo Victoria497044c2018-07-18 07:51:42 -0700749const StagingSchedule kValidStagingSchedule = {
750 {4, 10}, {10, 40}, {19, 70}, {26, 100}};
751
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700752} // namespace
Darin Petkove6ef2f82011-03-07 17:31:11 -0800753
754void UpdateAttempterTest::UpdateTestStart() {
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700755 attempter_.set_http_response_code(200);
Alex Deymo749ecf12014-10-21 20:06:57 -0700756
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700757 // Expect that the device policy is loaded by the |UpdateAttempter| at some
758 // point by calling |RefreshDevicePolicy()|.
Igor9fd76b62017-12-11 15:24:18 +0100759 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Alex Deymo749ecf12014-10-21 20:06:57 -0700760 EXPECT_CALL(*device_policy, LoadPolicy())
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800761 .Times(testing::AtLeast(1))
762 .WillRepeatedly(Return(true));
Igor9fd76b62017-12-11 15:24:18 +0100763 attempter_.policy_provider_.reset(
764 new policy::PolicyProvider(std::move(device_policy)));
Alex Deymo749ecf12014-10-21 20:06:57 -0700765
766 {
767 InSequence s;
Askar Aitzhan570ca872019-04-24 11:16:12 +0200768 for (const auto& update_action_type : GetUpdateActionTypes()) {
Alex Deymo749ecf12014-10-21 20:06:57 -0700769 EXPECT_CALL(*processor_,
Amin Hassanid3f4bea2018-04-30 14:52:40 -0700770 EnqueueAction(Pointee(
Askar Aitzhan570ca872019-04-24 11:16:12 +0200771 Property(&AbstractAction::Type, update_action_type))));
Alex Deymo749ecf12014-10-21 20:06:57 -0700772 }
Gilad Arnold74b5f552014-10-07 08:17:16 -0700773 EXPECT_CALL(*processor_, StartProcessing());
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700774 }
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700775
Amin Hassanie8153632020-10-27 15:11:28 -0700776 attempter_.Update({});
Alex Deymo60ca1a72015-06-18 18:19:15 -0700777 loop_.PostTask(FROM_HERE,
778 base::Bind(&UpdateAttempterTest::UpdateTestVerify,
779 base::Unretained(this)));
Darin Petkove6ef2f82011-03-07 17:31:11 -0800780}
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700781
Darin Petkove6ef2f82011-03-07 17:31:11 -0800782void UpdateAttempterTest::UpdateTestVerify() {
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700783 EXPECT_EQ(0, attempter_.http_response_code());
784 EXPECT_EQ(&attempter_, processor_->delegate());
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700785 EXPECT_EQ(UpdateStatus::CHECKING_FOR_UPDATE, attempter_.status());
Alex Deymo60ca1a72015-06-18 18:19:15 -0700786 loop_.BreakLoop();
Darin Petkove6ef2f82011-03-07 17:31:11 -0800787}
788
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800789void UpdateAttempterTest::RollbackTestStart(bool enterprise_rollback,
790 bool valid_slot) {
Chris Sosa76a29ae2013-07-11 17:59:24 -0700791 // Create a device policy so that we can change settings.
Igor9fd76b62017-12-11 15:24:18 +0100792 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Chris Sosa76a29ae2013-07-11 17:59:24 -0700793 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
Amin Hassani538bd592020-11-04 20:46:08 -0800794 FakeSystemState::Get()->set_device_policy(device_policy.get());
Igor9fd76b62017-12-11 15:24:18 +0100795 if (enterprise_rollback) {
796 // We return an empty owner as this is an enterprise.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800797 EXPECT_CALL(*device_policy, GetOwner(_))
798 .WillRepeatedly(DoAll(SetArgPointee<0>(string("")), Return(true)));
Igor9fd76b62017-12-11 15:24:18 +0100799 } else {
800 // We return a fake owner as this is an owned consumer device.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800801 EXPECT_CALL(*device_policy, GetOwner(_))
802 .WillRepeatedly(DoAll(SetArgPointee<0>(string("fake.mail@fake.com")),
803 Return(true)));
Igor9fd76b62017-12-11 15:24:18 +0100804 }
805
806 attempter_.policy_provider_.reset(
807 new policy::PolicyProvider(std::move(device_policy)));
Chris Sosa76a29ae2013-07-11 17:59:24 -0700808
Alex Deymo763e7db2015-08-27 21:08:08 -0700809 if (valid_slot) {
810 BootControlInterface::Slot rollback_slot = 1;
811 LOG(INFO) << "Test Mark Bootable: "
812 << BootControlInterface::SlotName(rollback_slot);
Amin Hassani538bd592020-11-04 20:46:08 -0800813 FakeSystemState::Get()->fake_boot_control()->SetSlotBootable(rollback_slot,
814 true);
Don Garrett6646b442013-11-13 15:29:11 -0800815 }
816
Chris Sosa28e479c2013-07-12 11:39:53 -0700817 bool is_rollback_allowed = false;
Chris Sosa76a29ae2013-07-11 17:59:24 -0700818
Chris Sosad38b1132014-03-25 10:43:59 -0700819 // We only allow rollback on devices that are not enterprise enrolled and
820 // which have a valid slot to rollback to.
821 if (!enterprise_rollback && valid_slot) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800822 is_rollback_allowed = true;
Chris Sosa28e479c2013-07-12 11:39:53 -0700823 }
824
Chris Sosa28e479c2013-07-12 11:39:53 -0700825 if (is_rollback_allowed) {
Chris Sosa76a29ae2013-07-11 17:59:24 -0700826 InSequence s;
Askar Aitzhan570ca872019-04-24 11:16:12 +0200827 for (const auto& rollback_action_type : GetRollbackActionTypes()) {
Chris Sosa76a29ae2013-07-11 17:59:24 -0700828 EXPECT_CALL(*processor_,
Askar Aitzhan570ca872019-04-24 11:16:12 +0200829 EnqueueAction(Pointee(
830 Property(&AbstractAction::Type, rollback_action_type))));
Chris Sosa76a29ae2013-07-11 17:59:24 -0700831 }
Gilad Arnold74b5f552014-10-07 08:17:16 -0700832 EXPECT_CALL(*processor_, StartProcessing());
Chris Sosa76a29ae2013-07-11 17:59:24 -0700833
Chris Sosa44b9b7e2014-04-02 13:53:46 -0700834 EXPECT_TRUE(attempter_.Rollback(true));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700835 loop_.PostTask(FROM_HERE,
836 base::Bind(&UpdateAttempterTest::RollbackTestVerify,
837 base::Unretained(this)));
Chris Sosa76a29ae2013-07-11 17:59:24 -0700838 } else {
Chris Sosa44b9b7e2014-04-02 13:53:46 -0700839 EXPECT_FALSE(attempter_.Rollback(true));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700840 loop_.BreakLoop();
Chris Sosa76a29ae2013-07-11 17:59:24 -0700841 }
842}
843
844void UpdateAttempterTest::RollbackTestVerify() {
845 // Verifies the actions that were enqueued.
846 EXPECT_EQ(&attempter_, processor_->delegate());
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700847 EXPECT_EQ(UpdateStatus::ATTEMPTING_ROLLBACK, attempter_.status());
Amin Hassanid3f4bea2018-04-30 14:52:40 -0700848 EXPECT_EQ(0U, attempter_.install_plan_->partitions.size());
849 EXPECT_EQ(attempter_.install_plan_->powerwash_required, true);
Alex Deymo60ca1a72015-06-18 18:19:15 -0700850 loop_.BreakLoop();
Chris Sosa76a29ae2013-07-11 17:59:24 -0700851}
852
Darin Petkove6ef2f82011-03-07 17:31:11 -0800853TEST_F(UpdateAttempterTest, UpdateTest) {
Alex Deymo461b2592015-07-24 20:10:52 -0700854 UpdateTestStart();
Alex Deymo60ca1a72015-06-18 18:19:15 -0700855 loop_.Run();
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700856}
857
Chris Sosa76a29ae2013-07-11 17:59:24 -0700858TEST_F(UpdateAttempterTest, RollbackTest) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700859 loop_.PostTask(FROM_HERE,
860 base::Bind(&UpdateAttempterTest::RollbackTestStart,
861 base::Unretained(this),
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800862 false,
863 true));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700864 loop_.Run();
Chris Sosa76a29ae2013-07-11 17:59:24 -0700865}
866
Don Garrett6646b442013-11-13 15:29:11 -0800867TEST_F(UpdateAttempterTest, InvalidSlotRollbackTest) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700868 loop_.PostTask(FROM_HERE,
869 base::Bind(&UpdateAttempterTest::RollbackTestStart,
870 base::Unretained(this),
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800871 false,
872 false));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700873 loop_.Run();
Don Garrett6646b442013-11-13 15:29:11 -0800874}
875
Chris Sosa76a29ae2013-07-11 17:59:24 -0700876TEST_F(UpdateAttempterTest, EnterpriseRollbackTest) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700877 loop_.PostTask(FROM_HERE,
878 base::Bind(&UpdateAttempterTest::RollbackTestStart,
879 base::Unretained(this),
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800880 true,
881 true));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700882 loop_.Run();
Chris Sosa76a29ae2013-07-11 17:59:24 -0700883}
884
Thieu Le116fda32011-04-19 11:01:54 -0700885void UpdateAttempterTest::PingOmahaTestStart() {
886 EXPECT_CALL(*processor_,
Amin Hassanid3f4bea2018-04-30 14:52:40 -0700887 EnqueueAction(Pointee(Property(
888 &AbstractAction::Type, OmahaRequestAction::StaticType()))));
Gilad Arnold74b5f552014-10-07 08:17:16 -0700889 EXPECT_CALL(*processor_, StartProcessing());
Thieu Le116fda32011-04-19 11:01:54 -0700890 attempter_.PingOmaha();
Alex Deymo60ca1a72015-06-18 18:19:15 -0700891 ScheduleQuitMainLoop();
Thieu Le116fda32011-04-19 11:01:54 -0700892}
893
894TEST_F(UpdateAttempterTest, PingOmahaTest) {
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700895 EXPECT_FALSE(attempter_.waiting_for_scheduled_check_);
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700896 EXPECT_FALSE(attempter_.WasScheduleUpdatesCalled());
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700897 // Disable scheduling of subsequnet checks; we're using the |DefaultPolicy| in
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700898 // testing, which is more permissive than we want to handle here.
899 attempter_.DisableScheduleUpdates();
Alex Deymo60ca1a72015-06-18 18:19:15 -0700900 loop_.PostTask(FROM_HERE,
901 base::Bind(&UpdateAttempterTest::PingOmahaTestStart,
902 base::Unretained(this)));
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700903 brillo::MessageLoopRunMaxIterations(&loop_, 100);
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700904 EXPECT_EQ(UpdateStatus::UPDATED_NEED_REBOOT, attempter_.status());
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700905 EXPECT_TRUE(attempter_.WasScheduleUpdatesCalled());
Thieu Le116fda32011-04-19 11:01:54 -0700906}
907
Darin Petkov18c7bce2011-06-16 14:07:00 -0700908TEST_F(UpdateAttempterTest, CreatePendingErrorEventTest) {
Alex Deymo8427b4a2014-11-05 14:00:32 -0800909 MockAction action;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700910 const ErrorCode kCode = ErrorCode::kDownloadTransferError;
Darin Petkov18c7bce2011-06-16 14:07:00 -0700911 attempter_.CreatePendingErrorEvent(&action, kCode);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700912 ASSERT_NE(nullptr, attempter_.error_event_.get());
Darin Petkov18c7bce2011-06-16 14:07:00 -0700913 EXPECT_EQ(OmahaEvent::kTypeUpdateComplete, attempter_.error_event_->type);
914 EXPECT_EQ(OmahaEvent::kResultError, attempter_.error_event_->result);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700915 EXPECT_EQ(
916 static_cast<ErrorCode>(static_cast<int>(kCode) |
917 static_cast<int>(ErrorCode::kTestOmahaUrlFlag)),
918 attempter_.error_event_->error_code);
Darin Petkov18c7bce2011-06-16 14:07:00 -0700919}
920
921TEST_F(UpdateAttempterTest, CreatePendingErrorEventResumedTest) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -0700922 attempter_.install_plan_.reset(new InstallPlan);
923 attempter_.install_plan_->is_resume = true;
Alex Deymo8427b4a2014-11-05 14:00:32 -0800924 MockAction action;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700925 const ErrorCode kCode = ErrorCode::kInstallDeviceOpenError;
Darin Petkov18c7bce2011-06-16 14:07:00 -0700926 attempter_.CreatePendingErrorEvent(&action, kCode);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700927 ASSERT_NE(nullptr, attempter_.error_event_.get());
Darin Petkov18c7bce2011-06-16 14:07:00 -0700928 EXPECT_EQ(OmahaEvent::kTypeUpdateComplete, attempter_.error_event_->type);
929 EXPECT_EQ(OmahaEvent::kResultError, attempter_.error_event_->result);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700930 EXPECT_EQ(
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800931 static_cast<ErrorCode>(static_cast<int>(kCode) |
932 static_cast<int>(ErrorCode::kResumedFlag) |
933 static_cast<int>(ErrorCode::kTestOmahaUrlFlag)),
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700934 attempter_.error_event_->error_code);
Darin Petkov18c7bce2011-06-16 14:07:00 -0700935}
936
David Zeuthen8f191b22013-08-06 12:27:50 -0700937TEST_F(UpdateAttempterTest, P2PNotStartedAtStartupWhenNotEnabled) {
938 MockP2PManager mock_p2p_manager;
Amin Hassani538bd592020-11-04 20:46:08 -0800939 FakeSystemState::Get()->set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -0700940 mock_p2p_manager.fake().SetP2PEnabled(false);
941 EXPECT_CALL(mock_p2p_manager, EnsureP2PRunning()).Times(0);
942 attempter_.UpdateEngineStarted();
943}
944
945TEST_F(UpdateAttempterTest, P2PNotStartedAtStartupWhenEnabledButNotSharing) {
946 MockP2PManager mock_p2p_manager;
Amin Hassani538bd592020-11-04 20:46:08 -0800947 FakeSystemState::Get()->set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -0700948 mock_p2p_manager.fake().SetP2PEnabled(true);
949 EXPECT_CALL(mock_p2p_manager, EnsureP2PRunning()).Times(0);
950 attempter_.UpdateEngineStarted();
951}
952
953TEST_F(UpdateAttempterTest, P2PStartedAtStartupWhenEnabledAndSharing) {
954 MockP2PManager mock_p2p_manager;
Amin Hassani538bd592020-11-04 20:46:08 -0800955 FakeSystemState::Get()->set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -0700956 mock_p2p_manager.fake().SetP2PEnabled(true);
957 mock_p2p_manager.fake().SetCountSharedFilesResult(1);
Gilad Arnold74b5f552014-10-07 08:17:16 -0700958 EXPECT_CALL(mock_p2p_manager, EnsureP2PRunning());
David Zeuthen8f191b22013-08-06 12:27:50 -0700959 attempter_.UpdateEngineStarted();
960}
961
962TEST_F(UpdateAttempterTest, P2PNotEnabled) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700963 loop_.PostTask(FROM_HERE,
964 base::Bind(&UpdateAttempterTest::P2PNotEnabledStart,
965 base::Unretained(this)));
966 loop_.Run();
David Zeuthen8f191b22013-08-06 12:27:50 -0700967}
Alex Deymo60ca1a72015-06-18 18:19:15 -0700968
David Zeuthen8f191b22013-08-06 12:27:50 -0700969void UpdateAttempterTest::P2PNotEnabledStart() {
970 // If P2P is not enabled, check that we do not attempt housekeeping
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700971 // and do not convey that P2P is to be used.
David Zeuthen8f191b22013-08-06 12:27:50 -0700972 MockP2PManager mock_p2p_manager;
Amin Hassani538bd592020-11-04 20:46:08 -0800973 FakeSystemState::Get()->set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -0700974 mock_p2p_manager.fake().SetP2PEnabled(false);
975 EXPECT_CALL(mock_p2p_manager, PerformHousekeeping()).Times(0);
Amin Hassanie8153632020-10-27 15:11:28 -0700976 attempter_.Update({});
Alex Deymo60ca1a72015-06-18 18:19:15 -0700977 EXPECT_FALSE(actual_using_p2p_for_downloading_);
Gilad Arnold74b5f552014-10-07 08:17:16 -0700978 EXPECT_FALSE(actual_using_p2p_for_sharing());
Alex Deymo60ca1a72015-06-18 18:19:15 -0700979 ScheduleQuitMainLoop();
David Zeuthen8f191b22013-08-06 12:27:50 -0700980}
981
982TEST_F(UpdateAttempterTest, P2PEnabledStartingFails) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700983 loop_.PostTask(FROM_HERE,
984 base::Bind(&UpdateAttempterTest::P2PEnabledStartingFailsStart,
985 base::Unretained(this)));
986 loop_.Run();
David Zeuthen8f191b22013-08-06 12:27:50 -0700987}
Alex Deymo60ca1a72015-06-18 18:19:15 -0700988
David Zeuthen8f191b22013-08-06 12:27:50 -0700989void UpdateAttempterTest::P2PEnabledStartingFailsStart() {
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700990 // If P2P is enabled, but starting it fails ensure we don't do
991 // any housekeeping and do not convey that P2P should be used.
David Zeuthen8f191b22013-08-06 12:27:50 -0700992 MockP2PManager mock_p2p_manager;
Amin Hassani538bd592020-11-04 20:46:08 -0800993 FakeSystemState::Get()->set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -0700994 mock_p2p_manager.fake().SetP2PEnabled(true);
995 mock_p2p_manager.fake().SetEnsureP2PRunningResult(false);
996 mock_p2p_manager.fake().SetPerformHousekeepingResult(false);
997 EXPECT_CALL(mock_p2p_manager, PerformHousekeeping()).Times(0);
Amin Hassanie8153632020-10-27 15:11:28 -0700998 attempter_.Update({});
Gilad Arnold74b5f552014-10-07 08:17:16 -0700999 EXPECT_FALSE(actual_using_p2p_for_downloading());
1000 EXPECT_FALSE(actual_using_p2p_for_sharing());
Alex Deymo60ca1a72015-06-18 18:19:15 -07001001 ScheduleQuitMainLoop();
David Zeuthen8f191b22013-08-06 12:27:50 -07001002}
1003
1004TEST_F(UpdateAttempterTest, P2PEnabledHousekeepingFails) {
Alex Deymo60ca1a72015-06-18 18:19:15 -07001005 loop_.PostTask(
1006 FROM_HERE,
1007 base::Bind(&UpdateAttempterTest::P2PEnabledHousekeepingFailsStart,
1008 base::Unretained(this)));
1009 loop_.Run();
David Zeuthen8f191b22013-08-06 12:27:50 -07001010}
Alex Deymo60ca1a72015-06-18 18:19:15 -07001011
David Zeuthen8f191b22013-08-06 12:27:50 -07001012void UpdateAttempterTest::P2PEnabledHousekeepingFailsStart() {
Jae Hoon Kimedb65502019-06-14 11:52:17 -07001013 // If P2P is enabled, starting it works but housekeeping fails, ensure
1014 // we do not convey P2P is to be used.
David Zeuthen8f191b22013-08-06 12:27:50 -07001015 MockP2PManager mock_p2p_manager;
Amin Hassani538bd592020-11-04 20:46:08 -08001016 FakeSystemState::Get()->set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -07001017 mock_p2p_manager.fake().SetP2PEnabled(true);
1018 mock_p2p_manager.fake().SetEnsureP2PRunningResult(true);
1019 mock_p2p_manager.fake().SetPerformHousekeepingResult(false);
Gilad Arnold74b5f552014-10-07 08:17:16 -07001020 EXPECT_CALL(mock_p2p_manager, PerformHousekeeping());
Amin Hassanie8153632020-10-27 15:11:28 -07001021 attempter_.Update({});
Gilad Arnold74b5f552014-10-07 08:17:16 -07001022 EXPECT_FALSE(actual_using_p2p_for_downloading());
1023 EXPECT_FALSE(actual_using_p2p_for_sharing());
Alex Deymo60ca1a72015-06-18 18:19:15 -07001024 ScheduleQuitMainLoop();
David Zeuthen8f191b22013-08-06 12:27:50 -07001025}
1026
1027TEST_F(UpdateAttempterTest, P2PEnabled) {
Alex Deymo60ca1a72015-06-18 18:19:15 -07001028 loop_.PostTask(FROM_HERE,
1029 base::Bind(&UpdateAttempterTest::P2PEnabledStart,
1030 base::Unretained(this)));
1031 loop_.Run();
David Zeuthen8f191b22013-08-06 12:27:50 -07001032}
Alex Deymo60ca1a72015-06-18 18:19:15 -07001033
David Zeuthen8f191b22013-08-06 12:27:50 -07001034void UpdateAttempterTest::P2PEnabledStart() {
1035 MockP2PManager mock_p2p_manager;
Amin Hassani538bd592020-11-04 20:46:08 -08001036 FakeSystemState::Get()->set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -07001037 // If P2P is enabled and starting it works, check that we performed
Jae Hoon Kimedb65502019-06-14 11:52:17 -07001038 // housekeeping and that we convey P2P should be used.
David Zeuthen8f191b22013-08-06 12:27:50 -07001039 mock_p2p_manager.fake().SetP2PEnabled(true);
1040 mock_p2p_manager.fake().SetEnsureP2PRunningResult(true);
1041 mock_p2p_manager.fake().SetPerformHousekeepingResult(true);
Gilad Arnold74b5f552014-10-07 08:17:16 -07001042 EXPECT_CALL(mock_p2p_manager, PerformHousekeeping());
Amin Hassanie8153632020-10-27 15:11:28 -07001043 attempter_.Update({});
Gilad Arnold74b5f552014-10-07 08:17:16 -07001044 EXPECT_TRUE(actual_using_p2p_for_downloading());
1045 EXPECT_TRUE(actual_using_p2p_for_sharing());
Alex Deymo60ca1a72015-06-18 18:19:15 -07001046 ScheduleQuitMainLoop();
David Zeuthen8f191b22013-08-06 12:27:50 -07001047}
1048
1049TEST_F(UpdateAttempterTest, P2PEnabledInteractive) {
Alex Deymo60ca1a72015-06-18 18:19:15 -07001050 loop_.PostTask(FROM_HERE,
1051 base::Bind(&UpdateAttempterTest::P2PEnabledInteractiveStart,
1052 base::Unretained(this)));
1053 loop_.Run();
David Zeuthen8f191b22013-08-06 12:27:50 -07001054}
Alex Deymo60ca1a72015-06-18 18:19:15 -07001055
David Zeuthen8f191b22013-08-06 12:27:50 -07001056void UpdateAttempterTest::P2PEnabledInteractiveStart() {
1057 MockP2PManager mock_p2p_manager;
Amin Hassani538bd592020-11-04 20:46:08 -08001058 FakeSystemState::Get()->set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -07001059 // For an interactive check, if P2P is enabled and starting it
1060 // works, check that we performed housekeeping and that we convey
Jae Hoon Kimedb65502019-06-14 11:52:17 -07001061 // P2P should be used for sharing but NOT for downloading.
David Zeuthen8f191b22013-08-06 12:27:50 -07001062 mock_p2p_manager.fake().SetP2PEnabled(true);
1063 mock_p2p_manager.fake().SetEnsureP2PRunningResult(true);
1064 mock_p2p_manager.fake().SetPerformHousekeepingResult(true);
Gilad Arnold74b5f552014-10-07 08:17:16 -07001065 EXPECT_CALL(mock_p2p_manager, PerformHousekeeping());
Amin Hassanie8153632020-10-27 15:11:28 -07001066 attempter_.Update({.interactive = true});
Gilad Arnold74b5f552014-10-07 08:17:16 -07001067 EXPECT_FALSE(actual_using_p2p_for_downloading());
1068 EXPECT_TRUE(actual_using_p2p_for_sharing());
Alex Deymo60ca1a72015-06-18 18:19:15 -07001069 ScheduleQuitMainLoop();
David Zeuthen8f191b22013-08-06 12:27:50 -07001070}
1071
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001072TEST_F(UpdateAttempterTest, ReadScatterFactorFromPolicy) {
Alex Deymo60ca1a72015-06-18 18:19:15 -07001073 loop_.PostTask(
1074 FROM_HERE,
1075 base::Bind(&UpdateAttempterTest::ReadScatterFactorFromPolicyTestStart,
1076 base::Unretained(this)));
1077 loop_.Run();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001078}
1079
1080// Tests that the scatter_factor_in_seconds value is properly fetched
1081// from the device policy.
1082void UpdateAttempterTest::ReadScatterFactorFromPolicyTestStart() {
Ben Chan9abb7632014-08-07 00:10:53 -07001083 int64_t scatter_factor_in_seconds = 36000;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001084
Igor9fd76b62017-12-11 15:24:18 +01001085 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001086 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
Amin Hassani538bd592020-11-04 20:46:08 -08001087 FakeSystemState::Get()->set_device_policy(device_policy.get());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001088
1089 EXPECT_CALL(*device_policy, GetScatterFactorInSeconds(_))
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001090 .WillRepeatedly(
1091 DoAll(SetArgPointee<0>(scatter_factor_in_seconds), Return(true)));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001092
Igor9fd76b62017-12-11 15:24:18 +01001093 attempter_.policy_provider_.reset(
1094 new policy::PolicyProvider(std::move(device_policy)));
1095
Amin Hassanie8153632020-10-27 15:11:28 -07001096 attempter_.Update({});
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001097 EXPECT_EQ(scatter_factor_in_seconds, attempter_.scatter_factor_.InSeconds());
1098
Alex Deymo60ca1a72015-06-18 18:19:15 -07001099 ScheduleQuitMainLoop();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001100}
1101
1102TEST_F(UpdateAttempterTest, DecrementUpdateCheckCountTest) {
Alex Deymo60ca1a72015-06-18 18:19:15 -07001103 loop_.PostTask(
1104 FROM_HERE,
1105 base::Bind(&UpdateAttempterTest::DecrementUpdateCheckCountTestStart,
1106 base::Unretained(this)));
1107 loop_.Run();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001108}
1109
1110void UpdateAttempterTest::DecrementUpdateCheckCountTestStart() {
1111 // Tests that the scatter_factor_in_seconds value is properly fetched
1112 // from the device policy and is decremented if value > 0.
Ben Chan9abb7632014-08-07 00:10:53 -07001113 int64_t initial_value = 5;
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001114 FakePrefs fake_prefs;
1115 attempter_.prefs_ = &fake_prefs;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001116
Amin Hassani538bd592020-11-04 20:46:08 -08001117 FakeSystemState::Get()->fake_hardware()->SetIsOOBEComplete(Time::UnixEpoch());
Jay Srinivasan08fce042012-06-07 16:31:01 -07001118
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001119 EXPECT_TRUE(fake_prefs.SetInt64(kPrefsUpdateCheckCount, initial_value));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001120
Ben Chan9abb7632014-08-07 00:10:53 -07001121 int64_t scatter_factor_in_seconds = 10;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001122
Igor9fd76b62017-12-11 15:24:18 +01001123 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001124 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
Amin Hassani538bd592020-11-04 20:46:08 -08001125 FakeSystemState::Get()->set_device_policy(device_policy.get());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001126
1127 EXPECT_CALL(*device_policy, GetScatterFactorInSeconds(_))
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001128 .WillRepeatedly(
1129 DoAll(SetArgPointee<0>(scatter_factor_in_seconds), Return(true)));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001130
Igor9fd76b62017-12-11 15:24:18 +01001131 attempter_.policy_provider_.reset(
1132 new policy::PolicyProvider(std::move(device_policy)));
1133
Amin Hassanie8153632020-10-27 15:11:28 -07001134 attempter_.Update({});
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001135 EXPECT_EQ(scatter_factor_in_seconds, attempter_.scatter_factor_.InSeconds());
1136
1137 // Make sure the file still exists.
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001138 EXPECT_TRUE(fake_prefs.Exists(kPrefsUpdateCheckCount));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001139
Ben Chan9abb7632014-08-07 00:10:53 -07001140 int64_t new_value;
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001141 EXPECT_TRUE(fake_prefs.GetInt64(kPrefsUpdateCheckCount, &new_value));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001142 EXPECT_EQ(initial_value - 1, new_value);
1143
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001144 EXPECT_TRUE(
1145 attempter_.omaha_request_params_->update_check_count_wait_enabled());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001146
1147 // However, if the count is already 0, it's not decremented. Test that.
1148 initial_value = 0;
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001149 EXPECT_TRUE(fake_prefs.SetInt64(kPrefsUpdateCheckCount, initial_value));
Amin Hassanie8153632020-10-27 15:11:28 -07001150 attempter_.Update({});
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001151 EXPECT_TRUE(fake_prefs.Exists(kPrefsUpdateCheckCount));
1152 EXPECT_TRUE(fake_prefs.GetInt64(kPrefsUpdateCheckCount, &new_value));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001153 EXPECT_EQ(initial_value, new_value);
1154
Alex Deymo60ca1a72015-06-18 18:19:15 -07001155 ScheduleQuitMainLoop();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001156}
1157
Jay Srinivasan08fce042012-06-07 16:31:01 -07001158TEST_F(UpdateAttempterTest, NoScatteringDoneDuringManualUpdateTestStart) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001159 loop_.PostTask(
1160 FROM_HERE,
1161 base::Bind(
1162 &UpdateAttempterTest::NoScatteringDoneDuringManualUpdateTestStart,
1163 base::Unretained(this)));
Alex Deymo60ca1a72015-06-18 18:19:15 -07001164 loop_.Run();
Jay Srinivasan08fce042012-06-07 16:31:01 -07001165}
1166
1167void UpdateAttempterTest::NoScatteringDoneDuringManualUpdateTestStart() {
1168 // Tests that no scattering logic is enabled if the update check
1169 // is manually done (as opposed to a scheduled update check)
Ben Chan9abb7632014-08-07 00:10:53 -07001170 int64_t initial_value = 8;
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001171 FakePrefs fake_prefs;
1172 attempter_.prefs_ = &fake_prefs;
Jay Srinivasan08fce042012-06-07 16:31:01 -07001173
Amin Hassani538bd592020-11-04 20:46:08 -08001174 FakeSystemState::Get()->fake_hardware()->SetIsOOBEComplete(Time::UnixEpoch());
1175 FakeSystemState::Get()->set_prefs(&fake_prefs);
Jay Srinivasan08fce042012-06-07 16:31:01 -07001176
Adolfo Victoriad3a1e352018-07-16 11:40:47 -07001177 EXPECT_TRUE(
1178 fake_prefs.SetInt64(kPrefsWallClockScatteringWaitPeriod, initial_value));
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001179 EXPECT_TRUE(fake_prefs.SetInt64(kPrefsUpdateCheckCount, initial_value));
Jay Srinivasan08fce042012-06-07 16:31:01 -07001180
1181 // make sure scatter_factor is non-zero as scattering is disabled
1182 // otherwise.
Ben Chan9abb7632014-08-07 00:10:53 -07001183 int64_t scatter_factor_in_seconds = 50;
Jay Srinivasan08fce042012-06-07 16:31:01 -07001184
Igor9fd76b62017-12-11 15:24:18 +01001185 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Jay Srinivasan08fce042012-06-07 16:31:01 -07001186 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
Amin Hassani538bd592020-11-04 20:46:08 -08001187 FakeSystemState::Get()->set_device_policy(device_policy.get());
Jay Srinivasan08fce042012-06-07 16:31:01 -07001188
1189 EXPECT_CALL(*device_policy, GetScatterFactorInSeconds(_))
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001190 .WillRepeatedly(
1191 DoAll(SetArgPointee<0>(scatter_factor_in_seconds), Return(true)));
Jay Srinivasan08fce042012-06-07 16:31:01 -07001192
Igor9fd76b62017-12-11 15:24:18 +01001193 attempter_.policy_provider_.reset(
1194 new policy::PolicyProvider(std::move(device_policy)));
1195
Gilad Arnoldb92f0df2013-01-10 16:32:45 -08001196 // Trigger an interactive check so we can test that scattering is disabled.
Amin Hassanie8153632020-10-27 15:11:28 -07001197 attempter_.Update({.interactive = true});
Jay Srinivasan08fce042012-06-07 16:31:01 -07001198 EXPECT_EQ(scatter_factor_in_seconds, attempter_.scatter_factor_.InSeconds());
1199
1200 // Make sure scattering is disabled for manual (i.e. user initiated) update
Jay Srinivasan21be0752012-07-25 15:44:56 -07001201 // checks and all artifacts are removed.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001202 EXPECT_FALSE(
1203 attempter_.omaha_request_params_->wall_clock_based_wait_enabled());
Adolfo Victoriad3a1e352018-07-16 11:40:47 -07001204 EXPECT_FALSE(fake_prefs.Exists(kPrefsWallClockScatteringWaitPeriod));
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001205 EXPECT_EQ(0, attempter_.omaha_request_params_->waiting_period().InSeconds());
1206 EXPECT_FALSE(
1207 attempter_.omaha_request_params_->update_check_count_wait_enabled());
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001208 EXPECT_FALSE(fake_prefs.Exists(kPrefsUpdateCheckCount));
Jay Srinivasan08fce042012-06-07 16:31:01 -07001209
Alex Deymo60ca1a72015-06-18 18:19:15 -07001210 ScheduleQuitMainLoop();
Jay Srinivasan08fce042012-06-07 16:31:01 -07001211}
1212
Adolfo Victoria497044c2018-07-18 07:51:42 -07001213void UpdateAttempterTest::SetUpStagingTest(const StagingSchedule& schedule,
1214 FakePrefs* prefs) {
1215 attempter_.prefs_ = prefs;
Amin Hassani538bd592020-11-04 20:46:08 -08001216 FakeSystemState::Get()->set_prefs(prefs);
Adolfo Victoria497044c2018-07-18 07:51:42 -07001217
1218 int64_t initial_value = 8;
1219 EXPECT_TRUE(
1220 prefs->SetInt64(kPrefsWallClockScatteringWaitPeriod, initial_value));
1221 EXPECT_TRUE(prefs->SetInt64(kPrefsUpdateCheckCount, initial_value));
1222 attempter_.scatter_factor_ = TimeDelta::FromSeconds(20);
1223
1224 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
1225 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
Amin Hassani538bd592020-11-04 20:46:08 -08001226 FakeSystemState::Get()->set_device_policy(device_policy.get());
Adolfo Victoria497044c2018-07-18 07:51:42 -07001227 EXPECT_CALL(*device_policy, GetDeviceUpdateStagingSchedule(_))
1228 .WillRepeatedly(DoAll(SetArgPointee<0>(schedule), Return(true)));
1229
1230 attempter_.policy_provider_.reset(
1231 new policy::PolicyProvider(std::move(device_policy)));
1232}
1233
1234TEST_F(UpdateAttempterTest, StagingSetsPrefsAndTurnsOffScattering) {
1235 loop_.PostTask(
1236 FROM_HERE,
1237 base::Bind(
1238 &UpdateAttempterTest::StagingSetsPrefsAndTurnsOffScatteringStart,
1239 base::Unretained(this)));
1240 loop_.Run();
1241}
1242
1243void UpdateAttempterTest::StagingSetsPrefsAndTurnsOffScatteringStart() {
1244 // Tests that staging sets its prefs properly and turns off scattering.
Amin Hassani538bd592020-11-04 20:46:08 -08001245 FakeSystemState::Get()->fake_hardware()->SetIsOOBEComplete(Time::UnixEpoch());
Adolfo Victoria497044c2018-07-18 07:51:42 -07001246 FakePrefs fake_prefs;
1247 SetUpStagingTest(kValidStagingSchedule, &fake_prefs);
1248
Amin Hassanie8153632020-10-27 15:11:28 -07001249 attempter_.Update({});
Adolfo Victoria497044c2018-07-18 07:51:42 -07001250 // Check that prefs have the correct values.
1251 int64_t update_count;
1252 EXPECT_TRUE(fake_prefs.GetInt64(kPrefsUpdateCheckCount, &update_count));
1253 int64_t waiting_time_days;
1254 EXPECT_TRUE(fake_prefs.GetInt64(kPrefsWallClockStagingWaitPeriod,
1255 &waiting_time_days));
1256 EXPECT_GT(waiting_time_days, 0);
1257 // Update count should have been decremented.
1258 EXPECT_EQ(7, update_count);
1259 // Check that Omaha parameters were updated correctly.
1260 EXPECT_TRUE(
1261 attempter_.omaha_request_params_->update_check_count_wait_enabled());
1262 EXPECT_TRUE(
1263 attempter_.omaha_request_params_->wall_clock_based_wait_enabled());
1264 EXPECT_EQ(waiting_time_days,
1265 attempter_.omaha_request_params_->waiting_period().InDays());
1266 // Check class variables.
1267 EXPECT_EQ(waiting_time_days, attempter_.staging_wait_time_.InDays());
1268 EXPECT_EQ(kValidStagingSchedule, attempter_.staging_schedule_);
1269 // Check that scattering is turned off
1270 EXPECT_EQ(0, attempter_.scatter_factor_.InSeconds());
1271 EXPECT_FALSE(fake_prefs.Exists(kPrefsWallClockScatteringWaitPeriod));
1272
1273 ScheduleQuitMainLoop();
1274}
1275
1276void UpdateAttempterTest::CheckStagingOff() {
1277 // Check that all prefs were removed.
1278 EXPECT_FALSE(attempter_.prefs_->Exists(kPrefsUpdateCheckCount));
1279 EXPECT_FALSE(attempter_.prefs_->Exists(kPrefsWallClockScatteringWaitPeriod));
1280 EXPECT_FALSE(attempter_.prefs_->Exists(kPrefsWallClockStagingWaitPeriod));
1281 // Check that the Omaha parameters have the correct value.
1282 EXPECT_EQ(0, attempter_.omaha_request_params_->waiting_period().InDays());
1283 EXPECT_EQ(attempter_.omaha_request_params_->waiting_period(),
1284 attempter_.staging_wait_time_);
1285 EXPECT_FALSE(
1286 attempter_.omaha_request_params_->update_check_count_wait_enabled());
1287 EXPECT_FALSE(
1288 attempter_.omaha_request_params_->wall_clock_based_wait_enabled());
1289 // Check that scattering is turned off too.
1290 EXPECT_EQ(0, attempter_.scatter_factor_.InSeconds());
1291}
1292
1293TEST_F(UpdateAttempterTest, StagingOffIfInteractive) {
1294 loop_.PostTask(FROM_HERE,
1295 base::Bind(&UpdateAttempterTest::StagingOffIfInteractiveStart,
1296 base::Unretained(this)));
1297 loop_.Run();
1298}
1299
1300void UpdateAttempterTest::StagingOffIfInteractiveStart() {
1301 // Tests that staging is turned off when an interactive update is requested.
Amin Hassani538bd592020-11-04 20:46:08 -08001302 FakeSystemState::Get()->fake_hardware()->SetIsOOBEComplete(Time::UnixEpoch());
Adolfo Victoria497044c2018-07-18 07:51:42 -07001303 FakePrefs fake_prefs;
1304 SetUpStagingTest(kValidStagingSchedule, &fake_prefs);
1305
Amin Hassanie8153632020-10-27 15:11:28 -07001306 attempter_.Update({.interactive = true});
Adolfo Victoria497044c2018-07-18 07:51:42 -07001307 CheckStagingOff();
1308
1309 ScheduleQuitMainLoop();
1310}
1311
1312TEST_F(UpdateAttempterTest, StagingOffIfOobe) {
1313 loop_.PostTask(FROM_HERE,
1314 base::Bind(&UpdateAttempterTest::StagingOffIfOobeStart,
1315 base::Unretained(this)));
1316 loop_.Run();
1317}
1318
1319void UpdateAttempterTest::StagingOffIfOobeStart() {
1320 // Tests that staging is turned off if OOBE hasn't been completed.
Amin Hassani538bd592020-11-04 20:46:08 -08001321 FakeSystemState::Get()->fake_hardware()->SetIsOOBEEnabled(true);
1322 FakeSystemState::Get()->fake_hardware()->UnsetIsOOBEComplete();
Adolfo Victoria497044c2018-07-18 07:51:42 -07001323 FakePrefs fake_prefs;
1324 SetUpStagingTest(kValidStagingSchedule, &fake_prefs);
1325
Amin Hassanie8153632020-10-27 15:11:28 -07001326 attempter_.Update({.interactive = true});
Adolfo Victoria497044c2018-07-18 07:51:42 -07001327 CheckStagingOff();
1328
1329 ScheduleQuitMainLoop();
1330}
1331
David Zeuthen985b1122013-10-09 12:13:15 -07001332// Checks that we only report daily metrics at most every 24 hours.
1333TEST_F(UpdateAttempterTest, ReportDailyMetrics) {
1334 FakeClock fake_clock;
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001335 FakePrefs fake_prefs;
David Zeuthen985b1122013-10-09 12:13:15 -07001336
Amin Hassani538bd592020-11-04 20:46:08 -08001337 FakeSystemState::Get()->set_clock(&fake_clock);
1338 FakeSystemState::Get()->set_prefs(&fake_prefs);
David Zeuthen985b1122013-10-09 12:13:15 -07001339
1340 Time epoch = Time::FromInternalValue(0);
1341 fake_clock.SetWallclockTime(epoch);
1342
1343 // If there is no kPrefsDailyMetricsLastReportedAt state variable,
1344 // we should report.
1345 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1346 // We should not report again if no time has passed.
1347 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1348
1349 // We should not report if only 10 hours has passed.
1350 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(10));
1351 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1352
1353 // We should not report if only 24 hours - 1 sec has passed.
1354 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(24) -
1355 TimeDelta::FromSeconds(1));
1356 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1357
1358 // We should report if 24 hours has passed.
1359 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(24));
1360 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1361
1362 // But then we should not report again..
1363 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1364
1365 // .. until another 24 hours has passed
1366 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(47));
1367 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1368 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(48));
1369 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1370 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1371
1372 // .. and another 24 hours
1373 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(71));
1374 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1375 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(72));
1376 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1377 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1378
1379 // If the span between time of reporting and present time is
1380 // negative, we report. This is in order to reset the timestamp and
1381 // avoid an edge condition whereby a distant point in the future is
1382 // in the state variable resulting in us never ever reporting again.
1383 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(71));
1384 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1385 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1386
1387 // In this case we should not update until the clock reads 71 + 24 = 95.
1388 // Check that.
1389 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(94));
1390 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1391 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(95));
1392 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1393 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
David Zeuthen985b1122013-10-09 12:13:15 -07001394}
1395
David Zeuthen3c55abd2013-10-14 12:48:03 -07001396TEST_F(UpdateAttempterTest, BootTimeInUpdateMarkerFile) {
David Zeuthen3c55abd2013-10-14 12:48:03 -07001397 FakeClock fake_clock;
1398 fake_clock.SetBootTime(Time::FromTimeT(42));
Amin Hassani538bd592020-11-04 20:46:08 -08001399 FakeSystemState::Get()->set_clock(&fake_clock);
Alex Deymo906191f2015-10-12 12:22:44 -07001400 FakePrefs fake_prefs;
Amin Hassani538bd592020-11-04 20:46:08 -08001401 FakeSystemState::Get()->set_prefs(&fake_prefs);
Sen Jiangaeeb2e02016-06-09 15:00:16 -07001402 attempter_.Init();
David Zeuthen3c55abd2013-10-14 12:48:03 -07001403
1404 Time boot_time;
Sen Jiangaeeb2e02016-06-09 15:00:16 -07001405 EXPECT_FALSE(attempter_.GetBootTimeAtUpdate(&boot_time));
David Zeuthen3c55abd2013-10-14 12:48:03 -07001406
Sen Jiangaeeb2e02016-06-09 15:00:16 -07001407 attempter_.WriteUpdateCompletedMarker();
David Zeuthen3c55abd2013-10-14 12:48:03 -07001408
Sen Jiangaeeb2e02016-06-09 15:00:16 -07001409 EXPECT_TRUE(attempter_.GetBootTimeAtUpdate(&boot_time));
David Zeuthen3c55abd2013-10-14 12:48:03 -07001410 EXPECT_EQ(boot_time.ToTimeT(), 42);
1411}
1412
David Pursell02c18642014-11-06 11:26:11 -08001413TEST_F(UpdateAttempterTest, AnyUpdateSourceAllowedUnofficial) {
Amin Hassani538bd592020-11-04 20:46:08 -08001414 FakeSystemState::Get()->fake_hardware()->SetIsOfficialBuild(false);
David Pursell02c18642014-11-06 11:26:11 -08001415 EXPECT_TRUE(attempter_.IsAnyUpdateSourceAllowed());
1416}
1417
1418TEST_F(UpdateAttempterTest, AnyUpdateSourceAllowedOfficialDevmode) {
Amin Hassani538bd592020-11-04 20:46:08 -08001419 FakeSystemState::Get()->fake_hardware()->SetIsOfficialBuild(true);
1420 FakeSystemState::Get()->fake_hardware()->SetAreDevFeaturesEnabled(true);
David Pursell02c18642014-11-06 11:26:11 -08001421 EXPECT_TRUE(attempter_.IsAnyUpdateSourceAllowed());
1422}
1423
1424TEST_F(UpdateAttempterTest, AnyUpdateSourceDisallowedOfficialNormal) {
Amin Hassani538bd592020-11-04 20:46:08 -08001425 FakeSystemState::Get()->fake_hardware()->SetIsOfficialBuild(true);
1426 FakeSystemState::Get()->fake_hardware()->SetAreDevFeaturesEnabled(false);
David Pursell02c18642014-11-06 11:26:11 -08001427 EXPECT_FALSE(attempter_.IsAnyUpdateSourceAllowed());
1428}
1429
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001430// TODO(kimjae): Follow testing pattern with params for |CheckForInstall()|.
1431// When adding, remove older tests related to |CheckForInstall()|.
1432TEST_F(UpdateAttempterTest, CheckForInstallNotIdleFails) {
1433 for (const auto status : kNonIdleUpdateStatuses) {
1434 // GIVEN a non-idle status.
1435 attempter_.status_ = status;
Xiaochu Liu8ba486f2018-11-06 11:14:10 -08001436
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001437 EXPECT_FALSE(attempter_.CheckForInstall({}, ""));
1438 }
Xiaochu Liu8ba486f2018-11-06 11:14:10 -08001439}
1440
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001441TEST_F(UpdateAttempterTest, CheckForUpdateNotIdleFails) {
1442 for (const auto status : kNonIdleUpdateStatuses) {
1443 // GIVEN a non-idle status.
1444 cfu_params_.status = status;
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001445
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001446 // THEN |ScheduleUpdates()| should not be called.
1447 cfu_params_.should_schedule_updates_be_called = false;
1448 // THEN result should indicate failure.
1449 cfu_params_.expected_result = false;
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001450
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001451 TestCheckForUpdate();
1452 }
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001453}
1454
1455TEST_F(UpdateAttempterTest, CheckForUpdateOfficalBuildClearsSource) {
1456 // GIVEN a official build.
1457
1458 // THEN we except forced app version + forced omaha url to be cleared.
1459
1460 TestCheckForUpdate();
1461}
1462
1463TEST_F(UpdateAttempterTest, CheckForUpdateUnofficialBuildChangesSource) {
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001464 // GIVEN a nonofficial build with dev features enabled.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001465 cfu_params_.is_official_build = false;
1466 cfu_params_.are_dev_features_enabled = true;
1467
1468 // THEN the forced app version + forced omaha url changes based on input.
1469 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1470 cfu_params_.expected_forced_omaha_url = cfu_params_.omaha_url;
1471
1472 TestCheckForUpdate();
1473}
1474
1475TEST_F(UpdateAttempterTest, CheckForUpdateOfficialBuildScheduledAUTest) {
1476 // GIVEN a scheduled autest omaha url.
1477 cfu_params_.omaha_url = "autest-scheduled";
1478
1479 // THEN forced app version is cleared.
1480 // THEN forced omaha url changes to default constant.
1481 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1482
1483 TestCheckForUpdate();
1484}
1485
1486TEST_F(UpdateAttempterTest, CheckForUpdateUnofficialBuildScheduledAUTest) {
1487 // GIVEN a scheduled autest omaha url.
1488 cfu_params_.omaha_url = "autest-scheduled";
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001489 // GIVEN a nonofficial build with dev features enabled.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001490 cfu_params_.is_official_build = false;
1491 cfu_params_.are_dev_features_enabled = true;
1492
1493 // THEN forced app version changes based on input.
1494 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1495 // THEN forced omaha url changes to default constant.
1496 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1497
1498 TestCheckForUpdate();
1499}
1500
1501TEST_F(UpdateAttempterTest, CheckForUpdateOfficialBuildAUTest) {
1502 // GIVEN a autest omaha url.
1503 cfu_params_.omaha_url = "autest";
1504
1505 // THEN forced app version is cleared.
1506 // THEN forced omaha url changes to default constant.
1507 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1508
1509 TestCheckForUpdate();
1510}
1511
1512TEST_F(UpdateAttempterTest, CheckForUpdateUnofficialBuildAUTest) {
1513 // GIVEN a autest omha url.
1514 cfu_params_.omaha_url = "autest";
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,
1528 CheckForUpdateNonInteractiveOfficialBuildScheduledAUTest) {
1529 // GIVEN a scheduled autest omaha url.
1530 cfu_params_.omaha_url = "autest-scheduled";
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001531 // GIVEN a noninteractive update.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001532 cfu_params_.flags = UpdateAttemptFlags::kFlagNonInteractive;
1533
1534 // THEN forced app version is cleared.
1535 // THEN forced omaha url changes to default constant.
1536 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1537
1538 TestCheckForUpdate();
1539}
1540
1541TEST_F(UpdateAttempterTest,
1542 CheckForUpdateNonInteractiveUnofficialBuildScheduledAUTest) {
1543 // GIVEN a scheduled autest omaha url.
1544 cfu_params_.omaha_url = "autest-scheduled";
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001545 // GIVEN a noninteractive update.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001546 cfu_params_.flags = UpdateAttemptFlags::kFlagNonInteractive;
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001547 // GIVEN a nonofficial build with dev features enabled.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001548 cfu_params_.is_official_build = false;
1549 cfu_params_.are_dev_features_enabled = true;
1550
1551 // THEN forced app version changes based on input.
1552 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1553 // THEN forced omaha url changes to default constant.
1554 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1555
1556 TestCheckForUpdate();
1557}
1558
1559TEST_F(UpdateAttempterTest, CheckForUpdateNonInteractiveOfficialBuildAUTest) {
1560 // GIVEN a autest omaha url.
1561 cfu_params_.omaha_url = "autest";
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001562 // GIVEN a noninteractive update.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001563 cfu_params_.flags = UpdateAttemptFlags::kFlagNonInteractive;
1564
1565 // THEN forced app version is cleared.
1566 // THEN forced omaha url changes to default constant.
1567 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1568
1569 TestCheckForUpdate();
1570}
1571
1572TEST_F(UpdateAttempterTest, CheckForUpdateNonInteractiveUnofficialBuildAUTest) {
1573 // GIVEN a autest omaha url.
1574 cfu_params_.omaha_url = "autest";
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001575 // GIVEN a noninteractive update.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001576 cfu_params_.flags = UpdateAttemptFlags::kFlagNonInteractive;
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001577 // GIVEN a nonofficial build with dev features enabled.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001578 cfu_params_.is_official_build = false;
1579 cfu_params_.are_dev_features_enabled = true;
1580
1581 // THEN forced app version changes based on input.
1582 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1583 // THEN forced omaha url changes to default constant.
1584 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1585
1586 TestCheckForUpdate();
David Pursell02c18642014-11-06 11:26:11 -08001587}
1588
Jae Hoon Kim2b73ac22019-07-02 11:17:24 -07001589TEST_F(UpdateAttempterTest, CheckForUpdateMissingForcedCallback1) {
1590 // GIVEN a official build.
1591 // GIVEN forced callback is not set.
1592 attempter_.set_forced_update_pending_callback(nullptr);
1593
1594 // THEN we except forced app version + forced omaha url to be cleared.
1595 // THEN |ScheduleUpdates()| should not be called.
1596 cfu_params_.should_schedule_updates_be_called = false;
1597
1598 TestCheckForUpdate();
1599}
1600
1601TEST_F(UpdateAttempterTest, CheckForUpdateMissingForcedCallback2) {
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001602 // GIVEN a nonofficial build with dev features enabled.
Jae Hoon Kim2b73ac22019-07-02 11:17:24 -07001603 cfu_params_.is_official_build = false;
1604 cfu_params_.are_dev_features_enabled = true;
1605 // GIVEN forced callback is not set.
1606 attempter_.set_forced_update_pending_callback(nullptr);
1607
1608 // THEN the forced app version + forced omaha url changes based on input.
1609 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1610 cfu_params_.expected_forced_omaha_url = cfu_params_.omaha_url;
1611 // THEN |ScheduleUpdates()| should not be called.
1612 cfu_params_.should_schedule_updates_be_called = false;
1613
1614 TestCheckForUpdate();
1615}
1616
Xiaochu Liu88d90382018-08-29 16:09:11 -07001617TEST_F(UpdateAttempterTest, CheckForInstallTest) {
Amin Hassani538bd592020-11-04 20:46:08 -08001618 FakeSystemState::Get()->fake_hardware()->SetIsOfficialBuild(true);
1619 FakeSystemState::Get()->fake_hardware()->SetAreDevFeaturesEnabled(false);
Xiaochu Liu88d90382018-08-29 16:09:11 -07001620 attempter_.CheckForInstall({}, "autest");
1621 EXPECT_EQ(constants::kOmahaDefaultAUTestURL, attempter_.forced_omaha_url());
1622
1623 attempter_.CheckForInstall({}, "autest-scheduled");
1624 EXPECT_EQ(constants::kOmahaDefaultAUTestURL, attempter_.forced_omaha_url());
1625
1626 attempter_.CheckForInstall({}, "http://omaha.phishing");
1627 EXPECT_EQ("", attempter_.forced_omaha_url());
1628}
1629
Colin Howesac170d92018-11-20 16:29:28 -08001630TEST_F(UpdateAttempterTest, InstallSetsStatusIdle) {
1631 attempter_.CheckForInstall({}, "http://foo.bar");
1632 attempter_.status_ = UpdateStatus::DOWNLOADING;
1633 EXPECT_TRUE(attempter_.is_install_);
1634 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1635 UpdateEngineStatus status;
1636 attempter_.GetStatus(&status);
1637 // Should set status to idle after an install operation.
1638 EXPECT_EQ(UpdateStatus::IDLE, status.status);
1639}
1640
Colin Howes978c1082018-12-03 11:46:12 -08001641TEST_F(UpdateAttempterTest, RollbackAfterInstall) {
1642 attempter_.is_install_ = true;
1643 attempter_.Rollback(false);
1644 EXPECT_FALSE(attempter_.is_install_);
1645}
1646
1647TEST_F(UpdateAttempterTest, UpdateAfterInstall) {
1648 attempter_.is_install_ = true;
1649 attempter_.CheckForUpdate("", "", UpdateAttemptFlags::kNone);
1650 EXPECT_FALSE(attempter_.is_install_);
1651}
1652
Xiyuan Xiac0e8f9a2017-02-22 13:19:35 -08001653TEST_F(UpdateAttempterTest, TargetVersionPrefixSetAndReset) {
Amin Hassanie8153632020-10-27 15:11:28 -07001654 UpdateCheckParams params;
1655 attempter_.CalculateUpdateParams({.target_version_prefix = "1234"});
Xiyuan Xiac0e8f9a2017-02-22 13:19:35 -08001656 EXPECT_EQ("1234",
Amin Hassani538bd592020-11-04 20:46:08 -08001657 FakeSystemState::Get()->request_params()->target_version_prefix());
Xiyuan Xiac0e8f9a2017-02-22 13:19:35 -08001658
Amin Hassanie8153632020-10-27 15:11:28 -07001659 attempter_.CalculateUpdateParams({});
Amin Hassani538bd592020-11-04 20:46:08 -08001660 EXPECT_TRUE(FakeSystemState::Get()
1661 ->request_params()
1662 ->target_version_prefix()
1663 .empty());
Xiyuan Xiac0e8f9a2017-02-22 13:19:35 -08001664}
1665
Amin Hassani37b67232020-08-13 09:29:48 -07001666TEST_F(UpdateAttempterTest, TargetChannelHintSetAndReset) {
Amin Hassanie8153632020-10-27 15:11:28 -07001667 attempter_.CalculateUpdateParams({.lts_tag = "hint"});
Amin Hassani538bd592020-11-04 20:46:08 -08001668 EXPECT_EQ("hint", FakeSystemState::Get()->request_params()->lts_tag());
Amin Hassani37b67232020-08-13 09:29:48 -07001669
Amin Hassanie8153632020-10-27 15:11:28 -07001670 attempter_.CalculateUpdateParams({});
Amin Hassani538bd592020-11-04 20:46:08 -08001671 EXPECT_TRUE(FakeSystemState::Get()->request_params()->lts_tag().empty());
Amin Hassani37b67232020-08-13 09:29:48 -07001672}
1673
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001674TEST_F(UpdateAttempterTest, RollbackAllowedSetAndReset) {
Amin Hassanie8153632020-10-27 15:11:28 -07001675 attempter_.CalculateUpdateParams({
1676 .target_version_prefix = "1234",
1677 .rollback_allowed = true,
1678 .rollback_allowed_milestones = 4,
1679 });
Amin Hassani538bd592020-11-04 20:46:08 -08001680 EXPECT_TRUE(FakeSystemState::Get()->request_params()->rollback_allowed());
1681 EXPECT_EQ(
1682 4,
1683 FakeSystemState::Get()->request_params()->rollback_allowed_milestones());
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001684
Amin Hassanie8153632020-10-27 15:11:28 -07001685 attempter_.CalculateUpdateParams({
1686 .target_version_prefix = "1234",
1687 .rollback_allowed_milestones = 4,
1688 });
Amin Hassani538bd592020-11-04 20:46:08 -08001689 EXPECT_FALSE(FakeSystemState::Get()->request_params()->rollback_allowed());
1690 EXPECT_EQ(
1691 4,
1692 FakeSystemState::Get()->request_params()->rollback_allowed_milestones());
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001693}
1694
Miriam Polzeraff72002020-08-27 08:20:39 +02001695TEST_F(UpdateAttempterTest, ChannelDowngradeNoRollback) {
1696 base::ScopedTempDir tempdir;
1697 ASSERT_TRUE(tempdir.CreateUniqueTempDir());
Amin Hassani538bd592020-11-04 20:46:08 -08001698 FakeSystemState::Get()->request_params()->set_root(tempdir.GetPath().value());
Amin Hassanie8153632020-10-27 15:11:28 -07001699 attempter_.CalculateUpdateParams({
1700 .target_channel = "stable-channel",
1701 });
Amin Hassani538bd592020-11-04 20:46:08 -08001702 EXPECT_FALSE(
1703 FakeSystemState::Get()->request_params()->is_powerwash_allowed());
Miriam Polzeraff72002020-08-27 08:20:39 +02001704}
1705
1706TEST_F(UpdateAttempterTest, ChannelDowngradeRollback) {
1707 base::ScopedTempDir tempdir;
1708 ASSERT_TRUE(tempdir.CreateUniqueTempDir());
Amin Hassani538bd592020-11-04 20:46:08 -08001709 FakeSystemState::Get()->request_params()->set_root(tempdir.GetPath().value());
Amin Hassanie8153632020-10-27 15:11:28 -07001710 attempter_.CalculateUpdateParams({
1711 .rollback_on_channel_downgrade = true,
1712 .target_channel = "stable-channel",
1713 });
Amin Hassani538bd592020-11-04 20:46:08 -08001714 EXPECT_TRUE(FakeSystemState::Get()->request_params()->is_powerwash_allowed());
Miriam Polzeraff72002020-08-27 08:20:39 +02001715}
1716
Aaron Wood23bd3392017-10-06 14:48:25 -07001717TEST_F(UpdateAttempterTest, UpdateDeferredByPolicyTest) {
1718 // Construct an OmahaResponseHandlerAction that has processed an InstallPlan,
1719 // but the update is being deferred by the Policy.
Amin Hassani538bd592020-11-04 20:46:08 -08001720 OmahaResponseHandlerAction response_action;
Amin Hassani68512d42018-07-31 23:52:33 -07001721 response_action.install_plan_.version = "a.b.c.d";
Amin Hassani68512d42018-07-31 23:52:33 -07001722 response_action.install_plan_.payloads.push_back(
Aaron Wood23bd3392017-10-06 14:48:25 -07001723 {.size = 1234ULL, .type = InstallPayloadType::kFull});
Aaron Wood23bd3392017-10-06 14:48:25 -07001724 // Inform the UpdateAttempter that the OmahaResponseHandlerAction has
1725 // completed, with the deferred-update error code.
1726 attempter_.ActionCompleted(
Amin Hassani68512d42018-07-31 23:52:33 -07001727 nullptr, &response_action, ErrorCode::kOmahaUpdateDeferredPerPolicy);
Aaron Wood23bd3392017-10-06 14:48:25 -07001728 {
1729 UpdateEngineStatus status;
1730 attempter_.GetStatus(&status);
1731 EXPECT_EQ(UpdateStatus::UPDATE_AVAILABLE, status.status);
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001732 EXPECT_TRUE(attempter_.install_plan_);
1733 EXPECT_EQ(attempter_.install_plan_->version, status.new_version);
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001734 EXPECT_EQ(attempter_.install_plan_->payloads[0].size,
Aaron Wood23bd3392017-10-06 14:48:25 -07001735 status.new_size_bytes);
1736 }
1737 // An "error" event should have been created to tell Omaha that the update is
1738 // being deferred.
1739 EXPECT_TRUE(nullptr != attempter_.error_event_);
1740 EXPECT_EQ(OmahaEvent::kTypeUpdateComplete, attempter_.error_event_->type);
1741 EXPECT_EQ(OmahaEvent::kResultUpdateDeferred, attempter_.error_event_->result);
1742 ErrorCode expected_code = static_cast<ErrorCode>(
1743 static_cast<int>(ErrorCode::kOmahaUpdateDeferredPerPolicy) |
1744 static_cast<int>(ErrorCode::kTestOmahaUrlFlag));
1745 EXPECT_EQ(expected_code, attempter_.error_event_->error_code);
1746 // End the processing
1747 attempter_.ProcessingDone(nullptr, ErrorCode::kOmahaUpdateDeferredPerPolicy);
1748 // Validate the state of the attempter.
1749 {
1750 UpdateEngineStatus status;
1751 attempter_.GetStatus(&status);
1752 EXPECT_EQ(UpdateStatus::REPORTING_ERROR_EVENT, status.status);
Amin Hassani68512d42018-07-31 23:52:33 -07001753 EXPECT_EQ(response_action.install_plan_.version, status.new_version);
Amin Hassani68512d42018-07-31 23:52:33 -07001754 EXPECT_EQ(response_action.install_plan_.payloads[0].size,
Aaron Wood23bd3392017-10-06 14:48:25 -07001755 status.new_size_bytes);
1756 }
1757}
1758
1759TEST_F(UpdateAttempterTest, UpdateIsNotRunningWhenUpdateAvailable) {
Jae Hoon Kim75daa382019-07-02 11:17:24 -07001760 // Default construction for |waiting_for_scheduled_check_| is false.
Jae Hoon Kimba2fdce2019-07-11 13:18:58 -07001761 EXPECT_FALSE(attempter_.IsBusyOrUpdateScheduled());
Aaron Wood23bd3392017-10-06 14:48:25 -07001762 // Verify in-progress update with UPDATE_AVAILABLE is running
1763 attempter_.status_ = UpdateStatus::UPDATE_AVAILABLE;
Jae Hoon Kimba2fdce2019-07-11 13:18:58 -07001764 EXPECT_TRUE(attempter_.IsBusyOrUpdateScheduled());
Aaron Wood23bd3392017-10-06 14:48:25 -07001765}
1766
Aaron Woodbf5a2522017-10-04 10:58:36 -07001767TEST_F(UpdateAttempterTest, UpdateAttemptFlagsCachedAtUpdateStart) {
1768 attempter_.SetUpdateAttemptFlags(UpdateAttemptFlags::kFlagRestrictDownload);
1769
1770 UpdateCheckParams params = {.updates_enabled = true};
1771 attempter_.OnUpdateScheduled(EvalStatus::kSucceeded, params);
1772
1773 EXPECT_EQ(UpdateAttemptFlags::kFlagRestrictDownload,
1774 attempter_.GetCurrentUpdateAttemptFlags());
1775}
1776
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001777TEST_F(UpdateAttempterTest, RollbackNotAllowed) {
1778 UpdateCheckParams params = {.updates_enabled = true,
1779 .rollback_allowed = false};
1780 attempter_.OnUpdateScheduled(EvalStatus::kSucceeded, params);
Amin Hassani538bd592020-11-04 20:46:08 -08001781 EXPECT_FALSE(FakeSystemState::Get()->request_params()->rollback_allowed());
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001782}
1783
1784TEST_F(UpdateAttempterTest, RollbackAllowed) {
1785 UpdateCheckParams params = {.updates_enabled = true,
1786 .rollback_allowed = true};
1787 attempter_.OnUpdateScheduled(EvalStatus::kSucceeded, params);
Amin Hassani538bd592020-11-04 20:46:08 -08001788 EXPECT_TRUE(FakeSystemState::Get()->request_params()->rollback_allowed());
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001789}
1790
Aaron Wood081c0232017-10-19 17:14:58 -07001791TEST_F(UpdateAttempterTest, InteractiveUpdateUsesPassedRestrictions) {
1792 attempter_.SetUpdateAttemptFlags(UpdateAttemptFlags::kFlagRestrictDownload);
1793
1794 attempter_.CheckForUpdate("", "", UpdateAttemptFlags::kNone);
1795 EXPECT_EQ(UpdateAttemptFlags::kNone,
1796 attempter_.GetCurrentUpdateAttemptFlags());
1797}
1798
1799TEST_F(UpdateAttempterTest, NonInteractiveUpdateUsesSetRestrictions) {
1800 attempter_.SetUpdateAttemptFlags(UpdateAttemptFlags::kNone);
1801
1802 // This tests that when CheckForUpdate() is called with the non-interactive
1803 // flag set, that it doesn't change the current UpdateAttemptFlags.
1804 attempter_.CheckForUpdate("",
1805 "",
1806 UpdateAttemptFlags::kFlagNonInteractive |
1807 UpdateAttemptFlags::kFlagRestrictDownload);
1808 EXPECT_EQ(UpdateAttemptFlags::kNone,
1809 attempter_.GetCurrentUpdateAttemptFlags());
1810}
1811
Marton Hunyadye58bddb2018-04-10 20:27:26 +02001812void UpdateAttempterTest::ResetRollbackHappenedStart(bool is_consumer,
1813 bool is_policy_loaded,
1814 bool expected_reset) {
Amin Hassani538bd592020-11-04 20:46:08 -08001815 EXPECT_CALL(*FakeSystemState::Get()->mock_payload_state(),
1816 GetRollbackHappened())
Marton Hunyadye58bddb2018-04-10 20:27:26 +02001817 .WillRepeatedly(Return(true));
1818 auto mock_policy_provider =
1819 std::make_unique<NiceMock<policy::MockPolicyProvider>>();
1820 EXPECT_CALL(*mock_policy_provider, IsConsumerDevice())
1821 .WillRepeatedly(Return(is_consumer));
1822 EXPECT_CALL(*mock_policy_provider, device_policy_is_loaded())
1823 .WillRepeatedly(Return(is_policy_loaded));
1824 const policy::MockDevicePolicy device_policy;
1825 EXPECT_CALL(*mock_policy_provider, GetDevicePolicy())
1826 .WillRepeatedly(ReturnRef(device_policy));
Amin Hassani538bd592020-11-04 20:46:08 -08001827 EXPECT_CALL(*FakeSystemState::Get()->mock_payload_state(),
Marton Hunyadye58bddb2018-04-10 20:27:26 +02001828 SetRollbackHappened(false))
1829 .Times(expected_reset ? 1 : 0);
1830 attempter_.policy_provider_ = std::move(mock_policy_provider);
Amin Hassanie8153632020-10-27 15:11:28 -07001831 attempter_.Update({});
Marton Hunyadye58bddb2018-04-10 20:27:26 +02001832 ScheduleQuitMainLoop();
1833}
1834
1835TEST_F(UpdateAttempterTest, ResetRollbackHappenedOobe) {
1836 loop_.PostTask(FROM_HERE,
1837 base::Bind(&UpdateAttempterTest::ResetRollbackHappenedStart,
1838 base::Unretained(this),
1839 /*is_consumer=*/false,
1840 /*is_policy_loaded=*/false,
1841 /*expected_reset=*/false));
1842 loop_.Run();
1843}
1844
1845TEST_F(UpdateAttempterTest, ResetRollbackHappenedConsumer) {
1846 loop_.PostTask(FROM_HERE,
1847 base::Bind(&UpdateAttempterTest::ResetRollbackHappenedStart,
1848 base::Unretained(this),
1849 /*is_consumer=*/true,
1850 /*is_policy_loaded=*/false,
1851 /*expected_reset=*/true));
1852 loop_.Run();
1853}
1854
1855TEST_F(UpdateAttempterTest, ResetRollbackHappenedEnterprise) {
1856 loop_.PostTask(FROM_HERE,
1857 base::Bind(&UpdateAttempterTest::ResetRollbackHappenedStart,
1858 base::Unretained(this),
1859 /*is_consumer=*/false,
1860 /*is_policy_loaded=*/true,
1861 /*expected_reset=*/true));
1862 loop_.Run();
1863}
1864
Marton Hunyady199152d2018-05-07 19:08:48 +02001865TEST_F(UpdateAttempterTest, SetRollbackHappenedRollback) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001866 attempter_.install_plan_.reset(new InstallPlan);
1867 attempter_.install_plan_->is_rollback = true;
Marton Hunyady199152d2018-05-07 19:08:48 +02001868
Amin Hassani538bd592020-11-04 20:46:08 -08001869 EXPECT_CALL(*FakeSystemState::Get()->mock_payload_state(),
Marton Hunyady199152d2018-05-07 19:08:48 +02001870 SetRollbackHappened(true))
1871 .Times(1);
1872 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1873}
1874
1875TEST_F(UpdateAttempterTest, SetRollbackHappenedNotRollback) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001876 attempter_.install_plan_.reset(new InstallPlan);
1877 attempter_.install_plan_->is_rollback = false;
Marton Hunyady199152d2018-05-07 19:08:48 +02001878
Amin Hassani538bd592020-11-04 20:46:08 -08001879 EXPECT_CALL(*FakeSystemState::Get()->mock_payload_state(),
Marton Hunyady199152d2018-05-07 19:08:48 +02001880 SetRollbackHappened(true))
1881 .Times(0);
1882 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1883}
1884
Marton Hunyadya0302682018-05-16 18:52:13 +02001885TEST_F(UpdateAttempterTest, RollbackMetricsRollbackSuccess) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001886 attempter_.install_plan_.reset(new InstallPlan);
1887 attempter_.install_plan_->is_rollback = true;
1888 attempter_.install_plan_->version = kRollbackVersion;
Marton Hunyadya0302682018-05-16 18:52:13 +02001889
Amin Hassani538bd592020-11-04 20:46:08 -08001890 EXPECT_CALL(*FakeSystemState::Get()->mock_metrics_reporter(),
Marton Hunyadya0302682018-05-16 18:52:13 +02001891 ReportEnterpriseRollbackMetrics(true, kRollbackVersion))
1892 .Times(1);
1893 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1894}
1895
1896TEST_F(UpdateAttempterTest, RollbackMetricsNotRollbackSuccess) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001897 attempter_.install_plan_.reset(new InstallPlan);
1898 attempter_.install_plan_->is_rollback = false;
1899 attempter_.install_plan_->version = kRollbackVersion;
Marton Hunyadya0302682018-05-16 18:52:13 +02001900
Amin Hassani538bd592020-11-04 20:46:08 -08001901 EXPECT_CALL(*FakeSystemState::Get()->mock_metrics_reporter(),
Marton Hunyadya0302682018-05-16 18:52:13 +02001902 ReportEnterpriseRollbackMetrics(_, _))
1903 .Times(0);
1904 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1905}
1906
1907TEST_F(UpdateAttempterTest, RollbackMetricsRollbackFailure) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001908 attempter_.install_plan_.reset(new InstallPlan);
1909 attempter_.install_plan_->is_rollback = true;
1910 attempter_.install_plan_->version = kRollbackVersion;
Marton Hunyadya0302682018-05-16 18:52:13 +02001911
Amin Hassani538bd592020-11-04 20:46:08 -08001912 EXPECT_CALL(*FakeSystemState::Get()->mock_metrics_reporter(),
Marton Hunyadya0302682018-05-16 18:52:13 +02001913 ReportEnterpriseRollbackMetrics(false, kRollbackVersion))
1914 .Times(1);
1915 MockAction action;
1916 attempter_.CreatePendingErrorEvent(&action, ErrorCode::kRollbackNotPossible);
1917 attempter_.ProcessingDone(nullptr, ErrorCode::kRollbackNotPossible);
1918}
1919
1920TEST_F(UpdateAttempterTest, RollbackMetricsNotRollbackFailure) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001921 attempter_.install_plan_.reset(new InstallPlan);
1922 attempter_.install_plan_->is_rollback = false;
1923 attempter_.install_plan_->version = kRollbackVersion;
Marton Hunyadya0302682018-05-16 18:52:13 +02001924
Amin Hassani538bd592020-11-04 20:46:08 -08001925 EXPECT_CALL(*FakeSystemState::Get()->mock_metrics_reporter(),
Marton Hunyadya0302682018-05-16 18:52:13 +02001926 ReportEnterpriseRollbackMetrics(_, _))
1927 .Times(0);
1928 MockAction action;
1929 attempter_.CreatePendingErrorEvent(&action, ErrorCode::kRollbackNotPossible);
1930 attempter_.ProcessingDone(nullptr, ErrorCode::kRollbackNotPossible);
1931}
1932
May Lippert60aa3ca2018-08-15 16:55:29 -07001933TEST_F(UpdateAttempterTest, TimeToUpdateAppliedMetricFailure) {
Amin Hassani538bd592020-11-04 20:46:08 -08001934 EXPECT_CALL(*FakeSystemState::Get()->mock_metrics_reporter(),
May Lippert60aa3ca2018-08-15 16:55:29 -07001935 ReportEnterpriseUpdateSeenToDownloadDays(_, _))
1936 .Times(0);
1937 attempter_.ProcessingDone(nullptr, ErrorCode::kOmahaUpdateDeferredPerPolicy);
1938}
1939
1940TEST_F(UpdateAttempterTest, TimeToUpdateAppliedOnNonEnterprise) {
1941 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Amin Hassani538bd592020-11-04 20:46:08 -08001942 FakeSystemState::Get()->set_device_policy(device_policy.get());
May Lippert60aa3ca2018-08-15 16:55:29 -07001943 // Make device policy return that this is not enterprise enrolled
1944 EXPECT_CALL(*device_policy, IsEnterpriseEnrolled()).WillOnce(Return(false));
1945
1946 // Ensure that the metric is not recorded.
Amin Hassani538bd592020-11-04 20:46:08 -08001947 EXPECT_CALL(*FakeSystemState::Get()->mock_metrics_reporter(),
May Lippert60aa3ca2018-08-15 16:55:29 -07001948 ReportEnterpriseUpdateSeenToDownloadDays(_, _))
1949 .Times(0);
1950 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1951}
1952
1953TEST_F(UpdateAttempterTest,
1954 TimeToUpdateAppliedWithTimeRestrictionMetricSuccess) {
1955 constexpr int kDaysToUpdate = 15;
1956 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Amin Hassani538bd592020-11-04 20:46:08 -08001957 FakeSystemState::Get()->set_device_policy(device_policy.get());
May Lippert60aa3ca2018-08-15 16:55:29 -07001958 // Make device policy return that this is enterprise enrolled
1959 EXPECT_CALL(*device_policy, IsEnterpriseEnrolled()).WillOnce(Return(true));
1960 // Pretend that there's a time restriction policy in place
1961 EXPECT_CALL(*device_policy, GetDisallowedTimeIntervals(_))
1962 .WillOnce(Return(true));
1963
1964 FakePrefs fake_prefs;
1965 Time update_first_seen_at = Time::Now();
1966 fake_prefs.SetInt64(kPrefsUpdateFirstSeenAt,
1967 update_first_seen_at.ToInternalValue());
1968
1969 FakeClock fake_clock;
1970 Time update_finished_at =
1971 update_first_seen_at + TimeDelta::FromDays(kDaysToUpdate);
1972 fake_clock.SetWallclockTime(update_finished_at);
1973
Amin Hassani538bd592020-11-04 20:46:08 -08001974 FakeSystemState::Get()->set_clock(&fake_clock);
1975 FakeSystemState::Get()->set_prefs(&fake_prefs);
May Lippert60aa3ca2018-08-15 16:55:29 -07001976
Amin Hassani538bd592020-11-04 20:46:08 -08001977 EXPECT_CALL(*FakeSystemState::Get()->mock_metrics_reporter(),
May Lippert60aa3ca2018-08-15 16:55:29 -07001978 ReportEnterpriseUpdateSeenToDownloadDays(true, kDaysToUpdate))
1979 .Times(1);
1980 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1981}
1982
1983TEST_F(UpdateAttempterTest,
1984 TimeToUpdateAppliedWithoutTimeRestrictionMetricSuccess) {
1985 constexpr int kDaysToUpdate = 15;
1986 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Amin Hassani538bd592020-11-04 20:46:08 -08001987 FakeSystemState::Get()->set_device_policy(device_policy.get());
May Lippert60aa3ca2018-08-15 16:55:29 -07001988 // Make device policy return that this is enterprise enrolled
1989 EXPECT_CALL(*device_policy, IsEnterpriseEnrolled()).WillOnce(Return(true));
1990 // Pretend that there's no time restriction policy in place
1991 EXPECT_CALL(*device_policy, GetDisallowedTimeIntervals(_))
1992 .WillOnce(Return(false));
1993
1994 FakePrefs fake_prefs;
1995 Time update_first_seen_at = Time::Now();
1996 fake_prefs.SetInt64(kPrefsUpdateFirstSeenAt,
1997 update_first_seen_at.ToInternalValue());
1998
1999 FakeClock fake_clock;
2000 Time update_finished_at =
2001 update_first_seen_at + TimeDelta::FromDays(kDaysToUpdate);
2002 fake_clock.SetWallclockTime(update_finished_at);
2003
Amin Hassani538bd592020-11-04 20:46:08 -08002004 FakeSystemState::Get()->set_clock(&fake_clock);
2005 FakeSystemState::Get()->set_prefs(&fake_prefs);
May Lippert60aa3ca2018-08-15 16:55:29 -07002006
Amin Hassani538bd592020-11-04 20:46:08 -08002007 EXPECT_CALL(*FakeSystemState::Get()->mock_metrics_reporter(),
May Lippert60aa3ca2018-08-15 16:55:29 -07002008 ReportEnterpriseUpdateSeenToDownloadDays(false, kDaysToUpdate))
2009 .Times(1);
2010 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
2011}
2012
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002013TEST_F(UpdateAttempterTest, ProcessingDoneUpdated) {
2014 // GIVEN an update finished.
2015
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002016 // THEN update_engine should call update completion.
2017 pd_params_.should_update_completed_be_called = true;
2018 // THEN need reboot since update applied.
2019 pd_params_.expected_exit_status = UpdateStatus::UPDATED_NEED_REBOOT;
2020 // THEN install indication should be false.
2021
2022 TestProcessingDone();
2023}
2024
2025TEST_F(UpdateAttempterTest, ProcessingDoneUpdatedDlcFilter) {
2026 // GIVEN an update finished.
2027 // GIVEN DLC |AppParams| list.
2028 auto dlc_1 = "dlc_1", dlc_2 = "dlc_2";
2029 pd_params_.dlc_apps_params = {{dlc_1, {.name = dlc_1, .updated = false}},
2030 {dlc_2, {.name = dlc_2}}};
2031
2032 // THEN update_engine should call update completion.
2033 pd_params_.should_update_completed_be_called = true;
2034 pd_params_.args_to_update_completed = {dlc_2};
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002035 // THEN need reboot since update applied.
2036 pd_params_.expected_exit_status = UpdateStatus::UPDATED_NEED_REBOOT;
2037 // THEN install indication should be false.
2038
2039 TestProcessingDone();
2040}
2041
2042TEST_F(UpdateAttempterTest, ProcessingDoneInstalled) {
2043 // GIVEN an install finished.
2044 pd_params_.is_install = true;
2045
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002046 // THEN update_engine should call install completion.
2047 pd_params_.should_install_completed_be_called = true;
2048 // THEN go idle.
2049 // THEN install indication should be false.
2050
2051 TestProcessingDone();
2052}
2053
2054TEST_F(UpdateAttempterTest, ProcessingDoneInstalledDlcFilter) {
2055 // GIVEN an install finished.
2056 pd_params_.is_install = true;
2057 // GIVEN DLC |AppParams| list.
2058 auto dlc_1 = "dlc_1", dlc_2 = "dlc_2";
2059 pd_params_.dlc_apps_params = {{dlc_1, {.name = dlc_1, .updated = false}},
2060 {dlc_2, {.name = dlc_2}}};
2061
2062 // THEN update_engine should call install completion.
2063 pd_params_.should_install_completed_be_called = true;
2064 pd_params_.args_to_install_completed = {dlc_2};
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002065 // THEN go idle.
2066 // THEN install indication should be false.
2067
2068 TestProcessingDone();
2069}
2070
2071TEST_F(UpdateAttempterTest, ProcessingDoneInstallReportingError) {
2072 // GIVEN an install finished.
2073 pd_params_.is_install = true;
2074 // GIVEN a reporting error occurred.
2075 pd_params_.status = UpdateStatus::REPORTING_ERROR_EVENT;
2076
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002077 // THEN update_engine should not call install completion.
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002078 // THEN go idle.
2079 // THEN install indication should be false.
2080
2081 TestProcessingDone();
2082}
2083
2084TEST_F(UpdateAttempterTest, ProcessingDoneNoUpdate) {
2085 // GIVEN an update finished.
2086 // GIVEN an action error occured.
2087 pd_params_.code = ErrorCode::kNoUpdate;
2088
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002089 // THEN update_engine should not call update completion.
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002090 // THEN go idle.
2091 // THEN install indication should be false.
2092
2093 TestProcessingDone();
2094}
2095
2096TEST_F(UpdateAttempterTest, ProcessingDoneNoInstall) {
2097 // GIVEN an install finished.
2098 pd_params_.is_install = true;
2099 // GIVEN an action error occured.
2100 pd_params_.code = ErrorCode::kNoUpdate;
2101
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002102 // THEN update_engine should not call install completion.
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002103 // THEN go idle.
2104 // THEN install indication should be false.
2105
2106 TestProcessingDone();
2107}
2108
2109TEST_F(UpdateAttempterTest, ProcessingDoneUpdateError) {
2110 // GIVEN an update finished.
2111 // GIVEN an action error occured.
2112 pd_params_.code = ErrorCode::kError;
2113 // GIVEN an event error is set.
2114 attempter_.error_event_.reset(new OmahaEvent(OmahaEvent::kTypeUpdateComplete,
2115 OmahaEvent::kResultError,
2116 ErrorCode::kError));
2117
2118 // THEN indicate a error event.
2119 pd_params_.expected_exit_status = UpdateStatus::REPORTING_ERROR_EVENT;
2120 // THEN install indication should be false.
2121
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002122 // THEN update_engine should not call update completion.
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002123 // THEN expect critical actions of |ScheduleErrorEventAction()|.
2124 EXPECT_CALL(*processor_, EnqueueAction(Pointee(_))).Times(1);
2125 EXPECT_CALL(*processor_, StartProcessing()).Times(1);
2126 // THEN |ScheduleUpdates()| will be called next |ProcessingDone()| so skip.
2127 pd_params_.should_schedule_updates_be_called = false;
2128
2129 TestProcessingDone();
2130}
2131
2132TEST_F(UpdateAttempterTest, ProcessingDoneInstallError) {
2133 // GIVEN an install finished.
2134 pd_params_.is_install = true;
2135 // GIVEN an action error occured.
2136 pd_params_.code = ErrorCode::kError;
2137 // GIVEN an event error is set.
2138 attempter_.error_event_.reset(new OmahaEvent(OmahaEvent::kTypeUpdateComplete,
2139 OmahaEvent::kResultError,
2140 ErrorCode::kError));
2141
2142 // THEN indicate a error event.
2143 pd_params_.expected_exit_status = UpdateStatus::REPORTING_ERROR_EVENT;
2144 // THEN install indication should be false.
2145
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002146 // THEN update_engine should not call install completion.
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002147 // THEN expect critical actions of |ScheduleErrorEventAction()|.
2148 EXPECT_CALL(*processor_, EnqueueAction(Pointee(_))).Times(1);
2149 EXPECT_CALL(*processor_, StartProcessing()).Times(1);
2150 // THEN |ScheduleUpdates()| will be called next |ProcessingDone()| so skip.
2151 pd_params_.should_schedule_updates_be_called = false;
2152
2153 TestProcessingDone();
2154}
2155
Amr Aboelkher21ac9962019-05-15 14:50:05 +02002156void UpdateAttempterTest::UpdateToQuickFixBuildStart(bool set_token) {
2157 // Tests that checks if |device_quick_fix_build_token| arrives when
2158 // policy is set and the device is enterprise enrolled based on |set_token|.
2159 string token = set_token ? "some_token" : "";
Askar Aitzhan570ca872019-04-24 11:16:12 +02002160 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Amin Hassani538bd592020-11-04 20:46:08 -08002161 FakeSystemState::Get()->set_device_policy(device_policy.get());
Askar Aitzhan570ca872019-04-24 11:16:12 +02002162 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
Amr Aboelkher21ac9962019-05-15 14:50:05 +02002163
2164 if (set_token)
2165 EXPECT_CALL(*device_policy, GetDeviceQuickFixBuildToken(_))
2166 .WillOnce(DoAll(SetArgPointee<0>(token), Return(true)));
2167 else
2168 EXPECT_CALL(*device_policy, GetDeviceQuickFixBuildToken(_))
2169 .WillOnce(Return(false));
Askar Aitzhan570ca872019-04-24 11:16:12 +02002170 attempter_.policy_provider_.reset(
2171 new policy::PolicyProvider(std::move(device_policy)));
Amin Hassanie8153632020-10-27 15:11:28 -07002172 attempter_.Update({});
Askar Aitzhan570ca872019-04-24 11:16:12 +02002173
Amr Aboelkher21ac9962019-05-15 14:50:05 +02002174 EXPECT_EQ(token, attempter_.omaha_request_params_->autoupdate_token());
Askar Aitzhan570ca872019-04-24 11:16:12 +02002175 ScheduleQuitMainLoop();
2176}
2177
Amr Aboelkher21ac9962019-05-15 14:50:05 +02002178TEST_F(UpdateAttempterTest,
2179 QuickFixTokenWhenDeviceIsEnterpriseEnrolledAndPolicyIsSet) {
Askar Aitzhan570ca872019-04-24 11:16:12 +02002180 loop_.PostTask(FROM_HERE,
2181 base::Bind(&UpdateAttempterTest::UpdateToQuickFixBuildStart,
Amr Aboelkher21ac9962019-05-15 14:50:05 +02002182 base::Unretained(this),
2183 /*set_token=*/true));
2184 loop_.Run();
2185}
2186
2187TEST_F(UpdateAttempterTest, EmptyQuickFixToken) {
2188 loop_.PostTask(FROM_HERE,
2189 base::Bind(&UpdateAttempterTest::UpdateToQuickFixBuildStart,
2190 base::Unretained(this),
2191 /*set_token=*/false));
Askar Aitzhan570ca872019-04-24 11:16:12 +02002192 loop_.Run();
2193}
2194
Jae Hoon Kim75daa382019-07-02 11:17:24 -07002195TEST_F(UpdateAttempterTest, ScheduleUpdateSpamHandlerTest) {
2196 EXPECT_CALL(mock_update_manager_, AsyncPolicyRequestUpdateCheckAllowed(_, _))
2197 .Times(1);
2198 EXPECT_TRUE(attempter_.ScheduleUpdates());
2199 // Now there is an update scheduled which means that all subsequent
2200 // |ScheduleUpdates()| should fail.
2201 EXPECT_FALSE(attempter_.ScheduleUpdates());
2202 EXPECT_FALSE(attempter_.ScheduleUpdates());
2203 EXPECT_FALSE(attempter_.ScheduleUpdates());
2204}
2205
2206// Critical tests to always make sure that an update is scheduled. The following
2207// unittest(s) try and cover the correctness in synergy between
2208// |UpdateAttempter| and |UpdateManager|. Also it is good to remember the
2209// actions that happen in the flow when |UpdateAttempter| get callbacked on
2210// |OnUpdateScheduled()| -> (various cases which leads to) -> |ProcessingDone()|
2211void UpdateAttempterTest::TestOnUpdateScheduled() {
2212 // Setup
2213 attempter_.SetWaitingForScheduledCheck(true);
2214 attempter_.DisableUpdate();
2215 attempter_.DisableScheduleUpdates();
2216
2217 // Invocation
2218 attempter_.OnUpdateScheduled(ous_params_.status, ous_params_.params);
2219
2220 // Verify
2221 EXPECT_EQ(ous_params_.exit_status, attempter_.status());
2222 EXPECT_EQ(ous_params_.should_schedule_updates_be_called,
2223 attempter_.WasScheduleUpdatesCalled());
2224 EXPECT_EQ(ous_params_.should_update_be_called, attempter_.WasUpdateCalled());
2225}
2226
2227TEST_F(UpdateAttempterTest, OnUpdatesScheduledFailed) {
2228 // GIVEN failed status.
2229
2230 // THEN update should be scheduled.
2231 ous_params_.should_schedule_updates_be_called = true;
2232
2233 TestOnUpdateScheduled();
2234}
2235
2236TEST_F(UpdateAttempterTest, OnUpdatesScheduledAskMeAgainLater) {
2237 // GIVEN ask me again later status.
2238 ous_params_.status = EvalStatus::kAskMeAgainLater;
2239
2240 // THEN update should be scheduled.
2241 ous_params_.should_schedule_updates_be_called = true;
2242
2243 TestOnUpdateScheduled();
2244}
2245
2246TEST_F(UpdateAttempterTest, OnUpdatesScheduledContinue) {
2247 // GIVEN continue status.
2248 ous_params_.status = EvalStatus::kContinue;
2249
2250 // THEN update should be scheduled.
2251 ous_params_.should_schedule_updates_be_called = true;
2252
2253 TestOnUpdateScheduled();
2254}
2255
2256TEST_F(UpdateAttempterTest, OnUpdatesScheduledSucceededButUpdateDisabledFails) {
2257 // GIVEN updates disabled.
2258 ous_params_.params = {.updates_enabled = false};
2259 // GIVEN succeeded status.
2260 ous_params_.status = EvalStatus::kSucceeded;
2261
2262 // THEN update should not be scheduled.
2263
2264 TestOnUpdateScheduled();
2265}
2266
2267TEST_F(UpdateAttempterTest, OnUpdatesScheduledSucceeded) {
2268 // GIVEN updates enabled.
2269 ous_params_.params = {.updates_enabled = true};
2270 // GIVEN succeeded status.
2271 ous_params_.status = EvalStatus::kSucceeded;
2272
2273 // THEN update should be called indicating status change.
2274 ous_params_.exit_status = UpdateStatus::CHECKING_FOR_UPDATE;
2275 ous_params_.should_update_be_called = true;
2276
2277 TestOnUpdateScheduled();
2278}
2279
Amin Hassani9be122e2019-08-29 09:20:12 -07002280TEST_F(UpdateAttempterTest, IsEnterpriseRollbackInGetStatusDefault) {
2281 UpdateEngineStatus status;
2282 attempter_.GetStatus(&status);
2283 EXPECT_FALSE(status.is_enterprise_rollback);
2284}
2285
2286TEST_F(UpdateAttempterTest, IsEnterpriseRollbackInGetStatusFalse) {
2287 attempter_.install_plan_.reset(new InstallPlan);
2288 attempter_.install_plan_->is_rollback = false;
2289
2290 UpdateEngineStatus status;
2291 attempter_.GetStatus(&status);
2292 EXPECT_FALSE(status.is_enterprise_rollback);
2293}
2294
2295TEST_F(UpdateAttempterTest, IsEnterpriseRollbackInGetStatusTrue) {
2296 attempter_.install_plan_.reset(new InstallPlan);
2297 attempter_.install_plan_->is_rollback = true;
2298
2299 UpdateEngineStatus status;
2300 attempter_.GetStatus(&status);
2301 EXPECT_TRUE(status.is_enterprise_rollback);
2302}
2303
Miriam Polzer0cf1acb2020-04-29 17:39:51 +02002304TEST_F(UpdateAttempterTest, PowerwashInGetStatusDefault) {
2305 UpdateEngineStatus status;
2306 attempter_.GetStatus(&status);
2307 EXPECT_FALSE(status.will_powerwash_after_reboot);
2308}
2309
2310TEST_F(UpdateAttempterTest, PowerwashInGetStatusTrueBecausePowerwashRequired) {
2311 attempter_.install_plan_.reset(new InstallPlan);
2312 attempter_.install_plan_->powerwash_required = true;
2313
2314 UpdateEngineStatus status;
2315 attempter_.GetStatus(&status);
2316 EXPECT_TRUE(status.will_powerwash_after_reboot);
2317}
2318
2319TEST_F(UpdateAttempterTest, PowerwashInGetStatusTrueBecauseRollback) {
2320 attempter_.install_plan_.reset(new InstallPlan);
2321 attempter_.install_plan_->is_rollback = true;
2322
2323 UpdateEngineStatus status;
2324 attempter_.GetStatus(&status);
2325 EXPECT_TRUE(status.will_powerwash_after_reboot);
2326}
2327
Jae Hoon Kim051627a2019-09-03 12:56:32 -07002328TEST_F(UpdateAttempterTest, FutureEolTest) {
2329 EolDate eol_date = std::numeric_limits<int64_t>::max();
Jae Hoon Kim2dfd35d2020-06-02 10:53:13 -07002330 EXPECT_CALL(*prefs_, Exists(kPrefsOmahaEolDate)).WillOnce(Return(true));
Jae Hoon Kim051627a2019-09-03 12:56:32 -07002331 EXPECT_CALL(*prefs_, GetString(kPrefsOmahaEolDate, _))
2332 .WillOnce(
2333 DoAll(SetArgPointee<1>(EolDateToString(eol_date)), Return(true)));
2334
2335 UpdateEngineStatus status;
2336 attempter_.GetStatus(&status);
2337 EXPECT_EQ(eol_date, status.eol_date);
2338}
2339
2340TEST_F(UpdateAttempterTest, PastEolTest) {
2341 EolDate eol_date = 1;
Jae Hoon Kim2dfd35d2020-06-02 10:53:13 -07002342 EXPECT_CALL(*prefs_, Exists(kPrefsOmahaEolDate)).WillOnce(Return(true));
Jae Hoon Kim051627a2019-09-03 12:56:32 -07002343 EXPECT_CALL(*prefs_, GetString(kPrefsOmahaEolDate, _))
2344 .WillOnce(
2345 DoAll(SetArgPointee<1>(EolDateToString(eol_date)), Return(true)));
2346
2347 UpdateEngineStatus status;
2348 attempter_.GetStatus(&status);
2349 EXPECT_EQ(eol_date, status.eol_date);
2350}
2351
2352TEST_F(UpdateAttempterTest, FailedEolTest) {
Jae Hoon Kim2dfd35d2020-06-02 10:53:13 -07002353 EXPECT_CALL(*prefs_, Exists(kPrefsOmahaEolDate)).WillOnce(Return(true));
Jae Hoon Kim051627a2019-09-03 12:56:32 -07002354 EXPECT_CALL(*prefs_, GetString(kPrefsOmahaEolDate, _))
2355 .WillOnce(Return(false));
2356
2357 UpdateEngineStatus status;
2358 attempter_.GetStatus(&status);
Jae Hoon Kim2dfd35d2020-06-02 10:53:13 -07002359 EXPECT_EQ(kEolDateInvalid, status.eol_date);
2360}
2361
2362TEST_F(UpdateAttempterTest, MissingEolTest) {
2363 EXPECT_CALL(*prefs_, Exists(kPrefsOmahaEolDate)).WillOnce(Return(false));
2364
2365 UpdateEngineStatus status;
2366 attempter_.GetStatus(&status);
2367 EXPECT_EQ(kEolDateInvalid, status.eol_date);
Jae Hoon Kim051627a2019-09-03 12:56:32 -07002368}
2369
Andrewe045aef2020-01-08 16:29:22 -08002370TEST_F(UpdateAttempterTest, CalculateDlcParamsInstallTest) {
Andrewe045aef2020-01-08 16:29:22 -08002371 string dlc_id = "dlc0";
Andrew065d78d2020-04-07 15:43:07 -07002372 FakePrefs fake_prefs;
Amin Hassani538bd592020-11-04 20:46:08 -08002373 FakeSystemState::Get()->set_prefs(&fake_prefs);
Andrewe045aef2020-01-08 16:29:22 -08002374 attempter_.is_install_ = true;
Amin Hassani2b68e6b2020-04-17 10:49:12 -07002375 attempter_.dlc_ids_ = {dlc_id};
Andrewe045aef2020-01-08 16:29:22 -08002376 attempter_.CalculateDlcParams();
2377
Amin Hassani538bd592020-11-04 20:46:08 -08002378 OmahaRequestParams* params = FakeSystemState::Get()->request_params();
Andrewe045aef2020-01-08 16:29:22 -08002379 EXPECT_EQ(1, params->dlc_apps_params().count(params->GetDlcAppId(dlc_id)));
2380 OmahaRequestParams::AppParams dlc_app_params =
2381 params->dlc_apps_params().at(params->GetDlcAppId(dlc_id));
2382 EXPECT_STREQ(dlc_id.c_str(), dlc_app_params.name.c_str());
2383 EXPECT_EQ(false, dlc_app_params.send_ping);
2384 // When the DLC gets installed, a ping is not sent, therefore we don't store
2385 // the values sent by Omaha.
Andrew065d78d2020-04-07 15:43:07 -07002386 auto last_active_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002387 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastActive});
Amin Hassani538bd592020-11-04 20:46:08 -08002388 EXPECT_FALSE(FakeSystemState::Get()->prefs()->Exists(last_active_key));
Andrew065d78d2020-04-07 15:43:07 -07002389 auto last_rollcall_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002390 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastRollcall});
Amin Hassani538bd592020-11-04 20:46:08 -08002391 EXPECT_FALSE(FakeSystemState::Get()->prefs()->Exists(last_rollcall_key));
Andrewe045aef2020-01-08 16:29:22 -08002392}
2393
2394TEST_F(UpdateAttempterTest, CalculateDlcParamsNoPrefFilesTest) {
Andrewe045aef2020-01-08 16:29:22 -08002395 string dlc_id = "dlc0";
Andrew065d78d2020-04-07 15:43:07 -07002396 FakePrefs fake_prefs;
Amin Hassani538bd592020-11-04 20:46:08 -08002397 FakeSystemState::Get()->set_prefs(&fake_prefs);
Amin Hassani2b68e6b2020-04-17 10:49:12 -07002398 EXPECT_CALL(mock_dlcservice_, GetDlcsToUpdate(_))
Andrewe045aef2020-01-08 16:29:22 -08002399 .WillOnce(
2400 DoAll(SetArgPointee<0>(std::vector<string>({dlc_id})), Return(true)));
2401
2402 attempter_.is_install_ = false;
2403 attempter_.CalculateDlcParams();
2404
Amin Hassani538bd592020-11-04 20:46:08 -08002405 OmahaRequestParams* params = FakeSystemState::Get()->request_params();
Andrewe045aef2020-01-08 16:29:22 -08002406 EXPECT_EQ(1, params->dlc_apps_params().count(params->GetDlcAppId(dlc_id)));
2407 OmahaRequestParams::AppParams dlc_app_params =
2408 params->dlc_apps_params().at(params->GetDlcAppId(dlc_id));
2409 EXPECT_STREQ(dlc_id.c_str(), dlc_app_params.name.c_str());
2410
2411 EXPECT_EQ(true, dlc_app_params.send_ping);
2412 EXPECT_EQ(0, dlc_app_params.ping_active);
2413 EXPECT_EQ(-1, dlc_app_params.ping_date_last_active);
2414 EXPECT_EQ(-1, dlc_app_params.ping_date_last_rollcall);
2415}
2416
2417TEST_F(UpdateAttempterTest, CalculateDlcParamsNonParseableValuesTest) {
Andrewe045aef2020-01-08 16:29:22 -08002418 string dlc_id = "dlc0";
Andrew065d78d2020-04-07 15:43:07 -07002419 MemoryPrefs prefs;
Amin Hassani538bd592020-11-04 20:46:08 -08002420 FakeSystemState::Get()->set_prefs(&prefs);
Amin Hassani2b68e6b2020-04-17 10:49:12 -07002421 EXPECT_CALL(mock_dlcservice_, GetDlcsToUpdate(_))
Andrewe045aef2020-01-08 16:29:22 -08002422 .WillOnce(
2423 DoAll(SetArgPointee<0>(std::vector<string>({dlc_id})), Return(true)));
2424
2425 // Write non numeric values in the metadata files.
Andrew065d78d2020-04-07 15:43:07 -07002426 auto active_key =
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002427 PrefsInterface::CreateSubKey({kDlcPrefsSubDir, dlc_id, kPrefsPingActive});
Andrew065d78d2020-04-07 15:43:07 -07002428 auto last_active_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002429 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastActive});
Andrew065d78d2020-04-07 15:43:07 -07002430 auto last_rollcall_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002431 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastRollcall});
Amin Hassani538bd592020-11-04 20:46:08 -08002432 FakeSystemState::Get()->prefs()->SetString(active_key, "z2yz");
2433 FakeSystemState::Get()->prefs()->SetString(last_active_key, "z2yz");
2434 FakeSystemState::Get()->prefs()->SetString(last_rollcall_key, "z2yz");
Andrewe045aef2020-01-08 16:29:22 -08002435 attempter_.is_install_ = false;
2436 attempter_.CalculateDlcParams();
2437
Amin Hassani538bd592020-11-04 20:46:08 -08002438 OmahaRequestParams* params = FakeSystemState::Get()->request_params();
Andrewe045aef2020-01-08 16:29:22 -08002439 EXPECT_EQ(1, params->dlc_apps_params().count(params->GetDlcAppId(dlc_id)));
2440 OmahaRequestParams::AppParams dlc_app_params =
2441 params->dlc_apps_params().at(params->GetDlcAppId(dlc_id));
2442 EXPECT_STREQ(dlc_id.c_str(), dlc_app_params.name.c_str());
2443
2444 EXPECT_EQ(true, dlc_app_params.send_ping);
2445 EXPECT_EQ(0, dlc_app_params.ping_active);
2446 EXPECT_EQ(-2, dlc_app_params.ping_date_last_active);
2447 EXPECT_EQ(-2, dlc_app_params.ping_date_last_rollcall);
2448}
2449
2450TEST_F(UpdateAttempterTest, CalculateDlcParamsValidValuesTest) {
Andrewe045aef2020-01-08 16:29:22 -08002451 string dlc_id = "dlc0";
Andrew065d78d2020-04-07 15:43:07 -07002452 MemoryPrefs fake_prefs;
Amin Hassani538bd592020-11-04 20:46:08 -08002453 FakeSystemState::Get()->set_prefs(&fake_prefs);
Amin Hassani2b68e6b2020-04-17 10:49:12 -07002454 EXPECT_CALL(mock_dlcservice_, GetDlcsToUpdate(_))
Andrewe045aef2020-01-08 16:29:22 -08002455 .WillOnce(
2456 DoAll(SetArgPointee<0>(std::vector<string>({dlc_id})), Return(true)));
2457
2458 // Write numeric values in the metadata files.
Andrew065d78d2020-04-07 15:43:07 -07002459 auto active_key =
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002460 PrefsInterface::CreateSubKey({kDlcPrefsSubDir, dlc_id, kPrefsPingActive});
Andrew065d78d2020-04-07 15:43:07 -07002461 auto last_active_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002462 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastActive});
Andrew065d78d2020-04-07 15:43:07 -07002463 auto last_rollcall_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002464 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastRollcall});
Andrew065d78d2020-04-07 15:43:07 -07002465
Amin Hassani538bd592020-11-04 20:46:08 -08002466 FakeSystemState::Get()->prefs()->SetInt64(active_key, 1);
2467 FakeSystemState::Get()->prefs()->SetInt64(last_active_key, 78);
2468 FakeSystemState::Get()->prefs()->SetInt64(last_rollcall_key, 99);
Andrewe045aef2020-01-08 16:29:22 -08002469 attempter_.is_install_ = false;
2470 attempter_.CalculateDlcParams();
2471
Amin Hassani538bd592020-11-04 20:46:08 -08002472 OmahaRequestParams* params = FakeSystemState::Get()->request_params();
Andrewe045aef2020-01-08 16:29:22 -08002473 EXPECT_EQ(1, params->dlc_apps_params().count(params->GetDlcAppId(dlc_id)));
2474 OmahaRequestParams::AppParams dlc_app_params =
2475 params->dlc_apps_params().at(params->GetDlcAppId(dlc_id));
2476 EXPECT_STREQ(dlc_id.c_str(), dlc_app_params.name.c_str());
2477
2478 EXPECT_EQ(true, dlc_app_params.send_ping);
2479 EXPECT_EQ(1, dlc_app_params.ping_active);
2480 EXPECT_EQ(78, dlc_app_params.ping_date_last_active);
2481 EXPECT_EQ(99, dlc_app_params.ping_date_last_rollcall);
2482}
Andrewa8d7df32020-03-15 20:10:01 -07002483
2484TEST_F(UpdateAttempterTest, CalculateDlcParamsRemoveStaleMetadata) {
Andrewa8d7df32020-03-15 20:10:01 -07002485 string dlc_id = "dlc0";
Andrew065d78d2020-04-07 15:43:07 -07002486 FakePrefs fake_prefs;
Amin Hassani538bd592020-11-04 20:46:08 -08002487 FakeSystemState::Get()->set_prefs(&fake_prefs);
Andrew065d78d2020-04-07 15:43:07 -07002488 auto active_key =
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002489 PrefsInterface::CreateSubKey({kDlcPrefsSubDir, dlc_id, kPrefsPingActive});
Andrew065d78d2020-04-07 15:43:07 -07002490 auto last_active_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002491 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastActive});
Andrew065d78d2020-04-07 15:43:07 -07002492 auto last_rollcall_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002493 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastRollcall});
Amin Hassani538bd592020-11-04 20:46:08 -08002494 FakeSystemState::Get()->prefs()->SetInt64(active_key, kPingInactiveValue);
2495 FakeSystemState::Get()->prefs()->SetInt64(last_active_key, 0);
2496 FakeSystemState::Get()->prefs()->SetInt64(last_rollcall_key, 0);
2497 EXPECT_TRUE(FakeSystemState::Get()->prefs()->Exists(active_key));
2498 EXPECT_TRUE(FakeSystemState::Get()->prefs()->Exists(last_active_key));
2499 EXPECT_TRUE(FakeSystemState::Get()->prefs()->Exists(last_rollcall_key));
Andrewa8d7df32020-03-15 20:10:01 -07002500
Andrew065d78d2020-04-07 15:43:07 -07002501 attempter_.dlc_ids_ = {dlc_id};
2502 attempter_.is_install_ = true;
Andrewa8d7df32020-03-15 20:10:01 -07002503 attempter_.CalculateDlcParams();
2504
Amin Hassani538bd592020-11-04 20:46:08 -08002505 EXPECT_FALSE(FakeSystemState::Get()->prefs()->Exists(last_active_key));
2506 EXPECT_FALSE(FakeSystemState::Get()->prefs()->Exists(last_rollcall_key));
Andrew065d78d2020-04-07 15:43:07 -07002507 // Active key is set on install.
Amin Hassani538bd592020-11-04 20:46:08 -08002508 EXPECT_TRUE(FakeSystemState::Get()->prefs()->Exists(active_key));
Andrew065d78d2020-04-07 15:43:07 -07002509 int64_t temp_int;
Amin Hassani538bd592020-11-04 20:46:08 -08002510 EXPECT_TRUE(FakeSystemState::Get()->prefs()->GetInt64(active_key, &temp_int));
Andrew065d78d2020-04-07 15:43:07 -07002511 EXPECT_EQ(temp_int, kPingActiveValue);
Andrewa8d7df32020-03-15 20:10:01 -07002512}
2513
2514TEST_F(UpdateAttempterTest, SetDlcActiveValue) {
Andrewa8d7df32020-03-15 20:10:01 -07002515 string dlc_id = "dlc0";
Andrew065d78d2020-04-07 15:43:07 -07002516 FakePrefs fake_prefs;
Amin Hassani538bd592020-11-04 20:46:08 -08002517 FakeSystemState::Get()->set_prefs(&fake_prefs);
Andrewa8d7df32020-03-15 20:10:01 -07002518 attempter_.SetDlcActiveValue(true, dlc_id);
Andrewa8d7df32020-03-15 20:10:01 -07002519 int64_t temp_int;
Andrew065d78d2020-04-07 15:43:07 -07002520 auto active_key =
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002521 PrefsInterface::CreateSubKey({kDlcPrefsSubDir, dlc_id, kPrefsPingActive});
Amin Hassani538bd592020-11-04 20:46:08 -08002522 EXPECT_TRUE(FakeSystemState::Get()->prefs()->Exists(active_key));
2523 EXPECT_TRUE(FakeSystemState::Get()->prefs()->GetInt64(active_key, &temp_int));
Andrewa8d7df32020-03-15 20:10:01 -07002524 EXPECT_EQ(temp_int, kPingActiveValue);
2525}
2526
2527TEST_F(UpdateAttempterTest, SetDlcInactive) {
Andrewa8d7df32020-03-15 20:10:01 -07002528 string dlc_id = "dlc0";
Andrew065d78d2020-04-07 15:43:07 -07002529 MemoryPrefs fake_prefs;
Amin Hassani538bd592020-11-04 20:46:08 -08002530 FakeSystemState::Get()->set_prefs(&fake_prefs);
Andrew065d78d2020-04-07 15:43:07 -07002531 auto sub_keys = {
2532 kPrefsPingActive, kPrefsPingLastActive, kPrefsPingLastRollcall};
2533 for (auto& sub_key : sub_keys) {
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002534 auto key = PrefsInterface::CreateSubKey({kDlcPrefsSubDir, dlc_id, sub_key});
Amin Hassani538bd592020-11-04 20:46:08 -08002535 FakeSystemState::Get()->prefs()->SetInt64(key, 1);
2536 EXPECT_TRUE(FakeSystemState::Get()->prefs()->Exists(key));
Andrew065d78d2020-04-07 15:43:07 -07002537 }
Andrewa8d7df32020-03-15 20:10:01 -07002538 attempter_.SetDlcActiveValue(false, dlc_id);
Andrew065d78d2020-04-07 15:43:07 -07002539 for (auto& sub_key : sub_keys) {
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002540 auto key = PrefsInterface::CreateSubKey({kDlcPrefsSubDir, dlc_id, sub_key});
Amin Hassani538bd592020-11-04 20:46:08 -08002541 EXPECT_FALSE(FakeSystemState::Get()->prefs()->Exists(key));
Andrew065d78d2020-04-07 15:43:07 -07002542 }
Andrewa8d7df32020-03-15 20:10:01 -07002543}
2544
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002545TEST_F(UpdateAttempterTest, GetSuccessfulDlcIds) {
2546 auto dlc_1 = "1", dlc_2 = "2", dlc_3 = "3";
2547 attempter_.omaha_request_params_->set_dlc_apps_params(
2548 {{dlc_1, {.name = dlc_1, .updated = false}},
2549 {dlc_2, {.name = dlc_2}},
2550 {dlc_3, {.name = dlc_3, .updated = false}}});
2551 EXPECT_THAT(attempter_.GetSuccessfulDlcIds(), ElementsAre(dlc_2));
2552}
2553
Darin Petkovf42cc1c2010-09-01 09:03:02 -07002554} // namespace chromeos_update_engine