blob: f3211a0e719e04741a370336ccd200f528d6c8da [file] [log] [blame]
Alex Deymoaea4c1c2015-08-19 20:24:43 -07001//
2// Copyright (C) 2012 The Android Open Source Project
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15//
Darin Petkovf42cc1c2010-09-01 09:03:02 -070016
Amin Hassaniec7bc112020-10-29 16:47:58 -070017#include "update_engine/cros/update_attempter.h"
Alex Deymo2c0db7b2014-11-04 12:23:39 -080018
Ben Chan9abb7632014-08-07 00:10:53 -070019#include <stdint.h>
20
Jae Hoon Kim051627a2019-09-03 12:56:32 -070021#include <limits>
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -070022#include <map>
Ben Chan02f7c1d2014-10-18 15:18:02 -070023#include <memory>
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -070024#include <string>
Jae Hoon Kimedb65502019-06-14 11:52:17 -070025#include <unordered_set>
Ben Chan02f7c1d2014-10-18 15:18:02 -070026
Ben Chan06c76a42014-09-05 08:21:06 -070027#include <base/files/file_util.h>
Miriam Polzeraff72002020-08-27 08:20:39 +020028#include <base/files/scoped_temp_dir.h>
Qijiang Fanb0b6cc22020-10-15 21:54:11 +090029#include <base/task/single_thread_task_executor.h>
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -070030#include <brillo/message_loops/base_message_loop.h>
31#include <brillo/message_loops/message_loop.h>
32#include <brillo/message_loops/message_loop_utils.h>
Darin Petkovf42cc1c2010-09-01 09:03:02 -070033#include <gtest/gtest.h>
Patrick Dubroy7fbbe8a2011-08-01 17:28:22 +020034#include <policy/libpolicy.h>
35#include <policy/mock_device_policy.h>
Marton Hunyadye58bddb2018-04-10 20:27:26 +020036#include <policy/mock_libpolicy.h>
Darin Petkovf42cc1c2010-09-01 09:03:02 -070037
Jae Hoon Kim0ae8fe12019-06-26 14:32:50 -070038#include "update_engine/common/constants.h"
Xiaochu Liu8ba486f2018-11-06 11:14:10 -080039#include "update_engine/common/dlcservice_interface.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080040#include "update_engine/common/fake_clock.h"
41#include "update_engine/common/fake_prefs.h"
Alex Deymo14fd1ec2016-02-24 22:03:57 -080042#include "update_engine/common/mock_action.h"
43#include "update_engine/common/mock_action_processor.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080044#include "update_engine/common/mock_http_fetcher.h"
45#include "update_engine/common/mock_prefs.h"
Amin Hassaniec7bc112020-10-29 16:47:58 -070046#include "update_engine/common/mock_service_observer.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080047#include "update_engine/common/platform_constants.h"
48#include "update_engine/common/prefs.h"
49#include "update_engine/common/test_utils.h"
50#include "update_engine/common/utils.h"
Amin Hassaniec7bc112020-10-29 16:47:58 -070051#include "update_engine/cros/fake_system_state.h"
52#include "update_engine/cros/mock_p2p_manager.h"
53#include "update_engine/cros/mock_payload_state.h"
54#include "update_engine/cros/omaha_utils.h"
Jae Hoon Kim0ae8fe12019-06-26 14:32:50 -070055#include "update_engine/libcurl_http_fetcher.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080056#include "update_engine/payload_consumer/filesystem_verifier_action.h"
57#include "update_engine/payload_consumer/install_plan.h"
58#include "update_engine/payload_consumer/payload_constants.h"
59#include "update_engine/payload_consumer/postinstall_runner_action.h"
Amin Hassani0882a512018-04-05 16:25:44 -070060#include "update_engine/update_boot_flags_action.h"
Jae Hoon Kim504c3cb2019-07-02 11:17:24 -070061#include "update_engine/update_manager/mock_update_manager.h"
Darin Petkovf42cc1c2010-09-01 09:03:02 -070062
David Zeuthen985b1122013-10-09 12:13:15 -070063using base::Time;
64using base::TimeDelta;
Aaron Woodbf5a2522017-10-04 10:58:36 -070065using chromeos_update_manager::EvalStatus;
Jae Hoon Kim504c3cb2019-07-02 11:17:24 -070066using chromeos_update_manager::MockUpdateManager;
Adolfo Victoria497044c2018-07-18 07:51:42 -070067using chromeos_update_manager::StagingSchedule;
Aaron Woodbf5a2522017-10-04 10:58:36 -070068using chromeos_update_manager::UpdateCheckParams;
Adolfo Victoria497044c2018-07-18 07:51:42 -070069using policy::DevicePolicy;
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -070070using std::map;
Darin Petkovf42cc1c2010-09-01 09:03:02 -070071using std::string;
Ben Chan02f7c1d2014-10-18 15:18:02 -070072using std::unique_ptr;
Jae Hoon Kimedb65502019-06-14 11:52:17 -070073using std::unordered_set;
Xiaochu Liu88d90382018-08-29 16:09:11 -070074using std::vector;
Aaron Woodbf5a2522017-10-04 10:58:36 -070075using testing::_;
Andrew065d78d2020-04-07 15:43:07 -070076using testing::Contains;
Darin Petkov36275772010-10-01 11:40:57 -070077using testing::DoAll;
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -070078using testing::ElementsAre;
Aaron Wood7f92e2b2017-08-28 14:51:21 -070079using testing::Field;
Darin Petkovf42cc1c2010-09-01 09:03:02 -070080using testing::InSequence;
Jae Hoon Kimedb65502019-06-14 11:52:17 -070081using testing::Invoke;
Darin Petkov2dd01092010-10-08 15:43:05 -070082using testing::Ne;
Darin Petkov9c096d62010-11-17 14:49:04 -080083using testing::NiceMock;
Amin Hassanid3f4bea2018-04-30 14:52:40 -070084using testing::Pointee;
Darin Petkovf42cc1c2010-09-01 09:03:02 -070085using testing::Property;
86using testing::Return;
Gilad Arnold74b5f552014-10-07 08:17:16 -070087using testing::ReturnPointee;
Marton Hunyadye58bddb2018-04-10 20:27:26 +020088using testing::ReturnRef;
Alex Deymo2c0db7b2014-11-04 12:23:39 -080089using testing::SaveArg;
Ben Chan672c1f52017-10-23 15:41:39 -070090using testing::SetArgPointee;
Aaron Woodbf5a2522017-10-04 10:58:36 -070091using update_engine::UpdateAttemptFlags;
Aaron Wood7f92e2b2017-08-28 14:51:21 -070092using update_engine::UpdateEngineStatus;
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -070093using update_engine::UpdateStatus;
Darin Petkovf42cc1c2010-09-01 09:03:02 -070094
95namespace chromeos_update_engine {
96
Xiaochu Liu8ba486f2018-11-06 11:14:10 -080097namespace {
98
Jae Hoon Kimc437ea52019-07-11 11:20:38 -070099const UpdateStatus kNonIdleUpdateStatuses[] = {
100 UpdateStatus::CHECKING_FOR_UPDATE,
101 UpdateStatus::UPDATE_AVAILABLE,
102 UpdateStatus::DOWNLOADING,
103 UpdateStatus::VERIFYING,
104 UpdateStatus::FINALIZING,
105 UpdateStatus::UPDATED_NEED_REBOOT,
106 UpdateStatus::REPORTING_ERROR_EVENT,
107 UpdateStatus::ATTEMPTING_ROLLBACK,
108 UpdateStatus::DISABLED,
109 UpdateStatus::NEED_PERMISSION_TO_UPDATE,
110};
111
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -0700112struct CheckForUpdateTestParams {
113 // Setups + Inputs:
114 UpdateStatus status = UpdateStatus::IDLE;
115 string app_version = "fake_app_version";
116 string omaha_url = "fake_omaha_url";
117 UpdateAttemptFlags flags = UpdateAttemptFlags::kNone;
118 bool is_official_build = true;
119 bool are_dev_features_enabled = false;
120
121 // Expects:
122 string expected_forced_app_version = "";
123 string expected_forced_omaha_url = "";
Jae Hoon Kim2b73ac22019-07-02 11:17:24 -0700124 bool should_schedule_updates_be_called = true;
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -0700125 bool expected_result = true;
126};
127
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700128struct OnUpdateScheduledTestParams {
129 // Setups + Inputs:
130 UpdateCheckParams params = {};
131 EvalStatus status = EvalStatus::kFailed;
132 // Expects:
133 UpdateStatus exit_status = UpdateStatus::IDLE;
134 bool should_schedule_updates_be_called = false;
135 bool should_update_be_called = false;
136};
137
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -0700138struct ProcessingDoneTestParams {
139 // Setups + Inputs:
140 bool is_install = false;
141 UpdateStatus status = UpdateStatus::CHECKING_FOR_UPDATE;
142 ActionProcessor* processor = nullptr;
143 ErrorCode code = ErrorCode::kSuccess;
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -0700144 map<string, OmahaRequestParams::AppParams> dlc_apps_params;
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -0700145
146 // Expects:
147 const bool kExpectedIsInstall = false;
148 bool should_schedule_updates_be_called = true;
149 UpdateStatus expected_exit_status = UpdateStatus::IDLE;
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -0700150 bool should_install_completed_be_called = false;
151 bool should_update_completed_be_called = false;
152 vector<string> args_to_install_completed;
153 vector<string> args_to_update_completed;
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -0700154};
155
Xiaochu Liu8ba486f2018-11-06 11:14:10 -0800156class MockDlcService : public DlcServiceInterface {
157 public:
Amin Hassani2b68e6b2020-04-17 10:49:12 -0700158 MOCK_METHOD1(GetDlcsToUpdate, bool(vector<string>*));
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -0700159 MOCK_METHOD1(InstallCompleted, bool(const vector<string>&));
160 MOCK_METHOD1(UpdateCompleted, bool(const vector<string>&));
Xiaochu Liu8ba486f2018-11-06 11:14:10 -0800161};
162
163} // namespace
164
Marton Hunyadya0302682018-05-16 18:52:13 +0200165const char kRollbackVersion[] = "10575.39.2";
166
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700167// Test a subclass rather than the main class directly so that we can mock out
Darin Petkovcd1666f2010-09-23 09:53:44 -0700168// methods within the class. There're explicit unit tests for the mocked out
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700169// methods.
170class UpdateAttempterUnderTest : public UpdateAttempter {
171 public:
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";
Amin Hassani68512d42018-07-31 23:52:33 -07001725 response_action.install_plan_.payloads.push_back(
Aaron Wood23bd3392017-10-06 14:48:25 -07001726 {.size = 1234ULL, .type = InstallPayloadType::kFull});
Aaron Wood23bd3392017-10-06 14:48:25 -07001727 // Inform the UpdateAttempter that the OmahaResponseHandlerAction has
1728 // completed, with the deferred-update error code.
1729 attempter_.ActionCompleted(
Amin Hassani68512d42018-07-31 23:52:33 -07001730 nullptr, &response_action, ErrorCode::kOmahaUpdateDeferredPerPolicy);
Aaron Wood23bd3392017-10-06 14:48:25 -07001731 {
1732 UpdateEngineStatus status;
1733 attempter_.GetStatus(&status);
1734 EXPECT_EQ(UpdateStatus::UPDATE_AVAILABLE, status.status);
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001735 EXPECT_TRUE(attempter_.install_plan_);
1736 EXPECT_EQ(attempter_.install_plan_->version, status.new_version);
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001737 EXPECT_EQ(attempter_.install_plan_->payloads[0].size,
Aaron Wood23bd3392017-10-06 14:48:25 -07001738 status.new_size_bytes);
1739 }
1740 // An "error" event should have been created to tell Omaha that the update is
1741 // being deferred.
1742 EXPECT_TRUE(nullptr != attempter_.error_event_);
1743 EXPECT_EQ(OmahaEvent::kTypeUpdateComplete, attempter_.error_event_->type);
1744 EXPECT_EQ(OmahaEvent::kResultUpdateDeferred, attempter_.error_event_->result);
1745 ErrorCode expected_code = static_cast<ErrorCode>(
1746 static_cast<int>(ErrorCode::kOmahaUpdateDeferredPerPolicy) |
1747 static_cast<int>(ErrorCode::kTestOmahaUrlFlag));
1748 EXPECT_EQ(expected_code, attempter_.error_event_->error_code);
1749 // End the processing
1750 attempter_.ProcessingDone(nullptr, ErrorCode::kOmahaUpdateDeferredPerPolicy);
1751 // Validate the state of the attempter.
1752 {
1753 UpdateEngineStatus status;
1754 attempter_.GetStatus(&status);
1755 EXPECT_EQ(UpdateStatus::REPORTING_ERROR_EVENT, status.status);
Amin Hassani68512d42018-07-31 23:52:33 -07001756 EXPECT_EQ(response_action.install_plan_.version, status.new_version);
Amin Hassani68512d42018-07-31 23:52:33 -07001757 EXPECT_EQ(response_action.install_plan_.payloads[0].size,
Aaron Wood23bd3392017-10-06 14:48:25 -07001758 status.new_size_bytes);
1759 }
1760}
1761
1762TEST_F(UpdateAttempterTest, UpdateIsNotRunningWhenUpdateAvailable) {
Jae Hoon Kim75daa382019-07-02 11:17:24 -07001763 // Default construction for |waiting_for_scheduled_check_| is false.
Jae Hoon Kimba2fdce2019-07-11 13:18:58 -07001764 EXPECT_FALSE(attempter_.IsBusyOrUpdateScheduled());
Aaron Wood23bd3392017-10-06 14:48:25 -07001765 // Verify in-progress update with UPDATE_AVAILABLE is running
1766 attempter_.status_ = UpdateStatus::UPDATE_AVAILABLE;
Jae Hoon Kimba2fdce2019-07-11 13:18:58 -07001767 EXPECT_TRUE(attempter_.IsBusyOrUpdateScheduled());
Aaron Wood23bd3392017-10-06 14:48:25 -07001768}
1769
Aaron Woodbf5a2522017-10-04 10:58:36 -07001770TEST_F(UpdateAttempterTest, UpdateAttemptFlagsCachedAtUpdateStart) {
1771 attempter_.SetUpdateAttemptFlags(UpdateAttemptFlags::kFlagRestrictDownload);
1772
1773 UpdateCheckParams params = {.updates_enabled = true};
1774 attempter_.OnUpdateScheduled(EvalStatus::kSucceeded, params);
1775
1776 EXPECT_EQ(UpdateAttemptFlags::kFlagRestrictDownload,
1777 attempter_.GetCurrentUpdateAttemptFlags());
1778}
1779
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001780TEST_F(UpdateAttempterTest, RollbackNotAllowed) {
1781 UpdateCheckParams params = {.updates_enabled = true,
1782 .rollback_allowed = false};
1783 attempter_.OnUpdateScheduled(EvalStatus::kSucceeded, params);
1784 EXPECT_FALSE(fake_system_state_.request_params()->rollback_allowed());
1785}
1786
1787TEST_F(UpdateAttempterTest, RollbackAllowed) {
1788 UpdateCheckParams params = {.updates_enabled = true,
1789 .rollback_allowed = true};
1790 attempter_.OnUpdateScheduled(EvalStatus::kSucceeded, params);
1791 EXPECT_TRUE(fake_system_state_.request_params()->rollback_allowed());
1792}
1793
Aaron Wood081c0232017-10-19 17:14:58 -07001794TEST_F(UpdateAttempterTest, InteractiveUpdateUsesPassedRestrictions) {
1795 attempter_.SetUpdateAttemptFlags(UpdateAttemptFlags::kFlagRestrictDownload);
1796
1797 attempter_.CheckForUpdate("", "", UpdateAttemptFlags::kNone);
1798 EXPECT_EQ(UpdateAttemptFlags::kNone,
1799 attempter_.GetCurrentUpdateAttemptFlags());
1800}
1801
1802TEST_F(UpdateAttempterTest, NonInteractiveUpdateUsesSetRestrictions) {
1803 attempter_.SetUpdateAttemptFlags(UpdateAttemptFlags::kNone);
1804
1805 // This tests that when CheckForUpdate() is called with the non-interactive
1806 // flag set, that it doesn't change the current UpdateAttemptFlags.
1807 attempter_.CheckForUpdate("",
1808 "",
1809 UpdateAttemptFlags::kFlagNonInteractive |
1810 UpdateAttemptFlags::kFlagRestrictDownload);
1811 EXPECT_EQ(UpdateAttemptFlags::kNone,
1812 attempter_.GetCurrentUpdateAttemptFlags());
1813}
1814
Marton Hunyadye58bddb2018-04-10 20:27:26 +02001815void UpdateAttempterTest::ResetRollbackHappenedStart(bool is_consumer,
1816 bool is_policy_loaded,
1817 bool expected_reset) {
1818 EXPECT_CALL(*fake_system_state_.mock_payload_state(), GetRollbackHappened())
1819 .WillRepeatedly(Return(true));
1820 auto mock_policy_provider =
1821 std::make_unique<NiceMock<policy::MockPolicyProvider>>();
1822 EXPECT_CALL(*mock_policy_provider, IsConsumerDevice())
1823 .WillRepeatedly(Return(is_consumer));
1824 EXPECT_CALL(*mock_policy_provider, device_policy_is_loaded())
1825 .WillRepeatedly(Return(is_policy_loaded));
1826 const policy::MockDevicePolicy device_policy;
1827 EXPECT_CALL(*mock_policy_provider, GetDevicePolicy())
1828 .WillRepeatedly(ReturnRef(device_policy));
1829 EXPECT_CALL(*fake_system_state_.mock_payload_state(),
1830 SetRollbackHappened(false))
1831 .Times(expected_reset ? 1 : 0);
1832 attempter_.policy_provider_ = std::move(mock_policy_provider);
Amin Hassanie8153632020-10-27 15:11:28 -07001833 attempter_.Update({});
Marton Hunyadye58bddb2018-04-10 20:27:26 +02001834 ScheduleQuitMainLoop();
1835}
1836
1837TEST_F(UpdateAttempterTest, ResetRollbackHappenedOobe) {
1838 loop_.PostTask(FROM_HERE,
1839 base::Bind(&UpdateAttempterTest::ResetRollbackHappenedStart,
1840 base::Unretained(this),
1841 /*is_consumer=*/false,
1842 /*is_policy_loaded=*/false,
1843 /*expected_reset=*/false));
1844 loop_.Run();
1845}
1846
1847TEST_F(UpdateAttempterTest, ResetRollbackHappenedConsumer) {
1848 loop_.PostTask(FROM_HERE,
1849 base::Bind(&UpdateAttempterTest::ResetRollbackHappenedStart,
1850 base::Unretained(this),
1851 /*is_consumer=*/true,
1852 /*is_policy_loaded=*/false,
1853 /*expected_reset=*/true));
1854 loop_.Run();
1855}
1856
1857TEST_F(UpdateAttempterTest, ResetRollbackHappenedEnterprise) {
1858 loop_.PostTask(FROM_HERE,
1859 base::Bind(&UpdateAttempterTest::ResetRollbackHappenedStart,
1860 base::Unretained(this),
1861 /*is_consumer=*/false,
1862 /*is_policy_loaded=*/true,
1863 /*expected_reset=*/true));
1864 loop_.Run();
1865}
1866
Marton Hunyady199152d2018-05-07 19:08:48 +02001867TEST_F(UpdateAttempterTest, SetRollbackHappenedRollback) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001868 attempter_.install_plan_.reset(new InstallPlan);
1869 attempter_.install_plan_->is_rollback = true;
Marton Hunyady199152d2018-05-07 19:08:48 +02001870
1871 EXPECT_CALL(*fake_system_state_.mock_payload_state(),
1872 SetRollbackHappened(true))
1873 .Times(1);
1874 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1875}
1876
1877TEST_F(UpdateAttempterTest, SetRollbackHappenedNotRollback) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001878 attempter_.install_plan_.reset(new InstallPlan);
1879 attempter_.install_plan_->is_rollback = false;
Marton Hunyady199152d2018-05-07 19:08:48 +02001880
1881 EXPECT_CALL(*fake_system_state_.mock_payload_state(),
1882 SetRollbackHappened(true))
1883 .Times(0);
1884 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1885}
1886
Marton Hunyadya0302682018-05-16 18:52:13 +02001887TEST_F(UpdateAttempterTest, RollbackMetricsRollbackSuccess) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001888 attempter_.install_plan_.reset(new InstallPlan);
1889 attempter_.install_plan_->is_rollback = true;
1890 attempter_.install_plan_->version = kRollbackVersion;
Marton Hunyadya0302682018-05-16 18:52:13 +02001891
1892 EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
1893 ReportEnterpriseRollbackMetrics(true, kRollbackVersion))
1894 .Times(1);
1895 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1896}
1897
1898TEST_F(UpdateAttempterTest, RollbackMetricsNotRollbackSuccess) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001899 attempter_.install_plan_.reset(new InstallPlan);
1900 attempter_.install_plan_->is_rollback = false;
1901 attempter_.install_plan_->version = kRollbackVersion;
Marton Hunyadya0302682018-05-16 18:52:13 +02001902
1903 EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
1904 ReportEnterpriseRollbackMetrics(_, _))
1905 .Times(0);
1906 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1907}
1908
1909TEST_F(UpdateAttempterTest, RollbackMetricsRollbackFailure) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001910 attempter_.install_plan_.reset(new InstallPlan);
1911 attempter_.install_plan_->is_rollback = true;
1912 attempter_.install_plan_->version = kRollbackVersion;
Marton Hunyadya0302682018-05-16 18:52:13 +02001913
1914 EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
1915 ReportEnterpriseRollbackMetrics(false, kRollbackVersion))
1916 .Times(1);
1917 MockAction action;
1918 attempter_.CreatePendingErrorEvent(&action, ErrorCode::kRollbackNotPossible);
1919 attempter_.ProcessingDone(nullptr, ErrorCode::kRollbackNotPossible);
1920}
1921
1922TEST_F(UpdateAttempterTest, RollbackMetricsNotRollbackFailure) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001923 attempter_.install_plan_.reset(new InstallPlan);
1924 attempter_.install_plan_->is_rollback = false;
1925 attempter_.install_plan_->version = kRollbackVersion;
Marton Hunyadya0302682018-05-16 18:52:13 +02001926
1927 EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
1928 ReportEnterpriseRollbackMetrics(_, _))
1929 .Times(0);
1930 MockAction action;
1931 attempter_.CreatePendingErrorEvent(&action, ErrorCode::kRollbackNotPossible);
1932 attempter_.ProcessingDone(nullptr, ErrorCode::kRollbackNotPossible);
1933}
1934
May Lippert60aa3ca2018-08-15 16:55:29 -07001935TEST_F(UpdateAttempterTest, TimeToUpdateAppliedMetricFailure) {
1936 EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
1937 ReportEnterpriseUpdateSeenToDownloadDays(_, _))
1938 .Times(0);
1939 attempter_.ProcessingDone(nullptr, ErrorCode::kOmahaUpdateDeferredPerPolicy);
1940}
1941
1942TEST_F(UpdateAttempterTest, TimeToUpdateAppliedOnNonEnterprise) {
1943 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
1944 fake_system_state_.set_device_policy(device_policy.get());
1945 // Make device policy return that this is not enterprise enrolled
1946 EXPECT_CALL(*device_policy, IsEnterpriseEnrolled()).WillOnce(Return(false));
1947
1948 // Ensure that the metric is not recorded.
1949 EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
1950 ReportEnterpriseUpdateSeenToDownloadDays(_, _))
1951 .Times(0);
1952 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1953}
1954
1955TEST_F(UpdateAttempterTest,
1956 TimeToUpdateAppliedWithTimeRestrictionMetricSuccess) {
1957 constexpr int kDaysToUpdate = 15;
1958 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
1959 fake_system_state_.set_device_policy(device_policy.get());
1960 // Make device policy return that this is enterprise enrolled
1961 EXPECT_CALL(*device_policy, IsEnterpriseEnrolled()).WillOnce(Return(true));
1962 // Pretend that there's a time restriction policy in place
1963 EXPECT_CALL(*device_policy, GetDisallowedTimeIntervals(_))
1964 .WillOnce(Return(true));
1965
1966 FakePrefs fake_prefs;
1967 Time update_first_seen_at = Time::Now();
1968 fake_prefs.SetInt64(kPrefsUpdateFirstSeenAt,
1969 update_first_seen_at.ToInternalValue());
1970
1971 FakeClock fake_clock;
1972 Time update_finished_at =
1973 update_first_seen_at + TimeDelta::FromDays(kDaysToUpdate);
1974 fake_clock.SetWallclockTime(update_finished_at);
1975
1976 fake_system_state_.set_clock(&fake_clock);
1977 fake_system_state_.set_prefs(&fake_prefs);
1978
1979 EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
1980 ReportEnterpriseUpdateSeenToDownloadDays(true, kDaysToUpdate))
1981 .Times(1);
1982 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1983}
1984
1985TEST_F(UpdateAttempterTest,
1986 TimeToUpdateAppliedWithoutTimeRestrictionMetricSuccess) {
1987 constexpr int kDaysToUpdate = 15;
1988 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
1989 fake_system_state_.set_device_policy(device_policy.get());
1990 // Make device policy return that this is enterprise enrolled
1991 EXPECT_CALL(*device_policy, IsEnterpriseEnrolled()).WillOnce(Return(true));
1992 // Pretend that there's no time restriction policy in place
1993 EXPECT_CALL(*device_policy, GetDisallowedTimeIntervals(_))
1994 .WillOnce(Return(false));
1995
1996 FakePrefs fake_prefs;
1997 Time update_first_seen_at = Time::Now();
1998 fake_prefs.SetInt64(kPrefsUpdateFirstSeenAt,
1999 update_first_seen_at.ToInternalValue());
2000
2001 FakeClock fake_clock;
2002 Time update_finished_at =
2003 update_first_seen_at + TimeDelta::FromDays(kDaysToUpdate);
2004 fake_clock.SetWallclockTime(update_finished_at);
2005
2006 fake_system_state_.set_clock(&fake_clock);
2007 fake_system_state_.set_prefs(&fake_prefs);
2008
2009 EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
2010 ReportEnterpriseUpdateSeenToDownloadDays(false, kDaysToUpdate))
2011 .Times(1);
2012 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
2013}
2014
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002015TEST_F(UpdateAttempterTest, ProcessingDoneUpdated) {
2016 // GIVEN an update finished.
2017
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002018 // THEN update_engine should call update completion.
2019 pd_params_.should_update_completed_be_called = true;
2020 // THEN need reboot since update applied.
2021 pd_params_.expected_exit_status = UpdateStatus::UPDATED_NEED_REBOOT;
2022 // THEN install indication should be false.
2023
2024 TestProcessingDone();
2025}
2026
2027TEST_F(UpdateAttempterTest, ProcessingDoneUpdatedDlcFilter) {
2028 // GIVEN an update finished.
2029 // GIVEN DLC |AppParams| list.
2030 auto dlc_1 = "dlc_1", dlc_2 = "dlc_2";
2031 pd_params_.dlc_apps_params = {{dlc_1, {.name = dlc_1, .updated = false}},
2032 {dlc_2, {.name = dlc_2}}};
2033
2034 // THEN update_engine should call update completion.
2035 pd_params_.should_update_completed_be_called = true;
2036 pd_params_.args_to_update_completed = {dlc_2};
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002037 // THEN need reboot since update applied.
2038 pd_params_.expected_exit_status = UpdateStatus::UPDATED_NEED_REBOOT;
2039 // THEN install indication should be false.
2040
2041 TestProcessingDone();
2042}
2043
2044TEST_F(UpdateAttempterTest, ProcessingDoneInstalled) {
2045 // GIVEN an install finished.
2046 pd_params_.is_install = true;
2047
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002048 // THEN update_engine should call install completion.
2049 pd_params_.should_install_completed_be_called = true;
2050 // THEN go idle.
2051 // THEN install indication should be false.
2052
2053 TestProcessingDone();
2054}
2055
2056TEST_F(UpdateAttempterTest, ProcessingDoneInstalledDlcFilter) {
2057 // GIVEN an install finished.
2058 pd_params_.is_install = true;
2059 // GIVEN DLC |AppParams| list.
2060 auto dlc_1 = "dlc_1", dlc_2 = "dlc_2";
2061 pd_params_.dlc_apps_params = {{dlc_1, {.name = dlc_1, .updated = false}},
2062 {dlc_2, {.name = dlc_2}}};
2063
2064 // THEN update_engine should call install completion.
2065 pd_params_.should_install_completed_be_called = true;
2066 pd_params_.args_to_install_completed = {dlc_2};
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002067 // THEN go idle.
2068 // THEN install indication should be false.
2069
2070 TestProcessingDone();
2071}
2072
2073TEST_F(UpdateAttempterTest, ProcessingDoneInstallReportingError) {
2074 // GIVEN an install finished.
2075 pd_params_.is_install = true;
2076 // GIVEN a reporting error occurred.
2077 pd_params_.status = UpdateStatus::REPORTING_ERROR_EVENT;
2078
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002079 // THEN update_engine should not call install completion.
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002080 // THEN go idle.
2081 // THEN install indication should be false.
2082
2083 TestProcessingDone();
2084}
2085
2086TEST_F(UpdateAttempterTest, ProcessingDoneNoUpdate) {
2087 // GIVEN an update finished.
2088 // GIVEN an action error occured.
2089 pd_params_.code = ErrorCode::kNoUpdate;
2090
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002091 // THEN update_engine should not call update completion.
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002092 // THEN go idle.
2093 // THEN install indication should be false.
2094
2095 TestProcessingDone();
2096}
2097
2098TEST_F(UpdateAttempterTest, ProcessingDoneNoInstall) {
2099 // GIVEN an install finished.
2100 pd_params_.is_install = true;
2101 // GIVEN an action error occured.
2102 pd_params_.code = ErrorCode::kNoUpdate;
2103
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002104 // THEN update_engine should not call install completion.
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002105 // THEN go idle.
2106 // THEN install indication should be false.
2107
2108 TestProcessingDone();
2109}
2110
2111TEST_F(UpdateAttempterTest, ProcessingDoneUpdateError) {
2112 // GIVEN an update finished.
2113 // GIVEN an action error occured.
2114 pd_params_.code = ErrorCode::kError;
2115 // GIVEN an event error is set.
2116 attempter_.error_event_.reset(new OmahaEvent(OmahaEvent::kTypeUpdateComplete,
2117 OmahaEvent::kResultError,
2118 ErrorCode::kError));
2119
2120 // THEN indicate a error event.
2121 pd_params_.expected_exit_status = UpdateStatus::REPORTING_ERROR_EVENT;
2122 // THEN install indication should be false.
2123
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002124 // THEN update_engine should not call update completion.
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002125 // THEN expect critical actions of |ScheduleErrorEventAction()|.
2126 EXPECT_CALL(*processor_, EnqueueAction(Pointee(_))).Times(1);
2127 EXPECT_CALL(*processor_, StartProcessing()).Times(1);
2128 // THEN |ScheduleUpdates()| will be called next |ProcessingDone()| so skip.
2129 pd_params_.should_schedule_updates_be_called = false;
2130
2131 TestProcessingDone();
2132}
2133
2134TEST_F(UpdateAttempterTest, ProcessingDoneInstallError) {
2135 // GIVEN an install finished.
2136 pd_params_.is_install = true;
2137 // GIVEN an action error occured.
2138 pd_params_.code = ErrorCode::kError;
2139 // GIVEN an event error is set.
2140 attempter_.error_event_.reset(new OmahaEvent(OmahaEvent::kTypeUpdateComplete,
2141 OmahaEvent::kResultError,
2142 ErrorCode::kError));
2143
2144 // THEN indicate a error event.
2145 pd_params_.expected_exit_status = UpdateStatus::REPORTING_ERROR_EVENT;
2146 // THEN install indication should be false.
2147
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002148 // THEN update_engine should not call install completion.
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002149 // THEN expect critical actions of |ScheduleErrorEventAction()|.
2150 EXPECT_CALL(*processor_, EnqueueAction(Pointee(_))).Times(1);
2151 EXPECT_CALL(*processor_, StartProcessing()).Times(1);
2152 // THEN |ScheduleUpdates()| will be called next |ProcessingDone()| so skip.
2153 pd_params_.should_schedule_updates_be_called = false;
2154
2155 TestProcessingDone();
2156}
2157
Amr Aboelkher21ac9962019-05-15 14:50:05 +02002158void UpdateAttempterTest::UpdateToQuickFixBuildStart(bool set_token) {
2159 // Tests that checks if |device_quick_fix_build_token| arrives when
2160 // policy is set and the device is enterprise enrolled based on |set_token|.
2161 string token = set_token ? "some_token" : "";
Askar Aitzhan570ca872019-04-24 11:16:12 +02002162 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
2163 fake_system_state_.set_device_policy(device_policy.get());
Askar Aitzhan570ca872019-04-24 11:16:12 +02002164 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
Amr Aboelkher21ac9962019-05-15 14:50:05 +02002165
2166 if (set_token)
2167 EXPECT_CALL(*device_policy, GetDeviceQuickFixBuildToken(_))
2168 .WillOnce(DoAll(SetArgPointee<0>(token), Return(true)));
2169 else
2170 EXPECT_CALL(*device_policy, GetDeviceQuickFixBuildToken(_))
2171 .WillOnce(Return(false));
Askar Aitzhan570ca872019-04-24 11:16:12 +02002172 attempter_.policy_provider_.reset(
2173 new policy::PolicyProvider(std::move(device_policy)));
Amin Hassanie8153632020-10-27 15:11:28 -07002174 attempter_.Update({});
Askar Aitzhan570ca872019-04-24 11:16:12 +02002175
Amr Aboelkher21ac9962019-05-15 14:50:05 +02002176 EXPECT_EQ(token, attempter_.omaha_request_params_->autoupdate_token());
Askar Aitzhan570ca872019-04-24 11:16:12 +02002177 ScheduleQuitMainLoop();
2178}
2179
Amr Aboelkher21ac9962019-05-15 14:50:05 +02002180TEST_F(UpdateAttempterTest,
2181 QuickFixTokenWhenDeviceIsEnterpriseEnrolledAndPolicyIsSet) {
Askar Aitzhan570ca872019-04-24 11:16:12 +02002182 loop_.PostTask(FROM_HERE,
2183 base::Bind(&UpdateAttempterTest::UpdateToQuickFixBuildStart,
Amr Aboelkher21ac9962019-05-15 14:50:05 +02002184 base::Unretained(this),
2185 /*set_token=*/true));
2186 loop_.Run();
2187}
2188
2189TEST_F(UpdateAttempterTest, EmptyQuickFixToken) {
2190 loop_.PostTask(FROM_HERE,
2191 base::Bind(&UpdateAttempterTest::UpdateToQuickFixBuildStart,
2192 base::Unretained(this),
2193 /*set_token=*/false));
Askar Aitzhan570ca872019-04-24 11:16:12 +02002194 loop_.Run();
2195}
2196
Jae Hoon Kim75daa382019-07-02 11:17:24 -07002197TEST_F(UpdateAttempterTest, ScheduleUpdateSpamHandlerTest) {
2198 EXPECT_CALL(mock_update_manager_, AsyncPolicyRequestUpdateCheckAllowed(_, _))
2199 .Times(1);
2200 EXPECT_TRUE(attempter_.ScheduleUpdates());
2201 // Now there is an update scheduled which means that all subsequent
2202 // |ScheduleUpdates()| should fail.
2203 EXPECT_FALSE(attempter_.ScheduleUpdates());
2204 EXPECT_FALSE(attempter_.ScheduleUpdates());
2205 EXPECT_FALSE(attempter_.ScheduleUpdates());
2206}
2207
2208// Critical tests to always make sure that an update is scheduled. The following
2209// unittest(s) try and cover the correctness in synergy between
2210// |UpdateAttempter| and |UpdateManager|. Also it is good to remember the
2211// actions that happen in the flow when |UpdateAttempter| get callbacked on
2212// |OnUpdateScheduled()| -> (various cases which leads to) -> |ProcessingDone()|
2213void UpdateAttempterTest::TestOnUpdateScheduled() {
2214 // Setup
2215 attempter_.SetWaitingForScheduledCheck(true);
2216 attempter_.DisableUpdate();
2217 attempter_.DisableScheduleUpdates();
2218
2219 // Invocation
2220 attempter_.OnUpdateScheduled(ous_params_.status, ous_params_.params);
2221
2222 // Verify
2223 EXPECT_EQ(ous_params_.exit_status, attempter_.status());
2224 EXPECT_EQ(ous_params_.should_schedule_updates_be_called,
2225 attempter_.WasScheduleUpdatesCalled());
2226 EXPECT_EQ(ous_params_.should_update_be_called, attempter_.WasUpdateCalled());
2227}
2228
2229TEST_F(UpdateAttempterTest, OnUpdatesScheduledFailed) {
2230 // GIVEN failed status.
2231
2232 // THEN update should be scheduled.
2233 ous_params_.should_schedule_updates_be_called = true;
2234
2235 TestOnUpdateScheduled();
2236}
2237
2238TEST_F(UpdateAttempterTest, OnUpdatesScheduledAskMeAgainLater) {
2239 // GIVEN ask me again later status.
2240 ous_params_.status = EvalStatus::kAskMeAgainLater;
2241
2242 // THEN update should be scheduled.
2243 ous_params_.should_schedule_updates_be_called = true;
2244
2245 TestOnUpdateScheduled();
2246}
2247
2248TEST_F(UpdateAttempterTest, OnUpdatesScheduledContinue) {
2249 // GIVEN continue status.
2250 ous_params_.status = EvalStatus::kContinue;
2251
2252 // THEN update should be scheduled.
2253 ous_params_.should_schedule_updates_be_called = true;
2254
2255 TestOnUpdateScheduled();
2256}
2257
2258TEST_F(UpdateAttempterTest, OnUpdatesScheduledSucceededButUpdateDisabledFails) {
2259 // GIVEN updates disabled.
2260 ous_params_.params = {.updates_enabled = false};
2261 // GIVEN succeeded status.
2262 ous_params_.status = EvalStatus::kSucceeded;
2263
2264 // THEN update should not be scheduled.
2265
2266 TestOnUpdateScheduled();
2267}
2268
2269TEST_F(UpdateAttempterTest, OnUpdatesScheduledSucceeded) {
2270 // GIVEN updates enabled.
2271 ous_params_.params = {.updates_enabled = true};
2272 // GIVEN succeeded status.
2273 ous_params_.status = EvalStatus::kSucceeded;
2274
2275 // THEN update should be called indicating status change.
2276 ous_params_.exit_status = UpdateStatus::CHECKING_FOR_UPDATE;
2277 ous_params_.should_update_be_called = true;
2278
2279 TestOnUpdateScheduled();
2280}
2281
Amin Hassani9be122e2019-08-29 09:20:12 -07002282TEST_F(UpdateAttempterTest, IsEnterpriseRollbackInGetStatusDefault) {
2283 UpdateEngineStatus status;
2284 attempter_.GetStatus(&status);
2285 EXPECT_FALSE(status.is_enterprise_rollback);
2286}
2287
2288TEST_F(UpdateAttempterTest, IsEnterpriseRollbackInGetStatusFalse) {
2289 attempter_.install_plan_.reset(new InstallPlan);
2290 attempter_.install_plan_->is_rollback = false;
2291
2292 UpdateEngineStatus status;
2293 attempter_.GetStatus(&status);
2294 EXPECT_FALSE(status.is_enterprise_rollback);
2295}
2296
2297TEST_F(UpdateAttempterTest, IsEnterpriseRollbackInGetStatusTrue) {
2298 attempter_.install_plan_.reset(new InstallPlan);
2299 attempter_.install_plan_->is_rollback = true;
2300
2301 UpdateEngineStatus status;
2302 attempter_.GetStatus(&status);
2303 EXPECT_TRUE(status.is_enterprise_rollback);
2304}
2305
Miriam Polzer0cf1acb2020-04-29 17:39:51 +02002306TEST_F(UpdateAttempterTest, PowerwashInGetStatusDefault) {
2307 UpdateEngineStatus status;
2308 attempter_.GetStatus(&status);
2309 EXPECT_FALSE(status.will_powerwash_after_reboot);
2310}
2311
2312TEST_F(UpdateAttempterTest, PowerwashInGetStatusTrueBecausePowerwashRequired) {
2313 attempter_.install_plan_.reset(new InstallPlan);
2314 attempter_.install_plan_->powerwash_required = true;
2315
2316 UpdateEngineStatus status;
2317 attempter_.GetStatus(&status);
2318 EXPECT_TRUE(status.will_powerwash_after_reboot);
2319}
2320
2321TEST_F(UpdateAttempterTest, PowerwashInGetStatusTrueBecauseRollback) {
2322 attempter_.install_plan_.reset(new InstallPlan);
2323 attempter_.install_plan_->is_rollback = true;
2324
2325 UpdateEngineStatus status;
2326 attempter_.GetStatus(&status);
2327 EXPECT_TRUE(status.will_powerwash_after_reboot);
2328}
2329
Jae Hoon Kim051627a2019-09-03 12:56:32 -07002330TEST_F(UpdateAttempterTest, FutureEolTest) {
2331 EolDate eol_date = std::numeric_limits<int64_t>::max();
Jae Hoon Kim2dfd35d2020-06-02 10:53:13 -07002332 EXPECT_CALL(*prefs_, Exists(kPrefsOmahaEolDate)).WillOnce(Return(true));
Jae Hoon Kim051627a2019-09-03 12:56:32 -07002333 EXPECT_CALL(*prefs_, GetString(kPrefsOmahaEolDate, _))
2334 .WillOnce(
2335 DoAll(SetArgPointee<1>(EolDateToString(eol_date)), Return(true)));
2336
2337 UpdateEngineStatus status;
2338 attempter_.GetStatus(&status);
2339 EXPECT_EQ(eol_date, status.eol_date);
2340}
2341
2342TEST_F(UpdateAttempterTest, PastEolTest) {
2343 EolDate eol_date = 1;
Jae Hoon Kim2dfd35d2020-06-02 10:53:13 -07002344 EXPECT_CALL(*prefs_, Exists(kPrefsOmahaEolDate)).WillOnce(Return(true));
Jae Hoon Kim051627a2019-09-03 12:56:32 -07002345 EXPECT_CALL(*prefs_, GetString(kPrefsOmahaEolDate, _))
2346 .WillOnce(
2347 DoAll(SetArgPointee<1>(EolDateToString(eol_date)), Return(true)));
2348
2349 UpdateEngineStatus status;
2350 attempter_.GetStatus(&status);
2351 EXPECT_EQ(eol_date, status.eol_date);
2352}
2353
2354TEST_F(UpdateAttempterTest, FailedEolTest) {
Jae Hoon Kim2dfd35d2020-06-02 10:53:13 -07002355 EXPECT_CALL(*prefs_, Exists(kPrefsOmahaEolDate)).WillOnce(Return(true));
Jae Hoon Kim051627a2019-09-03 12:56:32 -07002356 EXPECT_CALL(*prefs_, GetString(kPrefsOmahaEolDate, _))
2357 .WillOnce(Return(false));
2358
2359 UpdateEngineStatus status;
2360 attempter_.GetStatus(&status);
Jae Hoon Kim2dfd35d2020-06-02 10:53:13 -07002361 EXPECT_EQ(kEolDateInvalid, status.eol_date);
2362}
2363
2364TEST_F(UpdateAttempterTest, MissingEolTest) {
2365 EXPECT_CALL(*prefs_, Exists(kPrefsOmahaEolDate)).WillOnce(Return(false));
2366
2367 UpdateEngineStatus status;
2368 attempter_.GetStatus(&status);
2369 EXPECT_EQ(kEolDateInvalid, status.eol_date);
Jae Hoon Kim051627a2019-09-03 12:56:32 -07002370}
2371
Andrewe045aef2020-01-08 16:29:22 -08002372TEST_F(UpdateAttempterTest, CalculateDlcParamsInstallTest) {
Andrewe045aef2020-01-08 16:29:22 -08002373 string dlc_id = "dlc0";
Andrew065d78d2020-04-07 15:43:07 -07002374 FakePrefs fake_prefs;
2375 fake_system_state_.set_prefs(&fake_prefs);
Andrewe045aef2020-01-08 16:29:22 -08002376 attempter_.is_install_ = true;
Amin Hassani2b68e6b2020-04-17 10:49:12 -07002377 attempter_.dlc_ids_ = {dlc_id};
Andrewe045aef2020-01-08 16:29:22 -08002378 attempter_.CalculateDlcParams();
2379
2380 OmahaRequestParams* params = fake_system_state_.request_params();
2381 EXPECT_EQ(1, params->dlc_apps_params().count(params->GetDlcAppId(dlc_id)));
2382 OmahaRequestParams::AppParams dlc_app_params =
2383 params->dlc_apps_params().at(params->GetDlcAppId(dlc_id));
2384 EXPECT_STREQ(dlc_id.c_str(), dlc_app_params.name.c_str());
2385 EXPECT_EQ(false, dlc_app_params.send_ping);
2386 // When the DLC gets installed, a ping is not sent, therefore we don't store
2387 // the values sent by Omaha.
Andrew065d78d2020-04-07 15:43:07 -07002388 auto last_active_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002389 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastActive});
Andrew065d78d2020-04-07 15:43:07 -07002390 EXPECT_FALSE(fake_system_state_.prefs()->Exists(last_active_key));
2391 auto last_rollcall_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002392 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastRollcall});
Andrew065d78d2020-04-07 15:43:07 -07002393 EXPECT_FALSE(fake_system_state_.prefs()->Exists(last_rollcall_key));
Andrewe045aef2020-01-08 16:29:22 -08002394}
2395
2396TEST_F(UpdateAttempterTest, CalculateDlcParamsNoPrefFilesTest) {
Andrewe045aef2020-01-08 16:29:22 -08002397 string dlc_id = "dlc0";
Andrew065d78d2020-04-07 15:43:07 -07002398 FakePrefs fake_prefs;
2399 fake_system_state_.set_prefs(&fake_prefs);
Amin Hassani2b68e6b2020-04-17 10:49:12 -07002400 EXPECT_CALL(mock_dlcservice_, GetDlcsToUpdate(_))
Andrewe045aef2020-01-08 16:29:22 -08002401 .WillOnce(
2402 DoAll(SetArgPointee<0>(std::vector<string>({dlc_id})), Return(true)));
2403
2404 attempter_.is_install_ = false;
2405 attempter_.CalculateDlcParams();
2406
2407 OmahaRequestParams* params = fake_system_state_.request_params();
2408 EXPECT_EQ(1, params->dlc_apps_params().count(params->GetDlcAppId(dlc_id)));
2409 OmahaRequestParams::AppParams dlc_app_params =
2410 params->dlc_apps_params().at(params->GetDlcAppId(dlc_id));
2411 EXPECT_STREQ(dlc_id.c_str(), dlc_app_params.name.c_str());
2412
2413 EXPECT_EQ(true, dlc_app_params.send_ping);
2414 EXPECT_EQ(0, dlc_app_params.ping_active);
2415 EXPECT_EQ(-1, dlc_app_params.ping_date_last_active);
2416 EXPECT_EQ(-1, dlc_app_params.ping_date_last_rollcall);
2417}
2418
2419TEST_F(UpdateAttempterTest, CalculateDlcParamsNonParseableValuesTest) {
Andrewe045aef2020-01-08 16:29:22 -08002420 string dlc_id = "dlc0";
Andrew065d78d2020-04-07 15:43:07 -07002421 MemoryPrefs prefs;
2422 fake_system_state_.set_prefs(&prefs);
Amin Hassani2b68e6b2020-04-17 10:49:12 -07002423 EXPECT_CALL(mock_dlcservice_, GetDlcsToUpdate(_))
Andrewe045aef2020-01-08 16:29:22 -08002424 .WillOnce(
2425 DoAll(SetArgPointee<0>(std::vector<string>({dlc_id})), Return(true)));
2426
2427 // Write non numeric values in the metadata files.
Andrew065d78d2020-04-07 15:43:07 -07002428 auto active_key =
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002429 PrefsInterface::CreateSubKey({kDlcPrefsSubDir, dlc_id, kPrefsPingActive});
Andrew065d78d2020-04-07 15:43:07 -07002430 auto last_active_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002431 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastActive});
Andrew065d78d2020-04-07 15:43:07 -07002432 auto last_rollcall_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002433 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastRollcall});
Andrew065d78d2020-04-07 15:43:07 -07002434 fake_system_state_.prefs()->SetString(active_key, "z2yz");
2435 fake_system_state_.prefs()->SetString(last_active_key, "z2yz");
2436 fake_system_state_.prefs()->SetString(last_rollcall_key, "z2yz");
Andrewe045aef2020-01-08 16:29:22 -08002437 attempter_.is_install_ = false;
2438 attempter_.CalculateDlcParams();
2439
2440 OmahaRequestParams* params = fake_system_state_.request_params();
2441 EXPECT_EQ(1, params->dlc_apps_params().count(params->GetDlcAppId(dlc_id)));
2442 OmahaRequestParams::AppParams dlc_app_params =
2443 params->dlc_apps_params().at(params->GetDlcAppId(dlc_id));
2444 EXPECT_STREQ(dlc_id.c_str(), dlc_app_params.name.c_str());
2445
2446 EXPECT_EQ(true, dlc_app_params.send_ping);
2447 EXPECT_EQ(0, dlc_app_params.ping_active);
2448 EXPECT_EQ(-2, dlc_app_params.ping_date_last_active);
2449 EXPECT_EQ(-2, dlc_app_params.ping_date_last_rollcall);
2450}
2451
2452TEST_F(UpdateAttempterTest, CalculateDlcParamsValidValuesTest) {
Andrewe045aef2020-01-08 16:29:22 -08002453 string dlc_id = "dlc0";
Andrew065d78d2020-04-07 15:43:07 -07002454 MemoryPrefs fake_prefs;
2455 fake_system_state_.set_prefs(&fake_prefs);
Amin Hassani2b68e6b2020-04-17 10:49:12 -07002456 EXPECT_CALL(mock_dlcservice_, GetDlcsToUpdate(_))
Andrewe045aef2020-01-08 16:29:22 -08002457 .WillOnce(
2458 DoAll(SetArgPointee<0>(std::vector<string>({dlc_id})), Return(true)));
2459
2460 // Write numeric values in the metadata files.
Andrew065d78d2020-04-07 15:43:07 -07002461 auto active_key =
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002462 PrefsInterface::CreateSubKey({kDlcPrefsSubDir, dlc_id, kPrefsPingActive});
Andrew065d78d2020-04-07 15:43:07 -07002463 auto last_active_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002464 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastActive});
Andrew065d78d2020-04-07 15:43:07 -07002465 auto last_rollcall_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002466 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastRollcall});
Andrew065d78d2020-04-07 15:43:07 -07002467
2468 fake_system_state_.prefs()->SetInt64(active_key, 1);
2469 fake_system_state_.prefs()->SetInt64(last_active_key, 78);
2470 fake_system_state_.prefs()->SetInt64(last_rollcall_key, 99);
Andrewe045aef2020-01-08 16:29:22 -08002471 attempter_.is_install_ = false;
2472 attempter_.CalculateDlcParams();
2473
2474 OmahaRequestParams* params = fake_system_state_.request_params();
2475 EXPECT_EQ(1, params->dlc_apps_params().count(params->GetDlcAppId(dlc_id)));
2476 OmahaRequestParams::AppParams dlc_app_params =
2477 params->dlc_apps_params().at(params->GetDlcAppId(dlc_id));
2478 EXPECT_STREQ(dlc_id.c_str(), dlc_app_params.name.c_str());
2479
2480 EXPECT_EQ(true, dlc_app_params.send_ping);
2481 EXPECT_EQ(1, dlc_app_params.ping_active);
2482 EXPECT_EQ(78, dlc_app_params.ping_date_last_active);
2483 EXPECT_EQ(99, dlc_app_params.ping_date_last_rollcall);
2484}
Andrewa8d7df32020-03-15 20:10:01 -07002485
2486TEST_F(UpdateAttempterTest, CalculateDlcParamsRemoveStaleMetadata) {
Andrewa8d7df32020-03-15 20:10:01 -07002487 string dlc_id = "dlc0";
Andrew065d78d2020-04-07 15:43:07 -07002488 FakePrefs fake_prefs;
2489 fake_system_state_.set_prefs(&fake_prefs);
2490 auto active_key =
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002491 PrefsInterface::CreateSubKey({kDlcPrefsSubDir, dlc_id, kPrefsPingActive});
Andrew065d78d2020-04-07 15:43:07 -07002492 auto last_active_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002493 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastActive});
Andrew065d78d2020-04-07 15:43:07 -07002494 auto last_rollcall_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002495 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastRollcall});
Andrew065d78d2020-04-07 15:43:07 -07002496 fake_system_state_.prefs()->SetInt64(active_key, kPingInactiveValue);
2497 fake_system_state_.prefs()->SetInt64(last_active_key, 0);
2498 fake_system_state_.prefs()->SetInt64(last_rollcall_key, 0);
2499 EXPECT_TRUE(fake_system_state_.prefs()->Exists(active_key));
2500 EXPECT_TRUE(fake_system_state_.prefs()->Exists(last_active_key));
2501 EXPECT_TRUE(fake_system_state_.prefs()->Exists(last_rollcall_key));
Andrewa8d7df32020-03-15 20:10:01 -07002502
Andrew065d78d2020-04-07 15:43:07 -07002503 attempter_.dlc_ids_ = {dlc_id};
2504 attempter_.is_install_ = true;
Andrewa8d7df32020-03-15 20:10:01 -07002505 attempter_.CalculateDlcParams();
2506
Andrew065d78d2020-04-07 15:43:07 -07002507 EXPECT_FALSE(fake_system_state_.prefs()->Exists(last_active_key));
2508 EXPECT_FALSE(fake_system_state_.prefs()->Exists(last_rollcall_key));
2509 // Active key is set on install.
2510 EXPECT_TRUE(fake_system_state_.prefs()->Exists(active_key));
2511 int64_t temp_int;
2512 EXPECT_TRUE(fake_system_state_.prefs()->GetInt64(active_key, &temp_int));
2513 EXPECT_EQ(temp_int, kPingActiveValue);
Andrewa8d7df32020-03-15 20:10:01 -07002514}
2515
2516TEST_F(UpdateAttempterTest, SetDlcActiveValue) {
Andrewa8d7df32020-03-15 20:10:01 -07002517 string dlc_id = "dlc0";
Andrew065d78d2020-04-07 15:43:07 -07002518 FakePrefs fake_prefs;
2519 fake_system_state_.set_prefs(&fake_prefs);
Andrewa8d7df32020-03-15 20:10:01 -07002520 attempter_.SetDlcActiveValue(true, dlc_id);
Andrewa8d7df32020-03-15 20:10:01 -07002521 int64_t temp_int;
Andrew065d78d2020-04-07 15:43:07 -07002522 auto active_key =
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002523 PrefsInterface::CreateSubKey({kDlcPrefsSubDir, dlc_id, kPrefsPingActive});
Andrew065d78d2020-04-07 15:43:07 -07002524 EXPECT_TRUE(fake_system_state_.prefs()->Exists(active_key));
2525 EXPECT_TRUE(fake_system_state_.prefs()->GetInt64(active_key, &temp_int));
Andrewa8d7df32020-03-15 20:10:01 -07002526 EXPECT_EQ(temp_int, kPingActiveValue);
2527}
2528
2529TEST_F(UpdateAttempterTest, SetDlcInactive) {
Andrewa8d7df32020-03-15 20:10:01 -07002530 string dlc_id = "dlc0";
Andrew065d78d2020-04-07 15:43:07 -07002531 MemoryPrefs fake_prefs;
2532 fake_system_state_.set_prefs(&fake_prefs);
2533 auto sub_keys = {
2534 kPrefsPingActive, kPrefsPingLastActive, kPrefsPingLastRollcall};
2535 for (auto& sub_key : sub_keys) {
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002536 auto key = PrefsInterface::CreateSubKey({kDlcPrefsSubDir, dlc_id, sub_key});
Andrew065d78d2020-04-07 15:43:07 -07002537 fake_system_state_.prefs()->SetInt64(key, 1);
2538 EXPECT_TRUE(fake_system_state_.prefs()->Exists(key));
2539 }
Andrewa8d7df32020-03-15 20:10:01 -07002540 attempter_.SetDlcActiveValue(false, dlc_id);
Andrew065d78d2020-04-07 15:43:07 -07002541 for (auto& sub_key : sub_keys) {
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002542 auto key = PrefsInterface::CreateSubKey({kDlcPrefsSubDir, dlc_id, sub_key});
Andrew065d78d2020-04-07 15:43:07 -07002543 EXPECT_FALSE(fake_system_state_.prefs()->Exists(key));
2544 }
Andrewa8d7df32020-03-15 20:10:01 -07002545}
2546
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002547TEST_F(UpdateAttempterTest, GetSuccessfulDlcIds) {
2548 auto dlc_1 = "1", dlc_2 = "2", dlc_3 = "3";
2549 attempter_.omaha_request_params_->set_dlc_apps_params(
2550 {{dlc_1, {.name = dlc_1, .updated = false}},
2551 {dlc_2, {.name = dlc_2}},
2552 {dlc_3, {.name = dlc_3, .updated = false}}});
2553 EXPECT_THAT(attempter_.GetSuccessfulDlcIds(), ElementsAre(dlc_2));
2554}
2555
Darin Petkovf42cc1c2010-09-01 09:03:02 -07002556} // namespace chromeos_update_engine