blob: 767bb824cea5418dce8935ddd3e90dd9511802cd [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
Alex Deymo2c0db7b2014-11-04 12:23:39 -080017#include "update_engine/update_attempter.h"
18
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"
46#include "update_engine/common/platform_constants.h"
47#include "update_engine/common/prefs.h"
48#include "update_engine/common/test_utils.h"
49#include "update_engine/common/utils.h"
Gilad Arnold5bb4c902014-04-10 12:32:13 -070050#include "update_engine/fake_system_state.h"
Jae Hoon Kim0ae8fe12019-06-26 14:32:50 -070051#include "update_engine/libcurl_http_fetcher.h"
David Zeuthen8f191b22013-08-06 12:27:50 -070052#include "update_engine/mock_p2p_manager.h"
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080053#include "update_engine/mock_payload_state.h"
Aaron Wood9321f502017-09-07 11:18:54 -070054#include "update_engine/mock_service_observer.h"
Jae Hoon Kim051627a2019-09-03 12:56:32 -070055#include "update_engine/omaha_utils.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:
Jeffrey Kardatzkecf5f1f12017-10-02 16:08:44 -0700172 explicit UpdateAttempterUnderTest(SystemState* system_state)
173 : UpdateAttempter(system_state, nullptr) {}
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700174
Amin Hassanie8153632020-10-27 15:11:28 -0700175 void Update(const UpdateCheckParams& params) override {
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700176 update_called_ = true;
177 if (do_update_) {
Amin Hassanie8153632020-10-27 15:11:28 -0700178 UpdateAttempter::Update(params);
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700179 return;
180 }
181 LOG(INFO) << "[TEST] Update() disabled.";
182 status_ = UpdateStatus::CHECKING_FOR_UPDATE;
183 }
184
185 void DisableUpdate() { do_update_ = false; }
186
187 bool WasUpdateCalled() const { return update_called_; }
188
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700189 // Wrap the update scheduling method, allowing us to opt out of scheduled
190 // updates for testing purposes.
Xiaochu Liu88d90382018-08-29 16:09:11 -0700191 bool ScheduleUpdates() override {
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700192 schedule_updates_called_ = true;
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700193 if (do_schedule_updates_)
194 return UpdateAttempter::ScheduleUpdates();
195 LOG(INFO) << "[TEST] Update scheduling disabled.";
196 waiting_for_scheduled_check_ = true;
Xiaochu Liu88d90382018-08-29 16:09:11 -0700197 return true;
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700198 }
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700199
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700200 void DisableScheduleUpdates() { do_schedule_updates_ = false; }
201
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700202 // Indicates whether |ScheduleUpdates()| was called.
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700203 bool WasScheduleUpdatesCalled() const { return schedule_updates_called_; }
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700204
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -0700205 // Need to expose following private members of |UpdateAttempter| for tests.
206 const string& forced_app_version() const { return forced_app_version_; }
Alex Deymo60ca1a72015-06-18 18:19:15 -0700207 const string& forced_omaha_url() const { return forced_omaha_url_; }
David Pursell02c18642014-11-06 11:26:11 -0800208
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700209 // Need to expose |waiting_for_scheduled_check_| for testing.
210 void SetWaitingForScheduledCheck(bool waiting) {
211 waiting_for_scheduled_check_ = waiting;
212 }
213
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700214 private:
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700215 // Used for overrides of |Update()|.
216 bool update_called_ = false;
217 bool do_update_ = true;
218
219 // Used for overrides of |ScheduleUpdates()|.
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700220 bool schedule_updates_called_ = false;
221 bool do_schedule_updates_ = true;
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700222};
223
224class UpdateAttempterTest : public ::testing::Test {
225 protected:
Jay Srinivasan43488792012-06-19 00:25:31 -0700226 UpdateAttempterTest()
Daniel Erate5f6f252017-04-20 12:09:58 -0600227 : certificate_checker_(fake_system_state_.mock_prefs(),
Alex Deymo33e91e72015-12-01 18:26:08 -0300228 &openssl_wrapper_) {
Gilad Arnold1f847232014-04-07 12:07:49 -0700229 // Override system state members.
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700230 fake_system_state_.set_connection_manager(&mock_connection_manager);
231 fake_system_state_.set_update_attempter(&attempter_);
Xiaochu Liu8ba486f2018-11-06 11:14:10 -0800232 fake_system_state_.set_dlcservice(&mock_dlcservice_);
Jae Hoon Kim504c3cb2019-07-02 11:17:24 -0700233 fake_system_state_.set_update_manager(&mock_update_manager_);
Alex Deymo60ca1a72015-06-18 18:19:15 -0700234 loop_.SetAsCurrent();
Gilad Arnold1f847232014-04-07 12:07:49 -0700235
Alex Deymo33e91e72015-12-01 18:26:08 -0300236 certificate_checker_.Init();
237
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();
Jay Srinivasan43488792012-06-19 00:25:31 -0700242 }
Gilad Arnoldeff87cc2013-07-22 18:32:09 -0700243
Alex Deymo610277e2014-11-11 21:18:11 -0800244 void SetUp() override {
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700245 EXPECT_NE(nullptr, attempter_.system_state_);
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700246 EXPECT_NE(nullptr, attempter_.system_state_->update_manager());
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700247 EXPECT_EQ(0, attempter_.http_response_code_);
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700248 EXPECT_EQ(UpdateStatus::IDLE, attempter_.status_);
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700249 EXPECT_EQ(0.0, attempter_.download_progress_);
250 EXPECT_EQ(0, attempter_.last_checked_time_);
251 EXPECT_EQ("0.0.0.0", attempter_.new_version_);
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700252 EXPECT_EQ(0ULL, attempter_.new_payload_size_);
Alex Deymo8427b4a2014-11-05 14:00:32 -0800253 processor_ = new NiceMock<MockActionProcessor>();
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700254 attempter_.processor_.reset(processor_); // Transfers ownership.
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700255 prefs_ = fake_system_state_.mock_prefs();
Gilad Arnold74b5f552014-10-07 08:17:16 -0700256
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700257 // Setup store/load semantics of P2P properties via the mock |PayloadState|.
Gilad Arnold74b5f552014-10-07 08:17:16 -0700258 actual_using_p2p_for_downloading_ = false;
259 EXPECT_CALL(*fake_system_state_.mock_payload_state(),
260 SetUsingP2PForDownloading(_))
261 .WillRepeatedly(SaveArg<0>(&actual_using_p2p_for_downloading_));
262 EXPECT_CALL(*fake_system_state_.mock_payload_state(),
263 GetUsingP2PForDownloading())
264 .WillRepeatedly(ReturnPointee(&actual_using_p2p_for_downloading_));
265 actual_using_p2p_for_sharing_ = false;
266 EXPECT_CALL(*fake_system_state_.mock_payload_state(),
267 SetUsingP2PForSharing(_))
268 .WillRepeatedly(SaveArg<0>(&actual_using_p2p_for_sharing_));
269 EXPECT_CALL(*fake_system_state_.mock_payload_state(),
270 GetUsingP2PForDownloading())
271 .WillRepeatedly(ReturnPointee(&actual_using_p2p_for_sharing_));
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700272 }
273
Alex Deymo60ca1a72015-06-18 18:19:15 -0700274 public:
275 void ScheduleQuitMainLoop();
Patrick Dubroy7fbbe8a2011-08-01 17:28:22 +0200276
Alex Deymo60ca1a72015-06-18 18:19:15 -0700277 // Callbacks to run the different tests from the main loop.
Darin Petkove6ef2f82011-03-07 17:31:11 -0800278 void UpdateTestStart();
279 void UpdateTestVerify();
Alex Deymo60ca1a72015-06-18 18:19:15 -0700280 void RollbackTestStart(bool enterprise_rollback, bool valid_slot);
Chris Sosa76a29ae2013-07-11 17:59:24 -0700281 void RollbackTestVerify();
Thieu Le116fda32011-04-19 11:01:54 -0700282 void PingOmahaTestStart();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700283 void ReadScatterFactorFromPolicyTestStart();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700284 void DecrementUpdateCheckCountTestStart();
Jay Srinivasan08fce042012-06-07 16:31:01 -0700285 void NoScatteringDoneDuringManualUpdateTestStart();
David Zeuthen8f191b22013-08-06 12:27:50 -0700286 void P2PNotEnabledStart();
David Zeuthen8f191b22013-08-06 12:27:50 -0700287 void P2PEnabledStart();
David Zeuthen8f191b22013-08-06 12:27:50 -0700288 void P2PEnabledInteractiveStart();
David Zeuthen8f191b22013-08-06 12:27:50 -0700289 void P2PEnabledStartingFailsStart();
David Zeuthen8f191b22013-08-06 12:27:50 -0700290 void P2PEnabledHousekeepingFailsStart();
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700291 void SessionIdTestChange();
292 void SessionIdTestEnforceEmptyStrPingOmaha();
293 void SessionIdTestConsistencyInUpdateFlow();
Jae Hoon Kim0ae8fe12019-06-26 14:32:50 -0700294 void SessionIdTestInDownloadAction();
Amr Aboelkher21ac9962019-05-15 14:50:05 +0200295 void UpdateToQuickFixBuildStart(bool set_token);
Marton Hunyadye58bddb2018-04-10 20:27:26 +0200296 void ResetRollbackHappenedStart(bool is_consumer,
297 bool is_policy_available,
298 bool expected_reset);
Adolfo Victoria497044c2018-07-18 07:51:42 -0700299 // Staging related callbacks.
300 void SetUpStagingTest(const StagingSchedule& schedule, FakePrefs* prefs);
301 void CheckStagingOff();
302 void StagingSetsPrefsAndTurnsOffScatteringStart();
303 void StagingOffIfInteractiveStart();
304 void StagingOffIfOobeStart();
David Zeuthen8f191b22013-08-06 12:27:50 -0700305
Gilad Arnold74b5f552014-10-07 08:17:16 -0700306 bool actual_using_p2p_for_downloading() {
307 return actual_using_p2p_for_downloading_;
308 }
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800309 bool actual_using_p2p_for_sharing() { return actual_using_p2p_for_sharing_; }
Gilad Arnold74b5f552014-10-07 08:17:16 -0700310
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -0700311 // |CheckForUpdate()| related member functions.
312 void TestCheckForUpdate();
313
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700314 // |OnUpdateScheduled()| related member functions.
315 void TestOnUpdateScheduled();
316
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -0700317 // |ProcessingDone()| related member functions.
318 void TestProcessingDone();
319
Qijiang Fanb0b6cc22020-10-15 21:54:11 +0900320 base::SingleThreadTaskExecutor base_loop_{base::MessagePumpType::IO};
321 brillo::BaseMessageLoop loop_{base_loop_.task_runner()};
Alex Deymo60ca1a72015-06-18 18:19:15 -0700322
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700323 FakeSystemState fake_system_state_;
Jeffrey Kardatzkecf5f1f12017-10-02 16:08:44 -0700324 UpdateAttempterUnderTest attempter_{&fake_system_state_};
Alex Deymo33e91e72015-12-01 18:26:08 -0300325 OpenSSLWrapper openssl_wrapper_;
326 CertificateChecker certificate_checker_;
Xiaochu Liu8ba486f2018-11-06 11:14:10 -0800327 MockDlcService mock_dlcservice_;
Jae Hoon Kim504c3cb2019-07-02 11:17:24 -0700328 MockUpdateManager mock_update_manager_;
Alex Deymo30534502015-07-20 15:06:33 -0700329
Alex Deymo8427b4a2014-11-05 14:00:32 -0800330 NiceMock<MockActionProcessor>* processor_;
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700331 NiceMock<MockPrefs>*
332 prefs_; // Shortcut to |fake_system_state_->mock_prefs()|.
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800333 NiceMock<MockConnectionManager> mock_connection_manager;
Gilad Arnoldeff87cc2013-07-22 18:32:09 -0700334
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -0700335 // |CheckForUpdate()| test params.
336 CheckForUpdateTestParams cfu_params_;
337
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700338 // |OnUpdateScheduled()| test params.
339 OnUpdateScheduledTestParams ous_params_;
340
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -0700341 // |ProcessingDone()| test params.
342 ProcessingDoneTestParams pd_params_;
343
Gilad Arnold74b5f552014-10-07 08:17:16 -0700344 bool actual_using_p2p_for_downloading_;
345 bool actual_using_p2p_for_sharing_;
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700346};
347
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -0700348void UpdateAttempterTest::TestCheckForUpdate() {
349 // Setup
350 attempter_.status_ = cfu_params_.status;
351 fake_system_state_.fake_hardware()->SetIsOfficialBuild(
352 cfu_params_.is_official_build);
353 fake_system_state_.fake_hardware()->SetAreDevFeaturesEnabled(
354 cfu_params_.are_dev_features_enabled);
355
356 // Invocation
357 EXPECT_EQ(
358 cfu_params_.expected_result,
359 attempter_.CheckForUpdate(
360 cfu_params_.app_version, cfu_params_.omaha_url, cfu_params_.flags));
361
362 // Verify
363 EXPECT_EQ(cfu_params_.expected_forced_app_version,
364 attempter_.forced_app_version());
365 EXPECT_EQ(cfu_params_.expected_forced_omaha_url,
366 attempter_.forced_omaha_url());
Jae Hoon Kim2b73ac22019-07-02 11:17:24 -0700367 EXPECT_EQ(cfu_params_.should_schedule_updates_be_called,
368 attempter_.WasScheduleUpdatesCalled());
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -0700369}
370
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -0700371void UpdateAttempterTest::TestProcessingDone() {
372 // Setup
373 attempter_.DisableScheduleUpdates();
374 attempter_.is_install_ = pd_params_.is_install;
375 attempter_.status_ = pd_params_.status;
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -0700376 attempter_.omaha_request_params_->set_dlc_apps_params(
377 pd_params_.dlc_apps_params);
378
379 // Expects
380 if (pd_params_.should_install_completed_be_called)
381 EXPECT_CALL(mock_dlcservice_,
382 InstallCompleted(pd_params_.args_to_install_completed))
383 .WillOnce(Return(true));
384 else
385 EXPECT_CALL(mock_dlcservice_, InstallCompleted(_)).Times(0);
386 if (pd_params_.should_update_completed_be_called)
387 EXPECT_CALL(mock_dlcservice_,
388 UpdateCompleted(pd_params_.args_to_update_completed))
389 .WillOnce(Return(true));
390 else
391 EXPECT_CALL(mock_dlcservice_, UpdateCompleted(_)).Times(0);
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -0700392
393 // Invocation
394 attempter_.ProcessingDone(pd_params_.processor, pd_params_.code);
395
396 // Verify
397 EXPECT_EQ(pd_params_.kExpectedIsInstall, attempter_.is_install_);
398 EXPECT_EQ(pd_params_.should_schedule_updates_be_called,
399 attempter_.WasScheduleUpdatesCalled());
400 EXPECT_EQ(pd_params_.expected_exit_status, attempter_.status_);
401}
402
Alex Deymo60ca1a72015-06-18 18:19:15 -0700403void UpdateAttempterTest::ScheduleQuitMainLoop() {
Luis Hector Chavezf1cf3482016-07-19 14:29:19 -0700404 loop_.PostTask(
405 FROM_HERE,
406 base::Bind([](brillo::BaseMessageLoop* loop) { loop->BreakLoop(); },
407 base::Unretained(&loop_)));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700408}
409
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700410void UpdateAttempterTest::SessionIdTestChange() {
411 EXPECT_NE(UpdateStatus::UPDATED_NEED_REBOOT, attempter_.status());
412 const auto old_session_id = attempter_.session_id_;
Amin Hassanie8153632020-10-27 15:11:28 -0700413 attempter_.Update({});
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700414 EXPECT_NE(old_session_id, attempter_.session_id_);
415 ScheduleQuitMainLoop();
416}
417
418TEST_F(UpdateAttempterTest, SessionIdTestChange) {
419 loop_.PostTask(FROM_HERE,
420 base::Bind(&UpdateAttempterTest::SessionIdTestChange,
421 base::Unretained(this)));
422 loop_.Run();
423}
424
425void UpdateAttempterTest::SessionIdTestEnforceEmptyStrPingOmaha() {
426 // The |session_id_| should not be changed and should remain as an empty
427 // string when |status_| is |UPDATED_NEED_REBOOT| (only for consistency)
428 // and |PingOmaha()| is called.
429 attempter_.DisableScheduleUpdates();
430 attempter_.status_ = UpdateStatus::UPDATED_NEED_REBOOT;
431 const auto old_session_id = attempter_.session_id_;
432 auto CheckIfEmptySessionId = [](AbstractAction* aa) {
433 if (aa->Type() == OmahaRequestAction::StaticType()) {
434 EXPECT_TRUE(static_cast<OmahaRequestAction*>(aa)->session_id_.empty());
435 }
436 };
437 EXPECT_CALL(*processor_, EnqueueAction(Pointee(_)))
438 .WillRepeatedly(Invoke(CheckIfEmptySessionId));
439 EXPECT_CALL(*processor_, StartProcessing());
440 attempter_.PingOmaha();
441 EXPECT_EQ(old_session_id, attempter_.session_id_);
442 EXPECT_EQ(UpdateStatus::UPDATED_NEED_REBOOT, attempter_.status_);
443 ScheduleQuitMainLoop();
444}
445
446TEST_F(UpdateAttempterTest, SessionIdTestEnforceEmptyStrPingOmaha) {
447 loop_.PostTask(
448 FROM_HERE,
449 base::Bind(&UpdateAttempterTest::SessionIdTestEnforceEmptyStrPingOmaha,
450 base::Unretained(this)));
451 loop_.Run();
452}
453
454void UpdateAttempterTest::SessionIdTestConsistencyInUpdateFlow() {
455 // All session IDs passed into |OmahaRequestActions| should be enforced to
456 // have the same value in |BuildUpdateActions()|.
457 unordered_set<string> session_ids;
458 // Gather all the session IDs being passed to |OmahaRequestActions|.
459 auto CheckSessionId = [&session_ids](AbstractAction* aa) {
460 if (aa->Type() == OmahaRequestAction::StaticType())
461 session_ids.insert(static_cast<OmahaRequestAction*>(aa)->session_id_);
462 };
463 EXPECT_CALL(*processor_, EnqueueAction(Pointee(_)))
464 .WillRepeatedly(Invoke(CheckSessionId));
465 attempter_.BuildUpdateActions(false);
466 // Validate that all the session IDs are the same.
467 EXPECT_EQ(1, session_ids.size());
468 ScheduleQuitMainLoop();
469}
470
471TEST_F(UpdateAttempterTest, SessionIdTestConsistencyInUpdateFlow) {
472 loop_.PostTask(
473 FROM_HERE,
474 base::Bind(&UpdateAttempterTest::SessionIdTestConsistencyInUpdateFlow,
475 base::Unretained(this)));
476 loop_.Run();
477}
478
Jae Hoon Kim0ae8fe12019-06-26 14:32:50 -0700479void UpdateAttempterTest::SessionIdTestInDownloadAction() {
480 // The session ID passed into |DownloadAction|'s |LibcurlHttpFetcher| should
481 // be enforced to be included in the HTTP header as X-Goog-Update-SessionId.
482 string header_value;
483 auto CheckSessionIdInDownloadAction = [&header_value](AbstractAction* aa) {
484 if (aa->Type() == DownloadAction::StaticType()) {
485 DownloadAction* da = static_cast<DownloadAction*>(aa);
486 EXPECT_TRUE(da->http_fetcher()->GetHeader(kXGoogleUpdateSessionId,
487 &header_value));
488 }
489 };
490 EXPECT_CALL(*processor_, EnqueueAction(Pointee(_)))
491 .WillRepeatedly(Invoke(CheckSessionIdInDownloadAction));
492 attempter_.BuildUpdateActions(false);
493 // Validate that X-Goog-Update_SessionId is set correctly in HTTP Header.
494 EXPECT_EQ(attempter_.session_id_, header_value);
495 ScheduleQuitMainLoop();
496}
497
498TEST_F(UpdateAttempterTest, SessionIdTestInDownloadAction) {
499 loop_.PostTask(FROM_HERE,
500 base::Bind(&UpdateAttempterTest::SessionIdTestInDownloadAction,
501 base::Unretained(this)));
502 loop_.Run();
503}
504
Darin Petkov1b003102010-11-30 10:18:36 -0800505TEST_F(UpdateAttempterTest, ActionCompletedDownloadTest) {
Ben Chan02f7c1d2014-10-18 15:18:02 -0700506 unique_ptr<MockHttpFetcher> fetcher(new MockHttpFetcher("", 0, nullptr));
Darin Petkov1b003102010-11-30 10:18:36 -0800507 fetcher->FailTransfer(503); // Sets the HTTP response code.
Amin Hassani7ecda262017-07-11 17:10:50 -0700508 DownloadAction action(prefs_,
509 nullptr,
510 nullptr,
511 nullptr,
512 fetcher.release(),
Amin Hassanied37d682018-04-06 13:22:00 -0700513 false /* interactive */);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800514 EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _)).Times(0);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700515 attempter_.ActionCompleted(nullptr, &action, ErrorCode::kSuccess);
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700516 EXPECT_EQ(UpdateStatus::FINALIZING, attempter_.status());
Aaron Wood9321f502017-09-07 11:18:54 -0700517 EXPECT_EQ(0.0, attempter_.download_progress_);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700518 ASSERT_EQ(nullptr, attempter_.error_event_.get());
Darin Petkov1b003102010-11-30 10:18:36 -0800519}
520
521TEST_F(UpdateAttempterTest, ActionCompletedErrorTest) {
Alex Deymo8427b4a2014-11-05 14:00:32 -0800522 MockAction action;
523 EXPECT_CALL(action, Type()).WillRepeatedly(Return("MockAction"));
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700524 attempter_.status_ = UpdateStatus::DOWNLOADING;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800525 EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _))
Darin Petkov1b003102010-11-30 10:18:36 -0800526 .WillOnce(Return(false));
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700527 attempter_.ActionCompleted(nullptr, &action, ErrorCode::kError);
528 ASSERT_NE(nullptr, attempter_.error_event_.get());
Darin Petkov1b003102010-11-30 10:18:36 -0800529}
530
Aaron Wood9321f502017-09-07 11:18:54 -0700531TEST_F(UpdateAttempterTest, DownloadProgressAccumulationTest) {
532 // Simple test case, where all the values match (nothing was skipped)
533 uint64_t bytes_progressed_1 = 1024 * 1024; // 1MB
534 uint64_t bytes_progressed_2 = 1024 * 1024; // 1MB
535 uint64_t bytes_received_1 = bytes_progressed_1;
536 uint64_t bytes_received_2 = bytes_received_1 + bytes_progressed_2;
537 uint64_t bytes_total = 20 * 1024 * 1024; // 20MB
538
539 double progress_1 =
540 static_cast<double>(bytes_received_1) / static_cast<double>(bytes_total);
541 double progress_2 =
542 static_cast<double>(bytes_received_2) / static_cast<double>(bytes_total);
543
544 EXPECT_EQ(0.0, attempter_.download_progress_);
545 // This is set via inspecting the InstallPlan payloads when the
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700546 // |OmahaResponseAction| is completed.
Aaron Wood9321f502017-09-07 11:18:54 -0700547 attempter_.new_payload_size_ = bytes_total;
548 NiceMock<MockServiceObserver> observer;
549 EXPECT_CALL(observer,
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700550 SendStatusUpdate(AllOf(
551 Field(&UpdateEngineStatus::progress, progress_1),
552 Field(&UpdateEngineStatus::status, UpdateStatus::DOWNLOADING),
553 Field(&UpdateEngineStatus::new_size_bytes, bytes_total))));
Aaron Wood9321f502017-09-07 11:18:54 -0700554 EXPECT_CALL(observer,
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700555 SendStatusUpdate(AllOf(
556 Field(&UpdateEngineStatus::progress, progress_2),
557 Field(&UpdateEngineStatus::status, UpdateStatus::DOWNLOADING),
558 Field(&UpdateEngineStatus::new_size_bytes, bytes_total))));
Aaron Wood9321f502017-09-07 11:18:54 -0700559 attempter_.AddObserver(&observer);
560 attempter_.BytesReceived(bytes_progressed_1, bytes_received_1, bytes_total);
561 EXPECT_EQ(progress_1, attempter_.download_progress_);
562 // This iteration validates that a later set of updates to the variables are
563 // properly handled (so that |getStatus()| will return the same progress info
564 // as the callback is receiving.
565 attempter_.BytesReceived(bytes_progressed_2, bytes_received_2, bytes_total);
566 EXPECT_EQ(progress_2, attempter_.download_progress_);
567}
568
569TEST_F(UpdateAttempterTest, ChangeToDownloadingOnReceivedBytesTest) {
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700570 // The transition into |UpdateStatus::DOWNLOADING| happens when the
Aaron Wood9321f502017-09-07 11:18:54 -0700571 // first bytes are received.
572 uint64_t bytes_progressed = 1024 * 1024; // 1MB
573 uint64_t bytes_received = 2 * 1024 * 1024; // 2MB
574 uint64_t bytes_total = 20 * 1024 * 1024; // 300MB
575 attempter_.status_ = UpdateStatus::CHECKING_FOR_UPDATE;
576 // This is set via inspecting the InstallPlan payloads when the
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700577 // |OmahaResponseAction| is completed.
Aaron Wood9321f502017-09-07 11:18:54 -0700578 attempter_.new_payload_size_ = bytes_total;
579 EXPECT_EQ(0.0, attempter_.download_progress_);
580 NiceMock<MockServiceObserver> observer;
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700581 EXPECT_CALL(observer,
582 SendStatusUpdate(AllOf(
583 Field(&UpdateEngineStatus::status, UpdateStatus::DOWNLOADING),
584 Field(&UpdateEngineStatus::new_size_bytes, bytes_total))));
Aaron Wood9321f502017-09-07 11:18:54 -0700585 attempter_.AddObserver(&observer);
586 attempter_.BytesReceived(bytes_progressed, bytes_received, bytes_total);
587 EXPECT_EQ(UpdateStatus::DOWNLOADING, attempter_.status_);
588}
589
590TEST_F(UpdateAttempterTest, BroadcastCompleteDownloadTest) {
591 // There is a special case to ensure that at 100% downloaded,
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700592 // |download_progress_| is updated and broadcastest.
Aaron Wood9321f502017-09-07 11:18:54 -0700593 uint64_t bytes_progressed = 0; // ignored
594 uint64_t bytes_received = 5 * 1024 * 1024; // ignored
595 uint64_t bytes_total = 5 * 1024 * 1024; // 300MB
596 attempter_.status_ = UpdateStatus::DOWNLOADING;
597 attempter_.new_payload_size_ = bytes_total;
598 EXPECT_EQ(0.0, attempter_.download_progress_);
599 NiceMock<MockServiceObserver> observer;
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700600 EXPECT_CALL(observer,
601 SendStatusUpdate(AllOf(
602 Field(&UpdateEngineStatus::progress, 1.0),
603 Field(&UpdateEngineStatus::status, UpdateStatus::DOWNLOADING),
604 Field(&UpdateEngineStatus::new_size_bytes, bytes_total))));
Aaron Wood9321f502017-09-07 11:18:54 -0700605 attempter_.AddObserver(&observer);
606 attempter_.BytesReceived(bytes_progressed, bytes_received, bytes_total);
607 EXPECT_EQ(1.0, attempter_.download_progress_);
608}
609
Darin Petkov1b003102010-11-30 10:18:36 -0800610TEST_F(UpdateAttempterTest, ActionCompletedOmahaRequestTest) {
Ben Chan02f7c1d2014-10-18 15:18:02 -0700611 unique_ptr<MockHttpFetcher> fetcher(new MockHttpFetcher("", 0, nullptr));
Darin Petkov1b003102010-11-30 10:18:36 -0800612 fetcher->FailTransfer(500); // Sets the HTTP response code.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800613 OmahaRequestAction action(
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700614 &fake_system_state_, nullptr, std::move(fetcher), false, "");
Darin Petkov1b003102010-11-30 10:18:36 -0800615 ObjectCollectorAction<OmahaResponse> collector_action;
616 BondActions(&action, &collector_action);
617 OmahaResponse response;
618 response.poll_interval = 234;
619 action.SetOutputObject(response);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800620 EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _)).Times(0);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700621 attempter_.ActionCompleted(nullptr, &action, ErrorCode::kSuccess);
Darin Petkov1b003102010-11-30 10:18:36 -0800622 EXPECT_EQ(500, attempter_.http_response_code());
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700623 EXPECT_EQ(UpdateStatus::IDLE, attempter_.status());
Alex Deymo80f70ff2016-02-10 16:08:11 -0800624 EXPECT_EQ(234U, attempter_.server_dictated_poll_interval_);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700625 ASSERT_TRUE(attempter_.error_event_.get() == nullptr);
Darin Petkov1b003102010-11-30 10:18:36 -0800626}
627
Alex Deymo30534502015-07-20 15:06:33 -0700628TEST_F(UpdateAttempterTest, ConstructWithUpdatedMarkerTest) {
Alex Deymo906191f2015-10-12 12:22:44 -0700629 FakePrefs fake_prefs;
630 string boot_id;
631 EXPECT_TRUE(utils::GetBootId(&boot_id));
632 fake_prefs.SetString(kPrefsUpdateCompletedOnBootId, boot_id);
633 fake_system_state_.set_prefs(&fake_prefs);
Sen Jiangaeeb2e02016-06-09 15:00:16 -0700634 attempter_.Init();
635 EXPECT_EQ(UpdateStatus::UPDATED_NEED_REBOOT, attempter_.status());
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700636}
637
638TEST_F(UpdateAttempterTest, GetErrorCodeForActionTest) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700639 EXPECT_EQ(ErrorCode::kSuccess,
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700640 GetErrorCodeForAction(nullptr, ErrorCode::kSuccess));
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700641
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700642 FakeSystemState fake_system_state;
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800643 OmahaRequestAction omaha_request_action(
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700644 &fake_system_state, nullptr, nullptr, false, "");
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700645 EXPECT_EQ(ErrorCode::kOmahaRequestError,
646 GetErrorCodeForAction(&omaha_request_action, ErrorCode::kError));
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700647 OmahaResponseHandlerAction omaha_response_handler_action(&fake_system_state_);
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800648 EXPECT_EQ(
649 ErrorCode::kOmahaResponseHandlerError,
650 GetErrorCodeForAction(&omaha_response_handler_action, ErrorCode::kError));
Tianjie24f96092020-06-30 12:26:25 -0700651 DynamicPartitionControlStub dynamic_control_stub;
652 FilesystemVerifierAction filesystem_verifier_action(&dynamic_control_stub);
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800653 EXPECT_EQ(
654 ErrorCode::kFilesystemVerifierError,
655 GetErrorCodeForAction(&filesystem_verifier_action, ErrorCode::kError));
Alex Deymob15a0b82015-11-25 20:30:40 -0300656 PostinstallRunnerAction postinstall_runner_action(
Alex Deymofb905d92016-06-03 19:26:58 -0700657 fake_system_state.fake_boot_control(), fake_system_state.fake_hardware());
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800658 EXPECT_EQ(
659 ErrorCode::kPostinstallRunnerError,
660 GetErrorCodeForAction(&postinstall_runner_action, ErrorCode::kError));
Alex Deymo8427b4a2014-11-05 14:00:32 -0800661 MockAction action_mock;
662 EXPECT_CALL(action_mock, Type()).WillOnce(Return("MockAction"));
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700663 EXPECT_EQ(ErrorCode::kError,
664 GetErrorCodeForAction(&action_mock, ErrorCode::kError));
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700665}
666
Darin Petkov36275772010-10-01 11:40:57 -0700667TEST_F(UpdateAttempterTest, DisableDeltaUpdateIfNeededTest) {
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700668 attempter_.omaha_request_params_->set_delta_okay(true);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800669 EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _))
Darin Petkov36275772010-10-01 11:40:57 -0700670 .WillOnce(Return(false));
671 attempter_.DisableDeltaUpdateIfNeeded();
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700672 EXPECT_TRUE(attempter_.omaha_request_params_->delta_okay());
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800673 EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _))
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800674 .WillOnce(
675 DoAll(SetArgPointee<1>(UpdateAttempter::kMaxDeltaUpdateFailures - 1),
676 Return(true)));
Darin Petkov36275772010-10-01 11:40:57 -0700677 attempter_.DisableDeltaUpdateIfNeeded();
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700678 EXPECT_TRUE(attempter_.omaha_request_params_->delta_okay());
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800679 EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _))
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800680 .WillOnce(
681 DoAll(SetArgPointee<1>(UpdateAttempter::kMaxDeltaUpdateFailures),
682 Return(true)));
Darin Petkov36275772010-10-01 11:40:57 -0700683 attempter_.DisableDeltaUpdateIfNeeded();
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700684 EXPECT_FALSE(attempter_.omaha_request_params_->delta_okay());
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800685 EXPECT_CALL(*prefs_, GetInt64(_, _)).Times(0);
Darin Petkov36275772010-10-01 11:40:57 -0700686 attempter_.DisableDeltaUpdateIfNeeded();
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700687 EXPECT_FALSE(attempter_.omaha_request_params_->delta_okay());
Darin Petkov36275772010-10-01 11:40:57 -0700688}
689
690TEST_F(UpdateAttempterTest, MarkDeltaUpdateFailureTest) {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800691 EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _))
Darin Petkov36275772010-10-01 11:40:57 -0700692 .WillOnce(Return(false))
Ben Chan672c1f52017-10-23 15:41:39 -0700693 .WillOnce(DoAll(SetArgPointee<1>(-1), Return(true)))
694 .WillOnce(DoAll(SetArgPointee<1>(1), Return(true)))
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800695 .WillOnce(
696 DoAll(SetArgPointee<1>(UpdateAttempter::kMaxDeltaUpdateFailures),
697 Return(true)));
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800698 EXPECT_CALL(*prefs_, SetInt64(Ne(kPrefsDeltaUpdateFailures), _))
Darin Petkov2dd01092010-10-08 15:43:05 -0700699 .WillRepeatedly(Return(true));
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800700 EXPECT_CALL(*prefs_, SetInt64(kPrefsDeltaUpdateFailures, 1)).Times(2);
Gilad Arnold74b5f552014-10-07 08:17:16 -0700701 EXPECT_CALL(*prefs_, SetInt64(kPrefsDeltaUpdateFailures, 2));
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800702 EXPECT_CALL(*prefs_,
703 SetInt64(kPrefsDeltaUpdateFailures,
704 UpdateAttempter::kMaxDeltaUpdateFailures + 1));
705 for (int i = 0; i < 4; i++)
Darin Petkov36275772010-10-01 11:40:57 -0700706 attempter_.MarkDeltaUpdateFailure();
707}
708
Darin Petkov1b003102010-11-30 10:18:36 -0800709TEST_F(UpdateAttempterTest, ScheduleErrorEventActionNoEventTest) {
710 EXPECT_CALL(*processor_, EnqueueAction(_)).Times(0);
711 EXPECT_CALL(*processor_, StartProcessing()).Times(0);
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700712 EXPECT_CALL(*fake_system_state_.mock_payload_state(), UpdateFailed(_))
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800713 .Times(0);
714 OmahaResponse response;
Jay Srinivasan53173b92013-05-17 17:13:01 -0700715 string url1 = "http://url1";
Sen Jiang0affc2c2017-02-10 15:55:05 -0800716 response.packages.push_back({.payload_urls = {url1, "https://url"}});
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700717 EXPECT_CALL(*(fake_system_state_.mock_payload_state()), GetCurrentUrl())
Jay Srinivasan53173b92013-05-17 17:13:01 -0700718 .WillRepeatedly(Return(url1));
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700719 fake_system_state_.mock_payload_state()->SetResponse(response);
Darin Petkov1b003102010-11-30 10:18:36 -0800720 attempter_.ScheduleErrorEventAction();
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700721 EXPECT_EQ(url1, fake_system_state_.mock_payload_state()->GetCurrentUrl());
Darin Petkov1b003102010-11-30 10:18:36 -0800722}
723
724TEST_F(UpdateAttempterTest, ScheduleErrorEventActionTest) {
725 EXPECT_CALL(*processor_,
Amin Hassanid3f4bea2018-04-30 14:52:40 -0700726 EnqueueAction(Pointee(Property(
727 &AbstractAction::Type, OmahaRequestAction::StaticType()))));
Gilad Arnold74b5f552014-10-07 08:17:16 -0700728 EXPECT_CALL(*processor_, StartProcessing());
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700729 ErrorCode err = ErrorCode::kError;
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700730 EXPECT_CALL(*fake_system_state_.mock_payload_state(), UpdateFailed(err));
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800731 attempter_.error_event_.reset(new OmahaEvent(
732 OmahaEvent::kTypeUpdateComplete, OmahaEvent::kResultError, err));
Darin Petkov1b003102010-11-30 10:18:36 -0800733 attempter_.ScheduleErrorEventAction();
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700734 EXPECT_EQ(UpdateStatus::REPORTING_ERROR_EVENT, attempter_.status());
Darin Petkov1b003102010-11-30 10:18:36 -0800735}
736
Darin Petkove6ef2f82011-03-07 17:31:11 -0800737namespace {
Chris Sosa76a29ae2013-07-11 17:59:24 -0700738// Actions that will be built as part of an update check.
Askar Aitzhan570ca872019-04-24 11:16:12 +0200739vector<string> GetUpdateActionTypes() {
740 return {OmahaRequestAction::StaticType(),
741 OmahaResponseHandlerAction::StaticType(),
742 UpdateBootFlagsAction::StaticType(),
743 OmahaRequestAction::StaticType(),
744 DownloadAction::StaticType(),
745 OmahaRequestAction::StaticType(),
746 FilesystemVerifierAction::StaticType(),
747 PostinstallRunnerAction::StaticType(),
748 OmahaRequestAction::StaticType()};
749}
Chris Sosa76a29ae2013-07-11 17:59:24 -0700750
751// Actions that will be built as part of a user-initiated rollback.
Askar Aitzhan570ca872019-04-24 11:16:12 +0200752vector<string> GetRollbackActionTypes() {
753 return {InstallPlanAction::StaticType(),
754 PostinstallRunnerAction::StaticType()};
755}
Chris Sosa76a29ae2013-07-11 17:59:24 -0700756
Adolfo Victoria497044c2018-07-18 07:51:42 -0700757const StagingSchedule kValidStagingSchedule = {
758 {4, 10}, {10, 40}, {19, 70}, {26, 100}};
759
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700760} // namespace
Darin Petkove6ef2f82011-03-07 17:31:11 -0800761
762void UpdateAttempterTest::UpdateTestStart() {
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700763 attempter_.set_http_response_code(200);
Alex Deymo749ecf12014-10-21 20:06:57 -0700764
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700765 // Expect that the device policy is loaded by the |UpdateAttempter| at some
766 // point by calling |RefreshDevicePolicy()|.
Igor9fd76b62017-12-11 15:24:18 +0100767 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Alex Deymo749ecf12014-10-21 20:06:57 -0700768 EXPECT_CALL(*device_policy, LoadPolicy())
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800769 .Times(testing::AtLeast(1))
770 .WillRepeatedly(Return(true));
Igor9fd76b62017-12-11 15:24:18 +0100771 attempter_.policy_provider_.reset(
772 new policy::PolicyProvider(std::move(device_policy)));
Alex Deymo749ecf12014-10-21 20:06:57 -0700773
774 {
775 InSequence s;
Askar Aitzhan570ca872019-04-24 11:16:12 +0200776 for (const auto& update_action_type : GetUpdateActionTypes()) {
Alex Deymo749ecf12014-10-21 20:06:57 -0700777 EXPECT_CALL(*processor_,
Amin Hassanid3f4bea2018-04-30 14:52:40 -0700778 EnqueueAction(Pointee(
Askar Aitzhan570ca872019-04-24 11:16:12 +0200779 Property(&AbstractAction::Type, update_action_type))));
Alex Deymo749ecf12014-10-21 20:06:57 -0700780 }
Gilad Arnold74b5f552014-10-07 08:17:16 -0700781 EXPECT_CALL(*processor_, StartProcessing());
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700782 }
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700783
Amin Hassanie8153632020-10-27 15:11:28 -0700784 attempter_.Update({});
Alex Deymo60ca1a72015-06-18 18:19:15 -0700785 loop_.PostTask(FROM_HERE,
786 base::Bind(&UpdateAttempterTest::UpdateTestVerify,
787 base::Unretained(this)));
Darin Petkove6ef2f82011-03-07 17:31:11 -0800788}
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700789
Darin Petkove6ef2f82011-03-07 17:31:11 -0800790void UpdateAttempterTest::UpdateTestVerify() {
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700791 EXPECT_EQ(0, attempter_.http_response_code());
792 EXPECT_EQ(&attempter_, processor_->delegate());
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700793 EXPECT_EQ(UpdateStatus::CHECKING_FOR_UPDATE, attempter_.status());
Alex Deymo60ca1a72015-06-18 18:19:15 -0700794 loop_.BreakLoop();
Darin Petkove6ef2f82011-03-07 17:31:11 -0800795}
796
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800797void UpdateAttempterTest::RollbackTestStart(bool enterprise_rollback,
798 bool valid_slot) {
Chris Sosa76a29ae2013-07-11 17:59:24 -0700799 // Create a device policy so that we can change settings.
Igor9fd76b62017-12-11 15:24:18 +0100800 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Chris Sosa76a29ae2013-07-11 17:59:24 -0700801 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
Igor9fd76b62017-12-11 15:24:18 +0100802 fake_system_state_.set_device_policy(device_policy.get());
803 if (enterprise_rollback) {
804 // We return an empty owner as this is an enterprise.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800805 EXPECT_CALL(*device_policy, GetOwner(_))
806 .WillRepeatedly(DoAll(SetArgPointee<0>(string("")), Return(true)));
Igor9fd76b62017-12-11 15:24:18 +0100807 } else {
808 // We return a fake owner as this is an owned consumer device.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800809 EXPECT_CALL(*device_policy, GetOwner(_))
810 .WillRepeatedly(DoAll(SetArgPointee<0>(string("fake.mail@fake.com")),
811 Return(true)));
Igor9fd76b62017-12-11 15:24:18 +0100812 }
813
814 attempter_.policy_provider_.reset(
815 new policy::PolicyProvider(std::move(device_policy)));
Chris Sosa76a29ae2013-07-11 17:59:24 -0700816
Alex Deymo763e7db2015-08-27 21:08:08 -0700817 if (valid_slot) {
818 BootControlInterface::Slot rollback_slot = 1;
819 LOG(INFO) << "Test Mark Bootable: "
820 << BootControlInterface::SlotName(rollback_slot);
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700821 fake_system_state_.fake_boot_control()->SetSlotBootable(rollback_slot,
822 true);
Don Garrett6646b442013-11-13 15:29:11 -0800823 }
824
Chris Sosa28e479c2013-07-12 11:39:53 -0700825 bool is_rollback_allowed = false;
Chris Sosa76a29ae2013-07-11 17:59:24 -0700826
Chris Sosad38b1132014-03-25 10:43:59 -0700827 // We only allow rollback on devices that are not enterprise enrolled and
828 // which have a valid slot to rollback to.
829 if (!enterprise_rollback && valid_slot) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800830 is_rollback_allowed = true;
Chris Sosa28e479c2013-07-12 11:39:53 -0700831 }
832
Chris Sosa28e479c2013-07-12 11:39:53 -0700833 if (is_rollback_allowed) {
Chris Sosa76a29ae2013-07-11 17:59:24 -0700834 InSequence s;
Askar Aitzhan570ca872019-04-24 11:16:12 +0200835 for (const auto& rollback_action_type : GetRollbackActionTypes()) {
Chris Sosa76a29ae2013-07-11 17:59:24 -0700836 EXPECT_CALL(*processor_,
Askar Aitzhan570ca872019-04-24 11:16:12 +0200837 EnqueueAction(Pointee(
838 Property(&AbstractAction::Type, rollback_action_type))));
Chris Sosa76a29ae2013-07-11 17:59:24 -0700839 }
Gilad Arnold74b5f552014-10-07 08:17:16 -0700840 EXPECT_CALL(*processor_, StartProcessing());
Chris Sosa76a29ae2013-07-11 17:59:24 -0700841
Chris Sosa44b9b7e2014-04-02 13:53:46 -0700842 EXPECT_TRUE(attempter_.Rollback(true));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700843 loop_.PostTask(FROM_HERE,
844 base::Bind(&UpdateAttempterTest::RollbackTestVerify,
845 base::Unretained(this)));
Chris Sosa76a29ae2013-07-11 17:59:24 -0700846 } else {
Chris Sosa44b9b7e2014-04-02 13:53:46 -0700847 EXPECT_FALSE(attempter_.Rollback(true));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700848 loop_.BreakLoop();
Chris Sosa76a29ae2013-07-11 17:59:24 -0700849 }
850}
851
852void UpdateAttempterTest::RollbackTestVerify() {
853 // Verifies the actions that were enqueued.
854 EXPECT_EQ(&attempter_, processor_->delegate());
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700855 EXPECT_EQ(UpdateStatus::ATTEMPTING_ROLLBACK, attempter_.status());
Amin Hassanid3f4bea2018-04-30 14:52:40 -0700856 EXPECT_EQ(0U, attempter_.install_plan_->partitions.size());
857 EXPECT_EQ(attempter_.install_plan_->powerwash_required, true);
Alex Deymo60ca1a72015-06-18 18:19:15 -0700858 loop_.BreakLoop();
Chris Sosa76a29ae2013-07-11 17:59:24 -0700859}
860
Darin Petkove6ef2f82011-03-07 17:31:11 -0800861TEST_F(UpdateAttempterTest, UpdateTest) {
Alex Deymo461b2592015-07-24 20:10:52 -0700862 UpdateTestStart();
Alex Deymo60ca1a72015-06-18 18:19:15 -0700863 loop_.Run();
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700864}
865
Chris Sosa76a29ae2013-07-11 17:59:24 -0700866TEST_F(UpdateAttempterTest, RollbackTest) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700867 loop_.PostTask(FROM_HERE,
868 base::Bind(&UpdateAttempterTest::RollbackTestStart,
869 base::Unretained(this),
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800870 false,
871 true));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700872 loop_.Run();
Chris Sosa76a29ae2013-07-11 17:59:24 -0700873}
874
Don Garrett6646b442013-11-13 15:29:11 -0800875TEST_F(UpdateAttempterTest, InvalidSlotRollbackTest) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700876 loop_.PostTask(FROM_HERE,
877 base::Bind(&UpdateAttempterTest::RollbackTestStart,
878 base::Unretained(this),
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800879 false,
880 false));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700881 loop_.Run();
Don Garrett6646b442013-11-13 15:29:11 -0800882}
883
Chris Sosa76a29ae2013-07-11 17:59:24 -0700884TEST_F(UpdateAttempterTest, EnterpriseRollbackTest) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700885 loop_.PostTask(FROM_HERE,
886 base::Bind(&UpdateAttempterTest::RollbackTestStart,
887 base::Unretained(this),
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800888 true,
889 true));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700890 loop_.Run();
Chris Sosa76a29ae2013-07-11 17:59:24 -0700891}
892
Thieu Le116fda32011-04-19 11:01:54 -0700893void UpdateAttempterTest::PingOmahaTestStart() {
894 EXPECT_CALL(*processor_,
Amin Hassanid3f4bea2018-04-30 14:52:40 -0700895 EnqueueAction(Pointee(Property(
896 &AbstractAction::Type, OmahaRequestAction::StaticType()))));
Gilad Arnold74b5f552014-10-07 08:17:16 -0700897 EXPECT_CALL(*processor_, StartProcessing());
Thieu Le116fda32011-04-19 11:01:54 -0700898 attempter_.PingOmaha();
Alex Deymo60ca1a72015-06-18 18:19:15 -0700899 ScheduleQuitMainLoop();
Thieu Le116fda32011-04-19 11:01:54 -0700900}
901
902TEST_F(UpdateAttempterTest, PingOmahaTest) {
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700903 EXPECT_FALSE(attempter_.waiting_for_scheduled_check_);
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700904 EXPECT_FALSE(attempter_.WasScheduleUpdatesCalled());
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700905 // Disable scheduling of subsequnet checks; we're using the |DefaultPolicy| in
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700906 // testing, which is more permissive than we want to handle here.
907 attempter_.DisableScheduleUpdates();
Alex Deymo60ca1a72015-06-18 18:19:15 -0700908 loop_.PostTask(FROM_HERE,
909 base::Bind(&UpdateAttempterTest::PingOmahaTestStart,
910 base::Unretained(this)));
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700911 brillo::MessageLoopRunMaxIterations(&loop_, 100);
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700912 EXPECT_EQ(UpdateStatus::UPDATED_NEED_REBOOT, attempter_.status());
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700913 EXPECT_TRUE(attempter_.WasScheduleUpdatesCalled());
Thieu Le116fda32011-04-19 11:01:54 -0700914}
915
Darin Petkov18c7bce2011-06-16 14:07:00 -0700916TEST_F(UpdateAttempterTest, CreatePendingErrorEventTest) {
Alex Deymo8427b4a2014-11-05 14:00:32 -0800917 MockAction action;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700918 const ErrorCode kCode = ErrorCode::kDownloadTransferError;
Darin Petkov18c7bce2011-06-16 14:07:00 -0700919 attempter_.CreatePendingErrorEvent(&action, kCode);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700920 ASSERT_NE(nullptr, attempter_.error_event_.get());
Darin Petkov18c7bce2011-06-16 14:07:00 -0700921 EXPECT_EQ(OmahaEvent::kTypeUpdateComplete, attempter_.error_event_->type);
922 EXPECT_EQ(OmahaEvent::kResultError, attempter_.error_event_->result);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700923 EXPECT_EQ(
924 static_cast<ErrorCode>(static_cast<int>(kCode) |
925 static_cast<int>(ErrorCode::kTestOmahaUrlFlag)),
926 attempter_.error_event_->error_code);
Darin Petkov18c7bce2011-06-16 14:07:00 -0700927}
928
929TEST_F(UpdateAttempterTest, CreatePendingErrorEventResumedTest) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -0700930 attempter_.install_plan_.reset(new InstallPlan);
931 attempter_.install_plan_->is_resume = true;
Alex Deymo8427b4a2014-11-05 14:00:32 -0800932 MockAction action;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700933 const ErrorCode kCode = ErrorCode::kInstallDeviceOpenError;
Darin Petkov18c7bce2011-06-16 14:07:00 -0700934 attempter_.CreatePendingErrorEvent(&action, kCode);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700935 ASSERT_NE(nullptr, attempter_.error_event_.get());
Darin Petkov18c7bce2011-06-16 14:07:00 -0700936 EXPECT_EQ(OmahaEvent::kTypeUpdateComplete, attempter_.error_event_->type);
937 EXPECT_EQ(OmahaEvent::kResultError, attempter_.error_event_->result);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700938 EXPECT_EQ(
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800939 static_cast<ErrorCode>(static_cast<int>(kCode) |
940 static_cast<int>(ErrorCode::kResumedFlag) |
941 static_cast<int>(ErrorCode::kTestOmahaUrlFlag)),
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700942 attempter_.error_event_->error_code);
Darin Petkov18c7bce2011-06-16 14:07:00 -0700943}
944
David Zeuthen8f191b22013-08-06 12:27:50 -0700945TEST_F(UpdateAttempterTest, P2PNotStartedAtStartupWhenNotEnabled) {
946 MockP2PManager mock_p2p_manager;
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700947 fake_system_state_.set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -0700948 mock_p2p_manager.fake().SetP2PEnabled(false);
949 EXPECT_CALL(mock_p2p_manager, EnsureP2PRunning()).Times(0);
950 attempter_.UpdateEngineStarted();
951}
952
953TEST_F(UpdateAttempterTest, P2PNotStartedAtStartupWhenEnabledButNotSharing) {
954 MockP2PManager mock_p2p_manager;
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700955 fake_system_state_.set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -0700956 mock_p2p_manager.fake().SetP2PEnabled(true);
957 EXPECT_CALL(mock_p2p_manager, EnsureP2PRunning()).Times(0);
958 attempter_.UpdateEngineStarted();
959}
960
961TEST_F(UpdateAttempterTest, P2PStartedAtStartupWhenEnabledAndSharing) {
962 MockP2PManager mock_p2p_manager;
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700963 fake_system_state_.set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -0700964 mock_p2p_manager.fake().SetP2PEnabled(true);
965 mock_p2p_manager.fake().SetCountSharedFilesResult(1);
Gilad Arnold74b5f552014-10-07 08:17:16 -0700966 EXPECT_CALL(mock_p2p_manager, EnsureP2PRunning());
David Zeuthen8f191b22013-08-06 12:27:50 -0700967 attempter_.UpdateEngineStarted();
968}
969
970TEST_F(UpdateAttempterTest, P2PNotEnabled) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700971 loop_.PostTask(FROM_HERE,
972 base::Bind(&UpdateAttempterTest::P2PNotEnabledStart,
973 base::Unretained(this)));
974 loop_.Run();
David Zeuthen8f191b22013-08-06 12:27:50 -0700975}
Alex Deymo60ca1a72015-06-18 18:19:15 -0700976
David Zeuthen8f191b22013-08-06 12:27:50 -0700977void UpdateAttempterTest::P2PNotEnabledStart() {
978 // If P2P is not enabled, check that we do not attempt housekeeping
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700979 // and do not convey that P2P is to be used.
David Zeuthen8f191b22013-08-06 12:27:50 -0700980 MockP2PManager mock_p2p_manager;
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700981 fake_system_state_.set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -0700982 mock_p2p_manager.fake().SetP2PEnabled(false);
983 EXPECT_CALL(mock_p2p_manager, PerformHousekeeping()).Times(0);
Amin Hassanie8153632020-10-27 15:11:28 -0700984 attempter_.Update({});
Alex Deymo60ca1a72015-06-18 18:19:15 -0700985 EXPECT_FALSE(actual_using_p2p_for_downloading_);
Gilad Arnold74b5f552014-10-07 08:17:16 -0700986 EXPECT_FALSE(actual_using_p2p_for_sharing());
Alex Deymo60ca1a72015-06-18 18:19:15 -0700987 ScheduleQuitMainLoop();
David Zeuthen8f191b22013-08-06 12:27:50 -0700988}
989
990TEST_F(UpdateAttempterTest, P2PEnabledStartingFails) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700991 loop_.PostTask(FROM_HERE,
992 base::Bind(&UpdateAttempterTest::P2PEnabledStartingFailsStart,
993 base::Unretained(this)));
994 loop_.Run();
David Zeuthen8f191b22013-08-06 12:27:50 -0700995}
Alex Deymo60ca1a72015-06-18 18:19:15 -0700996
David Zeuthen8f191b22013-08-06 12:27:50 -0700997void UpdateAttempterTest::P2PEnabledStartingFailsStart() {
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700998 // If P2P is enabled, but starting it fails ensure we don't do
999 // any housekeeping and do not convey that P2P should be used.
David Zeuthen8f191b22013-08-06 12:27:50 -07001000 MockP2PManager mock_p2p_manager;
Gilad Arnold5bb4c902014-04-10 12:32:13 -07001001 fake_system_state_.set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -07001002 mock_p2p_manager.fake().SetP2PEnabled(true);
1003 mock_p2p_manager.fake().SetEnsureP2PRunningResult(false);
1004 mock_p2p_manager.fake().SetPerformHousekeepingResult(false);
1005 EXPECT_CALL(mock_p2p_manager, PerformHousekeeping()).Times(0);
Amin Hassanie8153632020-10-27 15:11:28 -07001006 attempter_.Update({});
Gilad Arnold74b5f552014-10-07 08:17:16 -07001007 EXPECT_FALSE(actual_using_p2p_for_downloading());
1008 EXPECT_FALSE(actual_using_p2p_for_sharing());
Alex Deymo60ca1a72015-06-18 18:19:15 -07001009 ScheduleQuitMainLoop();
David Zeuthen8f191b22013-08-06 12:27:50 -07001010}
1011
1012TEST_F(UpdateAttempterTest, P2PEnabledHousekeepingFails) {
Alex Deymo60ca1a72015-06-18 18:19:15 -07001013 loop_.PostTask(
1014 FROM_HERE,
1015 base::Bind(&UpdateAttempterTest::P2PEnabledHousekeepingFailsStart,
1016 base::Unretained(this)));
1017 loop_.Run();
David Zeuthen8f191b22013-08-06 12:27:50 -07001018}
Alex Deymo60ca1a72015-06-18 18:19:15 -07001019
David Zeuthen8f191b22013-08-06 12:27:50 -07001020void UpdateAttempterTest::P2PEnabledHousekeepingFailsStart() {
Jae Hoon Kimedb65502019-06-14 11:52:17 -07001021 // If P2P is enabled, starting it works but housekeeping fails, ensure
1022 // we do not convey P2P is to be used.
David Zeuthen8f191b22013-08-06 12:27:50 -07001023 MockP2PManager mock_p2p_manager;
Gilad Arnold5bb4c902014-04-10 12:32:13 -07001024 fake_system_state_.set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -07001025 mock_p2p_manager.fake().SetP2PEnabled(true);
1026 mock_p2p_manager.fake().SetEnsureP2PRunningResult(true);
1027 mock_p2p_manager.fake().SetPerformHousekeepingResult(false);
Gilad Arnold74b5f552014-10-07 08:17:16 -07001028 EXPECT_CALL(mock_p2p_manager, PerformHousekeeping());
Amin Hassanie8153632020-10-27 15:11:28 -07001029 attempter_.Update({});
Gilad Arnold74b5f552014-10-07 08:17:16 -07001030 EXPECT_FALSE(actual_using_p2p_for_downloading());
1031 EXPECT_FALSE(actual_using_p2p_for_sharing());
Alex Deymo60ca1a72015-06-18 18:19:15 -07001032 ScheduleQuitMainLoop();
David Zeuthen8f191b22013-08-06 12:27:50 -07001033}
1034
1035TEST_F(UpdateAttempterTest, P2PEnabled) {
Alex Deymo60ca1a72015-06-18 18:19:15 -07001036 loop_.PostTask(FROM_HERE,
1037 base::Bind(&UpdateAttempterTest::P2PEnabledStart,
1038 base::Unretained(this)));
1039 loop_.Run();
David Zeuthen8f191b22013-08-06 12:27:50 -07001040}
Alex Deymo60ca1a72015-06-18 18:19:15 -07001041
David Zeuthen8f191b22013-08-06 12:27:50 -07001042void UpdateAttempterTest::P2PEnabledStart() {
1043 MockP2PManager mock_p2p_manager;
Gilad Arnold5bb4c902014-04-10 12:32:13 -07001044 fake_system_state_.set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -07001045 // If P2P is enabled and starting it works, check that we performed
Jae Hoon Kimedb65502019-06-14 11:52:17 -07001046 // housekeeping and that we convey P2P should be used.
David Zeuthen8f191b22013-08-06 12:27:50 -07001047 mock_p2p_manager.fake().SetP2PEnabled(true);
1048 mock_p2p_manager.fake().SetEnsureP2PRunningResult(true);
1049 mock_p2p_manager.fake().SetPerformHousekeepingResult(true);
Gilad Arnold74b5f552014-10-07 08:17:16 -07001050 EXPECT_CALL(mock_p2p_manager, PerformHousekeeping());
Amin Hassanie8153632020-10-27 15:11:28 -07001051 attempter_.Update({});
Gilad Arnold74b5f552014-10-07 08:17:16 -07001052 EXPECT_TRUE(actual_using_p2p_for_downloading());
1053 EXPECT_TRUE(actual_using_p2p_for_sharing());
Alex Deymo60ca1a72015-06-18 18:19:15 -07001054 ScheduleQuitMainLoop();
David Zeuthen8f191b22013-08-06 12:27:50 -07001055}
1056
1057TEST_F(UpdateAttempterTest, P2PEnabledInteractive) {
Alex Deymo60ca1a72015-06-18 18:19:15 -07001058 loop_.PostTask(FROM_HERE,
1059 base::Bind(&UpdateAttempterTest::P2PEnabledInteractiveStart,
1060 base::Unretained(this)));
1061 loop_.Run();
David Zeuthen8f191b22013-08-06 12:27:50 -07001062}
Alex Deymo60ca1a72015-06-18 18:19:15 -07001063
David Zeuthen8f191b22013-08-06 12:27:50 -07001064void UpdateAttempterTest::P2PEnabledInteractiveStart() {
1065 MockP2PManager mock_p2p_manager;
Gilad Arnold5bb4c902014-04-10 12:32:13 -07001066 fake_system_state_.set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -07001067 // For an interactive check, if P2P is enabled and starting it
1068 // works, check that we performed housekeeping and that we convey
Jae Hoon Kimedb65502019-06-14 11:52:17 -07001069 // P2P should be used for sharing but NOT for downloading.
David Zeuthen8f191b22013-08-06 12:27:50 -07001070 mock_p2p_manager.fake().SetP2PEnabled(true);
1071 mock_p2p_manager.fake().SetEnsureP2PRunningResult(true);
1072 mock_p2p_manager.fake().SetPerformHousekeepingResult(true);
Gilad Arnold74b5f552014-10-07 08:17:16 -07001073 EXPECT_CALL(mock_p2p_manager, PerformHousekeeping());
Amin Hassanie8153632020-10-27 15:11:28 -07001074 attempter_.Update({.interactive = true});
Gilad Arnold74b5f552014-10-07 08:17:16 -07001075 EXPECT_FALSE(actual_using_p2p_for_downloading());
1076 EXPECT_TRUE(actual_using_p2p_for_sharing());
Alex Deymo60ca1a72015-06-18 18:19:15 -07001077 ScheduleQuitMainLoop();
David Zeuthen8f191b22013-08-06 12:27:50 -07001078}
1079
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001080TEST_F(UpdateAttempterTest, ReadScatterFactorFromPolicy) {
Alex Deymo60ca1a72015-06-18 18:19:15 -07001081 loop_.PostTask(
1082 FROM_HERE,
1083 base::Bind(&UpdateAttempterTest::ReadScatterFactorFromPolicyTestStart,
1084 base::Unretained(this)));
1085 loop_.Run();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001086}
1087
1088// Tests that the scatter_factor_in_seconds value is properly fetched
1089// from the device policy.
1090void UpdateAttempterTest::ReadScatterFactorFromPolicyTestStart() {
Ben Chan9abb7632014-08-07 00:10:53 -07001091 int64_t scatter_factor_in_seconds = 36000;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001092
Igor9fd76b62017-12-11 15:24:18 +01001093 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001094 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
Igor9fd76b62017-12-11 15:24:18 +01001095 fake_system_state_.set_device_policy(device_policy.get());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001096
1097 EXPECT_CALL(*device_policy, GetScatterFactorInSeconds(_))
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001098 .WillRepeatedly(
1099 DoAll(SetArgPointee<0>(scatter_factor_in_seconds), Return(true)));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001100
Igor9fd76b62017-12-11 15:24:18 +01001101 attempter_.policy_provider_.reset(
1102 new policy::PolicyProvider(std::move(device_policy)));
1103
Amin Hassanie8153632020-10-27 15:11:28 -07001104 attempter_.Update({});
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001105 EXPECT_EQ(scatter_factor_in_seconds, attempter_.scatter_factor_.InSeconds());
1106
Alex Deymo60ca1a72015-06-18 18:19:15 -07001107 ScheduleQuitMainLoop();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001108}
1109
1110TEST_F(UpdateAttempterTest, DecrementUpdateCheckCountTest) {
Alex Deymo60ca1a72015-06-18 18:19:15 -07001111 loop_.PostTask(
1112 FROM_HERE,
1113 base::Bind(&UpdateAttempterTest::DecrementUpdateCheckCountTestStart,
1114 base::Unretained(this)));
1115 loop_.Run();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001116}
1117
1118void UpdateAttempterTest::DecrementUpdateCheckCountTestStart() {
1119 // Tests that the scatter_factor_in_seconds value is properly fetched
1120 // from the device policy and is decremented if value > 0.
Ben Chan9abb7632014-08-07 00:10:53 -07001121 int64_t initial_value = 5;
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001122 FakePrefs fake_prefs;
1123 attempter_.prefs_ = &fake_prefs;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001124
Gilad Arnold5bb4c902014-04-10 12:32:13 -07001125 fake_system_state_.fake_hardware()->SetIsOOBEComplete(Time::UnixEpoch());
Jay Srinivasan08fce042012-06-07 16:31:01 -07001126
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001127 EXPECT_TRUE(fake_prefs.SetInt64(kPrefsUpdateCheckCount, initial_value));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001128
Ben Chan9abb7632014-08-07 00:10:53 -07001129 int64_t scatter_factor_in_seconds = 10;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001130
Igor9fd76b62017-12-11 15:24:18 +01001131 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001132 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
Igor9fd76b62017-12-11 15:24:18 +01001133 fake_system_state_.set_device_policy(device_policy.get());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001134
1135 EXPECT_CALL(*device_policy, GetScatterFactorInSeconds(_))
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001136 .WillRepeatedly(
1137 DoAll(SetArgPointee<0>(scatter_factor_in_seconds), Return(true)));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001138
Igor9fd76b62017-12-11 15:24:18 +01001139 attempter_.policy_provider_.reset(
1140 new policy::PolicyProvider(std::move(device_policy)));
1141
Amin Hassanie8153632020-10-27 15:11:28 -07001142 attempter_.Update({});
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001143 EXPECT_EQ(scatter_factor_in_seconds, attempter_.scatter_factor_.InSeconds());
1144
1145 // Make sure the file still exists.
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001146 EXPECT_TRUE(fake_prefs.Exists(kPrefsUpdateCheckCount));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001147
Ben Chan9abb7632014-08-07 00:10:53 -07001148 int64_t new_value;
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001149 EXPECT_TRUE(fake_prefs.GetInt64(kPrefsUpdateCheckCount, &new_value));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001150 EXPECT_EQ(initial_value - 1, new_value);
1151
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001152 EXPECT_TRUE(
1153 attempter_.omaha_request_params_->update_check_count_wait_enabled());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001154
1155 // However, if the count is already 0, it's not decremented. Test that.
1156 initial_value = 0;
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001157 EXPECT_TRUE(fake_prefs.SetInt64(kPrefsUpdateCheckCount, initial_value));
Amin Hassanie8153632020-10-27 15:11:28 -07001158 attempter_.Update({});
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001159 EXPECT_TRUE(fake_prefs.Exists(kPrefsUpdateCheckCount));
1160 EXPECT_TRUE(fake_prefs.GetInt64(kPrefsUpdateCheckCount, &new_value));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001161 EXPECT_EQ(initial_value, new_value);
1162
Alex Deymo60ca1a72015-06-18 18:19:15 -07001163 ScheduleQuitMainLoop();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001164}
1165
Jay Srinivasan08fce042012-06-07 16:31:01 -07001166TEST_F(UpdateAttempterTest, NoScatteringDoneDuringManualUpdateTestStart) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001167 loop_.PostTask(
1168 FROM_HERE,
1169 base::Bind(
1170 &UpdateAttempterTest::NoScatteringDoneDuringManualUpdateTestStart,
1171 base::Unretained(this)));
Alex Deymo60ca1a72015-06-18 18:19:15 -07001172 loop_.Run();
Jay Srinivasan08fce042012-06-07 16:31:01 -07001173}
1174
1175void UpdateAttempterTest::NoScatteringDoneDuringManualUpdateTestStart() {
1176 // Tests that no scattering logic is enabled if the update check
1177 // is manually done (as opposed to a scheduled update check)
Ben Chan9abb7632014-08-07 00:10:53 -07001178 int64_t initial_value = 8;
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001179 FakePrefs fake_prefs;
1180 attempter_.prefs_ = &fake_prefs;
Jay Srinivasan08fce042012-06-07 16:31:01 -07001181
Gilad Arnold5bb4c902014-04-10 12:32:13 -07001182 fake_system_state_.fake_hardware()->SetIsOOBEComplete(Time::UnixEpoch());
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001183 fake_system_state_.set_prefs(&fake_prefs);
Jay Srinivasan08fce042012-06-07 16:31:01 -07001184
Adolfo Victoriad3a1e352018-07-16 11:40:47 -07001185 EXPECT_TRUE(
1186 fake_prefs.SetInt64(kPrefsWallClockScatteringWaitPeriod, initial_value));
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001187 EXPECT_TRUE(fake_prefs.SetInt64(kPrefsUpdateCheckCount, initial_value));
Jay Srinivasan08fce042012-06-07 16:31:01 -07001188
1189 // make sure scatter_factor is non-zero as scattering is disabled
1190 // otherwise.
Ben Chan9abb7632014-08-07 00:10:53 -07001191 int64_t scatter_factor_in_seconds = 50;
Jay Srinivasan08fce042012-06-07 16:31:01 -07001192
Igor9fd76b62017-12-11 15:24:18 +01001193 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Jay Srinivasan08fce042012-06-07 16:31:01 -07001194 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
Igor9fd76b62017-12-11 15:24:18 +01001195 fake_system_state_.set_device_policy(device_policy.get());
Jay Srinivasan08fce042012-06-07 16:31:01 -07001196
1197 EXPECT_CALL(*device_policy, GetScatterFactorInSeconds(_))
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001198 .WillRepeatedly(
1199 DoAll(SetArgPointee<0>(scatter_factor_in_seconds), Return(true)));
Jay Srinivasan08fce042012-06-07 16:31:01 -07001200
Igor9fd76b62017-12-11 15:24:18 +01001201 attempter_.policy_provider_.reset(
1202 new policy::PolicyProvider(std::move(device_policy)));
1203
Gilad Arnoldb92f0df2013-01-10 16:32:45 -08001204 // Trigger an interactive check so we can test that scattering is disabled.
Amin Hassanie8153632020-10-27 15:11:28 -07001205 attempter_.Update({.interactive = true});
Jay Srinivasan08fce042012-06-07 16:31:01 -07001206 EXPECT_EQ(scatter_factor_in_seconds, attempter_.scatter_factor_.InSeconds());
1207
1208 // Make sure scattering is disabled for manual (i.e. user initiated) update
Jay Srinivasan21be0752012-07-25 15:44:56 -07001209 // checks and all artifacts are removed.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001210 EXPECT_FALSE(
1211 attempter_.omaha_request_params_->wall_clock_based_wait_enabled());
Adolfo Victoriad3a1e352018-07-16 11:40:47 -07001212 EXPECT_FALSE(fake_prefs.Exists(kPrefsWallClockScatteringWaitPeriod));
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001213 EXPECT_EQ(0, attempter_.omaha_request_params_->waiting_period().InSeconds());
1214 EXPECT_FALSE(
1215 attempter_.omaha_request_params_->update_check_count_wait_enabled());
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001216 EXPECT_FALSE(fake_prefs.Exists(kPrefsUpdateCheckCount));
Jay Srinivasan08fce042012-06-07 16:31:01 -07001217
Alex Deymo60ca1a72015-06-18 18:19:15 -07001218 ScheduleQuitMainLoop();
Jay Srinivasan08fce042012-06-07 16:31:01 -07001219}
1220
Adolfo Victoria497044c2018-07-18 07:51:42 -07001221void UpdateAttempterTest::SetUpStagingTest(const StagingSchedule& schedule,
1222 FakePrefs* prefs) {
1223 attempter_.prefs_ = prefs;
1224 fake_system_state_.set_prefs(prefs);
1225
1226 int64_t initial_value = 8;
1227 EXPECT_TRUE(
1228 prefs->SetInt64(kPrefsWallClockScatteringWaitPeriod, initial_value));
1229 EXPECT_TRUE(prefs->SetInt64(kPrefsUpdateCheckCount, initial_value));
1230 attempter_.scatter_factor_ = TimeDelta::FromSeconds(20);
1231
1232 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
1233 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
1234 fake_system_state_.set_device_policy(device_policy.get());
1235 EXPECT_CALL(*device_policy, GetDeviceUpdateStagingSchedule(_))
1236 .WillRepeatedly(DoAll(SetArgPointee<0>(schedule), Return(true)));
1237
1238 attempter_.policy_provider_.reset(
1239 new policy::PolicyProvider(std::move(device_policy)));
1240}
1241
1242TEST_F(UpdateAttempterTest, StagingSetsPrefsAndTurnsOffScattering) {
1243 loop_.PostTask(
1244 FROM_HERE,
1245 base::Bind(
1246 &UpdateAttempterTest::StagingSetsPrefsAndTurnsOffScatteringStart,
1247 base::Unretained(this)));
1248 loop_.Run();
1249}
1250
1251void UpdateAttempterTest::StagingSetsPrefsAndTurnsOffScatteringStart() {
1252 // Tests that staging sets its prefs properly and turns off scattering.
1253 fake_system_state_.fake_hardware()->SetIsOOBEComplete(Time::UnixEpoch());
1254 FakePrefs fake_prefs;
1255 SetUpStagingTest(kValidStagingSchedule, &fake_prefs);
1256
Amin Hassanie8153632020-10-27 15:11:28 -07001257 attempter_.Update({});
Adolfo Victoria497044c2018-07-18 07:51:42 -07001258 // Check that prefs have the correct values.
1259 int64_t update_count;
1260 EXPECT_TRUE(fake_prefs.GetInt64(kPrefsUpdateCheckCount, &update_count));
1261 int64_t waiting_time_days;
1262 EXPECT_TRUE(fake_prefs.GetInt64(kPrefsWallClockStagingWaitPeriod,
1263 &waiting_time_days));
1264 EXPECT_GT(waiting_time_days, 0);
1265 // Update count should have been decremented.
1266 EXPECT_EQ(7, update_count);
1267 // Check that Omaha parameters were updated correctly.
1268 EXPECT_TRUE(
1269 attempter_.omaha_request_params_->update_check_count_wait_enabled());
1270 EXPECT_TRUE(
1271 attempter_.omaha_request_params_->wall_clock_based_wait_enabled());
1272 EXPECT_EQ(waiting_time_days,
1273 attempter_.omaha_request_params_->waiting_period().InDays());
1274 // Check class variables.
1275 EXPECT_EQ(waiting_time_days, attempter_.staging_wait_time_.InDays());
1276 EXPECT_EQ(kValidStagingSchedule, attempter_.staging_schedule_);
1277 // Check that scattering is turned off
1278 EXPECT_EQ(0, attempter_.scatter_factor_.InSeconds());
1279 EXPECT_FALSE(fake_prefs.Exists(kPrefsWallClockScatteringWaitPeriod));
1280
1281 ScheduleQuitMainLoop();
1282}
1283
1284void UpdateAttempterTest::CheckStagingOff() {
1285 // Check that all prefs were removed.
1286 EXPECT_FALSE(attempter_.prefs_->Exists(kPrefsUpdateCheckCount));
1287 EXPECT_FALSE(attempter_.prefs_->Exists(kPrefsWallClockScatteringWaitPeriod));
1288 EXPECT_FALSE(attempter_.prefs_->Exists(kPrefsWallClockStagingWaitPeriod));
1289 // Check that the Omaha parameters have the correct value.
1290 EXPECT_EQ(0, attempter_.omaha_request_params_->waiting_period().InDays());
1291 EXPECT_EQ(attempter_.omaha_request_params_->waiting_period(),
1292 attempter_.staging_wait_time_);
1293 EXPECT_FALSE(
1294 attempter_.omaha_request_params_->update_check_count_wait_enabled());
1295 EXPECT_FALSE(
1296 attempter_.omaha_request_params_->wall_clock_based_wait_enabled());
1297 // Check that scattering is turned off too.
1298 EXPECT_EQ(0, attempter_.scatter_factor_.InSeconds());
1299}
1300
1301TEST_F(UpdateAttempterTest, StagingOffIfInteractive) {
1302 loop_.PostTask(FROM_HERE,
1303 base::Bind(&UpdateAttempterTest::StagingOffIfInteractiveStart,
1304 base::Unretained(this)));
1305 loop_.Run();
1306}
1307
1308void UpdateAttempterTest::StagingOffIfInteractiveStart() {
1309 // Tests that staging is turned off when an interactive update is requested.
1310 fake_system_state_.fake_hardware()->SetIsOOBEComplete(Time::UnixEpoch());
1311 FakePrefs fake_prefs;
1312 SetUpStagingTest(kValidStagingSchedule, &fake_prefs);
1313
Amin Hassanie8153632020-10-27 15:11:28 -07001314 attempter_.Update({.interactive = true});
Adolfo Victoria497044c2018-07-18 07:51:42 -07001315 CheckStagingOff();
1316
1317 ScheduleQuitMainLoop();
1318}
1319
1320TEST_F(UpdateAttempterTest, StagingOffIfOobe) {
1321 loop_.PostTask(FROM_HERE,
1322 base::Bind(&UpdateAttempterTest::StagingOffIfOobeStart,
1323 base::Unretained(this)));
1324 loop_.Run();
1325}
1326
1327void UpdateAttempterTest::StagingOffIfOobeStart() {
1328 // Tests that staging is turned off if OOBE hasn't been completed.
1329 fake_system_state_.fake_hardware()->SetIsOOBEEnabled(true);
1330 fake_system_state_.fake_hardware()->UnsetIsOOBEComplete();
1331 FakePrefs fake_prefs;
1332 SetUpStagingTest(kValidStagingSchedule, &fake_prefs);
1333
Amin Hassanie8153632020-10-27 15:11:28 -07001334 attempter_.Update({.interactive = true});
Adolfo Victoria497044c2018-07-18 07:51:42 -07001335 CheckStagingOff();
1336
1337 ScheduleQuitMainLoop();
1338}
1339
David Zeuthen985b1122013-10-09 12:13:15 -07001340// Checks that we only report daily metrics at most every 24 hours.
1341TEST_F(UpdateAttempterTest, ReportDailyMetrics) {
1342 FakeClock fake_clock;
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001343 FakePrefs fake_prefs;
David Zeuthen985b1122013-10-09 12:13:15 -07001344
Gilad Arnold5bb4c902014-04-10 12:32:13 -07001345 fake_system_state_.set_clock(&fake_clock);
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001346 fake_system_state_.set_prefs(&fake_prefs);
David Zeuthen985b1122013-10-09 12:13:15 -07001347
1348 Time epoch = Time::FromInternalValue(0);
1349 fake_clock.SetWallclockTime(epoch);
1350
1351 // If there is no kPrefsDailyMetricsLastReportedAt state variable,
1352 // we should report.
1353 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1354 // We should not report again if no time has passed.
1355 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1356
1357 // We should not report if only 10 hours has passed.
1358 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(10));
1359 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1360
1361 // We should not report if only 24 hours - 1 sec has passed.
1362 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(24) -
1363 TimeDelta::FromSeconds(1));
1364 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1365
1366 // We should report if 24 hours has passed.
1367 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(24));
1368 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1369
1370 // But then we should not report again..
1371 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1372
1373 // .. until another 24 hours has passed
1374 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(47));
1375 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1376 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(48));
1377 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1378 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1379
1380 // .. and another 24 hours
1381 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(71));
1382 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1383 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(72));
1384 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1385 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1386
1387 // If the span between time of reporting and present time is
1388 // negative, we report. This is in order to reset the timestamp and
1389 // avoid an edge condition whereby a distant point in the future is
1390 // in the state variable resulting in us never ever reporting again.
1391 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(71));
1392 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1393 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1394
1395 // In this case we should not update until the clock reads 71 + 24 = 95.
1396 // Check that.
1397 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(94));
1398 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1399 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(95));
1400 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1401 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
David Zeuthen985b1122013-10-09 12:13:15 -07001402}
1403
David Zeuthen3c55abd2013-10-14 12:48:03 -07001404TEST_F(UpdateAttempterTest, BootTimeInUpdateMarkerFile) {
David Zeuthen3c55abd2013-10-14 12:48:03 -07001405 FakeClock fake_clock;
1406 fake_clock.SetBootTime(Time::FromTimeT(42));
Gilad Arnold5bb4c902014-04-10 12:32:13 -07001407 fake_system_state_.set_clock(&fake_clock);
Alex Deymo906191f2015-10-12 12:22:44 -07001408 FakePrefs fake_prefs;
1409 fake_system_state_.set_prefs(&fake_prefs);
Sen Jiangaeeb2e02016-06-09 15:00:16 -07001410 attempter_.Init();
David Zeuthen3c55abd2013-10-14 12:48:03 -07001411
1412 Time boot_time;
Sen Jiangaeeb2e02016-06-09 15:00:16 -07001413 EXPECT_FALSE(attempter_.GetBootTimeAtUpdate(&boot_time));
David Zeuthen3c55abd2013-10-14 12:48:03 -07001414
Sen Jiangaeeb2e02016-06-09 15:00:16 -07001415 attempter_.WriteUpdateCompletedMarker();
David Zeuthen3c55abd2013-10-14 12:48:03 -07001416
Sen Jiangaeeb2e02016-06-09 15:00:16 -07001417 EXPECT_TRUE(attempter_.GetBootTimeAtUpdate(&boot_time));
David Zeuthen3c55abd2013-10-14 12:48:03 -07001418 EXPECT_EQ(boot_time.ToTimeT(), 42);
1419}
1420
David Pursell02c18642014-11-06 11:26:11 -08001421TEST_F(UpdateAttempterTest, AnyUpdateSourceAllowedUnofficial) {
1422 fake_system_state_.fake_hardware()->SetIsOfficialBuild(false);
1423 EXPECT_TRUE(attempter_.IsAnyUpdateSourceAllowed());
1424}
1425
1426TEST_F(UpdateAttempterTest, AnyUpdateSourceAllowedOfficialDevmode) {
1427 fake_system_state_.fake_hardware()->SetIsOfficialBuild(true);
Sen Jiange67bb5b2016-06-20 15:53:56 -07001428 fake_system_state_.fake_hardware()->SetAreDevFeaturesEnabled(true);
David Pursell02c18642014-11-06 11:26:11 -08001429 EXPECT_TRUE(attempter_.IsAnyUpdateSourceAllowed());
1430}
1431
1432TEST_F(UpdateAttempterTest, AnyUpdateSourceDisallowedOfficialNormal) {
1433 fake_system_state_.fake_hardware()->SetIsOfficialBuild(true);
Sen Jiange67bb5b2016-06-20 15:53:56 -07001434 fake_system_state_.fake_hardware()->SetAreDevFeaturesEnabled(false);
David Pursell02c18642014-11-06 11:26:11 -08001435 EXPECT_FALSE(attempter_.IsAnyUpdateSourceAllowed());
1436}
1437
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001438// TODO(kimjae): Follow testing pattern with params for |CheckForInstall()|.
1439// When adding, remove older tests related to |CheckForInstall()|.
1440TEST_F(UpdateAttempterTest, CheckForInstallNotIdleFails) {
1441 for (const auto status : kNonIdleUpdateStatuses) {
1442 // GIVEN a non-idle status.
1443 attempter_.status_ = status;
Xiaochu Liu8ba486f2018-11-06 11:14:10 -08001444
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001445 EXPECT_FALSE(attempter_.CheckForInstall({}, ""));
1446 }
Xiaochu Liu8ba486f2018-11-06 11:14:10 -08001447}
1448
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001449TEST_F(UpdateAttempterTest, CheckForUpdateNotIdleFails) {
1450 for (const auto status : kNonIdleUpdateStatuses) {
1451 // GIVEN a non-idle status.
1452 cfu_params_.status = status;
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001453
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001454 // THEN |ScheduleUpdates()| should not be called.
1455 cfu_params_.should_schedule_updates_be_called = false;
1456 // THEN result should indicate failure.
1457 cfu_params_.expected_result = false;
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001458
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001459 TestCheckForUpdate();
1460 }
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001461}
1462
1463TEST_F(UpdateAttempterTest, CheckForUpdateOfficalBuildClearsSource) {
1464 // GIVEN a official build.
1465
1466 // THEN we except forced app version + forced omaha url to be cleared.
1467
1468 TestCheckForUpdate();
1469}
1470
1471TEST_F(UpdateAttempterTest, CheckForUpdateUnofficialBuildChangesSource) {
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001472 // GIVEN a nonofficial build with dev features enabled.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001473 cfu_params_.is_official_build = false;
1474 cfu_params_.are_dev_features_enabled = true;
1475
1476 // THEN the forced app version + forced omaha url changes based on input.
1477 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1478 cfu_params_.expected_forced_omaha_url = cfu_params_.omaha_url;
1479
1480 TestCheckForUpdate();
1481}
1482
1483TEST_F(UpdateAttempterTest, CheckForUpdateOfficialBuildScheduledAUTest) {
1484 // GIVEN a scheduled autest omaha url.
1485 cfu_params_.omaha_url = "autest-scheduled";
1486
1487 // THEN forced app version is cleared.
1488 // THEN forced omaha url changes to default constant.
1489 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1490
1491 TestCheckForUpdate();
1492}
1493
1494TEST_F(UpdateAttempterTest, CheckForUpdateUnofficialBuildScheduledAUTest) {
1495 // GIVEN a scheduled autest omaha url.
1496 cfu_params_.omaha_url = "autest-scheduled";
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001497 // GIVEN a nonofficial build with dev features enabled.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001498 cfu_params_.is_official_build = false;
1499 cfu_params_.are_dev_features_enabled = true;
1500
1501 // THEN forced app version changes based on input.
1502 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1503 // THEN forced omaha url changes to default constant.
1504 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1505
1506 TestCheckForUpdate();
1507}
1508
1509TEST_F(UpdateAttempterTest, CheckForUpdateOfficialBuildAUTest) {
1510 // GIVEN a autest omaha url.
1511 cfu_params_.omaha_url = "autest";
1512
1513 // THEN forced app version is cleared.
1514 // THEN forced omaha url changes to default constant.
1515 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1516
1517 TestCheckForUpdate();
1518}
1519
1520TEST_F(UpdateAttempterTest, CheckForUpdateUnofficialBuildAUTest) {
1521 // GIVEN a autest omha url.
1522 cfu_params_.omaha_url = "autest";
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001523 // GIVEN a nonofficial build with dev features enabled.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001524 cfu_params_.is_official_build = false;
1525 cfu_params_.are_dev_features_enabled = true;
1526
1527 // THEN forced app version changes based on input.
1528 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1529 // THEN forced omaha url changes to default constant.
1530 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1531
1532 TestCheckForUpdate();
1533}
1534
1535TEST_F(UpdateAttempterTest,
1536 CheckForUpdateNonInteractiveOfficialBuildScheduledAUTest) {
1537 // GIVEN a scheduled autest omaha url.
1538 cfu_params_.omaha_url = "autest-scheduled";
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001539 // GIVEN a noninteractive update.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001540 cfu_params_.flags = UpdateAttemptFlags::kFlagNonInteractive;
1541
1542 // THEN forced app version is cleared.
1543 // THEN forced omaha url changes to default constant.
1544 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1545
1546 TestCheckForUpdate();
1547}
1548
1549TEST_F(UpdateAttempterTest,
1550 CheckForUpdateNonInteractiveUnofficialBuildScheduledAUTest) {
1551 // GIVEN a scheduled autest omaha url.
1552 cfu_params_.omaha_url = "autest-scheduled";
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001553 // GIVEN a noninteractive update.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001554 cfu_params_.flags = UpdateAttemptFlags::kFlagNonInteractive;
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001555 // GIVEN a nonofficial build with dev features enabled.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001556 cfu_params_.is_official_build = false;
1557 cfu_params_.are_dev_features_enabled = true;
1558
1559 // THEN forced app version changes based on input.
1560 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1561 // THEN forced omaha url changes to default constant.
1562 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1563
1564 TestCheckForUpdate();
1565}
1566
1567TEST_F(UpdateAttempterTest, CheckForUpdateNonInteractiveOfficialBuildAUTest) {
1568 // GIVEN a autest omaha url.
1569 cfu_params_.omaha_url = "autest";
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001570 // GIVEN a noninteractive update.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001571 cfu_params_.flags = UpdateAttemptFlags::kFlagNonInteractive;
1572
1573 // THEN forced app version is cleared.
1574 // THEN forced omaha url changes to default constant.
1575 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1576
1577 TestCheckForUpdate();
1578}
1579
1580TEST_F(UpdateAttempterTest, CheckForUpdateNonInteractiveUnofficialBuildAUTest) {
1581 // GIVEN a autest omaha url.
1582 cfu_params_.omaha_url = "autest";
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001583 // GIVEN a noninteractive update.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001584 cfu_params_.flags = UpdateAttemptFlags::kFlagNonInteractive;
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001585 // GIVEN a nonofficial build with dev features enabled.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001586 cfu_params_.is_official_build = false;
1587 cfu_params_.are_dev_features_enabled = true;
1588
1589 // THEN forced app version changes based on input.
1590 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1591 // THEN forced omaha url changes to default constant.
1592 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1593
1594 TestCheckForUpdate();
David Pursell02c18642014-11-06 11:26:11 -08001595}
1596
Jae Hoon Kim2b73ac22019-07-02 11:17:24 -07001597TEST_F(UpdateAttempterTest, CheckForUpdateMissingForcedCallback1) {
1598 // GIVEN a official build.
1599 // GIVEN forced callback is not set.
1600 attempter_.set_forced_update_pending_callback(nullptr);
1601
1602 // THEN we except forced app version + forced omaha url to be cleared.
1603 // THEN |ScheduleUpdates()| should not be called.
1604 cfu_params_.should_schedule_updates_be_called = false;
1605
1606 TestCheckForUpdate();
1607}
1608
1609TEST_F(UpdateAttempterTest, CheckForUpdateMissingForcedCallback2) {
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001610 // GIVEN a nonofficial build with dev features enabled.
Jae Hoon Kim2b73ac22019-07-02 11:17:24 -07001611 cfu_params_.is_official_build = false;
1612 cfu_params_.are_dev_features_enabled = true;
1613 // GIVEN forced callback is not set.
1614 attempter_.set_forced_update_pending_callback(nullptr);
1615
1616 // THEN the forced app version + forced omaha url changes based on input.
1617 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1618 cfu_params_.expected_forced_omaha_url = cfu_params_.omaha_url;
1619 // THEN |ScheduleUpdates()| should not be called.
1620 cfu_params_.should_schedule_updates_be_called = false;
1621
1622 TestCheckForUpdate();
1623}
1624
Xiaochu Liu88d90382018-08-29 16:09:11 -07001625TEST_F(UpdateAttempterTest, CheckForInstallTest) {
1626 fake_system_state_.fake_hardware()->SetIsOfficialBuild(true);
1627 fake_system_state_.fake_hardware()->SetAreDevFeaturesEnabled(false);
1628 attempter_.CheckForInstall({}, "autest");
1629 EXPECT_EQ(constants::kOmahaDefaultAUTestURL, attempter_.forced_omaha_url());
1630
1631 attempter_.CheckForInstall({}, "autest-scheduled");
1632 EXPECT_EQ(constants::kOmahaDefaultAUTestURL, attempter_.forced_omaha_url());
1633
1634 attempter_.CheckForInstall({}, "http://omaha.phishing");
1635 EXPECT_EQ("", attempter_.forced_omaha_url());
1636}
1637
Colin Howesac170d92018-11-20 16:29:28 -08001638TEST_F(UpdateAttempterTest, InstallSetsStatusIdle) {
1639 attempter_.CheckForInstall({}, "http://foo.bar");
1640 attempter_.status_ = UpdateStatus::DOWNLOADING;
1641 EXPECT_TRUE(attempter_.is_install_);
1642 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1643 UpdateEngineStatus status;
1644 attempter_.GetStatus(&status);
1645 // Should set status to idle after an install operation.
1646 EXPECT_EQ(UpdateStatus::IDLE, status.status);
1647}
1648
Colin Howes978c1082018-12-03 11:46:12 -08001649TEST_F(UpdateAttempterTest, RollbackAfterInstall) {
1650 attempter_.is_install_ = true;
1651 attempter_.Rollback(false);
1652 EXPECT_FALSE(attempter_.is_install_);
1653}
1654
1655TEST_F(UpdateAttempterTest, UpdateAfterInstall) {
1656 attempter_.is_install_ = true;
1657 attempter_.CheckForUpdate("", "", UpdateAttemptFlags::kNone);
1658 EXPECT_FALSE(attempter_.is_install_);
1659}
1660
Xiyuan Xiac0e8f9a2017-02-22 13:19:35 -08001661TEST_F(UpdateAttempterTest, TargetVersionPrefixSetAndReset) {
Amin Hassanie8153632020-10-27 15:11:28 -07001662 UpdateCheckParams params;
1663 attempter_.CalculateUpdateParams({.target_version_prefix = "1234"});
Xiyuan Xiac0e8f9a2017-02-22 13:19:35 -08001664 EXPECT_EQ("1234",
1665 fake_system_state_.request_params()->target_version_prefix());
1666
Amin Hassanie8153632020-10-27 15:11:28 -07001667 attempter_.CalculateUpdateParams({});
Xiyuan Xiac0e8f9a2017-02-22 13:19:35 -08001668 EXPECT_TRUE(
1669 fake_system_state_.request_params()->target_version_prefix().empty());
1670}
1671
Amin Hassani37b67232020-08-13 09:29:48 -07001672TEST_F(UpdateAttempterTest, TargetChannelHintSetAndReset) {
Amin Hassanie8153632020-10-27 15:11:28 -07001673 attempter_.CalculateUpdateParams({.lts_tag = "hint"});
Amin Hassani37b67232020-08-13 09:29:48 -07001674 EXPECT_EQ("hint", fake_system_state_.request_params()->lts_tag());
1675
Amin Hassanie8153632020-10-27 15:11:28 -07001676 attempter_.CalculateUpdateParams({});
Amin Hassani37b67232020-08-13 09:29:48 -07001677 EXPECT_TRUE(fake_system_state_.request_params()->lts_tag().empty());
1678}
1679
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001680TEST_F(UpdateAttempterTest, RollbackAllowedSetAndReset) {
Amin Hassanie8153632020-10-27 15:11:28 -07001681 attempter_.CalculateUpdateParams({
1682 .target_version_prefix = "1234",
1683 .rollback_allowed = true,
1684 .rollback_allowed_milestones = 4,
1685 });
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001686 EXPECT_TRUE(fake_system_state_.request_params()->rollback_allowed());
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -07001687 EXPECT_EQ(4,
1688 fake_system_state_.request_params()->rollback_allowed_milestones());
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001689
Amin Hassanie8153632020-10-27 15:11:28 -07001690 attempter_.CalculateUpdateParams({
1691 .target_version_prefix = "1234",
1692 .rollback_allowed_milestones = 4,
1693 });
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001694 EXPECT_FALSE(fake_system_state_.request_params()->rollback_allowed());
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -07001695 EXPECT_EQ(4,
1696 fake_system_state_.request_params()->rollback_allowed_milestones());
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001697}
1698
Miriam Polzeraff72002020-08-27 08:20:39 +02001699TEST_F(UpdateAttempterTest, ChannelDowngradeNoRollback) {
1700 base::ScopedTempDir tempdir;
1701 ASSERT_TRUE(tempdir.CreateUniqueTempDir());
1702 fake_system_state_.request_params()->set_root(tempdir.GetPath().value());
Amin Hassanie8153632020-10-27 15:11:28 -07001703 attempter_.CalculateUpdateParams({
1704 .target_channel = "stable-channel",
1705 });
Miriam Polzeraff72002020-08-27 08:20:39 +02001706 EXPECT_FALSE(fake_system_state_.request_params()->is_powerwash_allowed());
1707}
1708
1709TEST_F(UpdateAttempterTest, ChannelDowngradeRollback) {
1710 base::ScopedTempDir tempdir;
1711 ASSERT_TRUE(tempdir.CreateUniqueTempDir());
1712 fake_system_state_.request_params()->set_root(tempdir.GetPath().value());
Amin Hassanie8153632020-10-27 15:11:28 -07001713 attempter_.CalculateUpdateParams({
1714 .rollback_on_channel_downgrade = true,
1715 .target_channel = "stable-channel",
1716 });
Miriam Polzeraff72002020-08-27 08:20:39 +02001717 EXPECT_TRUE(fake_system_state_.request_params()->is_powerwash_allowed());
1718}
1719
Aaron Wood23bd3392017-10-06 14:48:25 -07001720TEST_F(UpdateAttempterTest, UpdateDeferredByPolicyTest) {
1721 // Construct an OmahaResponseHandlerAction that has processed an InstallPlan,
1722 // but the update is being deferred by the Policy.
Amin Hassani68512d42018-07-31 23:52:33 -07001723 OmahaResponseHandlerAction response_action(&fake_system_state_);
1724 response_action.install_plan_.version = "a.b.c.d";
1725 response_action.install_plan_.system_version = "b.c.d.e";
1726 response_action.install_plan_.payloads.push_back(
Aaron Wood23bd3392017-10-06 14:48:25 -07001727 {.size = 1234ULL, .type = InstallPayloadType::kFull});
Aaron Wood23bd3392017-10-06 14:48:25 -07001728 // Inform the UpdateAttempter that the OmahaResponseHandlerAction has
1729 // completed, with the deferred-update error code.
1730 attempter_.ActionCompleted(
Amin Hassani68512d42018-07-31 23:52:33 -07001731 nullptr, &response_action, ErrorCode::kOmahaUpdateDeferredPerPolicy);
Aaron Wood23bd3392017-10-06 14:48:25 -07001732 {
1733 UpdateEngineStatus status;
1734 attempter_.GetStatus(&status);
1735 EXPECT_EQ(UpdateStatus::UPDATE_AVAILABLE, status.status);
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001736 EXPECT_TRUE(attempter_.install_plan_);
1737 EXPECT_EQ(attempter_.install_plan_->version, status.new_version);
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001738 EXPECT_EQ(attempter_.install_plan_->payloads[0].size,
Aaron Wood23bd3392017-10-06 14:48:25 -07001739 status.new_size_bytes);
1740 }
1741 // An "error" event should have been created to tell Omaha that the update is
1742 // being deferred.
1743 EXPECT_TRUE(nullptr != attempter_.error_event_);
1744 EXPECT_EQ(OmahaEvent::kTypeUpdateComplete, attempter_.error_event_->type);
1745 EXPECT_EQ(OmahaEvent::kResultUpdateDeferred, attempter_.error_event_->result);
1746 ErrorCode expected_code = static_cast<ErrorCode>(
1747 static_cast<int>(ErrorCode::kOmahaUpdateDeferredPerPolicy) |
1748 static_cast<int>(ErrorCode::kTestOmahaUrlFlag));
1749 EXPECT_EQ(expected_code, attempter_.error_event_->error_code);
1750 // End the processing
1751 attempter_.ProcessingDone(nullptr, ErrorCode::kOmahaUpdateDeferredPerPolicy);
1752 // Validate the state of the attempter.
1753 {
1754 UpdateEngineStatus status;
1755 attempter_.GetStatus(&status);
1756 EXPECT_EQ(UpdateStatus::REPORTING_ERROR_EVENT, status.status);
Amin Hassani68512d42018-07-31 23:52:33 -07001757 EXPECT_EQ(response_action.install_plan_.version, status.new_version);
Amin Hassani68512d42018-07-31 23:52:33 -07001758 EXPECT_EQ(response_action.install_plan_.payloads[0].size,
Aaron Wood23bd3392017-10-06 14:48:25 -07001759 status.new_size_bytes);
1760 }
1761}
1762
1763TEST_F(UpdateAttempterTest, UpdateIsNotRunningWhenUpdateAvailable) {
Jae Hoon Kim75daa382019-07-02 11:17:24 -07001764 // Default construction for |waiting_for_scheduled_check_| is false.
Jae Hoon Kimba2fdce2019-07-11 13:18:58 -07001765 EXPECT_FALSE(attempter_.IsBusyOrUpdateScheduled());
Aaron Wood23bd3392017-10-06 14:48:25 -07001766 // Verify in-progress update with UPDATE_AVAILABLE is running
1767 attempter_.status_ = UpdateStatus::UPDATE_AVAILABLE;
Jae Hoon Kimba2fdce2019-07-11 13:18:58 -07001768 EXPECT_TRUE(attempter_.IsBusyOrUpdateScheduled());
Aaron Wood23bd3392017-10-06 14:48:25 -07001769}
1770
Aaron Woodbf5a2522017-10-04 10:58:36 -07001771TEST_F(UpdateAttempterTest, UpdateAttemptFlagsCachedAtUpdateStart) {
1772 attempter_.SetUpdateAttemptFlags(UpdateAttemptFlags::kFlagRestrictDownload);
1773
1774 UpdateCheckParams params = {.updates_enabled = true};
1775 attempter_.OnUpdateScheduled(EvalStatus::kSucceeded, params);
1776
1777 EXPECT_EQ(UpdateAttemptFlags::kFlagRestrictDownload,
1778 attempter_.GetCurrentUpdateAttemptFlags());
1779}
1780
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001781TEST_F(UpdateAttempterTest, RollbackNotAllowed) {
1782 UpdateCheckParams params = {.updates_enabled = true,
1783 .rollback_allowed = false};
1784 attempter_.OnUpdateScheduled(EvalStatus::kSucceeded, params);
1785 EXPECT_FALSE(fake_system_state_.request_params()->rollback_allowed());
1786}
1787
1788TEST_F(UpdateAttempterTest, RollbackAllowed) {
1789 UpdateCheckParams params = {.updates_enabled = true,
1790 .rollback_allowed = true};
1791 attempter_.OnUpdateScheduled(EvalStatus::kSucceeded, params);
1792 EXPECT_TRUE(fake_system_state_.request_params()->rollback_allowed());
1793}
1794
Aaron Wood081c0232017-10-19 17:14:58 -07001795TEST_F(UpdateAttempterTest, InteractiveUpdateUsesPassedRestrictions) {
1796 attempter_.SetUpdateAttemptFlags(UpdateAttemptFlags::kFlagRestrictDownload);
1797
1798 attempter_.CheckForUpdate("", "", UpdateAttemptFlags::kNone);
1799 EXPECT_EQ(UpdateAttemptFlags::kNone,
1800 attempter_.GetCurrentUpdateAttemptFlags());
1801}
1802
1803TEST_F(UpdateAttempterTest, NonInteractiveUpdateUsesSetRestrictions) {
1804 attempter_.SetUpdateAttemptFlags(UpdateAttemptFlags::kNone);
1805
1806 // This tests that when CheckForUpdate() is called with the non-interactive
1807 // flag set, that it doesn't change the current UpdateAttemptFlags.
1808 attempter_.CheckForUpdate("",
1809 "",
1810 UpdateAttemptFlags::kFlagNonInteractive |
1811 UpdateAttemptFlags::kFlagRestrictDownload);
1812 EXPECT_EQ(UpdateAttemptFlags::kNone,
1813 attempter_.GetCurrentUpdateAttemptFlags());
1814}
1815
Marton Hunyadye58bddb2018-04-10 20:27:26 +02001816void UpdateAttempterTest::ResetRollbackHappenedStart(bool is_consumer,
1817 bool is_policy_loaded,
1818 bool expected_reset) {
1819 EXPECT_CALL(*fake_system_state_.mock_payload_state(), GetRollbackHappened())
1820 .WillRepeatedly(Return(true));
1821 auto mock_policy_provider =
1822 std::make_unique<NiceMock<policy::MockPolicyProvider>>();
1823 EXPECT_CALL(*mock_policy_provider, IsConsumerDevice())
1824 .WillRepeatedly(Return(is_consumer));
1825 EXPECT_CALL(*mock_policy_provider, device_policy_is_loaded())
1826 .WillRepeatedly(Return(is_policy_loaded));
1827 const policy::MockDevicePolicy device_policy;
1828 EXPECT_CALL(*mock_policy_provider, GetDevicePolicy())
1829 .WillRepeatedly(ReturnRef(device_policy));
1830 EXPECT_CALL(*fake_system_state_.mock_payload_state(),
1831 SetRollbackHappened(false))
1832 .Times(expected_reset ? 1 : 0);
1833 attempter_.policy_provider_ = std::move(mock_policy_provider);
Amin Hassanie8153632020-10-27 15:11:28 -07001834 attempter_.Update({});
Marton Hunyadye58bddb2018-04-10 20:27:26 +02001835 ScheduleQuitMainLoop();
1836}
1837
1838TEST_F(UpdateAttempterTest, ResetRollbackHappenedOobe) {
1839 loop_.PostTask(FROM_HERE,
1840 base::Bind(&UpdateAttempterTest::ResetRollbackHappenedStart,
1841 base::Unretained(this),
1842 /*is_consumer=*/false,
1843 /*is_policy_loaded=*/false,
1844 /*expected_reset=*/false));
1845 loop_.Run();
1846}
1847
1848TEST_F(UpdateAttempterTest, ResetRollbackHappenedConsumer) {
1849 loop_.PostTask(FROM_HERE,
1850 base::Bind(&UpdateAttempterTest::ResetRollbackHappenedStart,
1851 base::Unretained(this),
1852 /*is_consumer=*/true,
1853 /*is_policy_loaded=*/false,
1854 /*expected_reset=*/true));
1855 loop_.Run();
1856}
1857
1858TEST_F(UpdateAttempterTest, ResetRollbackHappenedEnterprise) {
1859 loop_.PostTask(FROM_HERE,
1860 base::Bind(&UpdateAttempterTest::ResetRollbackHappenedStart,
1861 base::Unretained(this),
1862 /*is_consumer=*/false,
1863 /*is_policy_loaded=*/true,
1864 /*expected_reset=*/true));
1865 loop_.Run();
1866}
1867
Marton Hunyady199152d2018-05-07 19:08:48 +02001868TEST_F(UpdateAttempterTest, SetRollbackHappenedRollback) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001869 attempter_.install_plan_.reset(new InstallPlan);
1870 attempter_.install_plan_->is_rollback = true;
Marton Hunyady199152d2018-05-07 19:08:48 +02001871
1872 EXPECT_CALL(*fake_system_state_.mock_payload_state(),
1873 SetRollbackHappened(true))
1874 .Times(1);
1875 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1876}
1877
1878TEST_F(UpdateAttempterTest, SetRollbackHappenedNotRollback) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001879 attempter_.install_plan_.reset(new InstallPlan);
1880 attempter_.install_plan_->is_rollback = false;
Marton Hunyady199152d2018-05-07 19:08:48 +02001881
1882 EXPECT_CALL(*fake_system_state_.mock_payload_state(),
1883 SetRollbackHappened(true))
1884 .Times(0);
1885 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1886}
1887
Marton Hunyadya0302682018-05-16 18:52:13 +02001888TEST_F(UpdateAttempterTest, RollbackMetricsRollbackSuccess) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001889 attempter_.install_plan_.reset(new InstallPlan);
1890 attempter_.install_plan_->is_rollback = true;
1891 attempter_.install_plan_->version = kRollbackVersion;
Marton Hunyadya0302682018-05-16 18:52:13 +02001892
1893 EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
1894 ReportEnterpriseRollbackMetrics(true, kRollbackVersion))
1895 .Times(1);
1896 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1897}
1898
1899TEST_F(UpdateAttempterTest, RollbackMetricsNotRollbackSuccess) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001900 attempter_.install_plan_.reset(new InstallPlan);
1901 attempter_.install_plan_->is_rollback = false;
1902 attempter_.install_plan_->version = kRollbackVersion;
Marton Hunyadya0302682018-05-16 18:52:13 +02001903
1904 EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
1905 ReportEnterpriseRollbackMetrics(_, _))
1906 .Times(0);
1907 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1908}
1909
1910TEST_F(UpdateAttempterTest, RollbackMetricsRollbackFailure) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001911 attempter_.install_plan_.reset(new InstallPlan);
1912 attempter_.install_plan_->is_rollback = true;
1913 attempter_.install_plan_->version = kRollbackVersion;
Marton Hunyadya0302682018-05-16 18:52:13 +02001914
1915 EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
1916 ReportEnterpriseRollbackMetrics(false, kRollbackVersion))
1917 .Times(1);
1918 MockAction action;
1919 attempter_.CreatePendingErrorEvent(&action, ErrorCode::kRollbackNotPossible);
1920 attempter_.ProcessingDone(nullptr, ErrorCode::kRollbackNotPossible);
1921}
1922
1923TEST_F(UpdateAttempterTest, RollbackMetricsNotRollbackFailure) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001924 attempter_.install_plan_.reset(new InstallPlan);
1925 attempter_.install_plan_->is_rollback = false;
1926 attempter_.install_plan_->version = kRollbackVersion;
Marton Hunyadya0302682018-05-16 18:52:13 +02001927
1928 EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
1929 ReportEnterpriseRollbackMetrics(_, _))
1930 .Times(0);
1931 MockAction action;
1932 attempter_.CreatePendingErrorEvent(&action, ErrorCode::kRollbackNotPossible);
1933 attempter_.ProcessingDone(nullptr, ErrorCode::kRollbackNotPossible);
1934}
1935
May Lippert60aa3ca2018-08-15 16:55:29 -07001936TEST_F(UpdateAttempterTest, TimeToUpdateAppliedMetricFailure) {
1937 EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
1938 ReportEnterpriseUpdateSeenToDownloadDays(_, _))
1939 .Times(0);
1940 attempter_.ProcessingDone(nullptr, ErrorCode::kOmahaUpdateDeferredPerPolicy);
1941}
1942
1943TEST_F(UpdateAttempterTest, TimeToUpdateAppliedOnNonEnterprise) {
1944 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
1945 fake_system_state_.set_device_policy(device_policy.get());
1946 // Make device policy return that this is not enterprise enrolled
1947 EXPECT_CALL(*device_policy, IsEnterpriseEnrolled()).WillOnce(Return(false));
1948
1949 // Ensure that the metric is not recorded.
1950 EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
1951 ReportEnterpriseUpdateSeenToDownloadDays(_, _))
1952 .Times(0);
1953 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1954}
1955
1956TEST_F(UpdateAttempterTest,
1957 TimeToUpdateAppliedWithTimeRestrictionMetricSuccess) {
1958 constexpr int kDaysToUpdate = 15;
1959 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
1960 fake_system_state_.set_device_policy(device_policy.get());
1961 // Make device policy return that this is enterprise enrolled
1962 EXPECT_CALL(*device_policy, IsEnterpriseEnrolled()).WillOnce(Return(true));
1963 // Pretend that there's a time restriction policy in place
1964 EXPECT_CALL(*device_policy, GetDisallowedTimeIntervals(_))
1965 .WillOnce(Return(true));
1966
1967 FakePrefs fake_prefs;
1968 Time update_first_seen_at = Time::Now();
1969 fake_prefs.SetInt64(kPrefsUpdateFirstSeenAt,
1970 update_first_seen_at.ToInternalValue());
1971
1972 FakeClock fake_clock;
1973 Time update_finished_at =
1974 update_first_seen_at + TimeDelta::FromDays(kDaysToUpdate);
1975 fake_clock.SetWallclockTime(update_finished_at);
1976
1977 fake_system_state_.set_clock(&fake_clock);
1978 fake_system_state_.set_prefs(&fake_prefs);
1979
1980 EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
1981 ReportEnterpriseUpdateSeenToDownloadDays(true, kDaysToUpdate))
1982 .Times(1);
1983 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1984}
1985
1986TEST_F(UpdateAttempterTest,
1987 TimeToUpdateAppliedWithoutTimeRestrictionMetricSuccess) {
1988 constexpr int kDaysToUpdate = 15;
1989 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
1990 fake_system_state_.set_device_policy(device_policy.get());
1991 // Make device policy return that this is enterprise enrolled
1992 EXPECT_CALL(*device_policy, IsEnterpriseEnrolled()).WillOnce(Return(true));
1993 // Pretend that there's no time restriction policy in place
1994 EXPECT_CALL(*device_policy, GetDisallowedTimeIntervals(_))
1995 .WillOnce(Return(false));
1996
1997 FakePrefs fake_prefs;
1998 Time update_first_seen_at = Time::Now();
1999 fake_prefs.SetInt64(kPrefsUpdateFirstSeenAt,
2000 update_first_seen_at.ToInternalValue());
2001
2002 FakeClock fake_clock;
2003 Time update_finished_at =
2004 update_first_seen_at + TimeDelta::FromDays(kDaysToUpdate);
2005 fake_clock.SetWallclockTime(update_finished_at);
2006
2007 fake_system_state_.set_clock(&fake_clock);
2008 fake_system_state_.set_prefs(&fake_prefs);
2009
2010 EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
2011 ReportEnterpriseUpdateSeenToDownloadDays(false, kDaysToUpdate))
2012 .Times(1);
2013 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
2014}
2015
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002016TEST_F(UpdateAttempterTest, ProcessingDoneUpdated) {
2017 // GIVEN an update finished.
2018
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002019 // THEN update_engine should call update completion.
2020 pd_params_.should_update_completed_be_called = true;
2021 // THEN need reboot since update applied.
2022 pd_params_.expected_exit_status = UpdateStatus::UPDATED_NEED_REBOOT;
2023 // THEN install indication should be false.
2024
2025 TestProcessingDone();
2026}
2027
2028TEST_F(UpdateAttempterTest, ProcessingDoneUpdatedDlcFilter) {
2029 // GIVEN an update finished.
2030 // GIVEN DLC |AppParams| list.
2031 auto dlc_1 = "dlc_1", dlc_2 = "dlc_2";
2032 pd_params_.dlc_apps_params = {{dlc_1, {.name = dlc_1, .updated = false}},
2033 {dlc_2, {.name = dlc_2}}};
2034
2035 // THEN update_engine should call update completion.
2036 pd_params_.should_update_completed_be_called = true;
2037 pd_params_.args_to_update_completed = {dlc_2};
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002038 // THEN need reboot since update applied.
2039 pd_params_.expected_exit_status = UpdateStatus::UPDATED_NEED_REBOOT;
2040 // THEN install indication should be false.
2041
2042 TestProcessingDone();
2043}
2044
2045TEST_F(UpdateAttempterTest, ProcessingDoneInstalled) {
2046 // GIVEN an install finished.
2047 pd_params_.is_install = true;
2048
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002049 // THEN update_engine should call install completion.
2050 pd_params_.should_install_completed_be_called = true;
2051 // THEN go idle.
2052 // THEN install indication should be false.
2053
2054 TestProcessingDone();
2055}
2056
2057TEST_F(UpdateAttempterTest, ProcessingDoneInstalledDlcFilter) {
2058 // GIVEN an install finished.
2059 pd_params_.is_install = true;
2060 // GIVEN DLC |AppParams| list.
2061 auto dlc_1 = "dlc_1", dlc_2 = "dlc_2";
2062 pd_params_.dlc_apps_params = {{dlc_1, {.name = dlc_1, .updated = false}},
2063 {dlc_2, {.name = dlc_2}}};
2064
2065 // THEN update_engine should call install completion.
2066 pd_params_.should_install_completed_be_called = true;
2067 pd_params_.args_to_install_completed = {dlc_2};
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002068 // THEN go idle.
2069 // THEN install indication should be false.
2070
2071 TestProcessingDone();
2072}
2073
2074TEST_F(UpdateAttempterTest, ProcessingDoneInstallReportingError) {
2075 // GIVEN an install finished.
2076 pd_params_.is_install = true;
2077 // GIVEN a reporting error occurred.
2078 pd_params_.status = UpdateStatus::REPORTING_ERROR_EVENT;
2079
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002080 // THEN update_engine should not call install completion.
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002081 // THEN go idle.
2082 // THEN install indication should be false.
2083
2084 TestProcessingDone();
2085}
2086
2087TEST_F(UpdateAttempterTest, ProcessingDoneNoUpdate) {
2088 // GIVEN an update finished.
2089 // GIVEN an action error occured.
2090 pd_params_.code = ErrorCode::kNoUpdate;
2091
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002092 // THEN update_engine should not call update completion.
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002093 // THEN go idle.
2094 // THEN install indication should be false.
2095
2096 TestProcessingDone();
2097}
2098
2099TEST_F(UpdateAttempterTest, ProcessingDoneNoInstall) {
2100 // GIVEN an install finished.
2101 pd_params_.is_install = true;
2102 // GIVEN an action error occured.
2103 pd_params_.code = ErrorCode::kNoUpdate;
2104
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002105 // THEN update_engine should not call install completion.
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002106 // THEN go idle.
2107 // THEN install indication should be false.
2108
2109 TestProcessingDone();
2110}
2111
2112TEST_F(UpdateAttempterTest, ProcessingDoneUpdateError) {
2113 // GIVEN an update finished.
2114 // GIVEN an action error occured.
2115 pd_params_.code = ErrorCode::kError;
2116 // GIVEN an event error is set.
2117 attempter_.error_event_.reset(new OmahaEvent(OmahaEvent::kTypeUpdateComplete,
2118 OmahaEvent::kResultError,
2119 ErrorCode::kError));
2120
2121 // THEN indicate a error event.
2122 pd_params_.expected_exit_status = UpdateStatus::REPORTING_ERROR_EVENT;
2123 // THEN install indication should be false.
2124
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002125 // THEN update_engine should not call update completion.
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002126 // THEN expect critical actions of |ScheduleErrorEventAction()|.
2127 EXPECT_CALL(*processor_, EnqueueAction(Pointee(_))).Times(1);
2128 EXPECT_CALL(*processor_, StartProcessing()).Times(1);
2129 // THEN |ScheduleUpdates()| will be called next |ProcessingDone()| so skip.
2130 pd_params_.should_schedule_updates_be_called = false;
2131
2132 TestProcessingDone();
2133}
2134
2135TEST_F(UpdateAttempterTest, ProcessingDoneInstallError) {
2136 // GIVEN an install finished.
2137 pd_params_.is_install = true;
2138 // GIVEN an action error occured.
2139 pd_params_.code = ErrorCode::kError;
2140 // GIVEN an event error is set.
2141 attempter_.error_event_.reset(new OmahaEvent(OmahaEvent::kTypeUpdateComplete,
2142 OmahaEvent::kResultError,
2143 ErrorCode::kError));
2144
2145 // THEN indicate a error event.
2146 pd_params_.expected_exit_status = UpdateStatus::REPORTING_ERROR_EVENT;
2147 // THEN install indication should be false.
2148
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002149 // THEN update_engine should not call install completion.
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002150 // THEN expect critical actions of |ScheduleErrorEventAction()|.
2151 EXPECT_CALL(*processor_, EnqueueAction(Pointee(_))).Times(1);
2152 EXPECT_CALL(*processor_, StartProcessing()).Times(1);
2153 // THEN |ScheduleUpdates()| will be called next |ProcessingDone()| so skip.
2154 pd_params_.should_schedule_updates_be_called = false;
2155
2156 TestProcessingDone();
2157}
2158
Amr Aboelkher21ac9962019-05-15 14:50:05 +02002159void UpdateAttempterTest::UpdateToQuickFixBuildStart(bool set_token) {
2160 // Tests that checks if |device_quick_fix_build_token| arrives when
2161 // policy is set and the device is enterprise enrolled based on |set_token|.
2162 string token = set_token ? "some_token" : "";
Askar Aitzhan570ca872019-04-24 11:16:12 +02002163 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
2164 fake_system_state_.set_device_policy(device_policy.get());
Askar Aitzhan570ca872019-04-24 11:16:12 +02002165 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
Amr Aboelkher21ac9962019-05-15 14:50:05 +02002166
2167 if (set_token)
2168 EXPECT_CALL(*device_policy, GetDeviceQuickFixBuildToken(_))
2169 .WillOnce(DoAll(SetArgPointee<0>(token), Return(true)));
2170 else
2171 EXPECT_CALL(*device_policy, GetDeviceQuickFixBuildToken(_))
2172 .WillOnce(Return(false));
Askar Aitzhan570ca872019-04-24 11:16:12 +02002173 attempter_.policy_provider_.reset(
2174 new policy::PolicyProvider(std::move(device_policy)));
Amin Hassanie8153632020-10-27 15:11:28 -07002175 attempter_.Update({});
Askar Aitzhan570ca872019-04-24 11:16:12 +02002176
Amr Aboelkher21ac9962019-05-15 14:50:05 +02002177 EXPECT_EQ(token, attempter_.omaha_request_params_->autoupdate_token());
Askar Aitzhan570ca872019-04-24 11:16:12 +02002178 ScheduleQuitMainLoop();
2179}
2180
Amr Aboelkher21ac9962019-05-15 14:50:05 +02002181TEST_F(UpdateAttempterTest,
2182 QuickFixTokenWhenDeviceIsEnterpriseEnrolledAndPolicyIsSet) {
Askar Aitzhan570ca872019-04-24 11:16:12 +02002183 loop_.PostTask(FROM_HERE,
2184 base::Bind(&UpdateAttempterTest::UpdateToQuickFixBuildStart,
Amr Aboelkher21ac9962019-05-15 14:50:05 +02002185 base::Unretained(this),
2186 /*set_token=*/true));
2187 loop_.Run();
2188}
2189
2190TEST_F(UpdateAttempterTest, EmptyQuickFixToken) {
2191 loop_.PostTask(FROM_HERE,
2192 base::Bind(&UpdateAttempterTest::UpdateToQuickFixBuildStart,
2193 base::Unretained(this),
2194 /*set_token=*/false));
Askar Aitzhan570ca872019-04-24 11:16:12 +02002195 loop_.Run();
2196}
2197
Jae Hoon Kim75daa382019-07-02 11:17:24 -07002198TEST_F(UpdateAttempterTest, ScheduleUpdateSpamHandlerTest) {
2199 EXPECT_CALL(mock_update_manager_, AsyncPolicyRequestUpdateCheckAllowed(_, _))
2200 .Times(1);
2201 EXPECT_TRUE(attempter_.ScheduleUpdates());
2202 // Now there is an update scheduled which means that all subsequent
2203 // |ScheduleUpdates()| should fail.
2204 EXPECT_FALSE(attempter_.ScheduleUpdates());
2205 EXPECT_FALSE(attempter_.ScheduleUpdates());
2206 EXPECT_FALSE(attempter_.ScheduleUpdates());
2207}
2208
2209// Critical tests to always make sure that an update is scheduled. The following
2210// unittest(s) try and cover the correctness in synergy between
2211// |UpdateAttempter| and |UpdateManager|. Also it is good to remember the
2212// actions that happen in the flow when |UpdateAttempter| get callbacked on
2213// |OnUpdateScheduled()| -> (various cases which leads to) -> |ProcessingDone()|
2214void UpdateAttempterTest::TestOnUpdateScheduled() {
2215 // Setup
2216 attempter_.SetWaitingForScheduledCheck(true);
2217 attempter_.DisableUpdate();
2218 attempter_.DisableScheduleUpdates();
2219
2220 // Invocation
2221 attempter_.OnUpdateScheduled(ous_params_.status, ous_params_.params);
2222
2223 // Verify
2224 EXPECT_EQ(ous_params_.exit_status, attempter_.status());
2225 EXPECT_EQ(ous_params_.should_schedule_updates_be_called,
2226 attempter_.WasScheduleUpdatesCalled());
2227 EXPECT_EQ(ous_params_.should_update_be_called, attempter_.WasUpdateCalled());
2228}
2229
2230TEST_F(UpdateAttempterTest, OnUpdatesScheduledFailed) {
2231 // GIVEN failed status.
2232
2233 // THEN update should be scheduled.
2234 ous_params_.should_schedule_updates_be_called = true;
2235
2236 TestOnUpdateScheduled();
2237}
2238
2239TEST_F(UpdateAttempterTest, OnUpdatesScheduledAskMeAgainLater) {
2240 // GIVEN ask me again later status.
2241 ous_params_.status = EvalStatus::kAskMeAgainLater;
2242
2243 // THEN update should be scheduled.
2244 ous_params_.should_schedule_updates_be_called = true;
2245
2246 TestOnUpdateScheduled();
2247}
2248
2249TEST_F(UpdateAttempterTest, OnUpdatesScheduledContinue) {
2250 // GIVEN continue status.
2251 ous_params_.status = EvalStatus::kContinue;
2252
2253 // THEN update should be scheduled.
2254 ous_params_.should_schedule_updates_be_called = true;
2255
2256 TestOnUpdateScheduled();
2257}
2258
2259TEST_F(UpdateAttempterTest, OnUpdatesScheduledSucceededButUpdateDisabledFails) {
2260 // GIVEN updates disabled.
2261 ous_params_.params = {.updates_enabled = false};
2262 // GIVEN succeeded status.
2263 ous_params_.status = EvalStatus::kSucceeded;
2264
2265 // THEN update should not be scheduled.
2266
2267 TestOnUpdateScheduled();
2268}
2269
2270TEST_F(UpdateAttempterTest, OnUpdatesScheduledSucceeded) {
2271 // GIVEN updates enabled.
2272 ous_params_.params = {.updates_enabled = true};
2273 // GIVEN succeeded status.
2274 ous_params_.status = EvalStatus::kSucceeded;
2275
2276 // THEN update should be called indicating status change.
2277 ous_params_.exit_status = UpdateStatus::CHECKING_FOR_UPDATE;
2278 ous_params_.should_update_be_called = true;
2279
2280 TestOnUpdateScheduled();
2281}
2282
Amin Hassani9be122e2019-08-29 09:20:12 -07002283TEST_F(UpdateAttempterTest, IsEnterpriseRollbackInGetStatusDefault) {
2284 UpdateEngineStatus status;
2285 attempter_.GetStatus(&status);
2286 EXPECT_FALSE(status.is_enterprise_rollback);
2287}
2288
2289TEST_F(UpdateAttempterTest, IsEnterpriseRollbackInGetStatusFalse) {
2290 attempter_.install_plan_.reset(new InstallPlan);
2291 attempter_.install_plan_->is_rollback = false;
2292
2293 UpdateEngineStatus status;
2294 attempter_.GetStatus(&status);
2295 EXPECT_FALSE(status.is_enterprise_rollback);
2296}
2297
2298TEST_F(UpdateAttempterTest, IsEnterpriseRollbackInGetStatusTrue) {
2299 attempter_.install_plan_.reset(new InstallPlan);
2300 attempter_.install_plan_->is_rollback = true;
2301
2302 UpdateEngineStatus status;
2303 attempter_.GetStatus(&status);
2304 EXPECT_TRUE(status.is_enterprise_rollback);
2305}
2306
Miriam Polzer0cf1acb2020-04-29 17:39:51 +02002307TEST_F(UpdateAttempterTest, PowerwashInGetStatusDefault) {
2308 UpdateEngineStatus status;
2309 attempter_.GetStatus(&status);
2310 EXPECT_FALSE(status.will_powerwash_after_reboot);
2311}
2312
2313TEST_F(UpdateAttempterTest, PowerwashInGetStatusTrueBecausePowerwashRequired) {
2314 attempter_.install_plan_.reset(new InstallPlan);
2315 attempter_.install_plan_->powerwash_required = true;
2316
2317 UpdateEngineStatus status;
2318 attempter_.GetStatus(&status);
2319 EXPECT_TRUE(status.will_powerwash_after_reboot);
2320}
2321
2322TEST_F(UpdateAttempterTest, PowerwashInGetStatusTrueBecauseRollback) {
2323 attempter_.install_plan_.reset(new InstallPlan);
2324 attempter_.install_plan_->is_rollback = true;
2325
2326 UpdateEngineStatus status;
2327 attempter_.GetStatus(&status);
2328 EXPECT_TRUE(status.will_powerwash_after_reboot);
2329}
2330
Jae Hoon Kim051627a2019-09-03 12:56:32 -07002331TEST_F(UpdateAttempterTest, FutureEolTest) {
2332 EolDate eol_date = std::numeric_limits<int64_t>::max();
Jae Hoon Kim2dfd35d2020-06-02 10:53:13 -07002333 EXPECT_CALL(*prefs_, Exists(kPrefsOmahaEolDate)).WillOnce(Return(true));
Jae Hoon Kim051627a2019-09-03 12:56:32 -07002334 EXPECT_CALL(*prefs_, GetString(kPrefsOmahaEolDate, _))
2335 .WillOnce(
2336 DoAll(SetArgPointee<1>(EolDateToString(eol_date)), Return(true)));
2337
2338 UpdateEngineStatus status;
2339 attempter_.GetStatus(&status);
2340 EXPECT_EQ(eol_date, status.eol_date);
2341}
2342
2343TEST_F(UpdateAttempterTest, PastEolTest) {
2344 EolDate eol_date = 1;
Jae Hoon Kim2dfd35d2020-06-02 10:53:13 -07002345 EXPECT_CALL(*prefs_, Exists(kPrefsOmahaEolDate)).WillOnce(Return(true));
Jae Hoon Kim051627a2019-09-03 12:56:32 -07002346 EXPECT_CALL(*prefs_, GetString(kPrefsOmahaEolDate, _))
2347 .WillOnce(
2348 DoAll(SetArgPointee<1>(EolDateToString(eol_date)), Return(true)));
2349
2350 UpdateEngineStatus status;
2351 attempter_.GetStatus(&status);
2352 EXPECT_EQ(eol_date, status.eol_date);
2353}
2354
2355TEST_F(UpdateAttempterTest, FailedEolTest) {
Jae Hoon Kim2dfd35d2020-06-02 10:53:13 -07002356 EXPECT_CALL(*prefs_, Exists(kPrefsOmahaEolDate)).WillOnce(Return(true));
Jae Hoon Kim051627a2019-09-03 12:56:32 -07002357 EXPECT_CALL(*prefs_, GetString(kPrefsOmahaEolDate, _))
2358 .WillOnce(Return(false));
2359
2360 UpdateEngineStatus status;
2361 attempter_.GetStatus(&status);
Jae Hoon Kim2dfd35d2020-06-02 10:53:13 -07002362 EXPECT_EQ(kEolDateInvalid, status.eol_date);
2363}
2364
2365TEST_F(UpdateAttempterTest, MissingEolTest) {
2366 EXPECT_CALL(*prefs_, Exists(kPrefsOmahaEolDate)).WillOnce(Return(false));
2367
2368 UpdateEngineStatus status;
2369 attempter_.GetStatus(&status);
2370 EXPECT_EQ(kEolDateInvalid, status.eol_date);
Jae Hoon Kim051627a2019-09-03 12:56:32 -07002371}
2372
Andrewe045aef2020-01-08 16:29:22 -08002373TEST_F(UpdateAttempterTest, CalculateDlcParamsInstallTest) {
Andrewe045aef2020-01-08 16:29:22 -08002374 string dlc_id = "dlc0";
Andrew065d78d2020-04-07 15:43:07 -07002375 FakePrefs fake_prefs;
2376 fake_system_state_.set_prefs(&fake_prefs);
Andrewe045aef2020-01-08 16:29:22 -08002377 attempter_.is_install_ = true;
Amin Hassani2b68e6b2020-04-17 10:49:12 -07002378 attempter_.dlc_ids_ = {dlc_id};
Andrewe045aef2020-01-08 16:29:22 -08002379 attempter_.CalculateDlcParams();
2380
2381 OmahaRequestParams* params = fake_system_state_.request_params();
2382 EXPECT_EQ(1, params->dlc_apps_params().count(params->GetDlcAppId(dlc_id)));
2383 OmahaRequestParams::AppParams dlc_app_params =
2384 params->dlc_apps_params().at(params->GetDlcAppId(dlc_id));
2385 EXPECT_STREQ(dlc_id.c_str(), dlc_app_params.name.c_str());
2386 EXPECT_EQ(false, dlc_app_params.send_ping);
2387 // When the DLC gets installed, a ping is not sent, therefore we don't store
2388 // the values sent by Omaha.
Andrew065d78d2020-04-07 15:43:07 -07002389 auto last_active_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002390 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastActive});
Andrew065d78d2020-04-07 15:43:07 -07002391 EXPECT_FALSE(fake_system_state_.prefs()->Exists(last_active_key));
2392 auto last_rollcall_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002393 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastRollcall});
Andrew065d78d2020-04-07 15:43:07 -07002394 EXPECT_FALSE(fake_system_state_.prefs()->Exists(last_rollcall_key));
Andrewe045aef2020-01-08 16:29:22 -08002395}
2396
2397TEST_F(UpdateAttempterTest, CalculateDlcParamsNoPrefFilesTest) {
Andrewe045aef2020-01-08 16:29:22 -08002398 string dlc_id = "dlc0";
Andrew065d78d2020-04-07 15:43:07 -07002399 FakePrefs fake_prefs;
2400 fake_system_state_.set_prefs(&fake_prefs);
Amin Hassani2b68e6b2020-04-17 10:49:12 -07002401 EXPECT_CALL(mock_dlcservice_, GetDlcsToUpdate(_))
Andrewe045aef2020-01-08 16:29:22 -08002402 .WillOnce(
2403 DoAll(SetArgPointee<0>(std::vector<string>({dlc_id})), Return(true)));
2404
2405 attempter_.is_install_ = false;
2406 attempter_.CalculateDlcParams();
2407
2408 OmahaRequestParams* params = fake_system_state_.request_params();
2409 EXPECT_EQ(1, params->dlc_apps_params().count(params->GetDlcAppId(dlc_id)));
2410 OmahaRequestParams::AppParams dlc_app_params =
2411 params->dlc_apps_params().at(params->GetDlcAppId(dlc_id));
2412 EXPECT_STREQ(dlc_id.c_str(), dlc_app_params.name.c_str());
2413
2414 EXPECT_EQ(true, dlc_app_params.send_ping);
2415 EXPECT_EQ(0, dlc_app_params.ping_active);
2416 EXPECT_EQ(-1, dlc_app_params.ping_date_last_active);
2417 EXPECT_EQ(-1, dlc_app_params.ping_date_last_rollcall);
2418}
2419
2420TEST_F(UpdateAttempterTest, CalculateDlcParamsNonParseableValuesTest) {
Andrewe045aef2020-01-08 16:29:22 -08002421 string dlc_id = "dlc0";
Andrew065d78d2020-04-07 15:43:07 -07002422 MemoryPrefs prefs;
2423 fake_system_state_.set_prefs(&prefs);
Amin Hassani2b68e6b2020-04-17 10:49:12 -07002424 EXPECT_CALL(mock_dlcservice_, GetDlcsToUpdate(_))
Andrewe045aef2020-01-08 16:29:22 -08002425 .WillOnce(
2426 DoAll(SetArgPointee<0>(std::vector<string>({dlc_id})), Return(true)));
2427
2428 // Write non numeric values in the metadata files.
Andrew065d78d2020-04-07 15:43:07 -07002429 auto active_key =
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002430 PrefsInterface::CreateSubKey({kDlcPrefsSubDir, dlc_id, kPrefsPingActive});
Andrew065d78d2020-04-07 15:43:07 -07002431 auto last_active_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002432 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastActive});
Andrew065d78d2020-04-07 15:43:07 -07002433 auto last_rollcall_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002434 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastRollcall});
Andrew065d78d2020-04-07 15:43:07 -07002435 fake_system_state_.prefs()->SetString(active_key, "z2yz");
2436 fake_system_state_.prefs()->SetString(last_active_key, "z2yz");
2437 fake_system_state_.prefs()->SetString(last_rollcall_key, "z2yz");
Andrewe045aef2020-01-08 16:29:22 -08002438 attempter_.is_install_ = false;
2439 attempter_.CalculateDlcParams();
2440
2441 OmahaRequestParams* params = fake_system_state_.request_params();
2442 EXPECT_EQ(1, params->dlc_apps_params().count(params->GetDlcAppId(dlc_id)));
2443 OmahaRequestParams::AppParams dlc_app_params =
2444 params->dlc_apps_params().at(params->GetDlcAppId(dlc_id));
2445 EXPECT_STREQ(dlc_id.c_str(), dlc_app_params.name.c_str());
2446
2447 EXPECT_EQ(true, dlc_app_params.send_ping);
2448 EXPECT_EQ(0, dlc_app_params.ping_active);
2449 EXPECT_EQ(-2, dlc_app_params.ping_date_last_active);
2450 EXPECT_EQ(-2, dlc_app_params.ping_date_last_rollcall);
2451}
2452
2453TEST_F(UpdateAttempterTest, CalculateDlcParamsValidValuesTest) {
Andrewe045aef2020-01-08 16:29:22 -08002454 string dlc_id = "dlc0";
Andrew065d78d2020-04-07 15:43:07 -07002455 MemoryPrefs fake_prefs;
2456 fake_system_state_.set_prefs(&fake_prefs);
Amin Hassani2b68e6b2020-04-17 10:49:12 -07002457 EXPECT_CALL(mock_dlcservice_, GetDlcsToUpdate(_))
Andrewe045aef2020-01-08 16:29:22 -08002458 .WillOnce(
2459 DoAll(SetArgPointee<0>(std::vector<string>({dlc_id})), Return(true)));
2460
2461 // Write numeric values in the metadata files.
Andrew065d78d2020-04-07 15:43:07 -07002462 auto active_key =
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002463 PrefsInterface::CreateSubKey({kDlcPrefsSubDir, dlc_id, kPrefsPingActive});
Andrew065d78d2020-04-07 15:43:07 -07002464 auto last_active_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002465 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastActive});
Andrew065d78d2020-04-07 15:43:07 -07002466 auto last_rollcall_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002467 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastRollcall});
Andrew065d78d2020-04-07 15:43:07 -07002468
2469 fake_system_state_.prefs()->SetInt64(active_key, 1);
2470 fake_system_state_.prefs()->SetInt64(last_active_key, 78);
2471 fake_system_state_.prefs()->SetInt64(last_rollcall_key, 99);
Andrewe045aef2020-01-08 16:29:22 -08002472 attempter_.is_install_ = false;
2473 attempter_.CalculateDlcParams();
2474
2475 OmahaRequestParams* params = fake_system_state_.request_params();
2476 EXPECT_EQ(1, params->dlc_apps_params().count(params->GetDlcAppId(dlc_id)));
2477 OmahaRequestParams::AppParams dlc_app_params =
2478 params->dlc_apps_params().at(params->GetDlcAppId(dlc_id));
2479 EXPECT_STREQ(dlc_id.c_str(), dlc_app_params.name.c_str());
2480
2481 EXPECT_EQ(true, dlc_app_params.send_ping);
2482 EXPECT_EQ(1, dlc_app_params.ping_active);
2483 EXPECT_EQ(78, dlc_app_params.ping_date_last_active);
2484 EXPECT_EQ(99, dlc_app_params.ping_date_last_rollcall);
2485}
Andrewa8d7df32020-03-15 20:10:01 -07002486
2487TEST_F(UpdateAttempterTest, CalculateDlcParamsRemoveStaleMetadata) {
Andrewa8d7df32020-03-15 20:10:01 -07002488 string dlc_id = "dlc0";
Andrew065d78d2020-04-07 15:43:07 -07002489 FakePrefs fake_prefs;
2490 fake_system_state_.set_prefs(&fake_prefs);
2491 auto active_key =
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002492 PrefsInterface::CreateSubKey({kDlcPrefsSubDir, dlc_id, kPrefsPingActive});
Andrew065d78d2020-04-07 15:43:07 -07002493 auto last_active_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002494 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastActive});
Andrew065d78d2020-04-07 15:43:07 -07002495 auto last_rollcall_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002496 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastRollcall});
Andrew065d78d2020-04-07 15:43:07 -07002497 fake_system_state_.prefs()->SetInt64(active_key, kPingInactiveValue);
2498 fake_system_state_.prefs()->SetInt64(last_active_key, 0);
2499 fake_system_state_.prefs()->SetInt64(last_rollcall_key, 0);
2500 EXPECT_TRUE(fake_system_state_.prefs()->Exists(active_key));
2501 EXPECT_TRUE(fake_system_state_.prefs()->Exists(last_active_key));
2502 EXPECT_TRUE(fake_system_state_.prefs()->Exists(last_rollcall_key));
Andrewa8d7df32020-03-15 20:10:01 -07002503
Andrew065d78d2020-04-07 15:43:07 -07002504 attempter_.dlc_ids_ = {dlc_id};
2505 attempter_.is_install_ = true;
Andrewa8d7df32020-03-15 20:10:01 -07002506 attempter_.CalculateDlcParams();
2507
Andrew065d78d2020-04-07 15:43:07 -07002508 EXPECT_FALSE(fake_system_state_.prefs()->Exists(last_active_key));
2509 EXPECT_FALSE(fake_system_state_.prefs()->Exists(last_rollcall_key));
2510 // Active key is set on install.
2511 EXPECT_TRUE(fake_system_state_.prefs()->Exists(active_key));
2512 int64_t temp_int;
2513 EXPECT_TRUE(fake_system_state_.prefs()->GetInt64(active_key, &temp_int));
2514 EXPECT_EQ(temp_int, kPingActiveValue);
Andrewa8d7df32020-03-15 20:10:01 -07002515}
2516
2517TEST_F(UpdateAttempterTest, SetDlcActiveValue) {
Andrewa8d7df32020-03-15 20:10:01 -07002518 string dlc_id = "dlc0";
Andrew065d78d2020-04-07 15:43:07 -07002519 FakePrefs fake_prefs;
2520 fake_system_state_.set_prefs(&fake_prefs);
Andrewa8d7df32020-03-15 20:10:01 -07002521 attempter_.SetDlcActiveValue(true, dlc_id);
Andrewa8d7df32020-03-15 20:10:01 -07002522 int64_t temp_int;
Andrew065d78d2020-04-07 15:43:07 -07002523 auto active_key =
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002524 PrefsInterface::CreateSubKey({kDlcPrefsSubDir, dlc_id, kPrefsPingActive});
Andrew065d78d2020-04-07 15:43:07 -07002525 EXPECT_TRUE(fake_system_state_.prefs()->Exists(active_key));
2526 EXPECT_TRUE(fake_system_state_.prefs()->GetInt64(active_key, &temp_int));
Andrewa8d7df32020-03-15 20:10:01 -07002527 EXPECT_EQ(temp_int, kPingActiveValue);
2528}
2529
2530TEST_F(UpdateAttempterTest, SetDlcInactive) {
Andrewa8d7df32020-03-15 20:10:01 -07002531 string dlc_id = "dlc0";
Andrew065d78d2020-04-07 15:43:07 -07002532 MemoryPrefs fake_prefs;
2533 fake_system_state_.set_prefs(&fake_prefs);
2534 auto sub_keys = {
2535 kPrefsPingActive, kPrefsPingLastActive, kPrefsPingLastRollcall};
2536 for (auto& sub_key : sub_keys) {
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002537 auto key = PrefsInterface::CreateSubKey({kDlcPrefsSubDir, dlc_id, sub_key});
Andrew065d78d2020-04-07 15:43:07 -07002538 fake_system_state_.prefs()->SetInt64(key, 1);
2539 EXPECT_TRUE(fake_system_state_.prefs()->Exists(key));
2540 }
Andrewa8d7df32020-03-15 20:10:01 -07002541 attempter_.SetDlcActiveValue(false, dlc_id);
Andrew065d78d2020-04-07 15:43:07 -07002542 for (auto& sub_key : sub_keys) {
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002543 auto key = PrefsInterface::CreateSubKey({kDlcPrefsSubDir, dlc_id, sub_key});
Andrew065d78d2020-04-07 15:43:07 -07002544 EXPECT_FALSE(fake_system_state_.prefs()->Exists(key));
2545 }
Andrewa8d7df32020-03-15 20:10:01 -07002546}
2547
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002548TEST_F(UpdateAttempterTest, GetSuccessfulDlcIds) {
2549 auto dlc_1 = "1", dlc_2 = "2", dlc_3 = "3";
2550 attempter_.omaha_request_params_->set_dlc_apps_params(
2551 {{dlc_1, {.name = dlc_1, .updated = false}},
2552 {dlc_2, {.name = dlc_2}},
2553 {dlc_3, {.name = dlc_3, .updated = false}}});
2554 EXPECT_THAT(attempter_.GetSuccessfulDlcIds(), ElementsAre(dlc_2));
2555}
2556
Darin Petkovf42cc1c2010-09-01 09:03:02 -07002557} // namespace chromeos_update_engine