blob: 305dbdb935f77303479be672c7a23482f1004740 [file] [log] [blame]
Alex Deymoaea4c1c2015-08-19 20:24:43 -07001//
2// Copyright (C) 2012 The Android Open Source Project
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15//
Darin Petkovf42cc1c2010-09-01 09:03:02 -070016
Alex Deymo2c0db7b2014-11-04 12:23:39 -080017#include "update_engine/update_attempter.h"
18
Ben Chan9abb7632014-08-07 00:10:53 -070019#include <stdint.h>
20
Jae Hoon Kim051627a2019-09-03 12:56:32 -070021#include <limits>
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -070022#include <map>
Ben Chan02f7c1d2014-10-18 15:18:02 -070023#include <memory>
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -070024#include <string>
Jae Hoon Kimedb65502019-06-14 11:52:17 -070025#include <unordered_set>
Ben Chan02f7c1d2014-10-18 15:18:02 -070026
Ben Chan06c76a42014-09-05 08:21:06 -070027#include <base/files/file_util.h>
Alex Deymo0b3db6b2015-08-10 15:19:37 -070028#include <base/message_loop/message_loop.h>
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -070029#include <brillo/message_loops/base_message_loop.h>
30#include <brillo/message_loops/message_loop.h>
31#include <brillo/message_loops/message_loop_utils.h>
Darin Petkovf42cc1c2010-09-01 09:03:02 -070032#include <gtest/gtest.h>
Patrick Dubroy7fbbe8a2011-08-01 17:28:22 +020033#include <policy/libpolicy.h>
34#include <policy/mock_device_policy.h>
Marton Hunyadye58bddb2018-04-10 20:27:26 +020035#include <policy/mock_libpolicy.h>
Darin Petkovf42cc1c2010-09-01 09:03:02 -070036
Jae Hoon Kim0ae8fe12019-06-26 14:32:50 -070037#include "update_engine/common/constants.h"
Xiaochu Liu8ba486f2018-11-06 11:14:10 -080038#include "update_engine/common/dlcservice_interface.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080039#include "update_engine/common/fake_clock.h"
40#include "update_engine/common/fake_prefs.h"
Alex Deymo14fd1ec2016-02-24 22:03:57 -080041#include "update_engine/common/mock_action.h"
42#include "update_engine/common/mock_action_processor.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080043#include "update_engine/common/mock_http_fetcher.h"
44#include "update_engine/common/mock_prefs.h"
45#include "update_engine/common/platform_constants.h"
46#include "update_engine/common/prefs.h"
47#include "update_engine/common/test_utils.h"
48#include "update_engine/common/utils.h"
Gilad Arnold5bb4c902014-04-10 12:32:13 -070049#include "update_engine/fake_system_state.h"
Jae Hoon Kim0ae8fe12019-06-26 14:32:50 -070050#include "update_engine/libcurl_http_fetcher.h"
David Zeuthen8f191b22013-08-06 12:27:50 -070051#include "update_engine/mock_p2p_manager.h"
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080052#include "update_engine/mock_payload_state.h"
Aaron Wood9321f502017-09-07 11:18:54 -070053#include "update_engine/mock_service_observer.h"
Jae Hoon Kim051627a2019-09-03 12:56:32 -070054#include "update_engine/omaha_utils.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080055#include "update_engine/payload_consumer/filesystem_verifier_action.h"
56#include "update_engine/payload_consumer/install_plan.h"
57#include "update_engine/payload_consumer/payload_constants.h"
58#include "update_engine/payload_consumer/postinstall_runner_action.h"
Amin Hassani0882a512018-04-05 16:25:44 -070059#include "update_engine/update_boot_flags_action.h"
Jae Hoon Kim504c3cb2019-07-02 11:17:24 -070060#include "update_engine/update_manager/mock_update_manager.h"
Darin Petkovf42cc1c2010-09-01 09:03:02 -070061
David Zeuthen985b1122013-10-09 12:13:15 -070062using base::Time;
63using base::TimeDelta;
Aaron Woodbf5a2522017-10-04 10:58:36 -070064using chromeos_update_manager::EvalStatus;
Jae Hoon Kim504c3cb2019-07-02 11:17:24 -070065using chromeos_update_manager::MockUpdateManager;
Adolfo Victoria497044c2018-07-18 07:51:42 -070066using chromeos_update_manager::StagingSchedule;
Aaron Woodbf5a2522017-10-04 10:58:36 -070067using chromeos_update_manager::UpdateCheckParams;
Adolfo Victoria497044c2018-07-18 07:51:42 -070068using policy::DevicePolicy;
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -070069using std::map;
Darin Petkovf42cc1c2010-09-01 09:03:02 -070070using std::string;
Ben Chan02f7c1d2014-10-18 15:18:02 -070071using std::unique_ptr;
Jae Hoon Kimedb65502019-06-14 11:52:17 -070072using std::unordered_set;
Xiaochu Liu88d90382018-08-29 16:09:11 -070073using std::vector;
Aaron Woodbf5a2522017-10-04 10:58:36 -070074using testing::_;
Andrew065d78d2020-04-07 15:43:07 -070075using testing::Contains;
Darin Petkov36275772010-10-01 11:40:57 -070076using testing::DoAll;
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -070077using testing::ElementsAre;
Aaron Wood7f92e2b2017-08-28 14:51:21 -070078using testing::Field;
Darin Petkovf42cc1c2010-09-01 09:03:02 -070079using testing::InSequence;
Jae Hoon Kimedb65502019-06-14 11:52:17 -070080using testing::Invoke;
Darin Petkov2dd01092010-10-08 15:43:05 -070081using testing::Ne;
Darin Petkov9c096d62010-11-17 14:49:04 -080082using testing::NiceMock;
Amin Hassanid3f4bea2018-04-30 14:52:40 -070083using testing::Pointee;
Darin Petkovf42cc1c2010-09-01 09:03:02 -070084using testing::Property;
85using testing::Return;
Gilad Arnold74b5f552014-10-07 08:17:16 -070086using testing::ReturnPointee;
Marton Hunyadye58bddb2018-04-10 20:27:26 +020087using testing::ReturnRef;
Alex Deymo2c0db7b2014-11-04 12:23:39 -080088using testing::SaveArg;
Ben Chan672c1f52017-10-23 15:41:39 -070089using testing::SetArgPointee;
Aaron Woodbf5a2522017-10-04 10:58:36 -070090using update_engine::UpdateAttemptFlags;
Aaron Wood7f92e2b2017-08-28 14:51:21 -070091using update_engine::UpdateEngineStatus;
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -070092using update_engine::UpdateStatus;
Darin Petkovf42cc1c2010-09-01 09:03:02 -070093
94namespace chromeos_update_engine {
95
Xiaochu Liu8ba486f2018-11-06 11:14:10 -080096namespace {
97
Jae Hoon Kimc437ea52019-07-11 11:20:38 -070098const UpdateStatus kNonIdleUpdateStatuses[] = {
99 UpdateStatus::CHECKING_FOR_UPDATE,
100 UpdateStatus::UPDATE_AVAILABLE,
101 UpdateStatus::DOWNLOADING,
102 UpdateStatus::VERIFYING,
103 UpdateStatus::FINALIZING,
104 UpdateStatus::UPDATED_NEED_REBOOT,
105 UpdateStatus::REPORTING_ERROR_EVENT,
106 UpdateStatus::ATTEMPTING_ROLLBACK,
107 UpdateStatus::DISABLED,
108 UpdateStatus::NEED_PERMISSION_TO_UPDATE,
109};
110
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -0700111struct CheckForUpdateTestParams {
112 // Setups + Inputs:
113 UpdateStatus status = UpdateStatus::IDLE;
114 string app_version = "fake_app_version";
115 string omaha_url = "fake_omaha_url";
116 UpdateAttemptFlags flags = UpdateAttemptFlags::kNone;
117 bool is_official_build = true;
118 bool are_dev_features_enabled = false;
119
120 // Expects:
121 string expected_forced_app_version = "";
122 string expected_forced_omaha_url = "";
Jae Hoon Kim2b73ac22019-07-02 11:17:24 -0700123 bool should_schedule_updates_be_called = true;
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -0700124 bool expected_result = true;
125};
126
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700127struct OnUpdateScheduledTestParams {
128 // Setups + Inputs:
129 UpdateCheckParams params = {};
130 EvalStatus status = EvalStatus::kFailed;
131 // Expects:
132 UpdateStatus exit_status = UpdateStatus::IDLE;
133 bool should_schedule_updates_be_called = false;
134 bool should_update_be_called = false;
135};
136
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -0700137struct ProcessingDoneTestParams {
138 // Setups + Inputs:
139 bool is_install = false;
140 UpdateStatus status = UpdateStatus::CHECKING_FOR_UPDATE;
141 ActionProcessor* processor = nullptr;
142 ErrorCode code = ErrorCode::kSuccess;
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -0700143 map<string, OmahaRequestParams::AppParams> dlc_apps_params;
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -0700144
145 // Expects:
146 const bool kExpectedIsInstall = false;
147 bool should_schedule_updates_be_called = true;
148 UpdateStatus expected_exit_status = UpdateStatus::IDLE;
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -0700149 bool should_install_completed_be_called = false;
150 bool should_update_completed_be_called = false;
151 vector<string> args_to_install_completed;
152 vector<string> args_to_update_completed;
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -0700153};
154
Xiaochu Liu8ba486f2018-11-06 11:14:10 -0800155class MockDlcService : public DlcServiceInterface {
156 public:
Amin Hassani2b68e6b2020-04-17 10:49:12 -0700157 MOCK_METHOD1(GetDlcsToUpdate, bool(vector<string>*));
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -0700158 MOCK_METHOD1(InstallCompleted, bool(const vector<string>&));
159 MOCK_METHOD1(UpdateCompleted, bool(const vector<string>&));
Xiaochu Liu8ba486f2018-11-06 11:14:10 -0800160};
161
162} // namespace
163
Marton Hunyadya0302682018-05-16 18:52:13 +0200164const char kRollbackVersion[] = "10575.39.2";
165
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700166// Test a subclass rather than the main class directly so that we can mock out
Darin Petkovcd1666f2010-09-23 09:53:44 -0700167// methods within the class. There're explicit unit tests for the mocked out
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700168// methods.
169class UpdateAttempterUnderTest : public UpdateAttempter {
170 public:
Jeffrey Kardatzkecf5f1f12017-10-02 16:08:44 -0700171 explicit UpdateAttempterUnderTest(SystemState* system_state)
172 : UpdateAttempter(system_state, nullptr) {}
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700173
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700174 void Update(const std::string& app_version,
175 const std::string& omaha_url,
176 const std::string& target_channel,
177 const std::string& target_version_prefix,
178 bool rollback_allowed,
179 bool rollback_data_save_requested,
180 int rollback_allowed_milestones,
181 bool obey_proxies,
182 bool interactive) override {
183 update_called_ = true;
184 if (do_update_) {
185 UpdateAttempter::Update(app_version,
186 omaha_url,
187 target_channel,
188 target_version_prefix,
189 rollback_allowed,
190 rollback_data_save_requested,
191 rollback_allowed_milestones,
192 obey_proxies,
193 interactive);
194 return;
195 }
196 LOG(INFO) << "[TEST] Update() disabled.";
197 status_ = UpdateStatus::CHECKING_FOR_UPDATE;
198 }
199
200 void DisableUpdate() { do_update_ = false; }
201
202 bool WasUpdateCalled() const { return update_called_; }
203
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700204 // Wrap the update scheduling method, allowing us to opt out of scheduled
205 // updates for testing purposes.
Xiaochu Liu88d90382018-08-29 16:09:11 -0700206 bool ScheduleUpdates() override {
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700207 schedule_updates_called_ = true;
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700208 if (do_schedule_updates_)
209 return UpdateAttempter::ScheduleUpdates();
210 LOG(INFO) << "[TEST] Update scheduling disabled.";
211 waiting_for_scheduled_check_ = true;
Xiaochu Liu88d90382018-08-29 16:09:11 -0700212 return true;
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700213 }
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700214
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700215 void DisableScheduleUpdates() { do_schedule_updates_ = false; }
216
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700217 // Indicates whether |ScheduleUpdates()| was called.
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700218 bool WasScheduleUpdatesCalled() const { return schedule_updates_called_; }
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700219
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -0700220 // Need to expose following private members of |UpdateAttempter| for tests.
221 const string& forced_app_version() const { return forced_app_version_; }
Alex Deymo60ca1a72015-06-18 18:19:15 -0700222 const string& forced_omaha_url() const { return forced_omaha_url_; }
David Pursell02c18642014-11-06 11:26:11 -0800223
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700224 // Need to expose |waiting_for_scheduled_check_| for testing.
225 void SetWaitingForScheduledCheck(bool waiting) {
226 waiting_for_scheduled_check_ = waiting;
227 }
228
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700229 private:
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700230 // Used for overrides of |Update()|.
231 bool update_called_ = false;
232 bool do_update_ = true;
233
234 // Used for overrides of |ScheduleUpdates()|.
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700235 bool schedule_updates_called_ = false;
236 bool do_schedule_updates_ = true;
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700237};
238
239class UpdateAttempterTest : public ::testing::Test {
240 protected:
Jay Srinivasan43488792012-06-19 00:25:31 -0700241 UpdateAttempterTest()
Daniel Erate5f6f252017-04-20 12:09:58 -0600242 : certificate_checker_(fake_system_state_.mock_prefs(),
Alex Deymo33e91e72015-12-01 18:26:08 -0300243 &openssl_wrapper_) {
Gilad Arnold1f847232014-04-07 12:07:49 -0700244 // Override system state members.
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700245 fake_system_state_.set_connection_manager(&mock_connection_manager);
246 fake_system_state_.set_update_attempter(&attempter_);
Xiaochu Liu8ba486f2018-11-06 11:14:10 -0800247 fake_system_state_.set_dlcservice(&mock_dlcservice_);
Jae Hoon Kim504c3cb2019-07-02 11:17:24 -0700248 fake_system_state_.set_update_manager(&mock_update_manager_);
Alex Deymo60ca1a72015-06-18 18:19:15 -0700249 loop_.SetAsCurrent();
Gilad Arnold1f847232014-04-07 12:07:49 -0700250
Alex Deymo33e91e72015-12-01 18:26:08 -0300251 certificate_checker_.Init();
252
Xiaochu Liu8ba486f2018-11-06 11:14:10 -0800253 attempter_.set_forced_update_pending_callback(
254 new base::Callback<void(bool, bool)>(base::Bind([](bool, bool) {})));
Sen Jiange67bb5b2016-06-20 15:53:56 -0700255 // Finish initializing the attempter.
Gilad Arnold1f847232014-04-07 12:07:49 -0700256 attempter_.Init();
Jay Srinivasan43488792012-06-19 00:25:31 -0700257 }
Gilad Arnoldeff87cc2013-07-22 18:32:09 -0700258
Alex Deymo610277e2014-11-11 21:18:11 -0800259 void SetUp() override {
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700260 EXPECT_NE(nullptr, attempter_.system_state_);
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700261 EXPECT_NE(nullptr, attempter_.system_state_->update_manager());
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700262 EXPECT_EQ(0, attempter_.http_response_code_);
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700263 EXPECT_EQ(UpdateStatus::IDLE, attempter_.status_);
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700264 EXPECT_EQ(0.0, attempter_.download_progress_);
265 EXPECT_EQ(0, attempter_.last_checked_time_);
266 EXPECT_EQ("0.0.0.0", attempter_.new_version_);
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700267 EXPECT_EQ(0ULL, attempter_.new_payload_size_);
Alex Deymo8427b4a2014-11-05 14:00:32 -0800268 processor_ = new NiceMock<MockActionProcessor>();
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700269 attempter_.processor_.reset(processor_); // Transfers ownership.
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700270 prefs_ = fake_system_state_.mock_prefs();
Gilad Arnold74b5f552014-10-07 08:17:16 -0700271
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700272 // Setup store/load semantics of P2P properties via the mock |PayloadState|.
Gilad Arnold74b5f552014-10-07 08:17:16 -0700273 actual_using_p2p_for_downloading_ = false;
274 EXPECT_CALL(*fake_system_state_.mock_payload_state(),
275 SetUsingP2PForDownloading(_))
276 .WillRepeatedly(SaveArg<0>(&actual_using_p2p_for_downloading_));
277 EXPECT_CALL(*fake_system_state_.mock_payload_state(),
278 GetUsingP2PForDownloading())
279 .WillRepeatedly(ReturnPointee(&actual_using_p2p_for_downloading_));
280 actual_using_p2p_for_sharing_ = false;
281 EXPECT_CALL(*fake_system_state_.mock_payload_state(),
282 SetUsingP2PForSharing(_))
283 .WillRepeatedly(SaveArg<0>(&actual_using_p2p_for_sharing_));
284 EXPECT_CALL(*fake_system_state_.mock_payload_state(),
285 GetUsingP2PForDownloading())
286 .WillRepeatedly(ReturnPointee(&actual_using_p2p_for_sharing_));
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700287 }
288
Alex Deymo60ca1a72015-06-18 18:19:15 -0700289 public:
290 void ScheduleQuitMainLoop();
Patrick Dubroy7fbbe8a2011-08-01 17:28:22 +0200291
Alex Deymo60ca1a72015-06-18 18:19:15 -0700292 // Callbacks to run the different tests from the main loop.
Darin Petkove6ef2f82011-03-07 17:31:11 -0800293 void UpdateTestStart();
294 void UpdateTestVerify();
Alex Deymo60ca1a72015-06-18 18:19:15 -0700295 void RollbackTestStart(bool enterprise_rollback, bool valid_slot);
Chris Sosa76a29ae2013-07-11 17:59:24 -0700296 void RollbackTestVerify();
Thieu Le116fda32011-04-19 11:01:54 -0700297 void PingOmahaTestStart();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700298 void ReadScatterFactorFromPolicyTestStart();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700299 void DecrementUpdateCheckCountTestStart();
Jay Srinivasan08fce042012-06-07 16:31:01 -0700300 void NoScatteringDoneDuringManualUpdateTestStart();
David Zeuthen8f191b22013-08-06 12:27:50 -0700301 void P2PNotEnabledStart();
David Zeuthen8f191b22013-08-06 12:27:50 -0700302 void P2PEnabledStart();
David Zeuthen8f191b22013-08-06 12:27:50 -0700303 void P2PEnabledInteractiveStart();
David Zeuthen8f191b22013-08-06 12:27:50 -0700304 void P2PEnabledStartingFailsStart();
David Zeuthen8f191b22013-08-06 12:27:50 -0700305 void P2PEnabledHousekeepingFailsStart();
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700306 void SessionIdTestChange();
307 void SessionIdTestEnforceEmptyStrPingOmaha();
308 void SessionIdTestConsistencyInUpdateFlow();
Jae Hoon Kim0ae8fe12019-06-26 14:32:50 -0700309 void SessionIdTestInDownloadAction();
Amr Aboelkher21ac9962019-05-15 14:50:05 +0200310 void UpdateToQuickFixBuildStart(bool set_token);
Marton Hunyadye58bddb2018-04-10 20:27:26 +0200311 void ResetRollbackHappenedStart(bool is_consumer,
312 bool is_policy_available,
313 bool expected_reset);
Adolfo Victoria497044c2018-07-18 07:51:42 -0700314 // Staging related callbacks.
315 void SetUpStagingTest(const StagingSchedule& schedule, FakePrefs* prefs);
316 void CheckStagingOff();
317 void StagingSetsPrefsAndTurnsOffScatteringStart();
318 void StagingOffIfInteractiveStart();
319 void StagingOffIfOobeStart();
David Zeuthen8f191b22013-08-06 12:27:50 -0700320
Gilad Arnold74b5f552014-10-07 08:17:16 -0700321 bool actual_using_p2p_for_downloading() {
322 return actual_using_p2p_for_downloading_;
323 }
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800324 bool actual_using_p2p_for_sharing() { return actual_using_p2p_for_sharing_; }
Gilad Arnold74b5f552014-10-07 08:17:16 -0700325
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -0700326 // |CheckForUpdate()| related member functions.
327 void TestCheckForUpdate();
328
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700329 // |OnUpdateScheduled()| related member functions.
330 void TestOnUpdateScheduled();
331
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -0700332 // |ProcessingDone()| related member functions.
333 void TestProcessingDone();
334
Alex Deymo0b3db6b2015-08-10 15:19:37 -0700335 base::MessageLoopForIO base_loop_;
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700336 brillo::BaseMessageLoop loop_{&base_loop_};
Alex Deymo60ca1a72015-06-18 18:19:15 -0700337
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700338 FakeSystemState fake_system_state_;
Jeffrey Kardatzkecf5f1f12017-10-02 16:08:44 -0700339 UpdateAttempterUnderTest attempter_{&fake_system_state_};
Alex Deymo33e91e72015-12-01 18:26:08 -0300340 OpenSSLWrapper openssl_wrapper_;
341 CertificateChecker certificate_checker_;
Xiaochu Liu8ba486f2018-11-06 11:14:10 -0800342 MockDlcService mock_dlcservice_;
Jae Hoon Kim504c3cb2019-07-02 11:17:24 -0700343 MockUpdateManager mock_update_manager_;
Alex Deymo30534502015-07-20 15:06:33 -0700344
Alex Deymo8427b4a2014-11-05 14:00:32 -0800345 NiceMock<MockActionProcessor>* processor_;
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700346 NiceMock<MockPrefs>*
347 prefs_; // Shortcut to |fake_system_state_->mock_prefs()|.
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800348 NiceMock<MockConnectionManager> mock_connection_manager;
Gilad Arnoldeff87cc2013-07-22 18:32:09 -0700349
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -0700350 // |CheckForUpdate()| test params.
351 CheckForUpdateTestParams cfu_params_;
352
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700353 // |OnUpdateScheduled()| test params.
354 OnUpdateScheduledTestParams ous_params_;
355
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -0700356 // |ProcessingDone()| test params.
357 ProcessingDoneTestParams pd_params_;
358
Gilad Arnold74b5f552014-10-07 08:17:16 -0700359 bool actual_using_p2p_for_downloading_;
360 bool actual_using_p2p_for_sharing_;
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700361};
362
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -0700363void UpdateAttempterTest::TestCheckForUpdate() {
364 // Setup
365 attempter_.status_ = cfu_params_.status;
366 fake_system_state_.fake_hardware()->SetIsOfficialBuild(
367 cfu_params_.is_official_build);
368 fake_system_state_.fake_hardware()->SetAreDevFeaturesEnabled(
369 cfu_params_.are_dev_features_enabled);
370
371 // Invocation
372 EXPECT_EQ(
373 cfu_params_.expected_result,
374 attempter_.CheckForUpdate(
375 cfu_params_.app_version, cfu_params_.omaha_url, cfu_params_.flags));
376
377 // Verify
378 EXPECT_EQ(cfu_params_.expected_forced_app_version,
379 attempter_.forced_app_version());
380 EXPECT_EQ(cfu_params_.expected_forced_omaha_url,
381 attempter_.forced_omaha_url());
Jae Hoon Kim2b73ac22019-07-02 11:17:24 -0700382 EXPECT_EQ(cfu_params_.should_schedule_updates_be_called,
383 attempter_.WasScheduleUpdatesCalled());
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -0700384}
385
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -0700386void UpdateAttempterTest::TestProcessingDone() {
387 // Setup
388 attempter_.DisableScheduleUpdates();
389 attempter_.is_install_ = pd_params_.is_install;
390 attempter_.status_ = pd_params_.status;
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -0700391 attempter_.omaha_request_params_->set_dlc_apps_params(
392 pd_params_.dlc_apps_params);
393
394 // Expects
395 if (pd_params_.should_install_completed_be_called)
396 EXPECT_CALL(mock_dlcservice_,
397 InstallCompleted(pd_params_.args_to_install_completed))
398 .WillOnce(Return(true));
399 else
400 EXPECT_CALL(mock_dlcservice_, InstallCompleted(_)).Times(0);
401 if (pd_params_.should_update_completed_be_called)
402 EXPECT_CALL(mock_dlcservice_,
403 UpdateCompleted(pd_params_.args_to_update_completed))
404 .WillOnce(Return(true));
405 else
406 EXPECT_CALL(mock_dlcservice_, UpdateCompleted(_)).Times(0);
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -0700407
408 // Invocation
409 attempter_.ProcessingDone(pd_params_.processor, pd_params_.code);
410
411 // Verify
412 EXPECT_EQ(pd_params_.kExpectedIsInstall, attempter_.is_install_);
413 EXPECT_EQ(pd_params_.should_schedule_updates_be_called,
414 attempter_.WasScheduleUpdatesCalled());
415 EXPECT_EQ(pd_params_.expected_exit_status, attempter_.status_);
416}
417
Alex Deymo60ca1a72015-06-18 18:19:15 -0700418void UpdateAttempterTest::ScheduleQuitMainLoop() {
Luis Hector Chavezf1cf3482016-07-19 14:29:19 -0700419 loop_.PostTask(
420 FROM_HERE,
421 base::Bind([](brillo::BaseMessageLoop* loop) { loop->BreakLoop(); },
422 base::Unretained(&loop_)));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700423}
424
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700425void UpdateAttempterTest::SessionIdTestChange() {
426 EXPECT_NE(UpdateStatus::UPDATED_NEED_REBOOT, attempter_.status());
427 const auto old_session_id = attempter_.session_id_;
428 attempter_.Update("", "", "", "", false, false, 0, false, false);
429 EXPECT_NE(old_session_id, attempter_.session_id_);
430 ScheduleQuitMainLoop();
431}
432
433TEST_F(UpdateAttempterTest, SessionIdTestChange) {
434 loop_.PostTask(FROM_HERE,
435 base::Bind(&UpdateAttempterTest::SessionIdTestChange,
436 base::Unretained(this)));
437 loop_.Run();
438}
439
440void UpdateAttempterTest::SessionIdTestEnforceEmptyStrPingOmaha() {
441 // The |session_id_| should not be changed and should remain as an empty
442 // string when |status_| is |UPDATED_NEED_REBOOT| (only for consistency)
443 // and |PingOmaha()| is called.
444 attempter_.DisableScheduleUpdates();
445 attempter_.status_ = UpdateStatus::UPDATED_NEED_REBOOT;
446 const auto old_session_id = attempter_.session_id_;
447 auto CheckIfEmptySessionId = [](AbstractAction* aa) {
448 if (aa->Type() == OmahaRequestAction::StaticType()) {
449 EXPECT_TRUE(static_cast<OmahaRequestAction*>(aa)->session_id_.empty());
450 }
451 };
452 EXPECT_CALL(*processor_, EnqueueAction(Pointee(_)))
453 .WillRepeatedly(Invoke(CheckIfEmptySessionId));
454 EXPECT_CALL(*processor_, StartProcessing());
455 attempter_.PingOmaha();
456 EXPECT_EQ(old_session_id, attempter_.session_id_);
457 EXPECT_EQ(UpdateStatus::UPDATED_NEED_REBOOT, attempter_.status_);
458 ScheduleQuitMainLoop();
459}
460
461TEST_F(UpdateAttempterTest, SessionIdTestEnforceEmptyStrPingOmaha) {
462 loop_.PostTask(
463 FROM_HERE,
464 base::Bind(&UpdateAttempterTest::SessionIdTestEnforceEmptyStrPingOmaha,
465 base::Unretained(this)));
466 loop_.Run();
467}
468
469void UpdateAttempterTest::SessionIdTestConsistencyInUpdateFlow() {
470 // All session IDs passed into |OmahaRequestActions| should be enforced to
471 // have the same value in |BuildUpdateActions()|.
472 unordered_set<string> session_ids;
473 // Gather all the session IDs being passed to |OmahaRequestActions|.
474 auto CheckSessionId = [&session_ids](AbstractAction* aa) {
475 if (aa->Type() == OmahaRequestAction::StaticType())
476 session_ids.insert(static_cast<OmahaRequestAction*>(aa)->session_id_);
477 };
478 EXPECT_CALL(*processor_, EnqueueAction(Pointee(_)))
479 .WillRepeatedly(Invoke(CheckSessionId));
480 attempter_.BuildUpdateActions(false);
481 // Validate that all the session IDs are the same.
482 EXPECT_EQ(1, session_ids.size());
483 ScheduleQuitMainLoop();
484}
485
486TEST_F(UpdateAttempterTest, SessionIdTestConsistencyInUpdateFlow) {
487 loop_.PostTask(
488 FROM_HERE,
489 base::Bind(&UpdateAttempterTest::SessionIdTestConsistencyInUpdateFlow,
490 base::Unretained(this)));
491 loop_.Run();
492}
493
Jae Hoon Kim0ae8fe12019-06-26 14:32:50 -0700494void UpdateAttempterTest::SessionIdTestInDownloadAction() {
495 // The session ID passed into |DownloadAction|'s |LibcurlHttpFetcher| should
496 // be enforced to be included in the HTTP header as X-Goog-Update-SessionId.
497 string header_value;
498 auto CheckSessionIdInDownloadAction = [&header_value](AbstractAction* aa) {
499 if (aa->Type() == DownloadAction::StaticType()) {
500 DownloadAction* da = static_cast<DownloadAction*>(aa);
501 EXPECT_TRUE(da->http_fetcher()->GetHeader(kXGoogleUpdateSessionId,
502 &header_value));
503 }
504 };
505 EXPECT_CALL(*processor_, EnqueueAction(Pointee(_)))
506 .WillRepeatedly(Invoke(CheckSessionIdInDownloadAction));
507 attempter_.BuildUpdateActions(false);
508 // Validate that X-Goog-Update_SessionId is set correctly in HTTP Header.
509 EXPECT_EQ(attempter_.session_id_, header_value);
510 ScheduleQuitMainLoop();
511}
512
513TEST_F(UpdateAttempterTest, SessionIdTestInDownloadAction) {
514 loop_.PostTask(FROM_HERE,
515 base::Bind(&UpdateAttempterTest::SessionIdTestInDownloadAction,
516 base::Unretained(this)));
517 loop_.Run();
518}
519
Darin Petkov1b003102010-11-30 10:18:36 -0800520TEST_F(UpdateAttempterTest, ActionCompletedDownloadTest) {
Ben Chan02f7c1d2014-10-18 15:18:02 -0700521 unique_ptr<MockHttpFetcher> fetcher(new MockHttpFetcher("", 0, nullptr));
Darin Petkov1b003102010-11-30 10:18:36 -0800522 fetcher->FailTransfer(503); // Sets the HTTP response code.
Amin Hassani7ecda262017-07-11 17:10:50 -0700523 DownloadAction action(prefs_,
524 nullptr,
525 nullptr,
526 nullptr,
527 fetcher.release(),
Amin Hassanied37d682018-04-06 13:22:00 -0700528 false /* interactive */);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800529 EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _)).Times(0);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700530 attempter_.ActionCompleted(nullptr, &action, ErrorCode::kSuccess);
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700531 EXPECT_EQ(UpdateStatus::FINALIZING, attempter_.status());
Aaron Wood9321f502017-09-07 11:18:54 -0700532 EXPECT_EQ(0.0, attempter_.download_progress_);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700533 ASSERT_EQ(nullptr, attempter_.error_event_.get());
Darin Petkov1b003102010-11-30 10:18:36 -0800534}
535
536TEST_F(UpdateAttempterTest, ActionCompletedErrorTest) {
Alex Deymo8427b4a2014-11-05 14:00:32 -0800537 MockAction action;
538 EXPECT_CALL(action, Type()).WillRepeatedly(Return("MockAction"));
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700539 attempter_.status_ = UpdateStatus::DOWNLOADING;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800540 EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _))
Darin Petkov1b003102010-11-30 10:18:36 -0800541 .WillOnce(Return(false));
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700542 attempter_.ActionCompleted(nullptr, &action, ErrorCode::kError);
543 ASSERT_NE(nullptr, attempter_.error_event_.get());
Darin Petkov1b003102010-11-30 10:18:36 -0800544}
545
Aaron Wood9321f502017-09-07 11:18:54 -0700546TEST_F(UpdateAttempterTest, DownloadProgressAccumulationTest) {
547 // Simple test case, where all the values match (nothing was skipped)
548 uint64_t bytes_progressed_1 = 1024 * 1024; // 1MB
549 uint64_t bytes_progressed_2 = 1024 * 1024; // 1MB
550 uint64_t bytes_received_1 = bytes_progressed_1;
551 uint64_t bytes_received_2 = bytes_received_1 + bytes_progressed_2;
552 uint64_t bytes_total = 20 * 1024 * 1024; // 20MB
553
554 double progress_1 =
555 static_cast<double>(bytes_received_1) / static_cast<double>(bytes_total);
556 double progress_2 =
557 static_cast<double>(bytes_received_2) / static_cast<double>(bytes_total);
558
559 EXPECT_EQ(0.0, attempter_.download_progress_);
560 // This is set via inspecting the InstallPlan payloads when the
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700561 // |OmahaResponseAction| is completed.
Aaron Wood9321f502017-09-07 11:18:54 -0700562 attempter_.new_payload_size_ = bytes_total;
563 NiceMock<MockServiceObserver> observer;
564 EXPECT_CALL(observer,
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700565 SendStatusUpdate(AllOf(
566 Field(&UpdateEngineStatus::progress, progress_1),
567 Field(&UpdateEngineStatus::status, UpdateStatus::DOWNLOADING),
568 Field(&UpdateEngineStatus::new_size_bytes, bytes_total))));
Aaron Wood9321f502017-09-07 11:18:54 -0700569 EXPECT_CALL(observer,
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700570 SendStatusUpdate(AllOf(
571 Field(&UpdateEngineStatus::progress, progress_2),
572 Field(&UpdateEngineStatus::status, UpdateStatus::DOWNLOADING),
573 Field(&UpdateEngineStatus::new_size_bytes, bytes_total))));
Aaron Wood9321f502017-09-07 11:18:54 -0700574 attempter_.AddObserver(&observer);
575 attempter_.BytesReceived(bytes_progressed_1, bytes_received_1, bytes_total);
576 EXPECT_EQ(progress_1, attempter_.download_progress_);
577 // This iteration validates that a later set of updates to the variables are
578 // properly handled (so that |getStatus()| will return the same progress info
579 // as the callback is receiving.
580 attempter_.BytesReceived(bytes_progressed_2, bytes_received_2, bytes_total);
581 EXPECT_EQ(progress_2, attempter_.download_progress_);
582}
583
584TEST_F(UpdateAttempterTest, ChangeToDownloadingOnReceivedBytesTest) {
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700585 // The transition into |UpdateStatus::DOWNLOADING| happens when the
Aaron Wood9321f502017-09-07 11:18:54 -0700586 // first bytes are received.
587 uint64_t bytes_progressed = 1024 * 1024; // 1MB
588 uint64_t bytes_received = 2 * 1024 * 1024; // 2MB
589 uint64_t bytes_total = 20 * 1024 * 1024; // 300MB
590 attempter_.status_ = UpdateStatus::CHECKING_FOR_UPDATE;
591 // This is set via inspecting the InstallPlan payloads when the
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700592 // |OmahaResponseAction| is completed.
Aaron Wood9321f502017-09-07 11:18:54 -0700593 attempter_.new_payload_size_ = bytes_total;
594 EXPECT_EQ(0.0, attempter_.download_progress_);
595 NiceMock<MockServiceObserver> observer;
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700596 EXPECT_CALL(observer,
597 SendStatusUpdate(AllOf(
598 Field(&UpdateEngineStatus::status, UpdateStatus::DOWNLOADING),
599 Field(&UpdateEngineStatus::new_size_bytes, bytes_total))));
Aaron Wood9321f502017-09-07 11:18:54 -0700600 attempter_.AddObserver(&observer);
601 attempter_.BytesReceived(bytes_progressed, bytes_received, bytes_total);
602 EXPECT_EQ(UpdateStatus::DOWNLOADING, attempter_.status_);
603}
604
605TEST_F(UpdateAttempterTest, BroadcastCompleteDownloadTest) {
606 // There is a special case to ensure that at 100% downloaded,
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700607 // |download_progress_| is updated and broadcastest.
Aaron Wood9321f502017-09-07 11:18:54 -0700608 uint64_t bytes_progressed = 0; // ignored
609 uint64_t bytes_received = 5 * 1024 * 1024; // ignored
610 uint64_t bytes_total = 5 * 1024 * 1024; // 300MB
611 attempter_.status_ = UpdateStatus::DOWNLOADING;
612 attempter_.new_payload_size_ = bytes_total;
613 EXPECT_EQ(0.0, attempter_.download_progress_);
614 NiceMock<MockServiceObserver> observer;
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700615 EXPECT_CALL(observer,
616 SendStatusUpdate(AllOf(
617 Field(&UpdateEngineStatus::progress, 1.0),
618 Field(&UpdateEngineStatus::status, UpdateStatus::DOWNLOADING),
619 Field(&UpdateEngineStatus::new_size_bytes, bytes_total))));
Aaron Wood9321f502017-09-07 11:18:54 -0700620 attempter_.AddObserver(&observer);
621 attempter_.BytesReceived(bytes_progressed, bytes_received, bytes_total);
622 EXPECT_EQ(1.0, attempter_.download_progress_);
623}
624
Darin Petkov1b003102010-11-30 10:18:36 -0800625TEST_F(UpdateAttempterTest, ActionCompletedOmahaRequestTest) {
Ben Chan02f7c1d2014-10-18 15:18:02 -0700626 unique_ptr<MockHttpFetcher> fetcher(new MockHttpFetcher("", 0, nullptr));
Darin Petkov1b003102010-11-30 10:18:36 -0800627 fetcher->FailTransfer(500); // Sets the HTTP response code.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800628 OmahaRequestAction action(
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700629 &fake_system_state_, nullptr, std::move(fetcher), false, "");
Darin Petkov1b003102010-11-30 10:18:36 -0800630 ObjectCollectorAction<OmahaResponse> collector_action;
631 BondActions(&action, &collector_action);
632 OmahaResponse response;
633 response.poll_interval = 234;
634 action.SetOutputObject(response);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800635 EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _)).Times(0);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700636 attempter_.ActionCompleted(nullptr, &action, ErrorCode::kSuccess);
Darin Petkov1b003102010-11-30 10:18:36 -0800637 EXPECT_EQ(500, attempter_.http_response_code());
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700638 EXPECT_EQ(UpdateStatus::IDLE, attempter_.status());
Alex Deymo80f70ff2016-02-10 16:08:11 -0800639 EXPECT_EQ(234U, attempter_.server_dictated_poll_interval_);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700640 ASSERT_TRUE(attempter_.error_event_.get() == nullptr);
Darin Petkov1b003102010-11-30 10:18:36 -0800641}
642
Alex Deymo30534502015-07-20 15:06:33 -0700643TEST_F(UpdateAttempterTest, ConstructWithUpdatedMarkerTest) {
Alex Deymo906191f2015-10-12 12:22:44 -0700644 FakePrefs fake_prefs;
645 string boot_id;
646 EXPECT_TRUE(utils::GetBootId(&boot_id));
647 fake_prefs.SetString(kPrefsUpdateCompletedOnBootId, boot_id);
648 fake_system_state_.set_prefs(&fake_prefs);
Sen Jiangaeeb2e02016-06-09 15:00:16 -0700649 attempter_.Init();
650 EXPECT_EQ(UpdateStatus::UPDATED_NEED_REBOOT, attempter_.status());
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700651}
652
653TEST_F(UpdateAttempterTest, GetErrorCodeForActionTest) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700654 EXPECT_EQ(ErrorCode::kSuccess,
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700655 GetErrorCodeForAction(nullptr, ErrorCode::kSuccess));
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700656
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700657 FakeSystemState fake_system_state;
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800658 OmahaRequestAction omaha_request_action(
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700659 &fake_system_state, nullptr, nullptr, false, "");
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700660 EXPECT_EQ(ErrorCode::kOmahaRequestError,
661 GetErrorCodeForAction(&omaha_request_action, ErrorCode::kError));
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700662 OmahaResponseHandlerAction omaha_response_handler_action(&fake_system_state_);
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800663 EXPECT_EQ(
664 ErrorCode::kOmahaResponseHandlerError,
665 GetErrorCodeForAction(&omaha_response_handler_action, ErrorCode::kError));
Tianjie24f96092020-06-30 12:26:25 -0700666 DynamicPartitionControlStub dynamic_control_stub;
667 FilesystemVerifierAction filesystem_verifier_action(&dynamic_control_stub);
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800668 EXPECT_EQ(
669 ErrorCode::kFilesystemVerifierError,
670 GetErrorCodeForAction(&filesystem_verifier_action, ErrorCode::kError));
Alex Deymob15a0b82015-11-25 20:30:40 -0300671 PostinstallRunnerAction postinstall_runner_action(
Alex Deymofb905d92016-06-03 19:26:58 -0700672 fake_system_state.fake_boot_control(), fake_system_state.fake_hardware());
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800673 EXPECT_EQ(
674 ErrorCode::kPostinstallRunnerError,
675 GetErrorCodeForAction(&postinstall_runner_action, ErrorCode::kError));
Alex Deymo8427b4a2014-11-05 14:00:32 -0800676 MockAction action_mock;
677 EXPECT_CALL(action_mock, Type()).WillOnce(Return("MockAction"));
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700678 EXPECT_EQ(ErrorCode::kError,
679 GetErrorCodeForAction(&action_mock, ErrorCode::kError));
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700680}
681
Darin Petkov36275772010-10-01 11:40:57 -0700682TEST_F(UpdateAttempterTest, DisableDeltaUpdateIfNeededTest) {
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700683 attempter_.omaha_request_params_->set_delta_okay(true);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800684 EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _))
Darin Petkov36275772010-10-01 11:40:57 -0700685 .WillOnce(Return(false));
686 attempter_.DisableDeltaUpdateIfNeeded();
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700687 EXPECT_TRUE(attempter_.omaha_request_params_->delta_okay());
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800688 EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _))
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800689 .WillOnce(
690 DoAll(SetArgPointee<1>(UpdateAttempter::kMaxDeltaUpdateFailures - 1),
691 Return(true)));
Darin Petkov36275772010-10-01 11:40:57 -0700692 attempter_.DisableDeltaUpdateIfNeeded();
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700693 EXPECT_TRUE(attempter_.omaha_request_params_->delta_okay());
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800694 EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _))
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800695 .WillOnce(
696 DoAll(SetArgPointee<1>(UpdateAttempter::kMaxDeltaUpdateFailures),
697 Return(true)));
Darin Petkov36275772010-10-01 11:40:57 -0700698 attempter_.DisableDeltaUpdateIfNeeded();
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700699 EXPECT_FALSE(attempter_.omaha_request_params_->delta_okay());
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800700 EXPECT_CALL(*prefs_, GetInt64(_, _)).Times(0);
Darin Petkov36275772010-10-01 11:40:57 -0700701 attempter_.DisableDeltaUpdateIfNeeded();
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700702 EXPECT_FALSE(attempter_.omaha_request_params_->delta_okay());
Darin Petkov36275772010-10-01 11:40:57 -0700703}
704
705TEST_F(UpdateAttempterTest, MarkDeltaUpdateFailureTest) {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800706 EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _))
Darin Petkov36275772010-10-01 11:40:57 -0700707 .WillOnce(Return(false))
Ben Chan672c1f52017-10-23 15:41:39 -0700708 .WillOnce(DoAll(SetArgPointee<1>(-1), Return(true)))
709 .WillOnce(DoAll(SetArgPointee<1>(1), Return(true)))
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800710 .WillOnce(
711 DoAll(SetArgPointee<1>(UpdateAttempter::kMaxDeltaUpdateFailures),
712 Return(true)));
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800713 EXPECT_CALL(*prefs_, SetInt64(Ne(kPrefsDeltaUpdateFailures), _))
Darin Petkov2dd01092010-10-08 15:43:05 -0700714 .WillRepeatedly(Return(true));
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800715 EXPECT_CALL(*prefs_, SetInt64(kPrefsDeltaUpdateFailures, 1)).Times(2);
Gilad Arnold74b5f552014-10-07 08:17:16 -0700716 EXPECT_CALL(*prefs_, SetInt64(kPrefsDeltaUpdateFailures, 2));
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800717 EXPECT_CALL(*prefs_,
718 SetInt64(kPrefsDeltaUpdateFailures,
719 UpdateAttempter::kMaxDeltaUpdateFailures + 1));
720 for (int i = 0; i < 4; i++)
Darin Petkov36275772010-10-01 11:40:57 -0700721 attempter_.MarkDeltaUpdateFailure();
722}
723
Darin Petkov1b003102010-11-30 10:18:36 -0800724TEST_F(UpdateAttempterTest, ScheduleErrorEventActionNoEventTest) {
725 EXPECT_CALL(*processor_, EnqueueAction(_)).Times(0);
726 EXPECT_CALL(*processor_, StartProcessing()).Times(0);
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700727 EXPECT_CALL(*fake_system_state_.mock_payload_state(), UpdateFailed(_))
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800728 .Times(0);
729 OmahaResponse response;
Jay Srinivasan53173b92013-05-17 17:13:01 -0700730 string url1 = "http://url1";
Sen Jiang0affc2c2017-02-10 15:55:05 -0800731 response.packages.push_back({.payload_urls = {url1, "https://url"}});
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700732 EXPECT_CALL(*(fake_system_state_.mock_payload_state()), GetCurrentUrl())
Jay Srinivasan53173b92013-05-17 17:13:01 -0700733 .WillRepeatedly(Return(url1));
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700734 fake_system_state_.mock_payload_state()->SetResponse(response);
Darin Petkov1b003102010-11-30 10:18:36 -0800735 attempter_.ScheduleErrorEventAction();
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700736 EXPECT_EQ(url1, fake_system_state_.mock_payload_state()->GetCurrentUrl());
Darin Petkov1b003102010-11-30 10:18:36 -0800737}
738
739TEST_F(UpdateAttempterTest, ScheduleErrorEventActionTest) {
740 EXPECT_CALL(*processor_,
Amin Hassanid3f4bea2018-04-30 14:52:40 -0700741 EnqueueAction(Pointee(Property(
742 &AbstractAction::Type, OmahaRequestAction::StaticType()))));
Gilad Arnold74b5f552014-10-07 08:17:16 -0700743 EXPECT_CALL(*processor_, StartProcessing());
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700744 ErrorCode err = ErrorCode::kError;
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700745 EXPECT_CALL(*fake_system_state_.mock_payload_state(), UpdateFailed(err));
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800746 attempter_.error_event_.reset(new OmahaEvent(
747 OmahaEvent::kTypeUpdateComplete, OmahaEvent::kResultError, err));
Darin Petkov1b003102010-11-30 10:18:36 -0800748 attempter_.ScheduleErrorEventAction();
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700749 EXPECT_EQ(UpdateStatus::REPORTING_ERROR_EVENT, attempter_.status());
Darin Petkov1b003102010-11-30 10:18:36 -0800750}
751
Darin Petkove6ef2f82011-03-07 17:31:11 -0800752namespace {
Chris Sosa76a29ae2013-07-11 17:59:24 -0700753// Actions that will be built as part of an update check.
Askar Aitzhan570ca872019-04-24 11:16:12 +0200754vector<string> GetUpdateActionTypes() {
755 return {OmahaRequestAction::StaticType(),
756 OmahaResponseHandlerAction::StaticType(),
757 UpdateBootFlagsAction::StaticType(),
758 OmahaRequestAction::StaticType(),
759 DownloadAction::StaticType(),
760 OmahaRequestAction::StaticType(),
761 FilesystemVerifierAction::StaticType(),
762 PostinstallRunnerAction::StaticType(),
763 OmahaRequestAction::StaticType()};
764}
Chris Sosa76a29ae2013-07-11 17:59:24 -0700765
766// Actions that will be built as part of a user-initiated rollback.
Askar Aitzhan570ca872019-04-24 11:16:12 +0200767vector<string> GetRollbackActionTypes() {
768 return {InstallPlanAction::StaticType(),
769 PostinstallRunnerAction::StaticType()};
770}
Chris Sosa76a29ae2013-07-11 17:59:24 -0700771
Adolfo Victoria497044c2018-07-18 07:51:42 -0700772const StagingSchedule kValidStagingSchedule = {
773 {4, 10}, {10, 40}, {19, 70}, {26, 100}};
774
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700775} // namespace
Darin Petkove6ef2f82011-03-07 17:31:11 -0800776
777void UpdateAttempterTest::UpdateTestStart() {
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700778 attempter_.set_http_response_code(200);
Alex Deymo749ecf12014-10-21 20:06:57 -0700779
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700780 // Expect that the device policy is loaded by the |UpdateAttempter| at some
781 // point by calling |RefreshDevicePolicy()|.
Igor9fd76b62017-12-11 15:24:18 +0100782 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Alex Deymo749ecf12014-10-21 20:06:57 -0700783 EXPECT_CALL(*device_policy, LoadPolicy())
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800784 .Times(testing::AtLeast(1))
785 .WillRepeatedly(Return(true));
Igor9fd76b62017-12-11 15:24:18 +0100786 attempter_.policy_provider_.reset(
787 new policy::PolicyProvider(std::move(device_policy)));
Alex Deymo749ecf12014-10-21 20:06:57 -0700788
789 {
790 InSequence s;
Askar Aitzhan570ca872019-04-24 11:16:12 +0200791 for (const auto& update_action_type : GetUpdateActionTypes()) {
Alex Deymo749ecf12014-10-21 20:06:57 -0700792 EXPECT_CALL(*processor_,
Amin Hassanid3f4bea2018-04-30 14:52:40 -0700793 EnqueueAction(Pointee(
Askar Aitzhan570ca872019-04-24 11:16:12 +0200794 Property(&AbstractAction::Type, update_action_type))));
Alex Deymo749ecf12014-10-21 20:06:57 -0700795 }
Gilad Arnold74b5f552014-10-07 08:17:16 -0700796 EXPECT_CALL(*processor_, StartProcessing());
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700797 }
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700798
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -0800799 attempter_.Update("", "", "", "", false, false, 0, false, false);
Alex Deymo60ca1a72015-06-18 18:19:15 -0700800 loop_.PostTask(FROM_HERE,
801 base::Bind(&UpdateAttempterTest::UpdateTestVerify,
802 base::Unretained(this)));
Darin Petkove6ef2f82011-03-07 17:31:11 -0800803}
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700804
Darin Petkove6ef2f82011-03-07 17:31:11 -0800805void UpdateAttempterTest::UpdateTestVerify() {
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700806 EXPECT_EQ(0, attempter_.http_response_code());
807 EXPECT_EQ(&attempter_, processor_->delegate());
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700808 EXPECT_EQ(UpdateStatus::CHECKING_FOR_UPDATE, attempter_.status());
Alex Deymo60ca1a72015-06-18 18:19:15 -0700809 loop_.BreakLoop();
Darin Petkove6ef2f82011-03-07 17:31:11 -0800810}
811
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800812void UpdateAttempterTest::RollbackTestStart(bool enterprise_rollback,
813 bool valid_slot) {
Chris Sosa76a29ae2013-07-11 17:59:24 -0700814 // Create a device policy so that we can change settings.
Igor9fd76b62017-12-11 15:24:18 +0100815 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Chris Sosa76a29ae2013-07-11 17:59:24 -0700816 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
Igor9fd76b62017-12-11 15:24:18 +0100817 fake_system_state_.set_device_policy(device_policy.get());
818 if (enterprise_rollback) {
819 // We return an empty owner as this is an enterprise.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800820 EXPECT_CALL(*device_policy, GetOwner(_))
821 .WillRepeatedly(DoAll(SetArgPointee<0>(string("")), Return(true)));
Igor9fd76b62017-12-11 15:24:18 +0100822 } else {
823 // We return a fake owner as this is an owned consumer device.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800824 EXPECT_CALL(*device_policy, GetOwner(_))
825 .WillRepeatedly(DoAll(SetArgPointee<0>(string("fake.mail@fake.com")),
826 Return(true)));
Igor9fd76b62017-12-11 15:24:18 +0100827 }
828
829 attempter_.policy_provider_.reset(
830 new policy::PolicyProvider(std::move(device_policy)));
Chris Sosa76a29ae2013-07-11 17:59:24 -0700831
Alex Deymo763e7db2015-08-27 21:08:08 -0700832 if (valid_slot) {
833 BootControlInterface::Slot rollback_slot = 1;
834 LOG(INFO) << "Test Mark Bootable: "
835 << BootControlInterface::SlotName(rollback_slot);
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700836 fake_system_state_.fake_boot_control()->SetSlotBootable(rollback_slot,
837 true);
Don Garrett6646b442013-11-13 15:29:11 -0800838 }
839
Chris Sosa28e479c2013-07-12 11:39:53 -0700840 bool is_rollback_allowed = false;
Chris Sosa76a29ae2013-07-11 17:59:24 -0700841
Chris Sosad38b1132014-03-25 10:43:59 -0700842 // We only allow rollback on devices that are not enterprise enrolled and
843 // which have a valid slot to rollback to.
844 if (!enterprise_rollback && valid_slot) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800845 is_rollback_allowed = true;
Chris Sosa28e479c2013-07-12 11:39:53 -0700846 }
847
Chris Sosa28e479c2013-07-12 11:39:53 -0700848 if (is_rollback_allowed) {
Chris Sosa76a29ae2013-07-11 17:59:24 -0700849 InSequence s;
Askar Aitzhan570ca872019-04-24 11:16:12 +0200850 for (const auto& rollback_action_type : GetRollbackActionTypes()) {
Chris Sosa76a29ae2013-07-11 17:59:24 -0700851 EXPECT_CALL(*processor_,
Askar Aitzhan570ca872019-04-24 11:16:12 +0200852 EnqueueAction(Pointee(
853 Property(&AbstractAction::Type, rollback_action_type))));
Chris Sosa76a29ae2013-07-11 17:59:24 -0700854 }
Gilad Arnold74b5f552014-10-07 08:17:16 -0700855 EXPECT_CALL(*processor_, StartProcessing());
Chris Sosa76a29ae2013-07-11 17:59:24 -0700856
Chris Sosa44b9b7e2014-04-02 13:53:46 -0700857 EXPECT_TRUE(attempter_.Rollback(true));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700858 loop_.PostTask(FROM_HERE,
859 base::Bind(&UpdateAttempterTest::RollbackTestVerify,
860 base::Unretained(this)));
Chris Sosa76a29ae2013-07-11 17:59:24 -0700861 } else {
Chris Sosa44b9b7e2014-04-02 13:53:46 -0700862 EXPECT_FALSE(attempter_.Rollback(true));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700863 loop_.BreakLoop();
Chris Sosa76a29ae2013-07-11 17:59:24 -0700864 }
865}
866
867void UpdateAttempterTest::RollbackTestVerify() {
868 // Verifies the actions that were enqueued.
869 EXPECT_EQ(&attempter_, processor_->delegate());
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700870 EXPECT_EQ(UpdateStatus::ATTEMPTING_ROLLBACK, attempter_.status());
Amin Hassanid3f4bea2018-04-30 14:52:40 -0700871 EXPECT_EQ(0U, attempter_.install_plan_->partitions.size());
872 EXPECT_EQ(attempter_.install_plan_->powerwash_required, true);
Alex Deymo60ca1a72015-06-18 18:19:15 -0700873 loop_.BreakLoop();
Chris Sosa76a29ae2013-07-11 17:59:24 -0700874}
875
Darin Petkove6ef2f82011-03-07 17:31:11 -0800876TEST_F(UpdateAttempterTest, UpdateTest) {
Alex Deymo461b2592015-07-24 20:10:52 -0700877 UpdateTestStart();
Alex Deymo60ca1a72015-06-18 18:19:15 -0700878 loop_.Run();
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700879}
880
Chris Sosa76a29ae2013-07-11 17:59:24 -0700881TEST_F(UpdateAttempterTest, RollbackTest) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700882 loop_.PostTask(FROM_HERE,
883 base::Bind(&UpdateAttempterTest::RollbackTestStart,
884 base::Unretained(this),
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800885 false,
886 true));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700887 loop_.Run();
Chris Sosa76a29ae2013-07-11 17:59:24 -0700888}
889
Don Garrett6646b442013-11-13 15:29:11 -0800890TEST_F(UpdateAttempterTest, InvalidSlotRollbackTest) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700891 loop_.PostTask(FROM_HERE,
892 base::Bind(&UpdateAttempterTest::RollbackTestStart,
893 base::Unretained(this),
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800894 false,
895 false));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700896 loop_.Run();
Don Garrett6646b442013-11-13 15:29:11 -0800897}
898
Chris Sosa76a29ae2013-07-11 17:59:24 -0700899TEST_F(UpdateAttempterTest, EnterpriseRollbackTest) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700900 loop_.PostTask(FROM_HERE,
901 base::Bind(&UpdateAttempterTest::RollbackTestStart,
902 base::Unretained(this),
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800903 true,
904 true));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700905 loop_.Run();
Chris Sosa76a29ae2013-07-11 17:59:24 -0700906}
907
Thieu Le116fda32011-04-19 11:01:54 -0700908void UpdateAttempterTest::PingOmahaTestStart() {
909 EXPECT_CALL(*processor_,
Amin Hassanid3f4bea2018-04-30 14:52:40 -0700910 EnqueueAction(Pointee(Property(
911 &AbstractAction::Type, OmahaRequestAction::StaticType()))));
Gilad Arnold74b5f552014-10-07 08:17:16 -0700912 EXPECT_CALL(*processor_, StartProcessing());
Thieu Le116fda32011-04-19 11:01:54 -0700913 attempter_.PingOmaha();
Alex Deymo60ca1a72015-06-18 18:19:15 -0700914 ScheduleQuitMainLoop();
Thieu Le116fda32011-04-19 11:01:54 -0700915}
916
917TEST_F(UpdateAttempterTest, PingOmahaTest) {
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700918 EXPECT_FALSE(attempter_.waiting_for_scheduled_check_);
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700919 EXPECT_FALSE(attempter_.WasScheduleUpdatesCalled());
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700920 // Disable scheduling of subsequnet checks; we're using the |DefaultPolicy| in
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700921 // testing, which is more permissive than we want to handle here.
922 attempter_.DisableScheduleUpdates();
Alex Deymo60ca1a72015-06-18 18:19:15 -0700923 loop_.PostTask(FROM_HERE,
924 base::Bind(&UpdateAttempterTest::PingOmahaTestStart,
925 base::Unretained(this)));
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700926 brillo::MessageLoopRunMaxIterations(&loop_, 100);
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700927 EXPECT_EQ(UpdateStatus::UPDATED_NEED_REBOOT, attempter_.status());
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700928 EXPECT_TRUE(attempter_.WasScheduleUpdatesCalled());
Thieu Le116fda32011-04-19 11:01:54 -0700929}
930
Darin Petkov18c7bce2011-06-16 14:07:00 -0700931TEST_F(UpdateAttempterTest, CreatePendingErrorEventTest) {
Alex Deymo8427b4a2014-11-05 14:00:32 -0800932 MockAction action;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700933 const ErrorCode kCode = ErrorCode::kDownloadTransferError;
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(
939 static_cast<ErrorCode>(static_cast<int>(kCode) |
940 static_cast<int>(ErrorCode::kTestOmahaUrlFlag)),
941 attempter_.error_event_->error_code);
Darin Petkov18c7bce2011-06-16 14:07:00 -0700942}
943
944TEST_F(UpdateAttempterTest, CreatePendingErrorEventResumedTest) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -0700945 attempter_.install_plan_.reset(new InstallPlan);
946 attempter_.install_plan_->is_resume = true;
Alex Deymo8427b4a2014-11-05 14:00:32 -0800947 MockAction action;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700948 const ErrorCode kCode = ErrorCode::kInstallDeviceOpenError;
Darin Petkov18c7bce2011-06-16 14:07:00 -0700949 attempter_.CreatePendingErrorEvent(&action, kCode);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700950 ASSERT_NE(nullptr, attempter_.error_event_.get());
Darin Petkov18c7bce2011-06-16 14:07:00 -0700951 EXPECT_EQ(OmahaEvent::kTypeUpdateComplete, attempter_.error_event_->type);
952 EXPECT_EQ(OmahaEvent::kResultError, attempter_.error_event_->result);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700953 EXPECT_EQ(
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800954 static_cast<ErrorCode>(static_cast<int>(kCode) |
955 static_cast<int>(ErrorCode::kResumedFlag) |
956 static_cast<int>(ErrorCode::kTestOmahaUrlFlag)),
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700957 attempter_.error_event_->error_code);
Darin Petkov18c7bce2011-06-16 14:07:00 -0700958}
959
David Zeuthen8f191b22013-08-06 12:27:50 -0700960TEST_F(UpdateAttempterTest, P2PNotStartedAtStartupWhenNotEnabled) {
961 MockP2PManager mock_p2p_manager;
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700962 fake_system_state_.set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -0700963 mock_p2p_manager.fake().SetP2PEnabled(false);
964 EXPECT_CALL(mock_p2p_manager, EnsureP2PRunning()).Times(0);
965 attempter_.UpdateEngineStarted();
966}
967
968TEST_F(UpdateAttempterTest, P2PNotStartedAtStartupWhenEnabledButNotSharing) {
969 MockP2PManager mock_p2p_manager;
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700970 fake_system_state_.set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -0700971 mock_p2p_manager.fake().SetP2PEnabled(true);
972 EXPECT_CALL(mock_p2p_manager, EnsureP2PRunning()).Times(0);
973 attempter_.UpdateEngineStarted();
974}
975
976TEST_F(UpdateAttempterTest, P2PStartedAtStartupWhenEnabledAndSharing) {
977 MockP2PManager mock_p2p_manager;
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700978 fake_system_state_.set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -0700979 mock_p2p_manager.fake().SetP2PEnabled(true);
980 mock_p2p_manager.fake().SetCountSharedFilesResult(1);
Gilad Arnold74b5f552014-10-07 08:17:16 -0700981 EXPECT_CALL(mock_p2p_manager, EnsureP2PRunning());
David Zeuthen8f191b22013-08-06 12:27:50 -0700982 attempter_.UpdateEngineStarted();
983}
984
985TEST_F(UpdateAttempterTest, P2PNotEnabled) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700986 loop_.PostTask(FROM_HERE,
987 base::Bind(&UpdateAttempterTest::P2PNotEnabledStart,
988 base::Unretained(this)));
989 loop_.Run();
David Zeuthen8f191b22013-08-06 12:27:50 -0700990}
Alex Deymo60ca1a72015-06-18 18:19:15 -0700991
David Zeuthen8f191b22013-08-06 12:27:50 -0700992void UpdateAttempterTest::P2PNotEnabledStart() {
993 // If P2P is not enabled, check that we do not attempt housekeeping
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700994 // and do not convey that P2P is to be used.
David Zeuthen8f191b22013-08-06 12:27:50 -0700995 MockP2PManager mock_p2p_manager;
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700996 fake_system_state_.set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -0700997 mock_p2p_manager.fake().SetP2PEnabled(false);
998 EXPECT_CALL(mock_p2p_manager, PerformHousekeeping()).Times(0);
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -0800999 attempter_.Update("", "", "", "", false, false, 0, false, false);
Alex Deymo60ca1a72015-06-18 18:19:15 -07001000 EXPECT_FALSE(actual_using_p2p_for_downloading_);
Gilad Arnold74b5f552014-10-07 08:17:16 -07001001 EXPECT_FALSE(actual_using_p2p_for_sharing());
Alex Deymo60ca1a72015-06-18 18:19:15 -07001002 ScheduleQuitMainLoop();
David Zeuthen8f191b22013-08-06 12:27:50 -07001003}
1004
1005TEST_F(UpdateAttempterTest, P2PEnabledStartingFails) {
Alex Deymo60ca1a72015-06-18 18:19:15 -07001006 loop_.PostTask(FROM_HERE,
1007 base::Bind(&UpdateAttempterTest::P2PEnabledStartingFailsStart,
1008 base::Unretained(this)));
1009 loop_.Run();
David Zeuthen8f191b22013-08-06 12:27:50 -07001010}
Alex Deymo60ca1a72015-06-18 18:19:15 -07001011
David Zeuthen8f191b22013-08-06 12:27:50 -07001012void UpdateAttempterTest::P2PEnabledStartingFailsStart() {
Jae Hoon Kimedb65502019-06-14 11:52:17 -07001013 // If P2P is enabled, but starting it fails ensure we don't do
1014 // any housekeeping and do not convey that P2P should be used.
David Zeuthen8f191b22013-08-06 12:27:50 -07001015 MockP2PManager mock_p2p_manager;
Gilad Arnold5bb4c902014-04-10 12:32:13 -07001016 fake_system_state_.set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -07001017 mock_p2p_manager.fake().SetP2PEnabled(true);
1018 mock_p2p_manager.fake().SetEnsureP2PRunningResult(false);
1019 mock_p2p_manager.fake().SetPerformHousekeepingResult(false);
1020 EXPECT_CALL(mock_p2p_manager, PerformHousekeeping()).Times(0);
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001021 attempter_.Update("", "", "", "", false, false, 0, false, false);
Gilad Arnold74b5f552014-10-07 08:17:16 -07001022 EXPECT_FALSE(actual_using_p2p_for_downloading());
1023 EXPECT_FALSE(actual_using_p2p_for_sharing());
Alex Deymo60ca1a72015-06-18 18:19:15 -07001024 ScheduleQuitMainLoop();
David Zeuthen8f191b22013-08-06 12:27:50 -07001025}
1026
1027TEST_F(UpdateAttempterTest, P2PEnabledHousekeepingFails) {
Alex Deymo60ca1a72015-06-18 18:19:15 -07001028 loop_.PostTask(
1029 FROM_HERE,
1030 base::Bind(&UpdateAttempterTest::P2PEnabledHousekeepingFailsStart,
1031 base::Unretained(this)));
1032 loop_.Run();
David Zeuthen8f191b22013-08-06 12:27:50 -07001033}
Alex Deymo60ca1a72015-06-18 18:19:15 -07001034
David Zeuthen8f191b22013-08-06 12:27:50 -07001035void UpdateAttempterTest::P2PEnabledHousekeepingFailsStart() {
Jae Hoon Kimedb65502019-06-14 11:52:17 -07001036 // If P2P is enabled, starting it works but housekeeping fails, ensure
1037 // we do not convey P2P is to be used.
David Zeuthen8f191b22013-08-06 12:27:50 -07001038 MockP2PManager mock_p2p_manager;
Gilad Arnold5bb4c902014-04-10 12:32:13 -07001039 fake_system_state_.set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -07001040 mock_p2p_manager.fake().SetP2PEnabled(true);
1041 mock_p2p_manager.fake().SetEnsureP2PRunningResult(true);
1042 mock_p2p_manager.fake().SetPerformHousekeepingResult(false);
Gilad Arnold74b5f552014-10-07 08:17:16 -07001043 EXPECT_CALL(mock_p2p_manager, PerformHousekeeping());
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001044 attempter_.Update("", "", "", "", false, false, 0, false, false);
Gilad Arnold74b5f552014-10-07 08:17:16 -07001045 EXPECT_FALSE(actual_using_p2p_for_downloading());
1046 EXPECT_FALSE(actual_using_p2p_for_sharing());
Alex Deymo60ca1a72015-06-18 18:19:15 -07001047 ScheduleQuitMainLoop();
David Zeuthen8f191b22013-08-06 12:27:50 -07001048}
1049
1050TEST_F(UpdateAttempterTest, P2PEnabled) {
Alex Deymo60ca1a72015-06-18 18:19:15 -07001051 loop_.PostTask(FROM_HERE,
1052 base::Bind(&UpdateAttempterTest::P2PEnabledStart,
1053 base::Unretained(this)));
1054 loop_.Run();
David Zeuthen8f191b22013-08-06 12:27:50 -07001055}
Alex Deymo60ca1a72015-06-18 18:19:15 -07001056
David Zeuthen8f191b22013-08-06 12:27:50 -07001057void UpdateAttempterTest::P2PEnabledStart() {
1058 MockP2PManager mock_p2p_manager;
Gilad Arnold5bb4c902014-04-10 12:32:13 -07001059 fake_system_state_.set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -07001060 // If P2P is enabled and starting it works, check that we performed
Jae Hoon Kimedb65502019-06-14 11:52:17 -07001061 // housekeeping and that we convey P2P should be used.
David Zeuthen8f191b22013-08-06 12:27:50 -07001062 mock_p2p_manager.fake().SetP2PEnabled(true);
1063 mock_p2p_manager.fake().SetEnsureP2PRunningResult(true);
1064 mock_p2p_manager.fake().SetPerformHousekeepingResult(true);
Gilad Arnold74b5f552014-10-07 08:17:16 -07001065 EXPECT_CALL(mock_p2p_manager, PerformHousekeeping());
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001066 attempter_.Update("", "", "", "", false, false, 0, false, false);
Gilad Arnold74b5f552014-10-07 08:17:16 -07001067 EXPECT_TRUE(actual_using_p2p_for_downloading());
1068 EXPECT_TRUE(actual_using_p2p_for_sharing());
Alex Deymo60ca1a72015-06-18 18:19:15 -07001069 ScheduleQuitMainLoop();
David Zeuthen8f191b22013-08-06 12:27:50 -07001070}
1071
1072TEST_F(UpdateAttempterTest, P2PEnabledInteractive) {
Alex Deymo60ca1a72015-06-18 18:19:15 -07001073 loop_.PostTask(FROM_HERE,
1074 base::Bind(&UpdateAttempterTest::P2PEnabledInteractiveStart,
1075 base::Unretained(this)));
1076 loop_.Run();
David Zeuthen8f191b22013-08-06 12:27:50 -07001077}
Alex Deymo60ca1a72015-06-18 18:19:15 -07001078
David Zeuthen8f191b22013-08-06 12:27:50 -07001079void UpdateAttempterTest::P2PEnabledInteractiveStart() {
1080 MockP2PManager mock_p2p_manager;
Gilad Arnold5bb4c902014-04-10 12:32:13 -07001081 fake_system_state_.set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -07001082 // For an interactive check, if P2P is enabled and starting it
1083 // works, check that we performed housekeeping and that we convey
Jae Hoon Kimedb65502019-06-14 11:52:17 -07001084 // P2P should be used for sharing but NOT for downloading.
David Zeuthen8f191b22013-08-06 12:27:50 -07001085 mock_p2p_manager.fake().SetP2PEnabled(true);
1086 mock_p2p_manager.fake().SetEnsureP2PRunningResult(true);
1087 mock_p2p_manager.fake().SetPerformHousekeepingResult(true);
Gilad Arnold74b5f552014-10-07 08:17:16 -07001088 EXPECT_CALL(mock_p2p_manager, PerformHousekeeping());
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001089 attempter_.Update("",
1090 "",
1091 "",
1092 "",
1093 false,
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001094 false,
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -07001095 /*rollback_allowed_milestones=*/0,
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001096 false,
1097 /*interactive=*/true);
Gilad Arnold74b5f552014-10-07 08:17:16 -07001098 EXPECT_FALSE(actual_using_p2p_for_downloading());
1099 EXPECT_TRUE(actual_using_p2p_for_sharing());
Alex Deymo60ca1a72015-06-18 18:19:15 -07001100 ScheduleQuitMainLoop();
David Zeuthen8f191b22013-08-06 12:27:50 -07001101}
1102
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001103TEST_F(UpdateAttempterTest, ReadScatterFactorFromPolicy) {
Alex Deymo60ca1a72015-06-18 18:19:15 -07001104 loop_.PostTask(
1105 FROM_HERE,
1106 base::Bind(&UpdateAttempterTest::ReadScatterFactorFromPolicyTestStart,
1107 base::Unretained(this)));
1108 loop_.Run();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001109}
1110
1111// Tests that the scatter_factor_in_seconds value is properly fetched
1112// from the device policy.
1113void UpdateAttempterTest::ReadScatterFactorFromPolicyTestStart() {
Ben Chan9abb7632014-08-07 00:10:53 -07001114 int64_t scatter_factor_in_seconds = 36000;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001115
Igor9fd76b62017-12-11 15:24:18 +01001116 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001117 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
Igor9fd76b62017-12-11 15:24:18 +01001118 fake_system_state_.set_device_policy(device_policy.get());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001119
1120 EXPECT_CALL(*device_policy, GetScatterFactorInSeconds(_))
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001121 .WillRepeatedly(
1122 DoAll(SetArgPointee<0>(scatter_factor_in_seconds), Return(true)));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001123
Igor9fd76b62017-12-11 15:24:18 +01001124 attempter_.policy_provider_.reset(
1125 new policy::PolicyProvider(std::move(device_policy)));
1126
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001127 attempter_.Update("", "", "", "", false, false, 0, false, false);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001128 EXPECT_EQ(scatter_factor_in_seconds, attempter_.scatter_factor_.InSeconds());
1129
Alex Deymo60ca1a72015-06-18 18:19:15 -07001130 ScheduleQuitMainLoop();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001131}
1132
1133TEST_F(UpdateAttempterTest, DecrementUpdateCheckCountTest) {
Alex Deymo60ca1a72015-06-18 18:19:15 -07001134 loop_.PostTask(
1135 FROM_HERE,
1136 base::Bind(&UpdateAttempterTest::DecrementUpdateCheckCountTestStart,
1137 base::Unretained(this)));
1138 loop_.Run();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001139}
1140
1141void UpdateAttempterTest::DecrementUpdateCheckCountTestStart() {
1142 // Tests that the scatter_factor_in_seconds value is properly fetched
1143 // from the device policy and is decremented if value > 0.
Ben Chan9abb7632014-08-07 00:10:53 -07001144 int64_t initial_value = 5;
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001145 FakePrefs fake_prefs;
1146 attempter_.prefs_ = &fake_prefs;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001147
Gilad Arnold5bb4c902014-04-10 12:32:13 -07001148 fake_system_state_.fake_hardware()->SetIsOOBEComplete(Time::UnixEpoch());
Jay Srinivasan08fce042012-06-07 16:31:01 -07001149
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001150 EXPECT_TRUE(fake_prefs.SetInt64(kPrefsUpdateCheckCount, initial_value));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001151
Ben Chan9abb7632014-08-07 00:10:53 -07001152 int64_t scatter_factor_in_seconds = 10;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001153
Igor9fd76b62017-12-11 15:24:18 +01001154 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001155 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
Igor9fd76b62017-12-11 15:24:18 +01001156 fake_system_state_.set_device_policy(device_policy.get());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001157
1158 EXPECT_CALL(*device_policy, GetScatterFactorInSeconds(_))
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001159 .WillRepeatedly(
1160 DoAll(SetArgPointee<0>(scatter_factor_in_seconds), Return(true)));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001161
Igor9fd76b62017-12-11 15:24:18 +01001162 attempter_.policy_provider_.reset(
1163 new policy::PolicyProvider(std::move(device_policy)));
1164
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001165 attempter_.Update("", "", "", "", false, false, 0, false, false);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001166 EXPECT_EQ(scatter_factor_in_seconds, attempter_.scatter_factor_.InSeconds());
1167
1168 // Make sure the file still exists.
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001169 EXPECT_TRUE(fake_prefs.Exists(kPrefsUpdateCheckCount));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001170
Ben Chan9abb7632014-08-07 00:10:53 -07001171 int64_t new_value;
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001172 EXPECT_TRUE(fake_prefs.GetInt64(kPrefsUpdateCheckCount, &new_value));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001173 EXPECT_EQ(initial_value - 1, new_value);
1174
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001175 EXPECT_TRUE(
1176 attempter_.omaha_request_params_->update_check_count_wait_enabled());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001177
1178 // However, if the count is already 0, it's not decremented. Test that.
1179 initial_value = 0;
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001180 EXPECT_TRUE(fake_prefs.SetInt64(kPrefsUpdateCheckCount, initial_value));
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001181 attempter_.Update("", "", "", "", false, false, 0, false, false);
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001182 EXPECT_TRUE(fake_prefs.Exists(kPrefsUpdateCheckCount));
1183 EXPECT_TRUE(fake_prefs.GetInt64(kPrefsUpdateCheckCount, &new_value));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001184 EXPECT_EQ(initial_value, new_value);
1185
Alex Deymo60ca1a72015-06-18 18:19:15 -07001186 ScheduleQuitMainLoop();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001187}
1188
Jay Srinivasan08fce042012-06-07 16:31:01 -07001189TEST_F(UpdateAttempterTest, NoScatteringDoneDuringManualUpdateTestStart) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001190 loop_.PostTask(
1191 FROM_HERE,
1192 base::Bind(
1193 &UpdateAttempterTest::NoScatteringDoneDuringManualUpdateTestStart,
1194 base::Unretained(this)));
Alex Deymo60ca1a72015-06-18 18:19:15 -07001195 loop_.Run();
Jay Srinivasan08fce042012-06-07 16:31:01 -07001196}
1197
1198void UpdateAttempterTest::NoScatteringDoneDuringManualUpdateTestStart() {
1199 // Tests that no scattering logic is enabled if the update check
1200 // is manually done (as opposed to a scheduled update check)
Ben Chan9abb7632014-08-07 00:10:53 -07001201 int64_t initial_value = 8;
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001202 FakePrefs fake_prefs;
1203 attempter_.prefs_ = &fake_prefs;
Jay Srinivasan08fce042012-06-07 16:31:01 -07001204
Gilad Arnold5bb4c902014-04-10 12:32:13 -07001205 fake_system_state_.fake_hardware()->SetIsOOBEComplete(Time::UnixEpoch());
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001206 fake_system_state_.set_prefs(&fake_prefs);
Jay Srinivasan08fce042012-06-07 16:31:01 -07001207
Adolfo Victoriad3a1e352018-07-16 11:40:47 -07001208 EXPECT_TRUE(
1209 fake_prefs.SetInt64(kPrefsWallClockScatteringWaitPeriod, initial_value));
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001210 EXPECT_TRUE(fake_prefs.SetInt64(kPrefsUpdateCheckCount, initial_value));
Jay Srinivasan08fce042012-06-07 16:31:01 -07001211
1212 // make sure scatter_factor is non-zero as scattering is disabled
1213 // otherwise.
Ben Chan9abb7632014-08-07 00:10:53 -07001214 int64_t scatter_factor_in_seconds = 50;
Jay Srinivasan08fce042012-06-07 16:31:01 -07001215
Igor9fd76b62017-12-11 15:24:18 +01001216 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Jay Srinivasan08fce042012-06-07 16:31:01 -07001217 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
Igor9fd76b62017-12-11 15:24:18 +01001218 fake_system_state_.set_device_policy(device_policy.get());
Jay Srinivasan08fce042012-06-07 16:31:01 -07001219
1220 EXPECT_CALL(*device_policy, GetScatterFactorInSeconds(_))
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001221 .WillRepeatedly(
1222 DoAll(SetArgPointee<0>(scatter_factor_in_seconds), Return(true)));
Jay Srinivasan08fce042012-06-07 16:31:01 -07001223
Igor9fd76b62017-12-11 15:24:18 +01001224 attempter_.policy_provider_.reset(
1225 new policy::PolicyProvider(std::move(device_policy)));
1226
Gilad Arnoldb92f0df2013-01-10 16:32:45 -08001227 // Trigger an interactive check so we can test that scattering is disabled.
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001228 attempter_.Update("",
1229 "",
1230 "",
1231 "",
1232 false,
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001233 false,
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -07001234 /*rollback_allowed_milestones=*/0,
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001235 false,
1236 /*interactive=*/true);
Jay Srinivasan08fce042012-06-07 16:31:01 -07001237 EXPECT_EQ(scatter_factor_in_seconds, attempter_.scatter_factor_.InSeconds());
1238
1239 // Make sure scattering is disabled for manual (i.e. user initiated) update
Jay Srinivasan21be0752012-07-25 15:44:56 -07001240 // checks and all artifacts are removed.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001241 EXPECT_FALSE(
1242 attempter_.omaha_request_params_->wall_clock_based_wait_enabled());
Adolfo Victoriad3a1e352018-07-16 11:40:47 -07001243 EXPECT_FALSE(fake_prefs.Exists(kPrefsWallClockScatteringWaitPeriod));
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001244 EXPECT_EQ(0, attempter_.omaha_request_params_->waiting_period().InSeconds());
1245 EXPECT_FALSE(
1246 attempter_.omaha_request_params_->update_check_count_wait_enabled());
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001247 EXPECT_FALSE(fake_prefs.Exists(kPrefsUpdateCheckCount));
Jay Srinivasan08fce042012-06-07 16:31:01 -07001248
Alex Deymo60ca1a72015-06-18 18:19:15 -07001249 ScheduleQuitMainLoop();
Jay Srinivasan08fce042012-06-07 16:31:01 -07001250}
1251
Adolfo Victoria497044c2018-07-18 07:51:42 -07001252void UpdateAttempterTest::SetUpStagingTest(const StagingSchedule& schedule,
1253 FakePrefs* prefs) {
1254 attempter_.prefs_ = prefs;
1255 fake_system_state_.set_prefs(prefs);
1256
1257 int64_t initial_value = 8;
1258 EXPECT_TRUE(
1259 prefs->SetInt64(kPrefsWallClockScatteringWaitPeriod, initial_value));
1260 EXPECT_TRUE(prefs->SetInt64(kPrefsUpdateCheckCount, initial_value));
1261 attempter_.scatter_factor_ = TimeDelta::FromSeconds(20);
1262
1263 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
1264 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
1265 fake_system_state_.set_device_policy(device_policy.get());
1266 EXPECT_CALL(*device_policy, GetDeviceUpdateStagingSchedule(_))
1267 .WillRepeatedly(DoAll(SetArgPointee<0>(schedule), Return(true)));
1268
1269 attempter_.policy_provider_.reset(
1270 new policy::PolicyProvider(std::move(device_policy)));
1271}
1272
1273TEST_F(UpdateAttempterTest, StagingSetsPrefsAndTurnsOffScattering) {
1274 loop_.PostTask(
1275 FROM_HERE,
1276 base::Bind(
1277 &UpdateAttempterTest::StagingSetsPrefsAndTurnsOffScatteringStart,
1278 base::Unretained(this)));
1279 loop_.Run();
1280}
1281
1282void UpdateAttempterTest::StagingSetsPrefsAndTurnsOffScatteringStart() {
1283 // Tests that staging sets its prefs properly and turns off scattering.
1284 fake_system_state_.fake_hardware()->SetIsOOBEComplete(Time::UnixEpoch());
1285 FakePrefs fake_prefs;
1286 SetUpStagingTest(kValidStagingSchedule, &fake_prefs);
1287
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001288 attempter_.Update("", "", "", "", false, false, 0, false, false);
Adolfo Victoria497044c2018-07-18 07:51:42 -07001289 // Check that prefs have the correct values.
1290 int64_t update_count;
1291 EXPECT_TRUE(fake_prefs.GetInt64(kPrefsUpdateCheckCount, &update_count));
1292 int64_t waiting_time_days;
1293 EXPECT_TRUE(fake_prefs.GetInt64(kPrefsWallClockStagingWaitPeriod,
1294 &waiting_time_days));
1295 EXPECT_GT(waiting_time_days, 0);
1296 // Update count should have been decremented.
1297 EXPECT_EQ(7, update_count);
1298 // Check that Omaha parameters were updated correctly.
1299 EXPECT_TRUE(
1300 attempter_.omaha_request_params_->update_check_count_wait_enabled());
1301 EXPECT_TRUE(
1302 attempter_.omaha_request_params_->wall_clock_based_wait_enabled());
1303 EXPECT_EQ(waiting_time_days,
1304 attempter_.omaha_request_params_->waiting_period().InDays());
1305 // Check class variables.
1306 EXPECT_EQ(waiting_time_days, attempter_.staging_wait_time_.InDays());
1307 EXPECT_EQ(kValidStagingSchedule, attempter_.staging_schedule_);
1308 // Check that scattering is turned off
1309 EXPECT_EQ(0, attempter_.scatter_factor_.InSeconds());
1310 EXPECT_FALSE(fake_prefs.Exists(kPrefsWallClockScatteringWaitPeriod));
1311
1312 ScheduleQuitMainLoop();
1313}
1314
1315void UpdateAttempterTest::CheckStagingOff() {
1316 // Check that all prefs were removed.
1317 EXPECT_FALSE(attempter_.prefs_->Exists(kPrefsUpdateCheckCount));
1318 EXPECT_FALSE(attempter_.prefs_->Exists(kPrefsWallClockScatteringWaitPeriod));
1319 EXPECT_FALSE(attempter_.prefs_->Exists(kPrefsWallClockStagingWaitPeriod));
1320 // Check that the Omaha parameters have the correct value.
1321 EXPECT_EQ(0, attempter_.omaha_request_params_->waiting_period().InDays());
1322 EXPECT_EQ(attempter_.omaha_request_params_->waiting_period(),
1323 attempter_.staging_wait_time_);
1324 EXPECT_FALSE(
1325 attempter_.omaha_request_params_->update_check_count_wait_enabled());
1326 EXPECT_FALSE(
1327 attempter_.omaha_request_params_->wall_clock_based_wait_enabled());
1328 // Check that scattering is turned off too.
1329 EXPECT_EQ(0, attempter_.scatter_factor_.InSeconds());
1330}
1331
1332TEST_F(UpdateAttempterTest, StagingOffIfInteractive) {
1333 loop_.PostTask(FROM_HERE,
1334 base::Bind(&UpdateAttempterTest::StagingOffIfInteractiveStart,
1335 base::Unretained(this)));
1336 loop_.Run();
1337}
1338
1339void UpdateAttempterTest::StagingOffIfInteractiveStart() {
1340 // Tests that staging is turned off when an interactive update is requested.
1341 fake_system_state_.fake_hardware()->SetIsOOBEComplete(Time::UnixEpoch());
1342 FakePrefs fake_prefs;
1343 SetUpStagingTest(kValidStagingSchedule, &fake_prefs);
1344
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001345 attempter_.Update(
1346 "", "", "", "", false, false, 0, false, /* interactive = */ true);
Adolfo Victoria497044c2018-07-18 07:51:42 -07001347 CheckStagingOff();
1348
1349 ScheduleQuitMainLoop();
1350}
1351
1352TEST_F(UpdateAttempterTest, StagingOffIfOobe) {
1353 loop_.PostTask(FROM_HERE,
1354 base::Bind(&UpdateAttempterTest::StagingOffIfOobeStart,
1355 base::Unretained(this)));
1356 loop_.Run();
1357}
1358
1359void UpdateAttempterTest::StagingOffIfOobeStart() {
1360 // Tests that staging is turned off if OOBE hasn't been completed.
1361 fake_system_state_.fake_hardware()->SetIsOOBEEnabled(true);
1362 fake_system_state_.fake_hardware()->UnsetIsOOBEComplete();
1363 FakePrefs fake_prefs;
1364 SetUpStagingTest(kValidStagingSchedule, &fake_prefs);
1365
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001366 attempter_.Update(
1367 "", "", "", "", false, false, 0, false, /* interactive = */ true);
Adolfo Victoria497044c2018-07-18 07:51:42 -07001368 CheckStagingOff();
1369
1370 ScheduleQuitMainLoop();
1371}
1372
David Zeuthen985b1122013-10-09 12:13:15 -07001373// Checks that we only report daily metrics at most every 24 hours.
1374TEST_F(UpdateAttempterTest, ReportDailyMetrics) {
1375 FakeClock fake_clock;
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001376 FakePrefs fake_prefs;
David Zeuthen985b1122013-10-09 12:13:15 -07001377
Gilad Arnold5bb4c902014-04-10 12:32:13 -07001378 fake_system_state_.set_clock(&fake_clock);
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001379 fake_system_state_.set_prefs(&fake_prefs);
David Zeuthen985b1122013-10-09 12:13:15 -07001380
1381 Time epoch = Time::FromInternalValue(0);
1382 fake_clock.SetWallclockTime(epoch);
1383
1384 // If there is no kPrefsDailyMetricsLastReportedAt state variable,
1385 // we should report.
1386 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1387 // We should not report again if no time has passed.
1388 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1389
1390 // We should not report if only 10 hours has passed.
1391 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(10));
1392 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1393
1394 // We should not report if only 24 hours - 1 sec has passed.
1395 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(24) -
1396 TimeDelta::FromSeconds(1));
1397 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1398
1399 // We should report if 24 hours has passed.
1400 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(24));
1401 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1402
1403 // But then we should not report again..
1404 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1405
1406 // .. until another 24 hours has passed
1407 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(47));
1408 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1409 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(48));
1410 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1411 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1412
1413 // .. and another 24 hours
1414 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(71));
1415 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1416 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(72));
1417 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1418 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1419
1420 // If the span between time of reporting and present time is
1421 // negative, we report. This is in order to reset the timestamp and
1422 // avoid an edge condition whereby a distant point in the future is
1423 // in the state variable resulting in us never ever reporting again.
1424 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(71));
1425 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1426 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1427
1428 // In this case we should not update until the clock reads 71 + 24 = 95.
1429 // Check that.
1430 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(94));
1431 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1432 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(95));
1433 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1434 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
David Zeuthen985b1122013-10-09 12:13:15 -07001435}
1436
David Zeuthen3c55abd2013-10-14 12:48:03 -07001437TEST_F(UpdateAttempterTest, BootTimeInUpdateMarkerFile) {
David Zeuthen3c55abd2013-10-14 12:48:03 -07001438 FakeClock fake_clock;
1439 fake_clock.SetBootTime(Time::FromTimeT(42));
Gilad Arnold5bb4c902014-04-10 12:32:13 -07001440 fake_system_state_.set_clock(&fake_clock);
Alex Deymo906191f2015-10-12 12:22:44 -07001441 FakePrefs fake_prefs;
1442 fake_system_state_.set_prefs(&fake_prefs);
Sen Jiangaeeb2e02016-06-09 15:00:16 -07001443 attempter_.Init();
David Zeuthen3c55abd2013-10-14 12:48:03 -07001444
1445 Time boot_time;
Sen Jiangaeeb2e02016-06-09 15:00:16 -07001446 EXPECT_FALSE(attempter_.GetBootTimeAtUpdate(&boot_time));
David Zeuthen3c55abd2013-10-14 12:48:03 -07001447
Sen Jiangaeeb2e02016-06-09 15:00:16 -07001448 attempter_.WriteUpdateCompletedMarker();
David Zeuthen3c55abd2013-10-14 12:48:03 -07001449
Sen Jiangaeeb2e02016-06-09 15:00:16 -07001450 EXPECT_TRUE(attempter_.GetBootTimeAtUpdate(&boot_time));
David Zeuthen3c55abd2013-10-14 12:48:03 -07001451 EXPECT_EQ(boot_time.ToTimeT(), 42);
1452}
1453
David Pursell02c18642014-11-06 11:26:11 -08001454TEST_F(UpdateAttempterTest, AnyUpdateSourceAllowedUnofficial) {
1455 fake_system_state_.fake_hardware()->SetIsOfficialBuild(false);
1456 EXPECT_TRUE(attempter_.IsAnyUpdateSourceAllowed());
1457}
1458
1459TEST_F(UpdateAttempterTest, AnyUpdateSourceAllowedOfficialDevmode) {
1460 fake_system_state_.fake_hardware()->SetIsOfficialBuild(true);
Sen Jiange67bb5b2016-06-20 15:53:56 -07001461 fake_system_state_.fake_hardware()->SetAreDevFeaturesEnabled(true);
David Pursell02c18642014-11-06 11:26:11 -08001462 EXPECT_TRUE(attempter_.IsAnyUpdateSourceAllowed());
1463}
1464
1465TEST_F(UpdateAttempterTest, AnyUpdateSourceDisallowedOfficialNormal) {
1466 fake_system_state_.fake_hardware()->SetIsOfficialBuild(true);
Sen Jiange67bb5b2016-06-20 15:53:56 -07001467 fake_system_state_.fake_hardware()->SetAreDevFeaturesEnabled(false);
David Pursell02c18642014-11-06 11:26:11 -08001468 EXPECT_FALSE(attempter_.IsAnyUpdateSourceAllowed());
1469}
1470
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001471// TODO(kimjae): Follow testing pattern with params for |CheckForInstall()|.
1472// When adding, remove older tests related to |CheckForInstall()|.
1473TEST_F(UpdateAttempterTest, CheckForInstallNotIdleFails) {
1474 for (const auto status : kNonIdleUpdateStatuses) {
1475 // GIVEN a non-idle status.
1476 attempter_.status_ = status;
Xiaochu Liu8ba486f2018-11-06 11:14:10 -08001477
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001478 EXPECT_FALSE(attempter_.CheckForInstall({}, ""));
1479 }
Xiaochu Liu8ba486f2018-11-06 11:14:10 -08001480}
1481
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001482TEST_F(UpdateAttempterTest, CheckForUpdateNotIdleFails) {
1483 for (const auto status : kNonIdleUpdateStatuses) {
1484 // GIVEN a non-idle status.
1485 cfu_params_.status = status;
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001486
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001487 // THEN |ScheduleUpdates()| should not be called.
1488 cfu_params_.should_schedule_updates_be_called = false;
1489 // THEN result should indicate failure.
1490 cfu_params_.expected_result = false;
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001491
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001492 TestCheckForUpdate();
1493 }
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001494}
1495
1496TEST_F(UpdateAttempterTest, CheckForUpdateOfficalBuildClearsSource) {
1497 // GIVEN a official build.
1498
1499 // THEN we except forced app version + forced omaha url to be cleared.
1500
1501 TestCheckForUpdate();
1502}
1503
1504TEST_F(UpdateAttempterTest, CheckForUpdateUnofficialBuildChangesSource) {
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001505 // GIVEN a nonofficial build with dev features enabled.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001506 cfu_params_.is_official_build = false;
1507 cfu_params_.are_dev_features_enabled = true;
1508
1509 // THEN the forced app version + forced omaha url changes based on input.
1510 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1511 cfu_params_.expected_forced_omaha_url = cfu_params_.omaha_url;
1512
1513 TestCheckForUpdate();
1514}
1515
1516TEST_F(UpdateAttempterTest, CheckForUpdateOfficialBuildScheduledAUTest) {
1517 // GIVEN a scheduled autest omaha url.
1518 cfu_params_.omaha_url = "autest-scheduled";
1519
1520 // THEN forced app version is cleared.
1521 // THEN forced omaha url changes to default constant.
1522 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1523
1524 TestCheckForUpdate();
1525}
1526
1527TEST_F(UpdateAttempterTest, CheckForUpdateUnofficialBuildScheduledAUTest) {
1528 // GIVEN a scheduled autest omaha url.
1529 cfu_params_.omaha_url = "autest-scheduled";
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001530 // GIVEN a nonofficial build with dev features enabled.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001531 cfu_params_.is_official_build = false;
1532 cfu_params_.are_dev_features_enabled = true;
1533
1534 // THEN forced app version changes based on input.
1535 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1536 // THEN forced omaha url changes to default constant.
1537 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1538
1539 TestCheckForUpdate();
1540}
1541
1542TEST_F(UpdateAttempterTest, CheckForUpdateOfficialBuildAUTest) {
1543 // GIVEN a autest omaha url.
1544 cfu_params_.omaha_url = "autest";
1545
1546 // THEN forced app version is cleared.
1547 // THEN forced omaha url changes to default constant.
1548 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1549
1550 TestCheckForUpdate();
1551}
1552
1553TEST_F(UpdateAttempterTest, CheckForUpdateUnofficialBuildAUTest) {
1554 // GIVEN a autest omha url.
1555 cfu_params_.omaha_url = "autest";
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001556 // GIVEN a nonofficial build with dev features enabled.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001557 cfu_params_.is_official_build = false;
1558 cfu_params_.are_dev_features_enabled = true;
1559
1560 // THEN forced app version changes based on input.
1561 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1562 // THEN forced omaha url changes to default constant.
1563 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1564
1565 TestCheckForUpdate();
1566}
1567
1568TEST_F(UpdateAttempterTest,
1569 CheckForUpdateNonInteractiveOfficialBuildScheduledAUTest) {
1570 // GIVEN a scheduled autest omaha url.
1571 cfu_params_.omaha_url = "autest-scheduled";
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001572 // GIVEN a noninteractive update.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001573 cfu_params_.flags = UpdateAttemptFlags::kFlagNonInteractive;
1574
1575 // THEN forced app version is cleared.
1576 // THEN forced omaha url changes to default constant.
1577 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1578
1579 TestCheckForUpdate();
1580}
1581
1582TEST_F(UpdateAttempterTest,
1583 CheckForUpdateNonInteractiveUnofficialBuildScheduledAUTest) {
1584 // GIVEN a scheduled autest omaha url.
1585 cfu_params_.omaha_url = "autest-scheduled";
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001586 // GIVEN a noninteractive update.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001587 cfu_params_.flags = UpdateAttemptFlags::kFlagNonInteractive;
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001588 // GIVEN a nonofficial build with dev features enabled.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001589 cfu_params_.is_official_build = false;
1590 cfu_params_.are_dev_features_enabled = true;
1591
1592 // THEN forced app version changes based on input.
1593 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1594 // THEN forced omaha url changes to default constant.
1595 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1596
1597 TestCheckForUpdate();
1598}
1599
1600TEST_F(UpdateAttempterTest, CheckForUpdateNonInteractiveOfficialBuildAUTest) {
1601 // GIVEN a autest omaha url.
1602 cfu_params_.omaha_url = "autest";
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001603 // GIVEN a noninteractive update.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001604 cfu_params_.flags = UpdateAttemptFlags::kFlagNonInteractive;
1605
1606 // THEN forced app version is cleared.
1607 // THEN forced omaha url changes to default constant.
1608 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1609
1610 TestCheckForUpdate();
1611}
1612
1613TEST_F(UpdateAttempterTest, CheckForUpdateNonInteractiveUnofficialBuildAUTest) {
1614 // GIVEN a autest omaha url.
1615 cfu_params_.omaha_url = "autest";
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001616 // GIVEN a noninteractive update.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001617 cfu_params_.flags = UpdateAttemptFlags::kFlagNonInteractive;
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001618 // GIVEN a nonofficial build with dev features enabled.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001619 cfu_params_.is_official_build = false;
1620 cfu_params_.are_dev_features_enabled = true;
1621
1622 // THEN forced app version changes based on input.
1623 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1624 // THEN forced omaha url changes to default constant.
1625 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1626
1627 TestCheckForUpdate();
David Pursell02c18642014-11-06 11:26:11 -08001628}
1629
Jae Hoon Kim2b73ac22019-07-02 11:17:24 -07001630TEST_F(UpdateAttempterTest, CheckForUpdateMissingForcedCallback1) {
1631 // GIVEN a official build.
1632 // GIVEN forced callback is not set.
1633 attempter_.set_forced_update_pending_callback(nullptr);
1634
1635 // THEN we except forced app version + forced omaha url to be cleared.
1636 // THEN |ScheduleUpdates()| should not be called.
1637 cfu_params_.should_schedule_updates_be_called = false;
1638
1639 TestCheckForUpdate();
1640}
1641
1642TEST_F(UpdateAttempterTest, CheckForUpdateMissingForcedCallback2) {
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001643 // GIVEN a nonofficial build with dev features enabled.
Jae Hoon Kim2b73ac22019-07-02 11:17:24 -07001644 cfu_params_.is_official_build = false;
1645 cfu_params_.are_dev_features_enabled = true;
1646 // GIVEN forced callback is not set.
1647 attempter_.set_forced_update_pending_callback(nullptr);
1648
1649 // THEN the forced app version + forced omaha url changes based on input.
1650 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1651 cfu_params_.expected_forced_omaha_url = cfu_params_.omaha_url;
1652 // THEN |ScheduleUpdates()| should not be called.
1653 cfu_params_.should_schedule_updates_be_called = false;
1654
1655 TestCheckForUpdate();
1656}
1657
Xiaochu Liu88d90382018-08-29 16:09:11 -07001658TEST_F(UpdateAttempterTest, CheckForInstallTest) {
1659 fake_system_state_.fake_hardware()->SetIsOfficialBuild(true);
1660 fake_system_state_.fake_hardware()->SetAreDevFeaturesEnabled(false);
1661 attempter_.CheckForInstall({}, "autest");
1662 EXPECT_EQ(constants::kOmahaDefaultAUTestURL, attempter_.forced_omaha_url());
1663
1664 attempter_.CheckForInstall({}, "autest-scheduled");
1665 EXPECT_EQ(constants::kOmahaDefaultAUTestURL, attempter_.forced_omaha_url());
1666
1667 attempter_.CheckForInstall({}, "http://omaha.phishing");
1668 EXPECT_EQ("", attempter_.forced_omaha_url());
1669}
1670
Colin Howesac170d92018-11-20 16:29:28 -08001671TEST_F(UpdateAttempterTest, InstallSetsStatusIdle) {
1672 attempter_.CheckForInstall({}, "http://foo.bar");
1673 attempter_.status_ = UpdateStatus::DOWNLOADING;
1674 EXPECT_TRUE(attempter_.is_install_);
1675 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1676 UpdateEngineStatus status;
1677 attempter_.GetStatus(&status);
1678 // Should set status to idle after an install operation.
1679 EXPECT_EQ(UpdateStatus::IDLE, status.status);
1680}
1681
Colin Howes978c1082018-12-03 11:46:12 -08001682TEST_F(UpdateAttempterTest, RollbackAfterInstall) {
1683 attempter_.is_install_ = true;
1684 attempter_.Rollback(false);
1685 EXPECT_FALSE(attempter_.is_install_);
1686}
1687
1688TEST_F(UpdateAttempterTest, UpdateAfterInstall) {
1689 attempter_.is_install_ = true;
1690 attempter_.CheckForUpdate("", "", UpdateAttemptFlags::kNone);
1691 EXPECT_FALSE(attempter_.is_install_);
1692}
1693
Xiyuan Xiac0e8f9a2017-02-22 13:19:35 -08001694TEST_F(UpdateAttempterTest, TargetVersionPrefixSetAndReset) {
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001695 attempter_.CalculateUpdateParams(
1696 "", "", "", "1234", false, false, 4, false, false);
Xiyuan Xiac0e8f9a2017-02-22 13:19:35 -08001697 EXPECT_EQ("1234",
1698 fake_system_state_.request_params()->target_version_prefix());
1699
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001700 attempter_.CalculateUpdateParams(
1701 "", "", "", "", false, 4, false, false, false);
Xiyuan Xiac0e8f9a2017-02-22 13:19:35 -08001702 EXPECT_TRUE(
1703 fake_system_state_.request_params()->target_version_prefix().empty());
1704}
1705
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001706TEST_F(UpdateAttempterTest, RollbackAllowedSetAndReset) {
1707 attempter_.CalculateUpdateParams("",
1708 "",
1709 "",
1710 "1234",
1711 /*rollback_allowed=*/true,
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001712 /*rollback_data_save_requested=*/false,
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -07001713 /*rollback_allowed_milestones=*/4,
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001714 false,
1715 false);
1716 EXPECT_TRUE(fake_system_state_.request_params()->rollback_allowed());
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -07001717 EXPECT_EQ(4,
1718 fake_system_state_.request_params()->rollback_allowed_milestones());
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001719
1720 attempter_.CalculateUpdateParams("",
1721 "",
1722 "",
1723 "1234",
1724 /*rollback_allowed=*/false,
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001725 /*rollback_data_save_requested=*/false,
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -07001726 /*rollback_allowed_milestones=*/4,
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001727 false,
1728 false);
1729 EXPECT_FALSE(fake_system_state_.request_params()->rollback_allowed());
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -07001730 EXPECT_EQ(4,
1731 fake_system_state_.request_params()->rollback_allowed_milestones());
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001732}
1733
Aaron Wood23bd3392017-10-06 14:48:25 -07001734TEST_F(UpdateAttempterTest, UpdateDeferredByPolicyTest) {
1735 // Construct an OmahaResponseHandlerAction that has processed an InstallPlan,
1736 // but the update is being deferred by the Policy.
Amin Hassani68512d42018-07-31 23:52:33 -07001737 OmahaResponseHandlerAction response_action(&fake_system_state_);
1738 response_action.install_plan_.version = "a.b.c.d";
1739 response_action.install_plan_.system_version = "b.c.d.e";
1740 response_action.install_plan_.payloads.push_back(
Aaron Wood23bd3392017-10-06 14:48:25 -07001741 {.size = 1234ULL, .type = InstallPayloadType::kFull});
Aaron Wood23bd3392017-10-06 14:48:25 -07001742 // Inform the UpdateAttempter that the OmahaResponseHandlerAction has
1743 // completed, with the deferred-update error code.
1744 attempter_.ActionCompleted(
Amin Hassani68512d42018-07-31 23:52:33 -07001745 nullptr, &response_action, ErrorCode::kOmahaUpdateDeferredPerPolicy);
Aaron Wood23bd3392017-10-06 14:48:25 -07001746 {
1747 UpdateEngineStatus status;
1748 attempter_.GetStatus(&status);
1749 EXPECT_EQ(UpdateStatus::UPDATE_AVAILABLE, status.status);
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001750 EXPECT_TRUE(attempter_.install_plan_);
1751 EXPECT_EQ(attempter_.install_plan_->version, status.new_version);
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001752 EXPECT_EQ(attempter_.install_plan_->payloads[0].size,
Aaron Wood23bd3392017-10-06 14:48:25 -07001753 status.new_size_bytes);
1754 }
1755 // An "error" event should have been created to tell Omaha that the update is
1756 // being deferred.
1757 EXPECT_TRUE(nullptr != attempter_.error_event_);
1758 EXPECT_EQ(OmahaEvent::kTypeUpdateComplete, attempter_.error_event_->type);
1759 EXPECT_EQ(OmahaEvent::kResultUpdateDeferred, attempter_.error_event_->result);
1760 ErrorCode expected_code = static_cast<ErrorCode>(
1761 static_cast<int>(ErrorCode::kOmahaUpdateDeferredPerPolicy) |
1762 static_cast<int>(ErrorCode::kTestOmahaUrlFlag));
1763 EXPECT_EQ(expected_code, attempter_.error_event_->error_code);
1764 // End the processing
1765 attempter_.ProcessingDone(nullptr, ErrorCode::kOmahaUpdateDeferredPerPolicy);
1766 // Validate the state of the attempter.
1767 {
1768 UpdateEngineStatus status;
1769 attempter_.GetStatus(&status);
1770 EXPECT_EQ(UpdateStatus::REPORTING_ERROR_EVENT, status.status);
Amin Hassani68512d42018-07-31 23:52:33 -07001771 EXPECT_EQ(response_action.install_plan_.version, status.new_version);
Amin Hassani68512d42018-07-31 23:52:33 -07001772 EXPECT_EQ(response_action.install_plan_.payloads[0].size,
Aaron Wood23bd3392017-10-06 14:48:25 -07001773 status.new_size_bytes);
1774 }
1775}
1776
1777TEST_F(UpdateAttempterTest, UpdateIsNotRunningWhenUpdateAvailable) {
Jae Hoon Kim75daa382019-07-02 11:17:24 -07001778 // Default construction for |waiting_for_scheduled_check_| is false.
Jae Hoon Kimba2fdce2019-07-11 13:18:58 -07001779 EXPECT_FALSE(attempter_.IsBusyOrUpdateScheduled());
Aaron Wood23bd3392017-10-06 14:48:25 -07001780 // Verify in-progress update with UPDATE_AVAILABLE is running
1781 attempter_.status_ = UpdateStatus::UPDATE_AVAILABLE;
Jae Hoon Kimba2fdce2019-07-11 13:18:58 -07001782 EXPECT_TRUE(attempter_.IsBusyOrUpdateScheduled());
Aaron Wood23bd3392017-10-06 14:48:25 -07001783}
1784
Aaron Woodbf5a2522017-10-04 10:58:36 -07001785TEST_F(UpdateAttempterTest, UpdateAttemptFlagsCachedAtUpdateStart) {
1786 attempter_.SetUpdateAttemptFlags(UpdateAttemptFlags::kFlagRestrictDownload);
1787
1788 UpdateCheckParams params = {.updates_enabled = true};
1789 attempter_.OnUpdateScheduled(EvalStatus::kSucceeded, params);
1790
1791 EXPECT_EQ(UpdateAttemptFlags::kFlagRestrictDownload,
1792 attempter_.GetCurrentUpdateAttemptFlags());
1793}
1794
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001795TEST_F(UpdateAttempterTest, RollbackNotAllowed) {
1796 UpdateCheckParams params = {.updates_enabled = true,
1797 .rollback_allowed = false};
1798 attempter_.OnUpdateScheduled(EvalStatus::kSucceeded, params);
1799 EXPECT_FALSE(fake_system_state_.request_params()->rollback_allowed());
1800}
1801
1802TEST_F(UpdateAttempterTest, RollbackAllowed) {
1803 UpdateCheckParams params = {.updates_enabled = true,
1804 .rollback_allowed = true};
1805 attempter_.OnUpdateScheduled(EvalStatus::kSucceeded, params);
1806 EXPECT_TRUE(fake_system_state_.request_params()->rollback_allowed());
1807}
1808
Aaron Wood081c0232017-10-19 17:14:58 -07001809TEST_F(UpdateAttempterTest, InteractiveUpdateUsesPassedRestrictions) {
1810 attempter_.SetUpdateAttemptFlags(UpdateAttemptFlags::kFlagRestrictDownload);
1811
1812 attempter_.CheckForUpdate("", "", UpdateAttemptFlags::kNone);
1813 EXPECT_EQ(UpdateAttemptFlags::kNone,
1814 attempter_.GetCurrentUpdateAttemptFlags());
1815}
1816
1817TEST_F(UpdateAttempterTest, NonInteractiveUpdateUsesSetRestrictions) {
1818 attempter_.SetUpdateAttemptFlags(UpdateAttemptFlags::kNone);
1819
1820 // This tests that when CheckForUpdate() is called with the non-interactive
1821 // flag set, that it doesn't change the current UpdateAttemptFlags.
1822 attempter_.CheckForUpdate("",
1823 "",
1824 UpdateAttemptFlags::kFlagNonInteractive |
1825 UpdateAttemptFlags::kFlagRestrictDownload);
1826 EXPECT_EQ(UpdateAttemptFlags::kNone,
1827 attempter_.GetCurrentUpdateAttemptFlags());
1828}
1829
Marton Hunyadye58bddb2018-04-10 20:27:26 +02001830void UpdateAttempterTest::ResetRollbackHappenedStart(bool is_consumer,
1831 bool is_policy_loaded,
1832 bool expected_reset) {
1833 EXPECT_CALL(*fake_system_state_.mock_payload_state(), GetRollbackHappened())
1834 .WillRepeatedly(Return(true));
1835 auto mock_policy_provider =
1836 std::make_unique<NiceMock<policy::MockPolicyProvider>>();
1837 EXPECT_CALL(*mock_policy_provider, IsConsumerDevice())
1838 .WillRepeatedly(Return(is_consumer));
1839 EXPECT_CALL(*mock_policy_provider, device_policy_is_loaded())
1840 .WillRepeatedly(Return(is_policy_loaded));
1841 const policy::MockDevicePolicy device_policy;
1842 EXPECT_CALL(*mock_policy_provider, GetDevicePolicy())
1843 .WillRepeatedly(ReturnRef(device_policy));
1844 EXPECT_CALL(*fake_system_state_.mock_payload_state(),
1845 SetRollbackHappened(false))
1846 .Times(expected_reset ? 1 : 0);
1847 attempter_.policy_provider_ = std::move(mock_policy_provider);
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001848 attempter_.Update("", "", "", "", false, false, 0, false, false);
Marton Hunyadye58bddb2018-04-10 20:27:26 +02001849 ScheduleQuitMainLoop();
1850}
1851
1852TEST_F(UpdateAttempterTest, ResetRollbackHappenedOobe) {
1853 loop_.PostTask(FROM_HERE,
1854 base::Bind(&UpdateAttempterTest::ResetRollbackHappenedStart,
1855 base::Unretained(this),
1856 /*is_consumer=*/false,
1857 /*is_policy_loaded=*/false,
1858 /*expected_reset=*/false));
1859 loop_.Run();
1860}
1861
1862TEST_F(UpdateAttempterTest, ResetRollbackHappenedConsumer) {
1863 loop_.PostTask(FROM_HERE,
1864 base::Bind(&UpdateAttempterTest::ResetRollbackHappenedStart,
1865 base::Unretained(this),
1866 /*is_consumer=*/true,
1867 /*is_policy_loaded=*/false,
1868 /*expected_reset=*/true));
1869 loop_.Run();
1870}
1871
1872TEST_F(UpdateAttempterTest, ResetRollbackHappenedEnterprise) {
1873 loop_.PostTask(FROM_HERE,
1874 base::Bind(&UpdateAttempterTest::ResetRollbackHappenedStart,
1875 base::Unretained(this),
1876 /*is_consumer=*/false,
1877 /*is_policy_loaded=*/true,
1878 /*expected_reset=*/true));
1879 loop_.Run();
1880}
1881
Marton Hunyady199152d2018-05-07 19:08:48 +02001882TEST_F(UpdateAttempterTest, SetRollbackHappenedRollback) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001883 attempter_.install_plan_.reset(new InstallPlan);
1884 attempter_.install_plan_->is_rollback = true;
Marton Hunyady199152d2018-05-07 19:08:48 +02001885
1886 EXPECT_CALL(*fake_system_state_.mock_payload_state(),
1887 SetRollbackHappened(true))
1888 .Times(1);
1889 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1890}
1891
1892TEST_F(UpdateAttempterTest, SetRollbackHappenedNotRollback) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001893 attempter_.install_plan_.reset(new InstallPlan);
1894 attempter_.install_plan_->is_rollback = false;
Marton Hunyady199152d2018-05-07 19:08:48 +02001895
1896 EXPECT_CALL(*fake_system_state_.mock_payload_state(),
1897 SetRollbackHappened(true))
1898 .Times(0);
1899 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1900}
1901
Marton Hunyadya0302682018-05-16 18:52:13 +02001902TEST_F(UpdateAttempterTest, RollbackMetricsRollbackSuccess) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001903 attempter_.install_plan_.reset(new InstallPlan);
1904 attempter_.install_plan_->is_rollback = true;
1905 attempter_.install_plan_->version = kRollbackVersion;
Marton Hunyadya0302682018-05-16 18:52:13 +02001906
1907 EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
1908 ReportEnterpriseRollbackMetrics(true, kRollbackVersion))
1909 .Times(1);
1910 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1911}
1912
1913TEST_F(UpdateAttempterTest, RollbackMetricsNotRollbackSuccess) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001914 attempter_.install_plan_.reset(new InstallPlan);
1915 attempter_.install_plan_->is_rollback = false;
1916 attempter_.install_plan_->version = kRollbackVersion;
Marton Hunyadya0302682018-05-16 18:52:13 +02001917
1918 EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
1919 ReportEnterpriseRollbackMetrics(_, _))
1920 .Times(0);
1921 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1922}
1923
1924TEST_F(UpdateAttempterTest, RollbackMetricsRollbackFailure) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001925 attempter_.install_plan_.reset(new InstallPlan);
1926 attempter_.install_plan_->is_rollback = true;
1927 attempter_.install_plan_->version = kRollbackVersion;
Marton Hunyadya0302682018-05-16 18:52:13 +02001928
1929 EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
1930 ReportEnterpriseRollbackMetrics(false, kRollbackVersion))
1931 .Times(1);
1932 MockAction action;
1933 attempter_.CreatePendingErrorEvent(&action, ErrorCode::kRollbackNotPossible);
1934 attempter_.ProcessingDone(nullptr, ErrorCode::kRollbackNotPossible);
1935}
1936
1937TEST_F(UpdateAttempterTest, RollbackMetricsNotRollbackFailure) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001938 attempter_.install_plan_.reset(new InstallPlan);
1939 attempter_.install_plan_->is_rollback = false;
1940 attempter_.install_plan_->version = kRollbackVersion;
Marton Hunyadya0302682018-05-16 18:52:13 +02001941
1942 EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
1943 ReportEnterpriseRollbackMetrics(_, _))
1944 .Times(0);
1945 MockAction action;
1946 attempter_.CreatePendingErrorEvent(&action, ErrorCode::kRollbackNotPossible);
1947 attempter_.ProcessingDone(nullptr, ErrorCode::kRollbackNotPossible);
1948}
1949
May Lippert60aa3ca2018-08-15 16:55:29 -07001950TEST_F(UpdateAttempterTest, TimeToUpdateAppliedMetricFailure) {
1951 EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
1952 ReportEnterpriseUpdateSeenToDownloadDays(_, _))
1953 .Times(0);
1954 attempter_.ProcessingDone(nullptr, ErrorCode::kOmahaUpdateDeferredPerPolicy);
1955}
1956
1957TEST_F(UpdateAttempterTest, TimeToUpdateAppliedOnNonEnterprise) {
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 not enterprise enrolled
1961 EXPECT_CALL(*device_policy, IsEnterpriseEnrolled()).WillOnce(Return(false));
1962
1963 // Ensure that the metric is not recorded.
1964 EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
1965 ReportEnterpriseUpdateSeenToDownloadDays(_, _))
1966 .Times(0);
1967 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1968}
1969
1970TEST_F(UpdateAttempterTest,
1971 TimeToUpdateAppliedWithTimeRestrictionMetricSuccess) {
1972 constexpr int kDaysToUpdate = 15;
1973 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
1974 fake_system_state_.set_device_policy(device_policy.get());
1975 // Make device policy return that this is enterprise enrolled
1976 EXPECT_CALL(*device_policy, IsEnterpriseEnrolled()).WillOnce(Return(true));
1977 // Pretend that there's a time restriction policy in place
1978 EXPECT_CALL(*device_policy, GetDisallowedTimeIntervals(_))
1979 .WillOnce(Return(true));
1980
1981 FakePrefs fake_prefs;
1982 Time update_first_seen_at = Time::Now();
1983 fake_prefs.SetInt64(kPrefsUpdateFirstSeenAt,
1984 update_first_seen_at.ToInternalValue());
1985
1986 FakeClock fake_clock;
1987 Time update_finished_at =
1988 update_first_seen_at + TimeDelta::FromDays(kDaysToUpdate);
1989 fake_clock.SetWallclockTime(update_finished_at);
1990
1991 fake_system_state_.set_clock(&fake_clock);
1992 fake_system_state_.set_prefs(&fake_prefs);
1993
1994 EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
1995 ReportEnterpriseUpdateSeenToDownloadDays(true, kDaysToUpdate))
1996 .Times(1);
1997 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1998}
1999
2000TEST_F(UpdateAttempterTest,
2001 TimeToUpdateAppliedWithoutTimeRestrictionMetricSuccess) {
2002 constexpr int kDaysToUpdate = 15;
2003 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
2004 fake_system_state_.set_device_policy(device_policy.get());
2005 // Make device policy return that this is enterprise enrolled
2006 EXPECT_CALL(*device_policy, IsEnterpriseEnrolled()).WillOnce(Return(true));
2007 // Pretend that there's no time restriction policy in place
2008 EXPECT_CALL(*device_policy, GetDisallowedTimeIntervals(_))
2009 .WillOnce(Return(false));
2010
2011 FakePrefs fake_prefs;
2012 Time update_first_seen_at = Time::Now();
2013 fake_prefs.SetInt64(kPrefsUpdateFirstSeenAt,
2014 update_first_seen_at.ToInternalValue());
2015
2016 FakeClock fake_clock;
2017 Time update_finished_at =
2018 update_first_seen_at + TimeDelta::FromDays(kDaysToUpdate);
2019 fake_clock.SetWallclockTime(update_finished_at);
2020
2021 fake_system_state_.set_clock(&fake_clock);
2022 fake_system_state_.set_prefs(&fake_prefs);
2023
2024 EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
2025 ReportEnterpriseUpdateSeenToDownloadDays(false, kDaysToUpdate))
2026 .Times(1);
2027 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
2028}
2029
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002030TEST_F(UpdateAttempterTest, ProcessingDoneUpdated) {
2031 // GIVEN an update finished.
2032
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002033 // THEN update_engine should call update completion.
2034 pd_params_.should_update_completed_be_called = true;
2035 // THEN need reboot since update applied.
2036 pd_params_.expected_exit_status = UpdateStatus::UPDATED_NEED_REBOOT;
2037 // THEN install indication should be false.
2038
2039 TestProcessingDone();
2040}
2041
2042TEST_F(UpdateAttempterTest, ProcessingDoneUpdatedDlcFilter) {
2043 // GIVEN an update finished.
2044 // GIVEN DLC |AppParams| list.
2045 auto dlc_1 = "dlc_1", dlc_2 = "dlc_2";
2046 pd_params_.dlc_apps_params = {{dlc_1, {.name = dlc_1, .updated = false}},
2047 {dlc_2, {.name = dlc_2}}};
2048
2049 // THEN update_engine should call update completion.
2050 pd_params_.should_update_completed_be_called = true;
2051 pd_params_.args_to_update_completed = {dlc_2};
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002052 // THEN need reboot since update applied.
2053 pd_params_.expected_exit_status = UpdateStatus::UPDATED_NEED_REBOOT;
2054 // THEN install indication should be false.
2055
2056 TestProcessingDone();
2057}
2058
2059TEST_F(UpdateAttempterTest, ProcessingDoneInstalled) {
2060 // GIVEN an install finished.
2061 pd_params_.is_install = true;
2062
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002063 // THEN update_engine should call install completion.
2064 pd_params_.should_install_completed_be_called = true;
2065 // THEN go idle.
2066 // THEN install indication should be false.
2067
2068 TestProcessingDone();
2069}
2070
2071TEST_F(UpdateAttempterTest, ProcessingDoneInstalledDlcFilter) {
2072 // GIVEN an install finished.
2073 pd_params_.is_install = true;
2074 // GIVEN DLC |AppParams| list.
2075 auto dlc_1 = "dlc_1", dlc_2 = "dlc_2";
2076 pd_params_.dlc_apps_params = {{dlc_1, {.name = dlc_1, .updated = false}},
2077 {dlc_2, {.name = dlc_2}}};
2078
2079 // THEN update_engine should call install completion.
2080 pd_params_.should_install_completed_be_called = true;
2081 pd_params_.args_to_install_completed = {dlc_2};
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002082 // THEN go idle.
2083 // THEN install indication should be false.
2084
2085 TestProcessingDone();
2086}
2087
2088TEST_F(UpdateAttempterTest, ProcessingDoneInstallReportingError) {
2089 // GIVEN an install finished.
2090 pd_params_.is_install = true;
2091 // GIVEN a reporting error occurred.
2092 pd_params_.status = UpdateStatus::REPORTING_ERROR_EVENT;
2093
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002094 // THEN update_engine should not call install completion.
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002095 // THEN go idle.
2096 // THEN install indication should be false.
2097
2098 TestProcessingDone();
2099}
2100
2101TEST_F(UpdateAttempterTest, ProcessingDoneNoUpdate) {
2102 // GIVEN an update finished.
2103 // GIVEN an action error occured.
2104 pd_params_.code = ErrorCode::kNoUpdate;
2105
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002106 // THEN update_engine should not call update completion.
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002107 // THEN go idle.
2108 // THEN install indication should be false.
2109
2110 TestProcessingDone();
2111}
2112
2113TEST_F(UpdateAttempterTest, ProcessingDoneNoInstall) {
2114 // GIVEN an install finished.
2115 pd_params_.is_install = true;
2116 // GIVEN an action error occured.
2117 pd_params_.code = ErrorCode::kNoUpdate;
2118
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002119 // THEN update_engine should not call install completion.
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002120 // THEN go idle.
2121 // THEN install indication should be false.
2122
2123 TestProcessingDone();
2124}
2125
2126TEST_F(UpdateAttempterTest, ProcessingDoneUpdateError) {
2127 // GIVEN an update finished.
2128 // GIVEN an action error occured.
2129 pd_params_.code = ErrorCode::kError;
2130 // GIVEN an event error is set.
2131 attempter_.error_event_.reset(new OmahaEvent(OmahaEvent::kTypeUpdateComplete,
2132 OmahaEvent::kResultError,
2133 ErrorCode::kError));
2134
2135 // THEN indicate a error event.
2136 pd_params_.expected_exit_status = UpdateStatus::REPORTING_ERROR_EVENT;
2137 // THEN install indication should be false.
2138
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002139 // THEN update_engine should not call update completion.
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002140 // THEN expect critical actions of |ScheduleErrorEventAction()|.
2141 EXPECT_CALL(*processor_, EnqueueAction(Pointee(_))).Times(1);
2142 EXPECT_CALL(*processor_, StartProcessing()).Times(1);
2143 // THEN |ScheduleUpdates()| will be called next |ProcessingDone()| so skip.
2144 pd_params_.should_schedule_updates_be_called = false;
2145
2146 TestProcessingDone();
2147}
2148
2149TEST_F(UpdateAttempterTest, ProcessingDoneInstallError) {
2150 // GIVEN an install finished.
2151 pd_params_.is_install = true;
2152 // GIVEN an action error occured.
2153 pd_params_.code = ErrorCode::kError;
2154 // GIVEN an event error is set.
2155 attempter_.error_event_.reset(new OmahaEvent(OmahaEvent::kTypeUpdateComplete,
2156 OmahaEvent::kResultError,
2157 ErrorCode::kError));
2158
2159 // THEN indicate a error event.
2160 pd_params_.expected_exit_status = UpdateStatus::REPORTING_ERROR_EVENT;
2161 // THEN install indication should be false.
2162
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002163 // THEN update_engine should not call install completion.
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002164 // THEN expect critical actions of |ScheduleErrorEventAction()|.
2165 EXPECT_CALL(*processor_, EnqueueAction(Pointee(_))).Times(1);
2166 EXPECT_CALL(*processor_, StartProcessing()).Times(1);
2167 // THEN |ScheduleUpdates()| will be called next |ProcessingDone()| so skip.
2168 pd_params_.should_schedule_updates_be_called = false;
2169
2170 TestProcessingDone();
2171}
2172
Amr Aboelkher21ac9962019-05-15 14:50:05 +02002173void UpdateAttempterTest::UpdateToQuickFixBuildStart(bool set_token) {
2174 // Tests that checks if |device_quick_fix_build_token| arrives when
2175 // policy is set and the device is enterprise enrolled based on |set_token|.
2176 string token = set_token ? "some_token" : "";
Askar Aitzhan570ca872019-04-24 11:16:12 +02002177 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
2178 fake_system_state_.set_device_policy(device_policy.get());
Askar Aitzhan570ca872019-04-24 11:16:12 +02002179 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
Amr Aboelkher21ac9962019-05-15 14:50:05 +02002180
2181 if (set_token)
2182 EXPECT_CALL(*device_policy, GetDeviceQuickFixBuildToken(_))
2183 .WillOnce(DoAll(SetArgPointee<0>(token), Return(true)));
2184 else
2185 EXPECT_CALL(*device_policy, GetDeviceQuickFixBuildToken(_))
2186 .WillOnce(Return(false));
Askar Aitzhan570ca872019-04-24 11:16:12 +02002187 attempter_.policy_provider_.reset(
2188 new policy::PolicyProvider(std::move(device_policy)));
2189 attempter_.Update("", "", "", "", false, false, 0, false, false);
2190
Amr Aboelkher21ac9962019-05-15 14:50:05 +02002191 EXPECT_EQ(token, attempter_.omaha_request_params_->autoupdate_token());
Askar Aitzhan570ca872019-04-24 11:16:12 +02002192 ScheduleQuitMainLoop();
2193}
2194
Amr Aboelkher21ac9962019-05-15 14:50:05 +02002195TEST_F(UpdateAttempterTest,
2196 QuickFixTokenWhenDeviceIsEnterpriseEnrolledAndPolicyIsSet) {
Askar Aitzhan570ca872019-04-24 11:16:12 +02002197 loop_.PostTask(FROM_HERE,
2198 base::Bind(&UpdateAttempterTest::UpdateToQuickFixBuildStart,
Amr Aboelkher21ac9962019-05-15 14:50:05 +02002199 base::Unretained(this),
2200 /*set_token=*/true));
2201 loop_.Run();
2202}
2203
2204TEST_F(UpdateAttempterTest, EmptyQuickFixToken) {
2205 loop_.PostTask(FROM_HERE,
2206 base::Bind(&UpdateAttempterTest::UpdateToQuickFixBuildStart,
2207 base::Unretained(this),
2208 /*set_token=*/false));
Askar Aitzhan570ca872019-04-24 11:16:12 +02002209 loop_.Run();
2210}
2211
Jae Hoon Kim75daa382019-07-02 11:17:24 -07002212TEST_F(UpdateAttempterTest, ScheduleUpdateSpamHandlerTest) {
2213 EXPECT_CALL(mock_update_manager_, AsyncPolicyRequestUpdateCheckAllowed(_, _))
2214 .Times(1);
2215 EXPECT_TRUE(attempter_.ScheduleUpdates());
2216 // Now there is an update scheduled which means that all subsequent
2217 // |ScheduleUpdates()| should fail.
2218 EXPECT_FALSE(attempter_.ScheduleUpdates());
2219 EXPECT_FALSE(attempter_.ScheduleUpdates());
2220 EXPECT_FALSE(attempter_.ScheduleUpdates());
2221}
2222
2223// Critical tests to always make sure that an update is scheduled. The following
2224// unittest(s) try and cover the correctness in synergy between
2225// |UpdateAttempter| and |UpdateManager|. Also it is good to remember the
2226// actions that happen in the flow when |UpdateAttempter| get callbacked on
2227// |OnUpdateScheduled()| -> (various cases which leads to) -> |ProcessingDone()|
2228void UpdateAttempterTest::TestOnUpdateScheduled() {
2229 // Setup
2230 attempter_.SetWaitingForScheduledCheck(true);
2231 attempter_.DisableUpdate();
2232 attempter_.DisableScheduleUpdates();
2233
2234 // Invocation
2235 attempter_.OnUpdateScheduled(ous_params_.status, ous_params_.params);
2236
2237 // Verify
2238 EXPECT_EQ(ous_params_.exit_status, attempter_.status());
2239 EXPECT_EQ(ous_params_.should_schedule_updates_be_called,
2240 attempter_.WasScheduleUpdatesCalled());
2241 EXPECT_EQ(ous_params_.should_update_be_called, attempter_.WasUpdateCalled());
2242}
2243
2244TEST_F(UpdateAttempterTest, OnUpdatesScheduledFailed) {
2245 // GIVEN failed status.
2246
2247 // THEN update should be scheduled.
2248 ous_params_.should_schedule_updates_be_called = true;
2249
2250 TestOnUpdateScheduled();
2251}
2252
2253TEST_F(UpdateAttempterTest, OnUpdatesScheduledAskMeAgainLater) {
2254 // GIVEN ask me again later status.
2255 ous_params_.status = EvalStatus::kAskMeAgainLater;
2256
2257 // THEN update should be scheduled.
2258 ous_params_.should_schedule_updates_be_called = true;
2259
2260 TestOnUpdateScheduled();
2261}
2262
2263TEST_F(UpdateAttempterTest, OnUpdatesScheduledContinue) {
2264 // GIVEN continue status.
2265 ous_params_.status = EvalStatus::kContinue;
2266
2267 // THEN update should be scheduled.
2268 ous_params_.should_schedule_updates_be_called = true;
2269
2270 TestOnUpdateScheduled();
2271}
2272
2273TEST_F(UpdateAttempterTest, OnUpdatesScheduledSucceededButUpdateDisabledFails) {
2274 // GIVEN updates disabled.
2275 ous_params_.params = {.updates_enabled = false};
2276 // GIVEN succeeded status.
2277 ous_params_.status = EvalStatus::kSucceeded;
2278
2279 // THEN update should not be scheduled.
2280
2281 TestOnUpdateScheduled();
2282}
2283
2284TEST_F(UpdateAttempterTest, OnUpdatesScheduledSucceeded) {
2285 // GIVEN updates enabled.
2286 ous_params_.params = {.updates_enabled = true};
2287 // GIVEN succeeded status.
2288 ous_params_.status = EvalStatus::kSucceeded;
2289
2290 // THEN update should be called indicating status change.
2291 ous_params_.exit_status = UpdateStatus::CHECKING_FOR_UPDATE;
2292 ous_params_.should_update_be_called = true;
2293
2294 TestOnUpdateScheduled();
2295}
2296
Amin Hassani9be122e2019-08-29 09:20:12 -07002297TEST_F(UpdateAttempterTest, IsEnterpriseRollbackInGetStatusDefault) {
2298 UpdateEngineStatus status;
2299 attempter_.GetStatus(&status);
2300 EXPECT_FALSE(status.is_enterprise_rollback);
2301}
2302
2303TEST_F(UpdateAttempterTest, IsEnterpriseRollbackInGetStatusFalse) {
2304 attempter_.install_plan_.reset(new InstallPlan);
2305 attempter_.install_plan_->is_rollback = false;
2306
2307 UpdateEngineStatus status;
2308 attempter_.GetStatus(&status);
2309 EXPECT_FALSE(status.is_enterprise_rollback);
2310}
2311
2312TEST_F(UpdateAttempterTest, IsEnterpriseRollbackInGetStatusTrue) {
2313 attempter_.install_plan_.reset(new InstallPlan);
2314 attempter_.install_plan_->is_rollback = true;
2315
2316 UpdateEngineStatus status;
2317 attempter_.GetStatus(&status);
2318 EXPECT_TRUE(status.is_enterprise_rollback);
2319}
2320
Miriam Polzer0cf1acb2020-04-29 17:39:51 +02002321TEST_F(UpdateAttempterTest, PowerwashInGetStatusDefault) {
2322 UpdateEngineStatus status;
2323 attempter_.GetStatus(&status);
2324 EXPECT_FALSE(status.will_powerwash_after_reboot);
2325}
2326
2327TEST_F(UpdateAttempterTest, PowerwashInGetStatusTrueBecausePowerwashRequired) {
2328 attempter_.install_plan_.reset(new InstallPlan);
2329 attempter_.install_plan_->powerwash_required = true;
2330
2331 UpdateEngineStatus status;
2332 attempter_.GetStatus(&status);
2333 EXPECT_TRUE(status.will_powerwash_after_reboot);
2334}
2335
2336TEST_F(UpdateAttempterTest, PowerwashInGetStatusTrueBecauseRollback) {
2337 attempter_.install_plan_.reset(new InstallPlan);
2338 attempter_.install_plan_->is_rollback = true;
2339
2340 UpdateEngineStatus status;
2341 attempter_.GetStatus(&status);
2342 EXPECT_TRUE(status.will_powerwash_after_reboot);
2343}
2344
Jae Hoon Kim051627a2019-09-03 12:56:32 -07002345TEST_F(UpdateAttempterTest, FutureEolTest) {
2346 EolDate eol_date = std::numeric_limits<int64_t>::max();
Jae Hoon Kim2dfd35d2020-06-02 10:53:13 -07002347 EXPECT_CALL(*prefs_, Exists(kPrefsOmahaEolDate)).WillOnce(Return(true));
Jae Hoon Kim051627a2019-09-03 12:56:32 -07002348 EXPECT_CALL(*prefs_, GetString(kPrefsOmahaEolDate, _))
2349 .WillOnce(
2350 DoAll(SetArgPointee<1>(EolDateToString(eol_date)), Return(true)));
2351
2352 UpdateEngineStatus status;
2353 attempter_.GetStatus(&status);
2354 EXPECT_EQ(eol_date, status.eol_date);
2355}
2356
2357TEST_F(UpdateAttempterTest, PastEolTest) {
2358 EolDate eol_date = 1;
Jae Hoon Kim2dfd35d2020-06-02 10:53:13 -07002359 EXPECT_CALL(*prefs_, Exists(kPrefsOmahaEolDate)).WillOnce(Return(true));
Jae Hoon Kim051627a2019-09-03 12:56:32 -07002360 EXPECT_CALL(*prefs_, GetString(kPrefsOmahaEolDate, _))
2361 .WillOnce(
2362 DoAll(SetArgPointee<1>(EolDateToString(eol_date)), Return(true)));
2363
2364 UpdateEngineStatus status;
2365 attempter_.GetStatus(&status);
2366 EXPECT_EQ(eol_date, status.eol_date);
2367}
2368
2369TEST_F(UpdateAttempterTest, FailedEolTest) {
Jae Hoon Kim2dfd35d2020-06-02 10:53:13 -07002370 EXPECT_CALL(*prefs_, Exists(kPrefsOmahaEolDate)).WillOnce(Return(true));
Jae Hoon Kim051627a2019-09-03 12:56:32 -07002371 EXPECT_CALL(*prefs_, GetString(kPrefsOmahaEolDate, _))
2372 .WillOnce(Return(false));
2373
2374 UpdateEngineStatus status;
2375 attempter_.GetStatus(&status);
Jae Hoon Kim2dfd35d2020-06-02 10:53:13 -07002376 EXPECT_EQ(kEolDateInvalid, status.eol_date);
2377}
2378
2379TEST_F(UpdateAttempterTest, MissingEolTest) {
2380 EXPECT_CALL(*prefs_, Exists(kPrefsOmahaEolDate)).WillOnce(Return(false));
2381
2382 UpdateEngineStatus status;
2383 attempter_.GetStatus(&status);
2384 EXPECT_EQ(kEolDateInvalid, status.eol_date);
Jae Hoon Kim051627a2019-09-03 12:56:32 -07002385}
2386
Andrewe045aef2020-01-08 16:29:22 -08002387TEST_F(UpdateAttempterTest, CalculateDlcParamsInstallTest) {
Andrewe045aef2020-01-08 16:29:22 -08002388 string dlc_id = "dlc0";
Andrew065d78d2020-04-07 15:43:07 -07002389 FakePrefs fake_prefs;
2390 fake_system_state_.set_prefs(&fake_prefs);
Andrewe045aef2020-01-08 16:29:22 -08002391 attempter_.is_install_ = true;
Amin Hassani2b68e6b2020-04-17 10:49:12 -07002392 attempter_.dlc_ids_ = {dlc_id};
Andrewe045aef2020-01-08 16:29:22 -08002393 attempter_.CalculateDlcParams();
2394
2395 OmahaRequestParams* params = fake_system_state_.request_params();
2396 EXPECT_EQ(1, params->dlc_apps_params().count(params->GetDlcAppId(dlc_id)));
2397 OmahaRequestParams::AppParams dlc_app_params =
2398 params->dlc_apps_params().at(params->GetDlcAppId(dlc_id));
2399 EXPECT_STREQ(dlc_id.c_str(), dlc_app_params.name.c_str());
2400 EXPECT_EQ(false, dlc_app_params.send_ping);
2401 // When the DLC gets installed, a ping is not sent, therefore we don't store
2402 // the values sent by Omaha.
Andrew065d78d2020-04-07 15:43:07 -07002403 auto last_active_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002404 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastActive});
Andrew065d78d2020-04-07 15:43:07 -07002405 EXPECT_FALSE(fake_system_state_.prefs()->Exists(last_active_key));
2406 auto last_rollcall_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002407 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastRollcall});
Andrew065d78d2020-04-07 15:43:07 -07002408 EXPECT_FALSE(fake_system_state_.prefs()->Exists(last_rollcall_key));
Andrewe045aef2020-01-08 16:29:22 -08002409}
2410
2411TEST_F(UpdateAttempterTest, CalculateDlcParamsNoPrefFilesTest) {
Andrewe045aef2020-01-08 16:29:22 -08002412 string dlc_id = "dlc0";
Andrew065d78d2020-04-07 15:43:07 -07002413 FakePrefs fake_prefs;
2414 fake_system_state_.set_prefs(&fake_prefs);
Amin Hassani2b68e6b2020-04-17 10:49:12 -07002415 EXPECT_CALL(mock_dlcservice_, GetDlcsToUpdate(_))
Andrewe045aef2020-01-08 16:29:22 -08002416 .WillOnce(
2417 DoAll(SetArgPointee<0>(std::vector<string>({dlc_id})), Return(true)));
2418
2419 attempter_.is_install_ = false;
2420 attempter_.CalculateDlcParams();
2421
2422 OmahaRequestParams* params = fake_system_state_.request_params();
2423 EXPECT_EQ(1, params->dlc_apps_params().count(params->GetDlcAppId(dlc_id)));
2424 OmahaRequestParams::AppParams dlc_app_params =
2425 params->dlc_apps_params().at(params->GetDlcAppId(dlc_id));
2426 EXPECT_STREQ(dlc_id.c_str(), dlc_app_params.name.c_str());
2427
2428 EXPECT_EQ(true, dlc_app_params.send_ping);
2429 EXPECT_EQ(0, dlc_app_params.ping_active);
2430 EXPECT_EQ(-1, dlc_app_params.ping_date_last_active);
2431 EXPECT_EQ(-1, dlc_app_params.ping_date_last_rollcall);
2432}
2433
2434TEST_F(UpdateAttempterTest, CalculateDlcParamsNonParseableValuesTest) {
Andrewe045aef2020-01-08 16:29:22 -08002435 string dlc_id = "dlc0";
Andrew065d78d2020-04-07 15:43:07 -07002436 MemoryPrefs prefs;
2437 fake_system_state_.set_prefs(&prefs);
Amin Hassani2b68e6b2020-04-17 10:49:12 -07002438 EXPECT_CALL(mock_dlcservice_, GetDlcsToUpdate(_))
Andrewe045aef2020-01-08 16:29:22 -08002439 .WillOnce(
2440 DoAll(SetArgPointee<0>(std::vector<string>({dlc_id})), Return(true)));
2441
2442 // Write non numeric values in the metadata files.
Andrew065d78d2020-04-07 15:43:07 -07002443 auto active_key =
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002444 PrefsInterface::CreateSubKey({kDlcPrefsSubDir, dlc_id, kPrefsPingActive});
Andrew065d78d2020-04-07 15:43:07 -07002445 auto last_active_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002446 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastActive});
Andrew065d78d2020-04-07 15:43:07 -07002447 auto last_rollcall_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002448 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastRollcall});
Andrew065d78d2020-04-07 15:43:07 -07002449 fake_system_state_.prefs()->SetString(active_key, "z2yz");
2450 fake_system_state_.prefs()->SetString(last_active_key, "z2yz");
2451 fake_system_state_.prefs()->SetString(last_rollcall_key, "z2yz");
Andrewe045aef2020-01-08 16:29:22 -08002452 attempter_.is_install_ = false;
2453 attempter_.CalculateDlcParams();
2454
2455 OmahaRequestParams* params = fake_system_state_.request_params();
2456 EXPECT_EQ(1, params->dlc_apps_params().count(params->GetDlcAppId(dlc_id)));
2457 OmahaRequestParams::AppParams dlc_app_params =
2458 params->dlc_apps_params().at(params->GetDlcAppId(dlc_id));
2459 EXPECT_STREQ(dlc_id.c_str(), dlc_app_params.name.c_str());
2460
2461 EXPECT_EQ(true, dlc_app_params.send_ping);
2462 EXPECT_EQ(0, dlc_app_params.ping_active);
2463 EXPECT_EQ(-2, dlc_app_params.ping_date_last_active);
2464 EXPECT_EQ(-2, dlc_app_params.ping_date_last_rollcall);
2465}
2466
2467TEST_F(UpdateAttempterTest, CalculateDlcParamsValidValuesTest) {
Andrewe045aef2020-01-08 16:29:22 -08002468 string dlc_id = "dlc0";
Andrew065d78d2020-04-07 15:43:07 -07002469 MemoryPrefs fake_prefs;
2470 fake_system_state_.set_prefs(&fake_prefs);
Amin Hassani2b68e6b2020-04-17 10:49:12 -07002471 EXPECT_CALL(mock_dlcservice_, GetDlcsToUpdate(_))
Andrewe045aef2020-01-08 16:29:22 -08002472 .WillOnce(
2473 DoAll(SetArgPointee<0>(std::vector<string>({dlc_id})), Return(true)));
2474
2475 // Write numeric values in the metadata files.
Andrew065d78d2020-04-07 15:43:07 -07002476 auto active_key =
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002477 PrefsInterface::CreateSubKey({kDlcPrefsSubDir, dlc_id, kPrefsPingActive});
Andrew065d78d2020-04-07 15:43:07 -07002478 auto last_active_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002479 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastActive});
Andrew065d78d2020-04-07 15:43:07 -07002480 auto last_rollcall_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002481 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastRollcall});
Andrew065d78d2020-04-07 15:43:07 -07002482
2483 fake_system_state_.prefs()->SetInt64(active_key, 1);
2484 fake_system_state_.prefs()->SetInt64(last_active_key, 78);
2485 fake_system_state_.prefs()->SetInt64(last_rollcall_key, 99);
Andrewe045aef2020-01-08 16:29:22 -08002486 attempter_.is_install_ = false;
2487 attempter_.CalculateDlcParams();
2488
2489 OmahaRequestParams* params = fake_system_state_.request_params();
2490 EXPECT_EQ(1, params->dlc_apps_params().count(params->GetDlcAppId(dlc_id)));
2491 OmahaRequestParams::AppParams dlc_app_params =
2492 params->dlc_apps_params().at(params->GetDlcAppId(dlc_id));
2493 EXPECT_STREQ(dlc_id.c_str(), dlc_app_params.name.c_str());
2494
2495 EXPECT_EQ(true, dlc_app_params.send_ping);
2496 EXPECT_EQ(1, dlc_app_params.ping_active);
2497 EXPECT_EQ(78, dlc_app_params.ping_date_last_active);
2498 EXPECT_EQ(99, dlc_app_params.ping_date_last_rollcall);
2499}
Andrewa8d7df32020-03-15 20:10:01 -07002500
2501TEST_F(UpdateAttempterTest, CalculateDlcParamsRemoveStaleMetadata) {
Andrewa8d7df32020-03-15 20:10:01 -07002502 string dlc_id = "dlc0";
Andrew065d78d2020-04-07 15:43:07 -07002503 FakePrefs fake_prefs;
2504 fake_system_state_.set_prefs(&fake_prefs);
2505 auto active_key =
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002506 PrefsInterface::CreateSubKey({kDlcPrefsSubDir, dlc_id, kPrefsPingActive});
Andrew065d78d2020-04-07 15:43:07 -07002507 auto last_active_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002508 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastActive});
Andrew065d78d2020-04-07 15:43:07 -07002509 auto last_rollcall_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002510 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastRollcall});
Andrew065d78d2020-04-07 15:43:07 -07002511 fake_system_state_.prefs()->SetInt64(active_key, kPingInactiveValue);
2512 fake_system_state_.prefs()->SetInt64(last_active_key, 0);
2513 fake_system_state_.prefs()->SetInt64(last_rollcall_key, 0);
2514 EXPECT_TRUE(fake_system_state_.prefs()->Exists(active_key));
2515 EXPECT_TRUE(fake_system_state_.prefs()->Exists(last_active_key));
2516 EXPECT_TRUE(fake_system_state_.prefs()->Exists(last_rollcall_key));
Andrewa8d7df32020-03-15 20:10:01 -07002517
Andrew065d78d2020-04-07 15:43:07 -07002518 attempter_.dlc_ids_ = {dlc_id};
2519 attempter_.is_install_ = true;
Andrewa8d7df32020-03-15 20:10:01 -07002520 attempter_.CalculateDlcParams();
2521
Andrew065d78d2020-04-07 15:43:07 -07002522 EXPECT_FALSE(fake_system_state_.prefs()->Exists(last_active_key));
2523 EXPECT_FALSE(fake_system_state_.prefs()->Exists(last_rollcall_key));
2524 // Active key is set on install.
2525 EXPECT_TRUE(fake_system_state_.prefs()->Exists(active_key));
2526 int64_t temp_int;
2527 EXPECT_TRUE(fake_system_state_.prefs()->GetInt64(active_key, &temp_int));
2528 EXPECT_EQ(temp_int, kPingActiveValue);
Andrewa8d7df32020-03-15 20:10:01 -07002529}
2530
2531TEST_F(UpdateAttempterTest, SetDlcActiveValue) {
Andrewa8d7df32020-03-15 20:10:01 -07002532 string dlc_id = "dlc0";
Andrew065d78d2020-04-07 15:43:07 -07002533 FakePrefs fake_prefs;
2534 fake_system_state_.set_prefs(&fake_prefs);
Andrewa8d7df32020-03-15 20:10:01 -07002535 attempter_.SetDlcActiveValue(true, dlc_id);
Andrewa8d7df32020-03-15 20:10:01 -07002536 int64_t temp_int;
Andrew065d78d2020-04-07 15:43:07 -07002537 auto active_key =
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002538 PrefsInterface::CreateSubKey({kDlcPrefsSubDir, dlc_id, kPrefsPingActive});
Andrew065d78d2020-04-07 15:43:07 -07002539 EXPECT_TRUE(fake_system_state_.prefs()->Exists(active_key));
2540 EXPECT_TRUE(fake_system_state_.prefs()->GetInt64(active_key, &temp_int));
Andrewa8d7df32020-03-15 20:10:01 -07002541 EXPECT_EQ(temp_int, kPingActiveValue);
2542}
2543
2544TEST_F(UpdateAttempterTest, SetDlcInactive) {
Andrewa8d7df32020-03-15 20:10:01 -07002545 string dlc_id = "dlc0";
Andrew065d78d2020-04-07 15:43:07 -07002546 MemoryPrefs fake_prefs;
2547 fake_system_state_.set_prefs(&fake_prefs);
2548 auto sub_keys = {
2549 kPrefsPingActive, kPrefsPingLastActive, kPrefsPingLastRollcall};
2550 for (auto& sub_key : sub_keys) {
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002551 auto key = PrefsInterface::CreateSubKey({kDlcPrefsSubDir, dlc_id, sub_key});
Andrew065d78d2020-04-07 15:43:07 -07002552 fake_system_state_.prefs()->SetInt64(key, 1);
2553 EXPECT_TRUE(fake_system_state_.prefs()->Exists(key));
2554 }
Andrewa8d7df32020-03-15 20:10:01 -07002555 attempter_.SetDlcActiveValue(false, dlc_id);
Andrew065d78d2020-04-07 15:43:07 -07002556 for (auto& sub_key : sub_keys) {
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002557 auto key = PrefsInterface::CreateSubKey({kDlcPrefsSubDir, dlc_id, sub_key});
Andrew065d78d2020-04-07 15:43:07 -07002558 EXPECT_FALSE(fake_system_state_.prefs()->Exists(key));
2559 }
Andrewa8d7df32020-03-15 20:10:01 -07002560}
2561
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002562TEST_F(UpdateAttempterTest, GetSuccessfulDlcIds) {
2563 auto dlc_1 = "1", dlc_2 = "2", dlc_3 = "3";
2564 attempter_.omaha_request_params_->set_dlc_apps_params(
2565 {{dlc_1, {.name = dlc_1, .updated = false}},
2566 {dlc_2, {.name = dlc_2}},
2567 {dlc_3, {.name = dlc_3, .updated = false}}});
2568 EXPECT_THAT(attempter_.GetSuccessfulDlcIds(), ElementsAre(dlc_2));
2569}
2570
Darin Petkovf42cc1c2010-09-01 09:03:02 -07002571} // namespace chromeos_update_engine