blob: 3a1646fdf8960ffa925efaba2d7f437a76f2ea25 [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));
Sen Jiange6e4bb92016-04-05 14:59:12 -0700666 FilesystemVerifierAction filesystem_verifier_action;
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800667 EXPECT_EQ(
668 ErrorCode::kFilesystemVerifierError,
669 GetErrorCodeForAction(&filesystem_verifier_action, ErrorCode::kError));
Alex Deymob15a0b82015-11-25 20:30:40 -0300670 PostinstallRunnerAction postinstall_runner_action(
Alex Deymofb905d92016-06-03 19:26:58 -0700671 fake_system_state.fake_boot_control(), fake_system_state.fake_hardware());
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800672 EXPECT_EQ(
673 ErrorCode::kPostinstallRunnerError,
674 GetErrorCodeForAction(&postinstall_runner_action, ErrorCode::kError));
Alex Deymo8427b4a2014-11-05 14:00:32 -0800675 MockAction action_mock;
676 EXPECT_CALL(action_mock, Type()).WillOnce(Return("MockAction"));
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700677 EXPECT_EQ(ErrorCode::kError,
678 GetErrorCodeForAction(&action_mock, ErrorCode::kError));
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700679}
680
Darin Petkov36275772010-10-01 11:40:57 -0700681TEST_F(UpdateAttempterTest, DisableDeltaUpdateIfNeededTest) {
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700682 attempter_.omaha_request_params_->set_delta_okay(true);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800683 EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _))
Darin Petkov36275772010-10-01 11:40:57 -0700684 .WillOnce(Return(false));
685 attempter_.DisableDeltaUpdateIfNeeded();
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700686 EXPECT_TRUE(attempter_.omaha_request_params_->delta_okay());
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800687 EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _))
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800688 .WillOnce(
689 DoAll(SetArgPointee<1>(UpdateAttempter::kMaxDeltaUpdateFailures - 1),
690 Return(true)));
Darin Petkov36275772010-10-01 11:40:57 -0700691 attempter_.DisableDeltaUpdateIfNeeded();
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700692 EXPECT_TRUE(attempter_.omaha_request_params_->delta_okay());
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800693 EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _))
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800694 .WillOnce(
695 DoAll(SetArgPointee<1>(UpdateAttempter::kMaxDeltaUpdateFailures),
696 Return(true)));
Darin Petkov36275772010-10-01 11:40:57 -0700697 attempter_.DisableDeltaUpdateIfNeeded();
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700698 EXPECT_FALSE(attempter_.omaha_request_params_->delta_okay());
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800699 EXPECT_CALL(*prefs_, GetInt64(_, _)).Times(0);
Darin Petkov36275772010-10-01 11:40:57 -0700700 attempter_.DisableDeltaUpdateIfNeeded();
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700701 EXPECT_FALSE(attempter_.omaha_request_params_->delta_okay());
Darin Petkov36275772010-10-01 11:40:57 -0700702}
703
704TEST_F(UpdateAttempterTest, MarkDeltaUpdateFailureTest) {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800705 EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _))
Darin Petkov36275772010-10-01 11:40:57 -0700706 .WillOnce(Return(false))
Ben Chan672c1f52017-10-23 15:41:39 -0700707 .WillOnce(DoAll(SetArgPointee<1>(-1), Return(true)))
708 .WillOnce(DoAll(SetArgPointee<1>(1), Return(true)))
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800709 .WillOnce(
710 DoAll(SetArgPointee<1>(UpdateAttempter::kMaxDeltaUpdateFailures),
711 Return(true)));
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800712 EXPECT_CALL(*prefs_, SetInt64(Ne(kPrefsDeltaUpdateFailures), _))
Darin Petkov2dd01092010-10-08 15:43:05 -0700713 .WillRepeatedly(Return(true));
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800714 EXPECT_CALL(*prefs_, SetInt64(kPrefsDeltaUpdateFailures, 1)).Times(2);
Gilad Arnold74b5f552014-10-07 08:17:16 -0700715 EXPECT_CALL(*prefs_, SetInt64(kPrefsDeltaUpdateFailures, 2));
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800716 EXPECT_CALL(*prefs_,
717 SetInt64(kPrefsDeltaUpdateFailures,
718 UpdateAttempter::kMaxDeltaUpdateFailures + 1));
719 for (int i = 0; i < 4; i++)
Darin Petkov36275772010-10-01 11:40:57 -0700720 attempter_.MarkDeltaUpdateFailure();
721}
722
Darin Petkov1b003102010-11-30 10:18:36 -0800723TEST_F(UpdateAttempterTest, ScheduleErrorEventActionNoEventTest) {
724 EXPECT_CALL(*processor_, EnqueueAction(_)).Times(0);
725 EXPECT_CALL(*processor_, StartProcessing()).Times(0);
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700726 EXPECT_CALL(*fake_system_state_.mock_payload_state(), UpdateFailed(_))
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800727 .Times(0);
728 OmahaResponse response;
Jay Srinivasan53173b92013-05-17 17:13:01 -0700729 string url1 = "http://url1";
Sen Jiang0affc2c2017-02-10 15:55:05 -0800730 response.packages.push_back({.payload_urls = {url1, "https://url"}});
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700731 EXPECT_CALL(*(fake_system_state_.mock_payload_state()), GetCurrentUrl())
Jay Srinivasan53173b92013-05-17 17:13:01 -0700732 .WillRepeatedly(Return(url1));
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700733 fake_system_state_.mock_payload_state()->SetResponse(response);
Darin Petkov1b003102010-11-30 10:18:36 -0800734 attempter_.ScheduleErrorEventAction();
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700735 EXPECT_EQ(url1, fake_system_state_.mock_payload_state()->GetCurrentUrl());
Darin Petkov1b003102010-11-30 10:18:36 -0800736}
737
738TEST_F(UpdateAttempterTest, ScheduleErrorEventActionTest) {
739 EXPECT_CALL(*processor_,
Amin Hassanid3f4bea2018-04-30 14:52:40 -0700740 EnqueueAction(Pointee(Property(
741 &AbstractAction::Type, OmahaRequestAction::StaticType()))));
Gilad Arnold74b5f552014-10-07 08:17:16 -0700742 EXPECT_CALL(*processor_, StartProcessing());
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700743 ErrorCode err = ErrorCode::kError;
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700744 EXPECT_CALL(*fake_system_state_.mock_payload_state(), UpdateFailed(err));
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800745 attempter_.error_event_.reset(new OmahaEvent(
746 OmahaEvent::kTypeUpdateComplete, OmahaEvent::kResultError, err));
Darin Petkov1b003102010-11-30 10:18:36 -0800747 attempter_.ScheduleErrorEventAction();
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700748 EXPECT_EQ(UpdateStatus::REPORTING_ERROR_EVENT, attempter_.status());
Darin Petkov1b003102010-11-30 10:18:36 -0800749}
750
Darin Petkove6ef2f82011-03-07 17:31:11 -0800751namespace {
Chris Sosa76a29ae2013-07-11 17:59:24 -0700752// Actions that will be built as part of an update check.
Askar Aitzhan570ca872019-04-24 11:16:12 +0200753vector<string> GetUpdateActionTypes() {
754 return {OmahaRequestAction::StaticType(),
755 OmahaResponseHandlerAction::StaticType(),
756 UpdateBootFlagsAction::StaticType(),
757 OmahaRequestAction::StaticType(),
758 DownloadAction::StaticType(),
759 OmahaRequestAction::StaticType(),
760 FilesystemVerifierAction::StaticType(),
761 PostinstallRunnerAction::StaticType(),
762 OmahaRequestAction::StaticType()};
763}
Chris Sosa76a29ae2013-07-11 17:59:24 -0700764
765// Actions that will be built as part of a user-initiated rollback.
Askar Aitzhan570ca872019-04-24 11:16:12 +0200766vector<string> GetRollbackActionTypes() {
767 return {InstallPlanAction::StaticType(),
768 PostinstallRunnerAction::StaticType()};
769}
Chris Sosa76a29ae2013-07-11 17:59:24 -0700770
Adolfo Victoria497044c2018-07-18 07:51:42 -0700771const StagingSchedule kValidStagingSchedule = {
772 {4, 10}, {10, 40}, {19, 70}, {26, 100}};
773
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700774} // namespace
Darin Petkove6ef2f82011-03-07 17:31:11 -0800775
776void UpdateAttempterTest::UpdateTestStart() {
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700777 attempter_.set_http_response_code(200);
Alex Deymo749ecf12014-10-21 20:06:57 -0700778
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700779 // Expect that the device policy is loaded by the |UpdateAttempter| at some
780 // point by calling |RefreshDevicePolicy()|.
Igor9fd76b62017-12-11 15:24:18 +0100781 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Alex Deymo749ecf12014-10-21 20:06:57 -0700782 EXPECT_CALL(*device_policy, LoadPolicy())
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800783 .Times(testing::AtLeast(1))
784 .WillRepeatedly(Return(true));
Igor9fd76b62017-12-11 15:24:18 +0100785 attempter_.policy_provider_.reset(
786 new policy::PolicyProvider(std::move(device_policy)));
Alex Deymo749ecf12014-10-21 20:06:57 -0700787
788 {
789 InSequence s;
Askar Aitzhan570ca872019-04-24 11:16:12 +0200790 for (const auto& update_action_type : GetUpdateActionTypes()) {
Alex Deymo749ecf12014-10-21 20:06:57 -0700791 EXPECT_CALL(*processor_,
Amin Hassanid3f4bea2018-04-30 14:52:40 -0700792 EnqueueAction(Pointee(
Askar Aitzhan570ca872019-04-24 11:16:12 +0200793 Property(&AbstractAction::Type, update_action_type))));
Alex Deymo749ecf12014-10-21 20:06:57 -0700794 }
Gilad Arnold74b5f552014-10-07 08:17:16 -0700795 EXPECT_CALL(*processor_, StartProcessing());
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700796 }
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700797
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -0800798 attempter_.Update("", "", "", "", false, false, 0, false, false);
Alex Deymo60ca1a72015-06-18 18:19:15 -0700799 loop_.PostTask(FROM_HERE,
800 base::Bind(&UpdateAttempterTest::UpdateTestVerify,
801 base::Unretained(this)));
Darin Petkove6ef2f82011-03-07 17:31:11 -0800802}
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700803
Darin Petkove6ef2f82011-03-07 17:31:11 -0800804void UpdateAttempterTest::UpdateTestVerify() {
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700805 EXPECT_EQ(0, attempter_.http_response_code());
806 EXPECT_EQ(&attempter_, processor_->delegate());
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700807 EXPECT_EQ(UpdateStatus::CHECKING_FOR_UPDATE, attempter_.status());
Alex Deymo60ca1a72015-06-18 18:19:15 -0700808 loop_.BreakLoop();
Darin Petkove6ef2f82011-03-07 17:31:11 -0800809}
810
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800811void UpdateAttempterTest::RollbackTestStart(bool enterprise_rollback,
812 bool valid_slot) {
Chris Sosa76a29ae2013-07-11 17:59:24 -0700813 // Create a device policy so that we can change settings.
Igor9fd76b62017-12-11 15:24:18 +0100814 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Chris Sosa76a29ae2013-07-11 17:59:24 -0700815 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
Igor9fd76b62017-12-11 15:24:18 +0100816 fake_system_state_.set_device_policy(device_policy.get());
817 if (enterprise_rollback) {
818 // We return an empty owner as this is an enterprise.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800819 EXPECT_CALL(*device_policy, GetOwner(_))
820 .WillRepeatedly(DoAll(SetArgPointee<0>(string("")), Return(true)));
Igor9fd76b62017-12-11 15:24:18 +0100821 } else {
822 // We return a fake owner as this is an owned consumer device.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800823 EXPECT_CALL(*device_policy, GetOwner(_))
824 .WillRepeatedly(DoAll(SetArgPointee<0>(string("fake.mail@fake.com")),
825 Return(true)));
Igor9fd76b62017-12-11 15:24:18 +0100826 }
827
828 attempter_.policy_provider_.reset(
829 new policy::PolicyProvider(std::move(device_policy)));
Chris Sosa76a29ae2013-07-11 17:59:24 -0700830
Alex Deymo763e7db2015-08-27 21:08:08 -0700831 if (valid_slot) {
832 BootControlInterface::Slot rollback_slot = 1;
833 LOG(INFO) << "Test Mark Bootable: "
834 << BootControlInterface::SlotName(rollback_slot);
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700835 fake_system_state_.fake_boot_control()->SetSlotBootable(rollback_slot,
836 true);
Don Garrett6646b442013-11-13 15:29:11 -0800837 }
838
Chris Sosa28e479c2013-07-12 11:39:53 -0700839 bool is_rollback_allowed = false;
Chris Sosa76a29ae2013-07-11 17:59:24 -0700840
Chris Sosad38b1132014-03-25 10:43:59 -0700841 // We only allow rollback on devices that are not enterprise enrolled and
842 // which have a valid slot to rollback to.
843 if (!enterprise_rollback && valid_slot) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800844 is_rollback_allowed = true;
Chris Sosa28e479c2013-07-12 11:39:53 -0700845 }
846
Chris Sosa28e479c2013-07-12 11:39:53 -0700847 if (is_rollback_allowed) {
Chris Sosa76a29ae2013-07-11 17:59:24 -0700848 InSequence s;
Askar Aitzhan570ca872019-04-24 11:16:12 +0200849 for (const auto& rollback_action_type : GetRollbackActionTypes()) {
Chris Sosa76a29ae2013-07-11 17:59:24 -0700850 EXPECT_CALL(*processor_,
Askar Aitzhan570ca872019-04-24 11:16:12 +0200851 EnqueueAction(Pointee(
852 Property(&AbstractAction::Type, rollback_action_type))));
Chris Sosa76a29ae2013-07-11 17:59:24 -0700853 }
Gilad Arnold74b5f552014-10-07 08:17:16 -0700854 EXPECT_CALL(*processor_, StartProcessing());
Chris Sosa76a29ae2013-07-11 17:59:24 -0700855
Chris Sosa44b9b7e2014-04-02 13:53:46 -0700856 EXPECT_TRUE(attempter_.Rollback(true));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700857 loop_.PostTask(FROM_HERE,
858 base::Bind(&UpdateAttempterTest::RollbackTestVerify,
859 base::Unretained(this)));
Chris Sosa76a29ae2013-07-11 17:59:24 -0700860 } else {
Chris Sosa44b9b7e2014-04-02 13:53:46 -0700861 EXPECT_FALSE(attempter_.Rollback(true));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700862 loop_.BreakLoop();
Chris Sosa76a29ae2013-07-11 17:59:24 -0700863 }
864}
865
866void UpdateAttempterTest::RollbackTestVerify() {
867 // Verifies the actions that were enqueued.
868 EXPECT_EQ(&attempter_, processor_->delegate());
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700869 EXPECT_EQ(UpdateStatus::ATTEMPTING_ROLLBACK, attempter_.status());
Amin Hassanid3f4bea2018-04-30 14:52:40 -0700870 EXPECT_EQ(0U, attempter_.install_plan_->partitions.size());
871 EXPECT_EQ(attempter_.install_plan_->powerwash_required, true);
Alex Deymo60ca1a72015-06-18 18:19:15 -0700872 loop_.BreakLoop();
Chris Sosa76a29ae2013-07-11 17:59:24 -0700873}
874
Darin Petkove6ef2f82011-03-07 17:31:11 -0800875TEST_F(UpdateAttempterTest, UpdateTest) {
Alex Deymo461b2592015-07-24 20:10:52 -0700876 UpdateTestStart();
Alex Deymo60ca1a72015-06-18 18:19:15 -0700877 loop_.Run();
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700878}
879
Chris Sosa76a29ae2013-07-11 17:59:24 -0700880TEST_F(UpdateAttempterTest, RollbackTest) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700881 loop_.PostTask(FROM_HERE,
882 base::Bind(&UpdateAttempterTest::RollbackTestStart,
883 base::Unretained(this),
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800884 false,
885 true));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700886 loop_.Run();
Chris Sosa76a29ae2013-07-11 17:59:24 -0700887}
888
Don Garrett6646b442013-11-13 15:29:11 -0800889TEST_F(UpdateAttempterTest, InvalidSlotRollbackTest) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700890 loop_.PostTask(FROM_HERE,
891 base::Bind(&UpdateAttempterTest::RollbackTestStart,
892 base::Unretained(this),
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800893 false,
894 false));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700895 loop_.Run();
Don Garrett6646b442013-11-13 15:29:11 -0800896}
897
Chris Sosa76a29ae2013-07-11 17:59:24 -0700898TEST_F(UpdateAttempterTest, EnterpriseRollbackTest) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700899 loop_.PostTask(FROM_HERE,
900 base::Bind(&UpdateAttempterTest::RollbackTestStart,
901 base::Unretained(this),
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800902 true,
903 true));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700904 loop_.Run();
Chris Sosa76a29ae2013-07-11 17:59:24 -0700905}
906
Thieu Le116fda32011-04-19 11:01:54 -0700907void UpdateAttempterTest::PingOmahaTestStart() {
908 EXPECT_CALL(*processor_,
Amin Hassanid3f4bea2018-04-30 14:52:40 -0700909 EnqueueAction(Pointee(Property(
910 &AbstractAction::Type, OmahaRequestAction::StaticType()))));
Gilad Arnold74b5f552014-10-07 08:17:16 -0700911 EXPECT_CALL(*processor_, StartProcessing());
Thieu Le116fda32011-04-19 11:01:54 -0700912 attempter_.PingOmaha();
Alex Deymo60ca1a72015-06-18 18:19:15 -0700913 ScheduleQuitMainLoop();
Thieu Le116fda32011-04-19 11:01:54 -0700914}
915
916TEST_F(UpdateAttempterTest, PingOmahaTest) {
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700917 EXPECT_FALSE(attempter_.waiting_for_scheduled_check_);
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700918 EXPECT_FALSE(attempter_.WasScheduleUpdatesCalled());
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700919 // Disable scheduling of subsequnet checks; we're using the |DefaultPolicy| in
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700920 // testing, which is more permissive than we want to handle here.
921 attempter_.DisableScheduleUpdates();
Alex Deymo60ca1a72015-06-18 18:19:15 -0700922 loop_.PostTask(FROM_HERE,
923 base::Bind(&UpdateAttempterTest::PingOmahaTestStart,
924 base::Unretained(this)));
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700925 brillo::MessageLoopRunMaxIterations(&loop_, 100);
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700926 EXPECT_EQ(UpdateStatus::UPDATED_NEED_REBOOT, attempter_.status());
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700927 EXPECT_TRUE(attempter_.WasScheduleUpdatesCalled());
Thieu Le116fda32011-04-19 11:01:54 -0700928}
929
Darin Petkov18c7bce2011-06-16 14:07:00 -0700930TEST_F(UpdateAttempterTest, CreatePendingErrorEventTest) {
Alex Deymo8427b4a2014-11-05 14:00:32 -0800931 MockAction action;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700932 const ErrorCode kCode = ErrorCode::kDownloadTransferError;
Darin Petkov18c7bce2011-06-16 14:07:00 -0700933 attempter_.CreatePendingErrorEvent(&action, kCode);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700934 ASSERT_NE(nullptr, attempter_.error_event_.get());
Darin Petkov18c7bce2011-06-16 14:07:00 -0700935 EXPECT_EQ(OmahaEvent::kTypeUpdateComplete, attempter_.error_event_->type);
936 EXPECT_EQ(OmahaEvent::kResultError, attempter_.error_event_->result);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700937 EXPECT_EQ(
938 static_cast<ErrorCode>(static_cast<int>(kCode) |
939 static_cast<int>(ErrorCode::kTestOmahaUrlFlag)),
940 attempter_.error_event_->error_code);
Darin Petkov18c7bce2011-06-16 14:07:00 -0700941}
942
943TEST_F(UpdateAttempterTest, CreatePendingErrorEventResumedTest) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -0700944 attempter_.install_plan_.reset(new InstallPlan);
945 attempter_.install_plan_->is_resume = true;
Alex Deymo8427b4a2014-11-05 14:00:32 -0800946 MockAction action;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700947 const ErrorCode kCode = ErrorCode::kInstallDeviceOpenError;
Darin Petkov18c7bce2011-06-16 14:07:00 -0700948 attempter_.CreatePendingErrorEvent(&action, kCode);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700949 ASSERT_NE(nullptr, attempter_.error_event_.get());
Darin Petkov18c7bce2011-06-16 14:07:00 -0700950 EXPECT_EQ(OmahaEvent::kTypeUpdateComplete, attempter_.error_event_->type);
951 EXPECT_EQ(OmahaEvent::kResultError, attempter_.error_event_->result);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700952 EXPECT_EQ(
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800953 static_cast<ErrorCode>(static_cast<int>(kCode) |
954 static_cast<int>(ErrorCode::kResumedFlag) |
955 static_cast<int>(ErrorCode::kTestOmahaUrlFlag)),
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700956 attempter_.error_event_->error_code);
Darin Petkov18c7bce2011-06-16 14:07:00 -0700957}
958
David Zeuthen8f191b22013-08-06 12:27:50 -0700959TEST_F(UpdateAttempterTest, P2PNotStartedAtStartupWhenNotEnabled) {
960 MockP2PManager mock_p2p_manager;
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700961 fake_system_state_.set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -0700962 mock_p2p_manager.fake().SetP2PEnabled(false);
963 EXPECT_CALL(mock_p2p_manager, EnsureP2PRunning()).Times(0);
964 attempter_.UpdateEngineStarted();
965}
966
967TEST_F(UpdateAttempterTest, P2PNotStartedAtStartupWhenEnabledButNotSharing) {
968 MockP2PManager mock_p2p_manager;
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700969 fake_system_state_.set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -0700970 mock_p2p_manager.fake().SetP2PEnabled(true);
971 EXPECT_CALL(mock_p2p_manager, EnsureP2PRunning()).Times(0);
972 attempter_.UpdateEngineStarted();
973}
974
975TEST_F(UpdateAttempterTest, P2PStartedAtStartupWhenEnabledAndSharing) {
976 MockP2PManager mock_p2p_manager;
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700977 fake_system_state_.set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -0700978 mock_p2p_manager.fake().SetP2PEnabled(true);
979 mock_p2p_manager.fake().SetCountSharedFilesResult(1);
Gilad Arnold74b5f552014-10-07 08:17:16 -0700980 EXPECT_CALL(mock_p2p_manager, EnsureP2PRunning());
David Zeuthen8f191b22013-08-06 12:27:50 -0700981 attempter_.UpdateEngineStarted();
982}
983
984TEST_F(UpdateAttempterTest, P2PNotEnabled) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700985 loop_.PostTask(FROM_HERE,
986 base::Bind(&UpdateAttempterTest::P2PNotEnabledStart,
987 base::Unretained(this)));
988 loop_.Run();
David Zeuthen8f191b22013-08-06 12:27:50 -0700989}
Alex Deymo60ca1a72015-06-18 18:19:15 -0700990
David Zeuthen8f191b22013-08-06 12:27:50 -0700991void UpdateAttempterTest::P2PNotEnabledStart() {
992 // If P2P is not enabled, check that we do not attempt housekeeping
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700993 // and do not convey that P2P is to be used.
David Zeuthen8f191b22013-08-06 12:27:50 -0700994 MockP2PManager mock_p2p_manager;
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700995 fake_system_state_.set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -0700996 mock_p2p_manager.fake().SetP2PEnabled(false);
997 EXPECT_CALL(mock_p2p_manager, PerformHousekeeping()).Times(0);
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -0800998 attempter_.Update("", "", "", "", false, false, 0, false, false);
Alex Deymo60ca1a72015-06-18 18:19:15 -0700999 EXPECT_FALSE(actual_using_p2p_for_downloading_);
Gilad Arnold74b5f552014-10-07 08:17:16 -07001000 EXPECT_FALSE(actual_using_p2p_for_sharing());
Alex Deymo60ca1a72015-06-18 18:19:15 -07001001 ScheduleQuitMainLoop();
David Zeuthen8f191b22013-08-06 12:27:50 -07001002}
1003
1004TEST_F(UpdateAttempterTest, P2PEnabledStartingFails) {
Alex Deymo60ca1a72015-06-18 18:19:15 -07001005 loop_.PostTask(FROM_HERE,
1006 base::Bind(&UpdateAttempterTest::P2PEnabledStartingFailsStart,
1007 base::Unretained(this)));
1008 loop_.Run();
David Zeuthen8f191b22013-08-06 12:27:50 -07001009}
Alex Deymo60ca1a72015-06-18 18:19:15 -07001010
David Zeuthen8f191b22013-08-06 12:27:50 -07001011void UpdateAttempterTest::P2PEnabledStartingFailsStart() {
Jae Hoon Kimedb65502019-06-14 11:52:17 -07001012 // If P2P is enabled, but starting it fails ensure we don't do
1013 // any housekeeping and do not convey that P2P should be used.
David Zeuthen8f191b22013-08-06 12:27:50 -07001014 MockP2PManager mock_p2p_manager;
Gilad Arnold5bb4c902014-04-10 12:32:13 -07001015 fake_system_state_.set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -07001016 mock_p2p_manager.fake().SetP2PEnabled(true);
1017 mock_p2p_manager.fake().SetEnsureP2PRunningResult(false);
1018 mock_p2p_manager.fake().SetPerformHousekeepingResult(false);
1019 EXPECT_CALL(mock_p2p_manager, PerformHousekeeping()).Times(0);
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001020 attempter_.Update("", "", "", "", false, false, 0, false, false);
Gilad Arnold74b5f552014-10-07 08:17:16 -07001021 EXPECT_FALSE(actual_using_p2p_for_downloading());
1022 EXPECT_FALSE(actual_using_p2p_for_sharing());
Alex Deymo60ca1a72015-06-18 18:19:15 -07001023 ScheduleQuitMainLoop();
David Zeuthen8f191b22013-08-06 12:27:50 -07001024}
1025
1026TEST_F(UpdateAttempterTest, P2PEnabledHousekeepingFails) {
Alex Deymo60ca1a72015-06-18 18:19:15 -07001027 loop_.PostTask(
1028 FROM_HERE,
1029 base::Bind(&UpdateAttempterTest::P2PEnabledHousekeepingFailsStart,
1030 base::Unretained(this)));
1031 loop_.Run();
David Zeuthen8f191b22013-08-06 12:27:50 -07001032}
Alex Deymo60ca1a72015-06-18 18:19:15 -07001033
David Zeuthen8f191b22013-08-06 12:27:50 -07001034void UpdateAttempterTest::P2PEnabledHousekeepingFailsStart() {
Jae Hoon Kimedb65502019-06-14 11:52:17 -07001035 // If P2P is enabled, starting it works but housekeeping fails, ensure
1036 // we do not convey P2P is to be used.
David Zeuthen8f191b22013-08-06 12:27:50 -07001037 MockP2PManager mock_p2p_manager;
Gilad Arnold5bb4c902014-04-10 12:32:13 -07001038 fake_system_state_.set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -07001039 mock_p2p_manager.fake().SetP2PEnabled(true);
1040 mock_p2p_manager.fake().SetEnsureP2PRunningResult(true);
1041 mock_p2p_manager.fake().SetPerformHousekeepingResult(false);
Gilad Arnold74b5f552014-10-07 08:17:16 -07001042 EXPECT_CALL(mock_p2p_manager, PerformHousekeeping());
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001043 attempter_.Update("", "", "", "", false, false, 0, false, false);
Gilad Arnold74b5f552014-10-07 08:17:16 -07001044 EXPECT_FALSE(actual_using_p2p_for_downloading());
1045 EXPECT_FALSE(actual_using_p2p_for_sharing());
Alex Deymo60ca1a72015-06-18 18:19:15 -07001046 ScheduleQuitMainLoop();
David Zeuthen8f191b22013-08-06 12:27:50 -07001047}
1048
1049TEST_F(UpdateAttempterTest, P2PEnabled) {
Alex Deymo60ca1a72015-06-18 18:19:15 -07001050 loop_.PostTask(FROM_HERE,
1051 base::Bind(&UpdateAttempterTest::P2PEnabledStart,
1052 base::Unretained(this)));
1053 loop_.Run();
David Zeuthen8f191b22013-08-06 12:27:50 -07001054}
Alex Deymo60ca1a72015-06-18 18:19:15 -07001055
David Zeuthen8f191b22013-08-06 12:27:50 -07001056void UpdateAttempterTest::P2PEnabledStart() {
1057 MockP2PManager mock_p2p_manager;
Gilad Arnold5bb4c902014-04-10 12:32:13 -07001058 fake_system_state_.set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -07001059 // If P2P is enabled and starting it works, check that we performed
Jae Hoon Kimedb65502019-06-14 11:52:17 -07001060 // housekeeping and that we convey P2P should be used.
David Zeuthen8f191b22013-08-06 12:27:50 -07001061 mock_p2p_manager.fake().SetP2PEnabled(true);
1062 mock_p2p_manager.fake().SetEnsureP2PRunningResult(true);
1063 mock_p2p_manager.fake().SetPerformHousekeepingResult(true);
Gilad Arnold74b5f552014-10-07 08:17:16 -07001064 EXPECT_CALL(mock_p2p_manager, PerformHousekeeping());
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001065 attempter_.Update("", "", "", "", false, false, 0, false, false);
Gilad Arnold74b5f552014-10-07 08:17:16 -07001066 EXPECT_TRUE(actual_using_p2p_for_downloading());
1067 EXPECT_TRUE(actual_using_p2p_for_sharing());
Alex Deymo60ca1a72015-06-18 18:19:15 -07001068 ScheduleQuitMainLoop();
David Zeuthen8f191b22013-08-06 12:27:50 -07001069}
1070
1071TEST_F(UpdateAttempterTest, P2PEnabledInteractive) {
Alex Deymo60ca1a72015-06-18 18:19:15 -07001072 loop_.PostTask(FROM_HERE,
1073 base::Bind(&UpdateAttempterTest::P2PEnabledInteractiveStart,
1074 base::Unretained(this)));
1075 loop_.Run();
David Zeuthen8f191b22013-08-06 12:27:50 -07001076}
Alex Deymo60ca1a72015-06-18 18:19:15 -07001077
David Zeuthen8f191b22013-08-06 12:27:50 -07001078void UpdateAttempterTest::P2PEnabledInteractiveStart() {
1079 MockP2PManager mock_p2p_manager;
Gilad Arnold5bb4c902014-04-10 12:32:13 -07001080 fake_system_state_.set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -07001081 // For an interactive check, if P2P is enabled and starting it
1082 // works, check that we performed housekeeping and that we convey
Jae Hoon Kimedb65502019-06-14 11:52:17 -07001083 // P2P should be used for sharing but NOT for downloading.
David Zeuthen8f191b22013-08-06 12:27:50 -07001084 mock_p2p_manager.fake().SetP2PEnabled(true);
1085 mock_p2p_manager.fake().SetEnsureP2PRunningResult(true);
1086 mock_p2p_manager.fake().SetPerformHousekeepingResult(true);
Gilad Arnold74b5f552014-10-07 08:17:16 -07001087 EXPECT_CALL(mock_p2p_manager, PerformHousekeeping());
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001088 attempter_.Update("",
1089 "",
1090 "",
1091 "",
1092 false,
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001093 false,
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -07001094 /*rollback_allowed_milestones=*/0,
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001095 false,
1096 /*interactive=*/true);
Gilad Arnold74b5f552014-10-07 08:17:16 -07001097 EXPECT_FALSE(actual_using_p2p_for_downloading());
1098 EXPECT_TRUE(actual_using_p2p_for_sharing());
Alex Deymo60ca1a72015-06-18 18:19:15 -07001099 ScheduleQuitMainLoop();
David Zeuthen8f191b22013-08-06 12:27:50 -07001100}
1101
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001102TEST_F(UpdateAttempterTest, ReadScatterFactorFromPolicy) {
Alex Deymo60ca1a72015-06-18 18:19:15 -07001103 loop_.PostTask(
1104 FROM_HERE,
1105 base::Bind(&UpdateAttempterTest::ReadScatterFactorFromPolicyTestStart,
1106 base::Unretained(this)));
1107 loop_.Run();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001108}
1109
1110// Tests that the scatter_factor_in_seconds value is properly fetched
1111// from the device policy.
1112void UpdateAttempterTest::ReadScatterFactorFromPolicyTestStart() {
Ben Chan9abb7632014-08-07 00:10:53 -07001113 int64_t scatter_factor_in_seconds = 36000;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001114
Igor9fd76b62017-12-11 15:24:18 +01001115 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001116 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
Igor9fd76b62017-12-11 15:24:18 +01001117 fake_system_state_.set_device_policy(device_policy.get());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001118
1119 EXPECT_CALL(*device_policy, GetScatterFactorInSeconds(_))
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001120 .WillRepeatedly(
1121 DoAll(SetArgPointee<0>(scatter_factor_in_seconds), Return(true)));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001122
Igor9fd76b62017-12-11 15:24:18 +01001123 attempter_.policy_provider_.reset(
1124 new policy::PolicyProvider(std::move(device_policy)));
1125
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001126 attempter_.Update("", "", "", "", false, false, 0, false, false);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001127 EXPECT_EQ(scatter_factor_in_seconds, attempter_.scatter_factor_.InSeconds());
1128
Alex Deymo60ca1a72015-06-18 18:19:15 -07001129 ScheduleQuitMainLoop();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001130}
1131
1132TEST_F(UpdateAttempterTest, DecrementUpdateCheckCountTest) {
Alex Deymo60ca1a72015-06-18 18:19:15 -07001133 loop_.PostTask(
1134 FROM_HERE,
1135 base::Bind(&UpdateAttempterTest::DecrementUpdateCheckCountTestStart,
1136 base::Unretained(this)));
1137 loop_.Run();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001138}
1139
1140void UpdateAttempterTest::DecrementUpdateCheckCountTestStart() {
1141 // Tests that the scatter_factor_in_seconds value is properly fetched
1142 // from the device policy and is decremented if value > 0.
Ben Chan9abb7632014-08-07 00:10:53 -07001143 int64_t initial_value = 5;
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001144 FakePrefs fake_prefs;
1145 attempter_.prefs_ = &fake_prefs;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001146
Gilad Arnold5bb4c902014-04-10 12:32:13 -07001147 fake_system_state_.fake_hardware()->SetIsOOBEComplete(Time::UnixEpoch());
Jay Srinivasan08fce042012-06-07 16:31:01 -07001148
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001149 EXPECT_TRUE(fake_prefs.SetInt64(kPrefsUpdateCheckCount, initial_value));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001150
Ben Chan9abb7632014-08-07 00:10:53 -07001151 int64_t scatter_factor_in_seconds = 10;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001152
Igor9fd76b62017-12-11 15:24:18 +01001153 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001154 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
Igor9fd76b62017-12-11 15:24:18 +01001155 fake_system_state_.set_device_policy(device_policy.get());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001156
1157 EXPECT_CALL(*device_policy, GetScatterFactorInSeconds(_))
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001158 .WillRepeatedly(
1159 DoAll(SetArgPointee<0>(scatter_factor_in_seconds), Return(true)));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001160
Igor9fd76b62017-12-11 15:24:18 +01001161 attempter_.policy_provider_.reset(
1162 new policy::PolicyProvider(std::move(device_policy)));
1163
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001164 attempter_.Update("", "", "", "", false, false, 0, false, false);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001165 EXPECT_EQ(scatter_factor_in_seconds, attempter_.scatter_factor_.InSeconds());
1166
1167 // Make sure the file still exists.
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001168 EXPECT_TRUE(fake_prefs.Exists(kPrefsUpdateCheckCount));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001169
Ben Chan9abb7632014-08-07 00:10:53 -07001170 int64_t new_value;
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001171 EXPECT_TRUE(fake_prefs.GetInt64(kPrefsUpdateCheckCount, &new_value));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001172 EXPECT_EQ(initial_value - 1, new_value);
1173
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001174 EXPECT_TRUE(
1175 attempter_.omaha_request_params_->update_check_count_wait_enabled());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001176
1177 // However, if the count is already 0, it's not decremented. Test that.
1178 initial_value = 0;
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001179 EXPECT_TRUE(fake_prefs.SetInt64(kPrefsUpdateCheckCount, initial_value));
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001180 attempter_.Update("", "", "", "", false, false, 0, false, false);
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001181 EXPECT_TRUE(fake_prefs.Exists(kPrefsUpdateCheckCount));
1182 EXPECT_TRUE(fake_prefs.GetInt64(kPrefsUpdateCheckCount, &new_value));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001183 EXPECT_EQ(initial_value, new_value);
1184
Alex Deymo60ca1a72015-06-18 18:19:15 -07001185 ScheduleQuitMainLoop();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001186}
1187
Jay Srinivasan08fce042012-06-07 16:31:01 -07001188TEST_F(UpdateAttempterTest, NoScatteringDoneDuringManualUpdateTestStart) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001189 loop_.PostTask(
1190 FROM_HERE,
1191 base::Bind(
1192 &UpdateAttempterTest::NoScatteringDoneDuringManualUpdateTestStart,
1193 base::Unretained(this)));
Alex Deymo60ca1a72015-06-18 18:19:15 -07001194 loop_.Run();
Jay Srinivasan08fce042012-06-07 16:31:01 -07001195}
1196
1197void UpdateAttempterTest::NoScatteringDoneDuringManualUpdateTestStart() {
1198 // Tests that no scattering logic is enabled if the update check
1199 // is manually done (as opposed to a scheduled update check)
Ben Chan9abb7632014-08-07 00:10:53 -07001200 int64_t initial_value = 8;
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001201 FakePrefs fake_prefs;
1202 attempter_.prefs_ = &fake_prefs;
Jay Srinivasan08fce042012-06-07 16:31:01 -07001203
Gilad Arnold5bb4c902014-04-10 12:32:13 -07001204 fake_system_state_.fake_hardware()->SetIsOOBEComplete(Time::UnixEpoch());
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001205 fake_system_state_.set_prefs(&fake_prefs);
Jay Srinivasan08fce042012-06-07 16:31:01 -07001206
Adolfo Victoriad3a1e352018-07-16 11:40:47 -07001207 EXPECT_TRUE(
1208 fake_prefs.SetInt64(kPrefsWallClockScatteringWaitPeriod, initial_value));
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001209 EXPECT_TRUE(fake_prefs.SetInt64(kPrefsUpdateCheckCount, initial_value));
Jay Srinivasan08fce042012-06-07 16:31:01 -07001210
1211 // make sure scatter_factor is non-zero as scattering is disabled
1212 // otherwise.
Ben Chan9abb7632014-08-07 00:10:53 -07001213 int64_t scatter_factor_in_seconds = 50;
Jay Srinivasan08fce042012-06-07 16:31:01 -07001214
Igor9fd76b62017-12-11 15:24:18 +01001215 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Jay Srinivasan08fce042012-06-07 16:31:01 -07001216 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
Igor9fd76b62017-12-11 15:24:18 +01001217 fake_system_state_.set_device_policy(device_policy.get());
Jay Srinivasan08fce042012-06-07 16:31:01 -07001218
1219 EXPECT_CALL(*device_policy, GetScatterFactorInSeconds(_))
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001220 .WillRepeatedly(
1221 DoAll(SetArgPointee<0>(scatter_factor_in_seconds), Return(true)));
Jay Srinivasan08fce042012-06-07 16:31:01 -07001222
Igor9fd76b62017-12-11 15:24:18 +01001223 attempter_.policy_provider_.reset(
1224 new policy::PolicyProvider(std::move(device_policy)));
1225
Gilad Arnoldb92f0df2013-01-10 16:32:45 -08001226 // Trigger an interactive check so we can test that scattering is disabled.
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001227 attempter_.Update("",
1228 "",
1229 "",
1230 "",
1231 false,
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001232 false,
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -07001233 /*rollback_allowed_milestones=*/0,
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001234 false,
1235 /*interactive=*/true);
Jay Srinivasan08fce042012-06-07 16:31:01 -07001236 EXPECT_EQ(scatter_factor_in_seconds, attempter_.scatter_factor_.InSeconds());
1237
1238 // Make sure scattering is disabled for manual (i.e. user initiated) update
Jay Srinivasan21be0752012-07-25 15:44:56 -07001239 // checks and all artifacts are removed.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001240 EXPECT_FALSE(
1241 attempter_.omaha_request_params_->wall_clock_based_wait_enabled());
Adolfo Victoriad3a1e352018-07-16 11:40:47 -07001242 EXPECT_FALSE(fake_prefs.Exists(kPrefsWallClockScatteringWaitPeriod));
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001243 EXPECT_EQ(0, attempter_.omaha_request_params_->waiting_period().InSeconds());
1244 EXPECT_FALSE(
1245 attempter_.omaha_request_params_->update_check_count_wait_enabled());
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001246 EXPECT_FALSE(fake_prefs.Exists(kPrefsUpdateCheckCount));
Jay Srinivasan08fce042012-06-07 16:31:01 -07001247
Alex Deymo60ca1a72015-06-18 18:19:15 -07001248 ScheduleQuitMainLoop();
Jay Srinivasan08fce042012-06-07 16:31:01 -07001249}
1250
Adolfo Victoria497044c2018-07-18 07:51:42 -07001251void UpdateAttempterTest::SetUpStagingTest(const StagingSchedule& schedule,
1252 FakePrefs* prefs) {
1253 attempter_.prefs_ = prefs;
1254 fake_system_state_.set_prefs(prefs);
1255
1256 int64_t initial_value = 8;
1257 EXPECT_TRUE(
1258 prefs->SetInt64(kPrefsWallClockScatteringWaitPeriod, initial_value));
1259 EXPECT_TRUE(prefs->SetInt64(kPrefsUpdateCheckCount, initial_value));
1260 attempter_.scatter_factor_ = TimeDelta::FromSeconds(20);
1261
1262 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
1263 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
1264 fake_system_state_.set_device_policy(device_policy.get());
1265 EXPECT_CALL(*device_policy, GetDeviceUpdateStagingSchedule(_))
1266 .WillRepeatedly(DoAll(SetArgPointee<0>(schedule), Return(true)));
1267
1268 attempter_.policy_provider_.reset(
1269 new policy::PolicyProvider(std::move(device_policy)));
1270}
1271
1272TEST_F(UpdateAttempterTest, StagingSetsPrefsAndTurnsOffScattering) {
1273 loop_.PostTask(
1274 FROM_HERE,
1275 base::Bind(
1276 &UpdateAttempterTest::StagingSetsPrefsAndTurnsOffScatteringStart,
1277 base::Unretained(this)));
1278 loop_.Run();
1279}
1280
1281void UpdateAttempterTest::StagingSetsPrefsAndTurnsOffScatteringStart() {
1282 // Tests that staging sets its prefs properly and turns off scattering.
1283 fake_system_state_.fake_hardware()->SetIsOOBEComplete(Time::UnixEpoch());
1284 FakePrefs fake_prefs;
1285 SetUpStagingTest(kValidStagingSchedule, &fake_prefs);
1286
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001287 attempter_.Update("", "", "", "", false, false, 0, false, false);
Adolfo Victoria497044c2018-07-18 07:51:42 -07001288 // Check that prefs have the correct values.
1289 int64_t update_count;
1290 EXPECT_TRUE(fake_prefs.GetInt64(kPrefsUpdateCheckCount, &update_count));
1291 int64_t waiting_time_days;
1292 EXPECT_TRUE(fake_prefs.GetInt64(kPrefsWallClockStagingWaitPeriod,
1293 &waiting_time_days));
1294 EXPECT_GT(waiting_time_days, 0);
1295 // Update count should have been decremented.
1296 EXPECT_EQ(7, update_count);
1297 // Check that Omaha parameters were updated correctly.
1298 EXPECT_TRUE(
1299 attempter_.omaha_request_params_->update_check_count_wait_enabled());
1300 EXPECT_TRUE(
1301 attempter_.omaha_request_params_->wall_clock_based_wait_enabled());
1302 EXPECT_EQ(waiting_time_days,
1303 attempter_.omaha_request_params_->waiting_period().InDays());
1304 // Check class variables.
1305 EXPECT_EQ(waiting_time_days, attempter_.staging_wait_time_.InDays());
1306 EXPECT_EQ(kValidStagingSchedule, attempter_.staging_schedule_);
1307 // Check that scattering is turned off
1308 EXPECT_EQ(0, attempter_.scatter_factor_.InSeconds());
1309 EXPECT_FALSE(fake_prefs.Exists(kPrefsWallClockScatteringWaitPeriod));
1310
1311 ScheduleQuitMainLoop();
1312}
1313
1314void UpdateAttempterTest::CheckStagingOff() {
1315 // Check that all prefs were removed.
1316 EXPECT_FALSE(attempter_.prefs_->Exists(kPrefsUpdateCheckCount));
1317 EXPECT_FALSE(attempter_.prefs_->Exists(kPrefsWallClockScatteringWaitPeriod));
1318 EXPECT_FALSE(attempter_.prefs_->Exists(kPrefsWallClockStagingWaitPeriod));
1319 // Check that the Omaha parameters have the correct value.
1320 EXPECT_EQ(0, attempter_.omaha_request_params_->waiting_period().InDays());
1321 EXPECT_EQ(attempter_.omaha_request_params_->waiting_period(),
1322 attempter_.staging_wait_time_);
1323 EXPECT_FALSE(
1324 attempter_.omaha_request_params_->update_check_count_wait_enabled());
1325 EXPECT_FALSE(
1326 attempter_.omaha_request_params_->wall_clock_based_wait_enabled());
1327 // Check that scattering is turned off too.
1328 EXPECT_EQ(0, attempter_.scatter_factor_.InSeconds());
1329}
1330
1331TEST_F(UpdateAttempterTest, StagingOffIfInteractive) {
1332 loop_.PostTask(FROM_HERE,
1333 base::Bind(&UpdateAttempterTest::StagingOffIfInteractiveStart,
1334 base::Unretained(this)));
1335 loop_.Run();
1336}
1337
1338void UpdateAttempterTest::StagingOffIfInteractiveStart() {
1339 // Tests that staging is turned off when an interactive update is requested.
1340 fake_system_state_.fake_hardware()->SetIsOOBEComplete(Time::UnixEpoch());
1341 FakePrefs fake_prefs;
1342 SetUpStagingTest(kValidStagingSchedule, &fake_prefs);
1343
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001344 attempter_.Update(
1345 "", "", "", "", false, false, 0, false, /* interactive = */ true);
Adolfo Victoria497044c2018-07-18 07:51:42 -07001346 CheckStagingOff();
1347
1348 ScheduleQuitMainLoop();
1349}
1350
1351TEST_F(UpdateAttempterTest, StagingOffIfOobe) {
1352 loop_.PostTask(FROM_HERE,
1353 base::Bind(&UpdateAttempterTest::StagingOffIfOobeStart,
1354 base::Unretained(this)));
1355 loop_.Run();
1356}
1357
1358void UpdateAttempterTest::StagingOffIfOobeStart() {
1359 // Tests that staging is turned off if OOBE hasn't been completed.
1360 fake_system_state_.fake_hardware()->SetIsOOBEEnabled(true);
1361 fake_system_state_.fake_hardware()->UnsetIsOOBEComplete();
1362 FakePrefs fake_prefs;
1363 SetUpStagingTest(kValidStagingSchedule, &fake_prefs);
1364
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001365 attempter_.Update(
1366 "", "", "", "", false, false, 0, false, /* interactive = */ true);
Adolfo Victoria497044c2018-07-18 07:51:42 -07001367 CheckStagingOff();
1368
1369 ScheduleQuitMainLoop();
1370}
1371
David Zeuthen985b1122013-10-09 12:13:15 -07001372// Checks that we only report daily metrics at most every 24 hours.
1373TEST_F(UpdateAttempterTest, ReportDailyMetrics) {
1374 FakeClock fake_clock;
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001375 FakePrefs fake_prefs;
David Zeuthen985b1122013-10-09 12:13:15 -07001376
Gilad Arnold5bb4c902014-04-10 12:32:13 -07001377 fake_system_state_.set_clock(&fake_clock);
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001378 fake_system_state_.set_prefs(&fake_prefs);
David Zeuthen985b1122013-10-09 12:13:15 -07001379
1380 Time epoch = Time::FromInternalValue(0);
1381 fake_clock.SetWallclockTime(epoch);
1382
1383 // If there is no kPrefsDailyMetricsLastReportedAt state variable,
1384 // we should report.
1385 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1386 // We should not report again if no time has passed.
1387 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1388
1389 // We should not report if only 10 hours has passed.
1390 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(10));
1391 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1392
1393 // We should not report if only 24 hours - 1 sec has passed.
1394 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(24) -
1395 TimeDelta::FromSeconds(1));
1396 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1397
1398 // We should report if 24 hours has passed.
1399 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(24));
1400 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1401
1402 // But then we should not report again..
1403 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1404
1405 // .. until another 24 hours has passed
1406 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(47));
1407 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1408 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(48));
1409 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1410 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1411
1412 // .. and another 24 hours
1413 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(71));
1414 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1415 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(72));
1416 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1417 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1418
1419 // If the span between time of reporting and present time is
1420 // negative, we report. This is in order to reset the timestamp and
1421 // avoid an edge condition whereby a distant point in the future is
1422 // in the state variable resulting in us never ever reporting again.
1423 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(71));
1424 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1425 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1426
1427 // In this case we should not update until the clock reads 71 + 24 = 95.
1428 // Check that.
1429 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(94));
1430 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1431 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(95));
1432 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1433 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
David Zeuthen985b1122013-10-09 12:13:15 -07001434}
1435
David Zeuthen3c55abd2013-10-14 12:48:03 -07001436TEST_F(UpdateAttempterTest, BootTimeInUpdateMarkerFile) {
David Zeuthen3c55abd2013-10-14 12:48:03 -07001437 FakeClock fake_clock;
1438 fake_clock.SetBootTime(Time::FromTimeT(42));
Gilad Arnold5bb4c902014-04-10 12:32:13 -07001439 fake_system_state_.set_clock(&fake_clock);
Alex Deymo906191f2015-10-12 12:22:44 -07001440 FakePrefs fake_prefs;
1441 fake_system_state_.set_prefs(&fake_prefs);
Sen Jiangaeeb2e02016-06-09 15:00:16 -07001442 attempter_.Init();
David Zeuthen3c55abd2013-10-14 12:48:03 -07001443
1444 Time boot_time;
Sen Jiangaeeb2e02016-06-09 15:00:16 -07001445 EXPECT_FALSE(attempter_.GetBootTimeAtUpdate(&boot_time));
David Zeuthen3c55abd2013-10-14 12:48:03 -07001446
Sen Jiangaeeb2e02016-06-09 15:00:16 -07001447 attempter_.WriteUpdateCompletedMarker();
David Zeuthen3c55abd2013-10-14 12:48:03 -07001448
Sen Jiangaeeb2e02016-06-09 15:00:16 -07001449 EXPECT_TRUE(attempter_.GetBootTimeAtUpdate(&boot_time));
David Zeuthen3c55abd2013-10-14 12:48:03 -07001450 EXPECT_EQ(boot_time.ToTimeT(), 42);
1451}
1452
David Pursell02c18642014-11-06 11:26:11 -08001453TEST_F(UpdateAttempterTest, AnyUpdateSourceAllowedUnofficial) {
1454 fake_system_state_.fake_hardware()->SetIsOfficialBuild(false);
1455 EXPECT_TRUE(attempter_.IsAnyUpdateSourceAllowed());
1456}
1457
1458TEST_F(UpdateAttempterTest, AnyUpdateSourceAllowedOfficialDevmode) {
1459 fake_system_state_.fake_hardware()->SetIsOfficialBuild(true);
Sen Jiange67bb5b2016-06-20 15:53:56 -07001460 fake_system_state_.fake_hardware()->SetAreDevFeaturesEnabled(true);
David Pursell02c18642014-11-06 11:26:11 -08001461 EXPECT_TRUE(attempter_.IsAnyUpdateSourceAllowed());
1462}
1463
1464TEST_F(UpdateAttempterTest, AnyUpdateSourceDisallowedOfficialNormal) {
1465 fake_system_state_.fake_hardware()->SetIsOfficialBuild(true);
Sen Jiange67bb5b2016-06-20 15:53:56 -07001466 fake_system_state_.fake_hardware()->SetAreDevFeaturesEnabled(false);
David Pursell02c18642014-11-06 11:26:11 -08001467 EXPECT_FALSE(attempter_.IsAnyUpdateSourceAllowed());
1468}
1469
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001470// TODO(kimjae): Follow testing pattern with params for |CheckForInstall()|.
1471// When adding, remove older tests related to |CheckForInstall()|.
1472TEST_F(UpdateAttempterTest, CheckForInstallNotIdleFails) {
1473 for (const auto status : kNonIdleUpdateStatuses) {
1474 // GIVEN a non-idle status.
1475 attempter_.status_ = status;
Xiaochu Liu8ba486f2018-11-06 11:14:10 -08001476
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001477 EXPECT_FALSE(attempter_.CheckForInstall({}, ""));
1478 }
Xiaochu Liu8ba486f2018-11-06 11:14:10 -08001479}
1480
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001481TEST_F(UpdateAttempterTest, CheckForUpdateNotIdleFails) {
1482 for (const auto status : kNonIdleUpdateStatuses) {
1483 // GIVEN a non-idle status.
1484 cfu_params_.status = status;
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001485
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001486 // THEN |ScheduleUpdates()| should not be called.
1487 cfu_params_.should_schedule_updates_be_called = false;
1488 // THEN result should indicate failure.
1489 cfu_params_.expected_result = false;
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001490
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001491 TestCheckForUpdate();
1492 }
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001493}
1494
1495TEST_F(UpdateAttempterTest, CheckForUpdateOfficalBuildClearsSource) {
1496 // GIVEN a official build.
1497
1498 // THEN we except forced app version + forced omaha url to be cleared.
1499
1500 TestCheckForUpdate();
1501}
1502
1503TEST_F(UpdateAttempterTest, CheckForUpdateUnofficialBuildChangesSource) {
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001504 // GIVEN a nonofficial build with dev features enabled.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001505 cfu_params_.is_official_build = false;
1506 cfu_params_.are_dev_features_enabled = true;
1507
1508 // THEN the forced app version + forced omaha url changes based on input.
1509 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1510 cfu_params_.expected_forced_omaha_url = cfu_params_.omaha_url;
1511
1512 TestCheckForUpdate();
1513}
1514
1515TEST_F(UpdateAttempterTest, CheckForUpdateOfficialBuildScheduledAUTest) {
1516 // GIVEN a scheduled autest omaha url.
1517 cfu_params_.omaha_url = "autest-scheduled";
1518
1519 // THEN forced app version is cleared.
1520 // THEN forced omaha url changes to default constant.
1521 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1522
1523 TestCheckForUpdate();
1524}
1525
1526TEST_F(UpdateAttempterTest, CheckForUpdateUnofficialBuildScheduledAUTest) {
1527 // GIVEN a scheduled autest omaha url.
1528 cfu_params_.omaha_url = "autest-scheduled";
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001529 // GIVEN a nonofficial build with dev features enabled.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001530 cfu_params_.is_official_build = false;
1531 cfu_params_.are_dev_features_enabled = true;
1532
1533 // THEN forced app version changes based on input.
1534 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1535 // THEN forced omaha url changes to default constant.
1536 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1537
1538 TestCheckForUpdate();
1539}
1540
1541TEST_F(UpdateAttempterTest, CheckForUpdateOfficialBuildAUTest) {
1542 // GIVEN a autest omaha url.
1543 cfu_params_.omaha_url = "autest";
1544
1545 // THEN forced app version is cleared.
1546 // THEN forced omaha url changes to default constant.
1547 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1548
1549 TestCheckForUpdate();
1550}
1551
1552TEST_F(UpdateAttempterTest, CheckForUpdateUnofficialBuildAUTest) {
1553 // GIVEN a autest omha url.
1554 cfu_params_.omaha_url = "autest";
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001555 // GIVEN a nonofficial build with dev features enabled.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001556 cfu_params_.is_official_build = false;
1557 cfu_params_.are_dev_features_enabled = true;
1558
1559 // THEN forced app version changes based on input.
1560 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1561 // THEN forced omaha url changes to default constant.
1562 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1563
1564 TestCheckForUpdate();
1565}
1566
1567TEST_F(UpdateAttempterTest,
1568 CheckForUpdateNonInteractiveOfficialBuildScheduledAUTest) {
1569 // GIVEN a scheduled autest omaha url.
1570 cfu_params_.omaha_url = "autest-scheduled";
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001571 // GIVEN a noninteractive update.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001572 cfu_params_.flags = UpdateAttemptFlags::kFlagNonInteractive;
1573
1574 // THEN forced app version is cleared.
1575 // THEN forced omaha url changes to default constant.
1576 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1577
1578 TestCheckForUpdate();
1579}
1580
1581TEST_F(UpdateAttempterTest,
1582 CheckForUpdateNonInteractiveUnofficialBuildScheduledAUTest) {
1583 // GIVEN a scheduled autest omaha url.
1584 cfu_params_.omaha_url = "autest-scheduled";
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001585 // GIVEN a noninteractive update.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001586 cfu_params_.flags = UpdateAttemptFlags::kFlagNonInteractive;
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001587 // GIVEN a nonofficial build with dev features enabled.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001588 cfu_params_.is_official_build = false;
1589 cfu_params_.are_dev_features_enabled = true;
1590
1591 // THEN forced app version changes based on input.
1592 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1593 // THEN forced omaha url changes to default constant.
1594 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1595
1596 TestCheckForUpdate();
1597}
1598
1599TEST_F(UpdateAttempterTest, CheckForUpdateNonInteractiveOfficialBuildAUTest) {
1600 // GIVEN a autest omaha url.
1601 cfu_params_.omaha_url = "autest";
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001602 // GIVEN a noninteractive update.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001603 cfu_params_.flags = UpdateAttemptFlags::kFlagNonInteractive;
1604
1605 // THEN forced app version is cleared.
1606 // THEN forced omaha url changes to default constant.
1607 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1608
1609 TestCheckForUpdate();
1610}
1611
1612TEST_F(UpdateAttempterTest, CheckForUpdateNonInteractiveUnofficialBuildAUTest) {
1613 // GIVEN a autest omaha url.
1614 cfu_params_.omaha_url = "autest";
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001615 // GIVEN a noninteractive update.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001616 cfu_params_.flags = UpdateAttemptFlags::kFlagNonInteractive;
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001617 // GIVEN a nonofficial build with dev features enabled.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001618 cfu_params_.is_official_build = false;
1619 cfu_params_.are_dev_features_enabled = true;
1620
1621 // THEN forced app version changes based on input.
1622 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1623 // THEN forced omaha url changes to default constant.
1624 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1625
1626 TestCheckForUpdate();
David Pursell02c18642014-11-06 11:26:11 -08001627}
1628
Jae Hoon Kim2b73ac22019-07-02 11:17:24 -07001629TEST_F(UpdateAttempterTest, CheckForUpdateMissingForcedCallback1) {
1630 // GIVEN a official build.
1631 // GIVEN forced callback is not set.
1632 attempter_.set_forced_update_pending_callback(nullptr);
1633
1634 // THEN we except forced app version + forced omaha url to be cleared.
1635 // THEN |ScheduleUpdates()| should not be called.
1636 cfu_params_.should_schedule_updates_be_called = false;
1637
1638 TestCheckForUpdate();
1639}
1640
1641TEST_F(UpdateAttempterTest, CheckForUpdateMissingForcedCallback2) {
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001642 // GIVEN a nonofficial build with dev features enabled.
Jae Hoon Kim2b73ac22019-07-02 11:17:24 -07001643 cfu_params_.is_official_build = false;
1644 cfu_params_.are_dev_features_enabled = true;
1645 // GIVEN forced callback is not set.
1646 attempter_.set_forced_update_pending_callback(nullptr);
1647
1648 // THEN the forced app version + forced omaha url changes based on input.
1649 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1650 cfu_params_.expected_forced_omaha_url = cfu_params_.omaha_url;
1651 // THEN |ScheduleUpdates()| should not be called.
1652 cfu_params_.should_schedule_updates_be_called = false;
1653
1654 TestCheckForUpdate();
1655}
1656
Xiaochu Liu88d90382018-08-29 16:09:11 -07001657TEST_F(UpdateAttempterTest, CheckForInstallTest) {
1658 fake_system_state_.fake_hardware()->SetIsOfficialBuild(true);
1659 fake_system_state_.fake_hardware()->SetAreDevFeaturesEnabled(false);
1660 attempter_.CheckForInstall({}, "autest");
1661 EXPECT_EQ(constants::kOmahaDefaultAUTestURL, attempter_.forced_omaha_url());
1662
1663 attempter_.CheckForInstall({}, "autest-scheduled");
1664 EXPECT_EQ(constants::kOmahaDefaultAUTestURL, attempter_.forced_omaha_url());
1665
1666 attempter_.CheckForInstall({}, "http://omaha.phishing");
1667 EXPECT_EQ("", attempter_.forced_omaha_url());
1668}
1669
Colin Howesac170d92018-11-20 16:29:28 -08001670TEST_F(UpdateAttempterTest, InstallSetsStatusIdle) {
1671 attempter_.CheckForInstall({}, "http://foo.bar");
1672 attempter_.status_ = UpdateStatus::DOWNLOADING;
1673 EXPECT_TRUE(attempter_.is_install_);
1674 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1675 UpdateEngineStatus status;
1676 attempter_.GetStatus(&status);
1677 // Should set status to idle after an install operation.
1678 EXPECT_EQ(UpdateStatus::IDLE, status.status);
1679}
1680
Colin Howes978c1082018-12-03 11:46:12 -08001681TEST_F(UpdateAttempterTest, RollbackAfterInstall) {
1682 attempter_.is_install_ = true;
1683 attempter_.Rollback(false);
1684 EXPECT_FALSE(attempter_.is_install_);
1685}
1686
1687TEST_F(UpdateAttempterTest, UpdateAfterInstall) {
1688 attempter_.is_install_ = true;
1689 attempter_.CheckForUpdate("", "", UpdateAttemptFlags::kNone);
1690 EXPECT_FALSE(attempter_.is_install_);
1691}
1692
Xiyuan Xiac0e8f9a2017-02-22 13:19:35 -08001693TEST_F(UpdateAttempterTest, TargetVersionPrefixSetAndReset) {
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001694 attempter_.CalculateUpdateParams(
1695 "", "", "", "1234", false, false, 4, false, false);
Xiyuan Xiac0e8f9a2017-02-22 13:19:35 -08001696 EXPECT_EQ("1234",
1697 fake_system_state_.request_params()->target_version_prefix());
1698
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001699 attempter_.CalculateUpdateParams(
1700 "", "", "", "", false, 4, false, false, false);
Xiyuan Xiac0e8f9a2017-02-22 13:19:35 -08001701 EXPECT_TRUE(
1702 fake_system_state_.request_params()->target_version_prefix().empty());
1703}
1704
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001705TEST_F(UpdateAttempterTest, RollbackAllowedSetAndReset) {
1706 attempter_.CalculateUpdateParams("",
1707 "",
1708 "",
1709 "1234",
1710 /*rollback_allowed=*/true,
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001711 /*rollback_data_save_requested=*/false,
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -07001712 /*rollback_allowed_milestones=*/4,
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001713 false,
1714 false);
1715 EXPECT_TRUE(fake_system_state_.request_params()->rollback_allowed());
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -07001716 EXPECT_EQ(4,
1717 fake_system_state_.request_params()->rollback_allowed_milestones());
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001718
1719 attempter_.CalculateUpdateParams("",
1720 "",
1721 "",
1722 "1234",
1723 /*rollback_allowed=*/false,
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001724 /*rollback_data_save_requested=*/false,
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -07001725 /*rollback_allowed_milestones=*/4,
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001726 false,
1727 false);
1728 EXPECT_FALSE(fake_system_state_.request_params()->rollback_allowed());
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -07001729 EXPECT_EQ(4,
1730 fake_system_state_.request_params()->rollback_allowed_milestones());
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001731}
1732
Aaron Wood23bd3392017-10-06 14:48:25 -07001733TEST_F(UpdateAttempterTest, UpdateDeferredByPolicyTest) {
1734 // Construct an OmahaResponseHandlerAction that has processed an InstallPlan,
1735 // but the update is being deferred by the Policy.
Amin Hassani68512d42018-07-31 23:52:33 -07001736 OmahaResponseHandlerAction response_action(&fake_system_state_);
1737 response_action.install_plan_.version = "a.b.c.d";
1738 response_action.install_plan_.system_version = "b.c.d.e";
1739 response_action.install_plan_.payloads.push_back(
Aaron Wood23bd3392017-10-06 14:48:25 -07001740 {.size = 1234ULL, .type = InstallPayloadType::kFull});
Aaron Wood23bd3392017-10-06 14:48:25 -07001741 // Inform the UpdateAttempter that the OmahaResponseHandlerAction has
1742 // completed, with the deferred-update error code.
1743 attempter_.ActionCompleted(
Amin Hassani68512d42018-07-31 23:52:33 -07001744 nullptr, &response_action, ErrorCode::kOmahaUpdateDeferredPerPolicy);
Aaron Wood23bd3392017-10-06 14:48:25 -07001745 {
1746 UpdateEngineStatus status;
1747 attempter_.GetStatus(&status);
1748 EXPECT_EQ(UpdateStatus::UPDATE_AVAILABLE, status.status);
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001749 EXPECT_TRUE(attempter_.install_plan_);
1750 EXPECT_EQ(attempter_.install_plan_->version, status.new_version);
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001751 EXPECT_EQ(attempter_.install_plan_->payloads[0].size,
Aaron Wood23bd3392017-10-06 14:48:25 -07001752 status.new_size_bytes);
1753 }
1754 // An "error" event should have been created to tell Omaha that the update is
1755 // being deferred.
1756 EXPECT_TRUE(nullptr != attempter_.error_event_);
1757 EXPECT_EQ(OmahaEvent::kTypeUpdateComplete, attempter_.error_event_->type);
1758 EXPECT_EQ(OmahaEvent::kResultUpdateDeferred, attempter_.error_event_->result);
1759 ErrorCode expected_code = static_cast<ErrorCode>(
1760 static_cast<int>(ErrorCode::kOmahaUpdateDeferredPerPolicy) |
1761 static_cast<int>(ErrorCode::kTestOmahaUrlFlag));
1762 EXPECT_EQ(expected_code, attempter_.error_event_->error_code);
1763 // End the processing
1764 attempter_.ProcessingDone(nullptr, ErrorCode::kOmahaUpdateDeferredPerPolicy);
1765 // Validate the state of the attempter.
1766 {
1767 UpdateEngineStatus status;
1768 attempter_.GetStatus(&status);
1769 EXPECT_EQ(UpdateStatus::REPORTING_ERROR_EVENT, status.status);
Amin Hassani68512d42018-07-31 23:52:33 -07001770 EXPECT_EQ(response_action.install_plan_.version, status.new_version);
Amin Hassani68512d42018-07-31 23:52:33 -07001771 EXPECT_EQ(response_action.install_plan_.payloads[0].size,
Aaron Wood23bd3392017-10-06 14:48:25 -07001772 status.new_size_bytes);
1773 }
1774}
1775
1776TEST_F(UpdateAttempterTest, UpdateIsNotRunningWhenUpdateAvailable) {
Jae Hoon Kim75daa382019-07-02 11:17:24 -07001777 // Default construction for |waiting_for_scheduled_check_| is false.
Jae Hoon Kimba2fdce2019-07-11 13:18:58 -07001778 EXPECT_FALSE(attempter_.IsBusyOrUpdateScheduled());
Aaron Wood23bd3392017-10-06 14:48:25 -07001779 // Verify in-progress update with UPDATE_AVAILABLE is running
1780 attempter_.status_ = UpdateStatus::UPDATE_AVAILABLE;
Jae Hoon Kimba2fdce2019-07-11 13:18:58 -07001781 EXPECT_TRUE(attempter_.IsBusyOrUpdateScheduled());
Aaron Wood23bd3392017-10-06 14:48:25 -07001782}
1783
Aaron Woodbf5a2522017-10-04 10:58:36 -07001784TEST_F(UpdateAttempterTest, UpdateAttemptFlagsCachedAtUpdateStart) {
1785 attempter_.SetUpdateAttemptFlags(UpdateAttemptFlags::kFlagRestrictDownload);
1786
1787 UpdateCheckParams params = {.updates_enabled = true};
1788 attempter_.OnUpdateScheduled(EvalStatus::kSucceeded, params);
1789
1790 EXPECT_EQ(UpdateAttemptFlags::kFlagRestrictDownload,
1791 attempter_.GetCurrentUpdateAttemptFlags());
1792}
1793
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001794TEST_F(UpdateAttempterTest, RollbackNotAllowed) {
1795 UpdateCheckParams params = {.updates_enabled = true,
1796 .rollback_allowed = false};
1797 attempter_.OnUpdateScheduled(EvalStatus::kSucceeded, params);
1798 EXPECT_FALSE(fake_system_state_.request_params()->rollback_allowed());
1799}
1800
1801TEST_F(UpdateAttempterTest, RollbackAllowed) {
1802 UpdateCheckParams params = {.updates_enabled = true,
1803 .rollback_allowed = true};
1804 attempter_.OnUpdateScheduled(EvalStatus::kSucceeded, params);
1805 EXPECT_TRUE(fake_system_state_.request_params()->rollback_allowed());
1806}
1807
Aaron Wood081c0232017-10-19 17:14:58 -07001808TEST_F(UpdateAttempterTest, InteractiveUpdateUsesPassedRestrictions) {
1809 attempter_.SetUpdateAttemptFlags(UpdateAttemptFlags::kFlagRestrictDownload);
1810
1811 attempter_.CheckForUpdate("", "", UpdateAttemptFlags::kNone);
1812 EXPECT_EQ(UpdateAttemptFlags::kNone,
1813 attempter_.GetCurrentUpdateAttemptFlags());
1814}
1815
1816TEST_F(UpdateAttempterTest, NonInteractiveUpdateUsesSetRestrictions) {
1817 attempter_.SetUpdateAttemptFlags(UpdateAttemptFlags::kNone);
1818
1819 // This tests that when CheckForUpdate() is called with the non-interactive
1820 // flag set, that it doesn't change the current UpdateAttemptFlags.
1821 attempter_.CheckForUpdate("",
1822 "",
1823 UpdateAttemptFlags::kFlagNonInteractive |
1824 UpdateAttemptFlags::kFlagRestrictDownload);
1825 EXPECT_EQ(UpdateAttemptFlags::kNone,
1826 attempter_.GetCurrentUpdateAttemptFlags());
1827}
1828
Marton Hunyadye58bddb2018-04-10 20:27:26 +02001829void UpdateAttempterTest::ResetRollbackHappenedStart(bool is_consumer,
1830 bool is_policy_loaded,
1831 bool expected_reset) {
1832 EXPECT_CALL(*fake_system_state_.mock_payload_state(), GetRollbackHappened())
1833 .WillRepeatedly(Return(true));
1834 auto mock_policy_provider =
1835 std::make_unique<NiceMock<policy::MockPolicyProvider>>();
1836 EXPECT_CALL(*mock_policy_provider, IsConsumerDevice())
1837 .WillRepeatedly(Return(is_consumer));
1838 EXPECT_CALL(*mock_policy_provider, device_policy_is_loaded())
1839 .WillRepeatedly(Return(is_policy_loaded));
1840 const policy::MockDevicePolicy device_policy;
1841 EXPECT_CALL(*mock_policy_provider, GetDevicePolicy())
1842 .WillRepeatedly(ReturnRef(device_policy));
1843 EXPECT_CALL(*fake_system_state_.mock_payload_state(),
1844 SetRollbackHappened(false))
1845 .Times(expected_reset ? 1 : 0);
1846 attempter_.policy_provider_ = std::move(mock_policy_provider);
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001847 attempter_.Update("", "", "", "", false, false, 0, false, false);
Marton Hunyadye58bddb2018-04-10 20:27:26 +02001848 ScheduleQuitMainLoop();
1849}
1850
1851TEST_F(UpdateAttempterTest, ResetRollbackHappenedOobe) {
1852 loop_.PostTask(FROM_HERE,
1853 base::Bind(&UpdateAttempterTest::ResetRollbackHappenedStart,
1854 base::Unretained(this),
1855 /*is_consumer=*/false,
1856 /*is_policy_loaded=*/false,
1857 /*expected_reset=*/false));
1858 loop_.Run();
1859}
1860
1861TEST_F(UpdateAttempterTest, ResetRollbackHappenedConsumer) {
1862 loop_.PostTask(FROM_HERE,
1863 base::Bind(&UpdateAttempterTest::ResetRollbackHappenedStart,
1864 base::Unretained(this),
1865 /*is_consumer=*/true,
1866 /*is_policy_loaded=*/false,
1867 /*expected_reset=*/true));
1868 loop_.Run();
1869}
1870
1871TEST_F(UpdateAttempterTest, ResetRollbackHappenedEnterprise) {
1872 loop_.PostTask(FROM_HERE,
1873 base::Bind(&UpdateAttempterTest::ResetRollbackHappenedStart,
1874 base::Unretained(this),
1875 /*is_consumer=*/false,
1876 /*is_policy_loaded=*/true,
1877 /*expected_reset=*/true));
1878 loop_.Run();
1879}
1880
Marton Hunyady199152d2018-05-07 19:08:48 +02001881TEST_F(UpdateAttempterTest, SetRollbackHappenedRollback) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001882 attempter_.install_plan_.reset(new InstallPlan);
1883 attempter_.install_plan_->is_rollback = true;
Marton Hunyady199152d2018-05-07 19:08:48 +02001884
1885 EXPECT_CALL(*fake_system_state_.mock_payload_state(),
1886 SetRollbackHappened(true))
1887 .Times(1);
1888 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1889}
1890
1891TEST_F(UpdateAttempterTest, SetRollbackHappenedNotRollback) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001892 attempter_.install_plan_.reset(new InstallPlan);
1893 attempter_.install_plan_->is_rollback = false;
Marton Hunyady199152d2018-05-07 19:08:48 +02001894
1895 EXPECT_CALL(*fake_system_state_.mock_payload_state(),
1896 SetRollbackHappened(true))
1897 .Times(0);
1898 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1899}
1900
Marton Hunyadya0302682018-05-16 18:52:13 +02001901TEST_F(UpdateAttempterTest, RollbackMetricsRollbackSuccess) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001902 attempter_.install_plan_.reset(new InstallPlan);
1903 attempter_.install_plan_->is_rollback = true;
1904 attempter_.install_plan_->version = kRollbackVersion;
Marton Hunyadya0302682018-05-16 18:52:13 +02001905
1906 EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
1907 ReportEnterpriseRollbackMetrics(true, kRollbackVersion))
1908 .Times(1);
1909 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1910}
1911
1912TEST_F(UpdateAttempterTest, RollbackMetricsNotRollbackSuccess) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001913 attempter_.install_plan_.reset(new InstallPlan);
1914 attempter_.install_plan_->is_rollback = false;
1915 attempter_.install_plan_->version = kRollbackVersion;
Marton Hunyadya0302682018-05-16 18:52:13 +02001916
1917 EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
1918 ReportEnterpriseRollbackMetrics(_, _))
1919 .Times(0);
1920 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1921}
1922
1923TEST_F(UpdateAttempterTest, RollbackMetricsRollbackFailure) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001924 attempter_.install_plan_.reset(new InstallPlan);
1925 attempter_.install_plan_->is_rollback = true;
1926 attempter_.install_plan_->version = kRollbackVersion;
Marton Hunyadya0302682018-05-16 18:52:13 +02001927
1928 EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
1929 ReportEnterpriseRollbackMetrics(false, kRollbackVersion))
1930 .Times(1);
1931 MockAction action;
1932 attempter_.CreatePendingErrorEvent(&action, ErrorCode::kRollbackNotPossible);
1933 attempter_.ProcessingDone(nullptr, ErrorCode::kRollbackNotPossible);
1934}
1935
1936TEST_F(UpdateAttempterTest, RollbackMetricsNotRollbackFailure) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001937 attempter_.install_plan_.reset(new InstallPlan);
1938 attempter_.install_plan_->is_rollback = false;
1939 attempter_.install_plan_->version = kRollbackVersion;
Marton Hunyadya0302682018-05-16 18:52:13 +02001940
1941 EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
1942 ReportEnterpriseRollbackMetrics(_, _))
1943 .Times(0);
1944 MockAction action;
1945 attempter_.CreatePendingErrorEvent(&action, ErrorCode::kRollbackNotPossible);
1946 attempter_.ProcessingDone(nullptr, ErrorCode::kRollbackNotPossible);
1947}
1948
May Lippert60aa3ca2018-08-15 16:55:29 -07001949TEST_F(UpdateAttempterTest, TimeToUpdateAppliedMetricFailure) {
1950 EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
1951 ReportEnterpriseUpdateSeenToDownloadDays(_, _))
1952 .Times(0);
1953 attempter_.ProcessingDone(nullptr, ErrorCode::kOmahaUpdateDeferredPerPolicy);
1954}
1955
1956TEST_F(UpdateAttempterTest, TimeToUpdateAppliedOnNonEnterprise) {
1957 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
1958 fake_system_state_.set_device_policy(device_policy.get());
1959 // Make device policy return that this is not enterprise enrolled
1960 EXPECT_CALL(*device_policy, IsEnterpriseEnrolled()).WillOnce(Return(false));
1961
1962 // Ensure that the metric is not recorded.
1963 EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
1964 ReportEnterpriseUpdateSeenToDownloadDays(_, _))
1965 .Times(0);
1966 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1967}
1968
1969TEST_F(UpdateAttempterTest,
1970 TimeToUpdateAppliedWithTimeRestrictionMetricSuccess) {
1971 constexpr int kDaysToUpdate = 15;
1972 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
1973 fake_system_state_.set_device_policy(device_policy.get());
1974 // Make device policy return that this is enterprise enrolled
1975 EXPECT_CALL(*device_policy, IsEnterpriseEnrolled()).WillOnce(Return(true));
1976 // Pretend that there's a time restriction policy in place
1977 EXPECT_CALL(*device_policy, GetDisallowedTimeIntervals(_))
1978 .WillOnce(Return(true));
1979
1980 FakePrefs fake_prefs;
1981 Time update_first_seen_at = Time::Now();
1982 fake_prefs.SetInt64(kPrefsUpdateFirstSeenAt,
1983 update_first_seen_at.ToInternalValue());
1984
1985 FakeClock fake_clock;
1986 Time update_finished_at =
1987 update_first_seen_at + TimeDelta::FromDays(kDaysToUpdate);
1988 fake_clock.SetWallclockTime(update_finished_at);
1989
1990 fake_system_state_.set_clock(&fake_clock);
1991 fake_system_state_.set_prefs(&fake_prefs);
1992
1993 EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
1994 ReportEnterpriseUpdateSeenToDownloadDays(true, kDaysToUpdate))
1995 .Times(1);
1996 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1997}
1998
1999TEST_F(UpdateAttempterTest,
2000 TimeToUpdateAppliedWithoutTimeRestrictionMetricSuccess) {
2001 constexpr int kDaysToUpdate = 15;
2002 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
2003 fake_system_state_.set_device_policy(device_policy.get());
2004 // Make device policy return that this is enterprise enrolled
2005 EXPECT_CALL(*device_policy, IsEnterpriseEnrolled()).WillOnce(Return(true));
2006 // Pretend that there's no time restriction policy in place
2007 EXPECT_CALL(*device_policy, GetDisallowedTimeIntervals(_))
2008 .WillOnce(Return(false));
2009
2010 FakePrefs fake_prefs;
2011 Time update_first_seen_at = Time::Now();
2012 fake_prefs.SetInt64(kPrefsUpdateFirstSeenAt,
2013 update_first_seen_at.ToInternalValue());
2014
2015 FakeClock fake_clock;
2016 Time update_finished_at =
2017 update_first_seen_at + TimeDelta::FromDays(kDaysToUpdate);
2018 fake_clock.SetWallclockTime(update_finished_at);
2019
2020 fake_system_state_.set_clock(&fake_clock);
2021 fake_system_state_.set_prefs(&fake_prefs);
2022
2023 EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
2024 ReportEnterpriseUpdateSeenToDownloadDays(false, kDaysToUpdate))
2025 .Times(1);
2026 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
2027}
2028
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002029TEST_F(UpdateAttempterTest, ProcessingDoneUpdated) {
2030 // GIVEN an update finished.
2031
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002032 // THEN update_engine should call update completion.
2033 pd_params_.should_update_completed_be_called = true;
2034 // THEN need reboot since update applied.
2035 pd_params_.expected_exit_status = UpdateStatus::UPDATED_NEED_REBOOT;
2036 // THEN install indication should be false.
2037
2038 TestProcessingDone();
2039}
2040
2041TEST_F(UpdateAttempterTest, ProcessingDoneUpdatedDlcFilter) {
2042 // GIVEN an update finished.
2043 // GIVEN DLC |AppParams| list.
2044 auto dlc_1 = "dlc_1", dlc_2 = "dlc_2";
2045 pd_params_.dlc_apps_params = {{dlc_1, {.name = dlc_1, .updated = false}},
2046 {dlc_2, {.name = dlc_2}}};
2047
2048 // THEN update_engine should call update completion.
2049 pd_params_.should_update_completed_be_called = true;
2050 pd_params_.args_to_update_completed = {dlc_2};
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002051 // THEN need reboot since update applied.
2052 pd_params_.expected_exit_status = UpdateStatus::UPDATED_NEED_REBOOT;
2053 // THEN install indication should be false.
2054
2055 TestProcessingDone();
2056}
2057
2058TEST_F(UpdateAttempterTest, ProcessingDoneInstalled) {
2059 // GIVEN an install finished.
2060 pd_params_.is_install = true;
2061
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002062 // THEN update_engine should call install completion.
2063 pd_params_.should_install_completed_be_called = true;
2064 // THEN go idle.
2065 // THEN install indication should be false.
2066
2067 TestProcessingDone();
2068}
2069
2070TEST_F(UpdateAttempterTest, ProcessingDoneInstalledDlcFilter) {
2071 // GIVEN an install finished.
2072 pd_params_.is_install = true;
2073 // GIVEN DLC |AppParams| list.
2074 auto dlc_1 = "dlc_1", dlc_2 = "dlc_2";
2075 pd_params_.dlc_apps_params = {{dlc_1, {.name = dlc_1, .updated = false}},
2076 {dlc_2, {.name = dlc_2}}};
2077
2078 // THEN update_engine should call install completion.
2079 pd_params_.should_install_completed_be_called = true;
2080 pd_params_.args_to_install_completed = {dlc_2};
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002081 // THEN go idle.
2082 // THEN install indication should be false.
2083
2084 TestProcessingDone();
2085}
2086
2087TEST_F(UpdateAttempterTest, ProcessingDoneInstallReportingError) {
2088 // GIVEN an install finished.
2089 pd_params_.is_install = true;
2090 // GIVEN a reporting error occurred.
2091 pd_params_.status = UpdateStatus::REPORTING_ERROR_EVENT;
2092
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002093 // THEN update_engine should not call install completion.
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002094 // THEN go idle.
2095 // THEN install indication should be false.
2096
2097 TestProcessingDone();
2098}
2099
2100TEST_F(UpdateAttempterTest, ProcessingDoneNoUpdate) {
2101 // GIVEN an update finished.
2102 // GIVEN an action error occured.
2103 pd_params_.code = ErrorCode::kNoUpdate;
2104
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002105 // THEN update_engine should not call update completion.
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002106 // THEN go idle.
2107 // THEN install indication should be false.
2108
2109 TestProcessingDone();
2110}
2111
2112TEST_F(UpdateAttempterTest, ProcessingDoneNoInstall) {
2113 // GIVEN an install finished.
2114 pd_params_.is_install = true;
2115 // GIVEN an action error occured.
2116 pd_params_.code = ErrorCode::kNoUpdate;
2117
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002118 // THEN update_engine should not call install completion.
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002119 // THEN go idle.
2120 // THEN install indication should be false.
2121
2122 TestProcessingDone();
2123}
2124
2125TEST_F(UpdateAttempterTest, ProcessingDoneUpdateError) {
2126 // GIVEN an update finished.
2127 // GIVEN an action error occured.
2128 pd_params_.code = ErrorCode::kError;
2129 // GIVEN an event error is set.
2130 attempter_.error_event_.reset(new OmahaEvent(OmahaEvent::kTypeUpdateComplete,
2131 OmahaEvent::kResultError,
2132 ErrorCode::kError));
2133
2134 // THEN indicate a error event.
2135 pd_params_.expected_exit_status = UpdateStatus::REPORTING_ERROR_EVENT;
2136 // THEN install indication should be false.
2137
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002138 // THEN update_engine should not call update completion.
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002139 // THEN expect critical actions of |ScheduleErrorEventAction()|.
2140 EXPECT_CALL(*processor_, EnqueueAction(Pointee(_))).Times(1);
2141 EXPECT_CALL(*processor_, StartProcessing()).Times(1);
2142 // THEN |ScheduleUpdates()| will be called next |ProcessingDone()| so skip.
2143 pd_params_.should_schedule_updates_be_called = false;
2144
2145 TestProcessingDone();
2146}
2147
2148TEST_F(UpdateAttempterTest, ProcessingDoneInstallError) {
2149 // GIVEN an install finished.
2150 pd_params_.is_install = true;
2151 // GIVEN an action error occured.
2152 pd_params_.code = ErrorCode::kError;
2153 // GIVEN an event error is set.
2154 attempter_.error_event_.reset(new OmahaEvent(OmahaEvent::kTypeUpdateComplete,
2155 OmahaEvent::kResultError,
2156 ErrorCode::kError));
2157
2158 // THEN indicate a error event.
2159 pd_params_.expected_exit_status = UpdateStatus::REPORTING_ERROR_EVENT;
2160 // THEN install indication should be false.
2161
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002162 // THEN update_engine should not call install completion.
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002163 // THEN expect critical actions of |ScheduleErrorEventAction()|.
2164 EXPECT_CALL(*processor_, EnqueueAction(Pointee(_))).Times(1);
2165 EXPECT_CALL(*processor_, StartProcessing()).Times(1);
2166 // THEN |ScheduleUpdates()| will be called next |ProcessingDone()| so skip.
2167 pd_params_.should_schedule_updates_be_called = false;
2168
2169 TestProcessingDone();
2170}
2171
Amr Aboelkher21ac9962019-05-15 14:50:05 +02002172void UpdateAttempterTest::UpdateToQuickFixBuildStart(bool set_token) {
2173 // Tests that checks if |device_quick_fix_build_token| arrives when
2174 // policy is set and the device is enterprise enrolled based on |set_token|.
2175 string token = set_token ? "some_token" : "";
Askar Aitzhan570ca872019-04-24 11:16:12 +02002176 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
2177 fake_system_state_.set_device_policy(device_policy.get());
Askar Aitzhan570ca872019-04-24 11:16:12 +02002178 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
Amr Aboelkher21ac9962019-05-15 14:50:05 +02002179
2180 if (set_token)
2181 EXPECT_CALL(*device_policy, GetDeviceQuickFixBuildToken(_))
2182 .WillOnce(DoAll(SetArgPointee<0>(token), Return(true)));
2183 else
2184 EXPECT_CALL(*device_policy, GetDeviceQuickFixBuildToken(_))
2185 .WillOnce(Return(false));
Askar Aitzhan570ca872019-04-24 11:16:12 +02002186 attempter_.policy_provider_.reset(
2187 new policy::PolicyProvider(std::move(device_policy)));
2188 attempter_.Update("", "", "", "", false, false, 0, false, false);
2189
Amr Aboelkher21ac9962019-05-15 14:50:05 +02002190 EXPECT_EQ(token, attempter_.omaha_request_params_->autoupdate_token());
Askar Aitzhan570ca872019-04-24 11:16:12 +02002191 ScheduleQuitMainLoop();
2192}
2193
Amr Aboelkher21ac9962019-05-15 14:50:05 +02002194TEST_F(UpdateAttempterTest,
2195 QuickFixTokenWhenDeviceIsEnterpriseEnrolledAndPolicyIsSet) {
Askar Aitzhan570ca872019-04-24 11:16:12 +02002196 loop_.PostTask(FROM_HERE,
2197 base::Bind(&UpdateAttempterTest::UpdateToQuickFixBuildStart,
Amr Aboelkher21ac9962019-05-15 14:50:05 +02002198 base::Unretained(this),
2199 /*set_token=*/true));
2200 loop_.Run();
2201}
2202
2203TEST_F(UpdateAttempterTest, EmptyQuickFixToken) {
2204 loop_.PostTask(FROM_HERE,
2205 base::Bind(&UpdateAttempterTest::UpdateToQuickFixBuildStart,
2206 base::Unretained(this),
2207 /*set_token=*/false));
Askar Aitzhan570ca872019-04-24 11:16:12 +02002208 loop_.Run();
2209}
2210
Jae Hoon Kim75daa382019-07-02 11:17:24 -07002211TEST_F(UpdateAttempterTest, ScheduleUpdateSpamHandlerTest) {
2212 EXPECT_CALL(mock_update_manager_, AsyncPolicyRequestUpdateCheckAllowed(_, _))
2213 .Times(1);
2214 EXPECT_TRUE(attempter_.ScheduleUpdates());
2215 // Now there is an update scheduled which means that all subsequent
2216 // |ScheduleUpdates()| should fail.
2217 EXPECT_FALSE(attempter_.ScheduleUpdates());
2218 EXPECT_FALSE(attempter_.ScheduleUpdates());
2219 EXPECT_FALSE(attempter_.ScheduleUpdates());
2220}
2221
2222// Critical tests to always make sure that an update is scheduled. The following
2223// unittest(s) try and cover the correctness in synergy between
2224// |UpdateAttempter| and |UpdateManager|. Also it is good to remember the
2225// actions that happen in the flow when |UpdateAttempter| get callbacked on
2226// |OnUpdateScheduled()| -> (various cases which leads to) -> |ProcessingDone()|
2227void UpdateAttempterTest::TestOnUpdateScheduled() {
2228 // Setup
2229 attempter_.SetWaitingForScheduledCheck(true);
2230 attempter_.DisableUpdate();
2231 attempter_.DisableScheduleUpdates();
2232
2233 // Invocation
2234 attempter_.OnUpdateScheduled(ous_params_.status, ous_params_.params);
2235
2236 // Verify
2237 EXPECT_EQ(ous_params_.exit_status, attempter_.status());
2238 EXPECT_EQ(ous_params_.should_schedule_updates_be_called,
2239 attempter_.WasScheduleUpdatesCalled());
2240 EXPECT_EQ(ous_params_.should_update_be_called, attempter_.WasUpdateCalled());
2241}
2242
2243TEST_F(UpdateAttempterTest, OnUpdatesScheduledFailed) {
2244 // GIVEN failed status.
2245
2246 // THEN update should be scheduled.
2247 ous_params_.should_schedule_updates_be_called = true;
2248
2249 TestOnUpdateScheduled();
2250}
2251
2252TEST_F(UpdateAttempterTest, OnUpdatesScheduledAskMeAgainLater) {
2253 // GIVEN ask me again later status.
2254 ous_params_.status = EvalStatus::kAskMeAgainLater;
2255
2256 // THEN update should be scheduled.
2257 ous_params_.should_schedule_updates_be_called = true;
2258
2259 TestOnUpdateScheduled();
2260}
2261
2262TEST_F(UpdateAttempterTest, OnUpdatesScheduledContinue) {
2263 // GIVEN continue status.
2264 ous_params_.status = EvalStatus::kContinue;
2265
2266 // THEN update should be scheduled.
2267 ous_params_.should_schedule_updates_be_called = true;
2268
2269 TestOnUpdateScheduled();
2270}
2271
2272TEST_F(UpdateAttempterTest, OnUpdatesScheduledSucceededButUpdateDisabledFails) {
2273 // GIVEN updates disabled.
2274 ous_params_.params = {.updates_enabled = false};
2275 // GIVEN succeeded status.
2276 ous_params_.status = EvalStatus::kSucceeded;
2277
2278 // THEN update should not be scheduled.
2279
2280 TestOnUpdateScheduled();
2281}
2282
2283TEST_F(UpdateAttempterTest, OnUpdatesScheduledSucceeded) {
2284 // GIVEN updates enabled.
2285 ous_params_.params = {.updates_enabled = true};
2286 // GIVEN succeeded status.
2287 ous_params_.status = EvalStatus::kSucceeded;
2288
2289 // THEN update should be called indicating status change.
2290 ous_params_.exit_status = UpdateStatus::CHECKING_FOR_UPDATE;
2291 ous_params_.should_update_be_called = true;
2292
2293 TestOnUpdateScheduled();
2294}
2295
Amin Hassani9be122e2019-08-29 09:20:12 -07002296TEST_F(UpdateAttempterTest, IsEnterpriseRollbackInGetStatusDefault) {
2297 UpdateEngineStatus status;
2298 attempter_.GetStatus(&status);
2299 EXPECT_FALSE(status.is_enterprise_rollback);
2300}
2301
2302TEST_F(UpdateAttempterTest, IsEnterpriseRollbackInGetStatusFalse) {
2303 attempter_.install_plan_.reset(new InstallPlan);
2304 attempter_.install_plan_->is_rollback = false;
2305
2306 UpdateEngineStatus status;
2307 attempter_.GetStatus(&status);
2308 EXPECT_FALSE(status.is_enterprise_rollback);
2309}
2310
2311TEST_F(UpdateAttempterTest, IsEnterpriseRollbackInGetStatusTrue) {
2312 attempter_.install_plan_.reset(new InstallPlan);
2313 attempter_.install_plan_->is_rollback = true;
2314
2315 UpdateEngineStatus status;
2316 attempter_.GetStatus(&status);
2317 EXPECT_TRUE(status.is_enterprise_rollback);
2318}
2319
Miriam Polzer0cf1acb2020-04-29 17:39:51 +02002320TEST_F(UpdateAttempterTest, PowerwashInGetStatusDefault) {
2321 UpdateEngineStatus status;
2322 attempter_.GetStatus(&status);
2323 EXPECT_FALSE(status.will_powerwash_after_reboot);
2324}
2325
2326TEST_F(UpdateAttempterTest, PowerwashInGetStatusTrueBecausePowerwashRequired) {
2327 attempter_.install_plan_.reset(new InstallPlan);
2328 attempter_.install_plan_->powerwash_required = true;
2329
2330 UpdateEngineStatus status;
2331 attempter_.GetStatus(&status);
2332 EXPECT_TRUE(status.will_powerwash_after_reboot);
2333}
2334
2335TEST_F(UpdateAttempterTest, PowerwashInGetStatusTrueBecauseRollback) {
2336 attempter_.install_plan_.reset(new InstallPlan);
2337 attempter_.install_plan_->is_rollback = true;
2338
2339 UpdateEngineStatus status;
2340 attempter_.GetStatus(&status);
2341 EXPECT_TRUE(status.will_powerwash_after_reboot);
2342}
2343
Jae Hoon Kim051627a2019-09-03 12:56:32 -07002344TEST_F(UpdateAttempterTest, FutureEolTest) {
2345 EolDate eol_date = std::numeric_limits<int64_t>::max();
2346 EXPECT_CALL(*prefs_, GetString(kPrefsOmahaEolDate, _))
2347 .WillOnce(
2348 DoAll(SetArgPointee<1>(EolDateToString(eol_date)), Return(true)));
2349
2350 UpdateEngineStatus status;
2351 attempter_.GetStatus(&status);
2352 EXPECT_EQ(eol_date, status.eol_date);
2353}
2354
2355TEST_F(UpdateAttempterTest, PastEolTest) {
2356 EolDate eol_date = 1;
2357 EXPECT_CALL(*prefs_, GetString(kPrefsOmahaEolDate, _))
2358 .WillOnce(
2359 DoAll(SetArgPointee<1>(EolDateToString(eol_date)), Return(true)));
2360
2361 UpdateEngineStatus status;
2362 attempter_.GetStatus(&status);
2363 EXPECT_EQ(eol_date, status.eol_date);
2364}
2365
2366TEST_F(UpdateAttempterTest, FailedEolTest) {
2367 EolDate eol_date = kEolDateInvalid;
2368 EXPECT_CALL(*prefs_, GetString(kPrefsOmahaEolDate, _))
2369 .WillOnce(Return(false));
2370
2371 UpdateEngineStatus status;
2372 attempter_.GetStatus(&status);
2373 EXPECT_EQ(eol_date, status.eol_date);
2374}
2375
Andrewe045aef2020-01-08 16:29:22 -08002376TEST_F(UpdateAttempterTest, CalculateDlcParamsInstallTest) {
Andrewe045aef2020-01-08 16:29:22 -08002377 string dlc_id = "dlc0";
Andrew065d78d2020-04-07 15:43:07 -07002378 FakePrefs fake_prefs;
2379 fake_system_state_.set_prefs(&fake_prefs);
Andrewe045aef2020-01-08 16:29:22 -08002380 attempter_.is_install_ = true;
Amin Hassani2b68e6b2020-04-17 10:49:12 -07002381 attempter_.dlc_ids_ = {dlc_id};
Andrewe045aef2020-01-08 16:29:22 -08002382 attempter_.CalculateDlcParams();
2383
2384 OmahaRequestParams* params = fake_system_state_.request_params();
2385 EXPECT_EQ(1, params->dlc_apps_params().count(params->GetDlcAppId(dlc_id)));
2386 OmahaRequestParams::AppParams dlc_app_params =
2387 params->dlc_apps_params().at(params->GetDlcAppId(dlc_id));
2388 EXPECT_STREQ(dlc_id.c_str(), dlc_app_params.name.c_str());
2389 EXPECT_EQ(false, dlc_app_params.send_ping);
2390 // When the DLC gets installed, a ping is not sent, therefore we don't store
2391 // the values sent by Omaha.
Andrew065d78d2020-04-07 15:43:07 -07002392 auto last_active_key = PrefsInterface::CreateSubKey(
2393 kDlcPrefsSubDir, dlc_id, kPrefsPingLastActive);
2394 EXPECT_FALSE(fake_system_state_.prefs()->Exists(last_active_key));
2395 auto last_rollcall_key = PrefsInterface::CreateSubKey(
2396 kDlcPrefsSubDir, dlc_id, kPrefsPingLastRollcall);
2397 EXPECT_FALSE(fake_system_state_.prefs()->Exists(last_rollcall_key));
Andrewe045aef2020-01-08 16:29:22 -08002398}
2399
2400TEST_F(UpdateAttempterTest, CalculateDlcParamsNoPrefFilesTest) {
Andrewe045aef2020-01-08 16:29:22 -08002401 string dlc_id = "dlc0";
Andrew065d78d2020-04-07 15:43:07 -07002402 FakePrefs fake_prefs;
2403 fake_system_state_.set_prefs(&fake_prefs);
Amin Hassani2b68e6b2020-04-17 10:49:12 -07002404 EXPECT_CALL(mock_dlcservice_, GetDlcsToUpdate(_))
Andrewe045aef2020-01-08 16:29:22 -08002405 .WillOnce(
2406 DoAll(SetArgPointee<0>(std::vector<string>({dlc_id})), Return(true)));
2407
2408 attempter_.is_install_ = false;
2409 attempter_.CalculateDlcParams();
2410
2411 OmahaRequestParams* params = fake_system_state_.request_params();
2412 EXPECT_EQ(1, params->dlc_apps_params().count(params->GetDlcAppId(dlc_id)));
2413 OmahaRequestParams::AppParams dlc_app_params =
2414 params->dlc_apps_params().at(params->GetDlcAppId(dlc_id));
2415 EXPECT_STREQ(dlc_id.c_str(), dlc_app_params.name.c_str());
2416
2417 EXPECT_EQ(true, dlc_app_params.send_ping);
2418 EXPECT_EQ(0, dlc_app_params.ping_active);
2419 EXPECT_EQ(-1, dlc_app_params.ping_date_last_active);
2420 EXPECT_EQ(-1, dlc_app_params.ping_date_last_rollcall);
2421}
2422
2423TEST_F(UpdateAttempterTest, CalculateDlcParamsNonParseableValuesTest) {
Andrewe045aef2020-01-08 16:29:22 -08002424 string dlc_id = "dlc0";
Andrew065d78d2020-04-07 15:43:07 -07002425 MemoryPrefs prefs;
2426 fake_system_state_.set_prefs(&prefs);
Amin Hassani2b68e6b2020-04-17 10:49:12 -07002427 EXPECT_CALL(mock_dlcservice_, GetDlcsToUpdate(_))
Andrewe045aef2020-01-08 16:29:22 -08002428 .WillOnce(
2429 DoAll(SetArgPointee<0>(std::vector<string>({dlc_id})), Return(true)));
2430
2431 // Write non numeric values in the metadata files.
Andrew065d78d2020-04-07 15:43:07 -07002432 auto active_key =
2433 PrefsInterface::CreateSubKey(kDlcPrefsSubDir, dlc_id, kPrefsPingActive);
2434 auto last_active_key = PrefsInterface::CreateSubKey(
2435 kDlcPrefsSubDir, dlc_id, kPrefsPingLastActive);
2436 auto last_rollcall_key = PrefsInterface::CreateSubKey(
2437 kDlcPrefsSubDir, dlc_id, kPrefsPingLastRollcall);
2438 fake_system_state_.prefs()->SetString(active_key, "z2yz");
2439 fake_system_state_.prefs()->SetString(last_active_key, "z2yz");
2440 fake_system_state_.prefs()->SetString(last_rollcall_key, "z2yz");
Andrewe045aef2020-01-08 16:29:22 -08002441 attempter_.is_install_ = false;
2442 attempter_.CalculateDlcParams();
2443
2444 OmahaRequestParams* params = fake_system_state_.request_params();
2445 EXPECT_EQ(1, params->dlc_apps_params().count(params->GetDlcAppId(dlc_id)));
2446 OmahaRequestParams::AppParams dlc_app_params =
2447 params->dlc_apps_params().at(params->GetDlcAppId(dlc_id));
2448 EXPECT_STREQ(dlc_id.c_str(), dlc_app_params.name.c_str());
2449
2450 EXPECT_EQ(true, dlc_app_params.send_ping);
2451 EXPECT_EQ(0, dlc_app_params.ping_active);
2452 EXPECT_EQ(-2, dlc_app_params.ping_date_last_active);
2453 EXPECT_EQ(-2, dlc_app_params.ping_date_last_rollcall);
2454}
2455
2456TEST_F(UpdateAttempterTest, CalculateDlcParamsValidValuesTest) {
Andrewe045aef2020-01-08 16:29:22 -08002457 string dlc_id = "dlc0";
Andrew065d78d2020-04-07 15:43:07 -07002458 MemoryPrefs fake_prefs;
2459 fake_system_state_.set_prefs(&fake_prefs);
Amin Hassani2b68e6b2020-04-17 10:49:12 -07002460 EXPECT_CALL(mock_dlcservice_, GetDlcsToUpdate(_))
Andrewe045aef2020-01-08 16:29:22 -08002461 .WillOnce(
2462 DoAll(SetArgPointee<0>(std::vector<string>({dlc_id})), Return(true)));
2463
2464 // Write numeric values in the metadata files.
Andrew065d78d2020-04-07 15:43:07 -07002465 auto active_key =
2466 PrefsInterface::CreateSubKey(kDlcPrefsSubDir, dlc_id, kPrefsPingActive);
2467 auto last_active_key = PrefsInterface::CreateSubKey(
2468 kDlcPrefsSubDir, dlc_id, kPrefsPingLastActive);
2469 auto last_rollcall_key = PrefsInterface::CreateSubKey(
2470 kDlcPrefsSubDir, dlc_id, kPrefsPingLastRollcall);
2471
2472 fake_system_state_.prefs()->SetInt64(active_key, 1);
2473 fake_system_state_.prefs()->SetInt64(last_active_key, 78);
2474 fake_system_state_.prefs()->SetInt64(last_rollcall_key, 99);
Andrewe045aef2020-01-08 16:29:22 -08002475 attempter_.is_install_ = false;
2476 attempter_.CalculateDlcParams();
2477
2478 OmahaRequestParams* params = fake_system_state_.request_params();
2479 EXPECT_EQ(1, params->dlc_apps_params().count(params->GetDlcAppId(dlc_id)));
2480 OmahaRequestParams::AppParams dlc_app_params =
2481 params->dlc_apps_params().at(params->GetDlcAppId(dlc_id));
2482 EXPECT_STREQ(dlc_id.c_str(), dlc_app_params.name.c_str());
2483
2484 EXPECT_EQ(true, dlc_app_params.send_ping);
2485 EXPECT_EQ(1, dlc_app_params.ping_active);
2486 EXPECT_EQ(78, dlc_app_params.ping_date_last_active);
2487 EXPECT_EQ(99, dlc_app_params.ping_date_last_rollcall);
2488}
Andrewa8d7df32020-03-15 20:10:01 -07002489
2490TEST_F(UpdateAttempterTest, CalculateDlcParamsRemoveStaleMetadata) {
Andrewa8d7df32020-03-15 20:10:01 -07002491 string dlc_id = "dlc0";
Andrew065d78d2020-04-07 15:43:07 -07002492 FakePrefs fake_prefs;
2493 fake_system_state_.set_prefs(&fake_prefs);
2494 auto active_key =
2495 PrefsInterface::CreateSubKey(kDlcPrefsSubDir, dlc_id, kPrefsPingActive);
2496 auto last_active_key = PrefsInterface::CreateSubKey(
2497 kDlcPrefsSubDir, dlc_id, kPrefsPingLastActive);
2498 auto last_rollcall_key = PrefsInterface::CreateSubKey(
2499 kDlcPrefsSubDir, dlc_id, kPrefsPingLastRollcall);
2500 fake_system_state_.prefs()->SetInt64(active_key, kPingInactiveValue);
2501 fake_system_state_.prefs()->SetInt64(last_active_key, 0);
2502 fake_system_state_.prefs()->SetInt64(last_rollcall_key, 0);
2503 EXPECT_TRUE(fake_system_state_.prefs()->Exists(active_key));
2504 EXPECT_TRUE(fake_system_state_.prefs()->Exists(last_active_key));
2505 EXPECT_TRUE(fake_system_state_.prefs()->Exists(last_rollcall_key));
Andrewa8d7df32020-03-15 20:10:01 -07002506
Andrew065d78d2020-04-07 15:43:07 -07002507 attempter_.dlc_ids_ = {dlc_id};
2508 attempter_.is_install_ = true;
Andrewa8d7df32020-03-15 20:10:01 -07002509 attempter_.CalculateDlcParams();
2510
Andrew065d78d2020-04-07 15:43:07 -07002511 EXPECT_FALSE(fake_system_state_.prefs()->Exists(last_active_key));
2512 EXPECT_FALSE(fake_system_state_.prefs()->Exists(last_rollcall_key));
2513 // Active key is set on install.
2514 EXPECT_TRUE(fake_system_state_.prefs()->Exists(active_key));
2515 int64_t temp_int;
2516 EXPECT_TRUE(fake_system_state_.prefs()->GetInt64(active_key, &temp_int));
2517 EXPECT_EQ(temp_int, kPingActiveValue);
Andrewa8d7df32020-03-15 20:10:01 -07002518}
2519
2520TEST_F(UpdateAttempterTest, SetDlcActiveValue) {
Andrewa8d7df32020-03-15 20:10:01 -07002521 string dlc_id = "dlc0";
Andrew065d78d2020-04-07 15:43:07 -07002522 FakePrefs fake_prefs;
2523 fake_system_state_.set_prefs(&fake_prefs);
Andrewa8d7df32020-03-15 20:10:01 -07002524 attempter_.SetDlcActiveValue(true, dlc_id);
Andrewa8d7df32020-03-15 20:10:01 -07002525 int64_t temp_int;
Andrew065d78d2020-04-07 15:43:07 -07002526 auto active_key =
2527 PrefsInterface::CreateSubKey(kDlcPrefsSubDir, dlc_id, kPrefsPingActive);
2528 EXPECT_TRUE(fake_system_state_.prefs()->Exists(active_key));
2529 EXPECT_TRUE(fake_system_state_.prefs()->GetInt64(active_key, &temp_int));
Andrewa8d7df32020-03-15 20:10:01 -07002530 EXPECT_EQ(temp_int, kPingActiveValue);
2531}
2532
2533TEST_F(UpdateAttempterTest, SetDlcInactive) {
Andrewa8d7df32020-03-15 20:10:01 -07002534 string dlc_id = "dlc0";
Andrew065d78d2020-04-07 15:43:07 -07002535 MemoryPrefs fake_prefs;
2536 fake_system_state_.set_prefs(&fake_prefs);
2537 auto sub_keys = {
2538 kPrefsPingActive, kPrefsPingLastActive, kPrefsPingLastRollcall};
2539 for (auto& sub_key : sub_keys) {
2540 auto key = PrefsInterface::CreateSubKey(kDlcPrefsSubDir, dlc_id, sub_key);
2541 fake_system_state_.prefs()->SetInt64(key, 1);
2542 EXPECT_TRUE(fake_system_state_.prefs()->Exists(key));
2543 }
Andrewa8d7df32020-03-15 20:10:01 -07002544 attempter_.SetDlcActiveValue(false, dlc_id);
Andrew065d78d2020-04-07 15:43:07 -07002545 for (auto& sub_key : sub_keys) {
2546 auto key = PrefsInterface::CreateSubKey(kDlcPrefsSubDir, dlc_id, sub_key);
2547 EXPECT_FALSE(fake_system_state_.prefs()->Exists(key));
2548 }
Andrewa8d7df32020-03-15 20:10:01 -07002549}
2550
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002551TEST_F(UpdateAttempterTest, GetSuccessfulDlcIds) {
2552 auto dlc_1 = "1", dlc_2 = "2", dlc_3 = "3";
2553 attempter_.omaha_request_params_->set_dlc_apps_params(
2554 {{dlc_1, {.name = dlc_1, .updated = false}},
2555 {dlc_2, {.name = dlc_2}},
2556 {dlc_3, {.name = dlc_3, .updated = false}}});
2557 EXPECT_THAT(attempter_.GetSuccessfulDlcIds(), ElementsAre(dlc_2));
2558}
2559
Darin Petkovf42cc1c2010-09-01 09:03:02 -07002560} // namespace chromeos_update_engine